repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DevAndArtist/RxContainer | Sources/Transition.swift | 1 | 1745 | //
// Transition.swift
// RxContainer
//
// Created by Adrian Zubarev on 04.06.17.
// Copyright © 2017 RxSwiftCommunity. All rights reserved.
//
import UIKit
public final class Transition {
//==========-----------------------------==========//
//=====----- Private/Internal properties -----=====//
//==========-----------------------------==========//
///
var transitionCompletion: ((CompletionPosition) -> Void)?
//==========------------------------==========//
//=====----- Open/Public properties -----=====//
//==========------------------------==========//
///
public let context: Context
///
public let containerViewController: ContainerViewController
///
public private(set) var additionalAnimation: ((Context) -> Void)?
///
public private(set) var additionalCompletion: ((Context) -> Void)?
//==========-------------==========//
//=====----- Initializer -----=====//
//==========-------------==========//
///
init(
with context: Context, on containerViewController: ContainerViewController
) {
self.context = context
self.containerViewController = containerViewController
}
}
extension Transition {
///
public func animateAlongside(
_ animation: ( /* @escaping */ (Context) -> Void)?
) {
additionalAnimation = animation
}
public func animateAlongside(
_ animation: ( /* @escaping */ (Context) -> Void)?,
completion: ( /* @escaping */ (Context) -> Void)? = nil
) {
additionalAnimation = animation
additionalCompletion = completion
}
///
public func complete(at position: CompletionPosition) {
transitionCompletion?(position)
}
}
extension Transition {
///
public enum CompletionPosition { case start, end }
}
| mit | 3a0a11128d17a2dffc0742ac9b8bcfce | 22.567568 | 78 | 0.534977 | 4.912676 | false | false | false | false |
firebase/quickstart-ios | storage/StorageExample/Shared/ContentView.swift | 1 | 10164 | //
// Copyright (c) 2022 Google 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 SwiftUI
import FirebaseAuth
import FirebaseStorage
struct ContentView: View {
@EnvironmentObject var viewModel: ViewModel
@State private var authenticated: Bool = true
private var storage = Storage.storage()
private var imageURL: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("tempImage.jpeg")
var body: some View {
ZStack {
VStack {
#if os(iOS)
if let image = viewModel.image {
image
.resizable()
.scaledToFit()
.frame(minWidth: 300, maxHeight: 200)
.cornerRadius(16)
} else {
Image(systemName: "photo.fill")
.resizable()
.scaledToFit()
.opacity(0.6)
.frame(width: 300, height: 200, alignment: .top)
.cornerRadius(16)
.padding(.horizontal)
}
Button("Photo") {
viewModel.showingImagePicker = true
}
.buttonStyle(OrangeButton())
.disabled(!authenticated)
#elseif os(macOS)
ImagePicker(image: $viewModel.inputImage, imageURL: imageURL)
#elseif os(tvOS)
TextField("Upload an Image to Storage and type the path here.",
text: $viewModel.remoteStoragePathForSearch)
.onSubmit {
let filePath = viewModel.remoteStoragePathForSearch
let storageRef = storage.reference(withPath: filePath)
fetchDownloadURL(storageRef, storagePath: filePath)
}
#endif
if viewModel.image != nil {
Button("Upload from Data") {
uploadFromData()
}
.buttonStyle(OrangeButton())
}
if viewModel.image != nil, FileManager.default.fileExists(atPath: imageURL.path) {
Button("Upload from URL") {
uploadFromALocalFile()
}
.buttonStyle(OrangeButton())
}
if viewModel.downloadPicButtonEnabled {
Button("Download") {
Task {
await downloadImage()
}
}
.buttonStyle(OrangeButton())
}
}
#if os(iOS)
.sheet(isPresented: $viewModel.showingImagePicker) {
ImagePicker(image: $viewModel.inputImage, imageURL: imageURL)
}
#endif
.sheet(isPresented: $viewModel.downloadDone) {
if let image = viewModel.downloadedImage {
VStack {
image
.resizable()
.scaledToFit()
.frame(minWidth: 0, maxWidth: .infinity)
}
#if !os(tvOS)
.onTapGesture {
viewModel.downloadDone = false
}
#endif
#if os(macOS)
Button {
NSWorkspace.shared.selectFile(
viewModel.fileLocalDownloadURL!.path,
inFileViewerRootedAtPath: ""
)
} label: {
Text("Open in Finder")
}
.buttonStyle(OrangeButton())
#endif
}
}
.onChange(of: viewModel.inputImage) { _ in
loadImage()
}
.task {
await signInAnonymously()
}
.alert("Error", isPresented: $viewModel.errorFound) {
Button("ok") { viewModel.errorFound = false }
} message: {
if let errInfo = viewModel.errInfo {
Text(errInfo.localizedDescription)
} else {
Text("No error discription is found.")
}
}
.alert("Image was uploaded", isPresented: $viewModel.fileUploaded) {
Button("ok") {}
Button("Link") {
if let url = viewModel.fileDownloadURL {
print("downloaded url: \(url)")
#if os(iOS)
UIApplication.shared.open(url)
#elseif os(macOS)
NSWorkspace.shared.open(url)
#endif
}
}
}
if viewModel.isLoading {
LoadingView()
}
}
#if os(macOS)
.frame(width: 300, height: 600)
#endif
}
func loadImage() {
guard let inputImage = viewModel.inputImage else {
return
}
viewModel.image = setImage(fromImage: inputImage)
viewModel.showingImagePicker = false
}
func uploadFromALocalFile() {
let filePath = Auth.auth().currentUser!.uid +
"/\(Int(Date.timeIntervalSinceReferenceDate * 1000))/\(imageURL.lastPathComponent)"
let storageRef = storage.reference(withPath: filePath)
viewModel.isLoading = true
storageRef.putFile(from: imageURL, metadata: nil) { metadata, error in
guard let _ = metadata else {
// Uh-oh, an error occurred!
viewModel.errorFound = true
viewModel.errInfo = error
return
}
viewModel.isLoading = false
// You can also access to download URL after upload.
fetchDownloadURL(storageRef, storagePath: filePath)
}
}
func uploadFromData() {
guard let imageData = viewModel.inputImage?.jpeg else {
print("The image from url \(imageURL.path) cannot be transferred to data.")
return
}
let filePath = Auth.auth().currentUser!.uid +
"/\(Int(Date.timeIntervalSinceReferenceDate * 1000))/fromData/\(imageURL.lastPathComponent)"
let storageRef = storage.reference(withPath: filePath)
viewModel.isLoading = true
storageRef.putData(imageData, metadata: nil) { metadata, error in
guard let _ = metadata else {
// Uh-oh, an error occurred!
viewModel.errorFound = true
viewModel.errInfo = error
return
}
viewModel.isLoading = false
// You can also access to download URL after upload.
fetchDownloadURL(storageRef, storagePath: filePath)
}
}
func fetchDownloadURL(_ storageRef: StorageReference, storagePath: String) {
storageRef.downloadURL { url, error in
guard let downloadURL = url else {
print("Error getting download URL: \(error.debugDescription)")
viewModel.errorFound = true
viewModel.errInfo = error
return
}
print("download url: \(downloadURL) ")
viewModel.remoteStoragePath = storagePath
viewModel.downloadPicButtonEnabled = true
// tvOS Quickstart does not have `Upload` feature.
#if !os(tvOS)
viewModel.fileUploaded = true
#endif
viewModel.fileDownloadURL = downloadURL
}
}
func downloadImage() async {
// Create a reference to the file you want to download
let storageRef = Storage.storage().reference()
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let filePath = "file:\(documentsDirectory)/myimage.jpg"
guard let fileURL = URL(string: filePath) else { return }
guard let storagePath = viewModel.remoteStoragePath else {
return
}
viewModel.isLoading = true
do {
let imageURL = try await storageRef.child(storagePath).writeAsync(toFile: fileURL)
viewModel.downloadDone = true
viewModel.downloadedImage = setImage(fromURL: imageURL)
viewModel.fileLocalDownloadURL = imageURL
} catch {
viewModel.errorFound = true
viewModel.errInfo = error
}
viewModel.isLoading = false
}
func signInAnonymously() async {
// Using Cloud Storage for Firebase requires the user be authenticated. Here we are using
// anonymous authentication.
if Auth.auth().currentUser == nil {
do {
try await Auth.auth().signInAnonymously()
authenticated = true
} catch {
print("Not able to connect: \(error)")
Task { @MainActor in
viewModel.errorFound = true
viewModel.errInfo = error
}
authenticated = false
}
}
}
#if os(iOS) || os(tvOS)
func setImage(fromImage image: UIImage) -> Image {
return Image(uiImage: image)
}
#elseif os(macOS)
func setImage(fromImage image: NSImage) -> Image {
return Image(nsImage: image)
}
#endif
func setImage(fromURL url: URL) -> Image {
return setImage(fromImage: .init(contentsOfFile: url.path)!)
}
}
struct OrangeButton: ButtonStyle {
@Environment(\.isEnabled) private var isEnabled: Bool
#if os(tvOS)
@Environment(\.isFocused) var focused: Bool
#endif
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding()
.background(isEnabled ? Color.orange : Color.orange.opacity(0.5))
.foregroundColor(.white)
.clipShape(RoundedRectangle(cornerRadius: 16.0))
#if os(tvOS)
.scaleEffect(focused ? 1.2 : 1)
.animation(.easeIn, value: focused)
#endif
}
}
#if os(iOS) || os(tvOS)
extension UIImage {
var jpeg: Data? {
jpegData(compressionQuality: 1)
}
}
#elseif os(macOS)
extension NSImage {
var jpeg: Data? {
let cgImage = self.cgImage(forProposedRect: nil, context: nil, hints: nil)!
let bitmapRep = NSBitmapImageRep(cgImage: cgImage)
return bitmapRep.representation(
using: NSBitmapImageRep.FileType.jpeg,
properties: [:]
)
}
}
#endif
struct LoadingView: View {
var body: some View {
ZStack {
Color(.gray)
.ignoresSafeArea()
.opacity(0.5)
ProgressView()
.progressViewStyle(CircularProgressViewStyle(tint: .orange))
.scaleEffect(3)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| apache-2.0 | d026f6611e05c3bab68538ab2cff10f5 | 28.894118 | 98 | 0.607143 | 4.683871 | false | false | false | false |
HIkaruSato/PPParticleButton | PPParticleButton/PPParticleButton.swift | 2 | 2891 | //
// PPParticleButton.swift
// PPParticleButtonExample
//
// Created by HikaruSato on 2015/11/29.
// Copyright © 2015年 HikaruSato. All rights reserved.
//
import UIKit
import SpriteKit
import QuartzCore
enum PPParticleButtonEffectType {
case normal
case selected
case unSelected
}
class PPParticleButton: UIButton {
//var particleFileName:String = "starParticle"
var particleFileNameMap:[PPParticleButtonEffectType:String] = [PPParticleButtonEffectType:String]()
var effectParticleDuration:TimeInterval = 0.5
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
override init(frame: CGRect) {
super.init(frame: frame)
createSubViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
createSubViews()
}
func createSubViews() {
addTarget(self, action: #selector(PPParticleButton.effectParticle(_:)), for: UIControlEvents.touchUpInside)
}
func effectParticle(_ button:UIButton) {
guard let particleFileName = self.getParticleFileName() else {
//Nothing particle effect
return
}
let skView = SKView(frame:CGRect(
origin:CGPoint(x: -self.frame.origin.x, y: -self.frame.origin.y),
size: self.superview!.frame.size))
skView.backgroundColor = UIColor.clear
skView.allowsTransparency = true
self.addSubview(skView)
let scene = SKScene(size: self.superview!.frame.size)
scene.scaleMode = SKSceneScaleMode.aspectFill
scene.backgroundColor = UIColor.clear
let particle:SKEmitterNode = NSKeyedUnarchiver.unarchiveObject(withFile: Bundle.main.path(forResource: particleFileName, ofType: "sks")!) as! SKEmitterNode
particle.position = CGPoint(x: self.center.x, y: skView.frame.size.height - self.center.y)
skView.presentScene(scene)
let effect = SKAction.speed(to: 0.1, duration: self.effectParticleDuration)
let actionBlock = SKAction.run { () -> Void in
particle.particleBirthRate = 0;
}
let fadeOut = SKAction()
fadeOut.duration = 1
let remove = SKAction.removeFromParent()
let sequence = SKAction.sequence([effect, actionBlock, fadeOut, remove])
particle.run(sequence)
skView.scene!.addChild(particle)
let delay = (effect.duration + fadeOut.duration) * Double(NSEC_PER_SEC)
let time = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time, execute: {
skView.presentScene(nil)
skView.removeFromSuperview()
})
}
func getParticleFileName() -> String? {
if let filename = particleFileNameMap[PPParticleButtonEffectType.normal] {
return filename
}
if self.isSelected {
return particleFileNameMap[PPParticleButtonEffectType.selected]
} else {
return particleFileNameMap[PPParticleButtonEffectType.unSelected]
}
}
}
| mit | 609e96c37361aa6a9d057928b6f62f50 | 30.736264 | 157 | 0.743767 | 3.688378 | false | false | false | false |
klundberg/swift-corelibs-foundation | Foundation/URL.swift | 1 | 34562 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
/**
URLs to file system resources support the properties defined below. Note that not all property values will exist for all file system URLs. For example, if a file is located on a volume that does not support creation dates, it is valid to request the creation date property, but the returned value will be nil, and no error will be generated.
Only the fields requested by the keys you pass into the `URL` function to receive this value will be populated. The others will return `nil` regardless of the underlying property on the file system.
As a convenience, volume resource values can be requested from any file system URL. The value returned will reflect the property value for the volume on which the resource is located.
*/
public struct URLResourceValues {
private var _values: [URLResourceKey: AnyObject]
private var _keys: Set<URLResourceKey>
public init() {
_values = [:]
_keys = []
}
private init(keys: Set<URLResourceKey>, values: [URLResourceKey: AnyObject]) {
_values = values
_keys = keys
}
private func contains(_ key: URLResourceKey) -> Bool {
return _keys.contains(key)
}
private func _get<T>(_ key : URLResourceKey) -> T? {
return _values[key] as? T
}
private func _get(_ key : URLResourceKey) -> Bool? {
return (_values[key] as? NSNumber)?.boolValue
}
private func _get(_ key: URLResourceKey) -> Int? {
return (_values[key] as? NSNumber)?.intValue
}
private mutating func _set(_ key : URLResourceKey, newValue : AnyObject?) {
_keys.insert(key)
_values[key] = newValue
}
private mutating func _set(_ key : URLResourceKey, newValue : String?) {
_keys.insert(key)
_values[key] = newValue?._nsObject
}
private mutating func _set(_ key : URLResourceKey, newValue : [String]?) {
_keys.insert(key)
_values[key] = newValue?._nsObject
}
private mutating func _set(_ key : URLResourceKey, newValue : Date?) {
_keys.insert(key)
_values[key] = newValue?._nsObject
}
private mutating func _set(_ key : URLResourceKey, newValue : URL?) {
_keys.insert(key)
_values[key] = newValue?._nsObject
}
private mutating func _set(_ key : URLResourceKey, newValue : Bool?) {
_keys.insert(key)
if let value = newValue {
_values[key] = NSNumber(value: value)
} else {
_values[key] = nil
}
}
private mutating func _set(_ key : URLResourceKey, newValue : Int?) {
_keys.insert(key)
if let value = newValue {
_values[key] = NSNumber(value: value)
} else {
_values[key] = nil
}
}
/// A loosely-typed dictionary containing all keys and values.
///
/// If you have set temporary keys or non-standard keys, you can find them in here.
public var allValues : [URLResourceKey : AnyObject] {
return _values
}
/// The resource name provided by the file system.
public var name: String? {
get { return _get(.nameKey) }
set { _set(.nameKey, newValue: newValue) }
}
/// Localized or extension-hidden name as displayed to users.
public var localizedName: String? { return _get(.localizedNameKey) }
/// True for regular files.
public var isRegularFile: Bool? { return _get(.isRegularFileKey) }
/// True for directories.
public var isDirectory: Bool? { return _get(.isDirectoryKey) }
/// True for symlinks.
public var isSymbolicLink: Bool? { return _get(.isSymbolicLinkKey) }
/// True for the root directory of a volume.
public var isVolume: Bool? { return _get(.isVolumeKey) }
/// True for packaged directories.
///
/// - note: You can only set or clear this property on directories; if you try to set this property on non-directory objects, the property is ignored. If the directory is a package for some other reason (extension type, etc), setting this property to false will have no effect.
public var isPackage: Bool? {
get { return _get(.isPackageKey) }
set { _set(.isPackageKey, newValue: newValue) }
}
/// True if resource is an application.
public var isApplication: Bool? { return _get(.isApplicationKey) }
#if os(OSX)
/// True if the resource is scriptable. Only applies to applications.
public var applicationIsScriptable: Bool? { return _get(.applicationIsScriptableKey) }
#endif
/// True for system-immutable resources.
public var isSystemImmutable: Bool? { return _get(.isSystemImmutableKey) }
/// True for user-immutable resources
public var isUserImmutable: Bool? {
get { return _get(.isUserImmutableKey) }
set { _set(.isUserImmutableKey, newValue: newValue) }
}
/// True for resources normally not displayed to users.
///
/// - note: If the resource is a hidden because its name starts with a period, setting this property to false will not change the property.
public var isHidden: Bool? {
get { return _get(.isHiddenKey) }
set { _set(.isHiddenKey, newValue: newValue) }
}
/// True for resources whose filename extension is removed from the localized name property.
public var hasHiddenExtension: Bool? {
get { return _get(.hasHiddenExtensionKey) }
set { _set(.hasHiddenExtensionKey, newValue: newValue) }
}
/// The date the resource was created.
public var creationDate: Date? {
get { return _get(.creationDateKey) }
set { _set(.creationDateKey, newValue: newValue) }
}
/// The date the resource was last accessed.
public var contentAccessDate: Date? {
get { return _get(.contentAccessDateKey) }
set { _set(.contentAccessDateKey, newValue: newValue) }
}
/// The time the resource content was last modified.
public var contentModificationDate: Date? {
get { return _get(.contentModificationDateKey) }
set { _set(.contentModificationDateKey, newValue: newValue) }
}
/// The time the resource's attributes were last modified.
public var attributeModificationDate: Date? { return _get(.attributeModificationDateKey) }
/// Number of hard links to the resource.
public var linkCount: Int? { return _get(.linkCountKey) }
/// The resource's parent directory, if any.
public var parentDirectory: URL? { return _get(.parentDirectoryURLKey) }
/// URL of the volume on which the resource is stored.
public var volume: URL? { return _get(.volumeURLKey) }
/// Uniform type identifier (UTI) for the resource.
public var typeIdentifier: String? { return _get(.typeIdentifierKey) }
/// User-visible type or "kind" description.
public var localizedTypeDescription: String? { return _get(.localizedTypeDescriptionKey) }
/// The label number assigned to the resource.
public var labelNumber: Int? {
get { return _get(.labelNumberKey) }
set { _set(.labelNumberKey, newValue: newValue) }
}
/// The user-visible label text.
public var localizedLabel: String? {
get { return _get(.localizedLabelKey) }
}
/// An identifier which can be used to compare two file system objects for equality using `isEqual`.
///
/// Two object identifiers are equal if they have the same file system path or if the paths are linked to same inode on the same file system. This identifier is not persistent across system restarts.
public var fileResourceIdentifier: protocol<NSCopying, NSCoding, NSSecureCoding, NSObjectProtocol>? { return _get(.fileResourceIdentifierKey) }
/// An identifier that can be used to identify the volume the file system object is on.
///
/// Other objects on the same volume will have the same volume identifier and can be compared using for equality using `isEqual`. This identifier is not persistent across system restarts.
public var volumeIdentifier: protocol<NSCopying, NSCoding, NSSecureCoding, NSObjectProtocol>? { return _get(.volumeIdentifierKey) }
/// The optimal block size when reading or writing this file's data, or nil if not available.
public var preferredIOBlockSize: Int? { return _get(.preferredIOBlockSizeKey) }
/// True if this process (as determined by EUID) can read the resource.
public var isReadable: Bool? { return _get(.isReadableKey) }
/// True if this process (as determined by EUID) can write to the resource.
public var isWritable: Bool? { return _get(.isWritableKey) }
/// True if this process (as determined by EUID) can execute a file resource or search a directory resource.
public var isExecutable: Bool? { return _get(.isExecutableKey) }
/// The URL's path as a file system path.
public var path: String? { return _get(.pathKey) }
/// The document identifier -- a value assigned by the kernel to a document (which can be either a file or directory) and is used to identify the document regardless of where it gets moved on a volume.
///
/// The document identifier survives "safe save” operations; i.e it is sticky to the path it was assigned to (`replaceItem(at:,withItemAt:,backupItemName:,options:,resultingItem:) throws` is the preferred safe-save API). The document identifier is persistent across system restarts. The document identifier is not transferred when the file is copied. Document identifiers are only unique within a single volume. This property is not supported by all volumes.
public var documentIdentifier: Int? { return _get(.documentIdentifierKey) }
/// The date the resource was created, or renamed into or within its parent directory. Note that inconsistent behavior may be observed when this attribute is requested on hard-linked items. This property is not supported by all volumes.
public var addedToDirectoryDate: Date? { return _get(.addedToDirectoryDateKey) }
/// Returns the file system object type.
public var fileResourceType: URLFileResourceType? { return _get(.fileResourceTypeKey) }
/// Total file size in bytes
///
/// - note: Only applicable to regular files.
public var fileSize : Int? { return _get(.fileSizeKey) }
/// Total size allocated on disk for the file in bytes (number of blocks times block size)
///
/// - note: Only applicable to regular files.
public var fileAllocatedSize : Int? { return _get(.fileAllocatedSizeKey) }
/// Total displayable size of the file in bytes (this may include space used by metadata), or nil if not available.
///
/// - note: Only applicable to regular files.
public var totalFileSize : Int? { return _get(.totalFileSizeKey) }
/// Total allocated size of the file in bytes (this may include space used by metadata), or nil if not available. This can be less than the value returned by `totalFileSize` if the resource is compressed.
///
/// - note: Only applicable to regular files.
public var totalFileAllocatedSize : Int? { return _get(.totalFileAllocatedSizeKey) }
/// true if the resource is a Finder alias file or a symlink, false otherwise
///
/// - note: Only applicable to regular files.
public var isAliasFile : Bool? { return _get(.isAliasFileKey) }
}
public struct URL : ReferenceConvertible, CustomStringConvertible, Equatable {
public typealias ReferenceType = NSURL
private var _url : NSURL
/// Initialize with string.
///
/// Returns `nil` if a `URL` cannot be formed with the string.
public init?(string: String) {
if let inner = NSURL(string: string) {
_url = inner
} else {
return nil
}
}
public init?(string: String, relativeTo url: URL?) {
if let inner = NSURL(string: string, relativeTo: url) {
_url = inner
} else {
return nil
}
}
public init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory isDir: Bool, relativeTo baseURL: URL?) {
_url = NSURL(fileURLWithFileSystemRepresentation: path, isDirectory: isDir, relativeTo: baseURL)
}
/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
/// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
public init(fileURLWithPath path: String, isDirectory: Bool, relativeTo base: URL?) {
_url = NSURL(fileURLWithPath: path.isEmpty ? "." : path, isDirectory: isDirectory, relativeTo: base)
}
/// Initializes a newly created file URL referencing the local file or directory at path, relative to a base URL.
///
public init(fileURLWithPath path: String, relativeTo base: URL?) {
_url = NSURL(fileURLWithPath: path.isEmpty ? "." : path, relativeTo: base)
}
/// Initializes a newly created file URL referencing the local file or directory at path.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
/// - note: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
public init(fileURLWithPath path: String, isDirectory: Bool) {
_url = NSURL(fileURLWithPath: path.isEmpty ? "." : path, isDirectory: isDirectory)
}
/// Initializes a newly created file URL referencing the local file or directory at path.
///
/// If an empty string is used for the path, then the path is assumed to be ".".
public init(fileURLWithPath path: String) {
_url = NSURL(fileURLWithPath: path.isEmpty ? "." : path)
}
/// Initializes a newly created URL using the contents of the given data, relative to a base URL. If the data representation is not a legal URL string as ASCII bytes, the URL object may not behave as expected.
public init(dataRepresentation: Data, relativeTo url: URL?, isAbsolute: Bool = false) {
if isAbsolute {
_url = NSURL(absoluteURLWithDataRepresentation: dataRepresentation, relativeTo: url)
} else {
_url = NSURL(dataRepresentation: dataRepresentation, relativeTo: url)
}
}
/// Initializes a newly created URL referencing the local file or directory at the file system representation of the path. File system representation is a null-terminated C string with canonical UTF-8 encoding.
public init(fileURLWithFileSystemRepresentation path: UnsafePointer<Int8>, isDirectory: Bool, relativeToURL baseURL: URL?) {
_url = NSURL(fileURLWithFileSystemRepresentation: path, isDirectory: isDirectory, relativeTo: baseURL)
}
// MARK: -
public var description: String {
return _url.description
}
public var debugDescription: String {
return _url.debugDescription
}
public var hashValue : Int {
return _url.hash
}
// MARK: -
/// Returns the data representation of the URL's relativeString. If the URL was initialized with -initWithData:relativeToURL:, the data representation returned are the same bytes as those used at initialization; otherwise, the data representation returned are the bytes of the relativeString encoded with NSUTF8StringEncoding.
public var dataRepresentation: Data { return _url.dataRepresentation }
public var absoluteString: String? { return _url.absoluteString }
/// The relative portion of a URL. If baseURL is nil, or if the receiver is itself absolute, this is the same as absoluteString
public var relativeString: String { return _url.relativeString }
public var baseURL: URL? { return _url.baseURL }
/// If the receiver is itself absolute, this will return self.
public var absoluteURL: URL? { return _url.absoluteURL }
/// Any URL is composed of these two basic pieces. The full URL would be the concatenation of `myURL.scheme, ':', myURL.resourceSpecifier`.
public var scheme: String? { return _url.scheme }
/// Any URL is composed of these two basic pieces. The full URL would be the concatenation of `myURL.scheme, ':', myURL.resourceSpecifier`.
public var resourceSpecifier: String? { return _url.resourceSpecifier }
/// If the URL conforms to rfc 1808 (the most common form of URL), returns a component of the URL; otherwise it returns nil.
///
/// The litmus test for conformance is as recommended in RFC 1808 - whether the first two characters of resourceSpecifier is "//". In all cases, they return the component's value after resolving the receiver against its base URL.
public var host: String? { return _url.host }
/// If the URL conforms to rfc 1808 (the most common form of URL), returns a component of the URL; otherwise it returns nil.
///
/// The litmus test for conformance is as recommended in RFC 1808 - whether the first two characters of resourceSpecifier is "//". In all cases, they return the component's value after resolving the receiver against its base URL.
public var port: Int? { return _url.port?.intValue }
/// If the URL conforms to rfc 1808 (the most common form of URL), returns a component of the URL; otherwise it returns nil.
///
/// The litmus test for conformance is as recommended in RFC 1808 - whether the first two characters of resourceSpecifier is "//". In all cases, they return the component's value after resolving the receiver against its base URL.
public var user: String? { return _url.user }
/// If the URL conforms to rfc 1808 (the most common form of URL), returns a component of the URL; otherwise it returns nil.
///
/// The litmus test for conformance is as recommended in RFC 1808 - whether the first two characters of resourceSpecifier is "//". In all cases, they return the component's value after resolving the receiver against its base URL.
public var password: String? { return _url.password }
/// If the URL conforms to rfc 1808 (the most common form of URL), returns a component of the URL; otherwise it returns nil.
///
/// The litmus test for conformance is as recommended in RFC 1808 - whether the first two characters of resourceSpecifier is "//". In all cases, they return the component's value after resolving the receiver against its base URL.
public var path: String? { return _url.path }
/// If the URL conforms to rfc 1808 (the most common form of URL), returns a component of the URL; otherwise it returns nil.
///
/// The litmus test for conformance is as recommended in RFC 1808 - whether the first two characters of resourceSpecifier is "//". In all cases, they return the component's value after resolving the receiver against its base URL.
public var fragment: String? { return _url.fragment }
/// If the URL conforms to rfc 1808 (the most common form of URL), returns a component of the URL; otherwise it returns nil.
///
/// The litmus test for conformance is as recommended in RFC 1808 - whether the first two characters of resourceSpecifier is "//". In all cases, they return the component's value after resolving the receiver against its base URL.
public var parameterString: String? { return _url.parameterString }
/// If the URL conforms to rfc 1808 (the most common form of URL), returns a component of the URL; otherwise it returns nil.
///
/// The litmus test for conformance is as recommended in RFC 1808 - whether the first two characters of resourceSpecifier is "//". In all cases, they return the component's value after resolving the receiver against its base URL.
public var query: String? { return _url.query }
/// If the URL conforms to rfc 1808 (the most common form of URL), returns a component of the URL; otherwise it returns nil.
///
/// This is the same as path if baseURL is nil.
/// The litmus test for conformance is as recommended in RFC 1808 - whether the first two characters of resourceSpecifier is "//". In all cases, they return the component's value after resolving the receiver against its base URL.
public var relativePath: String? { return _url.relativePath }
public var hasDirectoryPath: Bool { return _url.hasDirectoryPath }
/// Passes the URL's path in file system representation to `block`.
///
/// File system representation is a null-terminated C string with canonical UTF-8 encoding.
/// - note: The pointer is not valid outside the context of the block.
public func withUnsafeFileSystemRepresentation(_ block: @noescape (UnsafePointer<Int8>) throws -> Void) rethrows {
try block(_url.fileSystemRepresentation)
}
/// Whether the scheme is file:; if `myURL.isFileURL` is `true`, then `myURL.path` is suitable for input into `FileManager` or `PathUtilities`.
public var isFileURL: Bool {
return _url.isFileURL
}
public func standardized() throws -> URL {
if let result = _url.standardized.map({ $0 }) {
return result;
} else {
// TODO: We need to call into CFURL to figure out the error
throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.FileReadUnknownError.rawValue, userInfo: [:])
}
}
/// Returns a file path URL that refers to the same resource as a specified URL.
///
/// File path URLs use a file system style path. A file reference URL's resource must exist and be reachable to be converted to a file path URL.
public func filePathURL() throws -> URL {
if let result = _url.filePathURL.map({ $0 }) {
return result
} else {
// TODO: We need to call into CFURL to figure out the error
throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.FileReadUnknownError.rawValue, userInfo: [:])
}
}
public var pathComponents: [String]? { return _url.pathComponents }
public var lastPathComponent: String? { return _url.lastPathComponent }
public var pathExtension: String? { return _url.pathExtension }
public func appendingPathComponent(_ pathComponent: String, isDirectory: Bool) throws -> URL {
// TODO: Use URLComponents to handle an empty-path case
/*
URLByAppendingPathComponent can return nil if:
• the URL does not have a path component. (see note 1)
• a mutable copy of the URLs string could not be created.
• a percent-encoded string of the new path component could not created using the same encoding as the URL’s string. (see note 2)
• a new URL object could not be created with the modified URL string.
Note 1: If NS/CFURL parsed URLs correctly, this would not occur because URL strings always have a path component. For example, the URL <mailto:[email protected]> should be parsed as Scheme=“mailto”, and Path= “[email protected]". Instead, CFURL returns false for CFURLCanBeDecomposed(), says Scheme=“mailto”, Path=nil, and ResourceSpecifier=“[email protected]”. rdar://problem/15060399
Note 2: CFURLCreateWithBytes() and CFURLCreateAbsoluteURLWithBytes() allow URLs to be created with an array of bytes and a CFStringEncoding. All other CFURL functions and URL methods which create URLs use kCFStringEncodingUTF8/NSUTF8StringEncoding. So, the encoding passed to CFURLCreateWithBytes/CFURLCreateAbsoluteURLWithBytes might prevent the percent-encoding of the new path component or path extension.
*/
guard let result = _url.appendingPathComponent(pathComponent, isDirectory: isDirectory) else {
throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.FileReadUnknownError.rawValue, userInfo: [:])
}
return result
}
public mutating func appendPathComponent(_ pathComponent: String, isDirectory: Bool) throws {
self = try appendingPathComponent(pathComponent, isDirectory: isDirectory)
}
public func appendingPathComponent(_ pathComponent: String) throws -> URL {
guard let result = _url.appendingPathComponent(pathComponent) else {
throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.FileReadUnknownError.rawValue, userInfo: [:])
}
return result
}
public mutating func appendPathComponent(_ pathComponent: String) throws {
self = try appendingPathComponent(pathComponent)
}
public func deletingLastPathComponent() throws -> URL {
/*
URLByDeletingLastPathComponent can return nil if:
• the URL is a file reference URL which cannot be resolved back to a path.
• the URL does not have a path component. (see note 1)
• a mutable copy of the URLs string could not be created.
• a new URL object could not be created with the modified URL string.
*/
if let result = _url.deletingLastPathComponent.map({ $0 }) {
return result
} else {
// TODO: We need to call into CFURL to figure out the error
throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.FileReadUnknownError.rawValue, userInfo: [:])
}
}
public mutating func deleteLastPathComponent() throws {
let result = try deletingLastPathComponent()
self = result
}
public func appendingPathExtension(_ pathExtension: String) throws -> URL {
/*
URLByAppendingPathExtension can return nil if:
• the new path extension is not a valid extension (see _CFExtensionIsValidToAppend)
• the URL is a file reference URL which cannot be resolved back to a path.
• the URL does not have a path component. (see note 1)
• a mutable copy of the URLs string could not be created.
• a percent-encoded string of the new path extension could not created using the same encoding as the URL’s string. (see note 1))
• a new URL object could not be created with the modified URL string.
*/
guard let result = _url.appendingPathExtension(pathExtension) else {
throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.FileReadUnknownError.rawValue, userInfo: [:])
}
return result
}
public mutating func appendPathExtension(_ pathExtension: String) throws {
self = try appendingPathExtension(pathExtension)
}
public func deletingPathExtension() throws -> URL {
/*
URLByDeletingPathExtension can return nil if:
• the URL is a file reference URL which cannot be resolved back to a path.
• the URL does not have a path component. (see note 1)
• a mutable copy of the URLs string could not be created.
• a new URL object could not be created with the modified URL string.
*/
if let result = _url.deletingPathExtension.map({ $0 }) {
return result
} else {
// TODO: We need to call into CFURL to figure out the error
throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.FileReadUnknownError.rawValue, userInfo: [:])
}
}
public mutating func deletePathExtension() throws {
let result = try deletingPathExtension()
self = result
}
public func standardizingPath() throws -> URL {
/*
URLByStandardizingPath can return nil if:
• the URL is a file reference URL which cannot be resolved back to a path.
• a new URL object could not be created with the standardized path).
*/
if let result = _url.standardizingPath.map({ $0 }) {
return result
} else {
// TODO: We need to call into CFURL to figure out the error
throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.FileReadUnknownError.rawValue, userInfo: [:])
}
}
public mutating func standardizePath() throws {
let result = try standardizingPath()
self = result
}
public func resolvingSymlinksInPath() throws -> URL {
/*
URLByResolvingSymlinksInPath can return nil if:
• the URL is a file reference URL which cannot be resolved back to a path.
• NSPathUtilities’ stringByResolvingSymlinksInPath property returns nil.
• a new URL object could not be created with the resolved path).
*/
if let result = _url.resolvingSymlinksInPath.map({ $0 }) {
return result
} else {
// TODO: We need to call into CFURL to figure out the error
throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.FileReadUnknownError.rawValue, userInfo: [:])
}
}
public mutating func resolveSymlinksInPath() throws {
let result = try resolvingSymlinksInPath()
self = result
}
// MARK: - Resource Values
#if false // disabled for now...
/// Sets the resource value identified by a given resource key.
///
/// This method writes the new resource values out to the backing store. Attempts to set a read-only resource property or to set a resource property not supported by the resource are ignored and are not considered errors. This method is currently applicable only to URLs for file system resources.
///
/// `URLResourceValues` keeps track of which of its properties have been set. Those values are the ones used by this function to determine which properties to write.
public mutating func setResourceValues(_ values: URLResourceValues) throws {
try _url.setResourceValues(values._values)
}
/// Return a collection of resource values identified by the given resource keys.
///
/// This method first checks if the URL object already caches the resource value. If so, it returns the cached resource value to the caller. If not, then this method synchronously obtains the resource value from the backing store, adds the resource value to the URL object's cache, and returns the resource value to the caller. The type of the resource value varies by resource property (see resource key definitions). If this method does not throw and the resulting value in the `URLResourceValues` is populated with nil, it means the resource property is not available for the specified resource and no errors occurred when determining the resource property was not available. This method is currently applicable only to URLs for file system resources.
///
/// When this function is used from the main thread, resource values cached by the URL (except those added as temporary properties) are removed the next time the main thread's run loop runs. `func removeCachedResourceValue(forKey:)` and `func removeAllCachedResourceValues()` also may be used to remove cached resource values.
///
/// Only the values for the keys specified in `keys` will be populated.
public func resourceValues(forKeys keys: Set<URLResourceKey>) throws -> URLResourceValues {
return URLResourceValues(keys: keys, values: try _url.resourceValues(forKeys: Array(keys)))
}
/// Sets a temporary resource value on the URL object.
///
/// Temporary resource values are for client use. Temporary resource values exist only in memory and are never written to the resource's backing store. Once set, a temporary resource value can be copied from the URL object with `func resourceValues(forKeys:)`. The values are stored in the loosely-typed `allValues` dictionary property.
///
/// To remove a temporary resource value from the URL object, use `func removeCachedResourceValue(forKey:)`. Care should be taken to ensure the key that identifies a temporary resource value is unique and does not conflict with system defined keys (using reverse domain name notation in your temporary resource value keys is recommended). This method is currently applicable only to URLs for file system resources.
public mutating func setTemporaryResourceValue(_ value : AnyObject, forKey key: URLResourceKey) {
_url.setTemporaryResourceValue(value, forKey: key)
}
/// Removes all cached resource values and all temporary resource values from the URL object.
///
/// This method is currently applicable only to URLs for file system resources.
public mutating func removeAllCachedResourceValues() {
_url.removeAllCachedResourceValues()
}
/// Removes the cached resource value identified by a given resource value key from the URL object.
///
/// Removing a cached resource value may remove other cached resource values because some resource values are cached as a set of values, and because some resource values depend on other resource values (temporary resource values have no dependencies). This method is currently applicable only to URLs for file system resources.
public mutating func removeCachedResourceValue(forKey key: URLResourceKey) {
_url.removeCachedResourceValue(forKey: key)
}
#endif
internal func _resolveSymlinksInPath(excludeSystemDirs: Bool) -> URL? {
return _url._resolveSymlinksInPath(excludeSystemDirs: excludeSystemDirs)
}
// MARK: - Bridging Support
internal init(reference: NSURL) {
_url = reference.copy() as! NSURL
}
internal var reference : NSURL {
return _url
}
}
public func ==(lhs: URL, rhs: URL) -> Bool {
return lhs.reference.isEqual(rhs.reference)
}
extension URL : Bridgeable {
public typealias BridgeType = NSURL
public func bridge() -> BridgeType {
return _nsObject
}
}
extension NSURL : Bridgeable {
public typealias BridgeType = URL
public func bridge() -> BridgeType {
return _swiftObject
}
}
| apache-2.0 | c1815720b565d688ba42903abb16a768 | 51.422492 | 758 | 0.686293 | 4.925603 | false | false | false | false |
KrishMunot/swift | test/expr/cast/array_downcast.swift | 6 | 1677 | // RUN: %target-parse-verify-swift
// XFAIL: linux
// FIXME: Should go into the standard library.
public extension _ObjectiveCBridgeable {
static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> Self {
var result: Self? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
class V {}
class U : V {}
class T : U {}
var v = V()
var u = U()
var t = T()
var va = [v]
var ua = [u]
var ta = [t]
va = ta
var va2: ([V])? = va as [V]
var v2: V = va2![0]
var ua2: ([U])? = va as? [U]
var u2: U = ua2![0]
var ta2: ([T])? = va as? [T]
var t2: T = ta2![0]
// Check downcasts that require bridging.
class A {
var x = 0
}
struct B : _ObjectiveCBridgeable {
static func _isBridgedToObjectiveC() -> Bool {
return true
}
func _bridgeToObjectiveC() -> A {
return A()
}
static func _forceBridgeFromObjectiveC(
_ x: A,
result: inout B?
) {
}
static func _conditionallyBridgeFromObjectiveC(
_ x: A,
result: inout B?
) -> Bool {
return true
}
}
func testBridgedDowncastAnyObject(_ arr: [AnyObject], arrOpt: [AnyObject]?,
arrIUO: [AnyObject]!) {
var b = B()
if let bArr = arr as? [B] {
b = bArr[0]
}
if let bArr = arrOpt as? [B] {
b = bArr[0]
}
if let bArr = arrIUO as? [B] {
b = bArr[0]
}
_ = b
}
func testBridgedIsAnyObject(_ arr: [AnyObject], arrOpt: [AnyObject]?,
arrIUO: [AnyObject]!) -> Bool {
let b = B()
if arr is [B] { return arr is [B] }
if arrOpt is [B] { return arrOpt is [B] }
if arrIUO is [B] { return arrIUO is [B] }
_ = b
return false
}
| apache-2.0 | c00204fe6077f0382a3803d699a925ee | 17.032258 | 78 | 0.56291 | 3.122905 | false | false | false | false |
JohnPJenkins/swift-t | stc/docs/gallery/fib/fib.swift | 2 | 193 | import sys;
(int o) fib(int i)
{
if (i >= 2)
{
o = fib(i-1) + fib(i-2);
}
else if (i == 1)
{
o = 1;
}
else
{
o = 0;
}
}
int n = toint(argv("n"));
trace(fib(n));
| apache-2.0 | 2b7d1d92256f4ff9a48805973b925021 | 8.65 | 28 | 0.38342 | 2.097826 | false | false | false | false |
carping/Postal | PostalTests/XCTest+Utils.swift | 1 | 2439 | //
// The MIT License (MIT)
//
// Copyright (c) 2017 Snips
//
// 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 XCTest
extension XCTestCase {
static func jsonFromFile(_ filename: String) -> [String: AnyObject] {
let jsonPath = Bundle(for: self).path(forResource: filename, ofType: "json")
let jsonData = try? Data(contentsOf: URL(fileURLWithPath: jsonPath!))
return try! JSONSerialization.jsonObject(with: jsonData!, options: []) as! [String: AnyObject]
}
static func jsonArrayFromFile(_ filename: String) -> [[String: AnyObject]] {
let jsonPath = Bundle(for: self).path(forResource: filename, ofType: "json")
let jsonData = try? Data(contentsOf: URL(fileURLWithPath: jsonPath!))
return try! JSONSerialization.jsonObject(with: jsonData!, options: []) as! [[String: AnyObject]]
}
static func credentialsFor(_ provider: String) -> (email: String, password: String) {
let json = jsonFromFile("provider_credentials")
guard let providerInfo = json[provider] as? [String: String] else { fatalError("\(provider) isn't in provider.json") }
guard let email = providerInfo["email"] else { fatalError("email not present for \(provider)") }
guard let password = providerInfo["password"] else { fatalError("password not \(provider)") }
return (email, password)
}
}
| mit | eb93fc37ade4d2fb3f02e5b23aec5e3f | 48.77551 | 126 | 0.701107 | 4.434545 | false | false | false | false |
KevinCoble/AIToolbox | Playgrounds/LinearRegression.playground/Sources/LinearRegression.swift | 1 | 16199 | //
// File.swift
// AIToolbox
//
// Created by Kevin Coble on 4/4/16.
// Copyright © 2016 Kevin Coble. All rights reserved.
//
import Foundation
import Accelerate
public enum LinearRegressionError: Error {
case modelExceedsInputDimension
case matrixSolutionError
case negativeInLogOrPower
case divideByZero
}
/// Function for subterm
public enum SubtermFunction { case
none,
naturalExponent,
sine,
cosine,
log,
power // uses power value of term raised to input
}
/// Struct for a piece of a term of the linear equation being fitted
/// Subterms can be combined --> a₁²a₂² is two subterms, a₁² mulitplied by a₂² in terms
public struct LinearRegressionSubTerm
{
let inputIndex : Int
public var power = 1.0
public var function = SubtermFunction.none
public var divide = false // If true this term divides the previous subterm (ignored on first subterm), else multiply
public init(withInput: Int)
{
inputIndex = withInput
}
public func getSubTermValue(_ withInputs: [Double]) throws -> Double
{
var result = withInputs[inputIndex]
if (power != 1.0) {
let powerResult = pow(result, power) // Allow negatives if power is integer - if not, nan will result
if (result < 0.0 && powerResult.isNaN) { throw LinearRegressionError.negativeInLogOrPower }
result = powerResult
}
switch (function) {
case .none:
break
case .naturalExponent:
result = exp(result)
case .sine:
result = sin(result)
case .cosine:
result = cos(result)
case .log:
if (result < 0.0) { throw LinearRegressionError.negativeInLogOrPower }
result = log(result)
case .power: // uses power value of term raised to input
if (power < 0.0) { throw LinearRegressionError.negativeInLogOrPower }
result = pow(power, withInputs[inputIndex])
}
return result
}
}
/// Struct for a single term of the linear equation being fitted
/// each term is a set of LinearRegressionSubTerms multiplied (or divided) together
public struct LinearRegressionTerm
{
var subterms : [LinearRegressionSubTerm] = []
public init()
{
// Empty initializer - all terms must be added manually
}
public init(withInput: Int, atPower: Double)
{
var subTerm = LinearRegressionSubTerm(withInput: withInput)
subTerm.power = atPower
subterms.append(subTerm)
}
public mutating func addSubTerm(_ subTerm: LinearRegressionSubTerm)
{
subterms.append(subTerm)
}
func getHighestInputIndex() -> Int
{
var highestIndex = -9999
for subterm in subterms {
if (subterm.inputIndex > highestIndex) { highestIndex = subterm.inputIndex }
}
return highestIndex
}
public func getTermValue(_ withInputs: [Double]) throws -> Double
{
var result = 1.0
for subterm in subterms {
if (subterm.divide) {
do {
let value = try subterm.getSubTermValue(withInputs)
if (value != 0) {
result /= value
}
else {
throw LinearRegressionError.divideByZero
}
}
catch let error {
throw error
}
}
else {
do {
try result *= subterm.getSubTermValue(withInputs)
}
catch let error {
throw error
}
}
}
return result
}
}
/// Class for linear (in parameter space) expression
/// model is (optional bias) + At₁ + Bt₂ + Ct₃ + ... where t are the LinearRegressionTerms
open class LinearRegressionModel : Regressor
{
open fileprivate(set) var inputDimension : Int
open fileprivate(set) var outputDimension : Int
var terms : [LinearRegressionTerm] = []
open var includeBias = true
open var regularization : Double?
open var Θ : [[Double]] = []
public init(inputSize: Int, outputSize: Int)
{
inputDimension = inputSize
outputDimension = outputSize
}
public convenience init(inputSize: Int, outputSize: Int, polygonOrder: Int, includeCrossTerms: Bool = false)
{
self.init(inputSize: inputSize, outputSize: outputSize)
// Add terms for each input to the polygon order specified
for input in 0..<inputSize {
for power in 0..<polygonOrder {
let term = LinearRegressionTerm(withInput: input, atPower: Double(power+1))
terms.append(term)
if (includeCrossTerms) {
for otherInput in 0..<input {
for otherPower in 0..<polygonOrder {
var term = LinearRegressionTerm(withInput: input, atPower: Double(power+1))
var subTerm = LinearRegressionSubTerm(withInput: otherInput)
subTerm.power = Double(otherPower+1)
term.addSubTerm(subTerm)
terms.append(term)
}
}
}
}
}
}
open func addTerm(_ newTerm: LinearRegressionTerm)
{
terms.append(newTerm)
}
open func getInputDimension() -> Int
{
return inputDimension
}
open func getOutputDimension() -> Int
{
return outputDimension
}
open func getParameterDimension() -> Int
{
var numParameters = terms.count
if (includeBias) { numParameters += 1 }
numParameters *= outputDimension
return numParameters
}
open func setParameters(_ parameters: [Double]) throws
{
if (parameters.count < getParameterDimension()) { throw MachineLearningError.notEnoughData }
var numParameters = terms.count
if (includeBias) { numParameters += 1 }
var offset = 0
if (Θ.count < outputDimension) { Θ = [[Double]](repeating: [], count: outputDimension) }
for index in 0..<outputDimension {
Θ[index] = Array(parameters[offset..<(offset+numParameters)])
offset += numParameters
}
}
open func setCustomInitializer(_ function: ((_ trainData: DataSet)->[Double])!) {
// Ignore, as Linear Regression doesn't use an initialization
}
open func getParameters() throws -> [Double]
{
var parameters : [Double] = []
for index in 0..<outputDimension {
parameters += Θ[index]
}
return parameters
}
open func trainRegressor(_ trainData: DataSet) throws
{
// Verify that the data is regression data
if (trainData.dataType != DataSetType.regression) { throw MachineLearningError.dataNotRegression }
// Get the number of input values needed by the model
var neededInputs = 0
for term in terms {
let termHighest = term.getHighestInputIndex()
if (termHighest > neededInputs) { neededInputs = termHighest }
}
// Validate that the model has the dimension
if (neededInputs >= inputDimension) {
throw LinearRegressionError.modelExceedsInputDimension
}
// Validate the data size
if (trainData.inputDimension != inputDimension || trainData.outputDimension != outputDimension) {
throw MachineLearningError.dataWrongDimension
}
// Get the number of terms in the matrix (columns)
let numColumns = getParameterDimension()
// Make sure we have enough data for a solution (at least 1 per term)
if (trainData.size < numColumns) {
throw MachineLearningError.notEnoughData
}
// Allocate the parameter array
Θ = [[Double]](repeating: [], count: outputDimension)
// We can use lapack dgels if no regularization term
if (regularization == nil) {
// Make a column-major matrix of the data, with any bias term
var A = [Double](repeating: 0.0, count: trainData.size * numColumns)
var offset = 0
if (includeBias) {
for _ in 0..<trainData.size {
A[offset] = 1.0
offset += 1
}
}
for parameter in 0..<terms.count {
for index in 0..<trainData.size {
do {
A[offset] = try terms[parameter].getTermValue(trainData.inputs[index])
}
catch let error {
throw error
}
offset += 1
}
}
// Make a column-major vector of the training output matrix
offset = 0
var y = [Double](repeating: 0.0, count: trainData.size * outputDimension)
for column in 0..<outputDimension {
for index in 0..<trainData.size {
y[offset] = trainData.outputs![index][column]
offset += 1
}
}
// Solve the matrix for the parameters Θ (DGELS)
let jobTChar = "N" as NSString
var jobT : Int8 = Int8(jobTChar.character(at: 0)) // not transposed
var m : Int32 = Int32(trainData.size)
var n : Int32 = Int32(numColumns)
var nrhs = Int32(outputDimension)
var work : [Double] = [0.0]
var lwork : Int32 = -1 // Ask for the best size of the work array
var info : Int32 = 0
dgels_(&jobT, &m, &n, &nrhs, &A, &m, &y, &m, &work, &lwork, &info)
if (info != 0 || work[0] < 1) {
throw LinearRegressionError.matrixSolutionError
}
lwork = Int32(work[0])
work = [Double](repeating: 0.0, count: Int(work[0]))
dgels_(&jobT, &m, &n, &nrhs, &A, &m, &y, &m, &work, &lwork, &info)
if (info != 0 || work[0] < 1) {
throw LinearRegressionError.matrixSolutionError
}
// Extract the parameters from the results
for output in 0..<outputDimension {
for parameter in 0..<numColumns {
Θ[output].append(y[output * trainData.size + parameter])
}
}
}
// If we have a regularization term, we need to work some of the algebra ourselves
else {
// Get the dimensions of the A matrix
let nNumPoints = trainData.size
let N : la_count_t = la_count_t(numColumns)
let M : la_count_t = la_count_t(nNumPoints)
// Generate the A Matrix
var dA = [Double](repeating: 0.0, count: trainData.size * numColumns)
var offset = 0
for point in 0..<nNumPoints {
if (includeBias) {
dA[offset] = 1.0
offset += 1
}
for parameter in 0..<terms.count {
do {
dA[offset] = try terms[parameter].getTermValue(trainData.inputs[point])
}
catch let error {
throw error
}
offset += 1
}
}
// Convert into Linear Algebra objects`
let A = la_matrix_from_double_buffer(dA, M, N,
N, la_hint_t(LA_NO_HINT), la_attribute_t(LA_DEFAULT_ATTRIBUTES))
// Calculate A'A
var AtA = la_matrix_product(la_transpose(A), A)
// If there is a regularization term, add λI (giving (A'A + λI)
if let regTerm = regularization {
let λI = la_scale_with_double(la_identity_matrix(N, la_scalar_type_t(LA_SCALAR_TYPE_DOUBLE), la_attribute_t(LA_DEFAULT_ATTRIBUTES)), regTerm)
AtA = la_sum(AtA, λI)
}
// Iterate through each solution
var Y = [Double](repeating: 0.0, count: trainData.size)
for solution in 0..<outputDimension {
// Generate the Y vector
for point in 0..<nNumPoints {
Y[point] = trainData.outputs![point][solution]
}
// Calculate A'Y
let vY = la_matrix_from_double_buffer(Y, M, 1,
1, la_hint_t(LA_NO_HINT), la_attribute_t(LA_DEFAULT_ATTRIBUTES))
let AtY = la_matrix_product(la_transpose(A), vY)
// W = inverse(A'A + λI) * A'Y
// (A'A + λI)W = A'Y --> of the form Ax = b, we can use the solve function
let W = la_solve(AtA, AtY)
// Extract the results back into the learning parameter array
var parameters = [Double](repeating: 0.0, count: numColumns)
la_vector_to_double_buffer(¶meters, 1, W)
Θ[solution] = parameters
}
}
}
open func continueTrainingRegressor(_ trainData: DataSet) throws
{
// Linear regression uses one-batch training (solved analytically)
throw MachineLearningError.continuationNotSupported
}
open func predictOne(_ inputs: [Double]) throws ->[Double]
{
// Make sure we are trained
if (Θ.count < 1) { throw MachineLearningError.notTrained }
// Get the number of input values needed by the model
var neededInputs = 0
for term in terms {
let termHighest = term.getHighestInputIndex()
if (termHighest > neededInputs) { neededInputs = termHighest }
}
// Validate that the model has the dimension
if (neededInputs >= inputDimension) {
throw LinearRegressionError.modelExceedsInputDimension
}
// Get the array of term values
var termValues : [Double] = []
// If we have a bias term, add it
if (includeBias) { termValues.append(1.0) }
// Add each term value
for term in terms {
do {
try termValues.append(term.getTermValue(inputs))
}
catch let error {
throw error
}
}
// Use dot product to multiply the term values by the computed parameters to get each value
var results : [Double] = []
var value = 0.0
for parameters in Θ {
vDSP_dotprD(termValues, 1, parameters, 1, &value, vDSP_Length(termValues.count))
results.append(value)
}
return results
}
open func predict(_ testData: DataSet) throws
{
// Verify the data set is the right type
if (testData.dataType != .regression) { throw MachineLearningError.dataNotRegression }
if (testData.inputDimension != inputDimension) { throw MachineLearningError.dataWrongDimension }
if (testData.outputDimension != outputDimension) { throw MachineLearningError.dataWrongDimension }
// predict on each input
testData.outputs = []
for index in 0..<testData.size {
do {
try testData.outputs!.append(predictOne(testData.inputs[index]))
}
catch let error {
throw error
}
}
}
}
| apache-2.0 | cc8bdfbef0202f98410a03268b102a6d | 34.290393 | 157 | 0.532018 | 4.598293 | false | false | false | false |
ahayman/RxStream | RxStream/Utilities/Either.swift | 1 | 4183 | //
// Either.swift
// RxStream
//
// Created by Aaron Hayman on 3/9/17.
// Copyright © 2017 Aaron Hayman. All rights reserved.
//
import Foundation
/**
Either serves as a functional construct to represent a variable that can be _either_ one value or another (Either Left or Right).
It includes convenience initializer and accessors, along with closures that can be used to execute code
depending on the value represent by Either.
*/
public enum Either<Left, Right> {
case left(Left)
case right(Right)
/// Convenient Initializer: Initialize with value and the Enum will choose the appropriate case for it.
public init(_ value: Left) {
self = .left(value)
}
/// Convenient Initializer: Initialize with value and the Enum will choose the appropriate case for it.
public init(_ value: Right) {
self = .right(value)
}
/// Returns the left value, if the Either contains one
public var left: Left? {
guard case let .left(value) = self else { return nil }
return value
}
/// Returns the right value, if the Either contains one
public var right: Right? {
guard case let .right(value) = self else { return nil }
return value
}
/// Use this to execute a handler that will only run if the enum is .success. Returns `self` for chaining.
@discardableResult public func onLeft(_ handler: (Left) -> Void) -> Either<Left, Right> {
switch self {
case let .left(value): handler(value)
default: break
}
return self
}
/// Use this to execute a handler that will only run if the enum is .failure. Returns `self` for chaining.
@discardableResult public func onRight(_ handler: (Right) -> Void) -> Either<Left, Right> {
switch self {
case let .right(value): handler(value)
default: break
}
return self
}
}
/**
EitherAnd is a specialized version of Either that can represent either value separately or _both_ values at once.
EitherAnd can be useful if you need to provide both values but do not know which values are coming in which order.
It solves the problem inherent in trying to represent two optional values, ( `(Left?, Right?)` ) when you know
you will have one or another, but never none at all.
*/
public enum EitherAnd<Left, Right> {
case left(Left)
case right(Right)
case both(Left, Right)
/// Convenient Initializer: Initialize with value and the Enum will choose the appropriate case for it.
public init(_ value: Left) {
self = .left(value)
}
/// Convenient Initializer: Initialize with value and the Enum will choose the appropriate case for it.
public init(_ value: Right) {
self = .right(value)
}
public init(_ left: Left, _ right: Right) {
self = .both(left, right)
}
/// Returns the left value, if the Either contains one
public var left: Left? {
switch self {
case let .left(value): return value
case let .both(value, _): return value
default: return nil
}
}
/// Returns the right value, if the Either contains one
public var right: Right? {
switch self {
case let .right(value): return value
case let .both(_, value): return value
default: return nil
}
}
public var both: (Left, Right)? {
switch self {
case let .both(left, right): return (left, right)
default: return nil
}
}
/// Use this to execute a handler that will only run if the enum is .success. Returns `self` for chaining.
@discardableResult public func onLeft(_ handler: (Left) -> Void) -> EitherAnd<Left, Right> {
switch self {
case let .left(value): handler(value)
default: break
}
return self
}
/// Use this to execute a handler that will only run if the enum is .failure. Returns `self` for chaining.
@discardableResult public func onRight(_ handler: (Right) -> Void) -> EitherAnd<Left, Right> {
switch self {
case let .right(value): handler(value)
default: break
}
return self
}
@discardableResult public func onBoth(_ handler: (Left, Right) -> Void) -> EitherAnd<Left, Right> {
switch self {
case let .both(left, right): handler(left, right)
default: break
}
return self
}
}
| mit | 73e31d6dc802447b1414c7b146a10b83 | 28.871429 | 131 | 0.670971 | 4.028902 | false | false | false | false |
xwu/swift | test/Distributed/Runtime/distributed_actor_self_calls.swift | 1 | 2412 | // RUN: %target-swift-emit-silgen -enable-experimental-distributed -disable-availability-checking -parse-as-library %s | %FileCheck %s
// RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-distributed -Xfrontend -disable-availability-checking -parse-as-library)
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: distributed
// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
import _Distributed
distributed actor Philosopher {
distributed func think() {
}
// CHECK: sil hidden [ossa] @$s28distributed_actor_self_calls11PhilosopherC10stopEatingyyF : $@convention(method) (@guaranteed Philosopher) -> () {
func stopEating() { // NOTE: marking this async solves the issue; we find the async context then
self.think()
// Confirm we're calling the function directly, rather than the distributed thunk
// Calling the thunk would crash, because it is async (and throws), and as we're not in an async function
// trying to get the async context to call the async thunk would fail here.
//
// CHECK: // function_ref Philosopher.think()
// CHECK-NEXT: [[E:%[0-9]+]] = function_ref @$s28distributed_actor_self_calls11PhilosopherC5thinkyyF : $@convention(method) (@guaranteed Philosopher) -> ()
}
}
// ==== Fake Transport ---------------------------------------------------------
struct ActorAddress: ActorIdentity {
let address: String
init(parse address : String) {
self.address = address
}
}
struct FakeTransport: ActorTransport {
func decodeIdentity(from decoder: Decoder) throws -> AnyActorIdentity {
fatalError("not implemented \(#function)")
}
func resolve<Act>(_ identity: AnyActorIdentity, as actorType: Act.Type) throws -> Act?
where Act: DistributedActor {
return nil
}
func assignIdentity<Act>(_ actorType: Act.Type) -> AnyActorIdentity
where Act: DistributedActor {
.init(ActorAddress(parse: ""))
}
public func actorReady<Act>(_ actor: Act)
where Act: DistributedActor {
print("\(#function):\(actor)")
}
func resignIdentity(_ id: AnyActorIdentity) {}
}
// ==== Execute ----------------------------------------------------------------
func test(transport: FakeTransport) async {
_ = Philosopher(transport: transport)
}
@main struct Main {
static func main() async {
await test(transport: FakeTransport())
}
}
| apache-2.0 | e4068a3793c1764249815e70bc95c936 | 31.16 | 161 | 0.667081 | 4.284192 | false | false | false | false |
Johnykutty/SwiftLint | Source/SwiftLintFramework/Extensions/String+SwiftLint.swift | 4 | 3020 | //
// String+SwiftLint.swift
// SwiftLint
//
// Created by JP Simard on 5/16/15.
// Copyright © 2015 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
extension String {
internal func hasTrailingWhitespace() -> Bool {
if isEmpty {
return false
}
if let unicodescalar = unicodeScalars.last {
return CharacterSet.whitespaces.contains(unicodescalar)
}
return false
}
internal func isUppercase() -> Bool {
return self == uppercased()
}
internal func isLowercase() -> Bool {
return self == lowercased()
}
internal func nameStrippingLeadingUnderscoreIfPrivate(_ dict: [String: SourceKitRepresentable]) -> String {
if let aclString = dict.accessibility,
let acl = AccessControlLevel(identifier: aclString),
acl.isPrivate && characters.first == "_" {
return substring(from: index(after: startIndex))
}
return self
}
private subscript (range: Range<Int>) -> String {
let nsrange = NSRange(location: range.lowerBound,
length: range.upperBound - range.lowerBound)
if let indexRange = nsrangeToIndexRange(nsrange) {
return substring(with: indexRange)
}
fatalError("invalid range")
}
internal func substring(from: Int, length: Int? = nil) -> String {
if let length = length {
return self[from..<from + length]
}
let index = characters.index(startIndex, offsetBy: from, limitedBy: endIndex)!
return substring(from: index)
}
internal func lastIndex(of search: String) -> Int? {
if let range = range(of: search, options: [.literal, .backwards]) {
return characters.distance(from: startIndex, to: range.lowerBound)
}
return nil
}
internal func nsrangeToIndexRange(_ nsrange: NSRange) -> Range<Index>? {
guard nsrange.location != NSNotFound else {
return nil
}
let from16 = utf16.index(utf16.startIndex, offsetBy: nsrange.location,
limitedBy: utf16.endIndex) ?? utf16.endIndex
let to16 = utf16.index(from16, offsetBy: nsrange.length,
limitedBy: utf16.endIndex) ?? utf16.endIndex
if let from = Index(from16, within: self), let to = Index(to16, within: self) {
return from..<to
}
return nil
}
public func absolutePathStandardized() -> String {
return bridge().absolutePathRepresentation().bridge().standardizingPath
}
internal var isFile: Bool {
var isDirectoryObjC: ObjCBool = false
if FileManager.default.fileExists(atPath: self, isDirectory: &isDirectoryObjC) {
#if os(Linux)
return !isDirectoryObjC
#else
return !isDirectoryObjC.boolValue
#endif
}
return false
}
}
| mit | 78a044943a3e36fa8639f6551590970d | 30.778947 | 111 | 0.596224 | 4.853698 | false | false | false | false |
dander521/ShareTest | Pods/Then/Sources/Then.swift | 9 | 2419 | // 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.
import Foundation
import CoreGraphics
public protocol Then {}
extension Then where Self: Any {
/// Makes it available to set properties with closures just after initializing.
///
/// let frame = CGRect().with {
/// $0.origin.x = 10
/// $0.size.width = 100
/// }
public func with(_ block: (inout Self) -> Void) -> Self {
var copy = self
block(©)
return copy
}
/// Makes it available to execute something with closures.
///
/// UserDefaults.standard.do {
/// $0.set("devxoul", forKey: "username")
/// $0.set("[email protected]", forKey: "email")
/// $0.synchronize()
/// }
public func `do`(_ block: (Self) -> Void) {
block(self)
}
}
extension Then where Self: AnyObject {
/// Makes it available to set properties with closures just after initializing.
///
/// let label = UILabel().then {
/// $0.textAlignment = .Center
/// $0.textColor = UIColor.blackColor()
/// $0.text = "Hello, World!"
/// }
public func then(_ block: (Self) -> Void) -> Self {
block(self)
return self
}
}
extension NSObject: Then {}
extension CGPoint: Then {}
extension CGRect: Then {}
extension CGSize: Then {}
extension CGVector: Then {}
| mit | bbb686aee612c7a7a759beba5c0ddce9 | 30.828947 | 81 | 0.667631 | 4.106961 | false | false | false | false |
opitzconsulting/inspire-IT-iOS-Giveaway | OCExpoX-Giveaway-iOS/OCExpoX-Giveaway-iOS/ZaehlerViewControllerExtension_PopOver.swift | 2 | 1635 | //
// File.swift
// OCExpoX-Giveaway-iOS
//
// Created by Selenzow, Eduard on 29.05.17.
// Copyright © 2017 OPITZ CONSULTING GmbH. All rights reserved.
//
import UIKit
import Popover
extension ZaehlerViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0: self.performSegue(withIdentifier: "showSettings", sender: self)
case 1: self.performSegue(withIdentifier: "showHilfe", sender: self)
case 2: self.performSegue(withIdentifier: "showDatenschutz", sender: self)
case 3: self.performSegue(withIdentifier: "showAbout", sender: self)
default: break
}
self.popover.dismiss()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
cell.textLabel?.text = self.texts[(indexPath as NSIndexPath).row]
return cell
}
func setupPopoverTableView() {
let startPoint = CGPoint(x: self.view.frame.width - 60, y: 55)
let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width / 2, height: 175))
tableView.delegate = self
tableView.dataSource = self
tableView.isScrollEnabled = false
self.popover = Popover(options: self.popoverOptions)
self.popover.show(tableView, point: startPoint)
}
}
| mit | bae7f1bc8a2c28ec1aa0ca5c32bf8372 | 34.521739 | 109 | 0.660955 | 4.368984 | false | false | false | false |
citysite102/kapi-kaffeine | kapi-kaffeine/kapi-kaffeine/KPMainListTableViewCell.swift | 1 | 11516 | //
// KPMainListTableViewCell.swift
// kapi-kaffeine
//
// Created by YU CHONKAO on 2017/4/10.
// Copyright © 2017年 kapi-kaffeine. All rights reserved.
//
import UIKit
import CoreLocation
import AlamofireImage
class KPMainListTableViewCell: UITableViewCell {
var dataModel: KPDataModel! {
didSet {
DispatchQueue.main.async {
self.shopNameLabel.text = self.dataModel.name ?? "未命名"
self.featureContainer.featureContents = self.dataModel.featureContents
self.scoreLabel.score = String(format: "%.1f",
(self.dataModel.averageRate?.doubleValue) ?? 0)
if self.dataModel.closed {
self.shopNameLabel.text = "(已歇業) " + (self.dataModel.name ?? "未命名")
self.shopStatusLabel.textColor = KPColorPalette.KPTextColor.grayColor_level5
self.shopStatusHint.backgroundColor = KPColorPalette.KPTextColor.grayColor_level5
self.shopStatusLabel.text = "已歇業"
} else {
if self.dataModel.businessHour != nil {
let shopStatus = self.dataModel.businessHour!.shopStatus
self.shopStatusLabel.textColor = KPColorPalette.KPTextColor.grayColor
self.shopStatusLabel.text = shopStatus.status
self.shopStatusHint.backgroundColor = shopStatus.isOpening ?
KPColorPalette.KPShopStatusColor.opened :
KPColorPalette.KPShopStatusColor.closed
} else {
self.shopStatusLabel.textColor = KPColorPalette.KPTextColor.grayColor_level5
self.shopStatusHint.backgroundColor = KPColorPalette.KPTextColor.grayColor_level5
self.shopStatusLabel.text = "暫無資料"
}
}
}
// self.shopImageView.image = R.image.demo_6()
if let photoURL = dataModel.covers?["kapi_s"] ?? dataModel.covers?["google_s"] {
self.shopImageView.af_setImage(withURL: URL(string: photoURL)!,
placeholderImage: drawImage(image: R.image.icon_loading()!,
rectSize: CGSize(width: 56, height: 56),
roundedRadius: 3),
filter: nil,
progress: nil,
progressQueue: DispatchQueue.global(),
imageTransition: UIImageView.ImageTransition.crossDissolve(0.2),
runImageTransitionIfCached: true,
completion: { response in
if let responseImage = response.result.value {
self.shopImageView.image = drawImage(image: responseImage,
rectSize: CGSize(width: 56, height: 56),
roundedRadius: 3)
} else {
self.shopImageView.image = drawImage(image: R.image.icon_noImage()!,
rectSize: CGSize(width: 56, height: 56),
roundedRadius: 3)
}
})
} else {
self.shopImageView.image = drawImage(image: R.image.icon_noImage()!,
rectSize: CGSize(width: 56, height: 56),
roundedRadius: 3)
}
locationDidUpdate()
}
}
var shopImageView: UIImageView!
var shopNameLabel: KPLayerLabel!
var shopDistanceLabel: KPLayerLabel!
var scoreLabel: KPMainListCellScoreLabel!
var separator: UIView!
private var shopStatusHint: UIView!
private var shopStatusLabel: UILabel!
private var featureContainer: KPMainListCellFeatureContainer!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
shopImageView = UIImageView(image: drawImage(image: R.image.demo_6()!,
rectSize: CGSize(width: 56, height: 56),
roundedRadius: 3))
shopImageView.contentMode = .scaleAspectFill
shopImageView.clipsToBounds = true
contentView.addSubview(shopImageView)
shopImageView.addConstraints(fromStringArray: ["H:|-8-[$self(60)]",
"V:|-12-[$self(60)]-12-|"])
shopNameLabel = KPLayerLabel()
shopNameLabel.font = UIFont.systemFont(ofSize: 14.0)
shopNameLabel.textColor = KPColorPalette.KPTextColor.grayColor
shopNameLabel.isOpaque = true
shopNameLabel.layer.masksToBounds = true
contentView.addSubview(shopNameLabel)
shopNameLabel.addConstraints(fromStringArray: ["H:[$view0]-8-[$self($metric0)]",
"V:|-12-[$self]"],
metrics: [UIScreen.main.bounds.size.width/2],
views: [shopImageView])
shopStatusHint = UIView()
shopStatusHint.backgroundColor = KPColorPalette.KPShopStatusColor.opened
shopStatusHint.layer.cornerRadius = 3.0
shopStatusHint.isOpaque = true
contentView.addSubview(shopStatusHint)
shopStatusHint.addConstraints(fromStringArray: ["H:[$view0]-8-[$self(6)]",
"V:[$view1]-10-[$self(6)]"],
views: [shopImageView,
shopNameLabel])
shopStatusLabel = KPLayerLabel()
shopStatusLabel.font = UIFont.systemFont(ofSize: 12.0)
shopStatusLabel.textColor = KPColorPalette.KPTextColor.grayColor
shopStatusLabel.text = "營業時間 未知"
shopStatusLabel.isOpaque = true
shopStatusLabel.layer.masksToBounds = true
contentView.addSubview(shopStatusLabel)
shopStatusLabel.addConstraints(fromStringArray: ["H:[$view0]-5-[$self($metric0)]"],
metrics: [UIScreen.main.bounds.size.width/2],
views: [shopStatusHint,
shopNameLabel])
shopStatusLabel.addConstraintForCenterAligning(to: shopStatusHint,
in: .vertical,
constant: -2)
shopDistanceLabel = KPLayerLabel()
shopDistanceLabel.font = UIFont.systemFont(ofSize: 20.0)
shopDistanceLabel.textColor = KPColorPalette.KPTextColor.mainColor
shopDistanceLabel.text = "0m"
shopDistanceLabel.isOpaque = true
shopDistanceLabel.layer.masksToBounds = true
shopDistanceLabel.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
contentView.addSubview(shopDistanceLabel)
shopDistanceLabel.addConstraints(fromStringArray: ["H:[$view0]-8-[$self]",
"V:[$self]-8-|"],
views: [shopImageView,
shopStatusLabel])
scoreLabel = KPMainListCellScoreLabel()
contentView.addSubview(scoreLabel)
scoreLabel.addConstraints(fromStringArray: ["H:[$self(30)]-8-|",
"V:|-12-[$self(22)]"])
featureContainer = KPMainListCellFeatureContainer()
contentView.addSubview(featureContainer)
featureContainer.addConstraints(fromStringArray: ["H:[$self]-8-|",
"V:[$self]-10-|"])
separator = UIView()
separator.backgroundColor = KPColorPalette.KPBackgroundColor.grayColor_level6
contentView.addSubview(separator)
separator.addConstraints(fromStringArray: ["V:[$self(1)]|",
"H:|[$self]|"])
NotificationCenter.default.addObserver(self, selector: #selector(locationDidUpdate), name: .KPLocationDidUpdate, object: nil)
}
override func layoutSubviews() {
super.layoutSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
backgroundColor = selected ? KPColorPalette.KPBackgroundColor.grayColor_level6 : UIColor.white
// Configure the view for the selected state
}
func locationDidUpdate() {
if let distanceInMeter = dataModel.distanceInMeter {
var distance = distanceInMeter
var unit = "m"
if distance > 1000 {
unit = "km"
distance = distance/1000
}
self.shopDistanceLabel.text = String(format: "%.1f%@", distance, unit)
} else {
self.shopDistanceLabel.text = "-"
}
}
}
class KPMainListCellScoreLabel: UILabel {
private var scoreLabel: UILabel!
var contentBackgroundColor: UIColor! {
didSet {
backgroundColor = contentBackgroundColor
scoreLabel.backgroundColor = contentBackgroundColor
}
}
var score: String! {
didSet {
scoreLabel.text = score
}
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = KPColorPalette.KPBackgroundColor.mainColor
layer.cornerRadius = 2.0
layer.masksToBounds = true
scoreLabel = UILabel()
scoreLabel.textColor = KPColorPalette.KPTextColor.whiteColor
scoreLabel.font = UIFont.systemFont(ofSize: 14.0)
scoreLabel.isOpaque = true
scoreLabel.backgroundColor = KPColorPalette.KPBackgroundColor.mainColor
addSubview(scoreLabel)
scoreLabel.addConstraintForCenterAligningToSuperview(in: .vertical)
scoreLabel.addConstraintForCenterAligningToSuperview(in: .horizontal)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | e571f3572fbf7b06a5593ca74af55bdb | 46.197531 | 133 | 0.518092 | 5.967222 | false | false | false | false |
ello/ello-ios | Sources/Controllers/Profile/Calculators/ProfileHeaderBioSizeCalculator.swift | 1 | 1769 | ////
/// ProfileHeaderBioSizeCalculator.swift
//
import PromiseKit
class ProfileHeaderBioSizeCalculator: CellSizeCalculator {
var webView: UIWebView = ElloWebView() { didSet { didSetWebView() } }
static func calculateHeight(webViewHeight: CGFloat) -> CGFloat {
guard webViewHeight > 0 else { return 0 }
return webViewHeight + ProfileHeaderBioCell.Size.margins.tops
}
override init(item: StreamCellItem, width: CGFloat, columnCount: Int) {
super.init(item: item, width: width, columnCount: columnCount)
didSetWebView()
}
private func didSetWebView() {
webView.frame.size.width = width
webView.delegate = self
}
override func process() {
guard
let user = cellItem.jsonable as? User,
let formattedShortBio = user.formattedShortBio,
!formattedShortBio.isEmpty
else {
assignCellHeight(all: 0)
return
}
guard !Globals.isTesting else {
assignCellHeight(all: ProfileHeaderBioSizeCalculator.calculateHeight(webViewHeight: 30))
return
}
webView.loadHTMLString(
StreamTextCellHTML.postHTML(formattedShortBio),
baseURL: URL(string: "/")
)
}
}
extension ProfileHeaderBioSizeCalculator: UIWebViewDelegate {
func webViewDidFinishLoad(_ webView: UIWebView) {
let webViewHeight = webView.windowContentSize()?.height ?? 0
let totalHeight = ProfileHeaderBioSizeCalculator.calculateHeight(
webViewHeight: webViewHeight
)
assignCellHeight(all: totalHeight)
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
assignCellHeight(all: 0)
}
}
| mit | 34d9f0fd52519ceb7fcc4008aba16aaf | 27.532258 | 100 | 0.64952 | 4.913889 | false | false | false | false |
Lves/LLRefresh | LLRefreshDemo/Demos/BgImageRefreshViewController.swift | 1 | 2033 | //
// BgImageRefreshViewController.swift
// LLRefreshDemo
//
// Created by lixingle on 2017/3/7.
// Copyright © 2017年 com.lvesli. All rights reserved.
//
import UIKit
import LLRefresh
class BgImageRefreshViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var dataArray:[String] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
//1.0 set header by block
setRefreshByBlock()
//2.0 set header by target
// setRefreshByTarget()
tableView.ll_header?.beginRefreshing()
}
//MARK: Block实现方式
func setRefreshByBlock(){
//1.0
tableView.ll_header = LLRefreshBGImageHeader(refreshingBlock: {[weak self] _ in
self?.loadNewData()
})
}
//MARK: Target实现方式
func setRefreshByTarget(){
tableView.ll_header = LLEatHeader(target: self, action: #selector(loadNewData))
}
func loadNewData() {
//update data
let format = DateFormatter()
format.dateFormat = "HH:mm:ss"
for _ in 0...2 {
dataArray.insert(format.string(from: Date()), at: 0)
}
sleep(2)
//end refreshing
tableView.ll_header?.endRefreshing()
tableView.reloadData()
}
// MARK: - Table view data source
func numberOfSectionsInTableView(_ tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
}
cell?.textLabel?.text = dataArray[indexPath.row]
return cell!
}
}
| mit | eb9c71fc543a50f5c89ddb6d33c54453 | 26.589041 | 109 | 0.608739 | 4.640553 | false | false | false | false |
jxxcarlson/exploring_swift | Universe00/Universe00/ViewController.swift | 1 | 2622 | //
// ViewController.swift
// universe01
//
// Created by James Carlson on 6/15/15.
// Copyright © 2015 James Carlson. All rights reserved.
//
/// http://www.raywenderlich.com/90488/calayer-in-ios-with-swift-10-examples
// Invocations: https://developer.apple.com/swift/blog/?id=19
import UIKit
class ViewController: UIViewController {
let clockTick = 0.01
let sideLength = 335.0
let graphicsView = GraphicsView()
let backgroundLabel = UILabel()
let statusLabel = UILabel()
func setupLabels() {
let backgroundFrame = CGRect(x:0, y:0, width: 380, height: 640)
backgroundLabel.frame = backgroundFrame
print(backgroundLabel)
backgroundLabel.backgroundColor = UIColor.blackColor()
self.view.addSubview(backgroundLabel)
let labelFrame = CGRect(x: 20, y: 375, width: 335, height: 50)
statusLabel.frame = labelFrame
statusLabel.font = UIFont(name: "Courier", size: 18)
statusLabel.textColor = UIColor.whiteColor()
self.view.addSubview(statusLabel)
}
func setupGraphicsViews() {
self.view.addSubview(graphicsView)
let graphicsFrame = CGRect(x: 20, y: 40, width: sideLength, height: sideLength)
graphicsView.frame = graphicsFrame
}
func setupUniverse() {
sharedUniverse.width = sideLength
sharedUniverse.height = sideLength
// Initialzie universe
let obj1 = Particle(cx: 0, cy: 0, r: 60.0)
obj1.color = UIColor(red:1.0, green:0.0, blue:0.0, alpha:0.5)
obj1.x = -40
let obj2 = Particle(cx: 0, cy: 0, r: 30.0)
obj2.color = UIColor(red:0.0, green:0.5, blue:0.15, alpha:0.5)
sharedUniverse.create(obj1)
sharedUniverse.create(obj2)
}
func update() {
sharedUniverse.step()
statusLabel.text = sharedUniverse.status()
graphicsView.setNeedsDisplay()
}
override func viewDidLoad() {
super.viewDidLoad()
setupLabels()
setupGraphicsViews()
setupUniverse()
var count = 0
NSTimer.schedule(repeatInterval: clockTick) { timer in
count++
self.update()
if count >= 1200000 {
timer.invalidate()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 74144c3451da13cb700c71654d66886c | 23.268519 | 87 | 0.578405 | 4.427365 | false | false | false | false |
lfaoro/Cast | Carthage/Checkouts/RxSwift/RxCocoa/OSX/NSImageView+Rx.swift | 1 | 1605 | //
// NSImageView+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 5/17/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
import Cocoa
extension NSImageView {
public func rx_subscribeImageTo(source: Observable<NSImage?>) -> Disposable {
return rx_subscribeImageTo(false)(source: source)
}
public func rx_subscribeImageTo
(animated: Bool)
(source: Observable<NSImage?>) -> Disposable {
MainScheduler.ensureExecutingOnScheduler()
return source.subscribe(AnonymousObserver { event in
switch event {
case .Next(let value):
if animated && value != nil {
let transition = CATransition()
transition.duration = 0.25
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = kCATransitionFade
self.layer!.addAnimation(transition, forKey: kCATransition)
}
else {
self.layer!.removeAllAnimations()
}
self.image = value
case .Error(let error):
#if DEBUG
rxFatalError("Binding error to textbox: \(error)")
#endif
break
case .Completed:
break
}
})
}
}
| mit | a3f552daaaa0a35fe11998676c4c9d9a | 31.755102 | 116 | 0.515888 | 5.879121 | false | false | false | false |
baodvu/dashtag | dashtag/RegisterViewController.swift | 1 | 3898 | //
// RegisterViewController.swift
// dashtag
//
// Created by Bao Vu on 10/16/16.
// Copyright © 2016 Dashtag. All rights reserved.
//
import UIKit
import FirebaseAuth
class RegisterViewController: UIViewController {
@IBOutlet weak var fullNameTF: UITextField!
@IBOutlet weak var emailTF: UITextField!
@IBOutlet weak var passwordTF: UITextField!
@IBOutlet weak var confirmPasswordTF: UITextField!
var fullName: String {
get {
return fullNameTF.text ?? ""
}
}
var email: String {
get {
let s = emailTF.text ?? ""
return isValidEmail(s) ? s : ""
}
}
var password: String {
get {
return (passwordTF.text ?? "" == confirmPasswordTF.text ?? "") ? passwordTF.text! : ""
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//Looks for single or multiple taps.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(RegisterViewController.dismissKeyboard))
//Uncomment the line below if you want the tap not not interfere and cancel other interactions.
//tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
//Calls this function when the tap is recognized.
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluateWithObject(testStr)
}
@IBAction func createAccount(sender: UIButton) {
if email == "" {
showAlert("Please check the email field")
return
}
if fullName == "" {
showAlert("Please check the name field")
return
}
if password == "" {
showAlert("Please check the password again")
return
}
FIRAuth.auth()?.createUserWithEmail(email, password: password) { (user, error) in
if (error != nil) {
print(error)
let alert = UIAlertController(title: "Registration failed", message: "Please make sure you entered all fields correctly", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} else {
if let user = user {
let changeRequest = user.profileChangeRequest()
changeRequest.displayName = self.fullName
changeRequest.commitChangesWithCompletion { error in
if error != nil {
// An error happened.
} else {
// Profile updated.
}
}
self.performSegueWithIdentifier("SegueRegisterToLogin", sender: self)
}
}
}
}
func showAlert(message: String) -> Void {
let alert = UIAlertController(title: "Registration failed", message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
| mit | f7a12e57ffba49028d44ab0795fa3b3d | 33.486726 | 183 | 0.573518 | 5.287653 | false | false | false | false |
testpress/ios-app | ios-app/Model/Exam.swift | 1 | 5766 | //
// Exam.swift
// ios-app
//
// Copyright © 2017 Testpress. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import ObjectMapper
class Exam: DBModel {
@objc dynamic var url: String = "";
@objc dynamic var id = 0;
@objc dynamic var title: String = "";
@objc dynamic var examDescription: String = "";
@objc dynamic var startDate: String = "";
@objc dynamic var endDate: String = "";
@objc dynamic var duration: String = "";
@objc dynamic var numberOfQuestions: Int = 0;
@objc dynamic var negativeMarks: String = "";
@objc dynamic var markPerQuestion: String = "";
@objc dynamic var templateType: Int = 0;
@objc dynamic var allowRetake: Bool = true;
@objc dynamic var maxRetakes: Int = 0;
@objc dynamic var enableRanks: Bool = false;
@objc dynamic var rankPublishingDate: String = "";
@objc dynamic var attemptsUrl: String = "";
@objc dynamic var attemptsCount: Int = 0;
@objc dynamic var pausedAttemptsCount: Int = 0;
@objc dynamic var allowPdf: Bool = false;
@objc dynamic var allowQuestionPdf: Bool = false;
@objc dynamic var created: String = "";
@objc dynamic var slug: String = "";
@objc dynamic var variableMarkPerQuestion: Bool = false;
@objc dynamic var showAnswers: Bool = false;
@objc dynamic var commentsCount: Int = 0;
@objc dynamic var allowPreemptiveSectionEnding: Bool = false;
@objc dynamic var immediateFeedback: Bool = false;
@objc dynamic var deviceAccessControl: String = "";
@objc dynamic var totalMarks: String = ""
@objc dynamic var passPercentage: Double = 0
@objc dynamic var showScore: Bool = true
@objc dynamic var showPercentile: Bool = true
@objc dynamic var studentsAttemptedCount: Int = 0
@objc dynamic var isGrowthHackEnabled: Bool = false;
@objc dynamic var shareTextForSolutionUnlock: String = "";
override public static func primaryKey() -> String? {
return "id"
}
public override func mapping(map: Map) {
url <- map["url"]
id <- map["id"]
title <- map["title"]
startDate <- map["start_date"]
endDate <- map["end_date"]
duration <- map["duration"]
numberOfQuestions <- map["number_of_questions"]
negativeMarks <- map["negative_marks"]
markPerQuestion <- map["mark_per_question"]
templateType <- map["template_type"]
allowRetake <- map["allow_retake"]
maxRetakes <- map["max_retakes"]
enableRanks <- map["enable_ranks"]
rankPublishingDate <- map["rank_publishing_date"]
attemptsUrl <- map["attempts_url"]
attemptsCount <- map["attempts_count"]
pausedAttemptsCount <- map["paused_attempts_count"]
allowPdf <- map["allow_pdf"]
allowQuestionPdf <- map["allow_question_pdf"]
created <- map["created"]
slug <- map["slug"]
variableMarkPerQuestion <- map["variable_mark_per_question"]
showAnswers <- map["show_answers"]
commentsCount <- map["comments_count"]
allowPreemptiveSectionEnding <- map["allow_preemptive_section_ending"]
immediateFeedback <- map["immediate_feedback"]
deviceAccessControl <- map["device_access_control"]
totalMarks <- map["total_marks"]
passPercentage <- map["pass_percentage"]
showScore <- map["show_score"]
showPercentile <- map["show_percentile"]
studentsAttemptedCount <- map["students_attempted_count"]
isGrowthHackEnabled <- map["is_growth_hack_enabled"]
shareTextForSolutionUnlock <- map["share_text_for_solution_unlock"]
examDescription <- map["description"]
}
func hasStarted() -> Bool {
guard let date = FormatDate.getDate(from: startDate) else {
assert(false, "no date from string")
return true
}
return date < Date()
}
func hasEnded() -> Bool {
if endDate == nil || endDate == "" {
return false
}
guard let date = FormatDate.getDate(from: endDate) else {
assert(false, "no date from string")
return false
}
return date < Date()
}
private func getKey() -> String {
let id = String(self.id)
return "\(id)_SHARE_TO_UNLOCK"
}
func getNumberOfTimesShared() -> Int {
return UserDefaults.standard.integer(forKey: getKey())
}
func incrementNumberOfTimesShared() {
UserDefaults.standard.set(getNumberOfTimesShared() + 1, forKey: getKey())
}
func getQuestionsURL() -> String {
return Constants.BASE_URL + "/api/v2.4/exams/\(id)/questions/"
}
}
| mit | f3b334b2a1bcb3eec771919c25208c68 | 39.314685 | 81 | 0.647702 | 4.328078 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/GameLift/GameLift_Error.swift | 1 | 6337 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for GameLift
public struct GameLiftErrorType: AWSErrorType {
enum Code: String {
case conflictException = "ConflictException"
case fleetCapacityExceededException = "FleetCapacityExceededException"
case gameSessionFullException = "GameSessionFullException"
case idempotentParameterMismatchException = "IdempotentParameterMismatchException"
case internalServiceException = "InternalServiceException"
case invalidFleetStatusException = "InvalidFleetStatusException"
case invalidGameSessionStatusException = "InvalidGameSessionStatusException"
case invalidRequestException = "InvalidRequestException"
case limitExceededException = "LimitExceededException"
case notFoundException = "NotFoundException"
case outOfCapacityException = "OutOfCapacityException"
case taggingFailedException = "TaggingFailedException"
case terminalRoutingStrategyException = "TerminalRoutingStrategyException"
case unauthorizedException = "UnauthorizedException"
case unsupportedRegionException = "UnsupportedRegionException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize GameLift
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// The requested operation would cause a conflict with the current state of a service resource associated with the request. Resolve the conflict before retrying this request.
public static var conflictException: Self { .init(.conflictException) }
/// The specified fleet has no available instances to fulfill a CreateGameSession request. Clients can retry such requests immediately or after a waiting period.
public static var fleetCapacityExceededException: Self { .init(.fleetCapacityExceededException) }
/// The game instance is currently full and cannot allow the requested player(s) to join. Clients can retry such requests immediately or after a waiting period.
public static var gameSessionFullException: Self { .init(.gameSessionFullException) }
/// A game session with this custom ID string already exists in this fleet. Resolve this conflict before retrying this request.
public static var idempotentParameterMismatchException: Self { .init(.idempotentParameterMismatchException) }
/// The service encountered an unrecoverable internal failure while processing the request. Clients can retry such requests immediately or after a waiting period.
public static var internalServiceException: Self { .init(.internalServiceException) }
/// The requested operation would cause a conflict with the current state of a resource associated with the request and/or the fleet. Resolve the conflict before retrying.
public static var invalidFleetStatusException: Self { .init(.invalidFleetStatusException) }
/// The requested operation would cause a conflict with the current state of a resource associated with the request and/or the game instance. Resolve the conflict before retrying.
public static var invalidGameSessionStatusException: Self { .init(.invalidGameSessionStatusException) }
/// One or more parameter values in the request are invalid. Correct the invalid parameter values before retrying.
public static var invalidRequestException: Self { .init(.invalidRequestException) }
/// The requested operation would cause the resource to exceed the allowed service limit. Resolve the issue before retrying.
public static var limitExceededException: Self { .init(.limitExceededException) }
/// A service resource associated with the request could not be found. Clients should not retry such requests.
public static var notFoundException: Self { .init(.notFoundException) }
/// The specified game server group has no available game servers to fulfill a ClaimGameServer request. Clients can retry such requests immediately or after a waiting period.
public static var outOfCapacityException: Self { .init(.outOfCapacityException) }
/// The requested tagging operation did not succeed. This may be due to invalid tag format or the maximum tag limit may have been exceeded. Resolve the issue before retrying.
public static var taggingFailedException: Self { .init(.taggingFailedException) }
/// The service is unable to resolve the routing for a particular alias because it has a terminal RoutingStrategy associated with it. The message returned in this exception is the message defined in the routing strategy itself. Such requests should only be retried if the routing strategy for the specified alias is modified.
public static var terminalRoutingStrategyException: Self { .init(.terminalRoutingStrategyException) }
/// The client failed authentication. Clients should not retry such requests.
public static var unauthorizedException: Self { .init(.unauthorizedException) }
/// The requested operation is not supported in the Region specified.
public static var unsupportedRegionException: Self { .init(.unsupportedRegionException) }
}
extension GameLiftErrorType: Equatable {
public static func == (lhs: GameLiftErrorType, rhs: GameLiftErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension GameLiftErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| apache-2.0 | 310821273c883827129ad8e245306329 | 63.010101 | 329 | 0.74499 | 5.361252 | false | false | false | false |
GiorgioNatili/CryptoMessages | CryptoMessages/messages/config/MessagesWiring.swift | 1 | 782 | //
// MessagesWiring.swift
// CryptoMessages
//
// Created by Giorgio Natili on 5/8/17.
// Copyright © 2017 Giorgio Natili. All rights reserved.
//
import Foundation
class MessagesWiring {
var view: MessagesView
init(_ view: MessagesView) {
// Any additional operation goes here
self.view = view
}
func configure() {
let presenter = Messages()
let localMessageService = LocalMessageService(localStorageGateway: CoreDataLocalStorage())
let interactor = MessagesInteractor(services: localMessageService)
presenter.view = view
presenter.interactor = interactor
view.presenter = presenter
interactor.presenter = presenter
}
}
| unlicense | 3831dc9033b7564d6e65f4b2c7549031 | 21.314286 | 98 | 0.62356 | 5.03871 | false | false | false | false |
midoks/Swift-Learning | GitHubStar/GitHubStar/GitHubStar/Controllers/common/base/GsListViewController.swift | 1 | 10166 | //
// GsListViewController.swift
// GitHubStar
//
// Created by midoks on 16/3/17.
// Copyright © 2016年 midoks. All rights reserved.
//
import UIKit
import SwiftyJSON
class GsListViewController: UIViewController {
var _tableView: UITableView?
var _tableData = Array<JSON>()
let cellIdentifier = "GsListCell"
var _tableFooterHeight:CGFloat = 0
var _tableSearchData = Array<JSON>()
var _searchView = UISearchBar()
var _searchValue = ""
var _refreshView = UIRefreshControl()
var _footerView = UIView()
var _refreshing = false
var _fixedUrl = ""
var pageInfo:GitResponseLink?
var delegate:GsListViewDelegate?
var showSearch = true
deinit {
print("GsListViewController deinit")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.resetView()
if !_refreshView.isRefreshing {
_refreshView.endRefreshing()
}
}
override func viewDidLoad() {
super.viewDidLoad()
initTableView()
if self.showSearch {
initSearchView()
}
initRefreshView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func initTableView(){
var vf = self.view.frame
if _tableFooterHeight > 0 {
vf.size.height -= _tableFooterHeight
}
_tableView = UITableView(frame: vf, style: UITableViewStyle.plain)
_tableView?.register(GsUsersIconTableViewCell.self, forCellReuseIdentifier: cellIdentifier)
_tableView?.dataSource = self
_tableView?.delegate = self
self.view.addSubview(_tableView!)
}
func initSearchView(){
_searchView.frame = CGRect.zero
_searchView.placeholder = sysLang(key: "Search")
_searchView.delegate = self
_searchView.sizeToFit()
_tableView!.tableHeaderView = _searchView
}
func initRefreshView(){
_refreshView.addTarget(self, action: #selector(self.refreshUrl), for: .valueChanged)
_tableView!.addSubview(_refreshView)
_tableView?.contentOffset.y -= 60
_refreshView.beginRefreshing()
refreshUrl()
}
func refreshUrl(){
_refreshView.endRefreshing()
}
func pullRefreshView(){
_tableView?.tableFooterView = nil
_footerView = UIView(frame: CGRect(x:0, y:0, width: self.view.frame.width, height: 44))
// let footerTopLine = UIView(frame: CGRectMake(0, 0, _footerView.frame.width, 0.5))
// footerTopLine.backgroundColor = UIColor.grayColor()
// footerTopLine.layer.opacity = 0.4
// _footerView.addSubview(footerTopLine)
let footerBottomLine = UIView(frame: CGRect(x: _footerView.frame.width*0.04, y: _footerView.frame.height - 1, width: _footerView.frame.width*0.96, height: 0.5))
footerBottomLine.backgroundColor = UIColor.gray
footerBottomLine.layer.opacity = 0.3
_footerView.addSubview(footerBottomLine)
let loadMoreText = UILabel(frame: CGRect(x: 0,y: 0, width: 110, height: 40))
loadMoreText.textAlignment = .center
loadMoreText.center = _footerView.center
loadMoreText.text = sysLang(key: "Loading")
_footerView.addSubview(loadMoreText)
let upLoading = UIActivityIndicatorView(frame: CGRect(x: 0,y: 0,width:30,height: 30))
upLoading.tintColor = UIColor.gray
upLoading.activityIndicatorViewStyle = .gray
upLoading.center.y = _footerView.center.y
upLoading.frame.origin.x = _footerView.center.x - 55 - 15
upLoading.startAnimating()
_footerView.addSubview(upLoading)
_tableView?.tableFooterView = _footerView
self.startPull()
}
//MARK: - Methods -
func applyFilter(searchKey:String){
_searchValue = searchKey
for i in _tableData {
let ok = self.delegate!.applyFilter(searchKey: searchKey, data: i)
if ok {
_tableSearchData.append(i)
}
}
}
func getSelectTableData(indexPath:NSIndexPath) -> JSON {
if _searchValue != "" {
if _tableSearchData.count > 0 {
return _tableSearchData[indexPath.row]
}
}
return _tableData[indexPath.row]
}
func startPull(){
_refreshView.beginRefreshing()
if !_refreshing {
_tableView?.contentOffset.y -= 64
}
_refreshing = true
}
func pullingEnd(){
_refreshing = false
_refreshView.endRefreshing()
_tableView?.tableFooterView = nil
}
}
//Mark: - UITableViewDataSource && UITableViewDelegate -
extension GsListViewController:UITableViewDataSource, UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if _searchValue != "" {
if _tableSearchData.count > 0 {
return _tableSearchData.count
} else {
return 1
}
}
return _tableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if _searchValue != "" {
if _tableSearchData.count == 0 {
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
cell.textLabel?.textAlignment = .center
cell.textLabel?.text = sysLang(key: "Can`t find it")
return cell
}
}
let cell = self.delegate?.listTableView(tableView: tableView, cellForRowAtIndexPath: indexPath as NSIndexPath)
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
if _searchValue != "" {
if _tableSearchData.count == 0 {
} else {
self.delegate!.listTableView(tableView: tableView, didSelectRowAtIndexPath: indexPath as NSIndexPath)
}
} else {
self.delegate!.listTableView(tableView: tableView, didSelectRowAtIndexPath: indexPath as NSIndexPath)
}
}
}
extension GsListViewController:UISearchBarDelegate {
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.showsCancelButton = true
return true
}
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
return true
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
searchBar.showsCancelButton = false
_searchValue = ""
self._tableSearchData = Array<JSON>()
self._tableView!.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
_tableSearchData = Array<JSON>()
if let searchKey = searchBar.text {
self.applyFilter(searchKey: searchKey)
}
_tableView!.reloadData()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
_tableSearchData = Array<JSON>()
if let searchKey = searchBar.text {
self.applyFilter(searchKey: searchKey)
}
_tableView!.reloadData()
}
}
extension GsListViewController {
func scrollViewDidScroll(scrollView: UIScrollView) {
let offsetY = scrollView.contentOffset.y
let judgeOffsetY = scrollView.contentSize.height + scrollView.contentInset.bottom -
scrollView.frame.height// - _tableView!.tableFooterView!.frame.height
if (offsetY > judgeOffsetY) && !_refreshing && (offsetY > (_tableView?.frame.height)!) {
let url = pageInfo?.nextPage
if (url != nil && _searchValue == "" && pageInfo?.nextNum != 1) {
self.pullRefreshView()
self.delegate!.pullUrlLoad(url: url!)
}
}
}
}
extension GsListViewController {
func resetView(){
let root = self.getRootVC()
let w = root.view.frame.width < root.view.frame.height
? root.view.frame.width : root.view.frame.height
let h = root.view.frame.height > root.view.frame.width
? root.view.frame.height : root.view.frame.width
if UIDevice.current.orientation.isPortrait {
_tableView?.frame = CGRect(x: 0, y: 0, width: w, height: h - _tableFooterHeight)
} else if UIDevice.current.orientation.isLandscape {
_tableView?.frame = CGRect(x: 0, y: 0, width: h, height: w - _tableFooterHeight)
}
self._tableView?.reloadData()
}
}
extension GsListViewController{
func getNavBarHeight() -> CGFloat {
return UIApplication.shared.statusBarFrame.height + (navigationController?.navigationBar.frame.height)!
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
var tsize = size
if _tableFooterHeight > 0 {
tsize.height -= _tableFooterHeight
}
_tableView?.frame.size = tsize
_tableView?.reloadData()
}
}
protocol GsListViewDelegate : NSObjectProtocol{
func listTableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
func listTableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) -> Void
func applyFilter(searchKey:String, data:JSON) -> Bool
func pullUrlLoad(url:String) -> Void
}
| apache-2.0 | 4efcc2a66bd260c49942ec5b46906881 | 29.890578 | 168 | 0.600512 | 5.026212 | false | false | false | false |
son11592/STKeyboard | Example/STKeyboard/MainView.swift | 1 | 3615 | //
// MainView.swift
// STKeyboard
//
// Created by Son on 1/19/17.
// Copyright © 2017 Sonracle. All rights reserved.
//
import UIKit
import STKeyboard
class MainView: View {
fileprivate let textField = UITextField()
fileprivate let segment = UISegmentedControl(items: ["Normal", "Photo", "Number"])
fileprivate let imageView = UIImageView()
fileprivate let background = STButton()
override func initView() {
super.initView()
self.frame = UIScreen.main.bounds
NotificationCenter.default.addObserver(self, selector: #selector(didSelectImage(_:)),
name: NSNotification.Name(rawValue: "PhotoKeyboardCollectionCellPickImage"), object: nil)
self.background.frame = UIScreen.main.bounds
self.background._normalBackgroundColor = UIColor.clear
self.background.addTarget(self, action: #selector(backgroundTUI), for: .touchUpInside)
self.textField.frame = CGRect(x: 30, y: 30, width: UIScreen.main.bounds.width - 60, height: 34)
self.textField.backgroundColor = UIColor.commonWhiteSand
self.textField.layer.cornerRadius = 5
self.textField.delegate = self
self.segment.frame = CGRect(x: 30, y: self.textField.frame.maxY + 20, width: UIScreen.main.bounds.width - 60, height: 40)
self.segment.addTarget(self, action: #selector(segmentDidChangeValue), for: UIControlEvents.valueChanged)
self.imageView.frame = CGRect(x: UIScreen.main.bounds.midX - 50, y: self.segment.frame.maxY + 20, width: 100, height: 100)
self.imageView.clipsToBounds = true
self.imageView.contentMode = UIViewContentMode.scaleToFill
self.imageView.layer.cornerRadius = 5
self.imageView.backgroundColor = UIColor.commonWhiteSand
self.addSubview(self.background)
self.addSubview(self.textField)
self.addSubview(self.segment)
self.addSubview(self.imageView)
}
func segmentDidChangeValue() {
self.clearImage()
switch self.segment.selectedSegmentIndex {
case 1:
self.textField.switchToSTKeyboard(withType: .photo)
break
case 2:
self.textField.switchToSTKeyboard(withType: .number)
break
default:
self.textField.switchToSTKeyboard(withType: .default)
break
}
// Begin editing
_ = self.textField.becomeFirstResponder()
}
func backgroundTUI() {
_ = self.textField.resignFirstResponder()
}
func didSelectImage(_ notification: Notification) {
// Take image
guard let img = notification.object as? UIImage else { return }
let ratio: CGFloat = img.size.width / img.size.height
if ratio > 1 {
let width: CGFloat = min(150, img.size.width)
let height: CGFloat = width * img.size.height / img.size.width
self.imageView.frame = CGRect(x: UIScreen.main.bounds.midX - width / 2, y: self.segment.frame.maxY + 20, width: width, height: height)
} else {
let height: CGFloat = min(150, img.size.height)
let width: CGFloat = height * img.size.width / img.size.height
self.imageView.frame = CGRect(x: UIScreen.main.bounds.midX - width / 2, y: self.segment.frame.maxY + 20, width: width, height: height)
}
self.imageView.image = img
}
fileprivate func clearImage() {
self.imageView.frame = CGRect(x: UIScreen.main.bounds.midX - 50, y: self.segment.frame.maxY + 20, width: 100, height: 100)
self.imageView.image = nil
}
}
// MARK: - UITextFieldDelegate
extension MainView: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
if self.segment.selectedSegmentIndex < 0 {
self.segment.selectedSegmentIndex = 0
}
}
}
| mit | fe46488c9321f1e902ee2b2b9376632f | 33.419048 | 140 | 0.699502 | 4.056117 | false | false | false | false |
czechboy0/XcodeServerSDK | XcodeServerSDK/Server Helpers/SocketIOHelper.swift | 1 | 4315 | //
// SocketIOHelper.swift
// XcodeServerSDK
//
// Created by Honza Dvorsky on 27/09/2015.
// Copyright © 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
/*
inspired by: /Applications/Xcode.app/Contents/Developer/usr/share/xcs/xcsd/node_modules/socket.io/lib/parser.js
also helped: https://github.com/Crphang/Roadents/blob/df59d10bd102f04962e933f9a477066ea0c84da7/socket.IO-objc-master/SocketIOTransportXHR.m
*/
public struct SocketIOPacket {
public enum PacketType: Int {
case Disconnect = 0
case Connect = 1
case Heartbeat = 2
case Message = 3
case JSON = 4
case Event = 5
case Ack = 6
case Error = 7
case Noop = 8
}
public enum ErrorReason: Int {
case TransportNotSupported = 0
case ClientNotHandshaken = 1
case Unauthorized = 2
}
public enum ErrorAdvice: Int {
case Reconnect = 0
}
private let dataString: String
public let type: PacketType
public let stringPayload: String
public var jsonPayload: NSDictionary? {
guard let data = self.stringPayload.dataUsingEncoding(NSUTF8StringEncoding) else { return nil }
let obj = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
let dict = obj as? NSDictionary
return dict
}
public init?(data: String) {
self.dataString = data
guard let comps = SocketIOPacket.parseComps(data) else { return nil }
(self.type, self.stringPayload) = comps
}
private static func countInitialColons(data: String) -> Int {
var initialColonsCount = 0
for i in data.characters {
if i == ":" {
initialColonsCount += 1
} else {
if initialColonsCount > 0 {
break
}
}
}
return initialColonsCount
}
private static func parseComps(data: String) -> (type: PacketType, stringPayload: String)? {
//find the initial sequence of colons and count them, to know how to split the packet
let initialColonsCount = self.countInitialColons(data)
let splitter = String(count: initialColonsCount, repeatedValue: Character(":"))
let comps = data
.componentsSeparatedByString(splitter)
.filter { $0.characters.count > 0 }
guard comps.count > 0 else { return nil }
guard
let typeString = comps.first,
let typeInt = Int(typeString),
let type = PacketType(rawValue: typeInt)
else { return nil }
let stringPayload = comps.count == 1 ? "" : (comps.last ?? "")
return (type, stringPayload)
}
//e.g. "7:::1+0"
public func parseError() -> (reason: ErrorReason?, advice: ErrorAdvice?) {
let comps = self.stringPayload.componentsSeparatedByString("+")
let reasonString = comps.first ?? ""
let reasonInt = Int(reasonString) ?? -1
let adviceString = comps.count == 2 ? comps.last! : ""
let adviceInt = Int(adviceString) ?? -1
let reason = ErrorReason(rawValue: reasonInt)
let advice = ErrorAdvice(rawValue: adviceInt)
return (reason, advice)
}
}
public class SocketIOHelper {
public static func parsePackets(message: String) -> [SocketIOPacket] {
let packetStrings = self.parsePacketStrings(message)
let packets = packetStrings.map { SocketIOPacket(data: $0) }.filter { $0 != nil }.map { $0! }
return packets
}
private static func parsePacketStrings(message: String) -> [String] {
// Sometimes Socket.IO "batches" up messages in one packet, so we have to split them.
// "Batched" format is:
// �[packet_0 length]�[packet_0]�[packet_1 length]�[packet_1]�[packet_n length]�[packet_n]
let splitChar = "\u{fffd}"
guard message.hasPrefix(splitChar) else { return [message] }
let comps = message
.substringFromIndex(message.startIndex.advancedBy(1))
.componentsSeparatedByString(splitChar)
.filter { $0.componentsSeparatedByString(":::").count > 1 }
return comps
}
}
| mit | bb0ea0267f914843ee2db890c17de775 | 33.416 | 139 | 0.609252 | 4.272095 | false | false | false | false |
nickswalker/ASCIIfy | Pod/Classes/ColorLookupTable.swift | 1 | 3795 | //
// Copyright for portions of ASCIIfy are held by Barış Koç, 2014 as part of
// project BKAsciiImage and Amy Dyer, 2012 as part of project Ascii. All other copyright
// for ASCIIfy are held by Nick Walker, 2016.
//
// 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.
//
// BlockGrid class and block struct are adapted from
// https://github.com/oxling/iphone-ascii/blob/master/ASCII/BlockGrid.h
//
import Foundation
import KDTree
extension Color: KDTreePoint {
@nonobjc public static var dimensions: Int = 3
public func kdDimension(_ dimension: Int) -> Double {
let (r, g, b, _) = components()
switch dimension {
case 0:
return Double(r)
case 1:
return Double(g)
case 2:
return Double(b)
default:
return 0.0
}
}
public func squaredDistance(to otherPoint: Color) -> Double {
let (r, g, b, a) = components()
let (or, og, ob, oa) = otherPoint.components()
return pow(r - or, 2) + pow(g - og, 2) + pow(b - ob, 2) + pow(a - oa, 2)
}
#if os(iOS)
private func components() -> (Double, Double, Double, Double) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 0.0
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return (Double(red), Double(green), Double(blue), Double(alpha))
}
#elseif os(OSX)
fileprivate func components() -> (Double, Double, Double, Double) {
let color = usingColorSpaceName(NSColorSpaceName.calibratedRGB)!
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 0.0
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return (Double(red), Double(green), Double(blue), Double(alpha))
}
#endif
}
open class ColorLookupTable: LookupTable {
// MARK: Properties
fileprivate let tree: KDTree<KDTreeEntry<Color, String>>
// MARK: Initialization
public init() {
let emojiList: [(String, Color)] = [("❤️", .red) , ("😡", .orange), ("🌞", .yellow), ("🍏", .green), ("🐌", .brown), ("🔵", .blue), ("👿", .purple), ("🌂", .magenta), ("🐇", .white)]
let entries = emojiList.map{KDTreeEntry<Color, String>(key: $1, value: $0)}
tree = KDTree(values: entries)
}
// MARK: LookupTable
open func lookup(_ block: BlockGrid.Block) -> String? {
let color = Color(red: CGFloat(block.r), green: CGFloat(block.g), blue: CGFloat(block.b), alpha: CGFloat(block.a))
let nearest = tree.nearest(to: KDTreeEntry<Color, String>(key: color, value: ""))
return nearest?.value
}
}
| mit | 32dfd8a89a44479f6de55b3559be641c | 38.621053 | 182 | 0.638151 | 3.779116 | false | false | false | false |
Parallaxer/Parallaxer | Sources/Base/Paralaxables/CGPoint+Parallaxable.swift | 1 | 811 | import CoreGraphics
extension CGPoint: Parallaxable {
public static func position(forValue value: CGPoint, from: CGPoint, to: CGPoint) -> Double {
let a = CGPoint(x: value.x - from.x, y: value.y - from.y)
let b = CGPoint(x: to.x - from.x, y: to.y - from.y)
let bmag = CGFloat(sqrt(Double(b.x * b.x + b.y * b.y)))
let bnorm = CGPoint(x: b.x / bmag, y: b.y / bmag)
let scalarProjection = a.x * bnorm.x + a.y * bnorm.y
return Double(scalarProjection / bmag)
}
public static func value(atPosition position: Double, from: CGPoint, to: CGPoint) -> CGPoint {
let position = CGFloat(position)
let b = CGPoint(x: to.x - from.x, y: to.y - from.y)
return CGPoint(x: from.x + b.x * position, y: from.y + b.y * position)
}
}
| mit | 0bb581546601cfea62e4fa45015d41f2 | 41.684211 | 98 | 0.591862 | 3.131274 | false | false | false | false |
NordicSemiconductor/IOS-Pods-DFU-Library | iOSDFULibrary/Classes/Implementation/LegacyDFU/DFU/LegacyDFUServiceInitiator.swift | 1 | 2372 | /*
* Copyright (c) 2019, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import CoreBluetooth
@objc public class LegacyDFUServiceInitiator : DFUServiceInitiator {
public override func start(targetWithIdentifier uuid: UUID) -> DFUServiceController? {
// The firmware file must be specified before calling `start(...)`.
guard let _ = file else {
delegateQueue.async {
self.delegate?.dfuError(.fileNotSpecified, didOccurWithMessage: "Firmware not specified")
}
return nil
}
targetIdentifier = uuid
let logger = LoggerHelper(self.logger, loggerQueue)
let executor = LegacyDFUExecutor(self, logger)
let controller = DFUServiceController()
controller.executor = executor
executor.start()
return controller
}
}
| bsd-3-clause | 46afebb9ef6a2996572b443488fdcb83 | 42.925926 | 105 | 0.726391 | 5.057569 | false | false | false | false |
abertelrud/swift-package-manager | Sources/PackageCollections/Model/TargetListResult.swift | 2 | 2222 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
import PackageModel
import SourceControl
extension PackageCollectionsModel {
public typealias TargetListResult = [TargetListItem]
public struct TargetListItem: Encodable {
public typealias Package = PackageCollectionsModel.TargetListResult.Package
/// Target
public let target: Target
/// Packages where the target is found
public let packages: [Package]
}
}
extension PackageCollectionsModel.TargetListResult {
/// Metadata of package that contains the target
public struct Package: Hashable, Encodable {
public typealias Version = PackageCollectionsModel.TargetListResult.PackageVersion
/// Package's identity
public let identity: PackageIdentity
/// Package's location
public let location: String
/// Package description
public let summary: String?
/// Package versions that contain the target
public let versions: [Version]
/// Package collections that contain this package and at least one of the `versions`
public let collections: [PackageCollectionsModel.CollectionIdentifier]
}
}
extension PackageCollectionsModel.TargetListResult {
/// Represents a package version
public struct PackageVersion: Hashable, Encodable, Comparable {
/// The version
public let version: TSCUtility.Version
/// Tools version
public let toolsVersion: ToolsVersion
/// Package name
public let packageName: String
public static func < (lhs: PackageVersion, rhs: PackageVersion) -> Bool {
lhs.version < rhs.version && lhs.toolsVersion < rhs.toolsVersion
}
}
}
| apache-2.0 | d4fe46dafd4dcefa2bdf623a0cd54654 | 30.742857 | 92 | 0.646715 | 5.847368 | false | false | false | false |
apple/swift | test/Parse/availability_query_unavailability.swift | 2 | 5880 | // RUN: %target-typecheck-verify-swift
// REQUIRES: OS=macosx
// This file is mostly an inverted version of availability_query.swift
if #unavailable(OSX 10.51) {
}
// Disallow explicit wildcards.
if #unavailable(OSX 10.51, *) {} // expected-error {{platform wildcard '*' is always implicit in #unavailable}} {{28-29=}}
// Disallow use as an expression.
if (#unavailable(OSX 10.51)) {} // expected-error {{#unavailable may only be used as condition of an 'if', 'guard'}}
let x = #unavailable(OSX 10.51) // expected-error {{#unavailable may only be used as condition of}}
(#unavailable(OSX 10.51) ? 1 : 0) // expected-error {{#unavailable may only be used as condition of an}}
if !#unavailable(OSX 10.52) { // expected-error {{#unavailable may only be used as condition of an}}
}
if let _ = Optional(5), !#unavailable(OSX 10.52) { // expected-error {{#unavailable may only be used as condition}}
}
if #unavailable(OSX 10.51) && #unavailable(OSX 10.52) { // expected-error {{expected ',' joining parts of a multi-clause condition}} {{27-30=,}}
}
if #unavailable { // expected-error {{expected availability condition}}
}
if #unavailable( { // expected-error {{expected platform name}} expected-error {{expected ')'}} expected-note {{to match this opening '('}}
}
if #unavailable() { // expected-error {{expected platform name}}
}
if #unavailable(OSX { // expected-error {{expected version number}} expected-error {{expected ')'}} expected-note {{to match this opening '('}}
}
if #unavailable(OSX) { // expected-error {{expected version number}}
}
if #unavailable(OSX 10.51 { // expected-error {{expected ')'}} expected-note {{to match this opening '('}}
}
if #unavailable(iDishwasherOS 10.51) { // expected-warning {{unrecognized platform name 'iDishwasherOS'}}
}
if #unavailable(iDishwasherOS 10.51) { // expected-warning {{unrecognized platform name 'iDishwasherOS'}}
}
if #unavailable(macos 10.51) { // expected-warning {{unrecognized platform name 'macos'; did you mean 'macOS'?}} {{17-22=macOS}}
}
if #unavailable(mscos 10.51) { // expected-warning {{unrecognized platform name 'mscos'; did you mean 'macOS'?}} {{17-22=macOS}}
}
if #unavailable(macoss 10.51) { // expected-warning {{unrecognized platform name 'macoss'; did you mean 'macOS'?}} {{17-23=macOS}}
}
if #unavailable(mac 10.51) { // expected-warning {{unrecognized platform name 'mac'; did you mean 'macOS'?}} {{17-20=macOS}}
}
if #unavailable(OSX 10.51, OSX 10.52) { // expected-error {{version for 'macOS' already specified}}
}
if #unavailable(OSX 10.51, iOS 8.0, *) { } // expected-error {{platform wildcard '*' is always implicit in #unavailable}} {{37-38=}}
if #unavailable(iOS 8.0) {
}
if #unavailable(iOSApplicationExtension, unavailable) { // expected-error 2{{expected version number}}
}
// Should this be a valid spelling since `#unvailable(*)` cannot be written?
if #unavailable() { // expected-error {{expected platform name}}
}
if #unavailable(OSX 10 { // expected-error {{expected ')' in availability query}} expected-note {{to match this opening '('}}
}
// Multiple platforms
if #unavailable(OSX 10.51, iOS 8.0) {
}
if #unavailable(OSX 10.51, { // expected-error {{expected platform name}} // expected-error {{expected ')'}} expected-note {{to match this opening '('}}
}
if #unavailable(OSX 10.51,) { // expected-error {{expected platform name}}
}
if #unavailable(OSX 10.51, iOS { // expected-error {{expected version number}} // expected-error {{expected ')'}} expected-note {{to match this opening '('}}
}
if #unavailable(OSX 10.51, iOS 8.0, iDishwasherOS 10.51) { // expected-warning {{unrecognized platform name 'iDishwasherOS'}}
}
if #unavailable(iDishwasherOS 10.51, OSX 10.51) { // expected-warning {{unrecognized platform name 'iDishwasherOS'}}
}
if #unavailable(OSX 10.51 || iOS 8.0) {// expected-error {{'||' cannot be used in an availability condition}}
}
// Emit Fix-It removing un-needed >=, for the moment.
if #unavailable(OSX >= 10.51) { // expected-error {{version comparison not needed}} {{21-24=}}
}
// Bool then #unavailable.
if 1 != 2, #unavailable(iOS 8.0) {}
// Pattern then #unavailable(iOS 8.0) {
if case 42 = 42, #unavailable(iOS 8.0) {}
if let _ = Optional(42), #unavailable(iOS 8.0) {}
// Allow "macOS" as well.
if #unavailable(macOS 10.51) {
}
// Prevent availability and unavailability being present in the same statement.
if #unavailable(macOS 10.51), #available(macOS 10.52, *) { // expected-error {{#available and #unavailable cannot be in the same statement}}
}
if #available(macOS 10.51, *), #unavailable(macOS 10.52) { // expected-error {{#available and #unavailable cannot be in the same statement}}
}
if #available(macOS 10.51, *), #available(macOS 10.55, *), #unavailable(macOS 10.53) { // expected-error {{#available and #unavailable cannot be in the same statement}}
}
if #unavailable(macOS 10.51), #unavailable(macOS 10.55), #available(macOS 10.53, *) { // expected-error {{#available and #unavailable cannot be in the same statement}}
}
if case 42 = 42, #available(macOS 10.51, *), #unavailable(macOS 10.52) { // expected-error {{#available and #unavailable cannot be in the same statement}}
}
if #available(macOS 10.51, *), case 42 = 42, #unavailable(macOS 10.52) { // expected-error {{#available and #unavailable cannot be in the same statement}}
}
// Allow availability and unavailability to mix if they are not in the same statement.
if #unavailable(macOS 11) {
if #available(macOS 10, *) { }
}
if #available(macOS 10, *) {
if #unavailable(macOS 11) { }
}
// Diagnose wrong spellings of unavailability
if #available(*) == false { // expected-error {{#available cannot be used as an expression, did you mean to use '#unavailable'?}} {{4-14=#unavailable}} {{18-27=}}
}
if !#available(*) { // expected-error {{#available cannot be used as an expression, did you mean to use '#unavailable'?}} {{4-15=#unavailable}}
}
| apache-2.0 | c496907ebe20a4fff2cf1572d961ab75 | 41.302158 | 168 | 0.691327 | 3.576642 | false | false | false | false |
sonsongithub/reddift | application/MoviePlayView.swift | 1 | 5545 | //
// MoviePlayView.swift
// reddift
//
// Created by sonson on 2016/10/23.
// Copyright © 2016年 sonson. All rights reserved.
//
import Foundation
import AVKit
import AVFoundation
import YouTubeGetVideoInfoAPIParser
let MoviePlayViewUpdateTime = Notification.Name(rawValue: "MoviePlayViewUpdateTime")
let MoviePlayViewDidChangeStatus = Notification.Name(rawValue: "MoviePlayViewDidChangeStatus")
func searchMp4(infos: [FormatStreamMap]) -> FormatStreamMap? {
for info in infos {
if let _ = info.type.range(of: "mp4") {
return info
}
if let _ = info.type.range(of: "3gp") {
return info
}
}
return nil
}
class MoviePlayView: UIView {
var videoTimeObserver: Any?
let movieURL: URL
var duration = CMTime()
var presentationSize = CGSize.zero
override class var layerClass: AnyClass {
get {
return AVPlayerLayer.self
}
}
deinit {
print("deinit MoviePlayerView")
removeAllObserversFromPlayer()
}
func removeAllObserversFromPlayer() {
if let player = playerLayer.player {
if let ob = videoTimeObserver {
player.removeTimeObserver(ob)
}
player.removeObserver(self, forKeyPath: "status")
}
}
var playerLayer: AVPlayerLayer! {
get {
if let layer = self.layer as? AVPlayerLayer {
return layer
} else {
return nil
}
}
}
/// Shared session configuration
var sessionConfiguration: URLSessionConfiguration {
get {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 30
configuration.timeoutIntervalForResource = 30
return configuration
}
}
func startToLoadMovie() {
if let youtubeContentID = movieURL.extractYouTubeContentID(),
let infoURL = URL(string: "https://www.youtube.com/get_video_info?video_id=\(youtubeContentID)") {
let request = URLRequest(url: infoURL)
let session = URLSession(configuration: sessionConfiguration)
print("Start loading metadata... \(infoURL.absoluteString)")
let task = session.dataTask(with: request, completionHandler: { (data, _, error) -> Void in
do {
guard let data = data else { throw NSError(domain: "", code: 0, userInfo: nil) }
guard let result = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as String? else { throw NSError(domain: "", code: 0, userInfo: nil) }
let maps = try FormatStreamMapFromString(result)
guard let map = searchMp4(infos: maps) else { throw NSError(domain: "", code: 0, userInfo: nil) }
DispatchQueue.main.async { self.loadMovie(url: map.url) }
} catch {
print("Failed parsing metadata... \(infoURL.absoluteString) - \(error)")
// handling error
}
})
task.resume()
} else {
loadMovie(url: movieURL)
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard let player = playerLayer.player else { return }
switch player.status {
case .readyToPlay:
Timer.scheduledTimer(timeInterval: TimeInterval(0.05), target: self, selector: #selector(MoviePlayView.waitForInitializingMovie(timer:)), userInfo: nil, repeats: true)
case .failed:
do {}
case .unknown:
do {}
}
}
func loadMovie(url: URL) {
let item = AVPlayerItem(url: url)
let player = AVPlayer(playerItem: item)
playerLayer.player = player
print("Start loading movie... \(url.absoluteString)")
playerLayer.player?.addObserver(self, forKeyPath: "status", options: .new, context: nil)
if let currentItem = player.currentItem {
duration = currentItem.asset.duration
}
videoTimeObserver = player.addPeriodicTimeObserver(
forInterval: CMTimeMake(150, 600),
queue: DispatchQueue.main) {
(_) -> Void in
let currentTime = player.currentTime()
DispatchQueue.main.async {
NotificationCenter.default.post(name: MoviePlayViewUpdateTime, object: nil, userInfo: ["Time": currentTime])
}
}
}
@objc func waitForInitializingMovie(timer: Timer) {
print(playerLayer.isReadyForDisplay)
if let player = playerLayer.player, let item = player.currentItem {
let s = item.presentationSize
if s.width * s.height > 0 {
self.presentationSize = item.presentationSize
timer.invalidate()
NotificationCenter.default.post(name: MoviePlayViewDidChangeStatus, object: nil, userInfo: nil)
}
}
}
init(url: URL) {
movieURL = url
super.init(frame: CGRect.zero)
startToLoadMovie()
self.backgroundColor = UIColor.black
}
required init?(coder: NSCoder) {
movieURL = URL(string: "")!
super.init(coder: coder)
self.backgroundColor = UIColor.black
}
}
| mit | 73ca08e64cca934968e0b7fc73031e28 | 33.855346 | 179 | 0.587153 | 4.961504 | false | true | false | false |
taisukeh/ScrollingBars | ScrollingBarsExample/ScrollingBarsExample/ViewController.swift | 2 | 4617 | //
// ViewController.swift
// ScrollingBarsExample
//
// Created by Taisuke Hori on 2015/01/06.
// Copyright (c) 2015年 Hori Taisuke. All rights reserved.
//
import UIKit
import ScrollingBars
class ViewController: UIViewController, ScrollingBarsDelegate, UIWebViewDelegate {
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var topBar: UIView!
@IBOutlet weak var bottomBar: UIToolbar!
@IBOutlet weak var topBarTopSpaceConstraint: NSLayoutConstraint!
@IBOutlet weak var topBarHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var bottomBarBottomSpaceConstraint: NSLayoutConstraint!
var scrollingBars = ScrollingBars()
override func viewDidLoad() {
super.viewDidLoad()
scrollingBars.follow(webView.scrollView, delegate: self)
webView.scrollView.delegate = scrollingBars
webView.delegate = self
webView.loadRequest(NSURLRequest(URL: NSURL(string: "http://en.wikipedia.org/wiki/Scroll")!))
}
func setTopBarElementAlpha(alpha: CGFloat) {
for view in topBar.subviews as [UIView] {
view.alpha = alpha
}
}
// MARK: - ScrollingBars
var topBarHeight: CGFloat {
return self.topBar.frame.size.height
}
var topBarMinHeight: CGFloat {
if UIApplication.sharedApplication().statusBarFrame.size.height > 20 {
// In-Call statusbar
return 0
} else {
return UIApplication.sharedApplication().statusBarFrame.size.height
}
}
var topBarPosition: CGFloat {
get {
return -self.topBarTopSpaceConstraint.constant
}
set {
self.topBarTopSpaceConstraint.constant = -newValue
let hiddingRatio = newValue / (self.topBarHeight - self.topBarMinHeight)
self.setTopBarElementAlpha(1 - hiddingRatio)
self.topBar.layoutIfNeeded()
}
}
var bottomBarHeight: CGFloat {
return self.bottomBar.frame.size.height
}
var bottomBarPosition: CGFloat {
get {
return -self.bottomBarBottomSpaceConstraint.constant
}
set {
self.bottomBarBottomSpaceConstraint.constant = -newValue
self.bottomBar.layoutIfNeeded()
}
}
var bottomBarMinHeight: CGFloat {
return 0
}
// MARK: - orientation
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animateAlongsideTransition({ (context : UIViewControllerTransitionCoordinatorContext!) -> Void in
self.updateTopBarHeight()
}, completion: nil)
}
func updateTopBarHeight() {
let orientation = UIApplication.sharedApplication().statusBarOrientation
var height: CGFloat
if orientation.isPortrait || UIDevice.currentDevice().userInterfaceIdiom == .Pad {
height = 64
} else {
height = 44
}
let isHeightChanged = self.topBarHeightConstraint.constant != height
if isHeightChanged {
self.topBarHeightConstraint.constant = height
self.topBar.layoutIfNeeded()
self.scrollingBars.refresh(animated: false)
}
}
// MARK: - UIWebViewDelegate
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
switch navigationType {
case .LinkClicked:
scrollingBars.showBars(animate: true)
default:
break
}
return true
}
// MARK: - ScrollView Delegate
/**
If you can't overwrite UIScrollView's delegate (e.g. You uses UITableView),
pass scroll view events to ScrollingBars.
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
scrollingBars.scrollViewWillBeginDragging(scrollView)
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
scrollingBars.scrollViewDidEndDragging(scrollView, willDecelerate: decelerate)
}
func scrollViewDidScroll(scrollView: UIScrollView) {
scrollingBars.scrollViewDidScroll(scrollView)
}
func scrollViewWillBeginDecelerating(scrollView: UIScrollView) {
scrollingBars.scrollViewWillBeginDecelerating(scrollView)
}
func scrollViewShouldScrollToTop(scrollView: UIScrollView) -> Bool {
return scrollingBars.scrollViewShouldScrollToTop(scrollView)
}
*/
}
| mit | 4be6be929ff54e00de702eec4d85b1fb | 29.163399 | 137 | 0.663705 | 5.533573 | false | false | false | false |
shahmishal/swift | test/NameBinding/scope_map.swift | 1 | 26718 | // XFAIL: enable-astscope-lookup
// Note: test of the scope map. All of these tests are line- and
// column-sensitive, so any additions should go at the end.
struct S0 {
class InnerC0 { }
}
extension S0 {
}
class C0 {
}
enum E0 {
case C0
case C1(Int, Int)
}
struct GenericS0<T, U> {
}
func genericFunc0<T, U>(t: T, u: U, i: Int = 10) {
}
class ContainsGenerics0 {
init<T, U>(t: T, u: U) {
}
deinit {
}
}
typealias GenericAlias0<T> = [T]
#if arch(unknown)
struct UnknownArchStruct { }
#else
struct OtherArchStruct { }
#endif
func functionBodies1(a: Int, b: Int?) {
let (x1, x2) = (a, b),
(y1, y2) = (b, a)
let (z1, z2) = (a, a)
do {
let a1 = a
let a2 = a
do {
let b1 = b
let b2 = b
}
}
do {
let b1 = b
let b2 = b
}
func f(_ i: Int) -> Int { return i }
let f2 = f(_:)
struct S7 { }
typealias S7Alias = S7
if let b1 = b, let b2 = b {
let c1 = b
} else {
let c2 = b
}
guard let b1 = b, { $0 > 5 }(b1), let b2 = b else {
let c = 5
return
}
while let b3 = b, let b4 = b {
let c = 5
}
repeat { } while true;
for (x, y) in [(1, "hello"), (2, "world")] where x % 2 == 0 {
}
do {
try throwing()
} catch let mine as MyError where mine.value == 17 {
} catch {
}
switch MyEnum.second(1) {
case .second(let x) where x == 17:
break;
case .first:
break;
default:
break;
}
for (var i = 0; i != 10; i += 1) { }
}
func throwing() throws { }
struct MyError : Error {
var value: Int
}
enum MyEnum {
case first
case second(Int)
case third
}
struct StructContainsAbstractStorageDecls {
subscript (i: Int, j: Int) -> Int {
set {
}
get {
return i + j
}
}
var computed: Int {
get {
return 0
}
set {
}
}
}
class ClassWithComputedProperties {
var willSetProperty: Int = 0 {
willSet { }
}
var didSetProperty: Int = 0 {
didSet { }
}
}
func funcWithComputedProperties(i: Int) {
var computed: Int {
set {
}
get {
return 0
}
}, var (stored1, stored2) = (1, 2),
var alsoComputed: Int {
return 17
}
do { }
}
func closures() {
{ x, y in
return { $0 + $1 }(x, y)
}(1, 2) +
{ a, b in a * b }(3, 4)
}
{ closures() }()
func defaultArguments(i: Int = 1,
j: Int = { $0 + $1 }(1, 2)) {
func localWithDefaults(i: Int = 1,
j: Int = { $0 + $1 }(1, 2)) {
}
let a = i + j
{ $0 }(a)
}
struct PatternInitializers {
var (a, b) = (1, 2),
(c, d) = (1.5, 2.5)
}
protocol ProtoWithSubscript {
subscript(native: Int) -> Int { get set }
}
func localPatternsWithSharedType() {
let i, j, k: Int
}
class LazyProperties {
var value: Int = 17
lazy var prop: Int = self.value
}
// RUN: not %target-swift-frontend -dump-scope-maps expanded %s 2> %t.expanded
// RUN: %FileCheck -check-prefix CHECK-EXPANDED %s < %t.expanded
// CHECK-EXPANDED: ***Complete scope map***
// CHECK-EXPANDED-NEXT: ASTSourceFileScope {{.*}}, (uncached) [1:1 - 5{{[0-9]*}}:1] 'SOURCE_DIR{{[/\\]}}test{{[/\\]}}NameBinding{{[/\\]}}scope_map.swift'
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [5:1 - 7:1] 'S0'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [5:11 - 7:1] 'S0'
// CHECK-EXPANDED-NEXT: `-NominalTypeDeclScope {{.*}}, [6:3 - 6:19] 'InnerC0'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [6:17 - 6:19] 'InnerC0'
// CHECK-EXPANDED-NEXT: |-ExtensionDeclScope {{.*}}, [9:1 - 10:1] 'S0'
// CHECK-EXPANDED-NEXT: `-ExtensionBodyScope {{.*}}, [9:14 - 10:1] 'S0'
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [12:1 - 13:1] 'C0'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [12:10 - 13:1] 'C0'
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [15:1 - 18:1] 'E0'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [15:9 - 18:1] 'E0'
// CHECK-EXPANDED-NEXT: |-EnumElementScope {{.*}}, [16:8 - 16:8]
// CHECK-EXPANDED-NEXT: `-EnumElementScope {{.*}}, [17:8 - 17:19]
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [17:10 - 17:19]
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [20:1 - 21:1] 'GenericS0'
// CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [20:17 - 21:1] param 0 'T'
// CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [20:17 - 21:1] param 1 'U'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [20:24 - 21:1] 'GenericS0'
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [23:1 - 24:1] 'genericFunc0(t:u:i:)'
// CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [23:18 - 24:1] param 0 'T'
// CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [23:18 - 24:1] param 1 'U'
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [23:24 - 24:1]
// CHECK-EXPANDED-NEXT: |-DefaultArgumentInitializerScope {{.*}}, [23:46 - 23:46]
// CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [23:50 - 24:1]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [23:50 - 24:1]
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [26:1 - 32:1] 'ContainsGenerics0'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [26:25 - 32:1] 'ContainsGenerics0'
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [27:3 - 28:3] 'init(t:u:)'
// CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [27:7 - 28:3] param 0 'T'
// CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [27:7 - 28:3] param 1 'U'
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [27:13 - 28:3]
// CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [27:26 - 28:3]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [27:26 - 28:3]
// CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [30:3 - 31:3] 'deinit'
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [30:3 - 31:3]
// CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [30:10 - 31:3]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [30:10 - 31:3]
// CHECK-EXPANDED-NEXT: |-TypeAliasDeclScope {{.*}}, [34:1 - 34:32] <no extended nominal?!>
// CHECK-EXPANDED-NEXT: `-GenericParamScope {{.*}}, [34:24 - 34:32] param 0 'T'
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [39:1 - 39:26] 'OtherArchStruct'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [39:24 - 39:26] 'OtherArchStruct'
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [42:1 - 101:1] 'functionBodies1(a:b:)'
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [42:21 - 101:1]
// CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [42:39 - 101:1]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [42:39 - 101:1]
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [43:7 - 43:23] entry 0 'x1' 'x2'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [43:18 - 43:23] entry 0 'x1' 'x2'
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [44:7 - 44:23] entry 1 'y1' 'y2'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [44:18 - 44:23] entry 1 'y1' 'y2'
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [45:7 - 45:23] entry 0 'z1' 'z2'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [45:18 - 45:23] entry 0 'z1' 'z2'
// CHECK-EXPANDED-NEXT: |-BraceStmtScope {{.*}}, [46:6 - 53:3]
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [47:9 - 47:14] entry 0 'a1'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [47:14 - 47:14] entry 0 'a1'
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [48:9 - 48:14] entry 0 'a2'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [48:14 - 48:14] entry 0 'a2'
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [49:8 - 52:5]
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [50:11 - 50:16] entry 0 'b1'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [50:16 - 50:16] entry 0 'b1'
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [51:11 - 51:16] entry 0 'b2'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [51:16 - 51:16] entry 0 'b2'
// CHECK-EXPANDED-NEXT: |-BraceStmtScope {{.*}}, [54:6 - 57:3]
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [55:9 - 55:14] entry 0 'b1'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [55:14 - 55:14] entry 0 'b1'
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [56:9 - 56:14] entry 0 'b2'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [56:14 - 56:14] entry 0 'b2'
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [58:3 - 58:38] 'f(_:)'
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [58:9 - 58:38]
// CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [58:27 - 58:38]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [58:27 - 58:38]
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [59:7 - 59:16] entry 0 'f2'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [59:12 - 59:16] entry 0 'f2'
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [60:3 - 60:15] 'S7'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [60:13 - 60:15] 'S7'
// CHECK-EXPANDED-NEXT: |-TypeAliasDeclScope {{.*}}, [61:3 - 61:23] <no extended nominal?!>
// CHECK-EXPANDED-NEXT: |-IfStmtScope {{.*}}, [63:3 - 67:3]
// CHECK-EXPANDED-NEXT: |-ConditionalClauseScope, [63:6 - 65:3] index 0
// CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [63:18 - 65:3] let b1?
// CHECK-EXPANDED-NEXT: `-ConditionalClauseScope, [63:18 - 65:3] index 1
// CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [63:29 - 65:3] let b2?
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [63:29 - 65:3]
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [64:9 - 64:14] entry 0 'c1'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [64:14 - 64:14] entry 0 'c1'
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [65:10 - 67:3]
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [66:9 - 66:14] entry 0 'c2'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [66:14 - 66:14] entry 0 'c2'
// CHECK-EXPANDED-NEXT: `-GuardStmtScope {{.*}}, [69:3 - 100:38]
// CHECK-EXPANDED-NEXT: |-ConditionalClauseScope, [69:9 - 69:53] index 0
// CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [69:21 - 69:53] let b1?
// CHECK-EXPANDED-NEXT: `-ConditionalClauseScope, [69:21 - 69:53] index 1
// CHECK-EXPANDED-NEXT: |-WholeClosureScope {{.*}}, [69:21 - 69:30]
// CHECK-EXPANDED-NEXT: `-ClosureBodyScope {{.*}}, [69:21 - 69:30]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [69:21 - 69:30]
// CHECK-EXPANDED-NEXT: `-ConditionalClauseScope, [69:37 - 69:53] index 2
// CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [69:53 - 69:53] let b2?
// CHECK-EXPANDED-NEXT: |-BraceStmtScope {{.*}}, [69:53 - 72:3]
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [70:9 - 70:13] entry 0 'c'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [70:13 - 70:13] entry 0 'c'
// CHECK-EXPANDED-NEXT: `-LookupParentDiversionScope, [72:3 - 100:38]
// CHECK-EXPANDED-NEXT: |-WhileStmtScope {{.*}}, [74:3 - 76:3]
// CHECK-EXPANDED-NEXT: `-ConditionalClauseScope, [74:9 - 76:3] index 0
// CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [74:21 - 76:3] let b3?
// CHECK-EXPANDED-NEXT: `-ConditionalClauseScope, [74:21 - 76:3] index 1
// CHECK-EXPANDED-NEXT: `-ConditionalClausePatternUseScope, [74:32 - 76:3] let b4?
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [74:32 - 76:3]
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [75:9 - 75:13] entry 0 'c'
// CHECK-EXPANDED-NEXT: `-PatternEntryInitializerScope {{.*}}, [75:13 - 75:13] entry 0 'c'
// CHECK-EXPANDED-NEXT: |-RepeatWhileScope {{.*}}, [78:3 - 78:20]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [78:10 - 78:12]
// CHECK-EXPANDED-NEXT: |-ForEachStmtScope {{.*}}, [80:3 - 82:3]
// CHECK-EXPANDED-NEXT: `-ForEachPatternScope, [80:52 - 82:3]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [80:63 - 82:3]
// CHECK-EXPANDED-NEXT: |-DoCatchStmtScope {{.*}}, [84:3 - 88:3]
// CHECK-EXPANDED-NEXT: |-BraceStmtScope {{.*}}, [84:6 - 86:3]
// CHECK-EXPANDED-NEXT: |-CatchStmtScope {{.*}}, [86:31 - 87:3]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [86:54 - 87:3]
// CHECK-EXPANDED-NEXT: `-CatchStmtScope {{.*}}, [87:11 - 88:3]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [87:11 - 88:3]
// CHECK-EXPANDED-NEXT: |-SwitchStmtScope {{.*}}, [90:3 - 99:3]
// CHECK-EXPANDED-NEXT: |-CaseStmtScope {{.*}}, [91:29 - 92:10]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [92:5 - 92:10]
// CHECK-EXPANDED-NEXT: |-CaseStmtScope {{.*}}, [95:5 - 95:10]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [95:5 - 95:10]
// CHECK-EXPANDED-NEXT: `-CaseStmtScope {{.*}}, [98:5 - 98:10]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [98:5 - 98:10]
// CHECK-EXPANDED-NEXT: `-ForEachStmtScope {{.*}}, [100:3 - 100:38]
// CHECK-EXPANDED-NEXT: `-ForEachPatternScope, [100:36 - 100:38]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [100:36 - 100:38]
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [103:1 - 103:26] 'throwing()'
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [103:14 - 103:26]
// CHECK-EXPANDED-NEXT: `-PureFunctionBodyScope {{.*}}, [103:24 - 103:26]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [103:24 - 103:26]
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [105:1 - 107:1] 'MyError'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [105:24 - 107:1] 'MyError'
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [106:7 - 106:14] entry 0 'value'
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [109:1 - 113:1] 'MyEnum'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [109:13 - 113:1] 'MyEnum'
// CHECK-EXPANDED-NEXT: |-EnumElementScope {{.*}}, [110:8 - 110:8]
// CHECK-EXPANDED-NEXT: |-EnumElementScope {{.*}}, [111:8 - 111:18]
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [111:14 - 111:18]
// CHECK-EXPANDED-NEXT: `-EnumElementScope {{.*}}, [112:8 - 112:8]
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [115:1 - 131:1] 'StructContainsAbstractStorageDecls'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [115:43 - 131:1] 'StructContainsAbstractStorageDecls'
// CHECK-EXPANDED-NEXT: |-SubscriptDeclScope {{.*}}, [116:3 - 122:3] scope_map.(file).StructContainsAbstractStorageDecls.subscript(_:_:)@SOURCE_DIR{{[/\\]}}test{{[/\\]}}NameBinding{{[/\\]}}scope_map.swift:116:3
// CHECK-EXPANDED-NEXT: `-ParameterListScope {{.*}}, [116:13 - 122:3]
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [117:5 - 118:5] '_'
// CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [117:9 - 118:5]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [117:9 - 118:5]
// CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [119:5 - 121:5] '_'
// CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [119:9 - 121:5]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [119:9 - 121:5]
// CHECK-EXPANDED-NEXT: `-PatternEntryDeclScope {{.*}}, [124:21 - 130:3] entry 0 'computed'
// CHECK-EXPANDED-NEXT: `-VarDeclScope {{.*}}, [124:21 - 130:3] scope_map.(file).StructContainsAbstractStorageDecls.computed@SOURCE_DIR{{[/\\]}}test{{[/\\]}}NameBinding{{[/\\]}}scope_map.swift:124:7
// CHECK-EXPANDED-NEXT: |-AbstractFunctionDeclScope {{.*}}, [125:5 - 127:5] '_'
// CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [125:9 - 127:5]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [125:9 - 127:5]
// CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [128:5 - 129:5] '_'
// CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [128:9 - 129:5]
// CHECK-EXPANDED-NEXT: `-BraceStmtScope {{.*}}, [128:9 - 129:5]
// CHECK-EXPANDED-NEXT: |-NominalTypeDeclScope {{.*}}, [133:1 - 141:1] 'ClassWithComputedProperties'
// CHECK-EXPANDED-NEXT: `-NominalTypeBodyScope {{.*}}, [133:35 - 141:1] 'ClassWithComputedProperties'
// CHECK-EXPANDED-NEXT: |-PatternEntryDeclScope {{.*}}, [134:7 - 136:3] entry 0 'willSetProperty'
// CHECK-EXPANDED-NEXT: |-PatternEntryInitializerScope {{.*}}, [134:30 - 134:30] entry 0 'willSetProperty'
// CHECK-EXPANDED-NEXT: `-VarDeclScope {{.*}}, [134:32 - 136:3] scope_map.(file).ClassWithComputedProperties.willSetProperty@SOURCE_DIR{{[/\\]}}test{{[/\\]}}NameBinding{{[/\\]}}scope_map.swift:134:7
// CHECK-EXPANDED-NEXT: `-AbstractFunctionDeclScope {{.*}}, [135:5 - 135:15] '_'
// CHECK-EXPANDED-NEXT: `-MethodBodyScope {{.*}}, [135:13 - 135:15]
`-BraceStmtScope {{.*}}, [135:13 - 135:15]
`-PatternEntryDeclScope {{.*}}, [138:7 - 140:3] entry 0 'didSetProperty'
|-PatternEntryInitializerScope {{.*}}, [138:29 - 138:29] entry 0 'didSetProperty'
`-VarDeclScope {{.*}}, [138:31 - 140:3] scope_map.(file).ClassWithComputedProperties.didSetProperty@SOURCE_DIR/test/NameBinding/scope_map.swift:138:7
`-AbstractFunctionDeclScope {{.*}}, [139:5 - 139:14] '_'
`-MethodBodyScope {{.*}}, [139:12 - 139:14]
`-BraceStmtScope {{.*}}, [139:12 - 139:14]
|-AbstractFunctionDeclScope {{.*}}, [143:1 - 156:1] 'funcWithComputedProperties(i:)'
`-ParameterListScope {{.*}}, [143:32 - 156:1]
`-PureFunctionBodyScope {{.*}}, [143:41 - 156:1]
`-BraceStmtScope {{.*}}, [143:41 - 156:1]
|-PatternEntryDeclScope {{.*}}, [144:21 - 150:3] entry 0 'computed'
`-VarDeclScope {{.*}}, [144:21 - 150:3] scope_map.(file).funcWithComputedProperties(i:).computed@SOURCE_DIR/test/NameBinding/scope_map.swift:144:7
|-AbstractFunctionDeclScope {{.*}}, [145:5 - 146:5] '_'
`-PureFunctionBodyScope {{.*}}, [145:9 - 146:5]
`-BraceStmtScope {{.*}}, [145:9 - 146:5]
`-AbstractFunctionDeclScope {{.*}}, [147:5 - 149:5] '_'
`-PureFunctionBodyScope {{.*}}, [147:9 - 149:5]
`-BraceStmtScope {{.*}}, [147:9 - 149:5]
|-PatternEntryDeclScope {{.*}}, [150:6 - 150:36] entry 1 'stored1' 'stored2'
`-PatternEntryInitializerScope {{.*}}, [150:31 - 150:36] entry 1 'stored1' 'stored2'
|-PatternEntryDeclScope {{.*}}, [151:25 - 153:3] entry 2 'alsoComputed'
`-VarDeclScope {{.*}}, [151:25 - 153:3] scope_map.(file).funcWithComputedProperties(i:).alsoComputed@SOURCE_DIR/test/NameBinding/scope_map.swift:151:7
`-AbstractFunctionDeclScope {{.*}}, [151:25 - 153:3] '_'
`-PureFunctionBodyScope {{.*}}, [151:25 - 153:3]
`-BraceStmtScope {{.*}}, [151:25 - 153:3]
`-BraceStmtScope {{.*}}, [155:6 - 155:8]
|-AbstractFunctionDeclScope {{.*}}, [158:1 - 163:1] 'closures()'
`-ParameterListScope {{.*}}, [158:14 - 163:1]
`-PureFunctionBodyScope {{.*}}, [158:17 - 163:1]
`-BraceStmtScope {{.*}}, [158:17 - 163:1]
|-WholeClosureScope {{.*}}, [159:3 - 161:3]
`-ClosureParametersScope {{.*}}, [159:5 - 161:3]
`-ClosureBodyScope {{.*}}, [159:10 - 161:3]
`-BraceStmtScope {{.*}}, [159:10 - 161:3]
`-WholeClosureScope {{.*}}, [160:12 - 160:22]
`-ClosureBodyScope {{.*}}, [160:12 - 160:22]
`-BraceStmtScope {{.*}}, [160:12 - 160:22]
`-WholeClosureScope {{.*}}, [162:3 - 162:19]
`-ClosureParametersScope {{.*}}, [162:5 - 162:19]
`-ClosureBodyScope {{.*}}, [162:10 - 162:19]
`-BraceStmtScope {{.*}}, [162:10 - 162:19]
`-TopLevelCodeScope {{.*}}, [165:1 - 195:1]
`-BraceStmtScope {{.*}}, [165:1 - 195:1]
|-WholeClosureScope {{.*}}, [165:1 - 165:14]
`-ClosureBodyScope {{.*}}, [165:1 - 165:14]
`-BraceStmtScope {{.*}}, [165:1 - 165:14]
|-AbstractFunctionDeclScope {{.*}}, [167:1 - 176:1] 'defaultArguments(i:j:)'
`-ParameterListScope {{.*}}, [167:22 - 176:1]
|-DefaultArgumentInitializerScope {{.*}}, [167:32 - 167:32]
|-DefaultArgumentInitializerScope {{.*}}, [168:32 - 168:48]
`-WholeClosureScope {{.*}}, [168:32 - 168:42]
`-ClosureBodyScope {{.*}}, [168:32 - 168:42]
`-BraceStmtScope {{.*}}, [168:32 - 168:42]
`-PureFunctionBodyScope {{.*}}, [168:51 - 176:1]
`-BraceStmtScope {{.*}}, [168:51 - 176:1]
|-AbstractFunctionDeclScope {{.*}}, [170:3 - 172:3] 'localWithDefaults(i:j:)'
`-ParameterListScope {{.*}}, [170:25 - 172:3]
|-DefaultArgumentInitializerScope {{.*}}, [170:35 - 170:35]
|-DefaultArgumentInitializerScope {{.*}}, [171:35 - 171:51]
`-WholeClosureScope {{.*}}, [171:35 - 171:45]
`-ClosureBodyScope {{.*}}, [171:35 - 171:45]
`-BraceStmtScope {{.*}}, [171:35 - 171:45]
`-PureFunctionBodyScope {{.*}}, [171:54 - 172:3]
`-BraceStmtScope {{.*}}, [171:54 - 172:3]
`-PatternEntryDeclScope {{.*}}, [174:7 - 175:11] entry 0 'a'
`-PatternEntryInitializerScope {{.*}}, [174:11 - 175:11] entry 0 'a'
`-WholeClosureScope {{.*}}, [175:3 - 175:8]
`-ClosureBodyScope {{.*}}, [175:3 - 175:8]
`-BraceStmtScope {{.*}}, [175:3 - 175:8]
|-NominalTypeDeclScope {{.*}}, [178:1 - 181:1] 'PatternInitializers'
`-NominalTypeBodyScope {{.*}}, [178:28 - 181:1] 'PatternInitializers'
|-PatternEntryDeclScope {{.*}}, [179:7 - 179:21] entry 0 'a' 'b'
`-PatternEntryInitializerScope {{.*}}, [179:16 - 179:21] entry 0 'a' 'b'
`-PatternEntryDeclScope {{.*}}, [180:7 - 180:25] entry 1 'c' 'd'
`-PatternEntryInitializerScope {{.*}}, [180:16 - 180:25] entry 1 'c' 'd'
|-NominalTypeDeclScope {{.*}}, [183:1 - 185:1] 'ProtoWithSubscript'
`-GenericParamScope {{.*}}, [183:29 - 185:1] param 0 'Self : ProtoWithSubscript'
`-NominalTypeBodyScope {{.*}}, [183:29 - 185:1] 'ProtoWithSubscript'
`-SubscriptDeclScope {{.*}}, [184:3 - 184:43] scope_map.(file).ProtoWithSubscript.subscript(_:)@SOURCE_DIR/test/NameBinding/scope_map.swift:184:3
`-ParameterListScope {{.*}}, [184:12 - 184:43]
|-AbstractFunctionDeclScope {{.*}}, [184:35 - 184:35] '_'
`-AbstractFunctionDeclScope {{.*}}, [184:39 - 184:39] '_'
|-AbstractFunctionDeclScope {{.*}}, [187:1 - 189:1] 'localPatternsWithSharedType()'
`-ParameterListScope {{.*}}, [187:33 - 189:1]
`-PureFunctionBodyScope {{.*}}, [187:36 - 189:1]
`-BraceStmtScope {{.*}}, [187:36 - 189:1]
|-PatternEntryDeclScope {{.*}}, [188:7 - 188:7] entry 0 'i'
|-PatternEntryDeclScope {{.*}}, [188:10 - 188:10] entry 1 'j'
`-PatternEntryDeclScope {{.*}}, [188:13 - 188:16] entry 2 'k'
`-NominalTypeDeclScope {{.*}}, [191:1 - 195:1] 'LazyProperties'
`-NominalTypeBodyScope {{.*}}, [191:22 - 195:1] 'LazyProperties'
|-PatternEntryDeclScope {{.*}}, [192:7 - 192:20] entry 0 'value'
`-PatternEntryInitializerScope {{.*}}, [192:20 - 192:20] entry 0 'value'
`-PatternEntryDeclScope {{.*}}, [194:12 - 194:29] entry 0 'prop'
`-PatternEntryInitializerScope {{.*}}, [194:24 - 194:29] entry 0 'prop'
// RUN: not %target-swift-frontend -dump-scope-maps 71:8,27:20,6:18,167:32,180:18,194:26 %s 2> %t.searches
// RUN: %FileCheck -check-prefix CHECK-SEARCHES %s < %t.searches
// CHECK-SEARCHES: ***Scope at 71:8***
// CHECK-SEARCHES-NEXT: BraceStmtScope {{.*}}, [69:53 - 72:3]
// CHECK-SEARCHES-NEXT: Local bindings: c
// CHECK-SEARCHES-NEXT: ***Scope at 27:20***
// CHECK-SEARCHES-NEXT: ParameterListScope {{.*}}, [27:13 - 28:3]
// CHECK-SEARCHES-NEXT: ***Scope at 6:18***
// CHECK-SEARCHES-NEXT: NominalTypeBodyScope {{.*}}, [6:17 - 6:19] 'InnerC0'
// CHECK-SEARCHES-NEXT: {{.*}} Module name=scope_map
// CHECK-SEARCHES-NEXT: {{.*}} FileUnit file="SOURCE_DIR{{[/|\\]}}test{{[/|\\]}}NameBinding{{[/|\\]}}scope_map.swift"
// CHECK-SEARCHES-NEXT: {{.*}} StructDecl name=S0
// CHECK-SEARCHES-NEXT: {{.*}} ClassDecl name=InnerC0
// CHECK-SEARCHES-NEXT: ***Scope at 167:32***
// CHECK-SEARCHES-NEXT: DefaultArgumentInitializerScope {{.*}}, [167:32 - 167:32]
// CHECK-SEARCHES-NEXT: {{.*}} Module name=scope_map
// CHECK-SEARCHES-NEXT: {{.*}} FileUnit file="SOURCE_DIR{{[/|\\]}}test{{[/|\\]}}NameBinding{{[/|\\]}}scope_map.swift"
// CHECK-SEARCHES-NEXT: {{.*}} AbstractFunctionDecl name=defaultArguments(i:j:) : (Int, Int) -> ()
// CHECK-SEARCHES-NEXT: {{.*}} Initializer DefaultArgument index=0
// CHECK-SEARCHES-NEXT: ***Scope at 180:18***
// CHECK-SEARCHES-NEXT: PatternEntryInitializerScope {{.*}}, [180:16 - 180:25] entry 1 'c' 'd'
// CHECK-SEARCHES-NEXT: {{.*}} Module name=scope_map
// CHECK-SEARCHES-NEXT: {{.*}} FileUnit file="SOURCE_DIR{{[/|\\]}}test{{[/|\\]}}NameBinding{{[/|\\]}}scope_map.swift"
// CHECK-SEARCHES-NEXT: {{.*}} StructDecl name=PatternInitializers
// CHECK-SEARCHES-NEXT: {{.*}} Initializer PatternBinding {{.*}} #1
// CHECK-SEARCHES-NEXT: ***Scope at 194:26***
// CHECK-SEARCHES-NEXT: PatternEntryInitializerScope {{.*}}, [194:24 - 194:29] entry 0 'prop'
// CHECK-SEARCHES-NEXT: {{.*}} Module name=scope_map
// CHECK-SEARCHES-NEXT: {{.*}} FileUnit file="SOURCE_DIR{{[/|\\]}}test{{[/|\\]}}NameBinding{{[/|\\]}}scope_map.swift"
// CHECK-SEARCHES-NEXT: {{.*}} ClassDecl name=LazyProperties
// CHECK-SEARCHES-NEXT: {{.*}} Initializer PatternBinding {{.*}} #0
// CHECK-SEARCHES-NEXT: Local bindings: self
// CHECK-SEARCHES-NOT: ***Complete scope map***
// REQUIRES: asserts
// absence of assertions can change the "uncached" bit and cause failures
| apache-2.0 | 2206e0ccbcaff7f5b0fb99e1104d2e74 | 51.594488 | 214 | 0.56505 | 3.602751 | false | false | false | false |
austinzmchen/guildOfWarWorldBosses | GoWWorldBosses/ViewControllers/Storage/WBStorageGeneralTableViewController.swift | 1 | 2901 | //
// WBStorageGeneralTableViewController.swift
// GoWWorldBosses
//
// Created by Austin Chen on 2016-11-28.
// Copyright © 2016 Austin Chen. All rights reserved.
//
import UIKit
import RealmSwift
import SDWebImage
class WBStorageGeneralTableViewController: UITableViewController {
@IBAction func unwindActionFromItemDetail(unwindSegue: UIStoryboardSegue) {}
var viewModel: WBStorageTableViewModelType? {
didSet {
viewModel?.delegate = self
}
}
let apiErrorView = WBApiErrorView()
override func viewDidLoad() {
super.viewDidLoad()
// set up api Error view
self.view.addSubview(self.apiErrorView)
self.apiErrorView.isHidden = true
var f = self.apiErrorView.frame
f = self.view.bounds
self.apiErrorView.frame = f
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "pushFromStorageTableVCToDetailVC",
let cell = sender as? UITableViewCell,
let indexPath = tableView.indexPath(for: cell),
let items = self.viewModel?.items
{
if let vc = segue.destination as? WBStorageDetailViewController {
vc.item = items[indexPath.row]
} else if let vc = segue.destination as? WBStorageMaterialDetailViewController {
vc.item = items[indexPath.row]
} else if let vc = segue.destination as? WBStorageWalletDetailViewController {
vc.item = items[indexPath.row]
}
}
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.viewModel?.items?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: self.viewModel!.identifierForSuitableCell(atIndex: indexPath.row),
for: indexPath) as! WBStorageItemTableViewCell
if (indexPath.row % 2) > 0 {
// odd number
cell.contentView.backgroundColor = UIColor(red: 10/255.0, green: 10/255.0, blue: 10/255.0, alpha: 1)
} else {
// even number
cell.contentView.backgroundColor = UIColor.black
}
return cell
}
}
extension WBStorageGeneralTableViewController: WBStorageTableViewModelDelegate {
func didComplete(success: Bool, items: [Any]?, error: Error?) {
guard let e = error as? WBRemoteError else {
return
}
switch e {
case .scopePermissionDenied:
self.apiErrorView.isHidden = false
default:
self.apiErrorView.isHidden = true
}
}
}
| mit | 810e0b55364b07a665a92c6a72bb1b45 | 32.333333 | 131 | 0.618621 | 4.931973 | false | false | false | false |
dipen30/Qmote | KodiRemote/Pods/UPnAtom/Source/UPnAtom.swift | 1 | 3693 | //
// UPnAtom.swift
//
// Copyright (c) 2015 David Robles
//
// 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
/// TODO: For now rooting to NSObject to expose to Objective-C, see Github issue #16
open class UPnAtom: NSObject {
// public
open static let sharedInstance = UPnAtom()
open let upnpRegistry: UPnPRegistry
open var ssdpTypes: Set<String> {
get { return ssdpDiscoveryAdapter.rawSSDPTypes }
set { ssdpDiscoveryAdapter.rawSSDPTypes = newValue }
}
// internal
unowned let ssdpDiscoveryAdapter: SSDPDiscoveryAdapter
override init() {
// configure discovery adapter
let adapterClass = UPnAtom.ssdpDiscoveryAdapterClass()
let adapter = adapterClass.init()
ssdpDiscoveryAdapter = adapter
// configure UPNP registry
upnpRegistry = UPnPRegistry(ssdpDiscoveryAdapter: ssdpDiscoveryAdapter)
for (upnpClass, urn) in UPnAtom.upnpClasses() {
self.upnpRegistry.register(upnpClass: upnpClass, forURN: urn)
}
}
deinit {
ssdpDiscoveryAdapter.stop()
}
open func ssdpDiscoveryRunning() -> Bool {
return ssdpDiscoveryAdapter.running
}
open func startSSDPDiscovery() {
ssdpDiscoveryAdapter.start()
}
open func stopSSDPDiscovery() {
ssdpDiscoveryAdapter.stop()
}
open func restartSSDPDiscovery() {
ssdpDiscoveryAdapter.restart()
}
/// Override to use a different SSDP adapter if another SSDP system is preferred over CocoaSSDP
class func ssdpDiscoveryAdapterClass() -> AbstractSSDPDiscoveryAdapter.Type {
return SSDPExplorerDiscoveryAdapter.self
}
/// Override to use a different default set of UPnP classes. Alternatively, registrations can be replaced, see UPnAtom.upnpRegistry.register()
class func upnpClasses() -> [(upnpClass: AbstractUPnP.Type, forURN: String)] {
return [
(upnpClass: MediaRenderer1Device.self, forURN: "urn:schemas-upnp-org:device:MediaRenderer:1"),
(upnpClass: MediaServer1Device.self, forURN: "urn:schemas-upnp-org:device:MediaServer:1"),
(upnpClass: AVTransport1Service.self, forURN: "urn:schemas-upnp-org:service:AVTransport:1"),
(upnpClass: ConnectionManager1Service.self, forURN: "urn:schemas-upnp-org:service:ConnectionManager:1"),
(upnpClass: ContentDirectory1Service.self, forURN: "urn:schemas-upnp-org:service:ContentDirectory:1"),
(upnpClass: RenderingControl1Service.self, forURN: "urn:schemas-upnp-org:service:RenderingControl:1")
]
}
}
| apache-2.0 | 795f09d821b6b2594e22f456d33566d2 | 40.965909 | 146 | 0.703222 | 4.076159 | false | false | false | false |
steveholt55/metro | iOS/MetroTransitUITests/XCTest+Wait.swift | 1 | 685 | //
// Copyright © 2016 Brandon Jenniges. All rights reserved.
//
import XCTest
extension XCTestCase {
func waitForElementToAppear(element: XCUIElement, file: String = __FILE__, line: UInt = __LINE__) {
let existsPredicate = NSPredicate(format: "exists == true")
expectationForPredicate(existsPredicate, evaluatedWithObject: element, handler: nil)
waitForExpectationsWithTimeout(5) { (error) -> Void in
if (error != nil) {
let message = "Failed to find \(element) after 5 seconds."
self.recordFailureWithDescription(message, inFile: file, atLine: line, expected: true)
}
}
}
}
| mit | 72809b5d3a707c9289013fc73c68cc40 | 35 | 103 | 0.628655 | 4.783217 | false | true | false | false |
aranasaurus/ratings-app | mobile/LikeLike/Modules/ItemsList/ItemDataSource.swift | 1 | 962 | //
// ItemDataSource.swift
// LikeLike
//
// Created by Ryan Arana on 11/11/17.
// Copyright © 2017 aranasaurus. All rights reserved.
//
import Foundation
protocol ItemDataSource {
var itemCount: Int { get }
func item(at indexPath: IndexPath) -> Item
func reloadData()
}
final class DataStoreItemDataSource {
private let dataStore: DataStore
private let sort: (Item, Item) -> Bool
private var ids: [String] = []
init(dataStore: DataStore, sort: @escaping (Item, Item) -> Bool = { $0.title < $1.title }) {
self.dataStore = dataStore
self.sort = sort
reloadData()
}
}
extension DataStoreItemDataSource: ItemDataSource {
var itemCount: Int {
return ids.count
}
func item(at indexPath: IndexPath) -> Item {
return dataStore.getItem(id: ids[indexPath.row])!
}
func reloadData() {
self.ids = dataStore.getAllItems().sorted(by: sort).map { $0.id }
}
}
| mit | c6ad97bb0897416b69fb42d95b84e2f2 | 21.880952 | 96 | 0.633715 | 3.828685 | false | false | false | false |
jslim89/maplot-ios | Maplot/Utilities/JSLocationManager.swift | 1 | 3605 | //
// JSLocationManager.swift
// Maplot
//
// Created by Jeong Sheng Lim on 9/5/15.
// Copyright © 2015 Js Lim. All rights reserved.
//
import CoreLocation
private let _JSLocationManagerSharedInstance = JSLocationManager()
class JSLocationManager: NSObject, CLLocationManagerDelegate {
private var locationManager: CLLocationManager!
var location: CLLocation!
override init() {
super.init()
updateLocationToDefault()
}
func startLocationManager() {
if CLLocationManager.locationServicesEnabled() {
locationManager = CLLocationManager()
if locationManager.respondsToSelector(Selector("requestWhenInUseAuthorization")) {
locationManager.requestWhenInUseAuthorization()
}
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
}
private func stopLocationManager() {
locationManager.stopUpdatingLocation()
locationManager.delegate = nil
locationManager = nil
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
updateLocationToDefault()
stopLocationManager()
}
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
if (newLocation.timestamp.timeIntervalSinceNow < -5.0) {
return;
}
if (newLocation.horizontalAccuracy < 0) {
return;
}
var distance = Double(MAXFLOAT) as CLLocationDistance
if (location != nil) {
distance = newLocation.distanceFromLocation(location)
}
location = newLocation;
if (location == nil || location.horizontalAccuracy > newLocation.horizontalAccuracy) {
if (newLocation.horizontalAccuracy <= self.locationManager.desiredAccuracy) {
stopLocationManager()
saveLastLocation()
}
} else if (distance < 1.0) {
stopLocationManager()
saveLastLocation()
}
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if (status == .NotDetermined) {
if (locationManager.respondsToSelector("requestWhenInUseAuthorization")) {
locationManager.requestWhenInUseAuthorization()
}
} else if (status == .AuthorizedWhenInUse) {
locationManager.startUpdatingLocation()
}
}
private func updateLocationToDefault() {
let defaults = NSUserDefaults.standardUserDefaults()
if let lastLocation = defaults.objectForKey("JSLastLocation") as? NSDictionary {
location = CLLocation(latitude: (lastLocation["lat"] as! NSNumber).doubleValue, longitude: (lastLocation["lng"] as! NSNumber).doubleValue)
return
}
location = CLLocation(latitude: 0, longitude: 0)
}
private func saveLastLocation() {
if (location == nil) { return }
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(["lat": location.coordinate.latitude, "lng": location.coordinate.longitude], forKey: "JSLastLocation")
defaults.synchronize()
}
class var sharedInstance: JSLocationManager {
return _JSLocationManagerSharedInstance
}
}
| gpl-3.0 | fe33d8629732447463a6a96e45f13f98 | 33 | 150 | 0.637625 | 6.203098 | false | false | false | false |
segmentio/analytics-ios | Examples/FullExampleFlowCatalyst/Analytics Example/Controllers/SignupViewController.swift | 2 | 2461 | //
// SignupViewController.swift
// Analytics Example
//
// Created by Cody Garvin on 6/9/20.
// Copyright © 2020 Cody Garvin. All rights reserved.
//
import UIKit
import Analytics
class SignupViewController: StepsViewController {
private var continueButton: UIButton!
private var trackButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
descriptionString = "Login with details using identify"
codeString = """
// Start with the analytics singleton
let analytics = Analytics.shared()
// Screen
analytics.screen("Signup")
// create user
analytics.track("Create Account", properties: ["Signed Up": ...])
// Alias new user id with anonymous id
analytics.alias("AA-BB-CC-NEW-ID")
// Start trial
analytics.track("Trial Started", properties: ...)
"""
// Add the button
let createButton = UIButton.SegmentButton("Create Account", target: self, action: #selector(createUser(_:)))
trackButton = UIButton.SegmentButton("Start Trial", target: self, action: #selector(trackUser(_:)))
trackButton.isEnabled = false
continueButton = UIButton.SegmentButton("Continue", target: self, action: #selector(continueToNext(_:)))
continueButton.isEnabled = false
propertyViews = [createButton, UIView.separator(), trackButton, UIView.separator(), continueButton, UIView.separator()]
// Fire off the beginning analytics
startAnalytics()
}
private
func startAnalytics() {
let analytics = Analytics.shared()
// identify screen load
analytics.screen("Signup")
}
@objc
func createUser(_ sender: Any) {
let analytics = Analytics.shared()
// track CTA tap
analytics.track("Create Account", properties: ["Signed Up": ["first": "Peter", "last": "Gibbons", "phone": "pgibbons"]])
analytics.alias("AA-BB-CC-NEW-ID")
trackButton.isEnabled = true
}
@objc func trackUser(_ sender: Any) {
let analytics = Analytics.shared()
// track user
analytics.track("Trial Started", properties: ["start_date": "2018-08-27"])
continueButton.isEnabled = true
}
@objc
func continueToNext(_ sender: Any) {
let invite = InviteViewController(nibName: nil, bundle: nil)
navigationController?.pushViewController(invite, animated: true)
}
}
| mit | 865640babdceb06775ad464735111feb | 29.37037 | 128 | 0.639431 | 4.615385 | false | false | false | false |
Daij-Djan/CoprightModifier | CopyrightModifier/FileWriter.swift | 1 | 3506 | //
// Writer.swift
// CoprightModifier
//
// Created by Dominik Pich on 22/11/14.
// Copyright (c) 2014 Dominik Pich. All rights reserved.
//
import Cocoa
import ZipArchive
fileprivate let backupZipName = "_CRMBackup.zip"
class FileWriter {
//operations
var shouldDoBackup = false
//MARK: private helpers
fileprivate var cancelWriting = false
fileprivate lazy var writerQueue: DispatchQueue = {
return DispatchQueue(label: "writer", attributes: [])
}()
//MARK: processing
func write(_ fileContents: Array<FileContent>, shouldDoBackupToFolder: URL?, progressHandler: @escaping (URL) -> Void, completionHandler: @escaping (Bool, Array<(URL)>, NSError?) -> Void) {
self.writerQueue.async {
var writtenFiles = Array<(URL)>()
//zip all existing
var ok = true
if let folder = shouldDoBackupToFolder {
let path = folder.appendingPathComponent(backupZipName).path
let maybeContentPaths = fileContents.map({ (fileContent) -> String in
fileContent.url.path
})
let contentPaths = maybeContentPaths.filter({ (path) -> Bool in
return FileManager.default.fileExists(atPath: path)
})
ok = SSZipArchive.createZipFile(atPath: path, withFilesAtPaths: contentPaths as [Any])
}
//write it out
var br = ok
var error:NSError?
if(ok) {
let result = self.write(fileContents, writtenFiles:&writtenFiles, progressHandler: progressHandler)
br = result.0
error = result.1
}
//fix error if needed
if(error == nil) {
error = NSError(domain: "CopyRightWriter", code: 0, userInfo: [NSLocalizedDescriptionKey:"unkown error"])
}
//report success | callback on main thread
DispatchQueue.main.async {
completionHandler(br, writtenFiles, self.cancelWriting ? nil : error)
}
}
}
func cancelAllProcessing(_ completionHandler: @escaping () -> Void) {
cancelWriting = true
self.writerQueue.async(execute: { () -> Void in
DispatchQueue.main.async(execute: { () -> Void in
self.cancelWriting = false
completionHandler()
})
})
}
//MARK: -
fileprivate func write(_ fileContents: Array<FileContent>, writtenFiles: inout Array<(URL)>, progressHandler: @escaping (URL) -> Void) -> (Bool, NSError?) {
for content in fileContents {
if(self.cancelWriting) {
return (false, nil)
}
//notify UI
DispatchQueue.main.async(execute: { () -> Void in
progressHandler(content.url as URL)
})
//write it
do {
try content.content.write(to: content.url as URL, atomically: false, encoding: String.Encoding.utf8)
}
catch let e as NSError {
return (false, NSError(domain: "CopyRightWriter", code: 21, userInfo: [NSLocalizedDescriptionKey:"error writing file content to disk for \(content.url): \(e)"]))
}
writtenFiles.append(content.url as (URL))
}
return (true, nil)
}
}
| gpl-2.0 | 18b203df2cabab69f626d083ddc3c914 | 34.06 | 193 | 0.553052 | 4.924157 | false | false | false | false |
alessandrostone/Rachmaninoff | Note.swift | 1 | 10370 | // The MIT License (MIT)
//
// Copyright (c) 2015 Rudolf Adamkovič
//
// 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
// MARK: Note
enum NoteName: String {
case C = "C"
case D = "D"
case E = "E"
case F = "F"
case G = "G"
case A = "A"
case B = "B"
}
struct Note {
let name: NoteName
let octave: Int
let sharp: Bool
init(name: NoteName, octave: Int, sharp: Bool) {
assert((-1...9).contains(octave))
assert(name != .E || sharp == false)
assert(name != .B || sharp == false)
self.name = name
self.octave = octave
self.sharp = sharp
}
var stringValue: String {
return ""
+ name.rawValue
+ (sharp ? "♯" : "")
+ ["₋₁", "₀", "₁", "₂", "₃", "₄", "₅", "₆", "₇", "₈", "₉"][octave + 1]
}
}
extension Note: Hashable {
var hashValue: Int {
return stringValue.hashValue
}
}
func ==(lhs: Note, rhs: Note) -> Bool {
return lhs.stringValue == rhs.stringValue
}
extension Note: CustomStringConvertible {
var description: String {
return stringValue
}
}
// MARK: Octave
extension Note {
static func notesInOctave(octave: Int) -> [Note] {
return [
Note(name: .C, octave: octave, sharp: false),
Note(name: .C, octave: octave, sharp: true),
Note(name: .D, octave: octave, sharp: false),
Note(name: .D, octave: octave, sharp: true),
Note(name: .E, octave: octave, sharp: false),
Note(name: .F, octave: octave, sharp: false),
Note(name: .F, octave: octave, sharp: true),
Note(name: .G, octave: octave, sharp: false),
Note(name: .G, octave: octave, sharp: true),
Note(name: .A, octave: octave, sharp: false),
Note(name: .A, octave: octave, sharp: true),
Note(name: .B, octave: octave, sharp: false)
]
}
}
// MARK: Chord
extension Note {
static let notesPerChord = 3
var majorChord: [Note] {
let majorChord: [Note]
switch (name, sharp) {
case (.C, false):
majorChord = [
Note(name: .C, octave: octave, sharp: false),
Note(name: .E, octave: octave, sharp: false),
Note(name: .G, octave: octave, sharp: false)
]
case (.C, true):
majorChord = [
Note(name: .C, octave: octave, sharp: true),
Note(name: .F, octave: octave, sharp: false),
Note(name: .G, octave: octave, sharp: true)
]
case (.D, false):
majorChord = [
Note(name: .D, octave: octave, sharp: false),
Note(name: .F, octave: octave, sharp: true),
Note(name: .A, octave: octave, sharp: false)
]
case (.D, true):
majorChord = [
Note(name: .D, octave: octave, sharp: true),
Note(name: .G, octave: octave, sharp: false),
Note(name: .A, octave: octave, sharp: true)
]
case (.E, _):
majorChord = [
Note(name: .E, octave: octave, sharp: false),
Note(name: .G, octave: octave, sharp: true),
Note(name: .B, octave: octave, sharp: false)
]
case (.F, false):
majorChord = [
Note(name: .F, octave: octave, sharp: false),
Note(name: .A, octave: octave, sharp: false),
Note(name: .C, octave: octave + 1, sharp: false)
]
case (.F, true):
majorChord = [
Note(name: .F, octave: octave, sharp: true),
Note(name: .A, octave: octave, sharp: true),
Note(name: .C, octave: octave + 1, sharp: true)
]
case (.G, false):
majorChord = [
Note(name: .G, octave: octave, sharp: false),
Note(name: .B, octave: octave, sharp: false),
Note(name: .D, octave: octave + 1, sharp: false)
]
case (.G, true):
majorChord = [
Note(name: .G, octave: octave, sharp: true),
Note(name: .C, octave: octave + 1, sharp: false),
Note(name: .D, octave: octave + 1, sharp: true)
]
case (.A, false):
majorChord = [
Note(name: .A, octave: octave, sharp: false),
Note(name: .C, octave: octave + 1, sharp: true),
Note(name: .E, octave: octave + 1, sharp: false)
]
case (.A, true):
majorChord = [
Note(name: .A, octave: octave, sharp: true),
Note(name: .D, octave: octave + 1, sharp: false),
Note(name: .F, octave: octave + 1, sharp: false)
]
case (.B, false):
majorChord = [
Note(name: .B, octave: octave, sharp: false),
Note(name: .D, octave: octave + 1, sharp: true),
Note(name: .F, octave: octave + 1, sharp: true)
]
default:
preconditionFailure()
}
return majorChord
}
}
// MARK: Chord Progression
extension Note {
static let chordsPerProgression = 3
var chordProgression: [Note] {
let chordProgression: [Note]
switch (name, sharp) {
case (.C, false):
chordProgression = [
Note(name: .C, octave: octave, sharp: false),
Note(name: .F, octave: octave, sharp: false),
Note(name: .G, octave: octave, sharp: false)
]
case (.C, true):
chordProgression = [
Note(name: .C, octave: octave, sharp: true),
Note(name: .F, octave: octave, sharp: true),
Note(name: .G, octave: octave, sharp: true)
]
case (.D, false):
chordProgression = [
Note(name: .D, octave: octave, sharp: false),
Note(name: .G, octave: octave, sharp: false),
Note(name: .A, octave: octave, sharp: false)
]
case (.D, true):
chordProgression = [
Note(name: .D, octave: octave, sharp: true),
Note(name: .G, octave: octave, sharp: true),
Note(name: .A, octave: octave, sharp: true)
]
case (.E, _):
chordProgression = [
Note(name: .E, octave: octave, sharp: false),
Note(name: .A, octave: octave, sharp: false),
Note(name: .B, octave: octave, sharp: false)
]
case (.F, false):
chordProgression = [
Note(name: .F, octave: octave, sharp: false),
Note(name: .A, octave: octave, sharp: true),
Note(name: .C, octave: octave + 1, sharp: false)
]
case (.F, true):
chordProgression = [
Note(name: .F, octave: octave, sharp: true),
Note(name: .B, octave: octave, sharp: false),
Note(name: .C, octave: octave + 1, sharp: true)
]
case (.G, false):
chordProgression = [
Note(name: .G, octave: octave, sharp: false),
Note(name: .C, octave: octave + 1, sharp: false),
Note(name: .D, octave: octave + 1, sharp: false)
]
case (.G, true):
chordProgression = [
Note(name: .G, octave: octave, sharp: true),
Note(name: .C, octave: octave + 1, sharp: true),
Note(name: .D, octave: octave + 1, sharp: true)
]
case (.A, false):
chordProgression = [
Note(name: .A, octave: octave, sharp: false),
Note(name: .D, octave: octave + 1, sharp: false),
Note(name: .E, octave: octave + 1, sharp: false)
]
case (.A, true):
chordProgression = [
Note(name: .A, octave: octave, sharp: true),
Note(name: .D, octave: octave + 1, sharp: true),
Note(name: .F, octave: octave + 1, sharp: false)
]
case (.B, _):
chordProgression = [
Note(name: .B, octave: octave, sharp: false),
Note(name: .E, octave: octave + 1, sharp: false),
Note(name: .F, octave: octave + 1, sharp: true)
]
default:
preconditionFailure()
}
return chordProgression
}
}
| mit | 6c9bef080c859e1ee587f8e7f4d5bfa1 | 29.967066 | 82 | 0.47259 | 4.218189 | false | false | false | false |
DigitalForms/CCValidator | CCValidator/Classes/CCValidator.swift | 1 | 13538 | //
// CreditCardsValidator.swift
// Pods
//
// Created by Mariusz Wisniewski on 17.02.2017.
// Digital Forms
//
import Foundation
/// `CreditCardType` is the credit card type name, used to name specific
/// real-life card type
@objc public enum CreditCardType: Int {
case AmericanExpress
case Dankort
case DinersClub
case Discover
case JCB
case Maestro
case MasterCard
case UnionPay
case VisaElectron
case Visa
case NotRecognized
}
/// Specific instance of CCValidator, that validates credit card type with given
/// set of prefixes and card number lengths
public class CCValidator: NSObject {
/// Array of prefixes describing credit card type. E.g. Visa prefix is just number `4`
/// and the prefix is of length 1 (i.e. we check only first digit when
/// looking for prefix)
public let prefixes: [CreditCardPrefix]
/// Array of possible lengths of a credit card type. E.g. Visa can have 13,
/// 16 or 19 digits, whereas MasterCard can be only 16 digits.
public let lengths: [Int]
/// Initialize new CCValidator instance with given set of prefixes and
/// card lengths
///
/// - Parameters:
/// - prefixes: Array of prefixes describing given card type
/// - lengths: Array of lengths describing given card type
public init(prefixes: [CreditCardPrefix], lengths: [Int]) {
self.prefixes = prefixes
self.lengths = lengths
}
/// Initialize new CCValidator instance with given credit card type.
/// We recommend you use this class, as this way you won't have to know
/// the specification details for supported credit card types.
///
/// - Parameter type: Credit Card Type. Passing `.NotRecognized` will not
/// throw an error, but will create a validator
/// with empty arrays of prefixes and lengths
public convenience init(type: CreditCardType) {
// default specs
var specs: (prefixes: [CreditCardPrefix], lengths:[Int]) = ([], [])
switch type {
case .AmericanExpress:
specs = CCValidator.americanExpressSpecs()
case .Dankort:
specs = CCValidator.dankortSpecs()
case .DinersClub:
specs = CCValidator.dinersClubSpecs()
case .Discover:
specs = CCValidator.discoverSpecs()
case .JCB:
specs = CCValidator.jcbSpecs()
case .Maestro:
specs = CCValidator.maestroSpecs()
case .MasterCard:
specs = CCValidator.masterCardSpecs()
case .UnionPay:
specs = CCValidator.unionPaySpecs()
case .Visa:
specs = CCValidator.visaSpecs()
case .VisaElectron:
specs = CCValidator.visaElectronSpecs()
case .NotRecognized:
// This does nothing, added only to have exhaustive switch case
// without using default case - so we get compiler error
// when add a new credit card type and we won't handle it here
break
}
self.init(prefixes: specs.prefixes, lengths: specs.lengths)
}
private class func americanExpressSpecs() -> (prefixes: [CreditCardPrefix], lengths: [Int]) {
return (
prefixes: [CreditCardPrefix(rangeStart: 34, rangeEnd: 34, length: 2),
CreditCardPrefix(rangeStart: 37, rangeEnd: 37, length: 2)],
lengths: [15]
)
}
private class func dankortSpecs() -> (prefixes: [CreditCardPrefix], lengths: [Int]) {
return (
prefixes: [CreditCardPrefix(rangeStart: 5019, rangeEnd: 5019, length: 4)],
lengths: [16]
)
}
private class func dinersClubSpecs() -> (prefixes: [CreditCardPrefix], lengths: [Int]) {
return (
prefixes: [CreditCardPrefix(rangeStart: 300, rangeEnd: 305, length: 3),
CreditCardPrefix(rangeStart: 309, rangeEnd: 309, length: 3),
CreditCardPrefix(rangeStart: 36, rangeEnd: 36, length: 2),
CreditCardPrefix(rangeStart: 38, rangeEnd: 39, length: 2)],
lengths: [14]
)
}
private class func discoverSpecs() -> (prefixes: [CreditCardPrefix], lengths: [Int]) {
return (
prefixes: [CreditCardPrefix(rangeStart: 6011, rangeEnd: 6011, length: 4),
CreditCardPrefix(rangeStart: 622126, rangeEnd: 622925, length: 6),
CreditCardPrefix(rangeStart: 644, rangeEnd: 649, length: 3),
CreditCardPrefix(rangeStart: 65, rangeEnd: 65, length: 2)],
lengths: [16,19]
)
}
private class func jcbSpecs() -> (prefixes: [CreditCardPrefix], lengths: [Int]) {
return (
prefixes: [CreditCardPrefix(rangeStart: 3528, rangeEnd: 3589, length: 4)],
lengths: [16]
)
}
private class func maestroSpecs() -> (prefixes: [CreditCardPrefix], lengths: [Int]) {
return (
prefixes: [CreditCardPrefix(rangeStart: 50, rangeEnd: 50, length: 2),
CreditCardPrefix(rangeStart: 56, rangeEnd: 58, length: 2),
CreditCardPrefix(rangeStart: 60, rangeEnd: 61, length: 2),
CreditCardPrefix(rangeStart: 63, rangeEnd: 69, length: 2)],
lengths: [12, 13, 14, 15, 16, 17, 18, 19]
)
}
private class func masterCardSpecs() -> (prefixes: [CreditCardPrefix], lengths: [Int]) {
return (
prefixes: [CreditCardPrefix(rangeStart: 2221, rangeEnd: 2720, length: 4),
CreditCardPrefix(rangeStart: 51, rangeEnd: 55, length: 2)],
lengths: [16]
)
}
private class func unionPaySpecs() -> (prefixes: [CreditCardPrefix], lengths: [Int]) {
return (
prefixes: [CreditCardPrefix(rangeStart: 62, rangeEnd: 62, length: 2),
CreditCardPrefix(rangeStart: 88, rangeEnd: 88, length: 2)],
lengths: [16, 17, 18, 19]
)
}
private class func visaElectronSpecs() -> (prefixes: [CreditCardPrefix], lengths: [Int]) {
return (
prefixes: [CreditCardPrefix(rangeStart: 4026, rangeEnd: 4026, length: 4),
CreditCardPrefix(rangeStart: 417500, rangeEnd: 417500, length: 6),
CreditCardPrefix(rangeStart: 4405, rangeEnd: 4405, length: 4),
CreditCardPrefix(rangeStart: 4508, rangeEnd: 4508, length: 4),
CreditCardPrefix(rangeStart: 4844, rangeEnd: 4844, length: 4),
CreditCardPrefix(rangeStart: 4913, rangeEnd: 4913, length: 4),
CreditCardPrefix(rangeStart: 4917, rangeEnd: 4917, length: 4)],
lengths: [16]
)
}
private class func visaSpecs() -> (prefixes: [CreditCardPrefix], lengths: [Int]) {
return (
prefixes: [CreditCardPrefix(rangeStart: 4, rangeEnd: 4, length: 1)],
lengths: [13, 16, 19]
)
}
}
// MARK: Validate Credit Card
public extension CCValidator {
private func validatePrefixSpecs(creditCardNumber number: String) -> Bool {
var validationPassed = false
for prefix in self.prefixes {
if number.count >= prefix.prefixLength {
let prefixEndIndex = number.index(number.startIndex, offsetBy: prefix.prefixLength)
let numberPrefix = number[..<prefixEndIndex]
if let number = Int(numberPrefix), number >= prefix.rangeStart, number <= prefix.rangeEnd {
validationPassed = true
break
}
}
}
return validationPassed
}
private func validateLengthSpecs(creditCardNumber number: String) -> Bool {
var validationPassed = false
if self.lengths.contains(number.count) {
validationPassed = true
}
return validationPassed
}
private class func possibleTypesCheckingLengthOnly(creditCardNumber number: String) -> [CreditCardType] {
let allTypes = self.allTypes()
var possibleTypes: [CreditCardType] = []
for type in allTypes {
let validator = CCValidator(type: type)
if validator.validateLengthSpecs(creditCardNumber: number) {
possibleTypes.append(type)
}
}
return possibleTypes
}
private class func validateWithLuhnAlgorithm(creditCardNumber number: String) -> Bool {
guard let _ = Int64(number) else {
//if string is not convertible to int, return false
return false
}
let numberOfChars = number.count
let numberToCheck = numberOfChars % 2 == 0 ? number : "0" + number
let digits = numberToCheck.map { Int(String($0)) }
let sum = digits.enumerated().reduce(0) { (sum, val: (offset: Int, element: Int?)) in
if (val.offset + 1) % 2 == 1 {
let element = val.element!
return sum + (element == 9 ? 9 : (element * 2) % 9)
}
// else
return sum + val.element!
}
let validates = sum % 10 == 0
return validates
}
private class func allTypes() -> [CreditCardType] {
return [
.AmericanExpress,
.Dankort,
.DinersClub,
.Discover,
.JCB,
.Maestro,
.MasterCard,
.UnionPay,
.VisaElectron,
.Visa,
]
}
/// Returns credit card type from prefix number.
///
/// IMPORTANT: It doesn't check if number is valid, only if prefix matches
/// issuer prefix
///
/// - Parameters:
/// - number: Credit Card number
/// - Returns: Credit Card Type, or `.NotRecognized` if failed to recognize the type
class func typeCheckingPrefixOnly(creditCardNumber number: String) -> CreditCardType {
return self.typeCheckingPrefixOnly(creditCardNumber: number, checkOnlyFromTypes: self.allTypes())
}
/// Returns credit card type from prefix number. Returned Type can be only
/// amongst the one passed as `checkOnlyFromTypes`
///
/// IMPORTANT: It doesn't check if number is valid, only if prefix matches
/// issuer prefix
///
/// - Parameters:
/// - number: Credit Card number
/// - types: Types of Credit Card to check (if you don't need to check all possible answers)
/// - Returns: Credit Card Type, or `.NotRecognized` if failed to recognize the type
class func typeCheckingPrefixOnly(creditCardNumber number: String, checkOnlyFromTypes types:[CreditCardType]) -> CreditCardType {
var type: CreditCardType = .NotRecognized
let number = number.removingWhitespaceAndNewlines()
for currentType in types {
let validator = CCValidator(type: currentType)
if validator.validatePrefixSpecs(creditCardNumber: number) {
type = currentType
break
}
}
return type
}
/// Validates given credit card number, checking card prefix, card length
/// plus validating number using Luhn algorithm.
///
/// - Returns: `true` if validation was passed, `false` otherwise
class func validate(creditCardNumber number: String) -> Bool {
return self.validate(creditCardNumber: number,
validatePrefix: true,
validateLength: true,
useLuhnAlgorithm: true)
}
/// Validates given credit card number. It allows to check any/all
/// of following things:
/// * checking card prefix,
/// * card length
/// * validatine using Luhn algorithm
///
/// IMPORTANT: If you pass all validation variables as `false`
/// nothing will be validated, and function will return `true`
///
/// - Parameters:
/// - number: Credit card number
/// - validatePrefix: `true` if we should validate card prefix
/// - validateLength: `true` if we should validate card length
/// - useLuhn: `true` if we should check number using Luhn algorithm
/// - Returns: `true` if validation was passed, `false` otherwise
class func validate(creditCardNumber number: String,
validatePrefix: Bool,
validateLength: Bool, useLuhnAlgorithm useLuhn: Bool) -> Bool {
let number = number.removingWhitespaceAndNewlines()
let possibleTypesByLength = self.possibleTypesCheckingLengthOnly(creditCardNumber: number)
if validateLength
&& possibleTypesByLength.isEmpty {
return false
}
let typeByPrefix = self.typeCheckingPrefixOnly(creditCardNumber: number)
if validatePrefix
&& typeByPrefix == .NotRecognized {
return false
}
let isLengthTypeAndPrefixTypeSame = possibleTypesByLength.contains(typeByPrefix)
if validateLength
&& validatePrefix
&& isLengthTypeAndPrefixTypeSame == false {
return false
}
if useLuhn
&& self.validateWithLuhnAlgorithm(creditCardNumber: number) == false {
return false
}
return true
}
}
| mit | 50acfb96cf44c789ddfeb9012ca5767f | 38.24058 | 133 | 0.590929 | 4.682809 | false | false | false | false |
sarvex/SwiftRecepies | Cloud/Creating and Managing Folders for Apps in iCloud/Creating and Managing Folders for Apps in iCloud/AppDelegate.swift | 1 | 4409 | //
// AppDelegate.swift
// Creating and Managing Folders for Apps in iCloud
//
// Created by vandad on 207//14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
/* 1 */
//import UIKit
//
//@UIApplicationMain
//class AppDelegate: UIResponder, UIApplicationDelegate {
//
// var window: UIWindow?
// let fileManager = NSFileManager()
// var documentsDirectory: String?
//
// func doesDocumentsDirectoryExist() -> Bool{
// var isDirectory = false as ObjCBool
// var mustCreateDocumentsDirectory = false
//
// if let directory = documentsDirectory{
// if fileManager.fileExistsAtPath(directory,
// isDirectory: &isDirectory){
// if isDirectory{
// return true
// }
// }
// }
//
// return false
// }
//
// func createDocumentsDirectory(){
// println("Must create the directory.")
//
// var directoryCreationError: NSError?
//
// if let directory = documentsDirectory{
// if fileManager.createDirectoryAtPath(directory,
// withIntermediateDirectories:true,
// attributes:nil,
// error:&directoryCreationError){
// println("Successfully created the folder")
// } else {
// if let error = directoryCreationError{
// println("Failed to create the folder with error = \(error)")
// }
// }
// } else {
// println("The directory was nil")
// }
//
// }
//
// func application(application: UIApplication,
// didFinishLaunchingWithOptions launchOptions:
// [NSObject : AnyObject]?) -> Bool {
//
// let containerURL =
// fileManager.URLForUbiquityContainerIdentifier(nil)
//
// documentsDirectory =
// containerURL!.path!.stringByAppendingPathComponent("Documents")
//
// if doesDocumentsDirectoryExist(){
// println("This folder already exists.")
// } else {
// createDocumentsDirectory()
// }
//
// return true
// }
//
//}
/* 2 */
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let fileManager = NSFileManager()
var documentsDirectory: String?
func storeFile(){
println("Storing a file in the directory...")
if let directory = documentsDirectory{
let path =
documentsDirectory!.stringByAppendingPathComponent("File.txt")
var writingError: NSError?
if "Hello, World!".writeToFile(path,
atomically: true,
encoding: NSUTF8StringEncoding,
error: &writingError){
println("Successfully saved the file")
} else {
if let error = writingError{
println("An error occurred while writing the file = \(error)")
}
}
} else {
println("The directory was nil")
}
}
func doesDocumentsDirectoryExist() -> Bool{
var isDirectory = false as ObjCBool
var mustCreateDocumentsDirectory = false
if let directory = documentsDirectory{
if fileManager.fileExistsAtPath(directory,
isDirectory: &isDirectory){
if isDirectory{
return true
}
}
}
return false
}
func createDocumentsDirectory(){
println("Must create the directory.")
var directoryCreationError: NSError?
if let directory = documentsDirectory{
if fileManager.createDirectoryAtPath(directory,
withIntermediateDirectories:true,
attributes:nil,
error:&directoryCreationError){
println("Successfully created the folder")
/* Now store the file */
storeFile()
} else {
if let error = directoryCreationError{
println("Failed to create the folder with error = \(error)")
}
}
} else {
println("The directory was nil")
}
}
func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[NSObject : AnyObject]?) -> Bool {
let containerURL =
fileManager.URLForUbiquityContainerIdentifier(nil)
documentsDirectory =
containerURL!.path!.stringByAppendingPathComponent("Documents")
if doesDocumentsDirectoryExist(){
println("This folder already exists.")
/* Now store the file */
storeFile()
} else {
createDocumentsDirectory()
}
return true
}
}
| isc | 853ec3f9737d6a7d044ee4693960e2ac | 23.769663 | 72 | 0.6176 | 4.926257 | false | false | false | false |
xudafeng/Tomato | Tomato/AppDelegate.swift | 1 | 4034 | //
// AppDelegate.swift
// Tomato
//
// Created by xdf on 7/25/14.
// Copyright (c) 2014 xdf. All rights reserved.
//
import Cocoa;
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet var window: NSWindow?
@IBOutlet var myButton: NSButton?
var time = NSText();
var label = NSText();
var isRun = false;
var seconds = NSDate.timeIntervalSinceReferenceDate();
let DEFAULT_TIME = 60 * 25;
let TITLE = "Pay More Attention To Do More.";
func setWindowView (container:NSWindow) {
var image = NSImageView()
image.frame = container.contentView!.frame;
image.image = NSImage(named: "tomato");
container.contentView!.addSubview(image);
container.styleMask = 2;
container.alphaValue = 0.95;
container.hasShadow = true;
container.backgroundColor = NSColor.orangeColor();
container.setFrame(NSRect(x: 0, y: 0, width: 300, height: 200), display: true);
container.center();
}
func setLabelView (title:NSString) {
label.alignment = .CenterTextAlignment;
label.backgroundColor = NSColor.clearColor();
label.textColor = NSColor.whiteColor();
label.font = NSFont(name:"Arial",size: 14);
label.frame = NSRect(x: 0, y: 170, width: self.window!.frame.width, height: self.window!.frame.height);
label.string = title;
self.window!.contentView!.addSubview(label);
}
func setTimeLabelView (container:NSWindow) {
var time = self.time;
time.string = formatTime2String(DEFAULT_TIME);
time.frame = NSRect(x: 0, y: 60, width: container.frame.width, height: container.frame.height);
time.alignCenter(nil);
time.textColor = NSColor.whiteColor();
time.font = NSFont(name:"Arial", size: 30);
time.backgroundColor = NSColor.clearColor();
container.contentView!.addSubview(time);
}
func startTimer () {
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "countDownLoop", userInfo: nil, repeats: true);
}
func orderOutTimer () {
NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "orderOutWindow", userInfo: nil, repeats: false);
}
func orderOutWindow () {
self.window?.orderOut(nil);
}
func formatTime2String (int: NSInteger) -> NSString{
var minute = int/60;
var sminute = String(minute);
if (countElements(String(minute)) == 1) {
sminute = "0" + sminute;
}
var view = sminute + ":";
var temp = String(int - minute * 60);
if (countElements(temp) == 1) {
temp = "0" + temp;
}
view += temp;
return String(view);
}
func applicationDidFinishLaunching(aNotification: NSNotification?) {
NSLog ("\nApp Start Launching ...");
setWindowView(self.window!);
setLabelView(TITLE);
setTimeLabelView(self.window!);
startTimer();
}
func countDownLoop () {
if(!isRun) {
return;
}
let current = NSDate.timeIntervalSinceReferenceDate();
let passedTime = Int(round(current - seconds));
let showTime = DEFAULT_TIME - passedTime;
if(showTime <= 0) {
self.window!.orderFront(nil);
time.string = formatTime2String(DEFAULT_TIME);
self.myButton?.title = "start";
self.myButton?.hidden = false;
self.label.string = TITLE;
self.window?.level = Int(CGWindowLevelForKey(Int32(kCGScreenSaverWindowLevelKey)));
isRun = false;
} else {
time.string = formatTime2String(showTime);
}
}
@IBAction func buttonTapped(sender: AnyObject) {
self.label.string = "3 seconds to prepare";
self.myButton?.hidden = true;
isRun = true;
orderOutTimer();
seconds = NSDate.timeIntervalSinceReferenceDate();
}
}
| mit | 6c137869e19684a9753838ee074d9aca | 31.272 | 123 | 0.599653 | 4.413567 | false | false | false | false |
react-native-kit/react-native-track-player | ios/RNTrackPlayer/Vendor/SwiftAudio/Classes/NowPlayingInfoController/NowPlayingInfoController.swift | 1 | 1338 | //
// MediaInfoController.swift
// SwiftAudio
//
// Created by Jørgen Henrichsen on 15/03/2018.
//
import Foundation
import MediaPlayer
public class NowPlayingInfoController: NowPlayingInfoControllerProtocol {
private var _infoCenter: NowPlayingInfoCenter
private var _info: [String: Any] = [:]
var infoCenter: NowPlayingInfoCenter {
return _infoCenter
}
var info: [String: Any] {
return _info
}
public required init() {
self._infoCenter = MPNowPlayingInfoCenter.default()
}
public required init(infoCenter: NowPlayingInfoCenter) {
self._infoCenter = infoCenter
}
public func set(keyValues: [NowPlayingInfoKeyValue]) {
DispatchQueue.main.async {
keyValues.forEach { (keyValue) in
self._info[keyValue.getKey()] = keyValue.getValue()
}
self._infoCenter.nowPlayingInfo = self._info
}
}
public func set(keyValue: NowPlayingInfoKeyValue) {
DispatchQueue.main.async {
self._info[keyValue.getKey()] = keyValue.getValue()
self._infoCenter.nowPlayingInfo = self._info
}
}
public func clear() {
DispatchQueue.main.async {
self._info = [:]
self._infoCenter.nowPlayingInfo = self._info
}
}
}
| apache-2.0 | caa9a194ed9bebc811813068577db9ed | 23.759259 | 73 | 0.617801 | 4.532203 | false | false | false | false |
leannenorthrop/markdown-swift | Markdown/Line.swift | 1 | 602 | //
// Line.swift
// Markdown
//
// Created by Leanne Northrop on 14/06/2015.
// Copyright (c) 2015 Leanne Northrop. All rights reserved.
//
import Foundation
struct Line : Printable {
var _lineNumber:Int = -1
var _text:String = ""
var _trailing:String = "\n\n"
var description:String {
get {
return self._lineNumber.description + " " + self._text + self._trailing
}
}
init(text:String, lineNumber:Int = -1, trailing:String = "\n\n"){
self._lineNumber = lineNumber
self._trailing = trailing
self._text = text
}
} | gpl-2.0 | e7781fd344f69f53a2cc9234e6f1a380 | 22.192308 | 83 | 0.586379 | 3.670732 | false | false | false | false |
ccloveswift/CLSCommon | Classes/UI/class_NavigationController.swift | 1 | 1503 | //
// extension_navigation.swift
// Pods
//
// Created by TT on 2017/1/7.
// Copyright © 2017年 TT. All rights reserved.
//
import Foundation
import UIKit
class class_NavigationController : UINavigationController, UINavigationBarDelegate
{
func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
if let delegate = self.topViewController as? UINavigationBarDelegate {
let ret = delegate.navigationBar?(navigationBar, shouldPop: item)
return ret ?? true
}
return true
}
func navigationBar(_ navigationBar: UINavigationBar, didPop item: UINavigationItem) {
if let delegate = self.topViewController as? UINavigationBarDelegate {
delegate.navigationBar?(navigationBar, didPop: item)
}
}
func navigationBar(_ navigationBar: UINavigationBar, shouldPush item: UINavigationItem) -> Bool {
if let delegate = self.topViewController as? UINavigationBarDelegate {
let ret = delegate.navigationBar?(navigationBar, shouldPush: item)
return ret ?? true
}
return true
}
func navigationBar(_ navigationBar: UINavigationBar, didPush item: UINavigationItem) {
if let delegate = self.topViewController as? UINavigationBarDelegate {
delegate.navigationBar?(navigationBar, didPush: item)
}
}
}
| mit | 634fd031da39024f2a5fdcc786e594c1 | 29.612245 | 101 | 0.64 | 5.597015 | false | false | false | false |
mostafaberg/BluetoothDLEAudioExample | DLEStreamer/DLEStreamer/ViewControllers/MainView/MainViewController.swift | 1 | 6907 | //
// MainViewController.swift
// DLEStreamer
//
// Created by Mostafa Berg on 22/11/2016.
// Copyright © 2016 Nordic Semiconductor ASA. All rights reserved.
//
import UIKit
import CoreBluetooth
class MainViewController: UIViewController, UITextFieldDelegate,CBCentralManagerDelegate, FileStreamerDelegate {
//MARK: - Properties
//
public var peripheral : CBPeripheral!
public var centralManager : CBCentralManager!
private var uartController : UARTController!
private var fileStreamer : FileStreamer!
private var trackIndex : Int = 0
private var tracks : [String]!
@IBAction func stopButtonTapped(_ sender: Any) {
stopButtonTapped()
}
@IBAction func playButtonTapped(_ sender: Any) {
beginStreaming()
}
@IBAction func previousButtonTapped(_ sender: Any) {
skipTrackTapped(direction: -1)
}
@IBAction func nextButtonTapped(_ sender: Any) {
skipTrackTapped(direction: 1)
}
@IBOutlet weak var trackTitleLabel: UILabel!
@IBOutlet weak var packetCountField: UITextField!
@IBOutlet weak var intervalField: UITextField!
@IBOutlet weak var bleStreamingIcon: UIImageView!
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var streamingProgress: UIProgressView!
//MARK: - ViewController methods
//
override func viewDidLoad() {
super.viewDidLoad()
centralManager.delegate = self
centralManager.connect(peripheral, options: nil)
if let name = peripheral.name {
self.title = name
} else {
self.title = "Peripheral"
}
packetCountField.returnKeyType = .next
intervalField.returnKeyType = .done
//Load perdefined tracks and set the first one as the target
tracks = prepareTrackList()
trackIndex = 0
trackTitleLabel.text = "sample_\(trackIndex + 1).bv32"
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setBluetoothIconVisible(visible: false)
self.streamingProgress.setProgress(0, animated: false)
}
override func viewWillDisappear(_ animated: Bool) {
//Disconnect when leaving view
centralManager.cancelPeripheralConnection(peripheral)
peripheral = nil
}
//MARK: - Implementation
//
func playButtonTapped() {
beginStreaming()
}
func stopButtonTapped() {
stopStreaming()
}
func skipTrackTapped(direction : Int) {
trackIndex = abs((trackIndex + direction) % tracks.count)
if fileStreamer != nil {
stopStreaming()
beginStreaming()
}
trackTitleLabel.text = "sample_\(trackIndex + 1).bv32"
}
func beginStreaming() {
let resourcePath = tracks[trackIndex]
fileStreamer = FileStreamer(withFilePath: resourcePath, andDelegate: self)
let packetCount = UInt64(packetCountField.text!)
let interval = Int(intervalField.text!)
fileStreamer.stream(withChunkSize: packetCount!, andInterval: interval!)
updateUIToStreamingState()
}
func stopStreaming() {
if fileStreamer != nil {
fileStreamer.close()
fileStreamer = nil
updateUIToStoppedState()
}
}
func streamChunk(aChunk : Data) {
uartController.stream(data: aChunk)
}
//MARK: - CBCentralManagerDelegate
//
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
uartController = UARTController(withPeripheral: peripheral)
uartController.discoverUARTService {
print("Peripheral ready for streaming")
}
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
print("Failed to connect")
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
if let aName = peripheral.name {
print("Disconnected from \(aName)")
} else {
print("Disconnected from peripheral")
}
}
public func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .poweredOff:
break
case .poweredOn:
break
case .resetting:
break
case .unauthorized:
break
case .unknown:
break
case .unsupported:
break
}
}
//MARK: - FileStreamerDelegate
func didReceiveChunk(data: Data, atOffset offset: UInt64, andTotalSize totalSize: UInt64) {
streamChunk(aChunk: data)
print(offset, totalSize)
let completion = Float(offset) / Float(totalSize)
self.streamingProgress.setProgress(completion, animated: true)
}
func reachedEOF() {
fileStreamer.close()
fileStreamer = nil
updateUIToStoppedState()
statusLabel.text = "Completed"
self.streamingProgress.setProgress(0, animated: true)
}
func updateUIToStreamingState() {
setBluetoothIconVisible(visible: true)
playButton.isEnabled = false
packetCountField.isEnabled = false
intervalField.isEnabled = false
statusLabel.text = "Streaming"
}
func updateUIToStoppedState() {
setBluetoothIconVisible(visible: false)
playButton.isEnabled = true
packetCountField.isEnabled = true
intervalField.isEnabled = true
statusLabel.text = "Stopped"
}
//MARK: - UITextFieldDelegate
public func textFieldDidEndEditing(_ textField: UITextField) {
textField.resignFirstResponder()
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == packetCountField {
intervalField.becomeFirstResponder()
}else if textField == intervalField {
intervalField.resignFirstResponder()
}
return false
}
//MARK: - Helpers
func getResorucePath(withResourceName aResourceName: String) -> String? {
return Bundle.main.path(forResource: aResourceName, ofType: "bv32")
}
func prepareTrackList() -> [String] {
var tracks = [String]()
for i in 1...21 {
tracks.append(getResorucePath(withResourceName: "sample_\(i)")!)
}
return tracks
}
func setBluetoothIconVisible(visible : Bool) {
var alphaValue : CGFloat = 0
if visible == true {
alphaValue = 1
}
UIView.animate(withDuration: 1, animations: {
self.bleStreamingIcon.alpha = alphaValue
})
}
}
| mit | 9a85626ffab8a4fe7b5ebdd131ebd255 | 29.422907 | 119 | 0.627281 | 5.059341 | false | false | false | false |
dehesa/apple-utilites | Sources/Apple/Visuals/CAAnimation.swift | 2 | 2920 | #if os(macOS) || os(iOS) || os(tvOS)
import QuartzCore
/// It adds monitoring functionality to `CAAnimation` instances.
public extension CAAnimation {
/// Type for the callbacks to be executed when an animation starts.
public typealias DidStartCallback = (_ anim: CAAnimation)->()
/// Type for the callbacks to be executed when an animation stops.
public typealias DidStopCallback = (_ anim: CAAnimation, _ finished: Bool)->()
/// It stores a callback that will get executed when the animation starts.
/// - warning: If the callback contains retain cycles, you will get memory leaks. Be careful!
public var didStartCallback: DidStartCallback? {
get { return (delegate as? AnimationDelegate)?.didStartCallback }
set {
if let delegate = self.delegate as? AnimationDelegate {
delegate.didStartCallback = newValue
} else {
delegate = AnimationDelegate(didStartCallback: newValue)
}
}
}
/// It stores a callback that will get executed when the animation stops.
/// - warning: If the callback contains retain cycles, you will get memory leaks. Be careful!
public var didStopCallback: DidStopCallback? {
get { return (delegate as? AnimationDelegate)?.didStopCallback }
set {
if let delegate = self.delegate as? AnimationDelegate {
delegate.didStopCallback = newValue
} else {
delegate = AnimationDelegate(didStopCallback: newValue)
}
}
}
}
/// Delegate of a `CAAnimation` instance.
/// - note: The `delegate` object is retained by the receiver. This is a rare exception to the memmory management rules that Cocoa objects prescribe.
fileprivate final class AnimationDelegate: NSObject, CAAnimationDelegate {
fileprivate var didStartCallback: CAAnimation.DidStartCallback?
fileprivate var didStopCallback : CAAnimation.DidStopCallback?
fileprivate init(didStartCallback: CAAnimation.DidStartCallback? = nil, didStopCallback: CAAnimation.DidStopCallback? = nil) {
self.didStartCallback = didStartCallback
self.didStopCallback = didStopCallback
super.init()
}
/// Called when the animation begins its active duration.
func animationDidStart(_ anim: CAAnimation) {
guard let callback = didStartCallback else { return }
didStartCallback = nil
callback(anim)
}
/// Called when the animation either completes its active duration or is removed from the object it is attached to (i.e. the layer). 'flag' is true if the animation reached the end of its active duration without being removed.
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
guard let callback = didStopCallback else { return }
didStopCallback = nil
callback(anim, flag)
}
}
#endif
| mit | a2156acccbbf2a7702bbf976674d757c | 44.625 | 230 | 0.680822 | 5.104895 | false | false | false | false |
sarahspins/Loop | Loop/Models/Glucose.swift | 1 | 1250 | //
// GlucoseRxMessage.swift
// Loop
//
// Created by Nathan Racklyeft on 5/30/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
import xDripG5
extension Glucose: SensorDisplayable {
var stateDescription: String {
let status: String
switch self.status {
case .OK:
status = ""
case .LowBattery:
status = NSLocalizedString(" Low Battery", comment: "The description of a low G5 transmitter battery with a leading space")
case .Unknown(let value):
status = String(format: "%02x", value)
}
return String(format: "%1$@ %2$@", String(state), status)
}
var trendType: GlucoseTrend? {
guard trend < Int(Int8.max) else {
return nil
}
switch trend {
case let x where x <= -30:
return .DownDownDown
case let x where x <= -20:
return .DownDown
case let x where x <= -10:
return .Down
case let x where x < 10:
return .Flat
case let x where x < 20:
return .Up
case let x where x < 30:
return .UpUp
default:
return .UpUpUp
}
}
}
| apache-2.0 | e55d43512c2563162d4a2977ef63798b | 23.98 | 135 | 0.542034 | 4.262799 | false | false | false | false |
vgorloff/AUHost | Vendor/mc/mcxUIReusable/Sources/AppKit/Custom/FullContentWindowController.swift | 1 | 3119 | //
// FullContentWindowController.swift
// MCA-OSS-AUH
//
// Created by Vlad Gorlov on 13.10.18.
// Copyright © 2018 Vlad Gorlov. All rights reserved.
//
#if canImport(AppKit) && !targetEnvironment(macCatalyst)
import AppKit
import mcxUIExtensions
open class FullContentWindowController: WindowController {
private let fullContentWindow: FullContentWindow
private let fullContentViewController = ViewController()
public private(set) lazy var titleBarContentContainer = View().autolayoutView()
public private(set) lazy var contentContainer = View().autolayoutView()
private lazy var titleOffsetConstraint =
titleBarContentContainer.leadingAnchor.constraint(equalTo: fullContentViewController.content.view.leadingAnchor)
public init(contentRect: CGRect, titleBarHeight: CGFloat, titleBarLeadingOffset: CGFloat? = nil) {
fullContentWindow = FullContentWindow(contentRect: contentRect, titleBarHeight: titleBarHeight,
titleBarLeadingOffset: titleBarLeadingOffset)
super.init(viewController: fullContentViewController, window: fullContentWindow)
content.window.delegate = self
fullContentViewController.content.view.addSubviews(titleBarContentContainer, contentContainer)
let standardWindowButtonsRect = fullContentWindow.standardWindowButtonsRect
anchor.withFormat("V:|[*][*]|", titleBarContentContainer, contentContainer).activate()
anchor.pin.horizontally(contentContainer).activate()
anchor.height.to(standardWindowButtonsRect.height, titleBarContentContainer).activate()
anchor.withFormat("[*]|", titleBarContentContainer).activate()
titleOffsetConstraint.activate()
titleOffsetConstraint.constant = standardWindowButtonsRect.maxX
}
override open func prepareForInterfaceBuilder() {
titleBarContentContainer.backgroundColor = .green
contentContainer.backgroundColor = .yellow
fullContentViewController.content.view.backgroundColor = .blue
fullContentWindow.titleBarAccessoryViewController.contentView.backgroundColor = NSColor.red.withAlphaComponent(0.4)
}
@available(*, unavailable)
public required init?(coder: NSCoder) {
fatalError()
}
}
extension FullContentWindowController {
public func embedTitleBarContent(_ viewController: NSViewController) {
fullContentViewController.embedChildViewController(viewController, container: titleBarContentContainer)
}
public func embedContent(_ viewController: NSViewController) {
fullContentViewController.embedChildViewController(viewController, container: contentContainer)
}
}
extension FullContentWindowController: NSWindowDelegate {
public func windowWillEnterFullScreen(_: Notification) {
fullContentWindow.titleBarAccessoryViewController.isHidden = true
titleOffsetConstraint.constant = 0
}
public func windowWillExitFullScreen(_: Notification) {
fullContentWindow.titleBarAccessoryViewController.isHidden = false
titleOffsetConstraint.constant = fullContentWindow.standardWindowButtonsRect.maxX
}
}
#endif
| mit | 8c8d05baf9f6c0089f819f1a869011ba | 38.974359 | 121 | 0.776459 | 5.441536 | false | false | false | false |
hughbe/day-date-picker | DayDatePicker/Classes/DayDatePicker/DayDatePickerView.swift | 1 | 20368 | //
// DayDatePickerView
// DayDatePicker
//
// Created by Hugh Bellamy on 01/02/2018.
//
import UIKit
import AudioToolbox // Sound list: https://github.com/klaas/SwiftySystemSounds
@IBDesignable
public class DayDatePickerView: UIControl {
// MARK: - Init
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Private Property
fileprivate var _date: Date!
fileprivate var _minDate: Date?
fileprivate var _maxDate: Date?
fileprivate var _textColor: UIColor?
fileprivate var _textFont: UIFont?
public let overlayView = UIView()
private let MaxDay = 365
private let MaxMonth = 12
private let MaxYear = NSInteger.max
private let MinDay = 0
private let MinMonth = 0
private let MinYear = 0
public var hasHapticFeedback: Bool = true
public var hasSound: Bool = true
// MARK: - Table View Property
fileprivate let dayTableView = UITableView()
fileprivate let monthTableView = UITableView()
fileprivate let yearTableView = UITableView()
fileprivate var rowHeight: CGFloat = 44
fileprivate var yearRange: Range<Int>!
fileprivate var monthRange: Range<Int>!
fileprivate var dayRange: Range<Int>!
public var dayFormatter = DateFormatter(format: "EEE d") {
didSet {
dayTableView.reloadData()
}
}
public var monthFormatter = DateFormatter(format: "MMM") {
didSet {
monthTableView.reloadData()
}
}
public var yearFormatter = DateFormatter(format: "yyyy") {
didSet {
yearTableView.reloadData()
}
}
// MARK: - Delegate
@IBOutlet public weak var delegate: DayDatePickerViewDelegate?
// MARK: - Public Property
public var minDate: Date? {
get {
return _minDate
} set {
setMinDate(minDate: newValue, animated: true)
}
}
public var maxDate: Date? {
get {
return _maxDate
} set {
setMaxDate(maxDate: newValue, animated: true)
}
}
public var date: Date {
get {
return _date
} set {
setDate(date: newValue, animated: true)
}
}
public var textFont: UIFont {
get {
return _textFont ?? UIFont.systemFont(ofSize: 20)
} set {
setTextWith(font: newValue, color: _textColor)
}
}
public var textColor: UIColor {
get {
return _textColor ?? .black
} set {
setTextWith(font: textFont, color: newValue)
}
}
override public var backgroundColor: UIColor? {
didSet {
dayTableView.backgroundColor = backgroundColor
dayTableView.reloadData()
monthTableView.backgroundColor = backgroundColor
monthTableView.reloadData()
yearTableView.backgroundColor = backgroundColor
yearTableView.reloadData()
}
}
public var showOrdinalIndicator = true {
didSet {
dayTableView.reloadData()
}
}
public func setDate(year: Int, month: Int, day: Int, animated: Bool) {
let date = Date(year: year, month: month, day: day)
setDate(date: date, animated: animated)
}
public func setDate(date: Foundation.Date, animated: Bool) {
let dateDate = Date(date: date)
setDate(date: dateDate, animated: animated)
}
// MARK: - Public methods
public func setDate(date: Date, animated: Bool) {
var date = date
if let minTime = _minDate, date < minTime {
date = minTime
} else if let maxDate = _maxDate, date > maxDate {
date = maxDate
}
let reloadMonthTableView = date.year != _date.year
let reloadDayTableView = reloadMonthTableView || date.month != _date.month
_date = date
if reloadMonthTableView {
monthTableView.reloadAndLayout()
}
if reloadDayTableView {
let startMonth = Date(year: year, month: month, day: 1)
if let selectedMonthRange = Calendar.current.range(of: .day, in: .month, for: startMonth.date),
let dataRange = Calendar.current.range(of: .day, in: .month, for: date.date),
dataRange.count > selectedMonthRange.count {
date = Date(year: year, month: month, day: selectedMonthRange.count)
_date = date
}
dayTableView.reloadAndLayout()
}
if dayTableView.superview != nil {
dayTableView.scrollToRow(row: date.day - dayRange.lowerBound, animated: animated)
monthTableView.scrollToRow(row: date.month - monthRange.lowerBound, animated: animated)
yearTableView.scrollToRow(row: date.year - yearRange.lowerBound, animated: animated)
}
sendActions(for: .editingChanged)
}
// MARK: - Set Min Date
public func setMinDate(year: Int, month: Int, day: Int, animated: Bool) {
let minDate = Date(year: year, month: month, day: day)
setMinDate(minDate: minDate, animated: animated)
}
public func setMinDate(_ date: Foundation.Date, animated: Bool) {
let minDate = Date(date: date)
setMinDate(minDate: minDate, animated: animated)
}
public func setMinDate(minDate: Date?, animated: Bool) {
_minDate = minDate
reload()
if let minDate = minDate, date < minDate {
setDate(date: minDate, animated: true)
}
}
// MARK: - Set Max Date
public func setMaxDate(year: Int, month: Int, day: Int, animated: Bool) {
let maxDate = Date(year: year, month: month, day: day)
setMaxDate(maxDate: maxDate, animated: true)
}
public func setMaxDate(_ date: Foundation.Date, animated: Bool) {
let maxDate = Date(date: date)
setMaxDate(maxDate: maxDate, animated: animated)
}
public func setMaxDate(maxDate: Date?, animated: Bool) {
_maxDate = maxDate
reload()
if let maxDate = maxDate, date > maxDate {
setDate(date: maxDate, animated: true)
}
}
// MARK: - Set Text
public func setTextWith(font: UIFont?, color: UIColor?) {
_textFont = font ?? UIFont.systemFont(ofSize: 20)
_textColor = color ?? .black
reload()
}
// MARK: - Set Feedback
public func setFeedback(hasHapticFeedback: Bool = true, hasSound: Bool = true) {
self.hasHapticFeedback = hasHapticFeedback
self.hasSound = hasSound
}
}
// Layout actions.
extension DayDatePickerView {
// MARK: - Override Interface Builder
public override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setup()
}
public override func awakeFromNib() {
super.awakeFromNib()
setup()
}
public override func layoutSubviews() {
super.layoutSubviews()
let contentInset = UIEdgeInsets(top: (frame.size.height - rowHeight) / 2, left: 0, bottom: (frame.size.height - rowHeight) / 2, right: 0)
dayTableView.contentInset = contentInset
monthTableView.contentInset = contentInset
yearTableView.contentInset = contentInset
dayTableView.separatorStyle = .none
monthTableView.separatorStyle = .none
yearTableView.separatorStyle = .none
setDate(date: _date, animated: false)
}
// MARK: - Setup
fileprivate func setup() {
if yearTableView.superview != nil {
return
}
setupTableView(tableView: dayTableView)
setupTableView(tableView: monthTableView)
setupTableView(tableView: yearTableView)
overlayView.backgroundColor = UIColor(red: 0, green: 153 / 255, blue: 102 / 255, alpha: 1)
overlayView.isUserInteractionEnabled = false
overlayView.translatesAutoresizingMaskIntoConstraints = false
overlayView.alpha = 0.5
addSubview(overlayView)
addConstraints([
NSLayoutConstraint(item: dayTableView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: dayTableView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: dayTableView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: dayTableView, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 0.4, constant: 0),
NSLayoutConstraint(item: monthTableView, attribute: .leading, relatedBy: .equal, toItem: dayTableView, attribute: .trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: monthTableView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: monthTableView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: monthTableView, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1 / 3, constant: 0),
NSLayoutConstraint(item: yearTableView, attribute: .leading, relatedBy: .equal, toItem: monthTableView, attribute: .trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: yearTableView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: yearTableView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: yearTableView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: overlayView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: overlayView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: overlayView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0),
NSLayoutConstraint(item: overlayView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: rowHeight)
])
if _date == nil {
let components = Calendar.current.dateComponents([.year, .month, .day], from: Foundation.Date()) as NSDateComponents
_date = Date(year: components.year, month: components.month, day: components.day)
}
dayRange = Calendar.current.range(of: .day, in: .month, for: _date.date)
monthRange = Calendar.current.range(of: .month, in: .year, for: _date.date)
yearRange = Calendar.current.range(of: .year, in: .era, for: _date.date)
}
private func setupTableView(tableView: UITableView) {
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.rowHeight = rowHeight
tableView.showsVerticalScrollIndicator = false
tableView.backgroundColor = self.backgroundColor
tableView.delegate = self
tableView.dataSource = self
tableView.scrollsToTop = false
addSubview(tableView)
}
}
// MARK: - Table View Data Source
extension DayDatePickerView: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == dayTableView {
if let daysInAMonth = Calendar.current.range(of: .day, in: .month, for: date.date) {
dayRange = daysInAMonth
return daysInAMonth.count
}
} else if tableView == monthTableView {
if let monthsInAYear = Calendar.current.range(of: .month, in: .year, for: date.date) {
monthRange = monthsInAYear
return monthsInAYear.count
}
} else if tableView == yearTableView {
if let yearsInAnEra = Calendar.current.range(of: .year, in: .era, for: date.date) {
yearRange = yearsInAnEra
return yearsInAnEra.count
}
}
return 0
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
cell.selectionStyle = .none
cell.textLabel?.textAlignment = .center
cell.textLabel?.font = textFont
cell.backgroundColor = self.backgroundColor
cell.textLabel?.textColor = textColor
if tableView == dayTableView {
let date = Date(year: year, month: month, day: dayRange.lowerBound + indexPath.row)
if let minDate = minDate, date < minDate {
cell.textLabel?.textColor = UIColor.lightGray
} else if let maxDate = maxDate, date > maxDate {
cell.textLabel?.textColor = UIColor.lightGray
}
var dayString = dayFormatter.string(from: date.date)
if showOrdinalIndicator {
dayString.append(date.day.ordinalIndicatorString)
}
cell.textLabel?.text = dayString
delegate?.customizeCell(cell: cell, atIndexPath: indexPath, forType: .day)
} else if tableView == monthTableView {
let month = monthRange.lowerBound + indexPath.row
if year < minYear || (year == minYear && month < minMonth) {
cell.textLabel?.textColor = UIColor.lightGray
} else if year > maxYear || (year == maxYear && month > maxMonth) {
cell.textLabel?.textColor = UIColor.lightGray
}
let date = Date(year: year, month: month, day: 1)
cell.textLabel?.text = monthFormatter.string(from: date.date)
delegate?.customizeCell(cell: cell, atIndexPath: indexPath, forType: .month)
} else if tableView == yearTableView {
let year = yearRange.lowerBound + indexPath.row
if year < minYear {
cell.textLabel?.textColor = UIColor.lightGray
} else if year > maxYear {
cell.textLabel?.textColor = UIColor.lightGray
}
let date = Date(year: year, month: 1, day: 1)
cell.textLabel?.text = yearFormatter.string(from: date.date)
delegate?.customizeCell(cell: cell, atIndexPath: indexPath, forType: .year)
}
return cell
}
}
// Table view data.
extension DayDatePickerView: UITableViewDelegate {
public func reload() {
dayTableView.reloadAndLayout()
monthTableView.reloadAndLayout()
yearTableView.reloadAndLayout()
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView == dayTableView {
day = dayRange.lowerBound + indexPath.row
} else if tableView == monthTableView {
month = monthRange.lowerBound + indexPath.row
} else if tableView == yearTableView {
year = yearRange.lowerBound + indexPath.row
}
delegate?.didSelectDate(day: day, month: month, year: year)
}
public func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if tableView.isDragging {
if #available(iOS 10.0, *), hasHapticFeedback {
let selectionFeedbackGenerator = UISelectionFeedbackGenerator()
selectionFeedbackGenerator.selectionChanged()
}
if hasSound {
let urlString = "System/Library/Audio/UISounds/nano/TimerStart_Haptic.caf"
let url = URL(fileURLWithPath: urlString)
var soundID: SystemSoundID = 0
AudioServicesCreateSystemSoundID(url as CFURL, &soundID)
AudioServicesPlaySystemSound(soundID)
}
}
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
guard let tableView = scrollView as? UITableView else {
return
}
if !decelerate {
alignTableViewToRow(tableView: tableView)
}
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
guard let tableView = scrollView as? UITableView else {
return
}
alignTableViewToRow(tableView: tableView)
}
public func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
guard let tableView = scrollView as? UITableView else {
return
}
alignTableViewToRow(tableView: tableView)
}
private func alignTableViewToRow(tableView: UITableView) {
let row = tableView.getRowScroll()
if tableView == dayTableView {
day = dayRange.lowerBound + row
} else if tableView == monthTableView {
month = monthRange.lowerBound + row
} else if tableView == yearTableView {
year = yearRange.lowerBound + row
}
delegate?.didSelectDate(day: day, month: month, year: year)
}
}
// MARK: - Interface Builder properties.
extension DayDatePickerView {
@IBInspectable
public var minYear: NSInteger {
get {
return _minDate?.year ?? MinYear
}
set {
setMinDate(year: newValue, month: _minDate?.month ?? MinMonth, day: _minDate?.day ?? MinDay, animated: true)
}
}
@IBInspectable
public var minMonth: NSInteger {
get {
return _minDate?.month ?? MinMonth
}
set {
setMinDate(year: _minDate?.year ?? MinYear, month: newValue, day: _minDate?.day ?? MinDay, animated: true)
}
}
@IBInspectable
public var minDay: NSInteger {
get {
return _minDate?.day ?? MinDay
}
set {
setMinDate(year: _minDate?.year ?? MinYear, month: _minDate?.month ?? MinMonth, day: newValue, animated: true)
}
}
@IBInspectable
public var maxYear: NSInteger {
get {
return _maxDate?.year ?? MaxYear
}
set {
setMinDate(year: newValue, month: _maxDate?.month ?? MaxMonth, day: _maxDate?.day ?? MaxDay, animated: true)
}
}
@IBInspectable
public var maxMonth: NSInteger {
get {
return _maxDate?.month ?? MaxMonth
}
set {
setMinDate(year: _maxDate?.year ?? MaxYear, month: newValue, day: _maxDate?.day ?? MaxDay, animated: true)
}
}
@IBInspectable
public var maxDay: NSInteger {
get {
return _maxDate?.day ?? MaxDay
}
set {
setMinDate(year: _maxDate?.year ?? MaxYear, month: _maxDate?.month ?? MaxMonth, day: newValue, animated: true)
}
}
@IBInspectable
public var year: NSInteger {
get {
return _date?.year ?? MinYear
}
set {
setDate(year: newValue, month: _date?.month ?? MinMonth, day: _date?.day ?? MinDay, animated: true)
}
}
@IBInspectable
public var month: NSInteger {
get {
return _date?.month ?? MinMonth
}
set {
setDate(year: _date?.year ?? MinYear, month: newValue, day: _date?.day ?? MinDay, animated: true)
}
}
@IBInspectable
public var day: NSInteger {
get {
return _date?.day ?? MinDay
}
set {
setDate(year: _date?.year ?? MinYear, month: _date?.month ?? MinMonth, day: newValue, animated: true)
}
}
}
| mit | 60403e371422bd26dab76ca3fa1e1635 | 34.859155 | 166 | 0.60546 | 4.734542 | false | false | false | false |
alexito4/Error-Handling-Script-Rust-Swift | Pods/Swiftline/Pod/Swiftline/Choose/ChooseSettings.swift | 1 | 3355 | //
// ChooseSettings.swift
// ChooseSettings
//
// Created by Omar Abdelhafith on 03/11/2015.
// Copyright © 2015 Omar Abdelhafith. All rights reserved.
//
import Foundation
/**
Choice index type
- Letters: Use letters as choice index (a. b. c.)
- Numbers: Use numbers as choice index (1. 2. 3.)
*/
public enum ChoiceIndexType {
case Letters
case Numbers
}
/// Settings to costumize the behavior of choose
public class ChooseSettings<T> {
typealias Item = T
var choices: [(choice: String, callback: Void -> T)] = []
/// Prompt message to use
public var promptQuestion = ""
/// Choice index used for choose items
public var index = ChoiceIndexType.Numbers
/// Index suffix used between the index and the item
public var indexSuffix = ". "
/**
Add a new item to the list of choices
- parameter choice: Item name
- parameter callback: callback called when the item is selected, the value returned from this call back will be returned from choose
*/
public func addChoice(choice: String..., callback: Void -> T) {
choice.forEach {
choices.append(($0, callback))
}
}
// MARK:- Internal
func validChoices() -> [String] {
let validChoices = Array(1...choices.count).map { "\($0)" }
return validChoices + stringChoices()
}
func stringChoices() -> [String] {
return choices.map { $0.choice }
}
func choiceForInput(item: String) -> T? {
if let value = Int(item) {
return choiceWithIntValue(value)
} else {
return choiceWithStringValue(item)
}
}
func choiceWithIntValue(value: Int) -> T? {
let index = value - 1
if index >= 0 && index < choices.count {
return choices[index].callback()
}
return nil
}
func choiceWithStringValue(value: String) -> T? {
let possibleIndex = choices.indexOf { $0.choice == value }
if let index = possibleIndex {
return choices[index].callback()
}
return nil
}
func preparePromptItems() -> [String] {
return zip(indexChoices(), stringChoices()).map { index, string in
return "\(index)\(indexSuffix)\(string)"
}
}
func indexChoices() -> [String] {
return stringChoices().enumerate().map { itemIndex, string in
if index == .Numbers {
return "\(itemIndex + 1)"
} else {
let character = "a".unicodeScalars.first!.value + UInt32(itemIndex)
return String(Character(UnicodeScalar(character)))
}
}
}
}
// MARK:- Internal Class
extension ChooseSettings: AskerValidator {
func validatedItem(forString string: String) -> T {
return choiceForInput(string)!
}
func invalidItemMessage(string: String?) -> String? {
if choiceForInput(string!) != nil {
return nil
}
let baseMessage = "You must choose one of"
let choicesString = validChoices().joinWithSeparator(", ")
return "\(baseMessage) [\(choicesString)]."
}
func newItemPromptMessage() -> String {
return "? "
}
} | mit | 824513971121a6a342b2ff355112b39b | 24.807692 | 137 | 0.57096 | 4.48996 | false | false | false | false |
longjianjiang/BlogDemo | CAReplicatorLayerDemo/CAReplicatorLayerDemo/MicMonitor.swift | 1 | 3029 | /*
* Copyright (c) 2014-2016 Razeware 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
import AVFoundation
class MicMonitor: NSObject {
private var recorder: AVAudioRecorder!
private var timer: Timer?
private var levelsHandler: ((Float)->Void)?
override init() {
let url = URL(fileURLWithPath: "/dev/null", isDirectory: true)
let settings: [String: Any] = [
AVSampleRateKey: 44100.0,
AVNumberOfChannelsKey: 1,
AVFormatIDKey: NSNumber(value: kAudioFormatAppleLossless),
AVEncoderAudioQualityKey: AVAudioQuality.min.rawValue
]
let audioSession = AVAudioSession.sharedInstance()
if audioSession.recordPermission() != .granted {
audioSession.requestRecordPermission({success in print("microphone permission: \(success)")})
}
do {
try recorder = AVAudioRecorder(url: url, settings: settings)
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch {
print("Couldn't initialize the mic input")
}
if let recorder = recorder {
//start observing mic levels
recorder.prepareToRecord()
recorder.isMeteringEnabled = true
}
}
func startMonitoringWithHandler(_ handler: ((Float)->Void)?) {
levelsHandler = handler
//start meters
timer = Timer.scheduledTimer(timeInterval: 0.02, target: self, selector: #selector(MicMonitor.handleMicLevel(_:)), userInfo: nil, repeats: true)
recorder.record()
}
func stopMonitoring() {
levelsHandler = nil
timer?.invalidate()
recorder.stop()
}
@objc func handleMicLevel(_ timer: Timer) {
recorder.updateMeters()
levelsHandler?(recorder.averagePower(forChannel: 0))
}
deinit {
stopMonitoring()
}
}
| apache-2.0 | 75d001a737c73649a76c73491856fc71 | 34.635294 | 152 | 0.659624 | 5.142615 | false | false | false | false |
lyft/SwiftLint | Source/SwiftLintFramework/Rules/CompilerProtocolInitRule.swift | 1 | 7154 | import Foundation
import SourceKittenFramework
public struct CompilerProtocolInitRule: ASTRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "compiler_protocol_init",
name: "Compiler Protocol Init",
description: "The initializers declared in compiler protocols such as `ExpressibleByArrayLiteral` " +
"shouldn't be called directly.",
kind: .lint,
nonTriggeringExamples: [
"let set: Set<Int> = [1, 2]\n",
"let set = Set(array)\n"
],
triggeringExamples: [
"let set = ↓Set(arrayLiteral: 1, 2)\n",
"let set = ↓Set.init(arrayLiteral: 1, 2)\n"
]
)
public func validate(file: File, kind: SwiftExpressionKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
return violationRanges(in: file, kind: kind, dictionary: dictionary).map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}
private func violationRanges(in file: File, kind: SwiftExpressionKind,
dictionary: [String: SourceKitRepresentable]) -> [NSRange] {
guard kind == .call, let name = dictionary.name else {
return []
}
for compilerProtocol in ExpressibleByCompiler.allProtocols {
guard compilerProtocol.initCallNames.contains(name),
case let arguments = dictionary.enclosedArguments.compactMap({ $0.name }),
compilerProtocol.match(arguments: arguments),
let offset = dictionary.offset,
let length = dictionary.length,
let range = file.contents.bridge().byteRangeToNSRange(start: offset, length: length) else {
continue
}
return [range]
}
return []
}
}
private struct ExpressibleByCompiler {
private let protocolName: String
let initCallNames: Set<String>
private let arguments: [[String]]
init(protocolName: String, types: Set<String>, arguments: [[String]]) {
self.protocolName = protocolName
self.arguments = arguments
initCallNames = Set(types.flatMap { [$0, "\($0).init"] })
}
static let allProtocols = [byArrayLiteral, byNilLiteral, byBooleanLiteral,
byFloatLiteral, byIntegerLiteral, byUnicodeScalarLiteral,
byExtendedGraphemeClusterLiteral, byStringLiteral,
byStringInterpolation, byDictionaryLiteral]
func match(arguments: [String]) -> Bool {
return self.arguments.contains { $0 == arguments }
}
private static let byArrayLiteral: ExpressibleByCompiler = {
let types: Set = [
"Array",
"ArraySlice",
"ContiguousArray",
"IndexPath",
"NSArray",
"NSCountedSet",
"NSMutableArray",
"NSMutableOrderedSet",
"NSMutableSet",
"NSOrderedSet",
"NSSet",
"SBElementArray",
"Set"
]
return ExpressibleByCompiler(protocolName: "ExpressibleByArrayLiteral",
types: types, arguments: [["arrayLiteral"]])
}()
private static let byNilLiteral = ExpressibleByCompiler(protocolName: "ExpressibleByNilLiteral",
types: ["ImplicitlyUnwrappedOptional", "Optional"],
arguments: [["nilLiteral"]])
private static let byBooleanLiteral = ExpressibleByCompiler(protocolName: "ExpressibleByBooleanLiteral",
types: ["Bool", "NSDecimalNumber",
"NSNumber", "ObjCBool"],
arguments: [["booleanLiteral"]])
private static let byFloatLiteral = ExpressibleByCompiler(protocolName: "ExpressibleByFloatLiteral",
types: ["Decimal", "NSDecimalNumber", "NSNumber"],
arguments: [["floatLiteral"]])
private static let byIntegerLiteral = ExpressibleByCompiler(protocolName: "ExpressibleByIntegerLiteral",
types: ["Decimal", "Double", "Float", "Float80",
"NSDecimalNumber", "NSNumber"],
arguments: [["integerLiteral"]])
private static let byUnicodeScalarLiteral = ExpressibleByCompiler(protocolName: "ExpressibleByUnicodeScalarLiteral",
types: ["StaticString", "String",
"UnicodeScalar"],
arguments: [["unicodeScalarLiteral"]])
private static let byExtendedGraphemeClusterLiteral =
ExpressibleByCompiler(protocolName: "ExpressibleByExtendedGraphemeClusterLiteral",
types: ["Character", "StaticString", "String"],
arguments: [["extendedGraphemeClusterLiteral"]])
private static let byStringLiteral = ExpressibleByCompiler(protocolName: "ExpressibleByStringLiteral",
types: ["CSLocalizedString", "NSMutableString",
"NSString", "Selector",
"StaticString", "String"],
arguments: [["stringLiteral"]])
private static let byStringInterpolation = ExpressibleByCompiler(protocolName: "ExpressibleByStringInterpolation",
types: ["String"],
arguments: [["stringInterpolation"],
["stringInterpolationSegment"]])
private static let byDictionaryLiteral = ExpressibleByCompiler(protocolName: "ExpressibleByDictionaryLiteral",
types: ["Dictionary", "DictionaryLiteral",
"NSDictionary", "NSMutableDictionary"],
arguments: [["dictionaryLiteral"]])
}
| mit | 35c73c23ce7cf2f6c2d11829937071f7 | 49.70922 | 120 | 0.503357 | 7.229525 | false | false | false | false |
zadr/conservatory | Code/Outputs/CARenderer.swift | 1 | 5474 | import QuartzCore
public final class CARenderer: Renderer {
public typealias RenderResultType = CALayer
private let layer = CALayer()
private var activeLayer: CALayer!
private var activeLayerAppearance: Appearance!
public init(size: Size) {
layer.bounds = Box(size: size).CGRectView
}
public var size: Size {
return Size(size: layer.bounds.size)
}
public func render(_ viewable: Viewable) -> RenderResultType? {
return render([ viewable ])
}
public func render(_ viewables: [Viewable]) -> RenderResultType? {
viewables.forEach {
// reset state before each run
activeLayerAppearance = Appearance()
activeLayer = nil
$0.render(self)
guard let activeLayer = activeLayer, let activeLayerAppearance = activeLayerAppearance else {
fatalError("activeLayer must be non-nil after render")
}
// aura
if let aura = activeLayerAppearance.aura {
activeLayer.shadowColor = aura.color.CGColorView
activeLayer.shadowOpacity = Float(aura.color.AView)
activeLayer.shadowOffset = aura.offset.CGSizeView
activeLayer.shadowRadius = CGFloat(aura.blur)
}
// blend modes
if var blendableLayer = activeLayer as? CVBlendableLayer {
blendableLayer.blendMode = activeLayerAppearance.blendMode
}
// transform
activeLayer.setAffineTransform(activeLayerAppearance.transform.CGAffineTransformView)
layer.addSublayer(activeLayer)
}
layer.setNeedsDisplay()
layer.displayIfNeeded()
return layer
}
public func draw(_ bezier: Bezier) {
let shapeLayer = CVShapeLayer()
shapeLayer.path = bezier.CGPathView
activeLayer = shapeLayer
}
public func draw(_ image: Image) {
let imageLayer = CVLayer()
imageLayer.bounds = Box(size: image.size).CGRectView
imageLayer.contents = image.CGImageView
activeLayer = imageLayer
}
public func draw(_ text: String, withTextEffects effects: [TextEffect]) {
let textLayer = CVTextLayer()
textLayer.allowsFontSubpixelQuantization = true
textLayer.string = text.cocoaValue(effects)
activeLayer = textLayer
}
public func apply(_ aura: Aura?) {
activeLayerAppearance.aura = aura
}
public func apply(_ background: Palette<Color, GradientOptions>) {
activeLayerAppearance.background = background
}
public func apply(_ border: Palette<Color, GradientOptions>, width: Double) {
activeLayerAppearance.border = border
activeLayerAppearance.borderWidth = width
}
public func apply(_ blendMode: BlendMode) {
activeLayerAppearance.blendMode = blendMode
}
public func apply(_ transform: Transform) {
activeLayerAppearance.transform = transform
}
public func fill() {
switch activeLayerAppearance.background {
case .none:
activeLayer.backgroundColor = Color.transparent.CGColorView
case .solid(let backgroundColor):
activeLayer.backgroundColor = backgroundColor.CGColorView
case .gradient(let backgroundColors, let options):
switch options.type {
case .linear:
var start = CGPoint(x: layer.bounds.midX, y: layer.bounds.minY)
start = start.applying(CGAffineTransform(rotationAngle: CGFloat(options.rotation)))
var end = CGPoint(x: layer.bounds.midX, y: layer.bounds.maxY)
end = end.applying(CGAffineTransform(rotationAngle: CGFloat(options.rotation)))
let gradientLayer = CAGradientLayer()
gradientLayer.bounds = activeLayer.bounds
gradientLayer.colors = backgroundColors.map { return $0.CGColorView }
gradientLayer.locations = backgroundColors.positions.map { return NSNumber(value: $0) }
gradientLayer.startPoint = start
gradientLayer.endPoint = end
gradientLayer.type = .axial
activeLayer.addSublayer(gradientLayer)
case .radial:
var start = CGPoint(x: layer.bounds.midX, y: layer.bounds.minY)
start = start.applying(CGAffineTransform(rotationAngle: CGFloat(options.rotation)))
var end = CGPoint(x: layer.bounds.midX, y: layer.bounds.maxY)
end = end.applying(CGAffineTransform(rotationAngle: CGFloat(options.rotation)))
let gradientLayer = CAGradientLayer()
gradientLayer.bounds = activeLayer.bounds
gradientLayer.colors = backgroundColors.map { return $0.CGColorView }
gradientLayer.locations = backgroundColors.positions.map { return NSNumber(value: $0) }
gradientLayer.startPoint = start
gradientLayer.endPoint = end
gradientLayer.type = .radial
activeLayer.addSublayer(gradientLayer)
}
}
}
public func stroke() {
// border
switch activeLayerAppearance.border {
case .none:
activeLayer.borderColor = nil
activeLayer.borderWidth = 0.0
case .solid(let borderColor):
activeLayer.borderColor = borderColor.CGColorView
activeLayer.borderWidth = CGFloat(activeLayerAppearance.borderWidth)
case .gradient(_, _):
precondition(false, "border gradients not yet supported with CARenderer")
}
}
}
// MARK: -
private protocol CVBlendableLayer {
var blendMode: BlendMode { set get }
}
private final class CVLayer: CALayer {
var blendMode: BlendMode = .normal
override func draw(in ctx: CGContext) {
ctx.setBlendMode(blendMode.CGBlendView)
super.draw(in: ctx)
}
}
private final class CVTextLayer: CATextLayer {
var blendMode: BlendMode = .normal
override func draw(in ctx: CGContext) {
ctx.setBlendMode(blendMode.CGBlendView)
super.draw(in: ctx)
}
}
private final class CVShapeLayer: CAShapeLayer {
var blendMode: BlendMode = .normal
override func draw(in ctx: CGContext) {
ctx.setBlendMode(blendMode.CGBlendView)
super.draw(in: ctx)
}
}
| bsd-2-clause | 2c68ab89c840c407e489bf69b4a09932 | 26.786802 | 96 | 0.742601 | 3.814634 | false | false | false | false |
piersadrian/switch | Flow/Sources/Server.swift | 1 | 3655 | //
// Server.swift
// Switch
//
// Created by Piers Mainwaring on 12/21/15.
// Copyright © 2016 Playfair, LLC. All rights reserved.
//
import Foundation
enum ServerStatus {
case Starting, Running, Stopping, Stopped
}
public protocol ServerDelegate: class {
func connectionForSocket(socket: IOSocket) -> Connection
}
public class Server: ListenerSocketDelegate, ConnectionDelegate {
// MARK: - Internal Properties
let socket: ListenerSocket
let requestQueue: dispatch_queue_t
let controlQueue: dispatch_queue_t
var concurrency: Int = 10
var status: ServerStatus = .Stopped
// MARK: - Private Properties
private var requestPool = Set<WrappedConnection>(minimumCapacity: 10) // TODO: global option?
// MARK: - Public Properties
public weak var delegate: ServerDelegate?
// MARK: - Lifecycle
public init() {
self.controlQueue = dispatch_queue_create("com.playfair.server-control", DISPATCH_QUEUE_SERIAL)
self.requestQueue = dispatch_queue_create("com.playfair.requests", DISPATCH_QUEUE_CONCURRENT)
self.socket = ListenerSocket(handlerQueue: self.requestQueue)
self.socket.delegate = self
}
deinit {
stop()
}
// MARK: - Public API
public func start() {
status = .Starting
Signals.trap(.TERM, .INT, action: stop)
socket.attach()
status = .Running
NSRunLoop.currentRunLoop().run()
}
public func stop() {
status = .Stopping
while !requestPool.isEmpty {}
status = .Stopped
socket.detach(immediately: true)
}
// MARK: - Private API
private func addConnection(conn: WrappedConnection) {
dispatch_sync(controlQueue) {
let oldPressure = Int(Float(self.requestPool.count) / Float(self.concurrency) * 100)
self.requestPool.insert(conn)
let newPressure = Int(Float(self.requestPool.count) / Float(self.concurrency) * 100)
// Log.event(conn.socket.socketFD, uuid: conn.socket.uuid, eventName: "connection add", oldValue: oldPressure, newValue: newPressure)
}
}
private func removeConnection(conn: WrappedConnection) {
dispatch_sync(controlQueue) {
let oldPressure = Int(Float(self.requestPool.count) / Float(self.concurrency) * 100)
self.requestPool.remove(conn)
let newPressure = Int(Float(self.requestPool.count) / Float(self.concurrency) * 100)
// Log.event(conn.socket.socketFD, uuid: conn.socket.uuid, eventName: "connection remove", oldValue: oldPressure, newValue: newPressure)
}
}
// MARK: - ListenerSocketDelegate
func shouldAcceptConnectionOnSocket(socket: ListenerSocket) -> Bool {
return requestPool.count < concurrency
}
func didAcceptConnectionOnSocket(socket: ListenerSocket, forChildSocket ioSocket: IOSocket) {
guard status == .Running else { return }
if var connection = delegate?.connectionForSocket(ioSocket) {
connection.delegate = self
addConnection(WrappedConnection(connection: connection))
dispatch_async(requestQueue) {
ioSocket.attach()
connection.start()
}
}
else {
ioSocket.detach()
}
}
func socketDidClose(socket: ListenerSocket) {
dispatch_async(dispatch_get_main_queue()) {
exit(0)
}
}
// MARK: - ConnectionDelegate
public func didCompleteConnection(connection: Connection) {
removeConnection(WrappedConnection(connection: connection))
}
}
| mit | db6aec3c6b72402d54413e289c4ead51 | 27.771654 | 147 | 0.647236 | 4.360382 | false | false | false | false |
kbelter/BubblePictures | BubblePictures/Classes/Structs/BPLayoutConfigurator.swift | 1 | 2041 | //
// BPLayoutConfigurator.swift
// Pods
//
// Created by Kevin Belter on 1/2/17.
//
//
import UIKit
public struct BPLayoutConfigurator {
var backgroundColorForTruncatedBubble: UIColor
var fontForBubbleTitles: UIFont
var colorForBubbleBorders: UIColor
var colorForBubbleTitles: UIColor
var maxCharactersForBubbleTitles: Int
var maxNumberOfBubbles: Int?
var displayForTruncatedCell: BPTruncatedCellDisplay?
var widthForBubbleBorders: CGFloat
var bubbleImageContentMode: UIView.ContentMode
var distanceInterBubbles: CGFloat?
var direction: BPDirection
var alignment: BPAlignment
public init(
backgroundColorForTruncatedBubble: UIColor = UIColor.gray,
fontForBubbleTitles: UIFont = UIFont.systemFont(ofSize: 15.0),
colorForBubbleBorders: UIColor = UIColor.white,
colorForBubbleTitles: UIColor = UIColor.white,
maxCharactersForBubbleTitles: Int = 3,
maxNumberOfBubbles: Int? = nil,
displayForTruncatedCell: BPTruncatedCellDisplay? = nil,
widthForBubbleBorders: CGFloat = 1.0,
bubbleImageContentMode: UIView.ContentMode = .scaleAspectFill,
distanceInterBubbles: CGFloat? = nil,
direction: BPDirection = .leftToRight,
alignment: BPAlignment = .left) {
self.backgroundColorForTruncatedBubble = backgroundColorForTruncatedBubble
self.fontForBubbleTitles = fontForBubbleTitles
self.colorForBubbleBorders = colorForBubbleBorders
self.colorForBubbleTitles = colorForBubbleTitles
self.maxCharactersForBubbleTitles = maxCharactersForBubbleTitles < 1 ? 1 : maxCharactersForBubbleTitles
self.maxNumberOfBubbles = maxNumberOfBubbles
self.displayForTruncatedCell = displayForTruncatedCell
self.widthForBubbleBorders = widthForBubbleBorders
self.bubbleImageContentMode = bubbleImageContentMode
self.distanceInterBubbles = distanceInterBubbles
self.direction = direction
self.alignment = alignment
}
}
| mit | ea93b2184d21222fef8e7827be00b0e6 | 39.019608 | 111 | 0.740813 | 4.894484 | false | false | false | false |
MaorS/macOS-PasswordManager | Pods/CSV.swift/Sources/CSVReader.swift | 1 | 13727 | //
// CSVReader.swift
// CSV
//
// Created by Yasuhiro Hatta on 2016/06/11.
// Copyright © 2016 yaslab. All rights reserved.
//
import Foundation
internal let LF: UnicodeScalar = "\n"
internal let CR: UnicodeScalar = "\r"
internal let DQUOTE: UnicodeScalar = "\""
internal let DQUOTE_STR: String = "\""
internal let DQUOTE2_STR: String = "\"\""
internal let defaultHasHeaderRow = false
internal let defaultTrimFields = false
internal let defaultDelimiter: UnicodeScalar = ","
internal let defaultWhitespaces = CharacterSet.whitespaces
/// No overview available.
public class CSVReader {
/// No overview available.
public struct Configuration {
/// `true` if the CSV has a header row, otherwise `false`. Default: `false`.
public var hasHeaderRow: Bool
/// No overview available.
public var trimFields: Bool
/// Default: `","`.
public var delimiter: UnicodeScalar
/// No overview available.
public var whitespaces: CharacterSet
/// No overview available.
internal init(
hasHeaderRow: Bool,
trimFields: Bool,
delimiter: UnicodeScalar,
whitespaces: CharacterSet) {
self.hasHeaderRow = hasHeaderRow
self.trimFields = trimFields
self.delimiter = delimiter
var whitespaces = whitespaces
_ = whitespaces.remove(delimiter)
self.whitespaces = whitespaces
}
}
fileprivate var iterator: AnyIterator<UnicodeScalar>
public let configuration: Configuration
public fileprivate (set) var error: Error?
fileprivate var back: UnicodeScalar?
fileprivate var fieldBuffer = String.UnicodeScalarView()
fileprivate var currentRowIndex: Int = 0
fileprivate var currentFieldIndex: Int = 0
/// CSV header row. To set a value for this property,
/// you set `true` to `headerRow` in initializer.
public private (set) var headerRow: [String]?
public fileprivate (set) var currentRow: [String]?
internal init<T: IteratorProtocol>(
iterator: T,
configuration: Configuration
) throws where T.Element == UnicodeScalar {
self.iterator = AnyIterator(iterator)
self.configuration = configuration
if configuration.hasHeaderRow {
guard let headerRow = readRow() else {
throw CSVError.cannotReadHeaderRow
}
self.headerRow = headerRow
}
}
}
extension CSVReader {
/// Create an instance with `InputStream`.
///
/// - parameter stream: An `InputStream` object. If the stream is not open,
/// initializer opens automatically.
/// - parameter codecType: A `UnicodeCodec` type for `stream`.
/// - parameter hasHeaderRow: `true` if the CSV has a header row, otherwise `false`. Default: `false`.
/// - parameter delimiter: Default: `","`.
public convenience init<T: UnicodeCodec>(
stream: InputStream,
codecType: T.Type,
hasHeaderRow: Bool = defaultHasHeaderRow,
trimFields: Bool = defaultTrimFields,
delimiter: UnicodeScalar = defaultDelimiter,
whitespaces: CharacterSet = defaultWhitespaces
) throws where T.CodeUnit == UInt8 {
let reader = try BinaryReader(stream: stream, endian: .unknown, closeOnDeinit: true)
let input = reader.makeUInt8Iterator()
let iterator = UnicodeIterator(input: input, inputEncodingType: codecType)
let config = Configuration(hasHeaderRow: hasHeaderRow,
trimFields: trimFields,
delimiter: delimiter,
whitespaces: whitespaces)
try self.init(iterator: iterator, configuration: config)
input.errorHandler = { [unowned self] in self.errorHandler(error: $0) }
iterator.errorHandler = { [unowned self] in self.errorHandler(error: $0) }
}
/// Create an instance with `InputStream`.
///
/// - parameter stream: An `InputStream` object. If the stream is not open,
/// initializer opens automatically.
/// - parameter codecType: A `UnicodeCodec` type for `stream`.
/// - parameter endian: Endian to use when reading a stream. Default: `.big`.
/// - parameter hasHeaderRow: `true` if the CSV has a header row, otherwise `false`. Default: `false`.
/// - parameter delimiter: Default: `","`.
public convenience init<T: UnicodeCodec>(
stream: InputStream,
codecType: T.Type,
endian: Endian = .big,
hasHeaderRow: Bool = defaultHasHeaderRow,
trimFields: Bool = defaultTrimFields,
delimiter: UnicodeScalar = defaultDelimiter,
whitespaces: CharacterSet = defaultWhitespaces
) throws where T.CodeUnit == UInt16 {
let reader = try BinaryReader(stream: stream, endian: endian, closeOnDeinit: true)
let input = reader.makeUInt16Iterator()
let iterator = UnicodeIterator(input: input, inputEncodingType: codecType)
let config = Configuration(hasHeaderRow: hasHeaderRow,
trimFields: trimFields,
delimiter: delimiter,
whitespaces: whitespaces)
try self.init(iterator: iterator, configuration: config)
input.errorHandler = { [unowned self] in self.errorHandler(error: $0) }
iterator.errorHandler = { [unowned self] in self.errorHandler(error: $0) }
}
/// Create an instance with `InputStream`.
///
/// - parameter stream: An `InputStream` object. If the stream is not open,
/// initializer opens automatically.
/// - parameter codecType: A `UnicodeCodec` type for `stream`.
/// - parameter endian: Endian to use when reading a stream. Default: `.big`.
/// - parameter hasHeaderRow: `true` if the CSV has a header row, otherwise `false`. Default: `false`.
/// - parameter delimiter: Default: `","`.
public convenience init<T: UnicodeCodec>(
stream: InputStream,
codecType: T.Type,
endian: Endian = .big,
hasHeaderRow: Bool = defaultHasHeaderRow,
trimFields: Bool = defaultTrimFields,
delimiter: UnicodeScalar = defaultDelimiter,
whitespaces: CharacterSet = defaultWhitespaces
) throws where T.CodeUnit == UInt32 {
let reader = try BinaryReader(stream: stream, endian: endian, closeOnDeinit: true)
let input = reader.makeUInt32Iterator()
let iterator = UnicodeIterator(input: input, inputEncodingType: codecType)
let config = Configuration(hasHeaderRow: hasHeaderRow,
trimFields: trimFields,
delimiter: delimiter,
whitespaces: whitespaces)
try self.init(iterator: iterator, configuration: config)
input.errorHandler = { [unowned self] in self.errorHandler(error: $0) }
iterator.errorHandler = { [unowned self] in self.errorHandler(error: $0) }
}
/// Create an instance with `InputStream`.
///
/// - parameter stream: An `InputStream` object. If the stream is not open,
/// initializer opens automatically.
/// - parameter hasHeaderRow: `true` if the CSV has a header row, otherwise `false`. Default: `false`.
/// - parameter delimiter: Default: `","`.
public convenience init(
stream: InputStream,
hasHeaderRow: Bool = defaultHasHeaderRow,
trimFields: Bool = defaultTrimFields,
delimiter: UnicodeScalar = defaultDelimiter,
whitespaces: CharacterSet = defaultWhitespaces
) throws {
try self.init(
stream: stream,
codecType: UTF8.self,
hasHeaderRow: hasHeaderRow,
trimFields: trimFields,
delimiter: delimiter,
whitespaces: whitespaces)
}
/// Create an instance with CSV string.
///
/// - parameter string: An CSV string.
/// - parameter hasHeaderRow: `true` if the CSV has a header row, otherwise `false`. Default: `false`.
/// - parameter delimiter: Default: `","`.
public convenience init(
string: String,
hasHeaderRow: Bool = defaultHasHeaderRow,
trimFields: Bool = defaultTrimFields,
delimiter: UnicodeScalar = defaultDelimiter,
whitespaces: CharacterSet = defaultWhitespaces
) throws {
let iterator = string.unicodeScalars.makeIterator()
let config = Configuration(hasHeaderRow: hasHeaderRow,
trimFields: trimFields,
delimiter: delimiter,
whitespaces: whitespaces)
try self.init(iterator: iterator, configuration: config)
}
private func errorHandler(error: Error) {
//configuration.fileInputErrorHandler?(error, currentRowIndex, currentFieldIndex)
self.error = error
}
}
// MARK: - Parse CSV
extension CSVReader {
fileprivate func readRow() -> [String]? {
currentFieldIndex = 0
var c = moveNext()
if c == nil {
return nil
}
var row = [String]()
var field: String
var end: Bool
while true {
if configuration.trimFields {
// Trim the leading spaces
while c != nil && configuration.whitespaces.contains(c!) {
c = moveNext()
}
}
if c == nil {
(field, end) = ("", true)
} else if c == DQUOTE {
(field, end) = readField(quoted: true)
} else {
back = c
(field, end) = readField(quoted: false)
if configuration.trimFields {
// Trim the trailing spaces
field = field.trimmingCharacters(in: configuration.whitespaces)
}
}
row.append(field)
if end {
break
}
currentFieldIndex += 1
c = moveNext()
}
currentRowIndex += 1
currentRow = row
return row
}
private func readField(quoted: Bool) -> (String, Bool) {
fieldBuffer.removeAll(keepingCapacity: true)
while let c = moveNext() {
if quoted {
if c == DQUOTE {
var cNext = moveNext()
if configuration.trimFields {
// Trim the trailing spaces
while cNext != nil && configuration.whitespaces.contains(cNext!) {
cNext = moveNext()
}
}
if cNext == nil || cNext == CR || cNext == LF {
if cNext == CR {
let cNextNext = moveNext()
if cNextNext != LF {
back = cNextNext
}
}
// END ROW
return (String(fieldBuffer), true)
} else if cNext == configuration.delimiter {
// END FIELD
return (String(fieldBuffer), false)
} else if cNext == DQUOTE {
// ESC
fieldBuffer.append(DQUOTE)
} else {
// ERROR?
fieldBuffer.append(c)
}
} else {
fieldBuffer.append(c)
}
} else {
if c == CR || c == LF {
if c == CR {
let cNext = moveNext()
if cNext != LF {
back = cNext
}
}
// END ROW
return (String(fieldBuffer), true)
} else if c == configuration.delimiter {
// END FIELD
return (String(fieldBuffer), false)
} else {
fieldBuffer.append(c)
}
}
}
// END FILE
return (String(fieldBuffer), true)
}
private func moveNext() -> UnicodeScalar? {
if back != nil {
defer {
back = nil
}
return back
}
return iterator.next()
}
}
//extension CSVReader {
//
// public func enumerateRows(_ block: (([String], [String]?, inout Bool) throws -> Void)) throws {
// var stop = false
// while let row = readRow() {
// try block(row, headerRow, &stop)
// if stop {
// break
// }
// }
// if let error = error {
// throw error
// }
// }
//
//}
extension CSVReader: IteratorProtocol {
@discardableResult
public func next() -> [String]? {
return readRow()
}
}
extension CSVReader {
public subscript(key: String) -> String? {
guard let header = headerRow else {
fatalError("CSVReader.headerRow must not be nil")
}
guard let index = header.index(of: key) else {
return nil
}
guard let row = currentRow else {
fatalError("CSVReader.currentRow must not be nil")
}
if index >= row.count {
return nil
}
return row[index]
}
}
| mit | adcaf61ce55ecb843e0a26d5e2b6b064 | 33.401003 | 106 | 0.547501 | 5.355443 | false | true | false | false |
frootloops/swift | test/SILGen/import_as_member.swift | 1 | 3027 | // RUN: %target-swift-frontend -emit-silgen -I %S/../IDE/Inputs/custom-modules %s | %FileCheck %s
// REQUIRES: objc_interop
import ImportAsMember.A
import ImportAsMember.Class
public func returnGlobalVar() -> Double {
return Struct1.globalVar
}
// CHECK-LABEL: sil {{.*}}returnGlobalVar{{.*}} () -> Double {
// CHECK: %0 = global_addr @IAMStruct1GlobalVar : $*Double
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] %0 : $*Double
// CHECK: [[VAL:%.*]] = load [trivial] [[READ]] : $*Double
// CHECK: return [[VAL]] : $Double
// CHECK-NEXT: }
// N.B. Whether by design or due to a bug, nullable NSString globals
// still import as non-null.
public func returnStringGlobalVar() -> String {
return Panda.cutenessFactor
}
// CHECK-LABEL: sil {{.*}}returnStringGlobalVar{{.*}} () -> @owned String {
// CHECK: %0 = global_addr @PKPandaCutenessFactor : $*NSString
// CHECK: [[VAL:%.*]] = load [copy] %0 : $*NSString
// CHECK: [[BRIDGE:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: [[RESULT:%.*]] = apply [[BRIDGE]](
// CHECK: return [[RESULT]] : $String
// CHECK-NEXT: }
public func returnNullableStringGlobalVar() -> String? {
return Panda.cuddlynessFactor
}
// CHECK-LABEL: sil {{.*}}returnNullableStringGlobalVar{{.*}} () -> @owned Optional<String> {
// CHECK: %0 = global_addr @PKPandaCuddlynessFactor : $*NSString
// CHECK: [[VAL:%.*]] = load [copy] %0 : $*NSString
// CHECK: [[BRIDGE:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ
// CHECK: [[RESULT:%.*]] = apply [[BRIDGE]](
// CHECK: [[SOME:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[RESULT]]
// CHECK: return [[SOME]] : $Optional<String>
// CHECK-NEXT: }
// CHECK-LABEL: sil {{.*}}useClass{{.*}}
// CHECK: bb0([[D:%[0-9]+]] : $Double, [[OPTS:%[0-9]+]] : $SomeClass.Options):
public func useClass(d: Double, opts: SomeClass.Options) {
// CHECK: [[CTOR:%[0-9]+]] = function_ref @MakeIAMSomeClass : $@convention(c) (Double) -> @autoreleased SomeClass
// CHECK: [[OBJ:%[0-9]+]] = apply [[CTOR]]([[D]])
let o = SomeClass(value: d)
// CHECK: [[BORROWED_OBJ:%.*]] = begin_borrow [[OBJ]]
// CHECK: [[APPLY_FN:%[0-9]+]] = function_ref @IAMSomeClassApplyOptions : $@convention(c) (SomeClass, SomeClass.Options) -> ()
// CHECK: apply [[APPLY_FN]]([[BORROWED_OBJ]], [[OPTS]])
// CHECK: end_borrow [[BORROWED_OBJ]] from [[OBJ]]
// CHECK: destroy_value [[OBJ]]
o.applyOptions(opts)
}
extension SomeClass {
// CHECK-LABEL: sil hidden @_T0So9SomeClassC16import_as_memberEABSd6double_tcfc
// CHECK: bb0([[DOUBLE:%[0-9]+]] : $Double
// CHECK-NOT: value_metatype
// CHECK: [[FNREF:%[0-9]+]] = function_ref @MakeIAMSomeClass
// CHECK: apply [[FNREF]]([[DOUBLE]])
convenience init(double: Double) {
self.init(value: double)
}
}
public func useSpecialInit() -> Struct1 {
// FIXME: the below triggers an assert, due to number or params mismatch
// return Struct1(specialLabel:())
}
| apache-2.0 | fc9d73575ff5ce362683bbf9eaebb61f | 41.633803 | 128 | 0.64255 | 3.507532 | false | false | false | false |
KrishMunot/swift | test/SILGen/cf_members.swift | 1 | 10723 | // RUN: %target-swift-frontend -emit-silgen -I %S/../IDE/Inputs/custom-modules %s | FileCheck %s
// REQUIRES: objc_interop
import ImportAsMember
func makeMetatype() -> Struct1.Type { return Struct1.self }
// CHECK-LABEL: sil @_TF10cf_members3foo
public func foo(_ x: Double) {
// CHECK: bb0([[X:%.*]] : $Double):
// CHECK: [[GLOBALVAR:%.*]] = global_addr @IAMStruct1GlobalVar
// CHECK: [[ZZ:%.*]] = load [[GLOBALVAR]]
let zz = Struct1.globalVar
// CHECK: assign [[ZZ]] to [[GLOBALVAR]]
Struct1.globalVar = zz
// CHECK: [[Z:%.*]] = project_box
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1CreateSimple
// CHECK: apply [[FN]]([[X]])
var z = Struct1(value: x)
// The metatype expression should still be evaluated even if it isn't
// used.
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1CreateSimple
// CHECK: [[MAKE_METATYPE:%.*]] = function_ref @_TF10cf_members12makeMetatype
// CHECK: apply [[MAKE_METATYPE]]()
// CHECK: apply [[FN]]([[X]])
z = makeMetatype().init(value: x)
// CHECK: [[THUNK:%.*]] = function_ref @_TTOFVSC7Struct1CFT5valueSd_S_
// CHECK: [[SELF:%.*]] = metatype $@thin Struct1.Type
// CHECK: [[A:%.*]] = apply [[THUNK]]([[SELF]])
let a: (Double) -> Struct1 = Struct1.init(value:)
// CHECK: apply [[A]]([[X]])
z = a(x)
// TODO: Support @convention(c) references that only capture thin metatype
// let b: @convention(c) (Double) -> Struct1 = Struct1.init(value:)
// z = b(x)
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1InvertInPlace
// CHECK: apply [[FN]]([[Z]])
z.invert()
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1Rotate : $@convention(c) (@in Struct1, Double) -> Struct1
// CHECK: [[ZVAL:%.*]] = load [[Z]]
// CHECK: store [[ZVAL]] to [[ZTMP:%.*]] :
// CHECK: apply [[FN]]([[ZTMP]], [[X]])
z = z.translate(radians: x)
// CHECK: [[THUNK:%.*]] = function_ref [[THUNK_NAME:@_TTOFVSC7Struct19translateFT7radiansSd_S_]]
// CHECK: [[ZVAL:%.*]] = load [[Z]]
// CHECK: [[C:%.*]] = apply [[THUNK]]([[ZVAL]])
let c: (Double) -> Struct1 = z.translate(radians:)
// CHECK: apply [[C]]([[X]])
z = c(x)
// CHECK: [[THUNK:%.*]] = function_ref [[THUNK_NAME]]
// CHECK: thin_to_thick_function [[THUNK]]
let d: (Struct1) -> (Double) -> Struct1 = Struct1.translate(radians:)
z = d(z)(x)
// TODO: If we implement SE-0042, this should thunk the value Struct1 param
// to a const* param to the underlying C symbol.
//
// let e: @convention(c) (Struct1, Double) -> Struct1
// = Struct1.translate(radians:)
// z = e(z, x)
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1Scale
// CHECK: [[ZVAL:%.*]] = load [[Z]]
// CHECK: apply [[FN]]([[ZVAL]], [[X]])
z = z.scale(x)
// CHECK: [[THUNK:%.*]] = function_ref @_TTOFVSC7Struct15scaleFSdS_
// CHECK: [[ZVAL:%.*]] = load [[Z]]
// CHECK: [[F:%.*]] = apply [[THUNK]]([[ZVAL]])
let f = z.scale
// CHECK: apply [[F]]([[X]])
z = f(x)
// CHECK: [[THUNK:%.*]] = function_ref @_TTOFVSC7Struct15scaleFSdS_
// CHECK: thin_to_thick_function [[THUNK]]
let g = Struct1.scale
// CHECK: [[ZVAL:%.*]] = load [[Z]]
z = g(z)(x)
// TODO: If we implement SE-0042, this should directly reference the
// underlying C function.
// let h: @convention(c) (Struct1, Double) -> Struct1 = Struct1.scale
// z = h(z, x)
// CHECK: [[ZVAL:%.*]] = load [[Z]]
// CHECK: store [[ZVAL]] to [[ZTMP:%.*]] :
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetRadius : $@convention(c) (@in Struct1) -> Double
// CHECK: apply [[GET]]([[ZTMP]])
_ = z.radius
// CHECK: [[ZVAL:%.*]] = load [[Z]]
// CHECK: [[SET:%.*]] = function_ref @IAMStruct1SetRadius : $@convention(c) (Struct1, Double) -> ()
// CHECK: apply [[SET]]([[ZVAL]], [[X]])
z.radius = x
// CHECK: [[ZVAL:%.*]] = load [[Z]]
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetAltitude : $@convention(c) (Struct1) -> Double
// CHECK: apply [[GET]]([[ZVAL]])
_ = z.altitude
// CHECK: [[SET:%.*]] = function_ref @IAMStruct1SetAltitude : $@convention(c) (@inout Struct1, Double) -> ()
// CHECK: apply [[SET]]([[Z]], [[X]])
z.altitude = x
// CHECK: [[ZVAL:%.*]] = load [[Z]]
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetMagnitude : $@convention(c) (Struct1) -> Double
// CHECK: apply [[GET]]([[ZVAL]])
_ = z.magnitude
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1StaticMethod
// CHECK: apply [[FN]]()
var y = Struct1.staticMethod()
// CHECK: [[THUNK:%.*]] = function_ref @_TTOZFVSC7Struct112staticMethodFT_Vs5Int32
// CHECK: [[SELF:%.*]] = metatype
// CHECK: [[I:%.*]] = apply [[THUNK]]([[SELF]])
let i = Struct1.staticMethod
// CHECK: apply [[I]]()
y = i()
// TODO: Support @convention(c) references that only capture thin metatype
// let j: @convention(c) () -> Int32 = Struct1.staticMethod
// y = j()
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetProperty
// CHECK: apply [[GET]]()
_ = Struct1.property
// CHECK: [[SET:%.*]] = function_ref @IAMStruct1StaticSetProperty
// CHECK: apply [[SET]](%{{[0-9]+}})
Struct1.property = y
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetOnlyProperty
// CHECK: apply [[GET]]()
_ = Struct1.getOnlyProperty
// CHECK: [[MAKE_METATYPE:%.*]] = function_ref @_TF10cf_members12makeMetatype
// CHECK: apply [[MAKE_METATYPE]]()
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetProperty
// CHECK: apply [[GET]]()
_ = makeMetatype().property
// CHECK: [[MAKE_METATYPE:%.*]] = function_ref @_TF10cf_members12makeMetatype
// CHECK: apply [[MAKE_METATYPE]]()
// CHECK: [[SET:%.*]] = function_ref @IAMStruct1StaticSetProperty
// CHECK: apply [[SET]](%{{[0-9]+}})
makeMetatype().property = y
// CHECK: [[MAKE_METATYPE:%.*]] = function_ref @_TF10cf_members12makeMetatype
// CHECK: apply [[MAKE_METATYPE]]()
// CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetOnlyProperty
// CHECK: apply [[GET]]()
_ = makeMetatype().getOnlyProperty
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1SelfComesLast : $@convention(c) (Double, Struct1) -> ()
// CHECK: [[ZVAL:%.*]] = load [[Z]]
// CHECK: apply [[FN]]([[X]], [[ZVAL]])
z.selfComesLast(x: x)
let k: (Double) -> () = z.selfComesLast(x:)
k(x)
let l: (Struct1) -> (Double) -> () = Struct1.selfComesLast(x:)
l(z)(x)
// TODO: If we implement SE-0042, this should thunk to reorder the arguments.
// let m: @convention(c) (Struct1, Double) -> () = Struct1.selfComesLast(x:)
// m(z, x)
// CHECK: [[FN:%.*]] = function_ref @IAMStruct1SelfComesThird : $@convention(c) (Int32, Float, Struct1, Double) -> ()
// CHECK: [[ZVAL:%.*]] = load [[Z]]
// CHECK: apply [[FN]]({{.*}}, {{.*}}, [[ZVAL]], [[X]])
z.selfComesThird(a: y, b: 0, x: x)
let n: (Int32, Float, Double) -> () = z.selfComesThird(a:b:x:)
n(y, 0, x)
let o: (Struct1) -> (Int32, Float, Double) -> ()
= Struct1.selfComesThird(a:b:x:)
o(z)(y, 0, x)
// TODO: If we implement SE-0042, this should thunk to reorder the arguments.
// let p: @convention(c) (Struct1, Int, Float, Double) -> ()
// = Struct1.selfComesThird(a:b:x:)
// p(z, y, 0, x)
}
// CHECK-LABEL: sil shared [thunk] @_TTOFVSC7Struct1CfT5valueSd_S_
// CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $@thin Struct1.Type):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1CreateSimple
// CHECK: [[RET:%.*]] = apply [[CFUNC]]([[X]])
// CHECK: return [[RET]]
// CHECK-LABEL: sil shared [thunk] @_TTOFVSC7Struct19translatefT7radiansSd_S_
// CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1):
// CHECK: store [[SELF]] to [[TMP:%.*]] :
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1Rotate
// CHECK: [[RET:%.*]] = apply [[CFUNC]]([[TMP]], [[X]])
// CHECK: return [[RET]]
// CHECK-LABEL: sil shared [thunk] @_TTOFVSC7Struct15scalefSdS_
// CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1Scale
// CHECK: [[RET:%.*]] = apply [[CFUNC]]([[SELF]], [[X]])
// CHECK: return [[RET]]
// CHECK-LABEL: sil shared [thunk] @_TTOZFVSC7Struct112staticMethodfT_Vs5Int32
// CHECK: bb0([[SELF:%.*]] : $@thin Struct1.Type):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1StaticMethod
// CHECK: [[RET:%.*]] = apply [[CFUNC]]()
// CHECK: return [[RET]]
// CHECK-LABEL: sil shared [thunk] @_TTOFVSC7Struct113selfComesLastfT1xSd_T_
// CHECK: bb0([[X:%.*]] : $Double, [[SELF:%.*]] : $Struct1):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1SelfComesLast
// CHECK: apply [[CFUNC]]([[X]], [[SELF]])
// CHECK-LABEL: sil shared [thunk] @_TTOFVSC7Struct114selfComesThirdfT1aVs5Int321bSf1xSd_T_
// CHECK: bb0([[X:%.*]] : $Int32, [[Y:%.*]] : $Float, [[Z:%.*]] : $Double, [[SELF:%.*]] : $Struct1):
// CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1SelfComesThird
// CHECK: apply [[CFUNC]]([[X]], [[Y]], [[SELF]], [[Z]])
// CHECK-LABEL: sil @_TF10cf_members3bar
public func bar(_ x: Double) {
// CHECK: function_ref @CCPowerSupplyCreate : $@convention(c) (Double) -> @owned CCPowerSupply
let ps = CCPowerSupply(watts: x)
// CHECK: function_ref @CCRefrigeratorCreate : $@convention(c) (CCPowerSupply) -> @owned CCRefrigerator
let fridge = CCRefrigerator(powerSupply: ps)
// CHECK: function_ref @CCRefrigeratorOpen : $@convention(c) (CCRefrigerator) -> ()
fridge.open()
// CHECK: function_ref @CCRefrigeratorGetPowerSupply : $@convention(c) (CCRefrigerator) -> @autoreleased CCPowerSupply
let ps2 = fridge.powerSupply
// CHECK: function_ref @CCRefrigeratorSetPowerSupply : $@convention(c) (CCRefrigerator, CCPowerSupply) -> ()
fridge.powerSupply = ps2
let a: (Double) -> CCPowerSupply = CCPowerSupply.init(watts:)
let _ = a(x)
let b: (CCRefrigerator) -> () -> () = CCRefrigerator.open
b(fridge)()
let c = fridge.open
c()
}
// CHECK-LABEL: sil @_TF10cf_members16importAsProtocolFPSo8IAMProto_T_
public func importAsProtocol(_ x: IAMProto_t) {
// CHECK: function_ref @mutateSomeState : $@convention(c) <τ_0_0 where τ_0_0 : IAMProto> (τ_0_0) -> ()
x.mutateSomeState()
// CHECK: function_ref @mutateSomeStateWithParameter : $@convention(c) <τ_0_0 where τ_0_0 : IAMProto> (τ_0_0, Int) -> ()
x.mutateSomeState(withParameter: 0)
// CHECK: function_ref @mutateSomeStateWithFirstParameter : $@convention(c) <τ_0_0 where τ_0_0 : IAMProto> (Int, τ_0_0) -> ()
x.mutateSomeState(withFirstParameter: 0)
// CHECK: function_ref @getSomeValue : $@convention(c) <τ_0_0 where τ_0_0 : IAMProto> (τ_0_0) -> Int32
let y = x.someValue
// CHECK: function_ref @setSomeValue : $@convention(c) <τ_0_0 where τ_0_0 : IAMProto> (τ_0_0, Int32) -> Int32
x.someValue = y
}
| apache-2.0 | eca39bbba041ce57bd137c61437ce8b9 | 41.324111 | 127 | 0.590213 | 3.331674 | false | false | false | false |
inspace-io/Social-Service-Browser | Sources/Clients/SocialServiceBrowserDropboxClient.swift | 1 | 9716 | //
// SocialServiceBrowserDropboxClient.swift
// Social Service Browser
//
// Created by Michal Zaborowski on 25.09.2017.
// Copyright © 2017 Inspace. All rights reserved.
//
import Foundation
import SwiftyDropbox
import Alamofire
#if IMPORT_SOCIAL_BROWSER_FRAMEWORK
import SocialServiceBrowserFramework
#endif
extension Alamofire.Request: SocialServiceBrowserOperationPerformable {
public func run() {
resume()
}
}
private let globalDropboxOperationQueue = OperationQueue()
class DropboxBlockOperation: BlockOperation, SocialServiceBrowserOperationPerformable {
public func run() {
globalDropboxOperationQueue.addOperation(self)
}
}
extension CallError: Error {
}
extension Files.Metadata: SocialServiceBrowerNode {
public var nodeId: String? {
if let file = self as? Files.FileMetadata {
return file.id
}
if let folder = self as? Files.FolderMetadata {
return folder.id
}
return nil
}
public var isImageFile: Bool {
guard !isDirectory else {
return false
}
if name.range(of: "\\.jpeg|\\.jpg|\\.JPEG|\\.JPG|\\.png|\\.PNG|\\.TIFF|\\.tiff", options: .regularExpression, range: nil, locale: nil) != nil {
return true
}
return false
}
public var isVideoFile: Bool {
guard !isDirectory else {
return false
}
if name.range(of: "\\.mov|\\.mp4|\\.mpv|\\.3gp|\\.MOV|\\.MP4|\\.MPV|\\.3GP", options: .regularExpression, range: nil, locale: nil) != nil {
return true
}
return false
}
public var isDirectory: Bool {
return self is Files.FolderMetadata
}
public var nodeName: String {
return name
}
public var path: String? {
return pathLower
}
}
private var filesAssociatedFilterObjectHandle: UInt8 = 0
extension Files.ListFolderResult: SocialServiceBrowerNodeListResponse {
var filter: SocialServiceBrowserFilterType? {
get {
guard let filter = objc_getAssociatedObject(self, &filesAssociatedFilterObjectHandle) as? SocialServiceBrowserFilterType else {
return nil
}
return filter
}
set {
objc_setAssociatedObject(self, &filesAssociatedFilterObjectHandle, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public var nodes: [SocialServiceBrowerNode] {
guard let filter = filter else {
return entries
}
switch filter {
case .images: return entries.filter({ $0.isImageFile || $0.isDirectory })
case .video: return entries.filter({ $0.isVideoFile || $0.isDirectory })
default: return entries
}
}
public var hasMoreResults: Bool {
return hasMore
}
public var nextCursorPath: String? {
return cursor
}
}
extension DownloadRequestFile: SocialServiceBrowserOperationPerformable {
public func run() {
request.run()
}
}
public class SocialServiceBrowserDropboxClient: SocialServiceBrowserClient {
public var serviceName: String = "Dropbox"
public var filter: SocialServiceBrowserFilterType = .none
private var client: DropboxClient? {
return DropboxClientsManager.authorizedClient
}
public init() {
}
public func requestRootNode(with completion: @escaping (SocialServiceBrowserResult<SocialServiceBrowerNodeListResponse, Error>) -> Void) -> SocialServiceBrowserOperationPerformable? {
return client?.files.listFolder(path: "").response(completionHandler: { [weak self] response, error in
if let error = error {
completion(SocialServiceBrowserResult.failure(NSError(domain: "SocialServiceBrowserDropboxClientDomain", code: -1, userInfo: [NSLocalizedDescriptionKey: error.description] as [String: Any])))
} else if let response = response {
response.filter = self?.filter
completion(SocialServiceBrowserResult.success(response))
} else {
fatalError()
}
}).request
}
public func requestChildren(for node: SocialServiceBrowerNode, withCompletion completion: @escaping (SocialServiceBrowserResult<SocialServiceBrowerNodeListResponse, Error>) -> Void) -> SocialServiceBrowserOperationPerformable? {
return client?.files.listFolder(path: node.path!).response(completionHandler: { [weak self] response, error in
if let error = error {
completion(SocialServiceBrowserResult.failure(error))
} else if let response = response {
response.filter = self?.filter
completion(SocialServiceBrowserResult.success(response))
} else {
fatalError()
}
}).request
}
public func requestThumbnail(for node: SocialServiceBrowerNode, withCompletion completion: @escaping (SocialServiceBrowserResult<UIImage, Error>) -> Void) -> SocialServiceBrowserOperationPerformable? {
let filePath = NSTemporaryDirectory().appending("/thumb_\(node.nodeName)")
if let nodePath = node.path as NSString?, let image = UIImage(named: "page_white_\(nodePath.pathExtension)", in: Bundle(for: type(of: self)), compatibleWith: nil) {
return DropboxBlockOperation {
completion(SocialServiceBrowserResult.success(image))
}
}
if !FileManager.default.fileExists(atPath: filePath) {
return client?.files.getThumbnail(path: node.path!, format: .jpeg, size: .w128h128, overwrite: true, destination: { (_, _) -> URL in
return URL(fileURLWithPath: filePath)
}).response(completionHandler: { (metadata, error) in
if let error = error,
case .routeError(let boxed, _, _, _) = error,
case .unsupportedExtension = boxed.unboxed {
if let nodePath = node.path as NSString?, let image = UIImage(named: "page_white_\(nodePath.pathExtension)", in: Bundle(for: type(of: self)), compatibleWith: nil) {
DispatchQueue.global(qos: .background).async {
try? UIImagePNGRepresentation(image)?.write(to: URL(fileURLWithPath: filePath))
}
completion(SocialServiceBrowserResult.success(image))
} else {
let image = UIImage(named: "page_white_import", in: Bundle(for: type(of: self)), compatibleWith: nil)!
DispatchQueue.global(qos: .background).async {
try? UIImagePNGRepresentation(image)?.write(to: URL(fileURLWithPath: filePath))
}
completion(SocialServiceBrowserResult.success(image))
}
} else if let error = error {
completion(SocialServiceBrowserResult.failure(error))
} else if let url = metadata?.1 {
DispatchQueue.global(qos: .background).async {
if let image = UIImage(contentsOfFile: url.path) {
DispatchQueue.main.async {
completion(SocialServiceBrowserResult.success(image))
}
} else {
DispatchQueue.main.async {
completion(SocialServiceBrowserResult.failure(NSError(domain: "SocialServiceBrowserDropboxClientDomain", code: -1, userInfo: [NSLocalizedDescriptionKey: "Failed to download image"] as [String: Any])))
}
}
}
}
}).request
}
return DropboxBlockOperation {
let image = UIImage(contentsOfFile: filePath)
if let image = image {
completion(.success(image))
} else {
completion(.success(UIImage()))
}
}
}
public func requestData(for node: SocialServiceBrowerNode, withCompletion: @escaping (SocialServiceBrowserResult<URL, Error>) -> Void) -> SocialServiceBrowserOperationPerformable? {
let documentsPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
guard let localPath = documentsPath?.appending("/\(node.nodeName)") else {
return nil
}
guard !FileManager.default.fileExists(atPath: localPath) else {
return DropboxBlockOperation {
OperationQueue.main.addOperation {
withCompletion(SocialServiceBrowserResult.success(URL(fileURLWithPath: localPath)))
}
}
}
let downloadRequest = client?.files?.download(path: node.path!, rev: nil, overwrite: true, destination: { (_, _) -> URL in
return URL(fileURLWithPath: localPath)
}).response(completionHandler: { (url, error) in
if let error = error {
withCompletion(SocialServiceBrowserResult.failure(NSError(domain: "SocialServiceBrowserDropboxClientDomain", code: -1, userInfo: [NSLocalizedDescriptionKey: error.description] as [String: Any])))
} else if let url = url {
withCompletion(SocialServiceBrowserResult.success(url.1))
} else {
fatalError()
}
})
return downloadRequest
}
}
| apache-2.0 | 6acfb7a4172adc4b91e36ccdedc9d7f2 | 38.815574 | 232 | 0.601132 | 5.337912 | false | false | false | false |
regexident/EventBus | EventBus/EventBus.swift | 1 | 12126 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import Foundation
public protocol EventBusProtocol: class {
var options: Options { get }
}
/// A type-safe event bus.
public class EventBus: EventBusProtocol {
internal struct WeakBox: Hashable {
internal weak var inner: AnyObject?
internal init(_ inner: AnyObject) {
self.inner = inner
}
internal static func == (lhs: WeakBox, rhs: WeakBox) -> Bool {
return lhs.inner === rhs.inner
}
internal static func == (lhs: WeakBox, rhs: AnyObject) -> Bool {
return lhs.inner === rhs
}
internal var hashValue: Int {
guard let inner = self.inner else {
return 0
}
return ObjectIdentifier(inner).hashValue
}
}
typealias WeakSet = Set<WeakBox>
public static var isStrict: Bool = false
/// A global shared event bus configured using default options.
public static let shared: EventBus = EventBus()
/// The event bus' configuration options.
public let options: Options
/// The event bus' label used for debugging.
public let label: String?
internal var errorHandler: ErrorHandler = DefaultErrorHandler()
internal var logHandler: LogHandler = DefaultLogHandler()
fileprivate var knownTypes: [ObjectIdentifier: Any] = [:]
fileprivate var registered: Set<ObjectIdentifier> = []
fileprivate var subscribed: [ObjectIdentifier: WeakSet] = [:]
fileprivate var chained: [ObjectIdentifier: WeakSet] = [:]
fileprivate let lock: NSRecursiveLock = .init()
fileprivate let notificationQueue: DispatchQueue
/// Creates an event bus with a given configuration and dispatch notificationQueue.
///
/// - Parameters:
/// - options: the event bus' options
/// - notificationQueue: the dispatch notificationQueue to notify subscribers on
public init(options: Options? = nil, label: String? = nil, notificationQueue: DispatchQueue = .global()) {
self.options = options ?? Options()
self.label = label
self.notificationQueue = notificationQueue
}
/// The event types the event bus is registered for.
public var registeredEventTypes: [Any] {
return self.registered.compactMap { self.knownTypes[$0] }
}
/// The event types the event bus has subscribers for.
public var subscribedEventTypes: [Any] {
return self.subscribed.keys.compactMap { self.knownTypes[$0] }
}
/// The event types the event bus has chains for.
public var chainedEventTypes: [Any] {
return self.chained.keys.compactMap { self.knownTypes[$0] }
}
@inline(__always)
fileprivate func warnIfNonClass<T>(_ subscriber: T) {
// Related bug: https://bugs.swift.org/browse/SR-4420:
guard !(type(of: subscriber as Any) is AnyClass) else {
return
}
self.errorHandler.eventBus(self, receivedNonClassSubscriber: type(of: subscriber))
}
@inline(__always)
fileprivate func warnIfUnknown<T>(_ eventType: T.Type) {
guard self.options.contains(.warnUnknown) else {
return
}
guard !self.registered.contains(ObjectIdentifier(eventType)) else {
return
}
self.errorHandler.eventBus(self, receivedUnknownEvent: eventType)
}
@inline(__always)
fileprivate func warnUnhandled<T>(_ eventType: T.Type) {
guard self.options.contains(.warnUnhandled) else {
return
}
self.errorHandler.eventBus(self, droppedUnhandledEvent: eventType)
}
@inline(__always)
fileprivate func logEvent<T>(_ eventType: T.Type) {
guard self.options.contains(.logEvents) else {
return
}
self.logHandler.eventBus(self, receivedEvent: eventType)
}
@inline(__always)
fileprivate func updateSubscribers<T>(for eventType: T.Type, closure: (inout WeakSet) -> ()) {
let identifier = ObjectIdentifier(eventType)
let subscribed = self.subscribed[identifier] ?? []
self.subscribed[identifier] = self.update(set: subscribed, closure: closure)
self.knownTypes[identifier] = String(describing: eventType)
}
@inline(__always)
fileprivate func updateChains<T>(for eventType: T.Type, closure: (inout WeakSet) -> ()) {
let identifier = ObjectIdentifier(eventType)
let chained = self.chained[identifier] ?? []
self.chained[identifier] = self.update(set: chained, closure: closure)
self.knownTypes[identifier] = String(describing: eventType)
}
@inline(__always)
fileprivate func update(set: WeakSet, closure: (inout WeakSet) -> ()) -> WeakSet? {
var mutableSet = set
closure(&mutableSet)
// Remove weak nil elements while we're at it:
let filteredSet = mutableSet.filter { $0.inner != nil }
return filteredSet.isEmpty ? nil : filteredSet
}
}
extension EventBus: EventRegistrable {
public func register<T>(forEvent eventType: T.Type) {
let identifier = ObjectIdentifier(eventType)
self.registered.insert(identifier)
self.knownTypes[identifier] = String(describing: eventType)
}
}
extension EventBus: EventSubscribable {
public func add<T>(subscriber: T, for eventType: T.Type) {
return self.add(subscriber: subscriber, for: eventType, options: self.options)
}
public func add<T>(subscriber: T, for eventType: T.Type, options: Options) {
self.warnIfNonClass(subscriber)
if options.contains(.warnUnknown) {
self.warnIfUnknown(eventType)
}
self.lock.with {
self.updateSubscribers(for: eventType) { subscribed in
subscribed.insert(WeakBox(subscriber as AnyObject))
}
}
}
public func remove<T>(subscriber: T, for eventType: T.Type) {
return self.remove(subscriber: subscriber, for: eventType, options: self.options)
}
public func remove<T>(subscriber: T, for eventType: T.Type, options: Options) {
self.warnIfNonClass(subscriber)
if options.contains(.warnUnknown) {
self.warnIfUnknown(eventType)
}
self.lock.with {
self.updateSubscribers(for: eventType) { subscribed in
while let index = subscribed.index(where: { $0 == (subscriber as AnyObject) }) {
subscribed.remove(at: index)
}
}
}
}
public func remove<T>(subscriber: T) {
return self.remove(subscriber: subscriber, options: self.options)
}
public func remove<T>(subscriber: T, options: Options) {
self.warnIfNonClass(subscriber)
self.lock.with {
for (identifier, subscribed) in self.subscribed {
self.subscribed[identifier] = self.update(set: subscribed) { subscribed in
while let index = subscribed.index(where: { $0 == (subscriber as AnyObject) }) {
subscribed.remove(at: index)
}
}
}
}
}
public func removeAllSubscribers() {
self.lock.with {
self.subscribed = [:]
}
}
internal func has<T>(subscriber: T, for eventType: T.Type) -> Bool {
return self.has(subscriber: subscriber, for: eventType, options: self.options)
}
internal func has<T>(subscriber: T, for eventType: T.Type, options: Options) -> Bool {
self.warnIfNonClass(subscriber)
if options.contains(.warnUnknown) {
self.warnIfUnknown(eventType)
}
return self.lock.with {
guard let subscribed = self.subscribed[ObjectIdentifier(eventType)] else {
return false
}
return subscribed.contains { $0 == (subscriber as AnyObject) }
}
}
}
extension EventBus: EventNotifiable {
@discardableResult
public func notify<T>(_ eventType: T.Type, closure: @escaping (T) -> ()) -> Bool {
return self.notify(eventType, options: self.options, closure: closure)
}
@discardableResult
public func notify<T>(_ eventType: T.Type, options: Options, closure: @escaping (T) -> ()) -> Bool {
if options.contains(.warnUnknown) {
self.warnIfUnknown(eventType)
}
self.logEvent(eventType)
return self.lock.with {
var handled: Int = 0
let identifier = ObjectIdentifier(eventType)
// Notify our direct subscribers:
if let subscribers = self.subscribed[identifier] {
for subscriber in subscribers.lazy.compactMap({ $0.inner as? T }) {
self.notificationQueue.async {
closure(subscriber)
}
}
handled += subscribers.count
}
// Notify our indirect subscribers:
if let chains = self.chained[identifier] {
for chain in chains.lazy.compactMap({ $0.inner as? EventNotifiable }) {
handled += chain.notify(eventType, closure: closure) ? 1 : 0
}
}
if (handled == 0) && options.contains(.warnUnhandled) {
self.warnUnhandled(eventType)
}
return handled > 0
}
}
}
extension EventBus: EventChainable {
public func attach<T>(chain: EventNotifiable, for eventType: T.Type) {
return self.attach(chain: chain, for: eventType, options: self.options)
}
public func attach<T>(chain: EventNotifiable, for eventType: T.Type, options: Options) {
if options.contains(.warnUnknown) {
self.warnIfUnknown(eventType)
}
self.lock.with {
self.updateChains(for: eventType) { chained in
chained.insert(WeakBox(chain as AnyObject))
}
}
}
public func detach<T>(chain: EventNotifiable, for eventType: T.Type) {
return self.detach(chain: chain, for: eventType, options: self.options)
}
public func detach<T>(chain: EventNotifiable, for eventType: T.Type, options: Options) {
if options.contains(.warnUnknown) {
self.warnIfUnknown(eventType)
}
self.lock.with {
self.updateChains(for: eventType) { chained in
chained.remove(WeakBox(chain as AnyObject))
}
}
}
public func detach(chain: EventNotifiable) {
self.lock.with {
for (identifier, chained) in self.chained {
self.chained[identifier] = self.update(set: chained) { chained in
chained.remove(WeakBox(chain as AnyObject))
}
}
}
}
public func detachAllChains() {
self.lock.with {
self.chained = [:]
}
}
internal func has<T>(chain: EventNotifiable, for eventType: T.Type) -> Bool {
return self.has(chain: chain, for: eventType, options: self.options)
}
internal func has<T>(chain: EventNotifiable, for eventType: T.Type, options: Options) -> Bool {
if options.contains(.warnUnknown) {
self.warnIfUnknown(eventType)
}
return self.lock.with {
guard let chained = self.chained[ObjectIdentifier(eventType)] else {
return false
}
return chained.contains { $0 == (chain as AnyObject) }
}
}
}
extension EventBus: CustomStringConvertible {
public var description: String {
var mutableSelf = self
return Swift.withUnsafePointer(to: &mutableSelf) { pointer in
let name = String(describing: type(of: self))
let address = String(format: "%p", pointer)
let label = self.label.map { " \"\($0)\"" } ?? ""
return "<\(name): \(address)\(label)>"
}
}
}
| mpl-2.0 | c715d0f39d0c6c57aeac8450b740506e | 34.046243 | 110 | 0.605393 | 4.536476 | false | false | false | false |
ideafamily/Emonar | Emonar/RecordViewController.swift | 1 | 14272 | //
// RecordViewController.swift
// Emonar
//
// Created by ZengJintao on 3/8/16.
// Copyright © 2016 ZengJintao. All rights reserved.
//
import UIKit
var timeSpan = 10.0
class RecordViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, EZMicrophoneDelegate, EZRecorderDelegate, EZAudioPlayerDelegate {
@IBOutlet weak var recordTableView: UITableView!
@IBOutlet weak var soundWaveView: EZAudioPlotGL!
@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var fileNameLabel: UILabel!
var datas:[EmotionData] = [EmotionData(emotion: "Analyzing", emotionDescription: "Sorry, Emonar doesn't understand your current emotion.Maybe input voice is too low", analyzed: false, startTime: nil)]
var datasIndex = 0
var timer:Timer?
var isRecording:Bool = false
let fileManager = FileManager.sharedInstance
var microphone:EZMicrophone!
var recorder: EZRecorder!
var player: EZAudioPlayer!
var beginTime:Date!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let session: AVAudioSession = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
try session.setActive(true)
} catch {
NSLog("Error setting up audio session category")
NSLog("Error setting up audio session active")
}
self.soundWaveView.backgroundColor = UIColor(red: 0.984, green: 0.71, blue: 0.365, alpha: 1)
self.soundWaveView.color = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
self.soundWaveView.plotType = EZPlotType.rolling
self.soundWaveView.shouldFill = true
self.soundWaveView.shouldMirror = true
self.soundWaveView.gain = 5
self.microphone = EZMicrophone(delegate: self)
self.player = EZAudioPlayer(delegate: self)
//
// Override the output to the speaker. Do this after creating the EZAudioPlayer
do {
try session.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
} catch {
NSLog("Error overriding output to the speaker")
}
self.navigationController?.isNavigationBarHidden = true
recordTableView.delegate = self
recordTableView.dataSource = self
recordTableView.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI))
recordButton.isSelected = false
// Do any additional setup after loading the view.
}
@nonobjc func microphone(_ microphone: EZMicrophone!, hasAudioReceived buffer: UnsafeMutablePointer<UnsafeMutablePointer<Float>>, withBufferSize bufferSize: UInt32, withNumberOfChannels numberOfChannels: UInt32) {
weak var weakSelf = self
runOnMainThread {
//
// All the audio plot needs is the buffer data (float*) and the size.
// Internally the audio plot will handle all the drawing related code,
// history management, and freeing its own resources. Hence, one badass
// line of code gets you a pretty plot :)
//
weakSelf!.soundWaveView.updateBuffer(buffer[0], withBufferSize: bufferSize)
}
}
func microphone(_ microphone: EZMicrophone!, hasBufferList bufferList: UnsafeMutablePointer<AudioBufferList>, withBufferSize bufferSize: UInt32, withNumberOfChannels numberOfChannels: UInt32) {
if self.isRecording && self.recorder != nil {
self.recorder.appendData(from: bufferList, withBufferSize: bufferSize)
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 && !isRecording {
//Initial cell
let cell = tableView.dequeueReusableCell(withIdentifier: "InitialTableViewCell", for: indexPath) as! InitialTableViewCell
cell.backgroundColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
cell.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI));
return cell
}
if datas[datas.count-1-indexPath.row].analyzed {
//Result cell
let cell = tableView.dequeueReusableCell(withIdentifier: "RecordTableViewCell", for: indexPath) as! RecordTableViewCell
cell.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI));
cell.emotionLabel.text = datas[datas.count-1-indexPath.row].emotion
cell.descriptionLabel.text = datas[datas.count-1-indexPath.row].emotionDescription
cell.backgroundColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
return cell
} else {
//Recording and Analyzing cell
let cell = tableView.dequeueReusableCell(withIdentifier: "AnalyzingTableViewCell", for: indexPath) as! AnalyzingTableViewCell
cell.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI));
cell.progressStart(datas[datas.count-1-indexPath.row].startTime!)
cell.backgroundColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
return cell
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datas.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 {
return 50
} else {
return 125
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.alpha = 0
UIView.animate(withDuration: 0.3, animations: { () -> Void in
cell.alpha = 1
})
}
@IBAction func cancelPressed(_ sender: UIButton) {
if isRecording {
self.microphone.stopFetchingAudio()
if (self.recorder != nil) {
self.recorder.closeAudioFile()
}
recordButton.isSelected = false
timer?.invalidate()
let elapsedTime = Date().timeIntervalSince(self.beginTime)
isRecording = false
self.recordTableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .automatic)
showSaveAlert(Tool.stringFromTimeInterval(elapsedTime))
} else {
self.dismiss(animated: true, completion: nil)
}
}
@IBAction func recordPressed(_ sender: UIButton) {
if !Tool.isConnectedToNetwork() {
let alertController = UIAlertController(title: "Please check your network connection", message: nil, preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Got it", style: UIAlertActionStyle.cancel, handler: nil))
self.present(alertController, animated: true, completion: nil)
} else {
if sender.isSelected == true {
sender.isSelected = false
timer!.invalidate()
isRecording = false
let elapsedTime = Date().timeIntervalSince(self.beginTime)
self.microphone.stopFetchingAudio()
if (self.recorder != nil) {
self.recorder.closeAudioFile()
}
runOnMainThread({
self.recordTableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .automatic)
self.showSaveAlert(Tool.stringFromTimeInterval(elapsedTime))
})
} else {
self.beginTime = Date()
sender.isSelected = true
isRecording = true
self.microphone.startFetchingAudio()
self.recorder = EZRecorder(url: self.testFilePathURL(), clientFormat: self.microphone.audioStreamBasicDescription(), fileType: EZRecorderFileType.WAV, delegate: self)
if datas.count > 1 {
datas.removeAll()
let currentData = EmotionData(emotion: "Analyzing", emotionDescription: "Sorry, Emonar doesn't understand your current emotion.Maybe input voice is too low", analyzed: false, startTime: nil)
datas.append(currentData)
}
datas[0].startTime = Date()
datasIndex = 0
runOnMainThread({
self.recordTableView.reloadData()
})
timer = Timer.scheduledTimer(timeInterval: timeSpan, target: self, selector: #selector(RecordViewController.timerFinished(_:)), userInfo: nil, repeats: true)
}
}
}
func runOnMainThread(_ block: @escaping () -> Void){
DispatchQueue.main.async {
block()
}
}
func applicationDocumentsDirectory() -> String? {
let paths: [AnyObject] = NSSearchPathForDirectoriesInDomains(Foundation.FileManager.SearchPathDirectory.documentDirectory, Foundation.FileManager.SearchPathDomainMask.userDomainMask, true) as [AnyObject]
if paths.count > 0 {
return paths[0] as? String
}
return nil
}
func filePath()->String{
return "\(self.applicationDocumentsDirectory()!)/\(fileManager.getAudioIndex()).wav"
}
func testFilePathURL() -> URL {
// print("content :\(content)")
return URL(fileURLWithPath: filePath())
}
func localFilePath() -> String {
return "/\(fileManager.getAudioIndex()).wav"
}
func timerFinished(_ timer: Timer) {
let localIndex = datasIndex
let currentData = EmotionData(emotion: "Analyzing\(datasIndex)",emotionDescription: "Description", analyzed: false, startTime: Date())
datas.append(currentData)
datasIndex += 1
runOnMainThread({
self.recordTableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .left)
})
APIWrapper.sharedInstance.startAnSessionAndSendAFile(filePath(), completion: { (object:Analysis_result_analysisSegments?) in
if object != nil {
let description = String.addString([object!.analysis.Mood.Composite.Secondary.Phrase,object!.analysis.Mood.Group11.Primary.Phrase,object!.analysis.Mood.Group11.Secondary.Phrase])
let modifiedDescription = description.substring(from: description.characters.index(description.startIndex, offsetBy: 1))
self.updateData(localIndex, content: object!.analysis.Mood.Composite.Primary.Phrase, description: modifiedDescription)
} else {
self.updateData(localIndex, content: "No Result", description: "Sorry, Emonar doesn't understand your current emotion.Maybe input voice is too low.")
}
})
if (self.recorder != nil && self.isRecording) {
self.isRecording = false
self.recorder.closeAudioFile()
fileManager.insertAudioToStorage(localFilePath())
self.recorder = EZRecorder(url: self.testFilePathURL(), clientFormat: self.microphone.audioStreamBasicDescription(), fileType: EZRecorderFileType.WAV, delegate: self)
isRecording = true
}
}
func updateData(_ localIndex:Int,content:String,description:String){
self.datas[localIndex].emotion = String.trimString(content)
self.datas[localIndex].analyzed = true
self.datas[localIndex].emotionDescription = description
let emotionData = self.datas[localIndex]
self.fileManager.insertEmotionDataToStorage(emotionData)
runOnMainThread({
self.recordTableView.reloadRows(at: [IndexPath(row: self.datas.count - localIndex - 1, section: 0)], with: .automatic)
})
}
deinit {
self.recordTableView = nil
}
func resetAllData() {
//1. delete all previous data
datas.removeAll()
//2. initial data
datas.append(EmotionData(emotion: "Analyzing", emotionDescription: "Sorry, Emonar doesn't understand your current emotion.Maybe input voice is too low", analyzed: false, startTime: nil))
datasIndex = 0
//3. reload data
runOnMainThread {
self.recordTableView.reloadData()
}
}
func showSaveAlert(_ recordLength:String) {
let alertController = UIAlertController(title: "Save your record?", message: nil, preferredStyle: UIAlertControllerStyle.alert)
alertController.addTextField { (name:UITextField) -> Void in
name.text = "New file"
}
let saveAction = UIAlertAction(title: "Save", style: .default) { (action:UIAlertAction) -> Void in
let fileName = alertController.textFields![0].text
print("save file: \(fileName!)")
self.fileManager.insertRecordFileToStorage(fileName!,recordLength: recordLength)
self.fileNameLabel.text = fileName!
self.timer?.invalidate()
//TODO: save the file
}
let deleteAction = UIAlertAction(title: "Delete", style: .default) { (action:UIAlertAction) -> Void in
//TODO: delete the file
self.timer?.invalidate()
// serlf.resetAllData()
}
alertController.addAction(saveAction)
alertController.addAction(deleteAction)
self.present(alertController, animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | ba78b4c2c4cda757c353893a50c01e9b | 39.427762 | 217 | 0.62105 | 5.153846 | false | false | false | false |
tkremenek/swift | test/DebugInfo/async-lifetime-extension.swift | 1 | 1320 | // RUN: %target-swift-frontend %s -emit-ir -g -o - \
// RUN: -module-name a -enable-experimental-concurrency -disable-availability-checking \
// RUN: | %FileCheck %s --check-prefix=CHECK
// REQUIRES: concurrency
// Test that lifetime extension preserves a dbg.declare for "n" in the resume
// funclet.
// CHECK-LABEL: define {{.*}} void @"$s1a4fiboyS2iYaFTQ0_"
// CHECK-NEXT: entryresume.0:
// CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[RHS:[0-9]+]], {{.*}}!DIExpression(DW_OP
// CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[LHS:[0-9]+]], {{.*}}!DIExpression(DW_OP
// CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[R:[0-9]+]], {{.*}}!DIExpression(DW_OP
// CHECK-NEXT: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[N:[0-9]+]], {{.*}}!DIExpression(DW_OP
// CHECK-NOT: {{ ret }}
// CHECK: call void asm sideeffect ""
// CHECK: ![[RHS]] = !DILocalVariable(name: "rhs"
// CHECK: ![[LHS]] = !DILocalVariable(name: "lhs"
// CHECK: ![[R]] = !DILocalVariable(name: "retval"
// CHECK: ![[N]] = !DILocalVariable(name: "n"
public func fibo(_ n: Int) async -> Int {
var retval = n
if retval < 2 { return 1 }
retval = retval - 1
let lhs = await fibo(retval - 1)
let rhs = await fibo(retval - 2)
return lhs + rhs + retval
}
| apache-2.0 | 48327daaf3db9da0f71c00086b79770d | 46.142857 | 113 | 0.627273 | 3.188406 | false | false | false | false |
Mobilette/MobiletteDashboardiOS | Pods/OAuthSwift/OAuthSwift/OAuthSwiftClient.swift | 1 | 11842 | //
// OAuthSwiftClient.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/21/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import Foundation
var OAuthSwiftDataEncoding: NSStringEncoding = NSUTF8StringEncoding
public class OAuthSwiftClient: NSObject {
private(set) public var credential: OAuthSwiftCredential
public var paramsLocation: OAuthSwiftHTTPRequest.ParamsLocation = .AuthorizationHeader
static let separator: String = "\r\n"
static var separatorData: NSData = {
return OAuthSwiftClient.separator.dataUsingEncoding(OAuthSwiftDataEncoding)!
}()
// MARK: init
public init(consumerKey: String, consumerSecret: String) {
self.credential = OAuthSwiftCredential(consumer_key: consumerKey, consumer_secret: consumerSecret)
}
public init(consumerKey: String, consumerSecret: String, accessToken: String, accessTokenSecret: String) {
self.credential = OAuthSwiftCredential(oauth_token: accessToken, oauth_token_secret: accessTokenSecret)
self.credential.consumer_key = consumerKey
self.credential.consumer_secret = consumerSecret
}
// MARK: client methods
public func get(urlString: String, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: .GET, parameters: parameters, headers: headers, success: success, failure: failure)
}
public func post(urlString: String, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: .POST, parameters: parameters, headers: headers, success: success, failure: failure)
}
public func put(urlString: String, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: .PUT, parameters: parameters, headers: headers,success: success, failure: failure)
}
public func delete(urlString: String, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: .DELETE, parameters: parameters, headers: headers,success: success, failure: failure)
}
public func patch(urlString: String, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: .PATCH, parameters: parameters, headers: headers,success: success, failure: failure)
}
public func request(url: String, method: OAuthSwiftHTTPRequest.Method, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
if let request = makeRequest(url, method: method, parameters: parameters, headers: headers) {
request.successHandler = success
request.failureHandler = failure
request.start()
}
}
public func makeRequest(urlString: String, method: OAuthSwiftHTTPRequest.Method, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil) -> OAuthSwiftHTTPRequest? {
if let url = NSURL(string: urlString) {
let request = OAuthSwiftHTTPRequest(URL: url, method: method, parameters: parameters, paramsLocation: self.paramsLocation)
var requestHeaders = [String:String]()
var signatureUrl = url
var signatureParameters = parameters
// Check if body must be hashed (oauth1)
let body: NSData? = nil
if method.isBody {
if let addHeaders = headers, contentType = addHeaders["Content-Type"]?.lowercaseString {
if contentType.rangeOfString("application/json") != nil {
// TODO: oauth_body_hash create body before signing if implementing body hashing
/*do {
let jsonData: NSData = try NSJSONSerialization.dataWithJSONObject(parameters, options: [])
request.HTTPBody = jsonData
requestHeaders["Content-Length"] = "\(jsonData.length)"
body = jsonData
}
catch {
}*/
signatureParameters = [:] // parameters are not used for general signature (could only be used for body hashing
}
// else other type are not supported, see setupRequestForOAuth()
}
}
// Need to account for the fact that some consumers will have additional parameters on the
// querystring, including in the case of fetching a request token. Especially in the case of
// additional parameters on the request, authorize, or access token exchanges, we need to
// normalize the URL and add to the parametes collection.
var queryStringParameters = Dictionary<String, AnyObject>()
let urlComponents = NSURLComponents(URL: url, resolvingAgainstBaseURL: false )
if let queryItems = urlComponents?.queryItems {
for queryItem in queryItems {
let value = queryItem.value?.safeStringByRemovingPercentEncoding ?? ""
queryStringParameters.updateValue(value, forKey: queryItem.name)
}
}
// According to the OAuth1.0a spec, the url used for signing is ONLY scheme, path, and query
if(queryStringParameters.count>0)
{
urlComponents?.query = nil
// This is safe to unwrap because these just came from an NSURL
signatureUrl = urlComponents?.URL ?? url
}
signatureParameters = signatureParameters.join(queryStringParameters)
switch self.paramsLocation {
case .AuthorizationHeader:
//Add oauth parameters in the Authorization header
requestHeaders += self.credential.makeHeaders(signatureUrl, method: method, parameters: signatureParameters, body: body)
case .RequestURIQuery:
//Add oauth parameters as request parameters
request.parameters += self.credential.authorizationParametersWithSignatureForMethod(method, url: signatureUrl, parameters: signatureParameters, body: body)
}
if let addHeaders = headers {
requestHeaders += addHeaders
}
request.headers = requestHeaders
request.dataEncoding = OAuthSwiftDataEncoding
return request
}
return nil
}
public func postImage(urlString: String, parameters: Dictionary<String, AnyObject>, image: NSData, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.multiPartRequest(urlString, method: .POST, parameters: parameters, image: image, success: success, failure: failure)
}
func multiPartRequest(url: String, method: OAuthSwiftHTTPRequest.Method, parameters: Dictionary<String, AnyObject>, image: NSData, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
if let request = makeRequest(url, method: method, parameters: parameters) {
var paramImage = [String: AnyObject]()
paramImage["media"] = image
let boundary = "AS-boundary-\(arc4random())-\(arc4random())"
let type = "multipart/form-data; boundary=\(boundary)"
let body = self.multiPartBodyFromParams(paramImage, boundary: boundary)
request.HTTPBody = body
request.headers += ["Content-Type": type] // "Content-Length": body.length.description
request.successHandler = success
request.failureHandler = failure
request.start()
}
}
public func multiPartBodyFromParams(parameters: [String: AnyObject], boundary: String) -> NSData {
let data = NSMutableData()
let prefixString = "--\(boundary)\r\n"
let prefixData = prefixString.dataUsingEncoding(OAuthSwiftDataEncoding)!
for (key, value) in parameters {
var sectionData: NSData
var sectionType: String?
var sectionFilename: String?
if let multiData = value as? NSData where key == "media" {
sectionData = multiData
sectionType = "image/jpeg"
sectionFilename = "file"
} else {
sectionData = "\(value)".dataUsingEncoding(OAuthSwiftDataEncoding)!
}
data.appendData(prefixData)
let multipartData = OAuthSwiftMultipartData(name: key, data: sectionData, fileName: sectionFilename, mimeType: sectionType)
data.appendMultipartData(multipartData, encoding: OAuthSwiftDataEncoding, separatorData: OAuthSwiftClient.separatorData)
}
let endingString = "--\(boundary)--\r\n"
let endingData = endingString.dataUsingEncoding(OAuthSwiftDataEncoding)!
data.appendData(endingData)
return data
}
public func postMultiPartRequest(url: String, method: OAuthSwiftHTTPRequest.Method, parameters: Dictionary<String, AnyObject>, multiparts: Array<OAuthSwiftMultipartData> = [], success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
if let request = makeRequest(url, method: method, parameters: parameters) {
let boundary = "POST-boundary-\(arc4random())-\(arc4random())"
let type = "multipart/form-data; boundary=\(boundary)"
let body = self.multiDataFromObject(parameters, multiparts: multiparts, boundary: boundary)
request.HTTPBody = body
request.headers += ["Content-Type": type] // "Content-Length": body.length.description
request.successHandler = success
request.failureHandler = failure
request.start()
}
}
func multiDataFromObject(object: [String:AnyObject], multiparts: Array<OAuthSwiftMultipartData>, boundary: String) -> NSData? {
let data = NSMutableData()
let prefixString = "--\(boundary)\r\n"
let prefixData = prefixString.dataUsingEncoding(OAuthSwiftDataEncoding)!
for (key, value) in object {
guard let valueData = "\(value)".dataUsingEncoding(OAuthSwiftDataEncoding) else {
continue
}
data.appendData(prefixData)
let multipartData = OAuthSwiftMultipartData(name: key, data: valueData, fileName: nil, mimeType: nil)
data.appendMultipartData(multipartData, encoding: OAuthSwiftDataEncoding, separatorData: OAuthSwiftClient.separatorData)
}
for multipart in multiparts {
data.appendData(prefixData)
data.appendMultipartData(multipart, encoding: OAuthSwiftDataEncoding, separatorData: OAuthSwiftClient.separatorData)
}
let endingString = "--\(boundary)--\r\n"
let endingData = endingString.dataUsingEncoding(OAuthSwiftDataEncoding)!
data.appendData(endingData)
return data
}
}
| mit | 0a46ae798df961e777d9f48fff177b4f | 49.391489 | 277 | 0.649637 | 5.487488 | false | false | false | false |
vi4m/Zewo | Modules/Reflection/Sources/Reflection/Set.swift | 1 | 1381 | /// Set value for key of an instance
public func set(_ value: Any, key: String, for instance: inout Any) throws {
let property = try propertyForType(type(of: instance), withName: key)
try setValue(value, forKey: key, property: property, storage: mutableStorageForInstance(&instance))
}
/// Set value for key of an instance
public func set(_ value: Any, key: String, for instance: AnyObject) throws {
var copy: Any = instance
try set(value, key: key, for: ©)
}
/// Set value for key of an instance
public func set<T>(_ value: Any, key: String, for instance: inout T) throws {
let property = try propertyForType(T.self, withName: key)
try setValue(value, forKey: key, property: property, storage: mutableStorageForInstance(&instance))
}
private func propertyForType(_ type: Any.Type, withName key: String) throws -> Property.Description {
guard let property = try properties(type).filter({ $0.key == key }).first else { throw ReflectionError.instanceHasNoKey(type: type, key: key) }
return property
}
private func setValue(_ value: Any, forKey key: String, property: Property.Description, storage: UnsafeMutableRawPointer) throws {
guard Reflection.value(value, is: property.type) else { throw ReflectionError.valueIsNotType(value: value, type: property.type) }
extensions(of: value).write(to: storage.advanced(by: property.offset))
}
| mit | 240aa08b397665e68aca01f65e6aa8c0 | 50.148148 | 147 | 0.729182 | 3.923295 | false | false | false | false |
basheersubei/swift-t | stc/bench/suite/sweep/embarrassing_lognorm.swift | 4 | 763 | #include <builtins.swift>
#include <io.swift>
#include <sys.swift>
@dispatch=WORKER
(float v) lognorm_work(int i, int j, float mu, float sigma) "lognorm_task" "0" "lognorm_task" [
"set <<v>> [ lognorm_task::lognorm_task_impl <<i>> <<j>> <<mu>> <<sigma>> ] "
];
main {
int N = toint(argv("N"));
int M = toint(argv("M"));
//float sleepTime = tofloat(argv("sleeptime"));
float mu = tofloat(argv("mu"));
float sigma = tofloat(argv("sigma"));
// print for debug
printf("trace: The number of arguments is: %i\n", argc());
printf("trace: The bounds are: %i, %i\n", N, M);
printf("trace: mu is: %f\n", mu);
printf("trace: sigma is: %f\n", sigma);
foreach i in [1:N] {
foreach j in [1:M] {
lognorm_work(i, j, mu, sigma);
}
}
}
| apache-2.0 | da26699b31c6dd0f192485234e482183 | 25.310345 | 95 | 0.585845 | 2.705674 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | Buy/Generated/Storefront/Mutation.swift | 1 | 86028 | //
// Mutation.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. 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
extension Storefront {
/// The schema’s entry-point for mutations. This acts as the public, top-level
/// API from which all mutation queries must start.
open class MutationQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = Mutation
open override var description: String {
return "mutation " + super.description
}
/// Updates the attributes on a cart.
///
/// - parameters:
/// - attributes: An array of key-value pairs that contains additional information about the cart.
/// - cartId: The ID of the cart.
///
@discardableResult
open func cartAttributesUpdate(alias: String? = nil, attributes: [AttributeInput], cartId: GraphQL.ID, _ subfields: (CartAttributesUpdatePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("attributes:[\(attributes.map{ "\($0.serialize())" }.joined(separator: ","))]")
args.append("cartId:\(GraphQL.quoteString(input: "\(cartId.rawValue)"))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CartAttributesUpdatePayloadQuery()
subfields(subquery)
addField(field: "cartAttributesUpdate", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Updates customer information associated with a cart. Buyer identity is used
/// to determine [international
/// pricing](https://shopify.dev/custom-storefronts/internationalization/international-pricing)
/// and should match the customer's shipping address.
///
/// - parameters:
/// - cartId: The ID of the cart.
/// - buyerIdentity: The customer associated with the cart. Used to determine
/// [international pricing](https://shopify.dev/custom-storefronts/internationalization/international-pricing).
/// Buyer identity should match the customer's shipping address.
///
@discardableResult
open func cartBuyerIdentityUpdate(alias: String? = nil, cartId: GraphQL.ID, buyerIdentity: CartBuyerIdentityInput, _ subfields: (CartBuyerIdentityUpdatePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("cartId:\(GraphQL.quoteString(input: "\(cartId.rawValue)"))")
args.append("buyerIdentity:\(buyerIdentity.serialize())")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CartBuyerIdentityUpdatePayloadQuery()
subfields(subquery)
addField(field: "cartBuyerIdentityUpdate", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Creates a new cart.
///
/// - parameters:
/// - input: The fields used to create a cart.
///
@discardableResult
open func cartCreate(alias: String? = nil, input: CartInput? = nil, _ subfields: (CartCreatePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
if let input = input {
args.append("input:\(input.serialize())")
}
let argsString: String? = args.isEmpty ? nil : "(\(args.joined(separator: ",")))"
let subquery = CartCreatePayloadQuery()
subfields(subquery)
addField(field: "cartCreate", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Updates the discount codes applied to the cart.
///
/// - parameters:
/// - cartId: The ID of the cart.
/// - discountCodes: The case-insensitive discount codes that the customer added at checkout.
///
@discardableResult
open func cartDiscountCodesUpdate(alias: String? = nil, cartId: GraphQL.ID, discountCodes: [String]? = nil, _ subfields: (CartDiscountCodesUpdatePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("cartId:\(GraphQL.quoteString(input: "\(cartId.rawValue)"))")
if let discountCodes = discountCodes {
args.append("discountCodes:[\(discountCodes.map{ "\(GraphQL.quoteString(input: $0))" }.joined(separator: ","))]")
}
let argsString: String? = args.isEmpty ? nil : "(\(args.joined(separator: ",")))"
let subquery = CartDiscountCodesUpdatePayloadQuery()
subfields(subquery)
addField(field: "cartDiscountCodesUpdate", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Adds a merchandise line to the cart.
///
/// - parameters:
/// - lines: A list of merchandise lines to add to the cart.
/// - cartId: The ID of the cart.
///
@discardableResult
open func cartLinesAdd(alias: String? = nil, lines: [CartLineInput], cartId: GraphQL.ID, _ subfields: (CartLinesAddPayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("lines:[\(lines.map{ "\($0.serialize())" }.joined(separator: ","))]")
args.append("cartId:\(GraphQL.quoteString(input: "\(cartId.rawValue)"))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CartLinesAddPayloadQuery()
subfields(subquery)
addField(field: "cartLinesAdd", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Removes one or more merchandise lines from the cart.
///
/// - parameters:
/// - cartId: The ID of the cart.
/// - lineIds: The merchandise line IDs to remove.
///
@discardableResult
open func cartLinesRemove(alias: String? = nil, cartId: GraphQL.ID, lineIds: [GraphQL.ID], _ subfields: (CartLinesRemovePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("cartId:\(GraphQL.quoteString(input: "\(cartId.rawValue)"))")
args.append("lineIds:[\(lineIds.map{ "\(GraphQL.quoteString(input: "\($0.rawValue)"))" }.joined(separator: ","))]")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CartLinesRemovePayloadQuery()
subfields(subquery)
addField(field: "cartLinesRemove", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Updates one or more merchandise lines on a cart.
///
/// - parameters:
/// - cartId: The ID of the cart.
/// - lines: The merchandise lines to update.
///
@discardableResult
open func cartLinesUpdate(alias: String? = nil, cartId: GraphQL.ID, lines: [CartLineUpdateInput], _ subfields: (CartLinesUpdatePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("cartId:\(GraphQL.quoteString(input: "\(cartId.rawValue)"))")
args.append("lines:[\(lines.map{ "\($0.serialize())" }.joined(separator: ","))]")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CartLinesUpdatePayloadQuery()
subfields(subquery)
addField(field: "cartLinesUpdate", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Updates the note on the cart.
///
/// - parameters:
/// - cartId: The ID of the cart.
/// - note: The note on the cart.
///
@discardableResult
open func cartNoteUpdate(alias: String? = nil, cartId: GraphQL.ID, note: String? = nil, _ subfields: (CartNoteUpdatePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("cartId:\(GraphQL.quoteString(input: "\(cartId.rawValue)"))")
if let note = note {
args.append("note:\(GraphQL.quoteString(input: note))")
}
let argsString: String? = args.isEmpty ? nil : "(\(args.joined(separator: ",")))"
let subquery = CartNoteUpdatePayloadQuery()
subfields(subquery)
addField(field: "cartNoteUpdate", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Update the selected delivery options for a delivery group.
///
/// - parameters:
/// - cartId: The ID of the cart.
/// - selectedDeliveryOptions: The selected delivery options.
///
@discardableResult
open func cartSelectedDeliveryOptionsUpdate(alias: String? = nil, cartId: GraphQL.ID, selectedDeliveryOptions: [CartSelectedDeliveryOptionInput], _ subfields: (CartSelectedDeliveryOptionsUpdatePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("cartId:\(GraphQL.quoteString(input: "\(cartId.rawValue)"))")
args.append("selectedDeliveryOptions:[\(selectedDeliveryOptions.map{ "\($0.serialize())" }.joined(separator: ","))]")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CartSelectedDeliveryOptionsUpdatePayloadQuery()
subfields(subquery)
addField(field: "cartSelectedDeliveryOptionsUpdate", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Updates the attributes of a checkout if `allowPartialAddresses` is `true`.
///
/// - parameters:
/// - checkoutId: The ID of the checkout.
/// - input: The checkout attributes to update.
///
@discardableResult
open func checkoutAttributesUpdateV2(alias: String? = nil, checkoutId: GraphQL.ID, input: CheckoutAttributesUpdateV2Input, _ subfields: (CheckoutAttributesUpdateV2PayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("checkoutId:\(GraphQL.quoteString(input: "\(checkoutId.rawValue)"))")
args.append("input:\(input.serialize())")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CheckoutAttributesUpdateV2PayloadQuery()
subfields(subquery)
addField(field: "checkoutAttributesUpdateV2", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Completes a checkout without providing payment information. You can use
/// this mutation for free items or items whose purchase price is covered by a
/// gift card.
///
/// - parameters:
/// - checkoutId: The ID of the checkout.
///
@discardableResult
open func checkoutCompleteFree(alias: String? = nil, checkoutId: GraphQL.ID, _ subfields: (CheckoutCompleteFreePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("checkoutId:\(GraphQL.quoteString(input: "\(checkoutId.rawValue)"))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CheckoutCompleteFreePayloadQuery()
subfields(subquery)
addField(field: "checkoutCompleteFree", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Completes a checkout using a credit card token from Shopify's card vault.
/// Before you can complete checkouts using CheckoutCompleteWithCreditCardV2,
/// you need to [_request payment
/// processing_](https://shopify.dev/apps/channels/getting-started#request-payment-processing).
///
/// - parameters:
/// - checkoutId: The ID of the checkout.
/// - payment: The credit card info to apply as a payment.
///
@discardableResult
open func checkoutCompleteWithCreditCardV2(alias: String? = nil, checkoutId: GraphQL.ID, payment: CreditCardPaymentInputV2, _ subfields: (CheckoutCompleteWithCreditCardV2PayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("checkoutId:\(GraphQL.quoteString(input: "\(checkoutId.rawValue)"))")
args.append("payment:\(payment.serialize())")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CheckoutCompleteWithCreditCardV2PayloadQuery()
subfields(subquery)
addField(field: "checkoutCompleteWithCreditCardV2", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Completes a checkout with a tokenized payment.
///
/// - parameters:
/// - checkoutId: The ID of the checkout.
/// - payment: The info to apply as a tokenized payment.
///
@discardableResult
open func checkoutCompleteWithTokenizedPaymentV3(alias: String? = nil, checkoutId: GraphQL.ID, payment: TokenizedPaymentInputV3, _ subfields: (CheckoutCompleteWithTokenizedPaymentV3PayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("checkoutId:\(GraphQL.quoteString(input: "\(checkoutId.rawValue)"))")
args.append("payment:\(payment.serialize())")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CheckoutCompleteWithTokenizedPaymentV3PayloadQuery()
subfields(subquery)
addField(field: "checkoutCompleteWithTokenizedPaymentV3", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Creates a new checkout.
///
/// - parameters:
/// - input: The fields used to create a checkout.
/// - queueToken: The checkout queue token. Available only to selected stores.
///
@discardableResult
open func checkoutCreate(alias: String? = nil, input: CheckoutCreateInput, queueToken: String? = nil, _ subfields: (CheckoutCreatePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("input:\(input.serialize())")
if let queueToken = queueToken {
args.append("queueToken:\(GraphQL.quoteString(input: queueToken))")
}
let argsString: String? = args.isEmpty ? nil : "(\(args.joined(separator: ",")))"
let subquery = CheckoutCreatePayloadQuery()
subfields(subquery)
addField(field: "checkoutCreate", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Associates a customer to the checkout.
///
/// - parameters:
/// - checkoutId: The ID of the checkout.
/// - customerAccessToken: The customer access token of the customer to associate.
///
@discardableResult
open func checkoutCustomerAssociateV2(alias: String? = nil, checkoutId: GraphQL.ID, customerAccessToken: String, _ subfields: (CheckoutCustomerAssociateV2PayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("checkoutId:\(GraphQL.quoteString(input: "\(checkoutId.rawValue)"))")
args.append("customerAccessToken:\(GraphQL.quoteString(input: customerAccessToken))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CheckoutCustomerAssociateV2PayloadQuery()
subfields(subquery)
addField(field: "checkoutCustomerAssociateV2", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Disassociates the current checkout customer from the checkout.
///
/// - parameters:
/// - checkoutId: The ID of the checkout.
///
@discardableResult
open func checkoutCustomerDisassociateV2(alias: String? = nil, checkoutId: GraphQL.ID, _ subfields: (CheckoutCustomerDisassociateV2PayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("checkoutId:\(GraphQL.quoteString(input: "\(checkoutId.rawValue)"))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CheckoutCustomerDisassociateV2PayloadQuery()
subfields(subquery)
addField(field: "checkoutCustomerDisassociateV2", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Applies a discount to an existing checkout using a discount code.
///
/// - parameters:
/// - discountCode: The discount code to apply to the checkout.
/// - checkoutId: The ID of the checkout.
///
@discardableResult
open func checkoutDiscountCodeApplyV2(alias: String? = nil, discountCode: String, checkoutId: GraphQL.ID, _ subfields: (CheckoutDiscountCodeApplyV2PayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("discountCode:\(GraphQL.quoteString(input: discountCode))")
args.append("checkoutId:\(GraphQL.quoteString(input: "\(checkoutId.rawValue)"))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CheckoutDiscountCodeApplyV2PayloadQuery()
subfields(subquery)
addField(field: "checkoutDiscountCodeApplyV2", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Removes the applied discounts from an existing checkout.
///
/// - parameters:
/// - checkoutId: The ID of the checkout.
///
@discardableResult
open func checkoutDiscountCodeRemove(alias: String? = nil, checkoutId: GraphQL.ID, _ subfields: (CheckoutDiscountCodeRemovePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("checkoutId:\(GraphQL.quoteString(input: "\(checkoutId.rawValue)"))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CheckoutDiscountCodeRemovePayloadQuery()
subfields(subquery)
addField(field: "checkoutDiscountCodeRemove", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Updates the email on an existing checkout.
///
/// - parameters:
/// - checkoutId: The ID of the checkout.
/// - email: The email to update the checkout with.
///
@discardableResult
open func checkoutEmailUpdateV2(alias: String? = nil, checkoutId: GraphQL.ID, email: String, _ subfields: (CheckoutEmailUpdateV2PayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("checkoutId:\(GraphQL.quoteString(input: "\(checkoutId.rawValue)"))")
args.append("email:\(GraphQL.quoteString(input: email))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CheckoutEmailUpdateV2PayloadQuery()
subfields(subquery)
addField(field: "checkoutEmailUpdateV2", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Removes an applied gift card from the checkout.
///
/// - parameters:
/// - appliedGiftCardId: The ID of the Applied Gift Card to remove from the Checkout.
/// - checkoutId: The ID of the checkout.
///
@discardableResult
open func checkoutGiftCardRemoveV2(alias: String? = nil, appliedGiftCardId: GraphQL.ID, checkoutId: GraphQL.ID, _ subfields: (CheckoutGiftCardRemoveV2PayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("appliedGiftCardId:\(GraphQL.quoteString(input: "\(appliedGiftCardId.rawValue)"))")
args.append("checkoutId:\(GraphQL.quoteString(input: "\(checkoutId.rawValue)"))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CheckoutGiftCardRemoveV2PayloadQuery()
subfields(subquery)
addField(field: "checkoutGiftCardRemoveV2", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Appends gift cards to an existing checkout.
///
/// - parameters:
/// - giftCardCodes: A list of gift card codes to append to the checkout.
/// - checkoutId: The ID of the checkout.
///
@discardableResult
open func checkoutGiftCardsAppend(alias: String? = nil, giftCardCodes: [String], checkoutId: GraphQL.ID, _ subfields: (CheckoutGiftCardsAppendPayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("giftCardCodes:[\(giftCardCodes.map{ "\(GraphQL.quoteString(input: $0))" }.joined(separator: ","))]")
args.append("checkoutId:\(GraphQL.quoteString(input: "\(checkoutId.rawValue)"))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CheckoutGiftCardsAppendPayloadQuery()
subfields(subquery)
addField(field: "checkoutGiftCardsAppend", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Adds a list of line items to a checkout.
///
/// - parameters:
/// - lineItems: A list of line item objects to add to the checkout.
/// - checkoutId: The ID of the checkout.
///
@discardableResult
open func checkoutLineItemsAdd(alias: String? = nil, lineItems: [CheckoutLineItemInput], checkoutId: GraphQL.ID, _ subfields: (CheckoutLineItemsAddPayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("lineItems:[\(lineItems.map{ "\($0.serialize())" }.joined(separator: ","))]")
args.append("checkoutId:\(GraphQL.quoteString(input: "\(checkoutId.rawValue)"))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CheckoutLineItemsAddPayloadQuery()
subfields(subquery)
addField(field: "checkoutLineItemsAdd", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Removes line items from an existing checkout.
///
/// - parameters:
/// - checkoutId: The checkout on which to remove line items.
/// - lineItemIds: Line item ids to remove.
///
@discardableResult
open func checkoutLineItemsRemove(alias: String? = nil, checkoutId: GraphQL.ID, lineItemIds: [GraphQL.ID], _ subfields: (CheckoutLineItemsRemovePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("checkoutId:\(GraphQL.quoteString(input: "\(checkoutId.rawValue)"))")
args.append("lineItemIds:[\(lineItemIds.map{ "\(GraphQL.quoteString(input: "\($0.rawValue)"))" }.joined(separator: ","))]")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CheckoutLineItemsRemovePayloadQuery()
subfields(subquery)
addField(field: "checkoutLineItemsRemove", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Sets a list of line items to a checkout.
///
/// - parameters:
/// - lineItems: A list of line item objects to set on the checkout.
/// - checkoutId: The ID of the checkout.
///
@discardableResult
open func checkoutLineItemsReplace(alias: String? = nil, lineItems: [CheckoutLineItemInput], checkoutId: GraphQL.ID, _ subfields: (CheckoutLineItemsReplacePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("lineItems:[\(lineItems.map{ "\($0.serialize())" }.joined(separator: ","))]")
args.append("checkoutId:\(GraphQL.quoteString(input: "\(checkoutId.rawValue)"))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CheckoutLineItemsReplacePayloadQuery()
subfields(subquery)
addField(field: "checkoutLineItemsReplace", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Updates line items on a checkout.
///
/// - parameters:
/// - checkoutId: The checkout on which to update line items.
/// - lineItems: Line items to update.
///
@discardableResult
open func checkoutLineItemsUpdate(alias: String? = nil, checkoutId: GraphQL.ID, lineItems: [CheckoutLineItemUpdateInput], _ subfields: (CheckoutLineItemsUpdatePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("checkoutId:\(GraphQL.quoteString(input: "\(checkoutId.rawValue)"))")
args.append("lineItems:[\(lineItems.map{ "\($0.serialize())" }.joined(separator: ","))]")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CheckoutLineItemsUpdatePayloadQuery()
subfields(subquery)
addField(field: "checkoutLineItemsUpdate", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Updates the shipping address of an existing checkout.
///
/// - parameters:
/// - shippingAddress: The shipping address to where the line items will be shipped.
/// - checkoutId: The ID of the checkout.
///
@discardableResult
open func checkoutShippingAddressUpdateV2(alias: String? = nil, shippingAddress: MailingAddressInput, checkoutId: GraphQL.ID, _ subfields: (CheckoutShippingAddressUpdateV2PayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("shippingAddress:\(shippingAddress.serialize())")
args.append("checkoutId:\(GraphQL.quoteString(input: "\(checkoutId.rawValue)"))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CheckoutShippingAddressUpdateV2PayloadQuery()
subfields(subquery)
addField(field: "checkoutShippingAddressUpdateV2", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Updates the shipping lines on an existing checkout.
///
/// - parameters:
/// - checkoutId: The ID of the checkout.
/// - shippingRateHandle: A unique identifier to a Checkout’s shipping provider, price, and title combination, enabling the customer to select the availableShippingRates.
///
@discardableResult
open func checkoutShippingLineUpdate(alias: String? = nil, checkoutId: GraphQL.ID, shippingRateHandle: String, _ subfields: (CheckoutShippingLineUpdatePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("checkoutId:\(GraphQL.quoteString(input: "\(checkoutId.rawValue)"))")
args.append("shippingRateHandle:\(GraphQL.quoteString(input: shippingRateHandle))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CheckoutShippingLineUpdatePayloadQuery()
subfields(subquery)
addField(field: "checkoutShippingLineUpdate", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Creates a customer access token. The customer access token is required to
/// modify the customer object in any way.
///
/// - parameters:
/// - input: The fields used to create a customer access token.
///
@discardableResult
open func customerAccessTokenCreate(alias: String? = nil, input: CustomerAccessTokenCreateInput, _ subfields: (CustomerAccessTokenCreatePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("input:\(input.serialize())")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CustomerAccessTokenCreatePayloadQuery()
subfields(subquery)
addField(field: "customerAccessTokenCreate", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Creates a customer access token using a [multipass
/// token](https://shopify.dev/api/multipass) instead of email and password. A
/// customer record is created if the customer doesn't exist. If a customer
/// record already exists but the record is disabled, then the customer record
/// is enabled.
///
/// - parameters:
/// - multipassToken: A valid [multipass token](https://shopify.dev/api/multipass) to be authenticated.
///
@discardableResult
open func customerAccessTokenCreateWithMultipass(alias: String? = nil, multipassToken: String, _ subfields: (CustomerAccessTokenCreateWithMultipassPayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("multipassToken:\(GraphQL.quoteString(input: multipassToken))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CustomerAccessTokenCreateWithMultipassPayloadQuery()
subfields(subquery)
addField(field: "customerAccessTokenCreateWithMultipass", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Permanently destroys a customer access token.
///
/// - parameters:
/// - customerAccessToken: The access token used to identify the customer.
///
@discardableResult
open func customerAccessTokenDelete(alias: String? = nil, customerAccessToken: String, _ subfields: (CustomerAccessTokenDeletePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("customerAccessToken:\(GraphQL.quoteString(input: customerAccessToken))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CustomerAccessTokenDeletePayloadQuery()
subfields(subquery)
addField(field: "customerAccessTokenDelete", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Renews a customer access token. Access token renewal must happen *before* a
/// token expires. If a token has already expired, a new one should be created
/// instead via `customerAccessTokenCreate`.
///
/// - parameters:
/// - customerAccessToken: The access token used to identify the customer.
///
@discardableResult
open func customerAccessTokenRenew(alias: String? = nil, customerAccessToken: String, _ subfields: (CustomerAccessTokenRenewPayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("customerAccessToken:\(GraphQL.quoteString(input: customerAccessToken))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CustomerAccessTokenRenewPayloadQuery()
subfields(subquery)
addField(field: "customerAccessTokenRenew", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Activates a customer.
///
/// - parameters:
/// - id: Specifies the customer to activate.
/// - input: The fields used to activate a customer.
///
@discardableResult
open func customerActivate(alias: String? = nil, id: GraphQL.ID, input: CustomerActivateInput, _ subfields: (CustomerActivatePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("id:\(GraphQL.quoteString(input: "\(id.rawValue)"))")
args.append("input:\(input.serialize())")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CustomerActivatePayloadQuery()
subfields(subquery)
addField(field: "customerActivate", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Activates a customer with the activation url received from
/// `customerCreate`.
///
/// - parameters:
/// - activationUrl: The customer activation URL.
/// - password: A new password set during activation.
///
@discardableResult
open func customerActivateByUrl(alias: String? = nil, activationUrl: URL, password: String, _ subfields: (CustomerActivateByUrlPayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("activationUrl:\(GraphQL.quoteString(input: "\(activationUrl.absoluteString)"))")
args.append("password:\(GraphQL.quoteString(input: password))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CustomerActivateByUrlPayloadQuery()
subfields(subquery)
addField(field: "customerActivateByUrl", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Creates a new address for a customer.
///
/// - parameters:
/// - customerAccessToken: The access token used to identify the customer.
/// - address: The customer mailing address to create.
///
@discardableResult
open func customerAddressCreate(alias: String? = nil, customerAccessToken: String, address: MailingAddressInput, _ subfields: (CustomerAddressCreatePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("customerAccessToken:\(GraphQL.quoteString(input: customerAccessToken))")
args.append("address:\(address.serialize())")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CustomerAddressCreatePayloadQuery()
subfields(subquery)
addField(field: "customerAddressCreate", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Permanently deletes the address of an existing customer.
///
/// - parameters:
/// - id: Specifies the address to delete.
/// - customerAccessToken: The access token used to identify the customer.
///
@discardableResult
open func customerAddressDelete(alias: String? = nil, id: GraphQL.ID, customerAccessToken: String, _ subfields: (CustomerAddressDeletePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("id:\(GraphQL.quoteString(input: "\(id.rawValue)"))")
args.append("customerAccessToken:\(GraphQL.quoteString(input: customerAccessToken))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CustomerAddressDeletePayloadQuery()
subfields(subquery)
addField(field: "customerAddressDelete", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Updates the address of an existing customer.
///
/// - parameters:
/// - customerAccessToken: The access token used to identify the customer.
/// - id: Specifies the customer address to update.
/// - address: The customer’s mailing address.
///
@discardableResult
open func customerAddressUpdate(alias: String? = nil, customerAccessToken: String, id: GraphQL.ID, address: MailingAddressInput, _ subfields: (CustomerAddressUpdatePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("customerAccessToken:\(GraphQL.quoteString(input: customerAccessToken))")
args.append("id:\(GraphQL.quoteString(input: "\(id.rawValue)"))")
args.append("address:\(address.serialize())")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CustomerAddressUpdatePayloadQuery()
subfields(subquery)
addField(field: "customerAddressUpdate", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Creates a new customer.
///
/// - parameters:
/// - input: The fields used to create a new customer.
///
@discardableResult
open func customerCreate(alias: String? = nil, input: CustomerCreateInput, _ subfields: (CustomerCreatePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("input:\(input.serialize())")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CustomerCreatePayloadQuery()
subfields(subquery)
addField(field: "customerCreate", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Updates the default address of an existing customer.
///
/// - parameters:
/// - customerAccessToken: The access token used to identify the customer.
/// - addressId: ID of the address to set as the new default for the customer.
///
@discardableResult
open func customerDefaultAddressUpdate(alias: String? = nil, customerAccessToken: String, addressId: GraphQL.ID, _ subfields: (CustomerDefaultAddressUpdatePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("customerAccessToken:\(GraphQL.quoteString(input: customerAccessToken))")
args.append("addressId:\(GraphQL.quoteString(input: "\(addressId.rawValue)"))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CustomerDefaultAddressUpdatePayloadQuery()
subfields(subquery)
addField(field: "customerDefaultAddressUpdate", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// "Sends a reset password email to the customer. The reset password email
/// contains a reset password URL and token that you can pass to the
/// [`customerResetByUrl`](https://shopify.dev/api/storefront/latest/mutations/customerResetByUrl)
/// or
/// [`customerReset`](https://shopify.dev/api/storefront/latest/mutations/customerReset)
/// mutation to reset the customer password."
///
/// - parameters:
/// - email: The email address of the customer to recover.
///
@discardableResult
open func customerRecover(alias: String? = nil, email: String, _ subfields: (CustomerRecoverPayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("email:\(GraphQL.quoteString(input: email))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CustomerRecoverPayloadQuery()
subfields(subquery)
addField(field: "customerRecover", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// "Resets a customer’s password with the token received from a reset password
/// email. You can send a reset password email with the
/// [`customerRecover`](https://shopify.dev/api/storefront/latest/mutations/customerRecover)
/// mutation."
///
/// - parameters:
/// - id: Specifies the customer to reset.
/// - input: The fields used to reset a customer’s password.
///
@discardableResult
open func customerReset(alias: String? = nil, id: GraphQL.ID, input: CustomerResetInput, _ subfields: (CustomerResetPayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("id:\(GraphQL.quoteString(input: "\(id.rawValue)"))")
args.append("input:\(input.serialize())")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CustomerResetPayloadQuery()
subfields(subquery)
addField(field: "customerReset", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// "Resets a customer’s password with the reset password URL received from a
/// reset password email. You can send a reset password email with the
/// [`customerRecover`](https://shopify.dev/api/storefront/latest/mutations/customerRecover)
/// mutation."
///
/// - parameters:
/// - resetUrl: The customer's reset password url.
/// - password: New password that will be set as part of the reset password process.
///
@discardableResult
open func customerResetByUrl(alias: String? = nil, resetUrl: URL, password: String, _ subfields: (CustomerResetByUrlPayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("resetUrl:\(GraphQL.quoteString(input: "\(resetUrl.absoluteString)"))")
args.append("password:\(GraphQL.quoteString(input: password))")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CustomerResetByUrlPayloadQuery()
subfields(subquery)
addField(field: "customerResetByUrl", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
/// Updates an existing customer.
///
/// - parameters:
/// - customerAccessToken: The access token used to identify the customer.
/// - customer: The customer object input.
///
@discardableResult
open func customerUpdate(alias: String? = nil, customerAccessToken: String, customer: CustomerUpdateInput, _ subfields: (CustomerUpdatePayloadQuery) -> Void) -> MutationQuery {
var args: [String] = []
args.append("customerAccessToken:\(GraphQL.quoteString(input: customerAccessToken))")
args.append("customer:\(customer.serialize())")
let argsString = "(\(args.joined(separator: ",")))"
let subquery = CustomerUpdatePayloadQuery()
subfields(subquery)
addField(field: "customerUpdate", aliasSuffix: alias, args: argsString, subfields: subquery)
return self
}
}
/// The schema’s entry-point for mutations. This acts as the public, top-level
/// API from which all mutation queries must start.
open class Mutation: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = MutationQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "cartAttributesUpdate":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CartAttributesUpdatePayload(fields: value)
case "cartBuyerIdentityUpdate":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CartBuyerIdentityUpdatePayload(fields: value)
case "cartCreate":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CartCreatePayload(fields: value)
case "cartDiscountCodesUpdate":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CartDiscountCodesUpdatePayload(fields: value)
case "cartLinesAdd":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CartLinesAddPayload(fields: value)
case "cartLinesRemove":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CartLinesRemovePayload(fields: value)
case "cartLinesUpdate":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CartLinesUpdatePayload(fields: value)
case "cartNoteUpdate":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CartNoteUpdatePayload(fields: value)
case "cartSelectedDeliveryOptionsUpdate":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CartSelectedDeliveryOptionsUpdatePayload(fields: value)
case "checkoutAttributesUpdateV2":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CheckoutAttributesUpdateV2Payload(fields: value)
case "checkoutCompleteFree":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CheckoutCompleteFreePayload(fields: value)
case "checkoutCompleteWithCreditCardV2":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CheckoutCompleteWithCreditCardV2Payload(fields: value)
case "checkoutCompleteWithTokenizedPaymentV3":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CheckoutCompleteWithTokenizedPaymentV3Payload(fields: value)
case "checkoutCreate":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CheckoutCreatePayload(fields: value)
case "checkoutCustomerAssociateV2":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CheckoutCustomerAssociateV2Payload(fields: value)
case "checkoutCustomerDisassociateV2":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CheckoutCustomerDisassociateV2Payload(fields: value)
case "checkoutDiscountCodeApplyV2":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CheckoutDiscountCodeApplyV2Payload(fields: value)
case "checkoutDiscountCodeRemove":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CheckoutDiscountCodeRemovePayload(fields: value)
case "checkoutEmailUpdateV2":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CheckoutEmailUpdateV2Payload(fields: value)
case "checkoutGiftCardRemoveV2":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CheckoutGiftCardRemoveV2Payload(fields: value)
case "checkoutGiftCardsAppend":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CheckoutGiftCardsAppendPayload(fields: value)
case "checkoutLineItemsAdd":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CheckoutLineItemsAddPayload(fields: value)
case "checkoutLineItemsRemove":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CheckoutLineItemsRemovePayload(fields: value)
case "checkoutLineItemsReplace":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CheckoutLineItemsReplacePayload(fields: value)
case "checkoutLineItemsUpdate":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CheckoutLineItemsUpdatePayload(fields: value)
case "checkoutShippingAddressUpdateV2":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CheckoutShippingAddressUpdateV2Payload(fields: value)
case "checkoutShippingLineUpdate":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CheckoutShippingLineUpdatePayload(fields: value)
case "customerAccessTokenCreate":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CustomerAccessTokenCreatePayload(fields: value)
case "customerAccessTokenCreateWithMultipass":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CustomerAccessTokenCreateWithMultipassPayload(fields: value)
case "customerAccessTokenDelete":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CustomerAccessTokenDeletePayload(fields: value)
case "customerAccessTokenRenew":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CustomerAccessTokenRenewPayload(fields: value)
case "customerActivate":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CustomerActivatePayload(fields: value)
case "customerActivateByUrl":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CustomerActivateByUrlPayload(fields: value)
case "customerAddressCreate":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CustomerAddressCreatePayload(fields: value)
case "customerAddressDelete":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CustomerAddressDeletePayload(fields: value)
case "customerAddressUpdate":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CustomerAddressUpdatePayload(fields: value)
case "customerCreate":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CustomerCreatePayload(fields: value)
case "customerDefaultAddressUpdate":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CustomerDefaultAddressUpdatePayload(fields: value)
case "customerRecover":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CustomerRecoverPayload(fields: value)
case "customerReset":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CustomerResetPayload(fields: value)
case "customerResetByUrl":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CustomerResetByUrlPayload(fields: value)
case "customerUpdate":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
return try CustomerUpdatePayload(fields: value)
default:
throw SchemaViolationError(type: Mutation.self, field: fieldName, value: fieldValue)
}
}
/// Updates the attributes on a cart.
open var cartAttributesUpdate: Storefront.CartAttributesUpdatePayload? {
return internalGetCartAttributesUpdate()
}
open func aliasedCartAttributesUpdate(alias: String) -> Storefront.CartAttributesUpdatePayload? {
return internalGetCartAttributesUpdate(alias: alias)
}
func internalGetCartAttributesUpdate(alias: String? = nil) -> Storefront.CartAttributesUpdatePayload? {
return field(field: "cartAttributesUpdate", aliasSuffix: alias) as! Storefront.CartAttributesUpdatePayload?
}
/// Updates customer information associated with a cart. Buyer identity is used
/// to determine [international
/// pricing](https://shopify.dev/custom-storefronts/internationalization/international-pricing)
/// and should match the customer's shipping address.
open var cartBuyerIdentityUpdate: Storefront.CartBuyerIdentityUpdatePayload? {
return internalGetCartBuyerIdentityUpdate()
}
open func aliasedCartBuyerIdentityUpdate(alias: String) -> Storefront.CartBuyerIdentityUpdatePayload? {
return internalGetCartBuyerIdentityUpdate(alias: alias)
}
func internalGetCartBuyerIdentityUpdate(alias: String? = nil) -> Storefront.CartBuyerIdentityUpdatePayload? {
return field(field: "cartBuyerIdentityUpdate", aliasSuffix: alias) as! Storefront.CartBuyerIdentityUpdatePayload?
}
/// Creates a new cart.
open var cartCreate: Storefront.CartCreatePayload? {
return internalGetCartCreate()
}
open func aliasedCartCreate(alias: String) -> Storefront.CartCreatePayload? {
return internalGetCartCreate(alias: alias)
}
func internalGetCartCreate(alias: String? = nil) -> Storefront.CartCreatePayload? {
return field(field: "cartCreate", aliasSuffix: alias) as! Storefront.CartCreatePayload?
}
/// Updates the discount codes applied to the cart.
open var cartDiscountCodesUpdate: Storefront.CartDiscountCodesUpdatePayload? {
return internalGetCartDiscountCodesUpdate()
}
open func aliasedCartDiscountCodesUpdate(alias: String) -> Storefront.CartDiscountCodesUpdatePayload? {
return internalGetCartDiscountCodesUpdate(alias: alias)
}
func internalGetCartDiscountCodesUpdate(alias: String? = nil) -> Storefront.CartDiscountCodesUpdatePayload? {
return field(field: "cartDiscountCodesUpdate", aliasSuffix: alias) as! Storefront.CartDiscountCodesUpdatePayload?
}
/// Adds a merchandise line to the cart.
open var cartLinesAdd: Storefront.CartLinesAddPayload? {
return internalGetCartLinesAdd()
}
open func aliasedCartLinesAdd(alias: String) -> Storefront.CartLinesAddPayload? {
return internalGetCartLinesAdd(alias: alias)
}
func internalGetCartLinesAdd(alias: String? = nil) -> Storefront.CartLinesAddPayload? {
return field(field: "cartLinesAdd", aliasSuffix: alias) as! Storefront.CartLinesAddPayload?
}
/// Removes one or more merchandise lines from the cart.
open var cartLinesRemove: Storefront.CartLinesRemovePayload? {
return internalGetCartLinesRemove()
}
open func aliasedCartLinesRemove(alias: String) -> Storefront.CartLinesRemovePayload? {
return internalGetCartLinesRemove(alias: alias)
}
func internalGetCartLinesRemove(alias: String? = nil) -> Storefront.CartLinesRemovePayload? {
return field(field: "cartLinesRemove", aliasSuffix: alias) as! Storefront.CartLinesRemovePayload?
}
/// Updates one or more merchandise lines on a cart.
open var cartLinesUpdate: Storefront.CartLinesUpdatePayload? {
return internalGetCartLinesUpdate()
}
open func aliasedCartLinesUpdate(alias: String) -> Storefront.CartLinesUpdatePayload? {
return internalGetCartLinesUpdate(alias: alias)
}
func internalGetCartLinesUpdate(alias: String? = nil) -> Storefront.CartLinesUpdatePayload? {
return field(field: "cartLinesUpdate", aliasSuffix: alias) as! Storefront.CartLinesUpdatePayload?
}
/// Updates the note on the cart.
open var cartNoteUpdate: Storefront.CartNoteUpdatePayload? {
return internalGetCartNoteUpdate()
}
open func aliasedCartNoteUpdate(alias: String) -> Storefront.CartNoteUpdatePayload? {
return internalGetCartNoteUpdate(alias: alias)
}
func internalGetCartNoteUpdate(alias: String? = nil) -> Storefront.CartNoteUpdatePayload? {
return field(field: "cartNoteUpdate", aliasSuffix: alias) as! Storefront.CartNoteUpdatePayload?
}
/// Update the selected delivery options for a delivery group.
open var cartSelectedDeliveryOptionsUpdate: Storefront.CartSelectedDeliveryOptionsUpdatePayload? {
return internalGetCartSelectedDeliveryOptionsUpdate()
}
open func aliasedCartSelectedDeliveryOptionsUpdate(alias: String) -> Storefront.CartSelectedDeliveryOptionsUpdatePayload? {
return internalGetCartSelectedDeliveryOptionsUpdate(alias: alias)
}
func internalGetCartSelectedDeliveryOptionsUpdate(alias: String? = nil) -> Storefront.CartSelectedDeliveryOptionsUpdatePayload? {
return field(field: "cartSelectedDeliveryOptionsUpdate", aliasSuffix: alias) as! Storefront.CartSelectedDeliveryOptionsUpdatePayload?
}
/// Updates the attributes of a checkout if `allowPartialAddresses` is `true`.
open var checkoutAttributesUpdateV2: Storefront.CheckoutAttributesUpdateV2Payload? {
return internalGetCheckoutAttributesUpdateV2()
}
open func aliasedCheckoutAttributesUpdateV2(alias: String) -> Storefront.CheckoutAttributesUpdateV2Payload? {
return internalGetCheckoutAttributesUpdateV2(alias: alias)
}
func internalGetCheckoutAttributesUpdateV2(alias: String? = nil) -> Storefront.CheckoutAttributesUpdateV2Payload? {
return field(field: "checkoutAttributesUpdateV2", aliasSuffix: alias) as! Storefront.CheckoutAttributesUpdateV2Payload?
}
/// Completes a checkout without providing payment information. You can use
/// this mutation for free items or items whose purchase price is covered by a
/// gift card.
open var checkoutCompleteFree: Storefront.CheckoutCompleteFreePayload? {
return internalGetCheckoutCompleteFree()
}
open func aliasedCheckoutCompleteFree(alias: String) -> Storefront.CheckoutCompleteFreePayload? {
return internalGetCheckoutCompleteFree(alias: alias)
}
func internalGetCheckoutCompleteFree(alias: String? = nil) -> Storefront.CheckoutCompleteFreePayload? {
return field(field: "checkoutCompleteFree", aliasSuffix: alias) as! Storefront.CheckoutCompleteFreePayload?
}
/// Completes a checkout using a credit card token from Shopify's card vault.
/// Before you can complete checkouts using CheckoutCompleteWithCreditCardV2,
/// you need to [_request payment
/// processing_](https://shopify.dev/apps/channels/getting-started#request-payment-processing).
open var checkoutCompleteWithCreditCardV2: Storefront.CheckoutCompleteWithCreditCardV2Payload? {
return internalGetCheckoutCompleteWithCreditCardV2()
}
open func aliasedCheckoutCompleteWithCreditCardV2(alias: String) -> Storefront.CheckoutCompleteWithCreditCardV2Payload? {
return internalGetCheckoutCompleteWithCreditCardV2(alias: alias)
}
func internalGetCheckoutCompleteWithCreditCardV2(alias: String? = nil) -> Storefront.CheckoutCompleteWithCreditCardV2Payload? {
return field(field: "checkoutCompleteWithCreditCardV2", aliasSuffix: alias) as! Storefront.CheckoutCompleteWithCreditCardV2Payload?
}
/// Completes a checkout with a tokenized payment.
open var checkoutCompleteWithTokenizedPaymentV3: Storefront.CheckoutCompleteWithTokenizedPaymentV3Payload? {
return internalGetCheckoutCompleteWithTokenizedPaymentV3()
}
open func aliasedCheckoutCompleteWithTokenizedPaymentV3(alias: String) -> Storefront.CheckoutCompleteWithTokenizedPaymentV3Payload? {
return internalGetCheckoutCompleteWithTokenizedPaymentV3(alias: alias)
}
func internalGetCheckoutCompleteWithTokenizedPaymentV3(alias: String? = nil) -> Storefront.CheckoutCompleteWithTokenizedPaymentV3Payload? {
return field(field: "checkoutCompleteWithTokenizedPaymentV3", aliasSuffix: alias) as! Storefront.CheckoutCompleteWithTokenizedPaymentV3Payload?
}
/// Creates a new checkout.
open var checkoutCreate: Storefront.CheckoutCreatePayload? {
return internalGetCheckoutCreate()
}
open func aliasedCheckoutCreate(alias: String) -> Storefront.CheckoutCreatePayload? {
return internalGetCheckoutCreate(alias: alias)
}
func internalGetCheckoutCreate(alias: String? = nil) -> Storefront.CheckoutCreatePayload? {
return field(field: "checkoutCreate", aliasSuffix: alias) as! Storefront.CheckoutCreatePayload?
}
/// Associates a customer to the checkout.
open var checkoutCustomerAssociateV2: Storefront.CheckoutCustomerAssociateV2Payload? {
return internalGetCheckoutCustomerAssociateV2()
}
open func aliasedCheckoutCustomerAssociateV2(alias: String) -> Storefront.CheckoutCustomerAssociateV2Payload? {
return internalGetCheckoutCustomerAssociateV2(alias: alias)
}
func internalGetCheckoutCustomerAssociateV2(alias: String? = nil) -> Storefront.CheckoutCustomerAssociateV2Payload? {
return field(field: "checkoutCustomerAssociateV2", aliasSuffix: alias) as! Storefront.CheckoutCustomerAssociateV2Payload?
}
/// Disassociates the current checkout customer from the checkout.
open var checkoutCustomerDisassociateV2: Storefront.CheckoutCustomerDisassociateV2Payload? {
return internalGetCheckoutCustomerDisassociateV2()
}
open func aliasedCheckoutCustomerDisassociateV2(alias: String) -> Storefront.CheckoutCustomerDisassociateV2Payload? {
return internalGetCheckoutCustomerDisassociateV2(alias: alias)
}
func internalGetCheckoutCustomerDisassociateV2(alias: String? = nil) -> Storefront.CheckoutCustomerDisassociateV2Payload? {
return field(field: "checkoutCustomerDisassociateV2", aliasSuffix: alias) as! Storefront.CheckoutCustomerDisassociateV2Payload?
}
/// Applies a discount to an existing checkout using a discount code.
open var checkoutDiscountCodeApplyV2: Storefront.CheckoutDiscountCodeApplyV2Payload? {
return internalGetCheckoutDiscountCodeApplyV2()
}
open func aliasedCheckoutDiscountCodeApplyV2(alias: String) -> Storefront.CheckoutDiscountCodeApplyV2Payload? {
return internalGetCheckoutDiscountCodeApplyV2(alias: alias)
}
func internalGetCheckoutDiscountCodeApplyV2(alias: String? = nil) -> Storefront.CheckoutDiscountCodeApplyV2Payload? {
return field(field: "checkoutDiscountCodeApplyV2", aliasSuffix: alias) as! Storefront.CheckoutDiscountCodeApplyV2Payload?
}
/// Removes the applied discounts from an existing checkout.
open var checkoutDiscountCodeRemove: Storefront.CheckoutDiscountCodeRemovePayload? {
return internalGetCheckoutDiscountCodeRemove()
}
open func aliasedCheckoutDiscountCodeRemove(alias: String) -> Storefront.CheckoutDiscountCodeRemovePayload? {
return internalGetCheckoutDiscountCodeRemove(alias: alias)
}
func internalGetCheckoutDiscountCodeRemove(alias: String? = nil) -> Storefront.CheckoutDiscountCodeRemovePayload? {
return field(field: "checkoutDiscountCodeRemove", aliasSuffix: alias) as! Storefront.CheckoutDiscountCodeRemovePayload?
}
/// Updates the email on an existing checkout.
open var checkoutEmailUpdateV2: Storefront.CheckoutEmailUpdateV2Payload? {
return internalGetCheckoutEmailUpdateV2()
}
open func aliasedCheckoutEmailUpdateV2(alias: String) -> Storefront.CheckoutEmailUpdateV2Payload? {
return internalGetCheckoutEmailUpdateV2(alias: alias)
}
func internalGetCheckoutEmailUpdateV2(alias: String? = nil) -> Storefront.CheckoutEmailUpdateV2Payload? {
return field(field: "checkoutEmailUpdateV2", aliasSuffix: alias) as! Storefront.CheckoutEmailUpdateV2Payload?
}
/// Removes an applied gift card from the checkout.
open var checkoutGiftCardRemoveV2: Storefront.CheckoutGiftCardRemoveV2Payload? {
return internalGetCheckoutGiftCardRemoveV2()
}
open func aliasedCheckoutGiftCardRemoveV2(alias: String) -> Storefront.CheckoutGiftCardRemoveV2Payload? {
return internalGetCheckoutGiftCardRemoveV2(alias: alias)
}
func internalGetCheckoutGiftCardRemoveV2(alias: String? = nil) -> Storefront.CheckoutGiftCardRemoveV2Payload? {
return field(field: "checkoutGiftCardRemoveV2", aliasSuffix: alias) as! Storefront.CheckoutGiftCardRemoveV2Payload?
}
/// Appends gift cards to an existing checkout.
open var checkoutGiftCardsAppend: Storefront.CheckoutGiftCardsAppendPayload? {
return internalGetCheckoutGiftCardsAppend()
}
open func aliasedCheckoutGiftCardsAppend(alias: String) -> Storefront.CheckoutGiftCardsAppendPayload? {
return internalGetCheckoutGiftCardsAppend(alias: alias)
}
func internalGetCheckoutGiftCardsAppend(alias: String? = nil) -> Storefront.CheckoutGiftCardsAppendPayload? {
return field(field: "checkoutGiftCardsAppend", aliasSuffix: alias) as! Storefront.CheckoutGiftCardsAppendPayload?
}
/// Adds a list of line items to a checkout.
open var checkoutLineItemsAdd: Storefront.CheckoutLineItemsAddPayload? {
return internalGetCheckoutLineItemsAdd()
}
open func aliasedCheckoutLineItemsAdd(alias: String) -> Storefront.CheckoutLineItemsAddPayload? {
return internalGetCheckoutLineItemsAdd(alias: alias)
}
func internalGetCheckoutLineItemsAdd(alias: String? = nil) -> Storefront.CheckoutLineItemsAddPayload? {
return field(field: "checkoutLineItemsAdd", aliasSuffix: alias) as! Storefront.CheckoutLineItemsAddPayload?
}
/// Removes line items from an existing checkout.
open var checkoutLineItemsRemove: Storefront.CheckoutLineItemsRemovePayload? {
return internalGetCheckoutLineItemsRemove()
}
open func aliasedCheckoutLineItemsRemove(alias: String) -> Storefront.CheckoutLineItemsRemovePayload? {
return internalGetCheckoutLineItemsRemove(alias: alias)
}
func internalGetCheckoutLineItemsRemove(alias: String? = nil) -> Storefront.CheckoutLineItemsRemovePayload? {
return field(field: "checkoutLineItemsRemove", aliasSuffix: alias) as! Storefront.CheckoutLineItemsRemovePayload?
}
/// Sets a list of line items to a checkout.
open var checkoutLineItemsReplace: Storefront.CheckoutLineItemsReplacePayload? {
return internalGetCheckoutLineItemsReplace()
}
open func aliasedCheckoutLineItemsReplace(alias: String) -> Storefront.CheckoutLineItemsReplacePayload? {
return internalGetCheckoutLineItemsReplace(alias: alias)
}
func internalGetCheckoutLineItemsReplace(alias: String? = nil) -> Storefront.CheckoutLineItemsReplacePayload? {
return field(field: "checkoutLineItemsReplace", aliasSuffix: alias) as! Storefront.CheckoutLineItemsReplacePayload?
}
/// Updates line items on a checkout.
open var checkoutLineItemsUpdate: Storefront.CheckoutLineItemsUpdatePayload? {
return internalGetCheckoutLineItemsUpdate()
}
open func aliasedCheckoutLineItemsUpdate(alias: String) -> Storefront.CheckoutLineItemsUpdatePayload? {
return internalGetCheckoutLineItemsUpdate(alias: alias)
}
func internalGetCheckoutLineItemsUpdate(alias: String? = nil) -> Storefront.CheckoutLineItemsUpdatePayload? {
return field(field: "checkoutLineItemsUpdate", aliasSuffix: alias) as! Storefront.CheckoutLineItemsUpdatePayload?
}
/// Updates the shipping address of an existing checkout.
open var checkoutShippingAddressUpdateV2: Storefront.CheckoutShippingAddressUpdateV2Payload? {
return internalGetCheckoutShippingAddressUpdateV2()
}
open func aliasedCheckoutShippingAddressUpdateV2(alias: String) -> Storefront.CheckoutShippingAddressUpdateV2Payload? {
return internalGetCheckoutShippingAddressUpdateV2(alias: alias)
}
func internalGetCheckoutShippingAddressUpdateV2(alias: String? = nil) -> Storefront.CheckoutShippingAddressUpdateV2Payload? {
return field(field: "checkoutShippingAddressUpdateV2", aliasSuffix: alias) as! Storefront.CheckoutShippingAddressUpdateV2Payload?
}
/// Updates the shipping lines on an existing checkout.
open var checkoutShippingLineUpdate: Storefront.CheckoutShippingLineUpdatePayload? {
return internalGetCheckoutShippingLineUpdate()
}
open func aliasedCheckoutShippingLineUpdate(alias: String) -> Storefront.CheckoutShippingLineUpdatePayload? {
return internalGetCheckoutShippingLineUpdate(alias: alias)
}
func internalGetCheckoutShippingLineUpdate(alias: String? = nil) -> Storefront.CheckoutShippingLineUpdatePayload? {
return field(field: "checkoutShippingLineUpdate", aliasSuffix: alias) as! Storefront.CheckoutShippingLineUpdatePayload?
}
/// Creates a customer access token. The customer access token is required to
/// modify the customer object in any way.
open var customerAccessTokenCreate: Storefront.CustomerAccessTokenCreatePayload? {
return internalGetCustomerAccessTokenCreate()
}
open func aliasedCustomerAccessTokenCreate(alias: String) -> Storefront.CustomerAccessTokenCreatePayload? {
return internalGetCustomerAccessTokenCreate(alias: alias)
}
func internalGetCustomerAccessTokenCreate(alias: String? = nil) -> Storefront.CustomerAccessTokenCreatePayload? {
return field(field: "customerAccessTokenCreate", aliasSuffix: alias) as! Storefront.CustomerAccessTokenCreatePayload?
}
/// Creates a customer access token using a [multipass
/// token](https://shopify.dev/api/multipass) instead of email and password. A
/// customer record is created if the customer doesn't exist. If a customer
/// record already exists but the record is disabled, then the customer record
/// is enabled.
open var customerAccessTokenCreateWithMultipass: Storefront.CustomerAccessTokenCreateWithMultipassPayload? {
return internalGetCustomerAccessTokenCreateWithMultipass()
}
open func aliasedCustomerAccessTokenCreateWithMultipass(alias: String) -> Storefront.CustomerAccessTokenCreateWithMultipassPayload? {
return internalGetCustomerAccessTokenCreateWithMultipass(alias: alias)
}
func internalGetCustomerAccessTokenCreateWithMultipass(alias: String? = nil) -> Storefront.CustomerAccessTokenCreateWithMultipassPayload? {
return field(field: "customerAccessTokenCreateWithMultipass", aliasSuffix: alias) as! Storefront.CustomerAccessTokenCreateWithMultipassPayload?
}
/// Permanently destroys a customer access token.
open var customerAccessTokenDelete: Storefront.CustomerAccessTokenDeletePayload? {
return internalGetCustomerAccessTokenDelete()
}
open func aliasedCustomerAccessTokenDelete(alias: String) -> Storefront.CustomerAccessTokenDeletePayload? {
return internalGetCustomerAccessTokenDelete(alias: alias)
}
func internalGetCustomerAccessTokenDelete(alias: String? = nil) -> Storefront.CustomerAccessTokenDeletePayload? {
return field(field: "customerAccessTokenDelete", aliasSuffix: alias) as! Storefront.CustomerAccessTokenDeletePayload?
}
/// Renews a customer access token. Access token renewal must happen *before* a
/// token expires. If a token has already expired, a new one should be created
/// instead via `customerAccessTokenCreate`.
open var customerAccessTokenRenew: Storefront.CustomerAccessTokenRenewPayload? {
return internalGetCustomerAccessTokenRenew()
}
open func aliasedCustomerAccessTokenRenew(alias: String) -> Storefront.CustomerAccessTokenRenewPayload? {
return internalGetCustomerAccessTokenRenew(alias: alias)
}
func internalGetCustomerAccessTokenRenew(alias: String? = nil) -> Storefront.CustomerAccessTokenRenewPayload? {
return field(field: "customerAccessTokenRenew", aliasSuffix: alias) as! Storefront.CustomerAccessTokenRenewPayload?
}
/// Activates a customer.
open var customerActivate: Storefront.CustomerActivatePayload? {
return internalGetCustomerActivate()
}
open func aliasedCustomerActivate(alias: String) -> Storefront.CustomerActivatePayload? {
return internalGetCustomerActivate(alias: alias)
}
func internalGetCustomerActivate(alias: String? = nil) -> Storefront.CustomerActivatePayload? {
return field(field: "customerActivate", aliasSuffix: alias) as! Storefront.CustomerActivatePayload?
}
/// Activates a customer with the activation url received from
/// `customerCreate`.
open var customerActivateByUrl: Storefront.CustomerActivateByUrlPayload? {
return internalGetCustomerActivateByUrl()
}
open func aliasedCustomerActivateByUrl(alias: String) -> Storefront.CustomerActivateByUrlPayload? {
return internalGetCustomerActivateByUrl(alias: alias)
}
func internalGetCustomerActivateByUrl(alias: String? = nil) -> Storefront.CustomerActivateByUrlPayload? {
return field(field: "customerActivateByUrl", aliasSuffix: alias) as! Storefront.CustomerActivateByUrlPayload?
}
/// Creates a new address for a customer.
open var customerAddressCreate: Storefront.CustomerAddressCreatePayload? {
return internalGetCustomerAddressCreate()
}
open func aliasedCustomerAddressCreate(alias: String) -> Storefront.CustomerAddressCreatePayload? {
return internalGetCustomerAddressCreate(alias: alias)
}
func internalGetCustomerAddressCreate(alias: String? = nil) -> Storefront.CustomerAddressCreatePayload? {
return field(field: "customerAddressCreate", aliasSuffix: alias) as! Storefront.CustomerAddressCreatePayload?
}
/// Permanently deletes the address of an existing customer.
open var customerAddressDelete: Storefront.CustomerAddressDeletePayload? {
return internalGetCustomerAddressDelete()
}
open func aliasedCustomerAddressDelete(alias: String) -> Storefront.CustomerAddressDeletePayload? {
return internalGetCustomerAddressDelete(alias: alias)
}
func internalGetCustomerAddressDelete(alias: String? = nil) -> Storefront.CustomerAddressDeletePayload? {
return field(field: "customerAddressDelete", aliasSuffix: alias) as! Storefront.CustomerAddressDeletePayload?
}
/// Updates the address of an existing customer.
open var customerAddressUpdate: Storefront.CustomerAddressUpdatePayload? {
return internalGetCustomerAddressUpdate()
}
open func aliasedCustomerAddressUpdate(alias: String) -> Storefront.CustomerAddressUpdatePayload? {
return internalGetCustomerAddressUpdate(alias: alias)
}
func internalGetCustomerAddressUpdate(alias: String? = nil) -> Storefront.CustomerAddressUpdatePayload? {
return field(field: "customerAddressUpdate", aliasSuffix: alias) as! Storefront.CustomerAddressUpdatePayload?
}
/// Creates a new customer.
open var customerCreate: Storefront.CustomerCreatePayload? {
return internalGetCustomerCreate()
}
open func aliasedCustomerCreate(alias: String) -> Storefront.CustomerCreatePayload? {
return internalGetCustomerCreate(alias: alias)
}
func internalGetCustomerCreate(alias: String? = nil) -> Storefront.CustomerCreatePayload? {
return field(field: "customerCreate", aliasSuffix: alias) as! Storefront.CustomerCreatePayload?
}
/// Updates the default address of an existing customer.
open var customerDefaultAddressUpdate: Storefront.CustomerDefaultAddressUpdatePayload? {
return internalGetCustomerDefaultAddressUpdate()
}
open func aliasedCustomerDefaultAddressUpdate(alias: String) -> Storefront.CustomerDefaultAddressUpdatePayload? {
return internalGetCustomerDefaultAddressUpdate(alias: alias)
}
func internalGetCustomerDefaultAddressUpdate(alias: String? = nil) -> Storefront.CustomerDefaultAddressUpdatePayload? {
return field(field: "customerDefaultAddressUpdate", aliasSuffix: alias) as! Storefront.CustomerDefaultAddressUpdatePayload?
}
/// "Sends a reset password email to the customer. The reset password email
/// contains a reset password URL and token that you can pass to the
/// [`customerResetByUrl`](https://shopify.dev/api/storefront/latest/mutations/customerResetByUrl)
/// or
/// [`customerReset`](https://shopify.dev/api/storefront/latest/mutations/customerReset)
/// mutation to reset the customer password."
open var customerRecover: Storefront.CustomerRecoverPayload? {
return internalGetCustomerRecover()
}
open func aliasedCustomerRecover(alias: String) -> Storefront.CustomerRecoverPayload? {
return internalGetCustomerRecover(alias: alias)
}
func internalGetCustomerRecover(alias: String? = nil) -> Storefront.CustomerRecoverPayload? {
return field(field: "customerRecover", aliasSuffix: alias) as! Storefront.CustomerRecoverPayload?
}
/// "Resets a customer’s password with the token received from a reset password
/// email. You can send a reset password email with the
/// [`customerRecover`](https://shopify.dev/api/storefront/latest/mutations/customerRecover)
/// mutation."
open var customerReset: Storefront.CustomerResetPayload? {
return internalGetCustomerReset()
}
open func aliasedCustomerReset(alias: String) -> Storefront.CustomerResetPayload? {
return internalGetCustomerReset(alias: alias)
}
func internalGetCustomerReset(alias: String? = nil) -> Storefront.CustomerResetPayload? {
return field(field: "customerReset", aliasSuffix: alias) as! Storefront.CustomerResetPayload?
}
/// "Resets a customer’s password with the reset password URL received from a
/// reset password email. You can send a reset password email with the
/// [`customerRecover`](https://shopify.dev/api/storefront/latest/mutations/customerRecover)
/// mutation."
open var customerResetByUrl: Storefront.CustomerResetByUrlPayload? {
return internalGetCustomerResetByUrl()
}
open func aliasedCustomerResetByUrl(alias: String) -> Storefront.CustomerResetByUrlPayload? {
return internalGetCustomerResetByUrl(alias: alias)
}
func internalGetCustomerResetByUrl(alias: String? = nil) -> Storefront.CustomerResetByUrlPayload? {
return field(field: "customerResetByUrl", aliasSuffix: alias) as! Storefront.CustomerResetByUrlPayload?
}
/// Updates an existing customer.
open var customerUpdate: Storefront.CustomerUpdatePayload? {
return internalGetCustomerUpdate()
}
open func aliasedCustomerUpdate(alias: String) -> Storefront.CustomerUpdatePayload? {
return internalGetCustomerUpdate(alias: alias)
}
func internalGetCustomerUpdate(alias: String? = nil) -> Storefront.CustomerUpdatePayload? {
return field(field: "customerUpdate", aliasSuffix: alias) as! Storefront.CustomerUpdatePayload?
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "cartAttributesUpdate":
if let value = internalGetCartAttributesUpdate() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "cartBuyerIdentityUpdate":
if let value = internalGetCartBuyerIdentityUpdate() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "cartCreate":
if let value = internalGetCartCreate() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "cartDiscountCodesUpdate":
if let value = internalGetCartDiscountCodesUpdate() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "cartLinesAdd":
if let value = internalGetCartLinesAdd() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "cartLinesRemove":
if let value = internalGetCartLinesRemove() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "cartLinesUpdate":
if let value = internalGetCartLinesUpdate() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "cartNoteUpdate":
if let value = internalGetCartNoteUpdate() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "cartSelectedDeliveryOptionsUpdate":
if let value = internalGetCartSelectedDeliveryOptionsUpdate() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutAttributesUpdateV2":
if let value = internalGetCheckoutAttributesUpdateV2() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutCompleteFree":
if let value = internalGetCheckoutCompleteFree() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutCompleteWithCreditCardV2":
if let value = internalGetCheckoutCompleteWithCreditCardV2() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutCompleteWithTokenizedPaymentV3":
if let value = internalGetCheckoutCompleteWithTokenizedPaymentV3() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutCreate":
if let value = internalGetCheckoutCreate() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutCustomerAssociateV2":
if let value = internalGetCheckoutCustomerAssociateV2() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutCustomerDisassociateV2":
if let value = internalGetCheckoutCustomerDisassociateV2() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutDiscountCodeApplyV2":
if let value = internalGetCheckoutDiscountCodeApplyV2() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutDiscountCodeRemove":
if let value = internalGetCheckoutDiscountCodeRemove() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutEmailUpdateV2":
if let value = internalGetCheckoutEmailUpdateV2() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutGiftCardRemoveV2":
if let value = internalGetCheckoutGiftCardRemoveV2() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutGiftCardsAppend":
if let value = internalGetCheckoutGiftCardsAppend() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutLineItemsAdd":
if let value = internalGetCheckoutLineItemsAdd() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutLineItemsRemove":
if let value = internalGetCheckoutLineItemsRemove() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutLineItemsReplace":
if let value = internalGetCheckoutLineItemsReplace() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutLineItemsUpdate":
if let value = internalGetCheckoutLineItemsUpdate() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutShippingAddressUpdateV2":
if let value = internalGetCheckoutShippingAddressUpdateV2() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "checkoutShippingLineUpdate":
if let value = internalGetCheckoutShippingLineUpdate() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerAccessTokenCreate":
if let value = internalGetCustomerAccessTokenCreate() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerAccessTokenCreateWithMultipass":
if let value = internalGetCustomerAccessTokenCreateWithMultipass() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerAccessTokenDelete":
if let value = internalGetCustomerAccessTokenDelete() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerAccessTokenRenew":
if let value = internalGetCustomerAccessTokenRenew() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerActivate":
if let value = internalGetCustomerActivate() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerActivateByUrl":
if let value = internalGetCustomerActivateByUrl() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerAddressCreate":
if let value = internalGetCustomerAddressCreate() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerAddressDelete":
if let value = internalGetCustomerAddressDelete() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerAddressUpdate":
if let value = internalGetCustomerAddressUpdate() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerCreate":
if let value = internalGetCustomerCreate() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerDefaultAddressUpdate":
if let value = internalGetCustomerDefaultAddressUpdate() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerRecover":
if let value = internalGetCustomerRecover() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerReset":
if let value = internalGetCustomerReset() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerResetByUrl":
if let value = internalGetCustomerResetByUrl() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "customerUpdate":
if let value = internalGetCustomerUpdate() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
default:
break
}
}
return response
}
}
}
| mit | 4a4f845d5ccff995d1b1370a52a1035b | 38.837888 | 236 | 0.732368 | 4.110787 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | Buy/Client/Graph.Cache.swift | 1 | 4935 | //
// Graph.Cache.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. 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
internal extension Graph {
typealias Hash = String
class Cache {
let cacheDirectory: URL
private static let fileManager = FileManager.default
private static let cacheName = "com.buy.graph.cache"
private let memoryCache = NSCache<NSString, CacheItem>()
// ----------------------------------
// MARK: - Init -
//
init(shopName: String) {
self.cacheDirectory = Cache.cacheDirectory(for: shopName)
self.createCacheDirectoryIfNeeded()
}
private func createCacheDirectoryIfNeeded() {
let cacheDirectory = self.cacheDirectory
if !Cache.fileManager.fileExists(atPath: cacheDirectory.path) {
try! Cache.fileManager.createDirectory(at: cacheDirectory, withIntermediateDirectories: true, attributes: nil)
}
}
func purgeInMemory() {
self.memoryCache.removeAllObjects()
}
func purge() {
self.purgeInMemory()
try? Cache.fileManager.removeItem(at: self.cacheDirectory)
self.createCacheDirectoryIfNeeded()
}
// ----------------------------------
// MARK: - Item Management -
//
func item(for hash: Hash) -> CacheItem? {
if let cacheItem = self.itemInMemory(for: hash) {
return cacheItem
} else {
let location = Graph.CacheItem.Location(inParent: self.cacheDirectory, hash: hash)
if let cacheItem = CacheItem(at: location) {
self.setInMemory(cacheItem)
return cacheItem
}
}
return nil
}
func set(_ cacheItem: CacheItem) {
self.setInMemory(cacheItem)
let location = Graph.CacheItem.Location(inParent: self.cacheDirectory, hash: cacheItem.hash)
cacheItem.write(to: location)
}
func remove(for hash: Hash) {
self.removeInMemory(for: hash)
let location = Graph.CacheItem.Location(inParent: self.cacheDirectory, hash: hash)
do {
try Cache.fileManager.removeItem(at: location.dataURL)
try Cache.fileManager.removeItem(at: location.metaURL)
} catch {
Log("Failed to delete cached item on disk: \(error)")
}
}
// ----------------------------------
// MARK: - Memory Cache -
//
private func setInMemory(_ cacheItem: CacheItem) {
self.memoryCache.setObject(cacheItem, forKey: cacheItem.hash as NSString)
}
private func itemInMemory(for hash: Hash) -> CacheItem? {
return self.memoryCache.object(forKey: hash as NSString)
}
private func removeInMemory(for hash: Hash) {
self.memoryCache.removeObject(forKey: hash as NSString)
}
// ----------------------------------
// MARK: - File System Cache -
//
private static func cacheDirectory(for shopName: String) -> URL {
let tmp = URL(fileURLWithPath: NSTemporaryDirectory())
var url = tmp
url = url.appendingPathComponent(Cache.cacheName)
url = url.appendingPathComponent(Global.frameworkVersion)
url = url.appendingPathComponent(SHA256.hash(shopName))
return url
}
}
}
| mit | 9369505e24cf8d36540d94b3d521adaa | 34.76087 | 126 | 0.5692 | 5.183824 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/UITestsFoundation/Screens/Editor/AztecEditorScreen.swift | 1 | 9241 | import ScreenObject
import XCTest
public class AztecEditorScreen: ScreenObject {
enum Mode {
case rich
case html
func toggle() -> Mode {
return self == .rich ? .html : .rich
}
}
let mode: Mode
private(set) var textView: XCUIElement
private let richTextField = "aztec-rich-text-view"
private let htmlTextField = "aztec-html-text-view"
var mediaButton: XCUIElement { app.buttons["format_toolbar_insert_media"] }
var sourcecodeButton: XCUIElement { app.buttons["format_toolbar_toggle_html_view"] }
private let textViewGetter: (String) -> (XCUIApplication) -> XCUIElement = { identifier in
return { app in
var textView = app.textViews[identifier]
if textView.exists == false {
if app.otherElements[identifier].exists {
textView = app.otherElements[identifier]
}
}
return textView
}
}
init(mode: Mode, app: XCUIApplication = XCUIApplication()) throws {
self.mode = mode
let textField: String
switch mode {
case .rich:
textField = richTextField
case .html:
textField = htmlTextField
}
textView = app.textViews[textField]
try super.init(
expectedElementGetters: [ textViewGetter(textField) ],
app: app,
waitTimeout: 7
)
showOptionsStrip()
}
func showOptionsStrip() {
textView.coordinate(withNormalizedOffset: .zero).tap()
expandOptionsStrip()
}
func expandOptionsStrip() {
let expandButton = app.children(matching: .window).element(boundBy: 1).children(matching: .other).element.children(matching: .other).element.children(matching: .other).element.children(matching: .button).element
if expandButton.exists && expandButton.isHittable && !sourcecodeButton.exists {
expandButton.tap()
}
}
@discardableResult
func addList(type: String) -> AztecEditorScreen {
let listButton = app.buttons["format_toolbar_toggle_list_unordered"]
tapToolbarButton(button: listButton)
if type == "ul" {
app.buttons["Unordered List"].tap()
} else if type == "ol" {
app.buttons["Ordered List"].tap()
}
return self
}
func addListWithLines(type: String, lines: Array<String>) -> AztecEditorScreen {
addList(type: type)
for (index, line) in lines.enumerated() {
enterText(text: line)
if index != (lines.count - 1) {
app.buttons["Return"].tap()
}
}
return self
}
/**
Tapping on toolbar button. And swipes if needed.
*/
@discardableResult
func tapToolbarButton(button: XCUIElement) -> AztecEditorScreen {
let linkButton = app.buttons["format_toolbar_insert_link"]
let swipeElement = mediaButton.isHittable ? mediaButton : linkButton
if !button.exists || !button.isHittable {
swipeElement.swipeLeft()
}
Logger.log(message: "Tapping on Toolbar button: \(button)", event: .d)
button.tap()
return self
}
/**
Tapping in to textView by specific coordinate. Its always tricky to know what cooridnates to click.
Here is a list of "known" coordinates:
30:32 - first word in 2d indented line (list)
30:72 - first word in 3d intended line (blockquote)
*/
func tapByCordinates(x: Int, y: Int) -> AztecEditorScreen {
// textView frames on different devices:
// iPhone X (0.0, 88.0, 375.0, 391.0)
// iPhone SE (0.0, 64.0, 320.0, 504.0)
let frame = textView.frame
var vector = CGVector(dx: frame.minX + CGFloat(x), dy: frame.minY + CGFloat(y))
if frame.minY == 88 {
let yDiff = frame.minY - 64 // 64 - is minY for "normal" devices
vector = CGVector(dx: frame.minX + CGFloat(x), dy: frame.minY - yDiff + CGFloat(y))
}
textView.coordinate(withNormalizedOffset: CGVector.zero).withOffset(vector).tap()
sleep(1) // to make sure that "paste" manu wont show up.
return self
}
/**
Common method to type in different text fields
*/
@discardableResult
public func enterText(text: String) -> AztecEditorScreen {
app.staticTexts["aztec-content-placeholder"].tap()
textView.typeText(text)
return self
}
/**
Enters text into title field.
- Parameter text: the test to enter into the title
*/
public func enterTextInTitle(text: String) -> AztecEditorScreen {
let titleView = app.textViews["Title"]
titleView.tap()
titleView.typeText(text)
return self
}
@discardableResult
func deleteText(chars: Int) -> AztecEditorScreen {
for _ in 1...chars {
app.keys["delete"].tap()
}
return self
}
func getViewContent() -> String {
if mode == .rich {
return getTextContent()
}
return getHTMLContent()
}
/**
Selects all entered text in provided textView element
*/
func selectAllText() -> AztecEditorScreen {
textView.coordinate(withNormalizedOffset: CGVector.zero).press(forDuration: 1)
app.menuItems["Select All"].tap()
return self
}
/*
Select Image from Camera Roll by its ID. Starts with 0
Simulator range: 0..4
*/
func addImageByOrder(id: Int) throws -> AztecEditorScreen {
tapToolbarButton(button: mediaButton)
// Allow access to device media
app.tap() // trigger the media permissions alert handler
// Make sure media picker is open
if mediaButton.exists {
tapToolbarButton(button: mediaButton)
}
// Inject the first picture
try MediaPickerAlbumScreen().selectImage(atIndex: 0)
app.buttons["insert_media_button"].tap()
// Wait for upload to finish
let uploadProgressBar = app.progressIndicators["Progress"]
XCTAssertEqual(
uploadProgressBar.waitFor(predicateString: "exists == false", timeout: 10),
.completed
)
return self
}
// returns void since return screen depends on from which screen it loaded
public func closeEditor() {
XCTContext.runActivity(named: "Close the Aztec editor") { (activity) in
XCTContext.runActivity(named: "Close the More menu if needed") { (activity) in
let actionSheet = app.sheets.element(boundBy: 0)
if actionSheet.exists {
if XCUIDevice.isPad {
app.otherElements["PopoverDismissRegion"].tap()
} else {
app.sheets.buttons["Keep Editing"].tap()
}
}
}
let editorCloseButton = app.navigationBars["Azctec Editor Navigation Bar"].buttons["Close"]
editorCloseButton.tap()
XCTContext.runActivity(named: "Discard any local changes") { (activity) in
let postHasChangesSheet = app.sheets["post-has-changes-alert"]
let discardButton = XCUIDevice.isPad ? postHasChangesSheet.buttons.lastMatch : postHasChangesSheet.buttons.element(boundBy: 1)
if postHasChangesSheet.exists && (discardButton?.exists ?? false) {
Logger.log(message: "Discarding unsaved changes", event: .v)
discardButton?.tap()
}
}
XCTAssertEqual(
editorCloseButton.waitFor(predicateString: "isEnabled == false"),
.completed,
"Aztec editor should be closed but is still loaded."
)
}
}
public func publish() throws -> EditorNoticeComponent {
app.buttons["Publish"].tap()
try confirmPublish()
return try EditorNoticeComponent(withNotice: "Post published", andAction: "View")
}
private func confirmPublish() throws {
if FancyAlertComponent.isLoaded() {
try FancyAlertComponent().acceptAlert()
} else {
app.buttons["Publish Now"].tap()
}
}
public func openPostSettings() throws -> EditorPostSettings {
app.buttons["more_post_options"].tap()
app.sheets.buttons["Post Settings"].tap()
return try EditorPostSettings()
}
private func getHTMLContent() -> String {
let text = textView.value as! String
// Remove spaces between HTML tags.
let regex = try! NSRegularExpression(pattern: ">\\s+?<", options: .caseInsensitive)
let range = NSMakeRange(0, text.count)
let strippedText = regex.stringByReplacingMatches(in: text, options: .reportCompletion, range: range, withTemplate: "><")
return strippedText
}
private func getTextContent() -> String {
return textView.value as! String
}
static func isLoaded(mode: Mode = .rich) -> Bool {
(try? AztecEditorScreen(mode: mode).isLoaded) ?? false
}
}
| gpl-2.0 | 53e24041c9e5593cf8f3eacf86a5b3ef | 30.539249 | 219 | 0.595715 | 4.688483 | false | false | false | false |
damboscolo/SwiftToast | Example/SwiftToast/MainViewController.swift | 1 | 10494 | //
// ViewController.swift
// SwiftToast
//
// Created by Daniele Boscolo on 04/04/17.
// Copyright © 2017 Daniele Boscolo. All rights reserved.
//
import UIKit
import SwiftToast
class MainViewController: UIViewController {
static let simpleCellIdentifier = "simpleCellIdentifier"
@IBOutlet weak var tableView: UITableView!
struct Section {
let rows: [Row]
let headerTitle: String
}
struct Row {
let title: String
let toast: SwiftToastProtocol
}
var sections: [Section] = []
override func viewDidLoad() {
super.viewDidLoad()
sections = [
Section(rows: firstSectionRows(), headerTitle: "Default"),
Section(rows: secondSectionRows(), headerTitle: "Customized View"),
Section(rows: thirdSectionRows(), headerTitle: "Customized navigation bar")
]
}
func firstSectionRows() -> [Row] {
return [
Row(title: "Navigation bar",
toast: SwiftToast(text: "This is a navigation bar toast")),
Row(title: "Status bar",
toast: SwiftToast(
text: "This is a status bar toast",
style: .statusBar)),
Row(title: "Bottom to top",
toast: SwiftToast(
text: "This is bottom to top toast",
target: self,
style: .bottomToTop)),
Row(title: "Below navigation bar",
toast: SwiftToast(
text: "This is Below navigation bar toast",
minimumHeight: CGFloat(100.0),
style: .belowNavigationBar))
]
}
func secondSectionRows() -> [Row] {
return [
Row(title: "Custom View",
toast: CustomSwiftToast(
duration: 3.0,
minimumHeight: nil,
aboveStatusBar: true,
statusBarStyle: .lightContent,
isUserInteractionEnabled: true,
target: nil,
style: .navigationBar,
title: "CUSTOM VIEW",
subtitle: "This is a totally customized view with my subtitle",
backgroundColor: .blue
)),
Row(title: "Customized Custom View",
toast: CustomSwiftToast(
duration: nil,
minimumHeight: nil,
aboveStatusBar: true,
statusBarStyle: .lightContent,
isUserInteractionEnabled: true,
target: self,
style: .bottomToTop,
title: "CHANGED CUSTOM VIEW!",
subtitle: "Easily change. This is a subtitle with three a lot of lines! Yes, a lot of lines. It's dynamic height. Yes, totally dynamic height, This is a subtitle with three lines! Yes, a lot of lines. It's dynamic height. Yes, totally dynamic heigh ☺️☺️",
backgroundColor: .orange
))
]
}
func thirdSectionRows() -> [Row] {
// Navigation bar
return [
Row(title: "Message and image",
toast: SwiftToast(
text: "This is a customized SwiftToast with image",
textAlignment: .left,
image: #imageLiteral(resourceName: "icAlert"),
backgroundColor: .purple,
textColor: .white,
font: .boldSystemFont(ofSize: 15.0),
duration: 2.0,
statusBarStyle: .lightContent,
aboveStatusBar: true,
target: nil,
style: .navigationBar)),
Row(title: "Dark status bar",
toast: SwiftToast(
text: "See the dark status bar. Cute right?",
textAlignment: .left,
image: #imageLiteral(resourceName: "icAlert"),
backgroundColor: #colorLiteral(red: 0.9098039269, green: 0.4784313738, blue: 0.6431372762, alpha: 1),
textColor: UIColor.black,
font: UIFont.boldSystemFont(ofSize: 13.0),
duration: 4.0,
statusBarStyle: .default,
aboveStatusBar: false,
target: nil,
style: .navigationBar)),
Row(title: "Above status bar",
toast: SwiftToast(
text: "You don't see status bar and the text is on center",
textAlignment: .center,
image: nil,
backgroundColor: #colorLiteral(red: 0.9411764741, green: 0.4980392158, blue: 0.3529411852, alpha: 1),
textColor: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0),
font: UIFont.boldSystemFont(ofSize: 13.0),
duration: 2.0,
statusBarStyle: .lightContent,
aboveStatusBar: true,
target: nil,
style: .navigationBar)),
Row(title: "Very long text",
toast: SwiftToast(
text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
textAlignment: .left,
image: nil,
backgroundColor: #colorLiteral(red: 0.723318932, green: 0.7605775616, blue: 0.8339516754, alpha: 1),
textColor: .black,
font: UIFont.boldSystemFont(ofSize: 13.0),
duration: 9.0,
statusBarStyle: .default,
aboveStatusBar: false,
target: nil,
style: .navigationBar)),
Row(title: "Very long text with image",
toast: SwiftToast(
text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
textAlignment: .left,
image: #imageLiteral(resourceName: "icAlert"),
backgroundColor: #colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1),
textColor: .white,
font: UIFont.systemFont(ofSize: 14.0),
duration: 9.0,
statusBarStyle: .lightContent,
aboveStatusBar: false,
target: nil,
style: .navigationBar)),
Row(title: "Force user interaction",
toast: SwiftToast(
text: "Click here to dismiss",
textAlignment: .left,
image: #imageLiteral(resourceName: "icAlert"),
backgroundColor: #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1),
textColor: UIColor.white,
font: UIFont.boldSystemFont(ofSize: 13.0),
duration: nil,
statusBarStyle: .lightContent,
aboveStatusBar: false,
target: nil,
style: .navigationBar))
]
}
}
// MARK:- UITableViewDelegate, UITableViewDataSource
extension MainViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].rows.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section].headerTitle
}
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if section == sections.count - 1 {
return "\nPowered by Daniele Boscolo\nFor more: github/damboscolo\n\n"
}
return nil
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: MainViewController.simpleCellIdentifier)
let row = sections[indexPath.section].rows[indexPath.row]
cell.textLabel?.text = row.title
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let toast = sections[indexPath.section].rows[indexPath.row].toast
if indexPath.section == 1 {
present(toast, withCustomSwiftToastView: CustomSwiftToastView(), animated: true)
} else {
present(toast, animated: true)
}
}
}
// MARK:- SwiftToastDelegate
extension MainViewController: SwiftToastDelegate {
func swiftToastDidTouchUpInside(_ swiftToast: SwiftToastProtocol) {
let alert = UIAlertController(title: "Alert", message: "SwiftToastDidTouchUpInside delegate", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel))
present(alert, animated: true)
}
func swiftToast(_ swiftToast: SwiftToastProtocol, presentedWith height: CGFloat) {
tableView.contentInset = UIEdgeInsetsMake(0.0, 0.0, height, 0.0)
}
func swiftToastDismissed(_ swiftToast: SwiftToastProtocol) {
tableView.contentInset = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)
}
}
| mit | 971341b6ce4162676b0f6b874bdb53c4 | 42.148148 | 474 | 0.554697 | 5.34949 | false | false | false | false |
QuarkX/Quark | Tests/QuarkTests/Quark/QuarkTests.swift | 1 | 5242 | import XCTest
@testable import Quark
class QuarkTests : XCTestCase {
func testConfiguration() throws {
let file = try File(path: "/tmp/TestConfiguration", mode: .truncateWrite)
try file.write("import QuarkConfiguration\n\nconfiguration = [\"server\": [\"log\": true]]")
try file.flush()
let configuration = try loadConfiguration(configurationFile: "/tmp/TestConfiguration", arguments: [])
XCTAssertEqual(configuration["server", "log"], true)
}
func testQuarkErrorDescription() throws {
XCTAssertEqual(String(describing: QuarkError.invalidArgument(description: "foo")), "foo")
}
// func testConfigurationProperty() throws {
// QuarkConfiguration.configuration = ["foo": "bar"]
// let file = try File(path: "/tmp/QuarkConfiguration")
// let parser = JSONMapParser()
// let data = try file.readAll()
// let configuration = try parser.parse(data)
// XCTAssertEqual(configuration, ["foo": "bar"])
// }
func testLoadCommandLineArguments() throws {
var arguments = ["-server.log", "-server.host", "127.0.0.1", "-server.port", "8080"]
var parsed = try Quark.load(arguments: arguments)
XCTAssertEqual(parsed, ["server": ["log": true, "host": "127.0.0.1", "port": 8080]])
arguments = ["-server.host", "127.0.0.1", "-server.log", "-server.port", "8080"]
parsed = try Quark.load(arguments: arguments)
XCTAssertEqual(parsed, ["server": ["log": true, "host": "127.0.0.1", "port": 8080]])
arguments = ["-server.host", "127.0.0.1", "-server.port", "8080", "-server.log"]
parsed = try Quark.load(arguments: arguments)
XCTAssertEqual(parsed, ["server": ["log": true, "host": "127.0.0.1", "port": 8080]])
arguments = ["-server.log", "-server.port", "8080", "-server.host", "127.0.0.1"]
parsed = try Quark.load(arguments: arguments)
XCTAssertEqual(parsed, ["server": ["log": true, "host": "127.0.0.1", "port": 8080]])
arguments = ["-server.port", "8080", "-server.log", "-server.host", "127.0.0.1"]
parsed = try Quark.load(arguments: arguments)
XCTAssertEqual(parsed, ["server": ["log": true, "host": "127.0.0.1", "port": 8080]])
arguments = ["-server.port", "8080", "-server.host", "127.0.0.1", "-server.log"]
parsed = try Quark.load(arguments: arguments)
XCTAssertEqual(parsed, ["server": ["log": true, "host": "127.0.0.1", "port": 8080]])
arguments = ["foo"]
XCTAssertThrowsError(try Quark.load(arguments: arguments))
arguments = ["-foo", "bar", "baz"]
XCTAssertThrowsError(try Quark.load(arguments: arguments))
arguments = ["-foo", "-bar", "baz", "buh"]
XCTAssertThrowsError(try Quark.load(arguments: arguments))
}
func testLoadEnvironmentVariables() throws {
let variables = ["FOO_BAR": "fuu", "_": "baz"]
let parsed = Quark.load(environmentVariables: variables)
XCTAssertEqual(parsed, ["fooBar": "fuu", "_": "baz"])
}
func testParseValues() throws {
XCTAssertEqual(parse(value: ""), "")
XCTAssertEqual(parse(value: "NULL"), nil)
XCTAssertEqual(parse(value: "Null"), nil)
XCTAssertEqual(parse(value: "null"), nil)
XCTAssertEqual(parse(value: "NIL"), nil)
XCTAssertEqual(parse(value: "Nil"), nil)
XCTAssertEqual(parse(value: "nil"), nil)
XCTAssertEqual(parse(value: "1964"), 1964)
XCTAssertEqual(parse(value: "4.20"), 4.2)
XCTAssertEqual(parse(value: "TRUE"), true)
XCTAssertEqual(parse(value: "True"), true)
XCTAssertEqual(parse(value: "true"), true)
XCTAssertEqual(parse(value: "FALSE"), false)
XCTAssertEqual(parse(value: "False"), false)
XCTAssertEqual(parse(value: "false"), false)
XCTAssertEqual(parse(value: "foo"), "foo")
}
func testBuildConfigurationBuildPath() throws {
XCTAssertEqual(BuildConfiguration.debug.buildPath, "debug")
XCTAssertEqual(BuildConfiguration.release.buildPath, "release")
XCTAssertEqual(BuildConfiguration.fast.buildPath, "release")
}
func testSpawnErorDescription() throws {
XCTAssertEqual(String(describing: SpawnError.exitStatus(0, [])), "exit(0): []")
}
func testSystemFailure() throws {
XCTAssertThrowsError(try sys([]))
XCTAssertThrowsError(try sys(["foo"]))
XCTAssertThrowsError(try sys(["cd", "foo"]))
}
}
extension QuarkTests {
static var allTests : [(String, (QuarkTests) -> () throws -> Void)] {
return [
("testConfiguration", testConfiguration),
("testQuarkErrorDescription", testQuarkErrorDescription),
// ("testConfigurationProperty", testConfigurationProperty),
("testLoadCommandLineArguments", testLoadCommandLineArguments),
("testLoadEnvironmentVariables", testLoadEnvironmentVariables),
("testParseValues", testParseValues),
("testBuildConfigurationBuildPath", testBuildConfigurationBuildPath),
("testSpawnErorDescription", testSpawnErorDescription),
("testSystemFailure", testSystemFailure),
]
}
}
| mit | 299f4de08bfff3f7bed25fca5b7398b7 | 43.803419 | 109 | 0.623998 | 4.220612 | false | true | false | false |
hgani/ganilib-ios | glib/Classes/Screen/Nav/MenuItem.swift | 1 | 1376 | public class MenuItem {
public private(set) var title: String
public private(set) var icon: GIcon?
private(set) var controller: UIViewController?
private(set) var onClick: (() -> Void)?
private(set) var isRoot = false
private(set) var cellClass: GTableViewCustomCell.Type = MenuCell.self
// public init(title: String, icon: String, root: Bool) {
// self.title = title
// self.icon = icon
// isRoot = root
// }
public init(title: String) {
self.title = title
}
public func icon(_ icon: GIcon) -> Self {
self.icon = icon
return self
}
public func root(_ root: Bool) -> Self {
isRoot = root
return self
}
public func screen(_ screen: GScreen) -> Self {
controller = screen
return self
}
public func onClick(_ onClick: @escaping () -> Void) -> Self {
self.onClick = onClick
return self
}
public func cellClass(_ cellClass: GTableViewCustomCell.Type) -> Self {
self.cellClass = cellClass
return self
}
public func hasAction() -> Bool {
return controller != nil || onClick != nil
}
}
#if INCLUDE_EUREKA
extension MenuItem {
public func screen(_ screen: GFormScreen) -> Self {
controller = screen
return self
}
}
#endif
| mit | 95ab8f03917eaa3dc0a91f178d290683 | 22.322034 | 75 | 0.577035 | 4.233846 | false | false | false | false |
paoloiulita/AbstractNumericStepper | Example/AbstractNumericStepper/Views/SecondNS.swift | 1 | 801 | //
// FirstNS.swift
// AbstractNumericStepper
//
// Created by Paolo Iulita on 04/05/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
import AbstractNumericStepper
class SecondNS: AbstractNumericStepper {
// MARK: initializers
override init(frame: CGRect) {
super.init(frame: frame)
loadViewFromNib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadViewFromNib()
}
// MARK: private methods
private func loadViewFromNib() {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "SecondNS", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
view.frame = bounds
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.addSubview(view);
}
} | mit | 0822dfc6ceebef726fa67834a4ff7797 | 21.25 | 71 | 0.72125 | 3.571429 | false | false | false | false |
vtourraine/AcknowList | Sources/AcknowList/AcknowListSwiftUI.swift | 1 | 7537 | //
// AcknowListSwiftUI.swift
//
// Copyright (c) 2015-2022 Vincent Tourraine (https://www.vtourraine.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import SwiftUI
extension Acknow: Identifiable {
public var id: String {
get {
title
}
}
}
/// View that displays a list of acknowledgements.
@available(iOS 13.0.0, macOS 10.15.0, watchOS 7.0.0, tvOS 13.0.0, *)
public struct AcknowListSwiftUIView: View {
/// The represented array of `Acknow`.
public var acknowledgements: [Acknow] = []
/// Header text to be displayed above the list of the acknowledgements.
public var headerText: String?
/// Footer text to be displayed below the list of the acknowledgements.
public var footerText: String?
public init(acknowList: AcknowList) {
acknowledgements = acknowList.acknowledgements
headerText = acknowList.headerText
footerText = acknowList.footerText
}
public init(acknowledgements: [Acknow], headerText: String? = nil, footerText: String? = nil) {
self.acknowledgements = acknowledgements
self.headerText = headerText
self.footerText = footerText
}
public init(plistFileURL: URL) {
guard let data = try? Data(contentsOf: plistFileURL),
let acknowList = try? AcknowPodDecoder().decode(from: data) else {
self.init(acknowledgements: [], headerText: nil, footerText: nil)
return
}
let header: String?
if acknowList.headerText != AcknowPodDecoder.K.DefaultHeaderText {
header = acknowList.headerText
}
else {
header = nil
}
self.init(acknowledgements: acknowList.acknowledgements, headerText: header, footerText: acknowList.footerText)
}
struct HeaderFooter: View {
let text: String?
var body: some View {
if let text = text {
Text(text)
}
else {
EmptyView()
}
}
}
public var body: some View {
#if os(iOS) || os(tvOS)
List {
Section(header: HeaderFooter(text: headerText), footer: HeaderFooter(text: footerText)) {
ForEach (acknowledgements) { acknowledgement in
AcknowListRowSwiftUIView(acknowledgement: acknowledgement)
}
}
}
.listStyle(GroupedListStyle())
.navigationBarTitle(Text(AcknowLocalization.localizedTitle()))
#else
List {
Section(header: HeaderFooter(text: headerText), footer: HeaderFooter(text: footerText)) {
ForEach (acknowledgements) { acknowledgement in
AcknowListRowSwiftUIView(acknowledgement: acknowledgement)
}
}
}
#endif
}
}
/// View that displays a row in a list of acknowledgements.
@available(iOS 13.0.0, macOS 10.15.0, watchOS 7.0.0, tvOS 13.0.0, *)
public struct AcknowListRowSwiftUIView: View {
/// The represented `Acknow`.
public var acknowledgement: Acknow
public var body: some View {
if acknowledgement.text != nil {
NavigationLink(destination: AcknowSwiftUIView(acknowledgement: acknowledgement)) {
Text(acknowledgement.title)
}
}
else if let repository = acknowledgement.repository,
canOpenRepository(for: repository) {
Button(action: {
#if os(iOS)
UIApplication.shared.open(repository)
#endif
}) {
Text(acknowledgement.title)
.foregroundColor(.primary)
}
}
else {
Text(acknowledgement.title)
}
}
private func canOpenRepository(for url: URL) -> Bool {
guard let scheme = url.scheme else {
return false
}
return scheme == "http" || scheme == "https"
}
}
@available(iOS 13.0.0, macOS 10.15.0, watchOS 7.0.0, tvOS 13.0.0, *)
struct AcknowListSwiftUI_Previews: PreviewProvider {
static let license = """
Copyright (c) 2015-2021 Vincent Tourraine (https://www.vtourraine.net)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
static let acks = [Acknow(title: "Title 1", text: license),
Acknow(title: "Title 2", text: license),
Acknow(title: "Title 3", text: license)]
static var previews: some View {
NavigationView {
AcknowListSwiftUIView(acknowledgements: acks)
}
.previewDevice(PreviewDevice(rawValue: "iPhone 12"))
NavigationView {
AcknowListSwiftUIView(acknowledgements: acks, headerText: "Test Header", footerText: "Test Footer")
}
.previewDevice(PreviewDevice(rawValue: "iPhone 12"))
NavigationView {
AcknowListSwiftUIView(acknowledgements: acks, headerText: "Test Header", footerText: "Test Footer")
}
.previewDevice(PreviewDevice(rawValue: "Apple TV 4K"))
NavigationView {
AcknowListSwiftUIView(acknowledgements: acks, headerText: "Test Header", footerText: "Test Footer")
}
.previewDevice(PreviewDevice(rawValue: "Apple Watch Series 6 - 44mm"))
NavigationView {
AcknowListSwiftUIView(acknowledgements: acks, headerText: "Test Header", footerText: "Test Footer")
}
.previewDevice(PreviewDevice(rawValue: "Mac"))
}
}
| mit | d1167729e16460a599d37f324530feec | 38.255208 | 468 | 0.651453 | 4.716521 | false | false | false | false |
Dsringari/scan4pase | Project/scan4pase/InvoiceVC.swift | 1 | 8738 | //
// InvoiceVC.swift
// scan4pase
//
// Created by Dhruv Sringari on 7/7/16.
// Copyright © 2016 Dhruv Sringari. All rights reserved.
//
import UIKit
class InvoiceVC: UIViewController {
@IBOutlet var textview: UITextView!
var paymentMethod: PaymentMethod = .cash
var paid: Bool = true
var name: String!
var iboNumber: String!
var checkNumber: String!
var otherMethodName: String!
var invoiceText: NSMutableAttributedString = NSMutableAttributedString(string: "")
var subject: String = ""
var cartDelegate: CartVCDelegate!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
buildText()
let keyboardDoneButtonView = UIToolbar()
keyboardDoneButtonView.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissKeyboard))
let flexibleWidth = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
keyboardDoneButtonView.items = [flexibleWidth, doneButton]
textview.inputAccessoryView = keyboardDoneButtonView
}
func buildText() {
// Justifications Config
let paragraphCenter = NSMutableParagraphStyle()
paragraphCenter.alignment = .center
let paragraphRight = NSMutableParagraphStyle()
paragraphRight.alignment = .right
// Styles
let fontSize: CGFloat = 15
let bold = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: fontSize), NSAttributedStringKey.foregroundColor: UIColor.black]
let boldBlue = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: fontSize), NSAttributedStringKey.foregroundColor: UIColor(red: 43, green: 130, blue: 201)]
let normal = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: fontSize), NSAttributedStringKey.foregroundColor: UIColor.black]
let normalRight = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: fontSize), NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.paragraphStyle: paragraphRight]
subject = "scan4pase - Invoice - \(name)"
// Identification
invoiceText += NSMutableAttributedString(string: "Identification\n", attributes: boldBlue)
invoiceText += NSMutableAttributedString(string: "Payee: ", attributes: bold) + NSMutableAttributedString(string: name + "\n", attributes: normal)
invoiceText += NSMutableAttributedString(string: "IBO Number: ", attributes: bold) + NSMutableAttributedString(string: iboNumber + "\n", attributes: normal)
// Payment Details
invoiceText += NSMutableAttributedString(string: "Payment Details\n", attributes: boldBlue)
invoiceText += NSMutableAttributedString(string: "Paid: ", attributes: bold) + NSMutableAttributedString(string: (paid ? "Yes" : "No") + "\n", attributes: normal)
if paid {
invoiceText += NSMutableAttributedString(string: "Payment Method: ", attributes: bold)
switch paymentMethod {
case PaymentMethod.cash:
invoiceText += NSMutableAttributedString(string: "Cash\n", attributes: normal)
case PaymentMethod.check:
invoiceText += NSMutableAttributedString(string: "Check\n", attributes: normal)
invoiceText += NSMutableAttributedString(string:"Check Number: ", attributes: bold) + NSMutableAttributedString(string: checkNumber + "\n", attributes: normal)
case PaymentMethod.creditCard:
invoiceText += NSMutableAttributedString(string:"Credit Card\n", attributes: normal)
case PaymentMethod.other:
invoiceText += NSMutableAttributedString(string: otherMethodName + "\n", attributes: normal)
}
}
// Order Details
let pointFormatter = NumberFormatter()
pointFormatter.numberStyle = .decimal
pointFormatter.maximumFractionDigits = 2
pointFormatter.minimumIntegerDigits = 1
pointFormatter.minimumFractionDigits = 2
let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .currency
invoiceText += NSMutableAttributedString(string: "Order Details\n", attributes: boldBlue)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a EEE MMMM d, yy"
invoiceText += NSMutableAttributedString(string: "Date: ", attributes: bold)
+ NSMutableAttributedString(string: dateFormatter.string(from: Date()) + "\n", attributes: normal)
let pvBVAttributedText = NSMutableAttributedString(string: "PV/BV Total: ", attributes: bold)
invoiceText += pvBVAttributedText
+ NSMutableAttributedString(string: pointFormatter.string(from: cartDelegate.pvTotal)! + " / " + pointFormatter.string(from: cartDelegate.bvTotal)! + "\n", attributes: normalRight)
let subtotalAttributedText = NSMutableAttributedString(string: "Subtotal (IBO / Retail): ", attributes: bold)
invoiceText += subtotalAttributedText
+ NSMutableAttributedString(string: currencyFormatter.string(from: cartDelegate.iboCostSubtotal)! + " / " + currencyFormatter.string(from: cartDelegate.retailCostSubtotal)! + "\n", attributes: normalRight)
let grandTotalAttributedText = NSMutableAttributedString(string: "Grand Total (IBO / Retail): ", attributes: bold)
invoiceText += grandTotalAttributedText
+ NSMutableAttributedString(string: currencyFormatter.string(from: cartDelegate.iboCostGrandTotal)! + " / " + currencyFormatter.string(from: cartDelegate.retailCostGrandTotal)! + "\n", attributes: normalRight)
if paymentMethod == .creditCard {
if let tax = UserDefaults.standard.object(forKey: "creditCardFeePercentage") as? NSNumber {
var tax = NSDecimalNumber(decimal: tax.decimalValue)
tax = tax.multiplying(byPowerOf10: -2)
tax = tax.adding(1)
let roundUP = NSDecimalNumberHandler(roundingMode: .plain, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true)
let iboGrandTotalWithFee = cartDelegate.iboCostGrandTotal.multiplying(by: tax, withBehavior: roundUP)
let retailGrandTotalWithFee = cartDelegate.retailCostGrandTotal.multiplying(by: tax, withBehavior: roundUP)
let iboGrandTotalWithFeeAttributedText = NSMutableAttributedString(string: "Grand Total w/ CC Fee (IBO / Retail): ", attributes: bold)
invoiceText += iboGrandTotalWithFeeAttributedText
+ NSMutableAttributedString(string: currencyFormatter.string(from: iboGrandTotalWithFee)! + " / " + currencyFormatter.string(from: retailGrandTotalWithFee)! + "\n", attributes: normalRight)
}
}
// Purchased Items
invoiceText += NSMutableAttributedString(string: "Purchased Items (\(cartDelegate.quantityTotal.stringValue))\n", attributes: boldBlue)
if let cartProducts = CartProduct.mr_findAll() as? [CartProduct] {
for cartProduct in cartProducts {
invoiceText += NSMutableAttributedString(string: "\(cartProduct.product!.sku!)\(cartProduct.product!.custom!.boolValue ? " Custom" : "") \(cartProduct.taxable!.boolValue ? "Taxed" : "Not Taxed") (\(cartProduct.quantity!.stringValue))", attributes: boldBlue)
invoiceText += NSMutableAttributedString(string: " - \(cartProduct.product!.name!)\n", attributes: normal)
}
}
textview.attributedText = invoiceText
}
@IBAction func shareInvoice(_ sender: AnyObject) {
let invoice = Invoice(subject: subject, message: invoiceText)
let activityViewController = UIActivityViewController(activityItems: [invoice], applicationActivities: nil)
activityViewController.completionWithItemsHandler = {_, completed, _, _ in
if (completed) {
self.performSegue(withIdentifier: "exit", sender: self)
}
}
present(activityViewController, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | c2bb1040e05d388ec3dcd6e8d77edef2 | 52.932099 | 273 | 0.693487 | 5.130358 | false | false | false | false |
zapdroid/RXWeather | Pods/Nimble/Sources/Nimble/Expression.swift | 1 | 4289 | import Foundation
// Memoizes the given closure, only calling the passed
// closure once; even if repeat calls to the returned closure
internal func memoizedClosure<T>(_ closure: @escaping () throws -> T) -> (Bool) throws -> T {
var cache: T?
return ({ withoutCaching in
if withoutCaching || cache == nil {
cache = try closure()
}
return cache!
})
}
/// Expression represents the closure of the value inside expect(...).
/// Expressions are memoized by default. This makes them safe to call
/// evaluate() multiple times without causing a re-evaluation of the underlying
/// closure.
///
/// @warning Since the closure can be any code, Objective-C code may choose
/// to raise an exception. Currently, Expression does not memoize
/// exception raising.
///
/// This provides a common consumable API for matchers to utilize to allow
/// Nimble to change internals to how the captured closure is managed.
public struct Expression<T> {
internal let _expression: (Bool) throws -> T?
internal let _withoutCaching: Bool
public let location: SourceLocation
public let isClosure: Bool
/// Creates a new expression struct. Normally, expect(...) will manage this
/// creation process. The expression is memoized.
///
/// @param expression The closure that produces a given value.
/// @param location The source location that this closure originates from.
/// @param isClosure A bool indicating if the captured expression is a
/// closure or internally produced closure. Some matchers
/// may require closures. For example, toEventually()
/// requires an explicit closure. This gives Nimble
/// flexibility if @autoclosure behavior changes between
/// Swift versions. Nimble internals always sets this true.
public init(expression: @escaping () throws -> T?, location: SourceLocation, isClosure: Bool = true) {
_expression = memoizedClosure(expression)
self.location = location
_withoutCaching = false
self.isClosure = isClosure
}
/// Creates a new expression struct. Normally, expect(...) will manage this
/// creation process.
///
/// @param expression The closure that produces a given value.
/// @param location The source location that this closure originates from.
/// @param withoutCaching Indicates if the struct should memoize the given
/// closure's result. Subsequent evaluate() calls will
/// not call the given closure if this is true.
/// @param isClosure A bool indicating if the captured expression is a
/// closure or internally produced closure. Some matchers
/// may require closures. For example, toEventually()
/// requires an explicit closure. This gives Nimble
/// flexibility if @autoclosure behavior changes between
/// Swift versions. Nimble internals always sets this true.
public init(memoizedExpression: @escaping (Bool) throws -> T?, location: SourceLocation, withoutCaching: Bool, isClosure: Bool = true) {
_expression = memoizedExpression
self.location = location
_withoutCaching = withoutCaching
self.isClosure = isClosure
}
/// Returns a new Expression from the given expression. Identical to a map()
/// on this type. This should be used only to typecast the Expression's
/// closure value.
///
/// The returned expression will preserve location and isClosure.
///
/// @param block The block that can cast the current Expression value to a
/// new type.
public func cast<U>(_ block: @escaping (T?) throws -> U?) -> Expression<U> {
return Expression<U>(expression: ({ try block(self.evaluate()) }), location: location, isClosure: isClosure)
}
public func evaluate() throws -> T? {
return try _expression(_withoutCaching)
}
public func withoutCaching() -> Expression<T> {
return Expression(memoizedExpression: _expression, location: location, withoutCaching: true, isClosure: isClosure)
}
}
| mit | e4ed1971a63ce436f3c2edd3bb35f450 | 46.655556 | 140 | 0.650035 | 5.211422 | false | false | false | false |
alexandrehcdc/dejavi | dejavi/CategoryRow.swift | 1 | 1109 | import Foundation
import UIKit
import RealmSwift
class CategoryRow : UITableViewCell { }
extension CategoryRow : UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 12
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("videoCell", forIndexPath: indexPath)
return cell
}
}
extension CategoryRow : UICollectionViewDelegateFlowLayout {
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let hardCodedPadding:CGFloat = 5
let itemsPerRow:CGFloat = 3
let itemWidth = (collectionView.bounds.width / itemsPerRow) - hardCodedPadding
let itemHeight = collectionView.bounds.height - (2 * hardCodedPadding)
return CGSize(width: itemWidth, height: itemHeight)
}
} | mit | f2bfbc2c5d187214590356870e1bb144 | 36 | 169 | 0.74752 | 6.127072 | false | false | false | false |
modocache/swift | test/SILGen/property_abstraction.swift | 2 | 4841 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
struct Int {
mutating func foo() {}
}
struct Foo<T, U> {
var f: (T) -> U
var g: T
}
// CHECK-LABEL: sil hidden @_TF20property_abstraction4getF
// CHECK: bb0([[X_ORIG:%.*]] : $Foo<Int, Int>):
// CHECK: [[F_ORIG:%.*]] = struct_extract [[X_ORIG]] : $Foo<Int, Int>, #Foo.f
// CHECK: strong_retain [[F_ORIG]]
// CHECK: [[REABSTRACT_FN:%.*]] = function_ref @_TTR
// CHECK: [[F_SUBST:%.*]] = partial_apply [[REABSTRACT_FN]]([[F_ORIG]])
// CHECK: return [[F_SUBST]]
func getF(_ x: Foo<Int, Int>) -> (Int) -> Int {
return x.f
}
// CHECK-LABEL: sil hidden @_TF20property_abstraction4setF
// CHECK: [[REABSTRACT_FN:%.*]] = function_ref @_TTR
// CHECK: [[F_ORIG:%.*]] = partial_apply [[REABSTRACT_FN]]({{%.*}})
// CHECK: [[F_ADDR:%.*]] = struct_element_addr {{%.*}} : $*Foo<Int, Int>, #Foo.f
// CHECK: assign [[F_ORIG]] to [[F_ADDR]]
func setF(_ x: inout Foo<Int, Int>, f: @escaping (Int) -> Int) {
x.f = f
}
func inOutFunc(_ f: inout ((Int) -> Int)) { }
// CHECK-LABEL: sil hidden @_TF20property_abstraction6inOutF
// CHECK: [[INOUTFUNC:%.*]] = function_ref @_TF20property_abstraction9inOutFunc
// CHECK: [[F_ADDR:%.*]] = struct_element_addr {{%.*}} : $*Foo<Int, Int>, #Foo.f
// CHECK: [[F_SUBST_MAT:%.*]] = alloc_stack
// CHECK: [[F_ORIG:%.*]] = load [[F_ADDR]]
// CHECK: [[REABSTRACT_FN:%.*]] = function_ref @_TTR
// CHECK: [[F_SUBST_IN:%.*]] = partial_apply [[REABSTRACT_FN]]([[F_ORIG]])
// CHECK: store [[F_SUBST_IN]] to [[F_SUBST_MAT]]
// CHECK: apply [[INOUTFUNC]]([[F_SUBST_MAT]])
// CHECK: [[F_SUBST_OUT:%.*]] = load [[F_SUBST_MAT]]
// CHECK: [[REABSTRACT_FN:%.*]] = function_ref @_TTR
// CHECK: [[F_ORIG:%.*]] = partial_apply [[REABSTRACT_FN]]([[F_SUBST_OUT]])
// CHECK: assign [[F_ORIG]] to [[F_ADDR]]
func inOutF(_ x: Foo<Int, Int>) {
var x = x
inOutFunc(&x.f)
}
// Don't produce a writeback for generic lvalues when there's no real
// abstraction difference. <rdar://problem/16530674>
// CHECK-LABEL: sil hidden @_TF20property_abstraction23noAbstractionDifference
func noAbstractionDifference(_ x: Foo<Int, Int>) {
var x = x
// CHECK: [[ADDR:%.*]] = struct_element_addr {{%.*}}, #Foo.g
// CHECK: apply {{%.*}}([[ADDR]])
x.g.foo()
}
protocol P {}
struct AddressOnlyLet<T> {
let f: (T) -> T
let makeAddressOnly: P
}
// CHECK-LABEL: sil hidden @_TF20property_abstraction34getAddressOnlyReabstractedProperty{{.*}} : $@convention(thin) (@in AddressOnlyLet<Int>) -> @owned @callee_owned (Int) -> Int
// CHECK: [[CLOSURE_ADDR:%.*]] = struct_element_addr {{%.*}} : $*AddressOnlyLet<Int>, #AddressOnlyLet.f
// CHECK: [[CLOSURE_ORIG:%.*]] = load [[CLOSURE_ADDR]]
// CHECK: [[REABSTRACT:%.*]] = function_ref
// CHECK: [[CLOSURE_SUBST:%.*]] = partial_apply [[REABSTRACT]]([[CLOSURE_ORIG]])
// CHECK: return [[CLOSURE_SUBST]]
func getAddressOnlyReabstractedProperty(_ x: AddressOnlyLet<Int>) -> (Int) -> Int {
return x.f
}
enum Bar<T, U> {
case F((T) -> U)
}
func getF(_ x: Bar<Int, Int>) -> (Int) -> Int {
switch x {
case .F(var f):
return f
}
}
func makeF(_ f: @escaping (Int) -> Int) -> Bar<Int, Int> {
return Bar.F(f)
}
struct ArrayLike<T> {
subscript(x: ()) -> T { get {} set {} }
}
typealias Test20341012 = (title: (), action: () -> ())
struct T20341012 {
private var options: ArrayLike<Test20341012> { get {} set {} }
// CHECK-LABEL: sil hidden @_TFV20property_abstraction9T203410121t{{.*}}
// CHECK: [[TMP1:%.*]] = alloc_stack $(title: (), action: @callee_owned (@in ()) -> @out ())
// CHECK: apply {{.*}}<(title: (), action: () -> ())>([[TMP1]],
mutating func t() {
_ = self.options[].title
}
}
class MyClass {}
// When simply assigning to a property, reabstract the r-value and assign
// to the base instead of materializing and then assigning.
protocol Factory {
associatedtype Product
var builder : () -> Product { get set }
}
func setBuilder<F: Factory where F.Product == MyClass>(_ factory: inout F) {
factory.builder = { return MyClass() }
}
// CHECK: sil hidden @_TF20property_abstraction10setBuilder{{.*}} : $@convention(thin) <F where F : Factory, F.Product == MyClass> (@inout F) -> ()
// CHECK: bb0(%0 : $*F):
// CHECK: [[F0:%.*]] = function_ref @_TFF20property_abstraction10setBuilder{{.*}} : $@convention(thin) () -> @owned MyClass
// CHECK: [[F1:%.*]] = thin_to_thick_function [[F0]]
// CHECK: [[SETTER:%.*]] = witness_method $F, #Factory.builder!setter.1
// CHECK: [[REABSTRACTOR:%.*]] = function_ref @_TTR
// CHECK: [[F2:%.*]] = partial_apply [[REABSTRACTOR]]([[F1]])
// CHECK: apply [[SETTER]]<F, MyClass>([[F2]], %0)
| apache-2.0 | d6918b101371828483ad75d3acc6d8eb | 36.238462 | 179 | 0.570956 | 3.304437 | false | false | false | false |
huonw/swift | test/PCMacro/Inputs/SilentPlaygroundsRuntime.swift | 27 | 2394 | // If you're modifying this file to add or modify function signatures, you
// should be notifying the maintainer of PlaygroundLogger and also the
// maintainer of lib/Sema/PlaygroundTransform.cpp.
struct SourceRange {
let sl : Int
let el : Int
let sc : Int
let ec : Int
var text : String {
return "[\(sl):\(sc)-\(el):\(ec)]"
}
}
class LogRecord {
let text : String
init(api : String, object : Any, name : String, id : Int, range : SourceRange) {
var object_description : String = ""
print(object, terminator: "", to: &object_description)
text = range.text + " " + api + "[" + name + "='" + object_description + "']"
}
init(api : String, object : Any, name : String, range : SourceRange) {
var object_description : String = ""
print(object, terminator: "", to: &object_description)
text = range.text + " " + api + "[" + name + "='" + object_description + "']"
}
init(api : String, object: Any, range : SourceRange) {
var object_description : String = ""
print(object, terminator: "", to: &object_description)
text = range.text + " " + api + "['" + object_description + "']"
}
init(api: String, range : SourceRange) {
text = range.text + " " + api
}
}
func $builtin_log<T>(_ object : T, _ name : String, _ sl : Int, _ el : Int, _ sc : Int, _ ec: Int) -> AnyObject? {
return LogRecord(api:"$builtin_log", object:object, name:name, range : SourceRange(sl:sl, el:el, sc:sc, ec:ec))
}
func $builtin_log_with_id<T>(_ object : T, _ name : String, _ id : Int, _ sl : Int, _ el : Int, _ sc : Int, _ ec: Int) -> AnyObject? {
return LogRecord(api:"$builtin_log", object:object, name:name, id:id, range : SourceRange(sl:sl, el:el, sc:sc, ec:ec))
}
func $builtin_log_scope_entry(_ sl : Int, _ el : Int, _ sc : Int, _ ec: Int) -> AnyObject? {
return LogRecord(api:"$builtin_log_scope_entry", range : SourceRange(sl:sl, el:el, sc:sc, ec:ec))
}
func $builtin_log_scope_exit(_ sl : Int, _ el : Int, _ sc : Int, _ ec: Int) -> AnyObject? {
return LogRecord(api:"$builtin_log_scope_exit", range : SourceRange(sl:sl, el:el, sc:sc, ec:ec))
}
func $builtin_postPrint(_ sl : Int, _ el : Int, _ sc : Int, _ ec: Int) -> AnyObject? {
return LogRecord(api:"$builtin_postPrint", range : SourceRange(sl:sl, el:el, sc:sc, ec:ec))
}
func $builtin_send_data(_ object:AnyObject?) {
let would_print = ((object as! LogRecord).text)
}
| apache-2.0 | 4793774b6d69fdcfaae5c90e92054f8d | 37.612903 | 134 | 0.615288 | 3.162483 | false | false | false | false |
steven7/ParkingApp | rethink-swift-master/Sources/Rethink/ReProtocol.swift | 1 | 5878 | /** Rethink.swift
Copyright (c) 2015 Pixelspark
Author: Tommy van der Vorst ([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
public enum ReProtocolVersion {
case v0_4
case v1_0
var protocolVersionCode: UInt32 {
switch self {
case .v0_4: return 0x400c2d20
case .v1_0: return 0x34c2bdc3
}
}
}
/** Protocol constants. */
internal class ReProtocol {
static let defaultPort = 28015
static let protocolType: UInt32 = 0x7e6970c7 // JSON
static let handshakeSuccessResponse = "SUCCESS"
static let defaultUser = "admin"
static let defaultPassword = ""
static let responseTypeSuccessAtom = 1
static let responseTypeSuccessSequence = 2
static let responseTypeSuccessPartial = 3
static let responseTypeWaitComplete = 4
static let responseTypeClientError = 16
static let responseTypeCompileError = 17
static let responseTypeRuntimeError = 18
enum ReQueryType: Int {
case start = 1
case `continue` = 2
case stop = 3
case noreply_WAIT = 4
}
}
/** These constants can be found in the RethinkDB Java driver source code:
https://github.com/rethinkdb/rethinkdb/blob/next/drivers/java/term_info.json */
internal enum ReTerm: Int {
case datum = 1
case make_array = 2
case make_obj = 3
case `var` = 10
case javascript = 11
case uuid = 169
case http = 153
case error = 12
case implicit_VAR = 13
case db = 14
case table = 15
case get = 16
case get_ALL = 78
case eq = 17
case ne = 18
case lt = 19
case le = 20
case gt = 21
case ge = 22
case not = 23
case add = 24
case sub = 25
case mul = 26
case div = 27
case mod = 28
case floor = 183
case ceil = 184
case round = 185
case append = 29
case prepend = 80
case difference = 95
case set_insert = 88
case set_intersection = 89
case set_union = 90
case set_difference = 91
case slice = 30
case skip = 70
case limit = 71
case offsets_OF = 87
case contains = 93
case get_field = 31
case keys = 94
case object = 143
case has_fields = 32
case with_fields = 96
case pluck = 33
case without = 34
case merge = 35
case between_deprecated = 36
case between = 182
case reduce = 37
case map = 38
case filter = 39
case concat_MAP = 40
case order_BY = 41
case distinct = 42
case count = 43
case is_EMPTY = 86
case union = 44
case nth = 45
case bracket = 170
case inner_join = 48
case outer_join = 49
case eq_join = 50
case zip = 72
case range = 173
case insert_at = 82
case delete_at = 83
case change_at = 84
case splice_at = 85
case coerce_to = 51
case type_of = 52
case update = 53
case delete = 54
case replace = 55
case insert = 56
case db_create = 57
case db_drop = 58
case db_list = 59
case table_create = 60
case table_drop = 61
case table_list = 62
case config = 174
case status = 175
case wait = 177
case reconfigure = 176
case rebalance = 179
case sync = 138
case index_create = 75
case index_drop = 76
case index_list = 77
case index_status = 139
case index_wait = 140
case index_rename = 156
case funcall = 64
case branch = 65
case or = 66
case and = 67
case for_each = 68
case `func` = 69
case asc = 73
case desc = 74
case info = 79
case match = 97
case upcase = 141
case downcase = 142
case sample = 81
case `default` = 92
case json = 98
case to_json_string = 172
case iso8601 = 99
case to_ISO8601 = 100
case epoch_time = 101
case to_epoch_time = 102
case now = 103
case in_timezone = 104
case during = 105
case date = 106
case time_of_day = 126
case timezone = 127
case year = 128
case month = 129
case day = 130
case day_of_week = 131
case day_of_year = 132
case hours = 133
case minutes = 134
case seconds = 135
case time = 136
case monday = 107
case tuesday = 108
case wednesday = 109
case thursday = 110
case friday = 111
case saturday = 112
case sunday = 113
case january = 114
case february = 115
case march = 116
case april = 117
case may = 118
case june = 119
case july = 120
case august = 121
case september = 122
case october = 123
case november = 124
case december = 125
case literal = 137
case group = 144
case sum = 145
case avg = 146
case min = 147
case max = 148
case split = 149
case ungroup = 150
case random = 151
case changes = 152
case args = 154
case binary = 155
case geojson = 157
case to_geojson = 158
case point = 159
case line = 160
case polygon = 161
case distance = 162
case intersects = 163
case includes = 164
case circle = 165
case get_intersecting = 166
case fill = 167
case get_nearest = 168
case polygon_sub = 171
case minval = 180
case maxval = 181
case fold = 187
case grant = 188
}
internal typealias ReQueryToken = UInt64
internal class ReTokenCounter {
private var nextQueryToken: UInt64 = 0x5ADFACE
private let mutex = Mutex()
func next() -> ReQueryToken {
return self.mutex.locked {
let nt = self.nextQueryToken
self.nextQueryToken += 1
return nt
}
}
}
| isc | af018f309f01ca609bf1907617bd984c | 21.694981 | 79 | 0.711807 | 3.168733 | false | false | false | false |
kysonyangs/ysbilibili | ysbilibili/Classes/Player/NormalPlayer/Controller/Detail/View/ZHNplayerTagListTableViewCell.swift | 1 | 2627 | //
// ZHNplayerTagListTableViewCell.swift
// zhnbilibili
//
// Created by 张辉男 on 16/12/30.
// Copyright © 2016年 zhn. All rights reserved.
//
import UIKit
class ZHNplayerTagListTableViewCell: YSBaseLineCell {
// tag的数组
var tagValueList: [String]? {
didSet{
guard let tagValueList = tagValueList else {return}
tagList.tags.removeAllObjects()
tagList.tags.addObjects(from: tagValueList)
}
}
// MARK - 懒加载控件
lazy var noticeLabel: UILabel = {
let noticeLabel = UILabel()
noticeLabel.text = "标签相关"
noticeLabel.font = UIFont.systemFont(ofSize: 15)
return noticeLabel
}()
lazy var editLabel: UILabel = {
let editLabel = UILabel()
editLabel.text = "编辑"
editLabel.font = UIFont.systemFont(ofSize: 13)
editLabel.textColor = UIColor.lightGray
editLabel.sizeToFit()
return editLabel
}()
lazy var tagList: JCTagListView = {
let tagList = JCTagListView()
tagList.tagTextFont = UIFont.systemFont(ofSize: 13)
tagList.tagBackgroundColor = UIColor.white
tagList.tagStrokeColor = UIColor.ysColor(red: 255, green: 255, blue: 255, alpha: 0.5)
tagList.tagCornerRadius = 14
return tagList
}()
// MARK - life cycle
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.addSubview(noticeLabel)
self.addSubview(editLabel)
self.addSubview(tagList)
self.selectionStyle = .none
self.backgroundColor = kHomeBackColor
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
noticeLabel.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(10)
make.top.equalTo(self).offset(5)
make.height.equalTo(30)
}
editLabel.snp.makeConstraints { (make) in
make.centerY.equalTo(noticeLabel.snp.centerY)
make.right.equalTo(self).offset(-10)
}
tagList.snp.makeConstraints { (make) in
make.top.equalTo(noticeLabel.snp.bottom)
make.left.right.bottom.equalTo(self)
}
}
class func instanceCell(tableView: UITableView) -> ZHNplayerTagListTableViewCell {
return ZHNplayerTagListTableViewCell(style: .default, reuseIdentifier: "ZHNplayerTagListTableViewCell")
}
}
| mit | 9c90cb83de7a67303f1b51bebdcaa366 | 30.585366 | 111 | 0.633205 | 4.42735 | false | false | false | false |
SteveBarnegren/SwiftChess | SwiftChess/Source/BoardRaterPawnProgression.swift | 1 | 1440 | //
// BoardRaterPawnProgression.swift
// SwiftChess
//
// Created by Steven Barnegren on 16/12/2016.
// Copyright © 2016 Steve Barnegren. All rights reserved.
//
import Foundation
class BoardRaterPawnProgression: BoardRater {
override func ratingFor(board: Board, color: Color) -> Double {
var rating = Double(0)
for location in BoardLocation.all {
guard let piece = board.getPiece(at: location) else {
continue
}
guard piece.type == .pawn else {
continue
}
let pawnRating = progressionRatingForPawn(at: location, color: piece.color)
rating += (piece.color == color) ? pawnRating : -pawnRating
}
return rating
}
func progressionRatingForPawn(at location: BoardLocation, color: Color) -> Double {
var squaresAdvanced = Int(0)
if color == .white {
if location.y < 2 {
return 0
}
squaresAdvanced = location.y - 2
} else {
if location.y > 5 {
return 0
}
squaresAdvanced = 7 - (location.y + 2)
}
return Double(squaresAdvanced) * configuration.boardRaterPawnProgressionWeighting.value
}
}
| mit | fe447eec6fd4ad984dc35fc8364a1ea4 | 24.245614 | 95 | 0.508687 | 5.084806 | false | false | false | false |
OpenKitten/BSON | Sources/BSON/Document/Document.swift | 1 | 1981 | import Foundation
import NIO
public struct Document: Primitive {
static let allocator = ByteBufferAllocator()
/// The internal storage engine that stores BSON in it's original binary form
/// The null terminator is missing here for performance reasons. We append it in `makeData()`
var storage: ByteBuffer
var usedCapacity: Int32 {
get {
guard let int = storage.getInteger(at: 0, endianness: .little, as: Int32.self) else {
assertionFailure("Corrupted document header")
return 0
}
return int
}
set {
Swift.assert(usedCapacity >= 5)
storage.set(integer: newValue, at: 0, endianness: .little)
}
}
/// Dictates whether this `Document` is an `Array` or `Dictionary`-like type
var isArray: Bool
/// Creates a new empty BSONDocument
///
/// `isArray` dictates what kind of subdocument the `Document` is, and is `false` by default
public init(isArray: Bool = false) {
var buffer = Document.allocator.buffer(capacity: 4_096)
buffer.write(integer: Int32(5), endianness: .little)
buffer.write(integer: UInt8(0), endianness: .little)
self.storage = buffer
self.isArray = isArray
}
/// Creates a new `Document` by parsing an existing `ByteBuffer`
public init(buffer: ByteBuffer, isArray: Bool = false) {
self.storage = buffer
self.isArray = isArray
}
/// Creates a new `Document` by parsing the existing `Data` buffer
public init(data: Data, isArray: Bool = false) {
self.storage = Document.allocator.buffer(capacity: data.count)
self.storage.write(bytes: data)
self.isArray = isArray
}
/// Creates a new `Document` from the given bytes
public init(bytes: [UInt8], isArray: Bool = false) {
self.init(data: Data(bytes: bytes), isArray: isArray)
}
}
| mit | 0de0170026f4ba9a9d067e7f38773e64 | 33.754386 | 97 | 0.615346 | 4.306522 | false | false | false | false |
francisykl/PagingMenuController | Example/PagingMenuControllerDemo2/RootViewControoler.swift | 1 | 2948 | //
// RootViewControoler.swift
// PagingMenuControllerDemo
//
// Created by Cheng-chien Kuo on 5/14/16.
// Copyright © 2016 kitasuke. All rights reserved.
//
import UIKit
import PagingMenuController
private struct PagingMenuOptions: PagingMenuControllerCustomizable {
fileprivate var componentType: ComponentType {
return .all(menuOptions: MenuOptions(), pagingControllers: pagingControllers)
}
fileprivate var pagingControllers: [UIViewController] {
let viewController1 = ViewController1()
let viewController2 = ViewController2()
return [viewController1, viewController2]
}
fileprivate struct MenuOptions: MenuViewCustomizable {
var displayMode: MenuDisplayMode {
return .segmentedControl
}
var itemsOptions: [MenuItemViewCustomizable] {
return [MenuItem1(), MenuItem2()]
}
}
fileprivate struct MenuItem1: MenuItemViewCustomizable {
var displayMode: MenuItemDisplayMode {
return .text(title: MenuItemText(text: "First Menu"))
}
}
fileprivate struct MenuItem2: MenuItemViewCustomizable {
var displayMode: MenuItemDisplayMode {
return .text(title: MenuItemText(text: "Second Menu"))
}
}
}
class RootViewControoler: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = UIColor.white
let options = PagingMenuOptions()
let pagingMenuController = PagingMenuController(options: options)
pagingMenuController.delegate = self
pagingMenuController.view.frame.origin.y += 64
pagingMenuController.view.frame.size.height -= 64
addChildViewController(pagingMenuController)
view.addSubview(pagingMenuController.view)
pagingMenuController.didMove(toParentViewController: self)
}
}
extension RootViewControoler: PagingMenuControllerDelegate {
// MARK: - PagingMenuControllerDelegate
func willMove(toMenu menuController: UIViewController, fromMenu previousMenuController: UIViewController) {
print(#function)
print(previousMenuController)
print(menuController)
}
func didMove(toMenu menuController: UIViewController, fromMenu previousMenuController: UIViewController) {
print(#function)
print(previousMenuController)
print(menuController)
}
func willMove(toMenuItem menuItemView: MenuItemView, fromMenuItem previousMenuItemView: MenuItemView) {
print(#function)
print(previousMenuItemView)
print(menuItemView)
}
func didMove(toMenuItem menuItemView: MenuItemView, fromMenuItem previousMenuItemView: MenuItemView) {
print(#function)
print(previousMenuItemView)
print(menuItemView)
}
}
| mit | 949e28704be092749456049ba4c1e150 | 32.873563 | 111 | 0.695623 | 5.581439 | false | false | false | false |
matthewpalmer/Locksmith | Source/LocksmithInternetProtocol.swift | 13 | 4872 | import Foundation
public enum LocksmithInternetProtocol: RawRepresentable {
case ftp, ftpAccount, http, irc, nntp, pop3, smtp, socks, imap, ldap, appleTalk, afp, telnet, ssh, ftps, https, httpProxy, httpsProxy, ftpProxy, smb, rtsp, rtspProxy, daap, eppc, ipp, nntps, ldaps, telnetS, imaps, ircs, pop3S
public init?(rawValue: String) {
switch rawValue {
case String(kSecAttrProtocolFTP):
self = .ftp
case String(kSecAttrProtocolFTPAccount):
self = .ftpAccount
case String(kSecAttrProtocolHTTP):
self = .http
case String(kSecAttrProtocolIRC):
self = .irc
case String(kSecAttrProtocolNNTP):
self = .nntp
case String(kSecAttrProtocolPOP3):
self = .pop3
case String(kSecAttrProtocolSMTP):
self = .smtp
case String(kSecAttrProtocolSOCKS):
self = .socks
case String(kSecAttrProtocolIMAP):
self = .imap
case String(kSecAttrProtocolLDAP):
self = .ldap
case String(kSecAttrProtocolAppleTalk):
self = .appleTalk
case String(kSecAttrProtocolAFP):
self = .afp
case String(kSecAttrProtocolTelnet):
self = .telnet
case String(kSecAttrProtocolSSH):
self = .ssh
case String(kSecAttrProtocolFTPS):
self = .ftps
case String(kSecAttrProtocolHTTPS):
self = .https
case String(kSecAttrProtocolHTTPProxy):
self = .httpProxy
case String(kSecAttrProtocolHTTPSProxy):
self = .httpsProxy
case String(kSecAttrProtocolFTPProxy):
self = .ftpProxy
case String(kSecAttrProtocolSMB):
self = .smb
case String(kSecAttrProtocolRTSP):
self = .rtsp
case String(kSecAttrProtocolRTSPProxy):
self = .rtspProxy
case String(kSecAttrProtocolDAAP):
self = .daap
case String(kSecAttrProtocolEPPC):
self = .eppc
case String(kSecAttrProtocolIPP):
self = .ipp
case String(kSecAttrProtocolNNTPS):
self = .nntps
case String(kSecAttrProtocolLDAPS):
self = .ldaps
case String(kSecAttrProtocolTelnetS):
self = .telnetS
case String(kSecAttrProtocolIMAPS):
self = .imaps
case String(kSecAttrProtocolIRCS):
self = .ircs
case String(kSecAttrProtocolPOP3S):
self = .pop3S
default:
self = .http
}
}
public var rawValue: String {
switch self {
case .ftp:
return String(kSecAttrProtocolFTP)
case .ftpAccount:
return String(kSecAttrProtocolFTPAccount)
case .http:
return String(kSecAttrProtocolHTTP)
case .irc:
return String(kSecAttrProtocolIRC)
case .nntp:
return String(kSecAttrProtocolNNTP)
case .pop3:
return String(kSecAttrProtocolPOP3)
case .smtp:
return String(kSecAttrProtocolSMTP)
case .socks:
return String(kSecAttrProtocolSOCKS)
case .imap:
return String(kSecAttrProtocolIMAP)
case .ldap:
return String(kSecAttrProtocolLDAP)
case .appleTalk:
return String(kSecAttrProtocolAppleTalk)
case .afp:
return String(kSecAttrProtocolAFP)
case .telnet:
return String(kSecAttrProtocolTelnet)
case .ssh:
return String(kSecAttrProtocolSSH)
case .ftps:
return String(kSecAttrProtocolFTPS)
case .https:
return String(kSecAttrProtocolHTTPS)
case .httpProxy:
return String(kSecAttrProtocolHTTPProxy)
case .httpsProxy:
return String(kSecAttrProtocolHTTPSProxy)
case .ftpProxy:
return String(kSecAttrProtocolFTPProxy)
case .smb:
return String(kSecAttrProtocolSMB)
case .rtsp:
return String(kSecAttrProtocolRTSP)
case .rtspProxy:
return String(kSecAttrProtocolRTSPProxy)
case .daap:
return String(kSecAttrProtocolDAAP)
case .eppc:
return String(kSecAttrProtocolEPPC)
case .ipp:
return String(kSecAttrProtocolIPP)
case .nntps:
return String(kSecAttrProtocolNNTPS)
case .ldaps:
return String(kSecAttrProtocolLDAPS)
case .telnetS:
return String(kSecAttrProtocolTelnetS)
case .imaps:
return String(kSecAttrProtocolIMAPS)
case .ircs:
return String(kSecAttrProtocolIRCS)
case .pop3S:
return String(kSecAttrProtocolPOP3S)
}
}
}
| mit | ae077fce6e67fa2291642fd64d667615 | 33.553191 | 229 | 0.590928 | 5.233083 | false | false | false | false |
seanwoodward/IBAnimatable | IBAnimatableApp/PresentingViewController.swift | 1 | 11195 | //
// Created by Tom Baranes on 16/07/16.
// Copyright © 2016 Jake Lin. All rights reserved.
//
import UIKit
import IBAnimatable
class PresentingViewController: AnimatableViewController, UIPickerViewDataSource, UIPickerViewDelegate {
// MARK: Properties IB
@IBOutlet weak var btnAnimationType: AnimatableButton!
@IBOutlet weak var btnDismissalAnimationType: AnimatableButton!
@IBOutlet weak var btnModalPosition: AnimatableButton!
@IBOutlet weak var btnModalSize: AnimatableButton!
@IBOutlet weak var btnKeyboardTranslation: AnimatableButton!
@IBOutlet weak var btnBlurEffectStyle: AnimatableButton!
@IBOutlet weak var labelCornerRadius: UILabel!
@IBOutlet weak var labelOpacity: UILabel!
@IBOutlet weak var labelBlurOpacity: UILabel!
@IBOutlet weak var labelShadowOpacity: UILabel!
@IBOutlet weak var labelShadowRadius: UILabel!
@IBOutlet weak var labelShadowOffsetX: UILabel!
@IBOutlet weak var labelShadowOffsetY: UILabel!
@IBOutlet weak var dimmingPickerView: AnimatableView!
@IBOutlet weak var containerPickerView: AnimatableView!
@IBOutlet weak var pickerView: UIPickerView!
@IBOutlet var sliderBackgroundColor: UISlider!
@IBOutlet var sliderCornerRadius: UISlider!
@IBOutlet var switchDismissOnTap: UISwitch!
@IBOutlet var sliderOpacity: UISlider!
@IBOutlet var sliderBlurOpacity: UISlider!
@IBOutlet var sliderShadowColor: UISlider!
@IBOutlet var sliderShadowOpacity: UISlider!
@IBOutlet var sliderShadowRadius: UISlider!
@IBOutlet var sliderShadowOffsetX: UISlider!
@IBOutlet var sliderShadowOffsetY: UISlider!
// MARK: Properties
private let animations = ["None", "Flip", "CrossDissolve", "Cover(Left)", "Cover(Right)", "Cover(Top)", "Cover(Bottom)", "Zoom", "DropDown"]
private let positions = ["Center", "TopCenter", "BottomCenter", "LeftCenter", "RightCenter"]
private let sizes = ["Half", "Full"]
private let keyboardTranslations = ["None", "MoveUp", "AboveKeyboard"]
private let blurEffectStyles = ["None", "ExtraLight", "Light", "Dark"]
private let colors = [UIColor.blackColor(), UIColor.redColor(), UIColor.orangeColor(), UIColor.brownColor(), UIColor.yellowColor(), UIColor.lightGrayColor(), UIColor.greenColor(), UIColor.cyanColor(), UIColor.blueColor(), UIColor.purpleColor(), UIColor.purpleColor().colorWithAlphaComponent(0.5), UIColor.darkGrayColor(), UIColor.magentaColor(), UIColor.whiteColor()]
private var selectedButton: UIButton?
private var selectedAnimationType: String?
private var selectedDismissalAnimationType: String?
private var selectedModalPosition: String?
private var selectedModalWidth: String = "Half"
private var selectedModalHeight: String = "Half"
private var selectedKeyboardTranslation: String?
private var selectedBlurEffectStyle: String?
// MARK: Life cycle
override func viewDidLoad() {
super.viewDidLoad()
}
private func setupModal(presentedViewController: AnimatableModalViewController) {
presentedViewController.presentationAnimationType = selectedAnimationType
presentedViewController.dismissalAnimationType = selectedDismissalAnimationType
presentedViewController.modalPosition = selectedModalPosition ?? "Center"
presentedViewController.modalWidth = selectedModalWidth ?? "Half"
presentedViewController.modalHeight = selectedModalHeight ?? "Half"
presentedViewController.backgroundColor = colors[Int(sliderBackgroundColor.value)]
presentedViewController.opacity = CGFloat(sliderOpacity.value)
presentedViewController.dismissOnTap = switchDismissOnTap.on
presentedViewController.keyboardTranslation = selectedKeyboardTranslation
presentedViewController.cornerRadius = CGFloat(sliderCornerRadius.value)
presentedViewController.blurEffectStyle = selectedBlurEffectStyle
presentedViewController.blurOpacity = CGFloat(sliderBlurOpacity.value)
presentedViewController.shadowColor = colors[Int(sliderShadowColor.value)]
presentedViewController.shadowOpacity = CGFloat(sliderShadowOpacity.value)
presentedViewController.shadowRadius = CGFloat(sliderShadowRadius.value)
presentedViewController.shadowOffset = CGPoint(x: CGFloat(sliderShadowOffsetX.value), y: CGFloat(sliderShadowOffsetY.value))
setDismissalAnimationTypeIfNeeded(presentedViewController)
}
private func setDismissalAnimationTypeIfNeeded(viewController: AnimatableModalViewController) {
guard selectedDismissalAnimationType == nil else {
return
}
// FIXME: Dirty hack to make `Flip` and `CrossDissolve` work properly for dismissal transition.
// If we don't apply this hack, both the dismissal transitions of `Flip` and `CrossDissolve` will slide down the modal not flip or crossDissolve(fade).
if viewController.presentationAnimationType == "Flip" {
viewController.dismissalAnimationType = "Flip"
} else if viewController.presentationAnimationType == "CrossDissolve" {
viewController.dismissalAnimationType = "CrossDissolve"
}
}
}
// MARK: - IBAction
extension PresentingViewController {
@IBAction func presentProgramatically() {
if let presentedViewController = UIStoryboard(name: "Presentations", bundle: nil).instantiateViewControllerWithIdentifier("PresentationPresentedViewController") as? AnimatableModalViewController {
setupModal(presentedViewController)
presentViewController(presentedViewController, animated: true, completion: nil)
}
}
@IBAction func animationTypePressed() {
selectedButton = btnAnimationType
showPicker()
}
@IBAction func dismissalAnimationTypePressed() {
selectedButton = btnDismissalAnimationType
showPicker()
}
@IBAction func modalPositionPressed() {
selectedButton = btnModalPosition
showPicker()
}
@IBAction func modalSizePressed() {
selectedButton = btnModalSize
showPicker()
}
@IBAction func keyboardTranslationPressed() {
selectedButton = btnKeyboardTranslation
showPicker()
}
@IBAction func blurEffectStylePressed() {
selectedButton = btnBlurEffectStyle
showPicker()
}
}
// MARK: - Slider value changed
extension PresentingViewController {
@IBAction func backgroundColorValueChanged(sender: UISlider) {
// labelShadowOpacity.text = "Shadow opacity (\(sender.value))"
}
@IBAction func cornerRadiusValueChanged(sender: UISlider) {
labelCornerRadius.text = "Corner radius (\(sender.value))"
}
@IBAction func opacityValueChanged(sender: UISlider) {
labelOpacity.text = "Opacity (\(sender.value))"
}
@IBAction func blurOpacityValueChanged(sender: UISlider) {
labelBlurOpacity.text = "Blur opacity (\(sender.value))"
}
@IBAction func shadowColorValueChanged(sender: UISlider) {
// labelShadowOpacity.text = "Shadow opacity (\(sender.value))"
}
@IBAction func shadowOpacityValueChanged(sender: UISlider) {
labelShadowOpacity.text = "Shadow opacity (\(sender.value))"
}
@IBAction func shadowRadiusValueChanged(sender: UISlider) {
labelShadowRadius.text = "Shadow radius (\(sender.value))"
}
@IBAction func shadowOffsetXValueChanged(sender: UISlider) {
labelShadowOffsetX.text = "Shadow offset X (\(sender.value))"
}
@IBAction func shadowOffsetYValueChanged(sender: UISlider) {
labelShadowOffsetY.text = "Shadow offset Y (\(sender.value))"
}
}
// MARK: - Picker
extension PresentingViewController {
func showPicker() {
pickerView.reloadAllComponents()
resetSelectedItemPicker()
dimmingPickerView.fadeIn()
containerPickerView.slideInUp()
dimmingPickerView.hidden = false
}
@IBAction func hidePicker() {
dimmingPickerView.fadeOut({
self.dimmingPickerView.hidden = true
})
containerPickerView.slideOutDown()
selectedButton = nil
}
// MARK: Helpers
func componentsForSelectedButton() -> [[String]] {
if selectedButton == btnAnimationType || selectedButton == btnDismissalAnimationType {
return [animations]
} else if selectedButton == btnModalPosition {
return [positions]
} else if selectedButton == btnModalSize {
return [sizes, sizes]
} else if selectedButton == btnKeyboardTranslation {
return [keyboardTranslations]
}
return [blurEffectStyles]
}
func resetSelectedItemPicker() {
var row: Int?
if selectedButton == btnAnimationType {
row = animations.indexOf(selectedAnimationType ?? "")
} else if selectedButton == btnDismissalAnimationType {
row = animations.indexOf(selectedDismissalAnimationType ?? "")
} else if selectedButton == btnModalPosition {
row = positions.indexOf(selectedModalPosition ?? "")
} else if selectedButton == btnModalSize {
pickerView.selectRow(sizes.indexOf(selectedModalWidth ?? "") ?? 0, inComponent: 0, animated: false)
pickerView.selectRow(sizes.indexOf(selectedModalHeight ?? "") ?? 0, inComponent: 1, animated: false)
return
} else if selectedButton == btnKeyboardTranslation {
row = keyboardTranslations.indexOf(selectedKeyboardTranslation ?? "")
} else if selectedButton == btnBlurEffectStyle {
row = blurEffectStyles.indexOf(selectedBlurEffectStyle ?? "")
}
pickerView.selectRow(row ?? 0, inComponent: 0, animated: false)
}
// MARK: UIPickerDelegate / DataSource
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return componentsForSelectedButton().count
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return componentsForSelectedButton()[component].count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return componentsForSelectedButton()[component][row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let title = componentsForSelectedButton()[component][row]
if selectedButton == btnAnimationType {
btnAnimationType.setTitle("Animation type (\(title))", forState: .Normal)
selectedAnimationType = title
} else if selectedButton == btnDismissalAnimationType {
btnDismissalAnimationType.setTitle("Dismissal animation type (\(title))", forState: .Normal)
selectedDismissalAnimationType = title
} else if selectedButton == btnModalPosition {
btnModalPosition.setTitle("Modal Position (\(title))", forState: .Normal)
selectedModalPosition = title
} else if selectedButton == btnModalSize && component == 0 {
btnModalSize.setTitle("Modal size (\(title) - \(selectedModalHeight))", forState: .Normal)
selectedModalWidth = title
} else if selectedButton == btnModalSize && component == 1 {
btnModalSize.setTitle("Modal size (\(selectedModalWidth) - \(title))", forState: .Normal)
selectedModalHeight = title
} else if selectedButton == btnKeyboardTranslation {
btnKeyboardTranslation.setTitle("Keyboard translation (\(title))", forState: .Normal)
selectedKeyboardTranslation = title
} else if selectedButton == btnBlurEffectStyle {
btnBlurEffectStyle.setTitle("Blur effect style (\(title))", forState: .Normal)
selectedBlurEffectStyle = title
}
}
}
| mit | a6073d40c64ab2b337f030c6dcefad8d | 38.55477 | 369 | 0.749777 | 5.141938 | false | false | false | false |
ECP-CANDLE/Supervisor | workflows/upf/test/test-json.swift | 1 | 576 |
import io;
import json;
// Sample UPF fragment:
s = "{ \"model_file\": \"/project/projectdirs/m2924/brettin/combo-inference/uq.0/save/combo.A=relu.B=32.E=50.O=adam.LR=None.CF=r.DF=d.wu_lr.re_lr.res.D1=1000.D2=1000.D3=1000.D4=1000.model.h5\", \"weights_file\": \"/project/projectdirs/m2924/brettin/combo-inference/uq.0/save/combo.A=relu.B=32.E=50.O=adam.LR=None.CF=r.DF=d.wu_lr.re_lr.res.D1=1000.D2=1000.D3=1000.D4=1000.weights.h5\", \"drug_set\": \"ALMANAC\", \"sample_set\": \"GDSC\" } ";
// Extract one entry:
printf("model_file: %s", json_get(s, "sample_set"));
| mit | ffbe4a22c469e4eb4a39cf2dc50bdb4e | 63 | 449 | 0.668403 | 2.133333 | false | false | false | false |
stripe/stripe-ios | StripeFinancialConnections/StripeFinancialConnections/Source/Web/FinancialConnectionsAccountFetcher.swift | 1 | 1895 | //
// FinancialConnectionsAccountFetcher.swift
// StripeFinancialConnections
//
// Created by Vardges Avetisyan on 12/30/21.
//
import Foundation
@_spi(STP) import StripeCore
protocol FinancialConnectionsAccountFetcher {
func fetchAccounts(
initial: [StripeAPI.FinancialConnectionsAccount]
) -> Future<[StripeAPI.FinancialConnectionsAccount]>
}
class FinancialConnectionsAccountAPIFetcher: FinancialConnectionsAccountFetcher {
// MARK: - Properties
private let api: FinancialConnectionsAPIClient
private let clientSecret: String
// MARK: - Init
init(api: FinancialConnectionsAPIClient, clientSecret: String) {
self.api = api
self.clientSecret = clientSecret
}
// MARK: - FinancialConnectionsAccountFetcher
func fetchAccounts(initial: [StripeAPI.FinancialConnectionsAccount]) -> Future<[StripeAPI.FinancialConnectionsAccount]> {
return fetchAccounts(resultsSoFar: initial)
}
}
// MARK: - Helpers
extension FinancialConnectionsAccountAPIFetcher {
private func fetchAccounts(
resultsSoFar: [StripeAPI.FinancialConnectionsAccount]
) -> Future<[StripeAPI.FinancialConnectionsAccount]> {
let lastId = resultsSoFar.last?.id
let promise = api.fetchFinancialConnectionsAccounts(clientSecret: clientSecret,
startingAfterAccountId: lastId)
return promise.chained { list in
let combinedResults = resultsSoFar + list.data
guard list.hasMore, combinedResults.count < Constants.maxAccountLimit else {
return Promise(value: combinedResults)
}
return self.fetchAccounts(resultsSoFar: combinedResults)
}
}
}
// MARK: - Constants
extension FinancialConnectionsAccountAPIFetcher {
private enum Constants {
static let maxAccountLimit = 100
}
}
| mit | 0234fac8e2f9a5651b2d5a7290ff8942 | 28.153846 | 125 | 0.702375 | 5.206044 | false | false | false | false |
stripe/stripe-ios | Tests/Tests/AnalyticsHelperTests.swift | 1 | 1489 | //
// AnalyticsHelperTests.swift
// StripeiOS Tests
//
// Created by Ramon Torres on 2/22/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import XCTest
@testable@_spi(STP) import Stripe
@testable@_spi(STP) import StripeCore
@testable@_spi(STP) import StripePaymentSheet
@testable@_spi(STP) import StripePayments
@testable@_spi(STP) import StripePaymentsUI
class AnalyticsHelperTests: XCTestCase {
func test_getDuration() {
let (sut, timeReference) = makeSUT()
sut.startTimeMeasurement(.checkout)
// Advance the clock by 10 seconds.
timeReference.advanceBy(10)
XCTAssertEqual(sut.getDuration(for: .checkout), 10)
// Advance the clock by 5 seconds.
timeReference.advanceBy(5)
XCTAssertEqual(sut.getDuration(for: .checkout), 15)
}
func test_getDuration_returnsNilWhenNotStarted() {
let (sut, _) = makeSUT()
XCTAssertNil(sut.getDuration(for: .checkout))
}
}
extension AnalyticsHelperTests {
class MockTimeReference {
var date = Date()
func advanceBy(_ timeInterval: TimeInterval) {
date = date.addingTimeInterval(timeInterval)
}
func now() -> Date {
return date
}
}
func makeSUT() -> (AnalyticsHelper, MockTimeReference) {
let timeReference = MockTimeReference()
let helper = AnalyticsHelper(timeProvider: timeReference.now)
return (helper, timeReference)
}
}
| mit | 5d742d3b4fa214c53388a851dfc373b4 | 23.8 | 69 | 0.655914 | 4.300578 | false | true | false | false |
ello/ello-ios | Specs/Model/RelationshipSpec.swift | 1 | 1107 | @testable import Ello
import Quick
import Nimble
class RelationshipPrioritySpec: QuickSpec {
override func spec() {
describe("RelationshipPriority") {
context("when the string matches a raw value") {
it("returns a Relationship created from the raw value") {
let priority = RelationshipPriority(stringValue: "friend")
expect(priority) == RelationshipPriority.following
}
}
context("when the string doesn't match a raw value") {
it("returns RelationshipPriority.none") {
let priority = RelationshipPriority(stringValue: "bad_string")
expect(priority) == RelationshipPriority.none
}
}
context("when the string is 'noise'") {
it("returns RelationshipPriority.following") {
let priority = RelationshipPriority(stringValue: "noise")
expect(priority) == RelationshipPriority.following
}
}
}
}
}
| mit | e4f147899781fdc680924d69f644e61d | 31.558824 | 82 | 0.551942 | 5.857143 | false | false | false | false |
trill-lang/trill | Sources/Options/Options.swift | 2 | 5806 | ///
/// Options.swift
///
/// Copyright 2016-2017 the Trill project authors.
/// Licensed under the MIT License.
///
/// Full license text available at https://github.com/trill-lang/trill
///
import Foundation
import Basic
import Utility
public enum OptimizationLevel: String, ArgumentKind {
case none = "0"
case less = "1"
case `default` = "2"
case aggressive = "3"
public init(argument: String) throws {
guard let level = OptimizationLevel(rawValue: argument) else {
throw ArgumentParserError.invalidValue(argument: argument,
error: .unknown(value: argument))
}
self = level
}
public static var completion: ShellCompletion {
return ShellCompletion.values([
(value: "O0", description: "Perform no optimizations."),
(value: "O1", description: "Perform a small set of optimizations."),
(value: "O2", description: "Perform the default set of optimizations."),
(value: "O3", description: "Perform aggressive optimizations.")
])
}
}
public struct Options {
public let filenames: [String]
public let targetTriple: String?
public let outputFilename: String?
public let mode: Mode
public let importC: Bool
public let emitTiming: Bool
public let jsonDiagnostics: Bool
public let parseOnly: Bool
public let showImports: Bool
public let includeStdlib: Bool
public let optimizationLevel: OptimizationLevel
public let jitArgs: [String]
public let linkerFlags: [String]
public let clangFlags: [String]
public var isStdin: Bool {
return filenames.count == 1 && filenames[0] == "-"
}
public static func parseCommandLine() throws -> Options {
let parser = ArgumentParser(commandName: "trill",
usage: "[options] <input-files>",
overview: "")
let help =
parser.add(option: "-help", shortName: "-h", kind: Bool.self,
usage: "Prints this help message.")
let targetTriple =
parser.add(option: "-target", kind: String.self,
usage: "Override the target triple for cross-compilation.")
let outputFilename =
parser.add(option: "-output-file", shortName: "-o", kind: String.self,
usage: "The file to write the resulting output to.")
let noImportC =
parser.add(option: "-no-import", kind: Bool.self,
usage: "Disable importing C declarations.")
let emitTiming =
parser.add(option: "-debug-print-timing", kind: Bool.self,
usage: "Print times for each pass (for debugging).")
let jsonDiagnostics =
parser.add(option: "-json-diagnostics",
kind: Bool.self,
usage: "Emit diagnostics as JSON instead of strings.")
let parseOnly =
parser.add(option: "-parse-only", kind: Bool.self,
usage: "Only parse the input file(s); do not typecheck.")
let showImports =
parser.add(option: "-show-imports", kind: Bool.self,
usage: "Whether to show imported declarations in AST dumps.")
let noStdlib =
parser.add(option: "-no-stdlib", kind: Bool.self,
usage: "Do not compile the standard library.")
let linkerFlags =
parser.add(option: "-Xlinker", kind: [String].self, strategy: .oneByOne,
usage: "Flags to pass to the linker when linking.")
let clangFlags =
parser.add(option: "-Xclang", kind: [String].self,
strategy: .oneByOne, usage: "Flags to pass to clang.")
let optimizationLevel =
parser.add(option: "-O", kind: OptimizationLevel.self,
usage: "The optimization level to apply to the program.")
let outputFormat =
parser.add(option: "-emit", kind: OutputFormat.self,
usage: "The kind of file to emit. Defaults to binary.")
let onlyDiagnostics =
parser.add(option: "-only-diagnostics", kind: Bool.self,
usage: "Only print diagnostics, no other output.")
let files =
parser.add(positional: "", kind: [String].self)
let jit = parser.add(option: "-run", kind: Bool.self,
usage: "JIT the specified files.")
let jitArgs = parser.add(option: "-args", kind: [String].self,
strategy: .remaining)
let args: ArgumentParser.Result
do {
let commandLineArgs = Array(CommandLine.arguments.dropFirst())
args = try parser.parse(commandLineArgs)
if args.get(help) != nil {
parser.printUsage(on: Basic.stdoutStream)
exit(0)
}
} catch {
parser.printUsage(on: Basic.stdoutStream)
exit(-1)
}
let mode: Mode
if let format = args.get(outputFormat) {
mode = .emit(format)
} else if args.get(jit) != nil {
mode = .jit
} else if args.get(onlyDiagnostics) != nil {
mode = .onlyDiagnostics
} else {
mode = .emit(.binary)
}
return Options(filenames: args.get(files) ?? [],
targetTriple: args.get(targetTriple),
outputFilename: args.get(outputFilename),
mode: mode,
importC: !(args.get(noImportC) ?? false),
emitTiming: args.get(emitTiming) ?? false,
jsonDiagnostics: args.get(jsonDiagnostics) ?? false,
parseOnly: args.get(parseOnly) ?? false,
showImports: args.get(showImports) ?? false,
includeStdlib: !(args.get(noStdlib) ?? false),
optimizationLevel: args.get(optimizationLevel) ?? .none,
jitArgs: args.get(jitArgs) ?? [],
linkerFlags: args.get(linkerFlags) ?? [],
clangFlags: args.get(clangFlags) ?? [])
}
}
| mit | 6f30d50b916c6107affef0707bd97be7 | 36.947712 | 78 | 0.601102 | 4.291205 | false | false | false | false |
sdhjl2000/swiftdialog | SwiftDialog/SliderElement.swift | 1 | 2692 | // Copyright 2014 Thomas K. Dyas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
public class SliderElement : Element {
var text: String
var value: Float
var slider: UISlider?
public init(text: String = "", value: Float = 0.0) {
self.text = text
self.value = value
}
public override func getCell(tableView: UITableView) -> UITableViewCell! {
let cellKey = "slider"
let sliderTag = 500
var cell = tableView.dequeueReusableCellWithIdentifier(cellKey) as! UITableViewCell!
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: cellKey)
cell.selectionStyle = .None
}
// Setup the text label.
cell.textLabel!.text = self.text
// Remove any existing slider from the content view.
if let view = cell.contentView.viewWithTag(sliderTag) {
view.removeFromSuperview()
}
if let slider = self.slider {
cell.contentView.addSubview(slider)
} else {
let slider = UISlider(frame: CGRect.zeroRect)
slider.tag = sliderTag
slider.autoresizingMask = .FlexibleWidth
slider.addTarget(self, action: "valueChanged:", forControlEvents: .ValueChanged)
cell.contentView.addSubview(slider)
self.slider = slider
}
let insets = tableView.separatorInset
let contentFrame = cell.contentView.bounds.rectByInsetting(dx: insets.left, dy: 0)
var sliderFrame = contentFrame
if self.text != "" {
let textSize = cell.textLabel!.intrinsicContentSize()
sliderFrame = CGRect(
x: contentFrame.minX + textSize.width + 10.0,
y: contentFrame.minY,
width: contentFrame.width - textSize.width - 10.0,
height: contentFrame.height
)
}
self.slider?.frame = sliderFrame
self.slider?.value = self.value
return cell
}
func valueChanged(slider: UISlider!) {
self.value = slider.value
}
}
| apache-2.0 | c919abe07b7b267e3a845bb2994cb874 | 33.075949 | 92 | 0.614785 | 4.824373 | false | false | false | false |
alitan2014/swift | Heath/Heath/Libs/DOFavoriteButton.swift | 9 | 15521 | //
// DOFavoriteButton.swift
// DOFavoriteButton
//
// Created by Daiki Okumura on 2015/07/09.
// Copyright (c) 2015 Daiki Okumura. All rights reserved.
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
import UIKit
class DOFavoriteButton: UIButton {
private var circleShape: CAShapeLayer!
private var circleMask: CAShapeLayer!
var circleColor: UIColor! = UIColor(red: 255/255, green: 172/255, blue: 51/255, alpha: 1.0) {
didSet {
circleShape.fillColor = circleColor.CGColor
}
}
private var lines: [CAShapeLayer]! = []
var lineColor = UIColor(red: 250/255, green: 120/255, blue: 68/255, alpha: 1.0) {
didSet {
for i in 0 ..< 5 {
lines[i].strokeColor = lineColor.CGColor
}
}
}
private var imageShape: CAShapeLayer!
var imageColorOn = UIColor(red: 255/255, green: 172/255, blue: 51/255, alpha: 1.0) {
didSet {
if (selected) {
imageShape.fillColor = imageColorOn.CGColor
}
}
}
var imageColorOff = UIColor(red: 136/255, green: 153/255, blue: 166/255, alpha: 1.0) {
didSet {
if (!selected) {
imageShape.fillColor = imageColorOff.CGColor
}
}
}
private let circleTransform = CAKeyframeAnimation(keyPath: "transform")
private let circleMaskTransform = CAKeyframeAnimation(keyPath: "transform")
private let lineStrokeStart = CAKeyframeAnimation(keyPath: "strokeStart")
private let lineStrokeEnd = CAKeyframeAnimation(keyPath: "strokeEnd")
private let lineOpacity = CAKeyframeAnimation(keyPath: "opacity")
private let imageTransform = CAKeyframeAnimation(keyPath: "transform")
var duration: Double = 1.0 {
didSet {
circleTransform.duration = 0.333 * duration // 0.0333 * 10
circleMaskTransform.duration = 0.333 * duration // 0.0333 * 10
lineStrokeStart.duration = 0.6 * duration //0.0333 * 18
lineStrokeEnd.duration = 0.6 * duration //0.0333 * 18
lineOpacity.duration = 1.0 * duration //0.0333 * 30
imageTransform.duration = 1.0 * duration //0.0333 * 30
}
}
override var selected : Bool {
didSet {
if (selected != oldValue) {
if selected {
imageShape.fillColor = imageColorOn.CGColor
} else {
deselect()
}
}
}
}
init() {
super.init(frame: CGRectZero)
createLayers(image: UIImage(named: "star"), imageFrame: frame)
}
override init(frame: CGRect) {
super.init(frame: frame)
createLayers(image: UIImage(named: "star"), imageFrame: CGRectMake(0, 0, frame.width, frame.height))
}
init(frame: CGRect, image: UIImage!, imageFrame: CGRect) {
super.init(frame: frame)
createLayers(image: image, imageFrame: imageFrame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
//layoutLayers()
}
func createLayers(#image: UIImage!, imageFrame: CGRect) {
let imgCenterPoint = CGPointMake(imageFrame.origin.x + imageFrame.width / 2, imageFrame.origin.y + imageFrame.height / 2)
let lineFrame = CGRectMake(imageFrame.origin.x - imageFrame.width / 4, imageFrame.origin.y - imageFrame.height / 4 , imageFrame.width * 1.5, imageFrame.height * 1.5)
//===============
// circle layer
//===============
circleShape = CAShapeLayer()
circleShape.bounds = imageFrame
circleShape.position = imgCenterPoint
circleShape.path = UIBezierPath(ovalInRect: imageFrame).CGPath
circleShape.fillColor = circleColor.CGColor
circleShape.transform = CATransform3DMakeScale(0.0, 0.0, 1.0)
self.layer.addSublayer(circleShape)
circleMask = CAShapeLayer()
circleMask.bounds = imageFrame
circleMask.position = imgCenterPoint
circleMask.fillRule = kCAFillRuleEvenOdd
circleShape.mask = circleMask
let maskPath = UIBezierPath(rect: imageFrame)
maskPath.addArcWithCenter(imgCenterPoint, radius: 0.1, startAngle: CGFloat(0.0), endAngle: CGFloat(M_PI * 2), clockwise: true)
circleMask.path = maskPath.CGPath
//===============
// line layer
//===============
for i in 0 ..< 5 {
let line = CAShapeLayer()
line.bounds = lineFrame
line.position = imgCenterPoint
line.masksToBounds = true
line.actions = ["strokeStart": NSNull(), "strokeEnd": NSNull()]
line.strokeColor = lineColor.CGColor
line.lineWidth = 1.25
line.miterLimit = 1.25
line.path = {
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, lineFrame.origin.x + lineFrame.width / 2, lineFrame.origin.y + lineFrame.height / 2)
CGPathAddLineToPoint(path, nil, lineFrame.origin.x + lineFrame.width / 2, lineFrame.origin.y)
return path
}()
line.lineCap = kCALineCapRound
line.lineJoin = kCALineJoinRound
line.strokeStart = 0.0
line.strokeEnd = 0.0
line.opacity = 0.0
line.transform = CATransform3DMakeRotation(CGFloat(M_PI) / 5 * (CGFloat(i) * 2 + 1), 0.0, 0.0, 1.0)
self.layer.addSublayer(line)
lines.append(line)
}
//===============
// image layer
//===============
imageShape = CAShapeLayer()
imageShape.bounds = imageFrame
imageShape.position = imgCenterPoint
imageShape.path = UIBezierPath(rect: imageFrame).CGPath
imageShape.fillColor = imageColorOff.CGColor
imageShape.actions = ["fillColor": NSNull()]
self.layer.addSublayer(imageShape)
let imageMask = CALayer()
imageMask.contents = image.CGImage
imageMask.bounds = imageFrame
imageMask.position = imgCenterPoint
imageShape.mask = imageMask
//==============================
// circle transform animation
//==============================
circleTransform.duration = 0.333 // 0.0333 * 10
circleTransform.values = [
NSValue(CATransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 0/10
NSValue(CATransform3D: CATransform3DMakeScale(0.5, 0.5, 1.0)), // 1/10
NSValue(CATransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)), // 2/10
NSValue(CATransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 3/10
NSValue(CATransform3D: CATransform3DMakeScale(1.3, 1.3, 1.0)), // 4/10
NSValue(CATransform3D: CATransform3DMakeScale(1.37, 1.37, 1.0)), // 5/10
NSValue(CATransform3D: CATransform3DMakeScale(1.4, 1.4, 1.0)), // 6/10
NSValue(CATransform3D: CATransform3DMakeScale(1.4, 1.4, 1.0)) // 10/10
]
circleTransform.keyTimes = [
0.0, // 0/10
0.1, // 1/10
0.2, // 2/10
0.3, // 3/10
0.4, // 4/10
0.5, // 5/10
0.6, // 6/10
1.0 // 10/10
]
circleMaskTransform.duration = 0.333 // 0.0333 * 10
circleMaskTransform.values = [
NSValue(CATransform3D: CATransform3DIdentity), // 0/10
NSValue(CATransform3D: CATransform3DIdentity), // 2/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 1.25, imageFrame.height * 1.25, 1.0)), // 3/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 2.688, imageFrame.height * 2.688, 1.0)), // 4/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 3.923, imageFrame.height * 3.923, 1.0)), // 5/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 4.375, imageFrame.height * 4.375, 1.0)), // 6/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 4.731, imageFrame.height * 4.731, 1.0)), // 7/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 5.0, imageFrame.height * 5.0, 1.0)), // 9/10
NSValue(CATransform3D: CATransform3DMakeScale(imageFrame.width * 5.0, imageFrame.height * 5.0, 1.0)) // 10/10
]
circleMaskTransform.keyTimes = [
0.0, // 0/10
0.2, // 2/10
0.3, // 3/10
0.4, // 4/10
0.5, // 5/10
0.6, // 6/10
0.7, // 7/10
0.9, // 9/10
1.0 // 10/10
]
//==============================
// line stroke animation
//==============================
lineStrokeStart.duration = 0.6 //0.0333 * 18
lineStrokeStart.values = [
0.0, // 0/18
0.0, // 1/18
0.18, // 2/18
0.2, // 3/18
0.26, // 4/18
0.32, // 5/18
0.4, // 6/18
0.6, // 7/18
0.71, // 8/18
0.89, // 17/18
0.92 // 18/18
]
lineStrokeStart.keyTimes = [
0.0, // 0/18
0.056, // 1/18
0.111, // 2/18
0.167, // 3/18
0.222, // 4/18
0.278, // 5/18
0.333, // 6/18
0.389, // 7/18
0.444, // 8/18
0.944, // 17/18
1.0, // 18/18
]
lineStrokeEnd.duration = 0.6 //0.0333 * 18
lineStrokeEnd.values = [
0.0, // 0/18
0.0, // 1/18
0.32, // 2/18
0.48, // 3/18
0.64, // 4/18
0.68, // 5/18
0.92, // 17/18
0.92 // 18/18
]
lineStrokeEnd.keyTimes = [
0.0, // 0/18
0.056, // 1/18
0.111, // 2/18
0.167, // 3/18
0.222, // 4/18
0.278, // 5/18
0.944, // 17/18
1.0, // 18/18
]
lineOpacity.duration = 1.0 //0.0333 * 30
lineOpacity.values = [
1.0, // 0/30
1.0, // 12/30
0.0 // 17/30
]
lineOpacity.keyTimes = [
0.0, // 0/30
0.4, // 12/30
0.567 // 17/30
]
//==============================
// image transform animation
//==============================
imageTransform.duration = 1.0 //0.0333 * 30
imageTransform.values = [
NSValue(CATransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 0/30
NSValue(CATransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 3/30
NSValue(CATransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 9/30
NSValue(CATransform3D: CATransform3DMakeScale(1.25, 1.25, 1.0)), // 10/30
NSValue(CATransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 11/30
NSValue(CATransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)), // 14/30
NSValue(CATransform3D: CATransform3DMakeScale(0.875, 0.875, 1.0)), // 15/30
NSValue(CATransform3D: CATransform3DMakeScale(0.875, 0.875, 1.0)), // 16/30
NSValue(CATransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)), // 17/30
NSValue(CATransform3D: CATransform3DMakeScale(1.013, 1.013, 1.0)), // 20/30
NSValue(CATransform3D: CATransform3DMakeScale(1.025, 1.025, 1.0)), // 21/30
NSValue(CATransform3D: CATransform3DMakeScale(1.013, 1.013, 1.0)), // 22/30
NSValue(CATransform3D: CATransform3DMakeScale(0.96, 0.96, 1.0)), // 25/30
NSValue(CATransform3D: CATransform3DMakeScale(0.95, 0.95, 1.0)), // 26/30
NSValue(CATransform3D: CATransform3DMakeScale(0.96, 0.96, 1.0)), // 27/30
NSValue(CATransform3D: CATransform3DMakeScale(0.99, 0.99, 1.0)), // 29/30
NSValue(CATransform3D: CATransform3DIdentity) // 30/30
]
imageTransform.keyTimes = [
0.0, // 0/30
0.1, // 3/30
0.3, // 9/30
0.333, // 10/30
0.367, // 11/30
0.467, // 14/30
0.5, // 15/30
0.533, // 16/30
0.567, // 17/30
0.667, // 20/30
0.7, // 21/30
0.733, // 22/30
0.833, // 25/30
0.867, // 26/30
0.9, // 27/30
0.967, // 29/30
1.0 // 30/30
]
//===============
// add target
//===============
self.addTarget(self, action: "touchDown:", forControlEvents: UIControlEvents.TouchDown)
self.addTarget(self, action: "touchUpInside:", forControlEvents: UIControlEvents.TouchUpInside)
self.addTarget(self, action: "touchDragExit:", forControlEvents: UIControlEvents.TouchDragExit)
self.addTarget(self, action: "touchDragEnter:", forControlEvents: UIControlEvents.TouchDragEnter)
self.addTarget(self, action: "touchCancel:", forControlEvents: UIControlEvents.TouchCancel)
}
func touchDown(sender: DOFavoriteButton) {
self.layer.opacity = 0.4
}
func touchUpInside(sender: DOFavoriteButton) {
self.layer.opacity = 1.0
}
func touchDragExit(sender: DOFavoriteButton) {
self.layer.opacity = 1.0
}
func touchDragEnter(sender: DOFavoriteButton) {
self.layer.opacity = 0.4
}
func touchCancel(sender: DOFavoriteButton) {
self.layer.opacity = 1.0
}
func select() {
selected = true
imageShape.fillColor = imageColorOn.CGColor
CATransaction.begin()
circleShape.addAnimation(circleTransform, forKey: "transform")
circleMask.addAnimation(circleMaskTransform, forKey: "transform")
imageShape.addAnimation(imageTransform, forKey: "transform")
for i in 0 ..< 5 {
lines[i].addAnimation(lineStrokeStart, forKey: "strokeStart")
lines[i].addAnimation(lineStrokeEnd, forKey: "strokeEnd")
lines[i].addAnimation(lineOpacity, forKey: "opacity")
}
CATransaction.commit()
}
func deselect() {
selected = false
imageShape.fillColor = imageColorOff.CGColor
// remove all animations
circleShape.removeAllAnimations()
circleMask.removeAllAnimations()
imageShape.removeAllAnimations()
lines[0].removeAllAnimations()
lines[1].removeAllAnimations()
lines[2].removeAllAnimations()
lines[3].removeAllAnimations()
lines[4].removeAllAnimations()
}
}
| gpl-2.0 | 8193c04b9673aead6de39def265f802e | 38.797436 | 173 | 0.523871 | 3.946351 | false | false | false | false |
everald/JetPack | Sources/Measures/Pressure.swift | 2 | 1855 | // TODO use SI unit for rawValue
// TODO make sure conversation millibar<>inHg is correct
private let inchesOfMercuryPerMillibar = 0.02953
private let millibarsPerInchOfMercury = 1 / inchesOfMercuryPerMillibar
public struct Pressure: Measure {
public static let name = MeasuresStrings.Measure.pressure
public static let rawUnit = PressureUnit.millibars
public var rawValue: Double
public init(_ value: Double, unit: PressureUnit) {
precondition(!value.isNaN, "Value must not be NaN.")
switch unit {
case .inchesOfMercury: rawValue = value * millibarsPerInchOfMercury
case .millibars: rawValue = value
}
}
public init(inchesOfMercury: Double) {
self.init(inchesOfMercury, unit: .inchesOfMercury)
}
public init(millibars: Double) {
self.init(millibars, unit: .millibars)
}
public init(rawValue: Double) {
self.rawValue = rawValue
}
public var inchesOfMercury: Double {
return millibars * inchesOfMercuryPerMillibar
}
public var millibars: Double {
return rawValue
}
public func valueInUnit(_ unit: PressureUnit) -> Double {
switch unit {
case .inchesOfMercury: return inchesOfMercury
case .millibars: return millibars
}
}
}
public enum PressureUnit: Unit {
case inchesOfMercury
case millibars
}
extension PressureUnit {
public var abbreviation: String {
switch self {
case .inchesOfMercury: return MeasuresStrings.Unit.InchOfMercury.abbreviation
case .millibars: return MeasuresStrings.Unit.Millibar.abbreviation
}
}
public var name: PluralizedString {
switch self {
case .inchesOfMercury: return MeasuresStrings.Unit.InchOfMercury.name
case .millibars: return MeasuresStrings.Unit.Millibar.name
}
}
public var symbol: String? {
switch self {
case .inchesOfMercury: return "″Hg"
case .millibars: return nil
}
}
}
| mit | 6ed1ed96c7f204884c6adb4753533d85 | 19.141304 | 79 | 0.733405 | 3.418819 | false | false | false | false |
cdtschange/SwiftMKit | SwiftMKit/UI/View/Password/PasswordTextView.swift | 1 | 5578 | //
// PasswordText.swift
// SwiftMKitDemo
//
// Created by cdts on 16/5/24.
// Copyright © 2016年 cdts. All rights reserved.
//
import Foundation
import UIKit
import IQKeyboardManager
public protocol PasswordTextViewDelegate: class {
func pt_didInputSixNumber(_ textView: PasswordTextView?, password : String)
}
public extension PasswordTextViewDelegate {
func pt_didInputSixNumber(_ textView: PasswordTextView?, password : String){}
}
open class PasswordTextView : UIView, UITextFieldDelegate {
fileprivate struct InnerConstant {
static let MaxCount = 6
static let InputViewBackGroundColor = UIColor(hex6: 0xF3F6FC)
static let borderWidth: CGFloat = 1
static let dotColor = UIColor.black
static let textColor = UIColor.black
static let textFont = UIFont.systemFont(ofSize: 20)
static let originEnableAutoToolbar = false
}
var isShow: Bool = false {
didSet {
setNeedsDisplay()
}
}
var inputTextField = UITextField()
open weak var delegate: PasswordTextViewDelegate?
open var password: String = "" {
didSet {
setNeedsDisplay()
}
}
open var inputViewColor = InnerConstant.InputViewBackGroundColor
open var borderWidth: CGFloat = InnerConstant.borderWidth
open var dotColor = InnerConstant.dotColor
open var textColor = InnerConstant.textColor
open var textFont = InnerConstant.textFont
open var originEnableAutoToolbar = InnerConstant.originEnableAutoToolbar
var passwordPannelType: PasswordPannelType = .normal
fileprivate var blackPointRadius: CGFloat = 8
public override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
}
func setupUI() {
backgroundColor = inputViewColor
inputTextField.keyboardType = .numberPad //解决iPhoneX键盘会忽大忽小的问题
inputTextField.delegate = self
inputTextField.inputView = NumberKeyboard.keyboard(inputTextField, type: .noDot)
addSubview(inputTextField)
addTapGesture(target: self, action: #selector(active))
blackPointRadius = (passwordPannelType == .normal) ? 8 : 5
if passwordPannelType == .fund {
borderWidth = 0.5
}
}
@objc func active() {
inputTextField.becomeFirstResponder()
}
func inactive() {
inputTextField.resignFirstResponder()
}
open override func draw(_ rect: CGRect) {
super.draw(rect)
let times = CGFloat(borderWidth) // 竖线的宽度
let rectangleWidth = (rect.width - 7*times) / CGFloat(InnerConstant.MaxCount)
let rectangleHeight = rect.height - times * 2
let fillColor = (passwordPannelType == .normal) ? UIColor.white : UIColor(hex6: 0xF8F8F8)
let borderColor = (passwordPannelType == .normal) ? UIColor.clear : UIColor(hex6: 0xE5E5E5)
for index in 0...InnerConstant.MaxCount {
let rectangleX = CGFloat(index) + CGFloat(index) * rectangleWidth + times
let path = UIBezierPath(rect: CGRect(x:rectangleX, y:times, width:rectangleWidth, height:rectangleHeight))
fillColor.setFill()
borderColor.setStroke()
path.stroke()
path.fill()
}
for index in 0..<password.length {
let string = "\(password[index])"
let floatIndex = CGFloat(index)
let centerX = floatIndex + floatIndex * rectangleWidth + rectangleWidth/2
let centerY = rectangleHeight/2
if self.isShow {
let textAttribute:[NSAttributedStringKey: Any] = [NSAttributedStringKey.foregroundColor: textColor,
NSAttributedStringKey.font: textFont]
let strSize = string.size(withAttributes: textAttribute)
let center = CGPoint(x: centerX - strSize.width/2, y: centerY - strSize.height/2)
string.draw(at: center, withAttributes: textAttribute)
} else {
let path = UIBezierPath()
let center = CGPoint(x: centerX, y: centerY)
path.addArc(withCenter: center, radius: 5, startAngle: 0, endAngle: .pi * 2, clockwise: true)
dotColor.setFill()
path.fill()
}
}
}
open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if password.length >= 6 && string != "" {
return false
}
if string == "" {
if password.length == 0 {
return false
}
password = password.toNSString.substring(to: password.length - 1)
} else {
password += string
}
if password.length >= 6 {
self.delegate?.pt_didInputSixNumber(self, password: password)
return false
} else {
return true
}
}
open func textFieldDidBeginEditing(_ textField: UITextField) {
originEnableAutoToolbar = IQKeyboardManager.shared().isEnableAutoToolbar
IQKeyboardManager.shared().isEnableAutoToolbar = false
}
open func textFieldDidEndEditing(_ textField: UITextField) {
IQKeyboardManager.shared().isEnableAutoToolbar = originEnableAutoToolbar
}
deinit {
print("PasswordTextView deinit")
}
}
| mit | 114fc6a810c1e88a1b53e86f9b94a881 | 36.439189 | 134 | 0.62967 | 4.899204 | false | false | false | false |
schibsted/layout | Layout/Layout+XML.swift | 1 | 7695 | // Copyright © 2017 Schibsted. All rights reserved.
import Foundation
extension Layout {
public init(xmlData: Data, url: URL? = nil, relativeTo: String? = #file) throws {
let xml: [XMLNode]
do {
xml = try XMLParser.parse(data: xmlData, options: .skipComments)
} catch {
throw LayoutError("XML parsing error: \(error)")
}
guard let root = xml.first else {
throw LayoutError("Empty XML document.")
}
guard !root.isHTML else {
guard case let .node(name, _, _) = root else {
preconditionFailure()
}
throw LayoutError("Invalid root element <\(name)> in XML. Root element must be a UIView or UIViewController.")
}
try self.init(xmlNode: root, url: url, relativeTo: relativeTo)
}
private init(xmlNode: XMLNode, url: URL?, relativeTo: String?) throws {
guard case .node(let className, var attributes, let childNodes) = xmlNode else {
preconditionFailure()
}
var body = ""
var isHTML = false
var children = [Layout]()
var childrenTagIndex: Int?
var parameters = [String: RuntimeType]()
var macros = [String: String]()
for node in childNodes {
switch node {
case let .node(_, attributes, childNodes):
if node.isMacro {
guard childNodes.isEmpty else {
throw LayoutError("<macro> node should not contain sub-nodes", in: className, in: url)
}
for key in ["name", "value"] {
guard let value = attributes[key], !value.isEmpty else {
throw LayoutError("<macro> \(key) is a required attribute", in: className, in: url)
}
}
var name = ""
var expression: String?
for (key, value) in attributes {
switch key {
case "name":
name = value
case "value":
expression = value
default:
throw LayoutError("Unexpected attribute \(key) in <macro>", in: className, in: url)
}
}
macros[name] = expression
} else if node.isChildren {
guard childNodes.isEmpty else {
throw LayoutError("<children> node should not contain sub-nodes", in: className, in: url)
}
for key in attributes.keys {
throw LayoutError("Unexpected attribute \(key) in <children>", in: className, in: url)
}
childrenTagIndex = children.count
} else if isHTML { // <param> is a valid html tag, so check if we're in an HTML context first
body += try LayoutError.wrap({ try node.toHTML() }, in: className, in: url)
} else if node.isParameter {
guard childNodes.isEmpty else {
throw LayoutError("<param> node should not contain sub-nodes", in: className, in: url)
}
for key in ["name", "type"] {
guard let value = attributes[key], !value.isEmpty else {
throw LayoutError("<param> \(key) is a required attribute", in: className, in: url)
}
}
var name = ""
var type: RuntimeType?
for (key, value) in attributes {
switch key {
case "name":
name = value
case "type":
guard let runtimeType = RuntimeType.type(named: value) else {
throw LayoutError("Unknown or unsupported type \(value) in <param>. Try using Any instead", in: className, in: url)
}
type = runtimeType
default:
throw LayoutError("Unexpected attribute \(key) in <param>", in: className, in: url)
}
}
parameters[name] = type
} else if node.isHTML {
body = try LayoutError.wrap({ try body.xmlEncoded() + node.toHTML() }, in: className, in: url)
isHTML = true
} else {
try LayoutError.wrap({
try children.append(Layout(xmlNode: node, url: url, relativeTo: relativeTo))
}, in: className, in: url)
}
case let .text(string):
body += isHTML ? string.xmlEncoded() : string
case .comment:
preconditionFailure()
}
}
func parseStringAttribute(for name: String) throws -> String? {
guard let expression = attributes[name] else {
return nil
}
attributes[name] = nil
let parts = try LayoutError.wrap({ try parseStringExpression(expression) }, in: className, in: url)
if parts.count == 1 {
switch parts[0] {
case .comment:
return nil
case let .string(string):
return string
case .expression:
break
}
} else if parts.isEmpty {
return nil
}
throw LayoutError("\(name) must be a literal value, not an expression", in: className, in: url)
}
let id = try parseStringAttribute(for: "id")
let xmlPath = try parseStringAttribute(for: "xml")
let templatePath = try parseStringAttribute(for: "template")
body = body
.trimmingCharacters(in: .whitespacesAndNewlines)
.replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
self.init(
className: className,
id: id,
expressions: attributes,
parameters: parameters,
macros: macros,
children: children,
body: body.isEmpty ? nil : body,
xmlPath: xmlPath,
templatePath: templatePath,
childrenTagIndex: childrenTagIndex,
relativePath: relativeTo,
rootURL: url
)
}
}
private extension XMLNode {
func toHTML() throws -> String {
var text = ""
switch self {
case let .node(name, attributes, children):
guard isHTML else {
throw LayoutError("Unsupported HTML element <\(name)>.")
}
text += "<\(name)"
for (key, value) in attributes {
text += " \(key)=\"\(value.xmlEncoded(forAttribute: true))\""
}
if emptyHTMLTags.contains(name) {
// TODO: if there are children, should this be an error
text += "/>" // TODO: should we remove the closing slash here?
break
}
text += ">"
for node in children {
text += try node.toHTML()
}
return text + "</\(name)>"
case let .text(string):
text += string.xmlEncoded()
case .comment:
break // Ignore
}
return text
}
}
| mit | a5e45ed6814da0dd97da5b18871ceb9d | 40.589189 | 147 | 0.473356 | 5.372905 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Display information/Graphics overlay (dictionary renderer) 3D/GraphicsOverlayDictionaryRenderer3DViewController.swift | 1 | 6474 | //
// Copyright © 2019 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import ArcGIS
/// A view controller that manages the interface of the Graphics Overlay
/// (Dictionary Renderer) 3D sample.
class GraphicsOverlayDictionaryRenderer3DViewController: UIViewController {
/// The scene view managed by the view controller.
@IBOutlet weak var sceneView: AGSSceneView! {
didSet {
sceneView.scene = AGSScene(basemapStyle: .arcGISTopographic)
sceneView.graphicsOverlays.add(makeGraphicsOverlay())
}
}
/// Creates a graphics overlay configured to display MIL-STD-2525D
/// symbology.
/// - Returns: A new `AGSGraphicsOverlay` object.
func makeGraphicsOverlay() -> AGSGraphicsOverlay {
let graphicsOverlay = AGSGraphicsOverlay()
// Create the style from Joint Military Symbology MIL-STD-2525D
// portal item.
let dictionarySymbolStyle = AGSDictionarySymbolStyle(
portalItem: AGSPortalItem(
portal: .arcGISOnline(withLoginRequired: false),
itemID: "d815f3bdf6e6452bb8fd153b654c94ca"
)
)
dictionarySymbolStyle.load { [weak self, weak graphicsOverlay] error in
guard let self = self, let graphicsOverlay = graphicsOverlay else {
return
}
if let error = error {
self.presentAlert(error: error)
} else {
let camera = AGSCamera(lookAt: graphicsOverlay.extent.center, distance: 15_000, heading: 0, pitch: 70, roll: 0)
self.sceneView.setViewpointCamera(camera)
// Use Ordered Anchor Points for the symbol style draw rule.
if let drawRuleConfiguration = dictionarySymbolStyle.configurations.first(where: { $0.name == "model" }) {
drawRuleConfiguration.value = "ORDERED ANCHOR POINTS"
}
graphicsOverlay.renderer = AGSDictionaryRenderer(dictionarySymbolStyle: dictionarySymbolStyle)
}
}
// Read the messages and add a graphic to the overlay for each messages.
if let messagesURL = Bundle.main.url(forResource: "Mil2525DMessages", withExtension: "xml") {
do {
let messagesData = try Data(contentsOf: messagesURL)
let messages = try MessageParser().parseMessages(from: messagesData)
let graphics = messages.map { AGSGraphic(geometry: AGSMultipoint(points: $0.points), symbol: nil, attributes: $0.attributes) }
graphicsOverlay.graphics.addObjects(from: graphics)
} catch {
print("Error reading or decoding messages: \(error)")
}
} else {
preconditionFailure("Missing Mil2525DMessages.xml")
}
return graphicsOverlay
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
// Add the source code button item to the right of navigation bar.
(navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = ["GraphicsOverlayDictionaryRenderer3DViewController"]
}
}
struct Message {
var points: [AGSPoint]
var attributes: [String: Any]
}
class MessageParser: NSObject {
struct ControlPoint {
var x: Double
var y: Double
}
private var controlPoints = [ControlPoint]()
private var wkid: Int?
private var attributes = [String: Any]()
private var contentsOfCurrentElement = ""
private var parsedMessages = [Message]()
func didFinishParsingMessage() {
let spatialReference = AGSSpatialReference(wkid: wkid!)
let points = controlPoints.map { AGSPoint(x: $0.x, y: $0.y, spatialReference: spatialReference) }
let message = Message(points: points, attributes: attributes)
parsedMessages.append(message)
wkid = nil
controlPoints.removeAll()
attributes.removeAll()
}
func parseMessages(from data: Data) throws -> [Message] {
defer { parsedMessages.removeAll() }
let parser = XMLParser(data: data)
parser.delegate = self
let parsingSucceeded = parser.parse()
if parsingSucceeded {
return parsedMessages
} else if let error = parser.parserError {
throw error
} else {
return []
}
}
}
extension MessageParser: XMLParserDelegate {
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String] = [:]) {
contentsOfCurrentElement.removeAll()
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
contentsOfCurrentElement.append(contentsOf: string)
}
enum Element: String {
case controlPoints = "_control_points"
case message
case messages
case wkid = "_wkid"
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if let element = Element(rawValue: elementName) {
switch element {
case .controlPoints:
controlPoints = contentsOfCurrentElement.split(separator: ";").map { (pair) in
let coordinates = pair.split(separator: ",")
return ControlPoint(x: Double(coordinates.first!)!, y: Double(coordinates.last!)!)
}
case .message:
didFinishParsingMessage()
case .messages:
break
case .wkid:
wkid = Int(contentsOfCurrentElement)
}
} else {
attributes[elementName] = contentsOfCurrentElement
}
contentsOfCurrentElement.removeAll()
}
}
| apache-2.0 | 2efdef3244196b7fe29ae87834ce6f68 | 37.301775 | 178 | 0.628148 | 4.975404 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Scenes/Scene properties expressions/ScenePropertiesExpressionsViewController.swift | 1 | 3174 | //
// Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class ScenePropertiesExpressionsViewController: UIViewController {
@IBOutlet var sceneView: AGSSceneView!
@IBOutlet var headingLabel: UILabel!
@IBOutlet var pitchLabel: UILabel!
private var coneGraphic: AGSGraphic!
override func viewDidLoad() {
super.viewDidLoad()
// add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["ScenePropertiesExpressionsViewController"]
// Initialize scene with streets basemap style.
let scene = AGSScene(basemapStyle: .arcGISStreets)
// assign scene to the scene view
self.sceneView.scene = scene
// set the viewpoint camera
let point = AGSPoint(x: 83.9, y: 28.4, z: 5200, spatialReference: .wgs84())
let camera = AGSCamera(lookAt: point, distance: 1000, heading: 0, pitch: 50, roll: 0)
self.sceneView.setViewpointCamera(camera)
// create a graphics overlay
let graphicsOverlay = AGSGraphicsOverlay()
graphicsOverlay.sceneProperties?.surfacePlacement = .relative
// add it to the scene view
self.sceneView.graphicsOverlays.add(graphicsOverlay)
// add renderer using rotation expressions
let renderer = AGSSimpleRenderer()
renderer.sceneProperties?.headingExpression = "[HEADING]"
renderer.sceneProperties?.pitchExpression = "[PITCH]"
graphicsOverlay.renderer = renderer
// create a red cone graphic
let coneSymbol = AGSSimpleMarkerSceneSymbol(style: .cone, color: .red, height: 200, width: 100, depth: 100, anchorPosition: .center)
coneSymbol.pitch = -90 // correct symbol's default pitch
let conePoint = AGSPoint(x: 83.9, y: 28.404, z: 5000, spatialReference: .wgs84())
let coneAttributes = ["HEADING": 0, "PITCH": 0]
let coneGraphic = AGSGraphic(geometry: conePoint, symbol: coneSymbol, attributes: coneAttributes)
graphicsOverlay.graphics.add(coneGraphic)
self.coneGraphic = coneGraphic
}
@IBAction func headingSliderValueChanged(_ slider: UISlider) {
coneGraphic.attributes["HEADING"] = slider.value
// update label
self.headingLabel.text = "\(Int(slider.value))"
}
@IBAction func pitchSliderValueChanged(_ slider: UISlider) {
coneGraphic.attributes["PITCH"] = slider.value
// update label
self.pitchLabel.text = "\(Int(slider.value))"
}
}
| apache-2.0 | 85350a711bbf965790ccd97516531acf | 40.763158 | 140 | 0.679269 | 4.553802 | 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.