repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
domenicosolazzo/practice-swift | CoreMotion/Ball/Ball/ViewController.swift | 1 | 1103 | //
// ViewController.swift
// Ball
//
// Created by Domenico on 02/05/15.
// Copyright (c) 2015 Domenico. All rights reserved.
//
import UIKit
import CoreMotion
class ViewController: UIViewController {
fileprivate let updateInterval = 1.0/60.0
fileprivate let motionManager = CMMotionManager()
fileprivate let queue = OperationQueue()
override func viewDidLoad() {
super.viewDidLoad()
motionManager.deviceMotionUpdateInterval = updateInterval
motionManager.startDeviceMotionUpdates(to: queue,
withHandler: {
(motionData: CMDeviceMotion!, error: NSError!) -> Void in
let ballView = self.view as! BallView
ballView.acceleration = motionData.gravity
DispatchQueue.main.asynchronously(DispatchQueue.mainexecute: {
ballView.update()
})
} as! CMDeviceMotionHandler)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | d761b98dd3753033cf6cf725ce95bd78 | 27.282051 | 78 | 0.640073 | 5.433498 | false | false | false | false |
johndpope/ClangWrapper.Swift | ClangASTViewer/AppDelegate.swift | 1 | 6460 | //
// AppDelegate.swift
// ClangASTViewer
//
// Created by Hoon H. on 2015/01/24.
// Copyright (c) 2015 Eonil. All rights reserved.
//
import Cocoa
import ClangWrapper
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
let idx = Index(excludeDeclarationsFromPCH: false, displayDiagnostics: false)
let mainSplit = MainSplitViewControlelr()
func applicationDidFinishLaunching(aNotification: NSNotification) {
window.contentViewController = mainSplit
var ps = [] as [String]
let p = NSBundle.mainBundle().resourcePath!
let p1 = p + "/LLDB.framework/Headers/LLDB.h"
let args = [
"-x", "c++",
"-std=c++11",
"-stdlib=libc++",
"-isysroot", "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk",
"-I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include",
"-F\(p)",
]
let tu = self.idx.parseTranslationUnit(p1, commandLineArguments: args)
println(tu.diagnostics)
precondition(tu.diagnostics.count == 0)
////
let root = ASTRootNode()
root.translationUnitChildNodes.append(TranslationUnitNode(tu))
mainSplit.syntaxTree.syntaxOutline.rootNodeRepresentation = root
mainSplit.syntaxTree.syntaxOutline.outlineView.reloadData()
mainSplit.syntaxTree.becomeFirstResponder()
}
func applicationWillTerminate(aNotification: NSNotification) {
}
}
///Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang
//-x c++
//-arch x86_64
//-fmessage-length=0
//-fdiagnostics-show-note-include-stack
//-fmacro-backtrace-limit=0
//-std=gnu++11
//-stdlib=libc++
//-fmodules
//-fmodules-cache-path=/Users/Eonil/Workshop/Temp/Xcode/Derivations/ModuleCache
//-fmodules-prune-interval=86400
//-fmodules-prune-after=345600
//-Wnon-modular-include-in-framework-module
//-Werror=non-modular-include-in-framework-module
//-Wno-trigraphs
//-fpascal-strings
//-O0
//-Wno-missing-field-initializers
//-Wno-missing-prototypes
//-Werror=return-type
//-Wunreachable-code
//-Werror=deprecated-objc-isa-usage
//-Werror=objc-root-class
//-Wno-non-virtual-dtor
//-Wno-overloaded-virtual
//-Wno-exit-time-destructors
//-Wno-missing-braces
//-Wparentheses
//-Wswitch
//-Wunused-function
//-Wno-unused-label
//-Wno-unused-parameter
//-Wunused-variable
//-Wunused-value
//-Wempty-body
//-Wconditional-uninitialized
//-Wno-unknown-pragmas
//-Wno-shadow
//-Wno-four-char-constants
//-Wno-conversion
//-Wconstant-conversion
//-Wint-conversion
//-Wbool-conversion
//-Wenum-conversion
//-Wshorten-64-to-32
//-Wno-newline-eof
//-Wno-c++11-extensions
//-DDEBUG=1
//-isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk
//-fasm-blocks
//-fstrict-aliasing
//-Wdeprecated-declarations
//-Winvalid-offsetof
//-mmacosx-version-min=10.10
//-g
//-fvisibility-inlines-hidden
//-Wno-sign-conversion
//-iquote /Users/Eonil/Workshop/Temp/Xcode/Derivations/LLDBWrapperOnly-airsqgxbfhgxzbftmxsbryswsmcx/Build/Intermediates/LLDBWrapper.build/Debug/SampleProgram4.build/SampleProgram4-generated-files.hmap
//-I/Users/Eonil/Workshop/Temp/Xcode/Derivations/LLDBWrapperOnly-airsqgxbfhgxzbftmxsbryswsmcx/Build/Intermediates/LLDBWrapper.build/Debug/SampleProgram4.build/SampleProgram4-own-target-headers.hmap
//-I/Users/Eonil/Workshop/Temp/Xcode/Derivations/LLDBWrapperOnly-airsqgxbfhgxzbftmxsbryswsmcx/Build/Intermediates/LLDBWrapper.build/Debug/SampleProgram4.build/SampleProgram4-all-target-headers.hmap
//-iquote /Users/Eonil/Workshop/Temp/Xcode/Derivations/LLDBWrapperOnly-airsqgxbfhgxzbftmxsbryswsmcx/Build/Intermediates/LLDBWrapper.build/Debug/SampleProgram4.build/SampleProgram4-project-headers.hmap
//-I/Users/Eonil/Workshop/Temp/Xcode/Derivations/LLDBWrapperOnly-airsqgxbfhgxzbftmxsbryswsmcx/Build/Products/Debug/include
//-I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
//-I/Users/Eonil/Workshop/Temp/Xcode/Derivations/LLDBWrapperOnly-airsqgxbfhgxzbftmxsbryswsmcx/Build/Intermediates/LLDBWrapper.build/Debug/SampleProgram4.build/DerivedSources/x86_64
//-I/Users/Eonil/Workshop/Temp/Xcode/Derivations/LLDBWrapperOnly-airsqgxbfhgxzbftmxsbryswsmcx/Build/Intermediates/LLDBWrapper.build/Debug/SampleProgram4.build/DerivedSources
//-F/Users/Eonil/Workshop/Temp/Xcode/Derivations/LLDBWrapperOnly-airsqgxbfhgxzbftmxsbryswsmcx/Build/Products/Debug
//-F/Users/Eonil/Workshop/Incubation/LLDBWrapper
//-MMD
//-MT dependencies
//-MF /Users/Eonil/Workshop/Temp/Xcode/Derivations/LLDBWrapperOnly-airsqgxbfhgxzbftmxsbryswsmcx/Build/Intermediates/LLDBWrapper.build/Debug/SampleProgram4.build/Objects-normal/x86_64/Try1.d
//--serialize-diagnostics /Users/Eonil/Workshop/Temp/Xcode/Derivations/LLDBWrapperOnly-airsqgxbfhgxzbftmxsbryswsmcx/Build/Intermediates/LLDBWrapper.build/Debug/SampleProgram4.build/Objects-normal/x86_64/Try1.dia
//-c /Users/Eonil/Workshop/Incubation/LLDBWrapper/SampleProgram4/Try1.cpp
//-o /Users/Eonil/Workshop/Temp/Xcode/Derivations/LLDBWrapperOnly-airsqgxbfhgxzbftmxsbryswsmcx/Build/Intermediates/LLDBWrapper.build/Debug/SampleProgram4.build/Objects-normal/x86_64/Try1.o
class MainSplitViewControlelr: NSSplitViewController {
let syntaxTree = SyntaxTreeViewController()
let typeTree = TypeTreeViewController()
override func viewDidLoad() {
super.viewDidLoad()
self.addSplitViewItem(NSSplitViewItem(viewController: syntaxTree))
// self.addSplitViewItem(NSSplitViewItem(viewController: typeTree))
}
}
class ScrollViewController: NSViewController {
var scrollView:NSScrollView {
get {
return view as! NSScrollView
}
}
override func loadView() {
super.view = NSScrollView()
}
var documentViewController:NSViewController? {
didSet {
self.scrollView.documentView = documentViewController?.view
}
}
}
class SyntaxTreeViewController: ScrollViewController {
let syntaxOutline = SyntaxOutlineViewController()
override func viewDidLoad() {
super.viewDidLoad()
scrollView.hasVerticalScroller = true
scrollView.hasHorizontalRuler = true
self.documentViewController = syntaxOutline
}
}
class TypeTreeViewController: ScrollViewController {
let typeOutline = SyntaxOutlineViewController()
override func viewDidLoad() {
super.viewDidLoad()
scrollView.hasVerticalScroller = true
scrollView.hasHorizontalRuler = true
self.documentViewController = typeOutline
}
}
| mit | 53261a1be4c6c21531d1b3ff231606f0 | 30.207729 | 211 | 0.790093 | 3.744928 | false | false | false | false |
keygx/ButtonStyleKit | ButtonStyleKitSample/ButtonStyleKit/ButtonStyleBuilder.swift | 1 | 16343 | //
// ButtonStyleBuilder.swift
// ButtonStyleKit
//
// Created by keygx on 2016/08/04.
// Copyright © 2016年 keygx. All rights reserved.
//
import UIKit
private class Property<T> {
var normal: T?
var highlighted: T?
var selected: T?
var disabled: T?
}
open class ButtonStyleBuilder {
// Basic
private weak var button: ButtonStyleKit!
private var state: ButtonStyleKit.ButtonState = .normal
// Styles
private var font = Property<UIFont>()
private var borderWidth = Property<CGFloat>()
private var borderColor = Property<UIColor>()
private var cornerRadius = Property<CGFloat>()
private var opacity = Property<Float>()
private var backgroundColor = Property<UIColor>()
private var tintColor = Property<UIColor>()
private var shadowColor = Property<UIColor>()
private var shadowOpacity = Property<Float>()
private var shadowOffset = Property<CGSize>()
private var shadowRadius = Property<CGFloat>()
private var shadowPath = Property<CGPath>()
private var clipsToBounds = Property<Bool>()
private var masksToBounds = Property<Bool>()
private var isExclusiveTouch = Property<Bool>()
private var contentHorizontalAlignment = Property<UIControl.ContentHorizontalAlignment>()
private var contentVerticalAlignment = Property<UIControl.ContentVerticalAlignment>()
private var titleEdgeInsets = Property<UIEdgeInsets>()
private var contentEdgeInsets = Property<UIEdgeInsets>()
private var imageEdgeInsets = Property<UIEdgeInsets>()
private var reversesTitleShadowWhenHighlighted = Property<Bool>()
private var adjustsImageWhenHighlighted = Property<Bool>()
private var adjustsImageWhenDisabled = Property<Bool>()
private var showsTouchWhenHighlighted = Property<Bool>()
public init() {}
// Chain
public func setButton(_ button: ButtonStyleKit) -> Self {
self.button = button
return self
}
public func setState(_ state: ButtonStyleKit.ButtonState) -> Self {
self.state = state
return self
}
public func setTitle(_ title: String) -> Self {
if let state = state.getState() {
button.setTitle(title, for: state)
} else {
button.setTitle(title, for: .normal)
button.setTitle(title, for: .highlighted)
button.setTitle(title, for: .selected)
button.setTitle(title, for: .disabled)
}
return self
}
public func setTitleColor(_ titleColor: UIColor) -> Self {
if let state = state.getState() {
button.setTitleColor(titleColor, for: state)
} else {
button.setTitleColor(titleColor, for: .normal)
button.setTitleColor(titleColor, for: .highlighted)
button.setTitleColor(titleColor, for: .selected)
button.setTitleColor(titleColor, for: .disabled)
}
return self
}
public func setTitleShadowColor(_ titleShadowColor: UIColor) -> Self {
if let state = state.getState() {
button.setTitleShadowColor(titleShadowColor, for: state)
} else {
button.setTitleShadowColor(titleShadowColor, for: .normal)
button.setTitleShadowColor(titleShadowColor, for: .highlighted)
button.setTitleShadowColor(titleShadowColor, for: .selected)
button.setTitleShadowColor(titleShadowColor, for: .disabled)
}
return self
}
public func setImage(_ image: UIImage) -> Self {
if let state = state.getState() {
button.setImage(image, for: state)
} else {
button.setImage(image, for: .normal)
button.setImage(image, for: .highlighted)
button.setImage(image, for: .selected)
button.setImage(image, for: .disabled)
}
return self
}
public func setBackgroundImage(_ backgroundImage: UIImage) -> Self {
if let state = state.getState() {
button.setBackgroundImage(backgroundImage, for: state)
} else {
button.setBackgroundImage(backgroundImage, for: .normal)
button.setBackgroundImage(backgroundImage, for: .highlighted)
button.setBackgroundImage(backgroundImage, for: .selected)
button.setBackgroundImage(backgroundImage, for: .disabled)
}
return self
}
public func setAttributedTitle(_ attributedTitle: NSAttributedString) -> Self {
if let state = state.getState() {
button.setAttributedTitle(attributedTitle, for: state)
} else {
button.setAttributedTitle(attributedTitle, for: .normal)
button.setAttributedTitle(attributedTitle, for: .highlighted)
button.setAttributedTitle(attributedTitle, for: .selected)
button.setAttributedTitle(attributedTitle, for: .disabled)
}
return self
}
public func setFont(_ font: UIFont) -> Self {
setProperty(param: self.font, value: font, state: state)
return self
}
public func setBorderWidth(_ borderWidth: CGFloat) -> Self {
setProperty(param: self.borderWidth, value: borderWidth, state: state)
return self
}
public func setBorderColor(_ borderColor: UIColor) -> Self {
setProperty(param: self.borderColor, value: borderColor, state: state)
return self
}
public func setCornerRadius(_ cornerRadius: CGFloat) -> Self {
setProperty(param: self.cornerRadius, value: cornerRadius, state: state)
return self
}
public func setOpacity(_ opacity: Float) -> Self {
setProperty(param: self.opacity, value: opacity, state: state)
return self
}
public func setBackgroundColor(_ backgroundColor: UIColor) -> Self {
setProperty(param: self.backgroundColor, value: backgroundColor, state: state)
return self
}
public func setTintColor(_ tintColor: UIColor) -> Self {
setProperty(param: self.tintColor, value: tintColor, state: state)
return self
}
public func setShadowColor(_ shadowColor: UIColor) -> Self {
setProperty(param: self.shadowColor, value: shadowColor, state: state)
return self
}
public func setShadowOpacity(_ shadowOpacity: Float) -> Self {
setProperty(param: self.shadowOpacity, value: shadowOpacity, state: state)
return self
}
public func setShadowOffset(_ shadowOffset: CGSize) -> Self {
setProperty(param: self.shadowOffset, value: shadowOffset, state: state)
return self
}
public func setShadowRadius(_ shadowRadius: CGFloat) -> Self {
setProperty(param: self.shadowRadius, value: shadowRadius, state: state)
return self
}
public func setShadowPath(_ shadowPath: CGPath) -> Self {
setProperty(param: self.shadowPath, value: shadowPath, state: state)
return self
}
public func setMasksToBounds(_ masksToBounds: Bool) -> Self {
setProperty(param: self.masksToBounds, value: masksToBounds, state: state)
return self
}
public func setClipsToBounds(_ clipsToBounds: Bool) -> Self {
setProperty(param: self.clipsToBounds, value: clipsToBounds, state: state)
return self
}
public func setExclusiveTouch(_ isExclusiveTouch: Bool) -> Self {
setProperty(param: self.isExclusiveTouch, value: isExclusiveTouch, state: state)
return self
}
public func setContentHorizontalAlignment(_ contentHorizontalAlignment: UIControl.ContentHorizontalAlignment) -> Self {
setProperty(param: self.contentHorizontalAlignment, value: contentHorizontalAlignment, state: state)
return self
}
public func setContentVerticalAlignment(_ contentVerticalAlignment: UIControl.ContentVerticalAlignment) -> Self {
setProperty(param: self.contentVerticalAlignment, value: contentVerticalAlignment, state: state)
return self
}
public func setTitleEdgeInsets(top: CGFloat, right: CGFloat, bottom: CGFloat, left: CGFloat) -> Self {
setProperty(param: self.titleEdgeInsets, value: UIEdgeInsets(top: top, left: left, bottom: bottom, right: right), state: state)
return self
}
public func setContentEdgeInsets(top: CGFloat, right: CGFloat, bottom: CGFloat, left: CGFloat) -> Self {
setProperty(param: self.contentEdgeInsets, value: UIEdgeInsets(top: top, left: left, bottom: bottom, right: right), state: state)
return self
}
public func setImageEdgeInsets(top: CGFloat, right: CGFloat, bottom: CGFloat, left: CGFloat) -> Self {
setProperty(param: self.imageEdgeInsets, value: UIEdgeInsets(top: top, left: left, bottom: bottom, right: right), state: state)
return self
}
public func setReversesTitleShadowWhenHighlighted(_ bool: Bool) -> Self {
setProperty(param: self.reversesTitleShadowWhenHighlighted, value: bool, state: state)
return self
}
public func setAdjustsImageWhenHighlighted(_ bool: Bool) -> Self {
setProperty(param: self.adjustsImageWhenHighlighted, value: bool, state: state)
return self
}
public func setAdjustsImageWhenDisabled(_ bool: Bool) -> Self {
setProperty(param: self.adjustsImageWhenDisabled, value: bool, state: state)
return self
}
public func setShowsTouchWhenHighlighted(_ bool: Bool) -> Self {
setProperty(param: self.showsTouchWhenHighlighted, value: bool, state: state)
return self
}
private func setProperty<T>(param: Property<T>, value: T, state: ButtonStyleKit.ButtonState) {
switch state {
case .all:
param.normal = value
param.highlighted = value
param.selected = value
param.disabled = value
case .normal:
param.normal = value
case .highlighted:
param.highlighted = value
case .selected:
param.selected = value
case .disabled:
param.disabled = value
}
}
// Appear
public func build() {
if let font = attachProperty(font, state: state) {
button.titleLabel?.font = font
}
if let borderWidth = attachProperty(borderWidth, state: state) {
button.layer.borderWidth = borderWidth
}
if let borderColor = attachProperty(borderColor, state: state) {
button.layer.borderColor = borderColor.cgColor
}
if let cornerRadius = attachProperty(cornerRadius, state: state) {
button.layer.cornerRadius = cornerRadius
}
if let opacity = attachProperty(opacity, state: state) {
button.layer.opacity = opacity
}
if let backgroundColor = attachProperty(backgroundColor, state: state) {
button.layer.backgroundColor = backgroundColor.cgColor
}
if let tintColor = attachProperty(tintColor, state: state) {
button.tintColor = tintColor
}
if let shadowColor = attachProperty(shadowColor, state: state) {
button.layer.shadowColor = shadowColor.cgColor
}
if let shadowOpacity = attachProperty(shadowOpacity, state: state) {
button.layer.shadowOpacity = shadowOpacity
}
if let shadowOffset = attachProperty(shadowOffset, state: state) {
button.layer.shadowOffset = shadowOffset
}
if let shadowRadius = attachProperty(shadowRadius, state: state) {
button.layer.shadowRadius = shadowRadius
}
if let shadowPath = attachProperty(shadowPath, state: state) {
button.layer.shadowPath = shadowPath
}
if let clipsToBounds = attachProperty(clipsToBounds, state: state) {
button.clipsToBounds = clipsToBounds
}
if let masksToBounds = attachProperty(masksToBounds, state: state) {
button.layer.masksToBounds = masksToBounds
}
if let isExclusiveTouch = attachProperty(isExclusiveTouch, state: state) {
button.isExclusiveTouch = isExclusiveTouch
}
if let contentHorizontalAlignment = attachProperty(contentHorizontalAlignment, state: state) {
button.contentHorizontalAlignment = contentHorizontalAlignment
}
if let contentVerticalAlignment = attachProperty(contentVerticalAlignment, state: state) {
button.contentVerticalAlignment = contentVerticalAlignment
}
if let titleEdgeInsets = attachProperty(titleEdgeInsets, state: state) {
button.titleEdgeInsets = titleEdgeInsets
}
if let contentEdgeInsets = attachProperty(contentEdgeInsets, state: state) {
button.contentEdgeInsets = contentEdgeInsets
}
if let imageEdgeInsets = attachProperty(imageEdgeInsets, state: state) {
button.imageEdgeInsets = imageEdgeInsets
}
if let reversesTitleShadowWhenHighlighted = attachProperty(reversesTitleShadowWhenHighlighted, state: state) {
button.reversesTitleShadowWhenHighlighted = reversesTitleShadowWhenHighlighted
}
if let adjustsImageWhenHighlighted = attachProperty(adjustsImageWhenHighlighted, state: state) {
button.adjustsImageWhenHighlighted = adjustsImageWhenHighlighted
}
if let adjustsImageWhenDisabled = attachProperty(adjustsImageWhenDisabled, state: state) {
button.adjustsImageWhenDisabled = adjustsImageWhenDisabled
}
if let showsTouchWhenHighlighted = attachProperty(showsTouchWhenHighlighted, state: state) {
button.showsTouchWhenHighlighted = showsTouchWhenHighlighted
}
}
public func apply() {
guard let button = button else { return }
self.state = button.currentState
build()
}
private func attachProperty<T>(_ prop: Property<T>, state: ButtonStyleKit.ButtonState) -> T? {
switch state {
case .all:
return nil
case .normal:
return prop.normal
case .highlighted:
return prop.highlighted
case .selected:
return prop.selected
case .disabled:
return prop.disabled
}
}
}
// Helpers
extension ButtonStyleBuilder {
public final func createViewToImage(color: UIColor, frame: CGRect? = nil) -> UIImage? {
// View
var rect = CGRect()
rect = {
if let f = frame {
return f
} else {
return CGRect(x: 0, y: 0, width: 100, height: 100)
}
}()
let view = UIView(frame: rect)
view.backgroundColor = color
// Image
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(view.frame.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
view.layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
public final func createImageView(frame: CGRect, normal: String, highlighted: String?) -> UIImageView {
let imageView = UIImageView(frame: frame)
imageView.image = UIImage(named: normal)
if let highlighted = highlighted {
imageView.highlightedImage = UIImage(named: highlighted)
}
imageView.contentMode = .scaleAspectFit
return imageView
}
public final func createImageView(frame: CGRect, normal: UIImage, highlighted: UIImage?) -> UIImageView {
let imageView = UIImageView(frame: frame)
imageView.image = normal
if let highlighted = highlighted {
imageView.highlightedImage = highlighted
}
imageView.contentMode = .scaleAspectFit
return imageView
}
}
| mit | 94b7366194e8b5e87fce09b01df69696 | 36.136364 | 137 | 0.637638 | 5.464883 | false | false | false | false |
roberthein/BouncyLayout | example/BouncyLayout/Examples.swift | 1 | 1626 | import UIKit
enum Example {
case chatMessage
case photosCollection
case barGraph
static let count = 3
func controller() -> ViewController {
return ViewController(example: self)
}
var title: String {
switch self {
case .chatMessage: return "Chat Messages"
case .photosCollection: return "Photos Collection"
case .barGraph: return "Bar Graph"
}
}
}
class Examples: UITableViewController {
let examples: [Example] = [.barGraph, .photosCollection, .chatMessage]
override func viewDidLoad() {
super.viewDidLoad()
title = "Examples"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if #available(iOS 11.0, *) {
navigationController?.navigationBar.prefersLargeTitles = true
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Example.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = examples[indexPath.row].title
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
navigationController?.pushViewController(examples[indexPath.row].controller(), animated: true)
}
}
| mit | 2c527f6fc05066a713e8f9345a6fa763 | 28.563636 | 109 | 0.648831 | 5.42 | false | false | false | false |
natecook1000/swift | stdlib/public/SDK/Foundation/Measurement.swift | 1 | 15344 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if DEPLOYMENT_RUNTIME_SWIFT
import CoreFoundation
#else
@_exported import Foundation // Clang module
import _SwiftCoreFoundationOverlayShims
#endif
/// A `Measurement` is a model type that holds a `Double` value associated with a `Unit`.
///
/// Measurements support a large set of operators, including `+`, `-`, `*`, `/`, and a full set of comparison operators.
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public struct Measurement<UnitType : Unit> : ReferenceConvertible, Comparable, Equatable {
public typealias ReferenceType = NSMeasurement
/// The unit component of the `Measurement`.
public let unit: UnitType
/// The value component of the `Measurement`.
public var value: Double
/// Create a `Measurement` given a specified value and unit.
public init(value: Double, unit: UnitType) {
self.value = value
self.unit = unit
}
public var hashValue: Int {
return Int(bitPattern: __CFHashDouble(value))
}
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
return "\(value) \(unit.symbol)"
}
public var debugDescription: String {
return "\(value) \(unit.symbol)"
}
public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
c.append((label: "value", value: value))
c.append((label: "unit", value: unit.symbol))
return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
}
}
/// When a `Measurement` contains a `Dimension` unit, it gains the ability to convert between the kinds of units in that dimension.
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement where UnitType : Dimension {
/// Returns a new measurement created by converting to the specified unit.
///
/// - parameter otherUnit: A unit of the same `Dimension`.
/// - returns: A converted measurement.
public func converted(to otherUnit: UnitType) -> Measurement<UnitType> {
if unit.isEqual(otherUnit) {
return Measurement(value: value, unit: otherUnit)
} else {
let valueInTermsOfBase = unit.converter.baseUnitValue(fromValue: value)
if otherUnit.isEqual(type(of: unit).baseUnit()) {
return Measurement(value: valueInTermsOfBase, unit: otherUnit)
} else {
let otherValueFromTermsOfBase = otherUnit.converter.value(fromBaseUnitValue: valueInTermsOfBase)
return Measurement(value: otherValueFromTermsOfBase, unit: otherUnit)
}
}
}
/// Converts the measurement to the specified unit.
///
/// - parameter otherUnit: A unit of the same `Dimension`.
public mutating func convert(to otherUnit: UnitType) {
self = converted(to: otherUnit)
}
/// Add two measurements of the same Dimension.
///
/// If the `unit` of the `lhs` and `rhs` are `isEqual`, then this returns the result of adding the `value` of each `Measurement`. If they are not equal, then this will convert both to the base unit of the `Dimension` and return the result as a `Measurement` of that base unit.
/// - returns: The result of adding the two measurements.
public static func +(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit.isEqual(rhs.unit) {
return Measurement(value: lhs.value + rhs.value, unit: lhs.unit)
} else {
let lhsValueInTermsOfBase = lhs.unit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhs.unit.converter.baseUnitValue(fromValue: rhs.value)
return Measurement(value: lhsValueInTermsOfBase + rhsValueInTermsOfBase, unit: type(of: lhs.unit).baseUnit())
}
}
/// Subtract two measurements of the same Dimension.
///
/// If the `unit` of the `lhs` and `rhs` are `==`, then this returns the result of subtracting the `value` of each `Measurement`. If they are not equal, then this will convert both to the base unit of the `Dimension` and return the result as a `Measurement` of that base unit.
/// - returns: The result of adding the two measurements.
public static func -(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit == rhs.unit {
return Measurement(value: lhs.value - rhs.value, unit: lhs.unit)
} else {
let lhsValueInTermsOfBase = lhs.unit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhs.unit.converter.baseUnitValue(fromValue: rhs.value)
return Measurement(value: lhsValueInTermsOfBase - rhsValueInTermsOfBase, unit: type(of: lhs.unit).baseUnit())
}
}
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement {
/// Add two measurements of the same Unit.
/// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`.
/// - returns: A measurement of value `lhs.value + rhs.value` and unit `lhs.unit`.
public static func +(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit.isEqual(rhs.unit) {
return Measurement(value: lhs.value + rhs.value, unit: lhs.unit)
} else {
fatalError("Attempt to add measurements with non-equal units")
}
}
/// Subtract two measurements of the same Unit.
/// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`.
/// - returns: A measurement of value `lhs.value - rhs.value` and unit `lhs.unit`.
public static func -(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit.isEqual(rhs.unit) {
return Measurement(value: lhs.value - rhs.value, unit: lhs.unit)
} else {
fatalError("Attempt to subtract measurements with non-equal units")
}
}
/// Multiply a measurement by a scalar value.
/// - returns: A measurement of value `lhs.value * rhs` with the same unit as `lhs`.
public static func *(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> {
return Measurement(value: lhs.value * rhs, unit: lhs.unit)
}
/// Multiply a scalar value by a measurement.
/// - returns: A measurement of value `lhs * rhs.value` with the same unit as `rhs`.
public static func *(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
return Measurement(value: lhs * rhs.value, unit: rhs.unit)
}
/// Divide a measurement by a scalar value.
/// - returns: A measurement of value `lhs.value / rhs` with the same unit as `lhs`.
public static func /(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> {
return Measurement(value: lhs.value / rhs, unit: lhs.unit)
}
/// Divide a scalar value by a measurement.
/// - returns: A measurement of value `lhs / rhs.value` with the same unit as `rhs`.
public static func /(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
return Measurement(value: lhs / rhs.value, unit: rhs.unit)
}
/// Compare two measurements of the same `Dimension`.
///
/// If `lhs.unit == rhs.unit`, returns `lhs.value == rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values.
/// - returns: `true` if the measurements are equal.
public static func ==<LeftHandSideType, RightHandSideType>(lhs: Measurement<LeftHandSideType>, rhs: Measurement<RightHandSideType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value == rhs.value
} else {
if let lhsDimensionalUnit = lhs.unit as? Dimension,
let rhsDimensionalUnit = rhs.unit as? Dimension {
if type(of: lhsDimensionalUnit).baseUnit() == type(of: rhsDimensionalUnit).baseUnit() {
let lhsValueInTermsOfBase = lhsDimensionalUnit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhsDimensionalUnit.converter.baseUnitValue(fromValue: rhs.value)
return lhsValueInTermsOfBase == rhsValueInTermsOfBase
}
}
return false
}
}
/// Compare two measurements of the same `Unit`.
/// - returns: `true` if the measurements can be compared and the `lhs` is less than the `rhs` converted value.
public static func <<LeftHandSideType, RightHandSideType>(lhs: Measurement<LeftHandSideType>, rhs: Measurement<RightHandSideType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value < rhs.value
} else {
if let lhsDimensionalUnit = lhs.unit as? Dimension,
let rhsDimensionalUnit = rhs.unit as? Dimension {
if type(of: lhsDimensionalUnit).baseUnit() == type(of: rhsDimensionalUnit).baseUnit() {
let lhsValueInTermsOfBase = lhsDimensionalUnit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhsDimensionalUnit.converter.baseUnitValue(fromValue: rhs.value)
return lhsValueInTermsOfBase < rhsValueInTermsOfBase
}
}
fatalError("Attempt to compare measurements with non-equal dimensions")
}
}
}
// Implementation note: similar to NSArray, NSDictionary, etc., NSMeasurement's import as an ObjC generic type is suppressed by the importer. Eventually we will need a more general purpose mechanism to correctly import generic types.
#if DEPLOYMENT_RUNTIME_SWIFT
internal typealias MeasurementBridgeType = _ObjectTypeBridgeable
#else
internal typealias MeasurementBridgeType = _ObjectiveCBridgeable
#endif
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : MeasurementBridgeType {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSMeasurement {
return NSMeasurement(doubleValue: value, unit: unit)
}
public static func _forceBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) {
result = Measurement(value: source.doubleValue, unit: source.unit as! UnitType)
}
public static func _conditionallyBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) -> Bool {
if let u = source.unit as? UnitType {
result = Measurement(value: source.doubleValue, unit: u)
return true
} else {
return false
}
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSMeasurement?) -> Measurement {
let u = source!.unit as! UnitType
return Measurement(value: source!.doubleValue, unit: u)
}
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension NSMeasurement : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
#if DEPLOYMENT_RUNTIME_SWIFT
return AnyHashable(Measurement._unconditionallyBridgeFromObjectiveC(self))
#else
return AnyHashable(self as Measurement)
#endif
}
}
// This workaround is required for the time being, because Swift doesn't support covariance for Measurement (26607639)
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension MeasurementFormatter {
public func string<UnitType>(from measurement: Measurement<UnitType>) -> String {
if let result = string(for: measurement) {
return result
} else {
return ""
}
}
}
// @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
// extension Unit : Codable {
// public convenience init(from decoder: Decoder) throws {
// let container = try decoder.singleValueContainer()
// let symbol = try container.decode(String.self)
// self.init(symbol: symbol)
// }
// public func encode(to encoder: Encoder) throws {
// var container = encoder.singleValueContainer()
// try container.encode(self.symbol)
// }
// }
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : Codable {
private enum CodingKeys : Int, CodingKey {
case value
case unit
}
private enum UnitCodingKeys : Int, CodingKey {
case symbol
case converter
}
private enum LinearConverterCodingKeys : Int, CodingKey {
case coefficient
case constant
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let value = try container.decode(Double.self, forKey: .value)
let unitContainer = try container.nestedContainer(keyedBy: UnitCodingKeys.self, forKey: .unit)
let symbol = try unitContainer.decode(String.self, forKey: .symbol)
let unit: UnitType
if UnitType.self is Dimension.Type {
let converterContainer = try unitContainer.nestedContainer(keyedBy: LinearConverterCodingKeys.self, forKey: .converter)
let coefficient = try converterContainer.decode(Double.self, forKey: .coefficient)
let constant = try converterContainer.decode(Double.self, forKey: .constant)
let unitMetaType = (UnitType.self as! Dimension.Type)
unit = (unitMetaType.init(symbol: symbol, converter: UnitConverterLinear(coefficient: coefficient, constant: constant)) as! UnitType)
} else {
unit = UnitType(symbol: symbol)
}
self.init(value: value, unit: unit)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.value, forKey: .value)
var unitContainer = container.nestedContainer(keyedBy: UnitCodingKeys.self, forKey: .unit)
try unitContainer.encode(self.unit.symbol, forKey: .symbol)
if UnitType.self is Dimension.Type {
guard type(of: (self.unit as! Dimension).converter) is UnitConverterLinear.Type else {
preconditionFailure("Cannot encode a Measurement whose UnitType has a non-linear unit converter.")
}
let converter = (self.unit as! Dimension).converter as! UnitConverterLinear
var converterContainer = unitContainer.nestedContainer(keyedBy: LinearConverterCodingKeys.self, forKey: .converter)
try converterContainer.encode(converter.coefficient, forKey: .coefficient)
try converterContainer.encode(converter.constant, forKey: .constant)
}
}
}
| apache-2.0 | 891a3786aa72f6ca6046fdd8cc65be90 | 44.666667 | 280 | 0.66091 | 4.678049 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/WordPressTest/PostBuilder.swift | 1 | 6148 | import Foundation
@testable import WordPress
/// Builds a Post
///
/// Defaults to creating a post in a self-hosted site.
class PostBuilder {
private let post: Post
init(_ context: NSManagedObjectContext = PostBuilder.setUpInMemoryManagedObjectContext(), blog: Blog? = nil) {
post = NSEntityDescription.insertNewObject(forEntityName: Post.entityName(), into: context) as! Post
// Non-null Core Data properties
post.blog = blog ?? BlogBuilder(context).build()
}
private static func buildPost(context: NSManagedObjectContext) -> Post {
let blog = NSEntityDescription.insertNewObject(forEntityName: Blog.entityName(), into: context) as! Blog
blog.xmlrpc = "http://example.com/xmlrpc.php"
blog.url = "http://example.com"
blog.username = "test"
blog.password = "test"
let post = NSEntityDescription.insertNewObject(forEntityName: Post.entityName(), into: context) as! Post
post.blog = blog
return post
}
func published() -> PostBuilder {
post.status = .publish
return self
}
func drafted() -> PostBuilder {
post.status = .draft
return self
}
func scheduled() -> PostBuilder {
post.status = .scheduled
return self
}
func trashed() -> PostBuilder {
post.status = .trash
return self
}
func `private`() -> PostBuilder {
post.status = .publishPrivate
return self
}
func pending() -> PostBuilder {
post.status = .pending
return self
}
func revision() -> PostBuilder {
post.setPrimitiveValue(post, forKey: "original")
return self
}
func autosaved() -> PostBuilder {
post.autosaveTitle = "a"
post.autosaveExcerpt = "b"
post.autosaveContent = "c"
post.autosaveModifiedDate = Date()
post.autosaveIdentifier = 1
return self
}
func withImage() -> PostBuilder {
post.pathForDisplayImage = "https://localhost/image.png"
return self
}
func with(status: BasePost.Status) -> PostBuilder {
post.status = status
return self
}
func with(pathForDisplayImage: String) -> PostBuilder {
post.pathForDisplayImage = pathForDisplayImage
return self
}
func with(title: String) -> PostBuilder {
post.postTitle = title
return self
}
func with(snippet: String) -> PostBuilder {
post.content = snippet
return self
}
func with(dateCreated: Date) -> PostBuilder {
post.dateCreated = dateCreated
return self
}
func with(dateModified: Date) -> PostBuilder {
post.dateModified = dateModified
return self
}
func with(author: String) -> PostBuilder {
post.author = author
return self
}
func with(userName: String) -> PostBuilder {
post.blog.username = userName
return self
}
func with(password: String) -> PostBuilder {
post.blog.password = password
return self
}
func with(remoteStatus: AbstractPostRemoteStatus) -> PostBuilder {
post.remoteStatus = remoteStatus
return self
}
func with(statusAfterSync: BasePost.Status?) -> PostBuilder {
post.statusAfterSync = statusAfterSync
return self
}
func with(image: String, status: MediaRemoteStatus? = nil, autoUploadFailureCount: Int = 0) -> PostBuilder {
guard let context = post.managedObjectContext else {
return self
}
guard let media = NSEntityDescription.insertNewObject(forEntityName: Media.entityName(), into: context) as? Media else {
return self
}
media.localURL = image
media.localThumbnailURL = "thumb-\(image)"
media.blog = post.blog
media.autoUploadFailureCount = NSNumber(value: autoUploadFailureCount)
if let status = status {
media.remoteStatus = status
}
media.addPostsObject(post)
post.addMediaObject(media)
return self
}
func with(media: [Media]) -> PostBuilder {
for item in media {
item.blog = post.blog
}
post.media = Set(media)
return self
}
func with(autoUploadAttemptsCount: Int) -> PostBuilder {
post.autoUploadAttemptsCount = NSNumber(value: autoUploadAttemptsCount)
return self
}
func `is`(sticked: Bool) -> PostBuilder {
post.isStickyPost = sticked
return self
}
func supportsWPComAPI() -> PostBuilder {
post.blog.supportsWPComAPI()
return self
}
func confirmedAutoUpload() -> PostBuilder {
post.shouldAttemptAutoUpload = true
return self
}
/// Sets a random postID to emulate that self exists in the server.
func withRemote() -> PostBuilder {
post.postID = NSNumber(value: arc4random_uniform(UINT32_MAX))
return self
}
func cancelledAutoUpload() -> PostBuilder {
post.shouldAttemptAutoUpload = false
return self
}
func build() -> Post {
// Todo: Enable this assertion once we can ensure that the post's MOC isn't being deallocated after the `PostBuilder` is
// assert(post.managedObjectContext != nil)
return post
}
static func setUpInMemoryManagedObjectContext() -> NSManagedObjectContext {
let managedObjectModel = NSManagedObjectModel.mergedModel(from: [Bundle.main])!
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
do {
try persistentStoreCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil)
} catch {
print("Adding in-memory persistent store failed")
}
let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator
return managedObjectContext
}
}
| gpl-2.0 | fd1ad16643babc1225e7aac9c276ebe4 | 26.693694 | 137 | 0.630937 | 5.076796 | false | false | false | false |
daaavid/TIY-Assignments | 37--Venue-Menu/Venue-Menu/Venue-Menu/SearchTableViewController.swift | 1 | 4835 | //
// SearchTableViewController.swift
// Venue-Menu
//
// Created by david on 11/26/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import QuartzCore
import CoreData
protocol APIControllerProtocol
{
func venuesWereFound(venues: [NSDictionary])
}
class SearchTableViewController: UITableViewController, APIControllerProtocol, UISearchBarDelegate
{
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var segmentedControl: UISegmentedControl!
var searchResults = [NSManagedObject]()
var location: Location!
let locationManager = LocationManager()
var apiController: APIController!
override func viewDidLoad()
{
super.viewDidLoad()
segmentedControl.hidden = true
searchBar.delegate = self
location = USER_LOCATION
// locationManager.delegate = self
// locationManager.configureLocationManager()
apiController = APIController(delegate: self)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return searchResults.count
}
func locationWasFound(location: Location)
{
self.location = location
}
@IBAction func segmentedControlValueChanged(sender: UISegmentedControl)
{
search()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar)
{
search()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar)
{
searchBar.resignFirstResponder()
}
func search()
{
if let _ = location
{
print("searching")
print(location)
if let term = searchBar.text
{
switch segmentedControl.selectedSegmentIndex
{
case 0: apiController.search(term, location: location, searchOption: "explore")
case 1: apiController.search(term, location: location, searchOption: "search")
default: print("segmentedControl unknown segmentIndex")
}
}
searchBar.resignFirstResponder()
}
}
func venuesWereFound(venues: [NSDictionary])
{
print(venues.count)
dispatch_async(dispatch_get_main_queue(), {
for eachVenueDict in venues
{
if let venue = Venue.venueWithJSON(eachVenueDict)
{
self.searchResults.append(venue)
}
}
self.apiController.cancelSearch()
self.tableView.reloadData()
})
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SearchCell", forIndexPath: indexPath) as! VenueCell
let venue = searchResults[indexPath.row]
cell.venueLabel.text = venue.valueForKey("name") as? String
cell.typeLabel.text = venue.valueForKey("type") as? String
cell.addressLabel.text = venue.valueForKey("address") as? String
if let imageURL = venue.valueForKey("icon") as? String
{
let imageView = makeCellImage(imageURL)
cell.addSubview(imageView)
}
return cell
}
func makeCellImage(iconURL: String) -> UIImageView
{
let imageView = UIImageView()
imageView.frame = CGRect(x: 8, y: 8, width: 64, height: 64)
imageView.downloadedFrom(iconURL, contentMode: .ScaleToFill)
imageView.round()
imageView.backgroundColor = UIColor(hue:0.625, saturation:0.8, brightness:0.886, alpha:1)
return imageView
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let mainVC = navigationController?.viewControllers[0] as! MainViewController
let detailVC = storyboard?.instantiateViewControllerWithIdentifier("detailVC") as! DetailViewController
let chosenVenue = searchResults[indexPath.row]
detailVC.venue = chosenVenue
detailVC.location = USER_LOCATION
detailVC.delegate = mainVC
navigationController?.pushViewController(detailVC, animated: true)
}
// override func viewDidDisappear(animated: Bool)
// {
// let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
// for venue in searchResults
// {
// managedObjectContext.deleteObject(venue)
// }
// }
}
| cc0-1.0 | a10c267a2025bf3645e8ff34411f2aaa | 29.402516 | 118 | 0.628051 | 5.493182 | false | false | false | false |
paulofaria/SwiftHTTPServer | Example Server/Responders/UserResponder.swift | 3 | 2976 | // UserResponder.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
struct User {
let name: String
}
struct Collection<T> {
var elements: [String: T] = [:]
private var currentId = 0
private mutating func getNewId() -> String {
let id = "\(currentId)"
currentId++
return id
}
mutating func add(element element: T) {
let id = getNewId()
elements[id] = element
}
func get(id id: String) -> T? {
return elements[id]
}
mutating func update(id id: String, element: T) {
elements[id] = element
}
mutating func delete(id id: String) {
elements.removeValueForKey(id)
}
}
final class UserResponder : ResourcefulResponder {
var users = Collection<User>()
func index(request: HTTPRequest) throws -> HTTPResponse {
return HTTPResponse(text: "\(users.elements)")
}
func create(request: HTTPRequest) throws -> HTTPResponse {
let name = try request.getParameter("name")
let user = User(name: name)
users.add(element: user)
return HTTPResponse(status: .Created)
}
func show(request: HTTPRequest) throws -> HTTPResponse {
let id = try request.getParameter("id")
let user = users.get(id: id)
return HTTPResponse(text: "\(user)")
}
func update(request: HTTPRequest) throws -> HTTPResponse {
let id = try request.getParameter("id")
let name = try request.getParameter("name")
let user = User(name: name)
users.update(id: id, element: user)
return HTTPResponse(status: .NoContent)
}
func destroy(request: HTTPRequest) throws -> HTTPResponse {
let id = try request.getParameter("id")
users.delete(id: id)
return HTTPResponse(status: .NoContent)
}
} | mit | bcfd187e7240cbe989aa189ecdd213e7 | 23.808333 | 81 | 0.65289 | 4.44843 | false | false | false | false |
lanjing99/RxSwiftDemo | 08-transforming-operators-in-practice/challenges/GitFeed/GitFeed/ActivityController.swift | 1 | 6439 | /*
* Copyright (c) 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 UIKit
import RxSwift
import RxCocoa
import Kingfisher
func cachedFileURL(_ fileName: String) -> URL {
return FileManager.default
.urls(for: .cachesDirectory, in: .allDomainsMask)
.first!
.appendingPathComponent(fileName)
}
class ActivityController: UITableViewController {
private let repo = "ReactiveX/RxSwift"
fileprivate let events = Variable<[Event]>([])
fileprivate let bag = DisposeBag()
private let eventsFileURL = cachedFileURL("events.plist")
private let modifiedFileURL = cachedFileURL("modified.txt")
fileprivate let lastModified = Variable<NSString?>(nil)
override func viewDidLoad() {
super.viewDidLoad()
title = repo
self.refreshControl = UIRefreshControl()
let refreshControl = self.refreshControl!
refreshControl.backgroundColor = UIColor(white: 0.98, alpha: 1.0)
refreshControl.tintColor = UIColor.darkGray
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
let eventsArray = (NSArray(contentsOf: eventsFileURL)
as? [[String: Any]]) ?? []
events.value = eventsArray.flatMap(Event.init)
lastModified.value = try? NSString(contentsOf: modifiedFileURL, usedEncoding: nil)
refresh()
}
func refresh() {
DispatchQueue.global(qos: .background).async { [weak self] in
guard let strongSelf = self else { return }
strongSelf.fetchEvents(repo: strongSelf.repo)
}
}
func fetchEvents(repo: String) {
//let response = Observable.from([repo])
let response = Observable.from(["https://api.github.com/search/repositories?q=language:swift&per_page=5"])
.map { urlString -> URL in
return URL(string: urlString)!
}
.flatMap { url -> Observable<Any> in
let request = URLRequest(url: url)
return URLSession.shared.rx.json(request: request)
}
.flatMap { response -> Observable<String> in
guard let response = response as? [String: Any],
let items = response["items"] as? [[String: Any]] else {
return Observable.never()
}
return Observable.from(items.map { $0["full_name"] as! String })
}
.map { urlString -> URL in
return URL(string: "https://api.github.com/repos/\(urlString)/events")!
}
.map { [weak self] url -> URLRequest in
var request = URLRequest(url: url)
if let modifiedHeader = self?.lastModified.value {
request.addValue(modifiedHeader as String,
forHTTPHeaderField: "Last-Modified")
}
return request
}
.flatMap { request -> Observable<(HTTPURLResponse, Data)> in
return URLSession.shared.rx.response(request: request)
}
.shareReplay(1)
response
.filter { response, _ in
return 200..<300 ~= response.statusCode
}
.map { _, data -> [[String: Any]] in
guard let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []),
let result = jsonObject as? [[String: Any]] else {
return []
}
return result
}
.filter { objects in
return objects.count > 0
}
.map { objects in
return objects.flatMap(Event.init)
}
.subscribe(onNext: { [weak self] newEvents in
self?.processEvents(newEvents)
})
.addDisposableTo(bag)
response
.filter {response, _ in
return 200..<400 ~= response.statusCode
}
.flatMap { response, _ -> Observable<NSString> in
guard let value = response.allHeaderFields["Last-Modified"] as? NSString else {
return Observable.never()
}
return Observable.just(value)
}
.subscribe(onNext: { [weak self] modifiedHeader in
guard let strongSelf = self else { return }
strongSelf.lastModified.value = modifiedHeader
try? modifiedHeader.write(to: strongSelf.modifiedFileURL, atomically: true,
encoding: String.Encoding.utf8.rawValue)
})
.addDisposableTo(bag)
}
func processEvents(_ newEvents: [Event]) {
var updatedEvents = newEvents + events.value
if updatedEvents.count > 50 {
updatedEvents = Array<Event>(updatedEvents.prefix(upTo: 50))
}
events.value = updatedEvents
DispatchQueue.main.async { [weak self] in
self?.tableView.reloadData()
self?.refreshControl?.endRefreshing()
}
let eventsArray = updatedEvents.map{ $0.dictionary } as NSArray
eventsArray.write(to: eventsFileURL, atomically: true)
}
// MARK: - Table Data Source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return events.value.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let event = events.value[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = event.name
cell.detailTextLabel?.text = event.repo + ", " + event.action.replacingOccurrences(of: "Event", with: "").lowercased()
cell.imageView?.kf.setImage(with: event.imageUrl, placeholder: UIImage(named: "blank-avatar"))
return cell
}
}
| mit | 9f7c557b89d23b7ae03f50b1d82f8d36 | 34.772222 | 122 | 0.669669 | 4.540903 | false | false | false | false |
vbudhram/firefox-ios | Shared/Extensions/UIImageExtensions.swift | 2 | 3370 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import SDWebImage
private let imageLock = NSLock()
extension CGRect {
public init(width: CGFloat, height: CGFloat) {
self.init(x: 0, y: 0, width: width, height: height)
}
public init(size: CGSize) {
self.init(origin: .zero, size: size)
}
}
extension Data {
public var isGIF : Bool {
return [0x47, 0x49, 0x46].elementsEqual(prefix(3))
}
}
extension UIImage {
/// Despite docs that say otherwise, UIImage(data: NSData) isn't thread-safe (see bug 1223132).
/// As a workaround, synchronize access to this initializer.
/// This fix requires that you *always* use this over UIImage(data: NSData)!
public static func imageFromDataThreadSafe(_ data: Data) -> UIImage? {
imageLock.lock()
let image = UIImage(data: data)
imageLock.unlock()
return image
}
/// Generates a UIImage from GIF data by calling out to SDWebImage. The latter in turn uses UIImage(data: NSData)
/// in certain cases so we have to synchronize calls (see bug 1223132).
public static func imageFromGIFDataThreadSafe(_ data: Data) -> UIImage? {
imageLock.lock()
let image = UIImage.sd_animatedGIF(with: data)
imageLock.unlock()
return image
}
public static func createWithColor(_ size: CGSize, color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let context = UIGraphicsGetCurrentContext()
let rect = CGRect(size: size)
color.setFill()
context!.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
public func createScaled(_ size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
draw(in: CGRect(size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
public static func templateImageNamed(_ name: String) -> UIImage? {
return UIImage(named: name)?.withRenderingMode(.alwaysTemplate)
}
// TESTING ONLY: not for use in release/production code.
// PNG comparison can return false negatives, be very careful using for non-equal comparison.
// PNG comparison requires UIImages to be constructed the same way in order for the metadata block to match,
// this function ensures that.
//
// This can be verified with this code:
// let image = UIImage(named: "fxLogo")!
// let data = UIImagePNGRepresentation(image)!
// assert(data != UIImagePNGRepresentation(UIImage(data: data)!))
@available(*, deprecated, message: "use only in testing code")
public func isStrictlyEqual(to other: UIImage) -> Bool {
// Must use same constructor for PNG metadata block to be the same.
let imageA = UIImage(data: UIImagePNGRepresentation(self)!)!
let imageB = UIImage(data: UIImagePNGRepresentation(other)!)!
let dataA = UIImagePNGRepresentation(imageA)!
let dataB = UIImagePNGRepresentation(imageB)!
return dataA == dataB
}
}
| mpl-2.0 | 3d29792366c501b93f75aa8cfa3db813 | 37.735632 | 117 | 0.670623 | 4.648276 | false | false | false | false |
iNoles/NolesFootball | NolesFootball.iOS/Noles Football/DemandViewController.swift | 1 | 3098 | //
// DemandViewController.swift
// Noles Football
//
// Created by Jonathan Steele on 5/6/16.
// Copyright © 2016 Jonathan Steele. All rights reserved.
//
import UIKit
import AVKit
import AVFoundation
class DemandViewController: UITableViewController {
private var list = [Demand]()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
let format = DateUtils(format: "yyyy-MM-dd'T'HH:mm:ss'Z'", isGMTWithLocale: true)
let dateFormatter = DateUtils(format: "EEE, MMM d, yyyy h:mm a")
parseXML(withURL: "http://www.seminoles.com/XML/services/v2/onDemand.v2.dbml?DB_OEM_ID=32900&maxrows=10&start=0&spid=157113", query: "//clip", callback: { [unowned self] childNode in
var demand = Demand()
childNode.forEach { nodes in
if nodes.tagName == "short_description" {
demand.description = nodes.firstChild?.content
}
if nodes.tagName == "start_date" {
let date = format.dateFromString(string: nodes.firstChild?.content)
demand.date = dateFormatter.stringFromDate(date: date!)
}
if nodes.tagName == "external_m3u8" {
demand.link = nodes.firstChild?.content
}
}
self.list.append(demand)
}, deferCallback: tableView.reloadData)
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in _: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
// Return the number of rows in the section.
return list.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "OnDemand", for: indexPath)
// Configure the cell...
let demand = list[indexPath.row]
cell.textLabel?.text = demand.description
cell.detailTextLabel?.text = demand.date
return cell
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender _: Any?) {
guard let int = tableView.indexPathForSelectedRow?.row else {
assertionFailure("Couldn't get TableView Selected Row")
return
}
if let url = URL(string: list[int].link!) {
let destination = segue.destination as! AVPlayerViewController
destination.player = AVPlayer(url: url)
}
}
}
| gpl-3.0 | 489887102dcb70f78b589511fc80eda5 | 34.597701 | 190 | 0.627058 | 4.757296 | false | false | false | false |
boolkybear/WSDL-Parser | WSDLParser/MessagesController.swift | 1 | 2261 | //
// MessagesController.swift
// WSDLParser
//
// Created by Boolky Bear on 25/2/15.
// Copyright (c) 2015 ByBDesigns. All rights reserved.
//
import Cocoa
class MessagesController: NSViewController {
var parser: WSDLParserDelegate?
var operation: WSDLParserDelegate.Operation?
@IBOutlet var inputMessageLabel: NSTextFieldCell!
@IBOutlet var outputMessageLabel: NSTextFieldCell!
class MessageWrapper: NSObject {
let message: WSDLParserDelegate.Message
init(message: WSDLParserDelegate.Message)
{
self.message = message
super.init()
}
}
enum SegueIdentifier: String
{
case MessageToTypesShow = "TypesShowSegue"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
self.inputMessageLabel?.stringValue = self.operation?.input?.message ?? ""
self.outputMessageLabel?.stringValue = self.operation?.output?.message ?? ""
}
func setDataOrigin(parser: WSDLParserDelegate, operation: WSDLParserDelegate.Operation)
{
self.parser = parser
self.operation = operation
let operationName = operation.name ?? "UNNAMED"
self.title = "Messages of \(operationName)"
self.inputMessageLabel?.setValue(self.operation?.input?.message)
self.outputMessageLabel?.setValue(self.operation?.output?.message)
}
override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) {
if let identifier = SegueIdentifier(rawValue: segue.identifier ?? "")
{
switch identifier
{
case .MessageToTypesShow:
if let messageWrapper = sender as? MessageWrapper
{
let controller = segue.destinationController as TypesViewController
controller.setDataOrigin(self.parser!, message: messageWrapper.message)
}
}
}
}
}
// Actions
extension MessagesController
{
func showMessageNamed(name: String?)
{
if let message = self.parser?.messageNamed(name ?? "")
{
self.performSegueWithIdentifier(SegueIdentifier.MessageToTypesShow.rawValue, sender: MessageWrapper(message: message))
}
}
@IBAction func inputButtonClicked(sender: AnyObject) {
self.showMessageNamed(self.operation?.input?.message)
}
@IBAction func outputButtonClicked(sender: AnyObject) {
self.showMessageNamed(self.operation?.output?.message)
}
} | mit | 63a8d80f81be8cdeb0e33195b8c7b378 | 24.133333 | 121 | 0.733304 | 4.030303 | false | false | false | false |
Moya/Moya | Tests/MoyaTests/MoyaProvider+ReactiveSpec.swift | 1 | 7953 | import Quick
import Nimble
import ReactiveSwift
import OHHTTPStubs
#if canImport(OHHTTPStubsSwift)
import OHHTTPStubsSwift
#endif
@testable import Moya
@testable import ReactiveMoya
final class MoyaProviderReactiveSpec: QuickSpec {
override func spec() {
describe("failing") {
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider<GitHub>(endpointClosure: failureEndpointClosure, stubClosure: MoyaProvider.immediatelyStub)
}
it("returns the correct error message") {
var receivedError: MoyaError?
waitUntil { done in
provider.reactive.request(.zen).startWithFailed { error in
receivedError = error
done()
}
}
switch receivedError {
case .some(.underlying(let error, _)):
expect(error.localizedDescription) == "Houston, we have a problem"
default:
fail("expected an Underlying error that Houston has a problem")
}
}
it("returns an error") {
var errored = false
let target: GitHub = .zen
provider.reactive.request(target).startWithFailed { _ in
errored = true
}
expect(errored).to(beTruthy())
}
}
describe("provider with SignalProducer") {
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider<GitHub>(stubClosure: MoyaProvider.immediatelyStub)
}
it("returns a Response object") {
var called = false
provider.reactive.request(.zen).startWithResult { _ in
called = true
}
expect(called).to(beTruthy())
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .zen
provider.reactive.request(target).startWithResult { result in
if case .success(let response) = result {
message = String(data: response.data, encoding: .utf8)
}
}
let sampleString = String(data: target.sampleData, encoding: .utf8)
expect(message!).to(equal(sampleString))
}
it("returns correct data for user profile request") {
var receivedResponse: NSDictionary?
let target: GitHub = .userProfile("ashfurrow")
provider.reactive.request(target).startWithResult { result in
if case .success(let response) = result {
receivedResponse = try! JSONSerialization.jsonObject(with: response.data, options: []) as? NSDictionary
}
}
let sampleData = target.sampleData
let sampleResponse = try! JSONSerialization.jsonObject(with: sampleData, options: []) as! NSDictionary
expect(receivedResponse).toNot(beNil())
expect(receivedResponse) == sampleResponse
}
}
describe("provider with inflight tracking") {
var provider: MoyaProvider<GitHub>!
beforeEach {
HTTPStubs.stubRequests(passingTest: {$0.url!.path == "/zen"}, withStubResponse: { _ in
return HTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil)
})
provider = MoyaProvider<GitHub>(trackInflights: true)
}
it("returns identical signalproducers for inflight requests") {
let target: GitHub = .zen
let signalProducer1: SignalProducer<Moya.Response, MoyaError> = provider.reactive.request(target)
let signalProducer2: SignalProducer<Moya.Response, MoyaError> = provider.reactive.request(target)
expect(provider.inflightRequests.keys.count).to( equal(0) )
var receivedResponse: Moya.Response!
signalProducer1.startWithResult { result in
if case .success(let response) = result {
receivedResponse = response
expect(provider.inflightRequests.count).to( equal(1) )
}
}
signalProducer2.startWithResult { result in
if case .success(let response) = result {
expect(receivedResponse).toNot( beNil() )
expect(receivedResponse).to( beIdenticalToResponse(response) )
expect(provider.inflightRequests.count).to( equal(1) )
}
}
// Allow for network request to complete
expect(provider.inflightRequests.count).toEventually( equal(0) )
}
}
describe("a provider with progress tracking") {
var provider: MoyaProvider<GitHubUserContent>!
beforeEach {
//delete downloaded filed before each test
let directoryURLs = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
let file = directoryURLs.first!.appendingPathComponent("logo_github.png")
try? FileManager.default.removeItem(at: file)
//`responseTime(-4)` equals to 1000 bytes at a time. The sample data is 4000 bytes.
HTTPStubs.stubRequests(passingTest: {$0.url!.path.hasSuffix("logo_github.png")}, withStubResponse: { _ in
return HTTPStubsResponse(data: GitHubUserContent.downloadMoyaWebContent("logo_github.png").sampleData, statusCode: 200, headers: nil).responseTime(-4)
})
provider = MoyaProvider<GitHubUserContent>()
}
it("tracks progress of request") {
let target: GitHubUserContent = .downloadMoyaWebContent("logo_github.png")
let expectedNextProgressValues = [0.25, 0.5, 0.75, 1.0, 1.0]
let expectedNextResponseCount = 1
let expectedFailedEventsCount = 0
let expectedInterruptedEventsCount = 0
let expectedCompletedEventsCount = 1
let timeout = DispatchTimeInterval.seconds(5)
var nextProgressValues: [Double] = []
var nextResponseCount = 0
var failedEventsCount = 0
var interruptedEventsCount = 0
var completedEventsCount = 0
_ = provider.reactive.requestWithProgress(target)
.start({ event in
switch event {
case let .value(element):
nextProgressValues.append(element.progress)
if element.response != nil { nextResponseCount += 1 }
case .failed: failedEventsCount += 1
case .completed: completedEventsCount += 1
case .interrupted: interruptedEventsCount += 1
}
})
expect(completedEventsCount).toEventually(equal(expectedCompletedEventsCount), timeout: timeout)
expect(failedEventsCount).toEventually(equal(expectedFailedEventsCount), timeout: timeout)
expect(interruptedEventsCount).toEventually(equal(expectedInterruptedEventsCount), timeout: timeout)
expect(nextResponseCount).toEventually(equal(expectedNextResponseCount), timeout: timeout)
expect(nextProgressValues).toEventually(equal(expectedNextProgressValues), timeout: timeout)
}
}
}
}
| mit | 91c52fbcd83fe40494ce3f0183642d19 | 40.421875 | 170 | 0.556268 | 5.952844 | false | false | false | false |
soapyigu/LeetCode_Swift | LinkedList/RotateList.swift | 1 | 1190 | /**
* Question Link: https://leetcode.com/problems/rotate-list/
* Primary idea: Runner Tech
* Time Complexity: O(n), Space Complexity: O(1)
*
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class RotateList {
func rotateRight(head: ListNode?, _ k: Int) -> ListNode? {
if head == nil {
return head
}
var prev = head
var post = head
let len = _getLength(head)
var k = k % len
while k > 0 {
post = post!.next
k -= 1
}
while post!.next != nil {
prev = prev!.next
post = post!.next
}
post!.next = head
post = prev!.next
prev!.next = nil
return post
}
private func _getLength(head: ListNode?) -> Int {
var len = 0
var node = head
while node != nil {
len += 1
node = node!.next
}
return len
}
} | mit | 2dd2bd683abc4ba297aba61a434444d0 | 20.267857 | 62 | 0.452941 | 4.219858 | false | false | false | false |
alexdoloz/Gridy | Example/Gridy/ExampleViewController.swift | 1 | 4011 | import UIKit
import Gridy
class ExampleViewController: UIViewController {
@IBOutlet weak var widthLabel: UILabel!
@IBOutlet weak var heightLabel: UILabel!
@IBOutlet weak var spaceXLabel: UILabel!
@IBOutlet weak var spaceYLabel: UILabel!
@IBOutlet weak var anchorPointYLabel: UILabel!
@IBOutlet weak var anchorPointXLabel: UILabel!
@IBOutlet weak var anchorCellXLabel: UILabel!
@IBOutlet weak var anchorCellYLabel: UILabel!
@IBOutlet weak var hideShowButton: UIButton!
@IBOutlet weak var menuView: UIVisualEffectView!
@IBOutlet weak var containerView: UIView!
var cellViews: [Cell: UIView] = [:]
let cellsInRow = 10
var grid: Grid4 = Grid4()
// MARK: Controls
@IBOutlet weak var widthSlider: UISlider!
@IBOutlet weak var heightSlider: UISlider!
@IBOutlet weak var spaceXSlider: UISlider!
@IBOutlet weak var spaceYSlider: UISlider!
@IBOutlet weak var anchorPointXSlider: UISlider!
@IBOutlet weak var anchorPointYSlider: UISlider!
@IBOutlet weak var anchorCellXStepper: UIStepper!
@IBOutlet weak var anchorCellYStepper: UIStepper!
@IBOutlet weak var anchorModeSegmentedControl: UISegmentedControl!
@IBOutlet weak var menuConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupActions()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
updateGrid()
}
func setupActions() {
let action = #selector(self.updateGrid)
[
widthSlider,
heightSlider,
spaceXSlider,
spaceYSlider,
anchorPointXSlider,
anchorPointYSlider,
anchorCellXStepper,
anchorCellYStepper,
anchorModeSegmentedControl
].forEach { control in
control.addTarget(self, action: action, forControlEvents: .ValueChanged)
}
}
func updateGrid() {
grid.width = CGFloat(widthSlider.value)
grid.height = CGFloat(heightSlider.value)
grid.spaceX = CGFloat(spaceXSlider.value)
grid.spaceY = CGFloat(spaceYSlider.value)
grid.anchorPoint = CGPoint(x: CGFloat(anchorPointXSlider.value), y: CGFloat(anchorPointYSlider.value))
grid.anchorCell = Cell(x: Int(anchorCellXStepper.value), y: Int(anchorCellYStepper.value))
grid.anchorMode = Grid4.AnchorMode(rawValue: anchorModeSegmentedControl.selectedSegmentIndex)!
updateUI()
}
func updateUI() {
for x in 0..<cellsInRow {
for y in 0..<cellsInRow {
let cell = Cell(x: x, y: y)
let cellView = cellViews[cell]!
let newFrame = grid.rectForCell(cell)
UIView.animateWithDuration(0.25) {
cellView.frame = newFrame
}
}
}
}
func setupUI() {
for x in 0..<cellsInRow {
for y in 0..<cellsInRow {
let cell = Cell(x: x, y: y)
let cellView = UIView()
cellView.backgroundColor = .yellowColor()
containerView.addSubview(cellView)
cellViews[cell] = cellView
}
}
}
@IBAction func hideShowPressed(sender: AnyObject) {
let wasHidden = menuView.frame.maxY > view.bounds.maxY
let hidden = !wasHidden
let newTitle = hidden ? "Show" : "Hide"
let newConstant = hidden ? -(menuView.frame.height - 40) : 0.0
menuConstraint.constant = newConstant
UIView.performWithoutAnimation {
self.hideShowButton.setTitle(newTitle, forState: .Normal)
}
UIView.animateWithDuration(0.25) {
self.view.layoutIfNeeded()
}
}
}
| mit | 414da7243ae3be25abc7cf8fe1cd6f44 | 27.246479 | 110 | 0.595861 | 5.01375 | false | false | false | false |
kylef/JSONWebToken.swift | Sources/JWT/Encode.swift | 1 | 1420 | import Foundation
/*** Encode a set of claims
- parameter claims: The set of claims
- parameter algorithm: The algorithm to sign the payload with
- returns: The JSON web token as a String
*/
public func encode(claims: ClaimSet, algorithm: Algorithm, headers: [String: String]? = nil) -> String {
let encoder = CompactJSONEncoder()
var headers = headers ?? [:]
if !headers.keys.contains("typ") {
headers["typ"] = "JWT"
}
headers["alg"] = algorithm.description
let header = try! encoder.encodeString(headers)
let payload = encoder.encodeString(claims.claims)!
let signingInput = "\(header).\(payload)"
let signature = base64encode(algorithm.algorithm.sign(signingInput.data(using: .utf8)!))
return "\(signingInput).\(signature)"
}
/*** Encode a dictionary of claims
- parameter claims: The dictionary of claims
- parameter algorithm: The algorithm to sign the payload with
- returns: The JSON web token as a String
*/
public func encode(claims: [String: Any], algorithm: Algorithm, headers: [String: String]? = nil) -> String {
return encode(claims: ClaimSet(claims: claims), algorithm: algorithm, headers: headers)
}
/// Encode a set of claims using the builder pattern
public func encode(_ algorithm: Algorithm, closure: ((ClaimSetBuilder) -> Void)) -> String {
let builder = ClaimSetBuilder()
closure(builder)
return encode(claims: builder.claims, algorithm: algorithm)
}
| bsd-2-clause | b61d81e72203a49293d1e8383adedf8d | 34.5 | 109 | 0.71831 | 4.104046 | false | false | false | false |
MrZoidberg/metapp | metapp/metapp/MACachedPhotoRequestor.swift | 1 | 1404 | //
// MACachedPhotoRequestor.swift
// metapp
//
// Created by Mykhaylo Merkulov on 11/1/16.
// Copyright © 2016 ZoidSoft. All rights reserved.
//
import UIKit
import Photos
import XCGLogger
protocol MAPhotoRequestor {
func requestImage(_ imageId: String, _ imageSize: CGSize, _ usingBlock: @escaping (UIImage) -> Void)
func stopCachingImagesForAllAssets()
}
final class MACachedPhotoRequestor: PHCachingImageManager, MAPhotoRequestor {
let log: XCGLogger?
init(log: XCGLogger?) {
self.log = log
}
func requestImage(_ imageId: String, _ imageSize: CGSize, _ usingBlock: @escaping (UIImage) -> Void) {
let fetchOptions = PHFetchOptions()
fetchOptions.wantsIncrementalChangeDetails = false
log?.debug("Requesting image for asset id: \(imageId)")
let fetchResults = PHAsset.fetchAssets(withLocalIdentifiers: [imageId], options: fetchOptions)
guard let asset = fetchResults.firstObject else {
return
}
let options = PHImageRequestOptions()
options.isNetworkAccessAllowed = true
options.isSynchronous = false
options.deliveryMode = .opportunistic
self.requestImage(for: asset, targetSize: imageSize, contentMode: .aspectFit, options: options)
{ result, info in
usingBlock(result!)
}
}
}
| mpl-2.0 | 1e2bbea4c4df78c69f4a2aaa3dbbcd1d | 28.851064 | 106 | 0.655738 | 4.871528 | false | false | false | false |
vknabel/EasyInject | Sources/EasyInject/GlobalInjector.swift | 1 | 1682 | /// Wraps a given `MutableInjector` in order to add reference semantics.
public final class GlobalInjector<K: ProvidableKey>: InjectorDerivingFromMutableInjector,
MutableInjector
{
public typealias Key = K
/// The internally used `Injector`.
private var injector: AnyInjector<K>
/**
Initializes `AnyInjector` with a given `Injector`.
- Parameter injector: The `Injector` that shall be wrapped.
*/
public init<I: Injector>(injector: I) where I.Key == Key {
self.injector = AnyInjector(injector: injector)
}
/// Creates a deep copy of `GlobalInjector` with the same contents.
/// Overrides default `InjectorDerivingFromMutableInjector.copy()`.
///
/// - Returns: A new `GlobalInjector`.
public func copy() -> GlobalInjector {
return GlobalInjector(injector: injector.copy())
}
/// Implements `MutableInjector.resolve(key:)`
public func resolve(key: Key) throws -> Providable {
return try injector.resolve(key: key)
}
/// Implements `MutableInjector.provide(key:usingFactory:)`
public func provide(
key: Key, usingFactory factory: @escaping (inout GlobalInjector) throws -> Providable
) {
return self.injector.provide(key: key) { _ in
var this = self
return try factory(&this)
}
}
/// See `MutableInjector.revoke(key:)`.
public func revoke(key: K) {
injector.revoke(key: key)
}
/// Implements `Injector.providedKeys` by passing the internal provided keys.
public var providedKeys: [K] {
return injector.providedKeys
}
}
extension GlobalInjector {
/// Creates a strict global injector.
public convenience init() {
self.init(injector: StrictInjector())
}
}
| mit | edcfd124090354686e142250aa267443 | 28 | 89 | 0.693817 | 4.279898 | false | false | false | false |
Shivol/Swift-CS333 | playgrounds/swift/Swift Standard Library 2.playground/Pages/Processing Sequences and Collections.xcplaygroundpage/Contents.swift | 5 | 4554 | /*:
[Table of Contents](Table%20of%20Contents) | [Previous](@previous) | [Next](@next)
****
# Processing Sequences and Collections
Sequences and collections implement methods such as `map(_:)`, `filter(_:)`, and `reduce(_:_:)` to consume and transform their contents. You can compose these methods together to efficiently implement complex algorithms.
A collection's `filter(_:)` method returns an array containing only the elements that pass the provided test. Let's create a shopping list by filtering out ingredients that have already been purchased.
*/
let shoppingList = sampleIngredients.filter { ingredient in
return !ingredient.purchased
}
visualize(sampleIngredients, shoppingList)
/*:
The `map(_:)` method returns a new array by applying a `transform` to each element in a collection. For example, the following code multiplies the quantity of the ingredient by the cost of the ingredient to find the total cost for each ingredient.
*/
let totalPrices = shoppingList.map { ingredient in
return ingredient.quantity * ingredient.price
}
visualize(shoppingList, totalPrices)
/*:
You can use the `reduce(_:_:)` method to combine elements of an array into a single value. The `reduce(_:_:)` method takes an initial value to start with and then a closure or function to combine each element in the array with the previous value. The following code takes the total price list and adds them together to compute a final remaining cost:
*/
let sum = totalPrices.reduce(0) { currentPrice, priceToAdd in
return currentPrice + priceToAdd
}
sum
/*:
- Experiment: Try changing the initial value from `0` to another number. How does this affect the final sum?
The `map(_:)`, `filter(_:)`, and `reduce(_:_:)` methods compose naturally, so you can collapse the code above into a single operation. The following code example implements the `remainingCost` function, used by the app to display the remaining cost for a recipe.
*/
func remainingCost(_ list: [Ingredient]) -> Int {
return list.filter { !$0.purchased }
.map { $0.quantity * $0.price }
.reduce(0) { $0 + $1 }
}
let cost = remainingCost(sampleIngredients)
/*:
## Sorting and Searching
Sequences and collections also provide methods to sort their contents or find an element matching specific criteria. Depending on the contents of your collection, you can use simple variations of these methods. For example, you can sort an array of elements that are comparable by default, like numbers or strings, with just the `sorted()` method. The following code creates a new array from the list of total prices, sorted from lowest to highest:
*/
let sortedTotals = totalPrices.sorted()
/*:
To sort an array of a type that doesn't have a defined ordering, the `sorted(by:)` method takes a closure that returns `true` if the first element should be ordered before the second. Let's sort the ingredients by their prices:
*/
let sortedIngredients = sampleIngredients.sorted { $0.price < $1.price }
showIngredients(sortedIngredients)
/*:
- Experiment: Can you reverse the sorting order of the ingredients, so the most expensive ingredient is listed first? How would you sort the list by quantity instead of price?
The methods for finding an element in a collection work the same way. When a collection's elements can be compared for equality (that is, they conform to the `Equatable` protocol), you can pass any value to the collection's `index(of:)` method to find its position in the collection. The following code creates a new array of just the names of the ingredients and then finds the position of rice in the array:
*/
let ingredientNames = sampleIngredients.map { $0.name }
if let i = ingredientNames.index(of: "Rice") {
ingredientNames[i]
}
/*:
Alternatively, you can use a collection's `index(where:)` method to find the position of the first element that passes the provided test. Here's how you can find the first ingredient that has already been purchased:
*/
let purchased: Int? = sampleIngredients.index(where: { $0.purchased })
visualize(sampleIngredients, purchased)
/*:
There are many more generic algorithms in the standard library similar to those above that you can compose together.
- callout(Checkpoint):
At this point you have learned how to process sequences and collections and why value semantics make it easier to reason about the code you write. In the next section, you'll learn how to use ranges to slice into collections.
****
[Table of Contents](Table%20of%20Contents) | [Previous](@previous) | [Next](@next)
*/
| mit | 50d556f73ca8c96f49882a6db0af0a76 | 56.64557 | 448 | 0.755819 | 4.535857 | false | false | false | false |
DragonCherry/HFSwipeView | HFSwipeView/Classes/HFSwipeView+Page.swift | 1 | 1943 | //
// HFSwipeView+Utility.swift
// Pods
//
// Created by DragonCherry on 01/03/2017.
//
//
import UIKit
// MARK: - Page Control
extension HFSwipeView {
internal func moveRealPage(_ realPage: Int, animated: Bool) {
if realPage >= 0 && realPage < realViewCount && realPage == currentRealPage {
print("moveRealPage received same page(\(realPage)) == currentPage(\(currentRealPage))")
return
}
print("[\(self.tag)]: \(realPage)")
let realIndex = IndexPath(item: realPage, section: 0)
if autoAlignEnabled {
let offset = centeredOffsetForIndex(realIndex)
collectionView.setContentOffset(offset, animated: animated)
}
if !circulating {
updateCurrentView(displayIndexUsing(realIndex))
}
}
internal func updateCurrentView(_ displayIndex: IndexPath) {
currentPage = displayIndex.row
currentRealPage = displayIndex.row
if let view = indexViewMapper[currentRealPage] {
dataSource?.swipeView?(self, needUpdateCurrentViewForIndexPath: displayIndex, view: view)
} else {
print("Failed to retrieve current view from indexViewMapper for indexPath: \(displayIndex.row)")
}
}
internal func autoAlign(_ scrollView: UIScrollView, indexPath: IndexPath) {
if autoAlignEnabled {
if !circulating {
let offset = scrollView.contentOffset
if offset.x > 0 && offset.x < scrollView.contentSize.width - frame.size.width {
collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}
} else {
collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}
}
print("[\(self.tag)]: real -> \(indexPath.row)")
}
}
| mit | ac841d3bf781e6ec02dcc344b60249cb | 33.087719 | 108 | 0.599074 | 5.033679 | false | false | false | false |
christiancompton/kube7 | Sources/Application/Application.swift | 1 | 671 | import Foundation
import Kitura
import LoggerAPI
import Configuration
import CloudEnvironment
import Health
public let router = Router()
public let cloudEnv = CloudEnv()
public let projectPath = ConfigurationManager.BasePath.project.path
public var port: Int = 8080
public let health = Health()
public func initialize() throws {
// Configuration
port = cloudEnv.port
// Capabilities
// Services
// Middleware
router.all(middleware: BodyParser())
router.all(middleware: StaticFileServer())
// Endpoints
initializeHealthRoutes()
}
public func run() throws {
Kitura.addHTTPServer(onPort: port, with: router)
Kitura.run()
}
| mit | 3f0218ebf1785a95f3a9028c1317ab54 | 19.333333 | 67 | 0.728763 | 4.414474 | false | true | false | false |
zvonler/PasswordElephant | external/github.com/apple/swift-protobuf/Tests/SwiftProtobufTests/Test_Duration.swift | 7 | 11930 | // Tests/SwiftProtobufTests/Test_Duration.swift - Exercise well-known Duration type
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Duration type includes custom JSON format, some hand-implemented convenience
/// methods, and arithmetic operators.
///
// -----------------------------------------------------------------------------
import XCTest
import SwiftProtobuf
import Foundation
class Test_Duration: XCTestCase, PBTestHelpers {
typealias MessageTestType = Google_Protobuf_Duration
func testJSON_encode() throws {
assertJSONEncode("\"100s\"") { (o: inout MessageTestType) in
o.seconds = 100
o.nanos = 0
}
// Always prints exactly 3, 6, or 9 digits
assertJSONEncode("\"100.100s\"") { (o: inout MessageTestType) in
o.seconds = 100
o.nanos = 100000000
}
assertJSONEncode("\"100.001s\"") { (o: inout MessageTestType) in
o.seconds = 100
o.nanos = 1000000
}
assertJSONEncode("\"100.000100s\"") { (o: inout MessageTestType) in
o.seconds = 100
o.nanos = 100000
}
assertJSONEncode("\"100.000001s\"") { (o: inout MessageTestType) in
o.seconds = 100
o.nanos = 1000
}
assertJSONEncode("\"100.000000100s\"") { (o: inout MessageTestType) in
o.seconds = 100
o.nanos = 100
}
assertJSONEncode("\"100.000000001s\"") { (o: inout MessageTestType) in
o.seconds = 100
o.nanos = 1
}
// Negative durations
assertJSONEncode("\"-100.100s\"") { (o: inout MessageTestType) in
o.seconds = -100
o.nanos = -100000000
}
}
func testJSON_decode() throws {
assertJSONDecodeSucceeds("\"1.000000000s\"") {(o:MessageTestType) in
o.seconds == 1 && o.nanos == 0
}
assertJSONDecodeSucceeds("\"-315576000000.999999999s\"") {(o:MessageTestType) in
o.seconds == -315576000000 && o.nanos == -999999999
}
assertJSONDecodeFails("\"-315576000001s\"")
assertJSONDecodeSucceeds("\"315576000000.999999999s\"") {(o:MessageTestType) in
o.seconds == 315576000000 && o.nanos == 999999999
}
assertJSONDecodeFails("\"315576000001s\"")
assertJSONDecodeFails("\"999999999999999999999.999999999s\"")
assertJSONDecodeFails("\"\"")
assertJSONDecodeFails("100.100s")
assertJSONDecodeFails("\"-100.-100s\"")
assertJSONDecodeFails("\"100.001\"")
assertJSONDecodeFails("\"100.001sXXX\"")
}
func testSerializationFailure() throws {
let maxOutOfRange = Google_Protobuf_Duration(seconds:-315576000001)
XCTAssertThrowsError(try maxOutOfRange.jsonString())
let minInRange = Google_Protobuf_Duration(seconds:-315576000000, nanos: -999999999)
let _ = try minInRange.jsonString() // Assert does not throw
let maxInRange = Google_Protobuf_Duration(seconds:315576000000, nanos: 999999999)
let _ = try maxInRange.jsonString() // Assert does not throw
let minOutOfRange = Google_Protobuf_Duration(seconds:315576000001)
XCTAssertThrowsError(try minOutOfRange.jsonString())
}
// Make sure durations work correctly when stored in a field
func testJSON_durationField() throws {
do {
let valid = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalDuration\": \"1.001s\"}")
XCTAssertEqual(valid.optionalDuration, Google_Protobuf_Duration(seconds: 1, nanos: 1000000))
} catch {
XCTFail("Should have decoded correctly")
}
XCTAssertThrowsError(try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalDuration\": \"-315576000001.000000000s\"}"))
XCTAssertThrowsError(try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalDuration\": \"315576000001.000000000s\"}"))
XCTAssertThrowsError(try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalDuration\": \"1.001\"}"))
}
func testFieldMember() throws {
// Verify behavior when a duration appears as a field on a larger object
let json1 = "{\"optionalDuration\": \"-315576000000.999999999s\"}"
let m1 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: json1)
XCTAssertEqual(m1.optionalDuration.seconds, -315576000000)
XCTAssertEqual(m1.optionalDuration.nanos, -999999999)
let json2 = "{\"repeatedDuration\": [\"1.5s\", \"-1.5s\"]}"
let expected2 = [Google_Protobuf_Duration(seconds:1, nanos:500000000), Google_Protobuf_Duration(seconds:-1, nanos:-500000000)]
let actual2 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: json2)
XCTAssertEqual(actual2.repeatedDuration, expected2)
}
func testTranscode() throws {
let jsonMax = "{\"optionalDuration\": \"315576000000.999999999s\"}"
let parsedMax = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: jsonMax)
XCTAssertEqual(parsedMax.optionalDuration.seconds, 315576000000)
XCTAssertEqual(parsedMax.optionalDuration.nanos, 999999999)
XCTAssertEqual(try parsedMax.serializedData(), Data(bytes:[234, 18, 13, 8, 128, 188, 174, 206, 151, 9, 16, 255, 147, 235, 220, 3]))
let jsonMin = "{\"optionalDuration\": \"-315576000000.999999999s\"}"
let parsedMin = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: jsonMin)
XCTAssertEqual(parsedMin.optionalDuration.seconds, -315576000000)
XCTAssertEqual(parsedMin.optionalDuration.nanos, -999999999)
XCTAssertEqual(try parsedMin.serializedData(), Data(bytes:[234, 18, 22, 8, 128, 196, 209, 177, 232, 246, 255, 255, 255, 1, 16, 129, 236, 148, 163, 252, 255, 255, 255, 255, 1]))
}
func testConformance() throws {
let tooSmall = try ProtobufTestMessages_Proto3_TestAllTypesProto3(serializedData: Data(bytes: [234, 18, 11, 8, 255, 195, 209, 177, 232, 246, 255, 255, 255, 1]))
XCTAssertEqual(tooSmall.optionalDuration.seconds, -315576000001)
XCTAssertEqual(tooSmall.optionalDuration.nanos, 0)
XCTAssertThrowsError(try tooSmall.jsonString())
let tooBig = try ProtobufTestMessages_Proto3_TestAllTypesProto3(serializedData: Data(bytes: [234, 18, 7, 8, 129, 188, 174, 206, 151, 9]))
XCTAssertEqual(tooBig.optionalDuration.seconds, 315576000001)
XCTAssertEqual(tooBig.optionalDuration.nanos, 0)
XCTAssertThrowsError(try tooBig.jsonString())
}
func testBasicArithmetic() throws {
let an2_n2 = Google_Protobuf_Duration(seconds: -2, nanos: -2)
let an1_n1 = Google_Protobuf_Duration(seconds: -1, nanos: -1)
let a0 = Google_Protobuf_Duration()
let a1_1 = Google_Protobuf_Duration(seconds: 1, nanos: 1)
let a2_2 = Google_Protobuf_Duration(seconds: 2, nanos: 2)
let a3_3 = Google_Protobuf_Duration(seconds: 3, nanos: 3)
let a4_4 = Google_Protobuf_Duration(seconds: 4, nanos: 4)
XCTAssertEqual(a1_1, a0 + a1_1)
XCTAssertEqual(a1_1, a1_1 + a0)
XCTAssertEqual(a2_2, a1_1 + a1_1)
XCTAssertEqual(a3_3, a1_1 + a2_2)
XCTAssertEqual(a1_1, a4_4 - a3_3)
XCTAssertEqual(an1_n1, a3_3 - a4_4)
XCTAssertEqual(an1_n1, a3_3 + -a4_4)
XCTAssertEqual(an1_n1, -a1_1)
XCTAssertEqual(a2_2, -an2_n2)
XCTAssertEqual(a2_2, -an2_n2)
}
func testArithmeticNormalizes() throws {
// Addition normalizes the result
XCTAssertEqual(Google_Protobuf_Duration() + Google_Protobuf_Duration(seconds: 0, nanos: 2000000001),
Google_Protobuf_Duration(seconds: 2, nanos: 1))
// Subtraction normalizes the result
XCTAssertEqual(Google_Protobuf_Duration() - Google_Protobuf_Duration(seconds: 0, nanos: 2000000001),
Google_Protobuf_Duration(seconds: -2, nanos: -1))
// Unary minus normalizes the result
XCTAssertEqual(-Google_Protobuf_Duration(seconds: 0, nanos: 2000000001),
Google_Protobuf_Duration(seconds: -2, nanos: -1))
XCTAssertEqual(-Google_Protobuf_Duration(seconds: 0, nanos: -2000000001),
Google_Protobuf_Duration(seconds: 2, nanos: 1))
XCTAssertEqual(-Google_Protobuf_Duration(seconds: 1, nanos: -2000000001),
Google_Protobuf_Duration(seconds: 1, nanos: 1))
XCTAssertEqual(-Google_Protobuf_Duration(seconds: -1, nanos: 2000000001),
Google_Protobuf_Duration(seconds: -1, nanos: -1))
XCTAssertEqual(-Google_Protobuf_Duration(seconds: -1, nanos: -2000000001),
Google_Protobuf_Duration(seconds: 3, nanos: 1))
XCTAssertEqual(-Google_Protobuf_Duration(seconds: 1, nanos: 2000000001),
Google_Protobuf_Duration(seconds: -3, nanos: -1))
}
func testFloatLiteralConvertible() throws {
var a: Google_Protobuf_Duration = 1.5
XCTAssertEqual(a, Google_Protobuf_Duration(seconds: 1, nanos: 500000000))
a = 100.000000001
XCTAssertEqual(a, Google_Protobuf_Duration(seconds: 100, nanos: 1))
a = 1.9999999991
XCTAssertEqual(a, Google_Protobuf_Duration(seconds: 1, nanos: 999999999))
a = 1.9999999999
XCTAssertEqual(a, Google_Protobuf_Duration(seconds: 2, nanos: 0))
var c = ProtobufTestMessages_Proto3_TestAllTypesProto3()
c.optionalDuration = 100.000000001
XCTAssertEqual(Data(bytes: [234, 18, 4, 8, 100, 16, 1]), try c.serializedData())
XCTAssertEqual("{\"optionalDuration\":\"100.000000001s\"}", try c.jsonString())
}
func testInitializationByTimeIntervals() throws {
// Negative interval
let t1 = Google_Protobuf_Duration(timeInterval: -123.456)
XCTAssertEqual(t1.seconds, -123)
XCTAssertEqual(t1.nanos, -456000000)
// Full precision
let t2 = Google_Protobuf_Duration(timeInterval: -123.999999999)
XCTAssertEqual(t2.seconds, -123)
XCTAssertEqual(t2.nanos, -999999999)
// Round up
let t3 = Google_Protobuf_Duration(timeInterval: -123.9999999994)
XCTAssertEqual(t3.seconds, -123)
XCTAssertEqual(t3.nanos, -999999999)
// Round down
let t4 = Google_Protobuf_Duration(timeInterval: -123.9999999996)
XCTAssertEqual(t4.seconds, -124)
XCTAssertEqual(t4.nanos, 0)
let t5 = Google_Protobuf_Duration(timeInterval: 0)
XCTAssertEqual(t5.seconds, 0)
XCTAssertEqual(t5.nanos, 0)
// Positive interval
let t6 = Google_Protobuf_Duration(timeInterval: 123.456)
XCTAssertEqual(t6.seconds, 123)
XCTAssertEqual(t6.nanos, 456000000)
// Full precision
let t7 = Google_Protobuf_Duration(timeInterval: 123.999999999)
XCTAssertEqual(t7.seconds, 123)
XCTAssertEqual(t7.nanos, 999999999)
// Round down
let t8 = Google_Protobuf_Duration(timeInterval: 123.9999999994)
XCTAssertEqual(t8.seconds, 123)
XCTAssertEqual(t8.nanos, 999999999)
// Round up
let t9 = Google_Protobuf_Duration(timeInterval: 123.9999999996)
XCTAssertEqual(t9.seconds, 124)
XCTAssertEqual(t9.nanos, 0)
}
func testGetters() throws {
let t1 = Google_Protobuf_Duration(seconds: -123, nanos: -123456789)
XCTAssertEqual(t1.timeInterval, -123.123456789)
let t2 = Google_Protobuf_Duration(seconds: 123, nanos: 123456789)
XCTAssertEqual(t2.timeInterval, 123.123456789)
}
}
| gpl-3.0 | 6a5c9f12b89f70b9dd006bdfd89b23b1 | 45.24031 | 184 | 0.64736 | 4.40059 | false | true | false | false |
velos/FeedbinKit | FeedbinKit/Networking/SubscriptionClient.swift | 1 | 4729 | //
// SubscriptionClient.swift
// FeedbinKit
//
// Created by Bill Williams on 11/12/14.
// Copyright (c) 2014 Velos Mobile. All rights reserved.
//
import Foundation
import Alamofire
import BrightFutures
import ObjectMapper
enum SubscriptionRouter: URLRequestConvertible {
static let baseURLString = "https://api.feedbin.com/v2/"
case ReadAll()
case ReadAllSince(sinceDate: NSDate)
case Create(NSURL)
case Read(Subscription)
case Update(Subscription)
case Delete(Subscription)
var method: Alamofire.Method {
switch self {
case .ReadAll:
return .GET
case .ReadAllSince:
return .GET
case .Create:
return .POST
case .Read:
return .GET
case .Update:
return .PATCH
case .Delete:
return .DELETE
}
}
var path: String {
switch self {
case .ReadAll:
return "/subscriptions.json"
case .ReadAllSince(let sinceDate):
return "/subscriptions.json?since=\(sinceDate)"
case .Create:
return "/subscriptions.json"
case .Read(let subscription):
return "/subscriptions/\(subscription.identifier).json"
case .Update(let subscription):
return "/subscriptions/\(subscription.identifier).json"
case .Delete(let subscription):
return "/subscriptions/\(subscription.identifier).json"
}
}
// MARK: URLRequestConvertible
var URLRequest: NSURLRequest {
let URL = NSURL(string: SubscriptionRouter.baseURLString)
let mutableURLRequest = NSMutableURLRequest(URL: URL!.URLByAppendingPathComponent(path))
mutableURLRequest.HTTPMethod = method.rawValue
switch self {
case Update(let subscription):
let JSONString = Mapper().toJSONString(subscription, prettyPrint: false)
mutableURLRequest.HTTPBody = JSONString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
default:
break
}
return mutableURLRequest
}
}
public extension FeedbinClient {
public func readAllSubscriptions() -> Future<[Subscription]> {
return request(SubscriptionRouter.ReadAll()) { _, _, responseString in
return Mapper().map(responseString, to: Subscription.self)
}
}
public func readAllSubscriptionsSince(sinceDate: NSDate) -> Future<[Subscription]> {
return request(SubscriptionRouter.ReadAllSince(sinceDate: sinceDate)) { _, _, responseString in
return Mapper().map(responseString, to: Subscription.self)
}
}
public func readSubscription(subscription: Subscription) -> Future<Subscription> {
return request(SubscriptionRouter.Read(subscription)) { _, _, responseString in
return Mapper().map(responseString, to: subscription)
}
}
public func createSubscription(feedURL: NSURL) -> Future<([Subscription]?, NSURL?)> {
return request(SubscriptionRouter.Create(feedURL)) { _, response, responseString in
if response == nil {
return (nil, nil)
}
switch response!.statusCode {
case 201, 302:
// 201 Created, 302 Found
// TODO: this should provide a Subscription object instead
if let subscriptionURLString = response!.allHeaderFields["Location"] as? NSString {
let subscriptionURL: NSURL? = NSURL(string: subscriptionURLString)
return (nil, subscriptionURL)
}
case 300:
let subscriptions: [Subscription]? = Mapper().map(responseString, to: Subscription.self)
return (subscriptions, nil)
default:
// assume anything else is failure
return (nil, nil)
}
return (nil, nil)
}
}
public func updateSubscription(subscription: Subscription) -> Future<Subscription> {
return request(SubscriptionRouter.Update(subscription)) { _, _, responseString in
return Mapper().map(responseString, to: Subscription.self)
}
}
public func deleteSubscription(subscription: Subscription) -> Future<Void> {
return self.request(SubscriptionRouter.Delete(subscription)) { _, response, _ in
if response?.statusCode == 200 {
// think of this as returning [NSNull null] instead of nil.
// yes, that's extraordinarily silly. typesafety!
return Void()
} else {
return nil
}
}
}
}
| mit | 7a55f9d52f25779f91d765bfe014c02b | 30.526667 | 120 | 0.608162 | 5.343503 | false | false | false | false |
TwilioDevEd/twiliochat-swift | twiliochat/MenuTableCell.swift | 1 | 1407 | import UIKit
class MenuTableCell: UITableViewCell {
var label: UILabel!
var channelName: String {
get {
return label?.text ?? String()
}
set(name) {
label.text = name
}
}
var selectedBackgroundColor: UIColor {
return UIColor(red:0.969, green:0.902, blue:0.894, alpha:1)
}
var labelHighlightedTextColor: UIColor {
return UIColor(red:0.22, green:0.024, blue:0.016, alpha:1)
}
var labelTextColor: UIColor {
return UIColor(red:0.973, green:0.557, blue:0.502, alpha:1)
}
override func awakeFromNib() {
label = viewWithTag(200) as? UILabel
label.highlightedTextColor = labelHighlightedTextColor
label.textColor = labelTextColor
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if (selected) {
contentView.backgroundColor = selectedBackgroundColor
} else {
contentView.backgroundColor = nil
}
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
if (highlighted) {
contentView.backgroundColor = selectedBackgroundColor
} else {
contentView.backgroundColor = nil
}
}
}
| mit | 962bf02ff5033dba2a8bd09bf83df2d3 | 27.14 | 71 | 0.601279 | 4.818493 | false | false | false | false |
mozilla-mobile/firefox-ios | Tests/UITests/DomainAutocompleteTests.swift | 2 | 6484 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import Shared
class DomainAutocompleteTests: KIFTestCase {
override func setUp() {
super.setUp()
BrowserUtils.dismissFirstRunUI(tester())
}
func testAutocomplete() {
tester().wait(forTimeInterval: 3)
tester().waitForAnimationsToFinish()
tester().wait(forTimeInterval: 3)
BrowserUtils.addHistoryEntry("Foo bar baz", url: URL(string: "https://foo.bar.baz.org/dingbat")!)
tester().tapView(withAccessibilityIdentifier: "urlBar-cancel")
tester().wait(forTimeInterval: 1)
tester().tapView(withAccessibilityIdentifier: "url")
let textField = tester().waitForView(withAccessibilityLabel: "Address and Search") as! UITextField
// Multiple subdomains.
tester().enterText(intoCurrentFirstResponder: "f")
tester().waitForAnimationsToFinish()
BrowserUtils.ensureAutocompletionResult(tester(), textField: textField, prefix: "f", completion: "oo.bar.baz.org")
tester().clearTextFromFirstResponder()
tester().waitForAnimationsToFinish()
// Expected behavior but changed intentionally https://bugzilla.mozilla.org/show_bug.cgi?id=1536746
// tester().enterText(intoCurrentFirstResponder: "b")
// BrowserUtils.ensureAutocompletionResult(tester(), textField: textField, prefix: "b", completion: "ar.baz.org")
// tester().enterText(intoCurrentFirstResponder: "a")
// BrowserUtils.ensureAutocompletionResult(tester(), textField: textField, prefix: "ba", completion: "r.baz.org")
// tester().enterText(intoCurrentFirstResponder: "z")
// Current and temporary behaviour entering more than 2 chars for the matching
tester().enterText(intoCurrentFirstResponder: "bar")
tester().waitForAnimationsToFinish()
BrowserUtils.ensureAutocompletionResult(tester(), textField: textField, prefix: "bar", completion: ".baz.org")
tester().enterText(intoCurrentFirstResponder: ".ba")
tester().waitForAnimationsToFinish()
BrowserUtils.ensureAutocompletionResult(tester(), textField: textField, prefix: "bar.ba", completion: "z.org")
tester().enterText(intoCurrentFirstResponder: "z")
tester().waitForAnimationsToFinish()
BrowserUtils.ensureAutocompletionResult(tester(), textField: textField, prefix: "bar.baz", completion: ".org")
}
func testAutocompleteAfterDeleteWithBackSpace() {
tester().waitForAnimationsToFinish()
tester().wait(forTimeInterval: 1)
tester().tapView(withAccessibilityIdentifier: "url")
let textField = tester().waitForView(withAccessibilityLabel: "Address and Search") as! UITextField
tester().enterText(intoCurrentFirstResponder: "facebook")
tester().waitForAnimationsToFinish()
BrowserUtils.ensureAutocompletionResult(tester(), textField: textField, prefix: "facebook", completion: ".com")
// Remove the completion part .com
tester().enterText(intoCurrentFirstResponder: XCUIKeyboardKey.delete.rawValue)
tester().waitForAnimationsToFinish()
// Tap on Go to perform a search
tester().tapView(withAccessibilityLabel: "go")
tester().waitForAnimationsToFinish()
tester().wait(forTimeInterval: 1)
// Tap on the url to go back to the awesomebar results
tester().tapView(withAccessibilityIdentifier: "url")
tester().waitForAnimationsToFinish()
let textField2 = tester().waitForView(withAccessibilityLabel: "Address and Search") as! UITextField
// Facebook word appears highlighted and so it is shown as facebook\u{7F} when extracting the value to compare
BrowserUtils.ensureAutocompletionResult(tester(), textField: textField2 , prefix: "facebook\u{7F}", completion: "")
}
// Bug https://bugzilla.mozilla.org/show_bug.cgi?id=1541832 scenario 1
func testAutocompleteOnechar() {
tester().waitForAnimationsToFinish()
tester().wait(forTimeInterval: 1)
tester().tapView(withAccessibilityIdentifier: "url")
let textField = tester().waitForView(withAccessibilityLabel: "Address and Search") as! UITextField
tester().enterText(intoCurrentFirstResponder: "f")
tester().waitForAnimationsToFinish()
BrowserUtils.ensureAutocompletionResult(tester(), textField: textField, prefix: "f", completion: "acebook.com")
}
// Bug https://bugzilla.mozilla.org/show_bug.cgi?id=1541832 scenario 2
func testAutocompleteOneCharAfterRemovingPreviousTerm() {
tester().wait(forTimeInterval: 3)
tester().tapView(withAccessibilityIdentifier: "url")
let textField = tester().waitForView(withAccessibilityLabel: "Address and Search") as! UITextField
tester().enterText(intoCurrentFirstResponder: "foo")
// Remove the completion part and the the foo chars one by one
for _ in 1...4 {
tester().tapView(withAccessibilityIdentifier: "address")
tester().enterText(intoCurrentFirstResponder: "\u{0008}")
}
tester().waitForAnimationsToFinish()
tester().enterText(intoCurrentFirstResponder: "f")
tester().waitForAnimationsToFinish()
BrowserUtils.ensureAutocompletionResult(tester(), textField: textField, prefix: "f", completion: "acebook.com")
}
// Bug https://bugzilla.mozilla.org/show_bug.cgi?id=1541832 scenario 3
func testAutocompleteOneCharAfterRemovingWithClearButton() {
tester().wait(forTimeInterval: 1)
tester().tapView(withAccessibilityIdentifier: "url")
let textField = tester().waitForView(withAccessibilityLabel: "Address and Search") as! UITextField
tester().enterText(intoCurrentFirstResponder: "foo")
tester().tapView(withAccessibilityLabel: "Clear text")
tester().enterText(intoCurrentFirstResponder: "f")
BrowserUtils.ensureAutocompletionResult(tester(), textField: textField, prefix: "f", completion: "acebook.com")
}
override func tearDown() {
super.tearDown()
tester().tapView(withAccessibilityIdentifier: "urlBar-cancel")
BrowserUtils.resetToAboutHomeKIF(tester())
tester().wait(forTimeInterval: 3)
BrowserUtils.clearPrivateDataKIF(tester())
}
}
| mpl-2.0 | d1b3dfd7df734b8edfe859357a1fca78 | 52.147541 | 123 | 0.700802 | 5.380913 | false | true | false | false |
pusher/pusher-websocket-swift | Tests/Extensions/XCTest+Assertions.swift | 2 | 738 | import XCTest
private func executeAndAssignResult<T>(_ expression: () throws -> T?, to: inout T?) rethrows {
to = try expression()
}
private func executeAndAssignEquatableResult<T>(_ expression: @autoclosure () throws -> T?, to: inout T?) rethrows where T: Equatable {
to = try expression()
}
func XCTAssertNotNil<T>(_ expression: @autoclosure () throws -> T?, _ message: String = "", file: StaticString = #file, line: UInt = #line, also validateResult: (T) -> Void) {
var result: T?
XCTAssertNoThrow(try executeAndAssignResult(expression, to: &result), message, file: file, line: line)
XCTAssertNotNil(result, message, file: file, line: line)
if let result = result {
validateResult(result)
}
}
| mit | acf9f5fc35b8077a004645db44f8c9c5 | 34.142857 | 175 | 0.677507 | 3.946524 | false | false | false | false |
jianghongbing/APIReferenceDemo | UserNotifications/LocalNotificationDemo/LocalNotificationDemo/NotificationManager.swift | 1 | 2967 | //
// NotificationManager.swift
// LocalNotificationDemo
//
// Created by pantosoft on 2017/9/15.
// Copyright © 2017年 jianghongbing. All rights reserved.
//
import UIKit
import UserNotifications
//enum NotificationType {
//
//}
enum NotificationCategoryType: String {
case normal
case input
case customUI
}
enum InputNotificationActionType:String {
case input
case hello
case none
}
class NotificationManager: NSObject, UNUserNotificationCenterDelegate{
static let defaultManager = NotificationManager()
private override init() {
super.init()
}
func registerCategory() {
let inputCategory: UNNotificationCategory = {
let inputAction = UNTextInputNotificationAction(identifier: InputNotificationActionType.input.rawValue, title: "Input", options: [.foreground], textInputButtonTitle: "send", textInputPlaceholder: "input text")
let helloAction = UNNotificationAction(identifier: InputNotificationActionType.hello.rawValue, title: "hello", options: [.foreground])
let cancelAction = UNNotificationAction(identifier: InputNotificationActionType.none.rawValue, title: "Cancel", options: [.destructive])
let category = UNNotificationCategory(identifier: NotificationCategoryType.input.rawValue, actions: [inputAction, helloAction, cancelAction], intentIdentifiers: [], options: [.customDismissAction])
return category
}();
UNUserNotificationCenter.current().setNotificationCategories([inputCategory])
}
func requestAuthentication() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
UIApplication.shared.registerForRemoteNotifications()
}else {
if let error = error {
print(error.localizedDescription)
}
}
}
}
}
extension NotificationManager {
//#MARK: UNUserNotificationCenterDelegate
//1.将要呈现通知的时候,会调用该方法,可以通过completionHandler回调来设置该通知显示为alert,是否播放声音,是否显示badgeNumber
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("will present notification")
completionHandler([.alert, .sound, .badge])
}
//2.当点击了通知,或者通过的action方式进入app,delegate会收到该消息,可以在这个方法里面来处理点击通知的逻辑
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("did receive notification:\(response)")
completionHandler()
}
}
| mit | 4be3e6ebd3d81bb3588b71075e2e34bc | 36.386667 | 221 | 0.707204 | 5.44466 | false | false | false | false |
a2/MessagePack.swift | Tests/MessagePackTests/DescriptionTests.swift | 1 | 4153 | import Foundation
import XCTest
@testable import MessagePack
class DescriptionTests: XCTestCase {
static var allTests = {
return [
("testNilDescription", testNilDescription),
("testBoolDescription", testBoolDescription),
("testIntDescription", testIntDescription),
("testUIntDescription", testUIntDescription),
("testFloatDescription", testFloatDescription),
("testDoubleDescription", testDoubleDescription),
("testStringDescription", testStringDescription),
("testBinaryDescription", testBinaryDescription),
("testArrayDescription", testArrayDescription),
("testMapDescription", testMapDescription),
("testExtendedDescription", testExtendedDescription),
]
}()
func testNilDescription() {
XCTAssertEqual(MessagePackValue.nil.description, "nil")
}
func testBoolDescription() {
XCTAssertEqual(MessagePackValue.bool(true).description, "bool(true)")
XCTAssertEqual(MessagePackValue.bool(false).description, "bool(false)")
}
func testIntDescription() {
XCTAssertEqual(MessagePackValue.int(-1).description, "int(-1)")
XCTAssertEqual(MessagePackValue.int(0).description, "int(0)")
XCTAssertEqual(MessagePackValue.int(1).description, "int(1)")
}
func testUIntDescription() {
XCTAssertEqual(MessagePackValue.uint(0).description, "uint(0)")
XCTAssertEqual(MessagePackValue.uint(1).description, "uint(1)")
XCTAssertEqual(MessagePackValue.uint(2).description, "uint(2)")
}
func testFloatDescription() {
XCTAssertEqual(MessagePackValue.float(0.0).description, "float(0.0)")
XCTAssertEqual(MessagePackValue.float(1.618).description, "float(1.618)")
XCTAssertEqual(MessagePackValue.float(3.14).description, "float(3.14)")
}
func testDoubleDescription() {
XCTAssertEqual(MessagePackValue.double(0.0).description, "double(0.0)")
XCTAssertEqual(MessagePackValue.double(1.618).description, "double(1.618)")
XCTAssertEqual(MessagePackValue.double(3.14).description, "double(3.14)")
}
func testStringDescription() {
XCTAssertEqual(MessagePackValue.string("").description, "string()".description)
XCTAssertEqual(MessagePackValue.string("MessagePack").description, "string(MessagePack)".description)
}
func testBinaryDescription() {
XCTAssertEqual(MessagePackValue.binary(Data()).description, "data(0 bytes)")
XCTAssertEqual(MessagePackValue.binary(Data(Data([0x00, 0x01, 0x02, 0x03, 0x04]))).description, "data(5 bytes)")
}
func testArrayDescription() {
let values: [MessagePackValue] = [1, true, ""]
XCTAssertEqual(MessagePackValue.array(values).description, "array([int(1), bool(true), string()])")
}
func testMapDescription() {
let values: [MessagePackValue: MessagePackValue] = [
"a": "apple",
"b": "banana",
"c": "cookie",
]
let components = [
"string(a): string(apple)",
"string(b): string(banana)",
"string(c): string(cookie)",
]
let indexPermutations: [[Int]] = [
[0, 1, 2],
[0, 2, 1],
[1, 0, 2],
[1, 2, 0],
[2, 0, 1],
[2, 1, 0],
]
let description = MessagePackValue.map(values).description
var isValid = false
for indices in indexPermutations {
let permutation = indices.map { index in components[index] }
let innerDescription = permutation.joined(separator: ", ")
if description == "map([\(innerDescription)])" {
isValid = true
break
}
}
XCTAssertTrue(isValid)
}
func testExtendedDescription() {
XCTAssertEqual(MessagePackValue.extended(5, Data()).description, "extended(5, 0 bytes)")
XCTAssertEqual(MessagePackValue.extended(5, Data([0x00, 0x10, 0x20, 0x30, 0x40])).description, "extended(5, 5 bytes)")
}
}
| mit | fbf22da75d3274cfb550b48fa400fd5b | 36.414414 | 126 | 0.625813 | 4.735462 | false | true | false | false |
jgonfer/JGFLabRoom | JGFLabRoom/Resources/Constants.swift | 1 | 3278 | //
// Constants.swift
// JGFLabRoom
//
// Created by Josep Gonzalez Fernandez on 14/1/16.
// Copyright © 2016 Josep Gonzalez Fernandez. All rights reserved.
//
import UIKit
// MARK: API Key & Secret
// This information shouldn't be stored in the app.
let kApiTwitterConsumerKey = "OYPHJXmYb1Cxy17dzBT4Ka7XB"
let kApiTwitterConsumerecret = "DW02qNxB9NbI7enPdng7JmSS1krOLmbnWwVPEuo92eI6PX3F0Z"
let kApiTwitterAccessToken = "299522050-hb4KjuNZB8cdsYSE7siYaVUi3DKydT91uMLeWq3X"
let kApiTwitterAccessTokenSecret = "U5fqldL0ZiNzpjymUWxzguEdCobOGuiOhQSCSh7TxK9Aq"
let kApiFacebookAppId = "991680990875333"
let kApiFacebookAppSecret = "cd081e29e4a3e60ce94111fbe900dd2a"
let kApiGoogleDriveConsumerKey = "643943608923-8g6rebcsiakcvc0qsk564bisk0p5ibqs.apps.googleusercontent.com"
let kApiGoogleDriveConsumerSecret = "ghNixvFtLYwaRtWvlv8Mbzkh"
let kApiSpotifyClientId = "3c9218af7c314198985ae6733b47afd4"
let kApiSpotifyClientSecret = "d31263e050f34f83a7ce219dd991cb0c"
let kApiGitHubClientId = "5072d51c60d715e79c95"
let kApiGitHubClientSecret = "28af606db9df21a2ac4c4eb72ddd00306790fc00"
// MARK: Keychain Keys
let kKeychainKeyGitHub = "github"
// MARK: Apps URLs
let kUrlApps = "https://itunes.apple.com/search?term=josep+gonzalez+fernandez&country=us&entity=software"
let kUrlTravelApps = "https://itunes.apple.com/search?term=travel&country=us&entity=software&limit=200"
let kUrlGameApps = "https://itunes.apple.com/search?term=games&country=us&entity=software&limit=200"
let kUrlProductivityApps = "https://itunes.apple.com/search?term=productivity&country=us&entity=software&limit=200"
// MARK: GitHub URLs
let kUrlGitHubRepos = "https://api.github.com/user/repos"
let kUrlGitHubAuth = "https://github.com/login/oauth/authorize?client_id=\(kApiGitHubClientId)&scope=repo&state=Request_Access_Token"
let kUrlGitHubGetToken = "https://github.com/login/oauth/access_token"
// MARK: Segues Identifier
let kSegueIdEventKit = "showEventKit"
let kSegueIdListEvents = "showListEvents"
let kSegueIdGCD = "showGCD"
let kSegueIdListApps = "showListApps"
let kSegueIdCommonCrypto = "showCommonCrypto"
let kSegueIdKeychain = "showKeychain"
let kSegueIdTouchID = "showTouchID"
let kSegueIdCCSettings = "showCCSettings"
let kSegueIdSocial = "showSocial"
let kSegueIdSocialOptions = "showSocialOptions"
let kSegueIdSTwitter = "showSTwitter"
let kSegueIdSFacebook = "showSFacebook"
let kSegueIdSGoogleDrive = "showSGoogleDrive"
let kSegueIdSGitHub = "showSGitHub"
// MARK: Error Domains
let kErrorDomainConnection = "Connection Error"
let kErrorDomainGitHub = "GitHub Error"
// MARK: Error Codes
let kErrorCodeJSONSerialization = 1
let kErrorCodeGitHubNoToken = 2
let kErrorCodeGitHubBadCredentials = 3
// MARK: Error Messages
let kErrorMessageJSONSerialize = "Could not serialize JSON object"
let kErrorMessageRetryRequest = "Please retry your request"
let kErrorMessageNoToken = "There is no token available"
let kErrorMessageLogInAgain = "Please log in again"
let kErrorMessageGitHubBadCredentials = "Bad credentials"
// MARK: Colors
// Green Mantis
let kColorPrimary = UIColor(red:0.39, green:0.8, blue:0.35, alpha:1)
let kColorPrimaryAlpha = UIColor(red:0.39, green:0.8, blue:0.35, alpha:0.3)
let kColorWrong = UIColor(red:0.82, green:0.26, blue:0.14, alpha:1) | mit | 76290863470e2a2cb2508b9b7095f9f7 | 33.505263 | 133 | 0.80531 | 3.106161 | false | false | false | false |
devpunk/cartesian | cartesian/View/Store/VStoreCellPurchased.swift | 1 | 793 | import UIKit
class VStoreCellPurchased:VStoreCell
{
override init(frame:CGRect)
{
super.init(frame:frame)
backgroundColor = UIColor.cartesianBlue
isUserInteractionEnabled = false
let label:UILabel = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.isUserInteractionEnabled = false
label.textAlignment = NSTextAlignment.center
label.font = UIFont.medium(size:16)
label.textColor = UIColor.white
label.text = NSLocalizedString("VStoreCellPurchased_label", comment:"")
addSubview(label)
NSLayoutConstraint.equals(
view:label,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
}
| mit | 6383879e0ed7d6131badab25eef11547 | 25.433333 | 79 | 0.627995 | 5.468966 | false | false | false | false |
lili668668/TagList | TagList2/AppDelegate.swift | 1 | 2772 | //
// AppDelegate.swift
// TagList2
//
// Created by mac on 2017/3/11.
// Copyright © 2017年 mac. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var db: OpaquePointer? = nil
static let ENTRY = "entry"
static let IS_FINISH = "is_finish"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let fm = FileManager.default
let src = Bundle.main.path(forResource: "TagList", ofType: "sqlite")
let dst = NSHomeDirectory() + "/Documents/TagList.sqlite"
if !fm.fileExists(atPath: dst) {
try! fm.copyItem(atPath: src!, toPath: dst)
}
if sqlite3_open(dst, &db) != SQLITE_OK {
db = nil
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
guard db != nil else {
return
}
sqlite3_close(db!)
}
}
| mit | c63a3882c48f435a5662d1a13998ba21 | 39.720588 | 285 | 0.694113 | 5.254269 | false | false | false | false |
SwiftKitz/Appz | Appz/AppzTests/AppsTests/AppStoreTests.swift | 2 | 1764 | //
// AppStoreTests.swift
// Appz
//
// Created by Mazyad Alabduljaleel on 11/10/15.
// Copyright © 2015 kitz. All rights reserved.
//
import XCTest
@testable import Appz
class AppStoreTests: XCTestCase {
let appCaller = ApplicationCallerMock()
func testConfiguration() {
let appStore = Applications.AppStore()
XCTAssertEqual(appStore.scheme, "itms-apps:")
XCTAssertEqual(appStore.fallbackURL, "http:")
}
func testOpenApp() {
let appId = "395107915"
let action = Applications.AppStore.Action.app(id: appId)
XCTAssertEqual(action.paths.app.pathComponents, ["itunes.apple.com", "app", "id\(appId)"])
XCTAssertEqual(action.paths.app.queryParameters, [:])
XCTAssertEqual(action.paths.web, Path())
}
func testOpenAccount() {
let accountId = "395107918"
let action = Applications.AppStore.Action.account(id: accountId)
XCTAssertEqual(action.paths.app.pathComponents, ["itunes.apple.com", "developer", "id\(accountId)"])
XCTAssertEqual(action.paths.app.queryParameters, [:])
XCTAssertEqual(action.paths.web, Path())
}
func testRateApp() {
let appId = "327630330"
let action = Applications.AppStore.Action.rateApp(id: appId)
XCTAssertEqual(action.paths.app.pathComponents, ["itunes.apple.com", "WebObjects", "MZStore.woa", "wa", "viewContentsUserReviews"])
XCTAssertEqual(action.paths.app.queryParameters, [
"type":"Purple+Software",
"id":appId,])
XCTAssertEqual(action.paths.web, Path())
}
}
| mit | 9ce4f6cbb9051de8c280ca23f439be59 | 31.054545 | 139 | 0.59671 | 4.627297 | false | true | false | false |
OscarSwanros/swift | test/Serialization/Inputs/def_struct.swift | 32 | 2491 | public struct Empty {}
public struct TwoInts {
public var x, y : Int
public init(x: Int, y: Int) {
self.x = x
self.y = y
}
}
public struct ComputedProperty {
public var value : Int {
get {
var result = 0
return result
}
}
}
public struct StaticProperties {
public static var foo: Int = 0
public static let bar: Int = 0
public static var baz: Int {
return 0
}
}
// Generics
public struct Pair<A, B> {
public var first : A
public var second : B
public init(a : A, b : B) {
first = a
second = b
}
}
public typealias VoidPairTuple = ((), ())
public struct GenericCtor<U> {
public init<T>(_ t : T) {}
public func doSomething<T>(_ t: T) {}
}
// Protocols
public protocol Resettable {
mutating
func reset()
}
public struct ResettableIntWrapper : Resettable {
public var value : Int
public mutating
func reset() {
var zero = 0
value = zero
}
public init(value: Int) { self.value = value }
}
public protocol Computable {
mutating
func compute()
}
public typealias Cacheable = Resettable & Computable
public protocol SpecialResettable : Resettable, Computable {}
public protocol HasAssociatedType {
associatedtype ComputableType : Computable
}
public struct ComputableWrapper<T : Computable> : HasAssociatedType {
public typealias ComputableType = T
public init() {}
}
public protocol AnotherAssociated {
associatedtype ResettableType : Resettable
}
public struct ResettableWrapper<T : Resettable> : AnotherAssociated {
public typealias ResettableType = T
public init() {}
}
public func cacheViaWrappers<
T : HasAssociatedType, U : AnotherAssociated
where T.ComputableType == U.ResettableType
>(_ computable : T, _ resettable : U) {}
// Subscripts
public struct ReadonlySimpleSubscript {
public subscript(x : Int) -> Bool {
return true
}
public init() {}
}
public struct ComplexSubscript {
public subscript(x : Int, y : Bool) -> Int {
set(newValue) {
// do nothing!
}
get {
return 0
}
}
public init() {}
}
// Extensions
public extension Empty {
public func doAbsolutelyNothing() {}
}
public struct UnComputable {}
extension UnComputable : Computable {
public init(x : Int) {}
public func compute() {}
public static func canCompute() -> Bool {
return true
}
}
public extension Pair {
public func swap() -> (B, A) {
return (second, first)
}
}
public struct Burger {
public let pattyCount: Int
}
| apache-2.0 | 66d532ce56be771679b5d7e2b50c58ee | 16.920863 | 69 | 0.663589 | 3.838213 | false | false | false | false |
mamouneyya/TheSkillsProof | Pods/p2.OAuth2/Sources/Base/OAuth2ClientConfig.swift | 3 | 6886 | //
// OAuth2ClientConfig.swift
// OAuth2
//
// Created by Pascal Pfiffner on 16/11/15.
// Copyright © 2015 Pascal Pfiffner. All rights reserved.
//
import Foundation
/**
Client configuration object that holds on to client-server specific configurations such as client id, -secret and server URLs.
*/
public class OAuth2ClientConfig {
/// The client id.
public final var clientId: String?
/// The client secret, usually only needed for code grant.
public final var clientSecret: String?
/// The name of the client, e.g. for use during dynamic client registration.
public final var clientName: String?
/// The URL to authorize against.
public final let authorizeURL: NSURL
/// The URL where we can exchange a code for a token.
public final var tokenURL: NSURL?
/// Where a logo/icon for the app can be found.
public final var logoURL: NSURL?
/// The scope currently in use.
public var scope: String?
/// The redirect URL string currently in use.
public var redirect: String?
/// All redirect URLs passed to the initializer.
public var redirectURLs: [String]?
/// The receiver's access token.
public var accessToken: String?
/// The access token's expiry date.
public var accessTokenExpiry: NSDate?
/// If set to true (the default), uses a keychain-supplied access token even if no "expires_in" parameter was supplied.
public var accessTokenAssumeUnexpired = true
/// The receiver's long-time refresh token.
public var refreshToken: String?
/// The URL to register a client against.
public final var registrationURL: NSURL?
/// How the client communicates the client secret with the server. Defaults to ".None" if there is no secret, ".ClientSecretPost" if
/// "secret_in_body" is `true` and ".ClientSecretBasic" otherwise. Interacts with the `authConfig.secretInBody` client setting.
public final var endpointAuthMethod = OAuth2EndpointAuthMethod.None
/**
Initializer to initialize properties from a settings dictionary.
*/
public init(settings: OAuth2JSON) {
clientId = settings["client_id"] as? String
clientSecret = settings["client_secret"] as? String
clientName = settings["client_name"] as? String
// authorize URL
var aURL: NSURL?
if let auth = settings["authorize_uri"] as? String {
aURL = NSURL(string: auth)
}
authorizeURL = aURL ?? NSURL(string: "http://localhost")!
// token, registration and logo URLs
if let token = settings["token_uri"] as? String {
tokenURL = NSURL(string: token)
}
if let registration = settings["registration_uri"] as? String {
registrationURL = NSURL(string: registration)
}
if let logo = settings["logo_uri"] as? String {
logoURL = NSURL(string: logo)
}
// client authentication options
scope = settings["scope"] as? String
if let redirs = settings["redirect_uris"] as? [String] {
redirectURLs = redirs
redirect = redirs.first
}
if let inBody = settings["secret_in_body"] as? Bool where inBody {
endpointAuthMethod = .ClientSecretPost
}
else if nil != clientSecret {
endpointAuthMethod = .ClientSecretBasic
}
// access token options
if let assume = settings["token_assume_unexpired"] as? Bool {
accessTokenAssumeUnexpired = assume
}
}
/**
Update properties from response data.
- parameter json: JSON data returned from a request
*/
func updateFromResponse(json: OAuth2JSON) {
if let access = json["access_token"] as? String {
accessToken = access
}
accessTokenExpiry = nil
if let expires = json["expires_in"] as? NSTimeInterval {
accessTokenExpiry = NSDate(timeIntervalSinceNow: expires)
}
else if let expires = json["expires_in"] as? String { // when parsing implicit grant from URL fragment
accessTokenExpiry = NSDate(timeIntervalSinceNow: Double(expires) ?? 0.0)
}
if let refresh = json["refresh_token"] as? String {
refreshToken = refresh
}
}
/**
Creates a dictionary of credential items that can be stored to the keychain.
- returns: A storable dictionary with credentials
*/
func storableCredentialItems() -> [String: NSCoding]? {
guard let clientId = clientId where !clientId.isEmpty else { return nil }
var items: [String: NSCoding] = ["id": clientId]
if let secret = clientSecret {
items["secret"] = secret
}
items["endpointAuthMethod"] = endpointAuthMethod.rawValue
return items
}
/**
Creates a dictionary of token items that can be stored to the keychain.
- returns: A storable dictionary with token data
*/
func storableTokenItems() -> [String: NSCoding]? {
guard let access = accessToken where !access.isEmpty else { return nil }
var items: [String: NSCoding] = ["accessToken": access]
if let date = accessTokenExpiry where date == date.laterDate(NSDate()) {
items["accessTokenDate"] = date
}
if let refresh = refreshToken where !refresh.isEmpty {
items["refreshToken"] = refresh
}
return items
}
/**
Updates receiver's instance variables with values found in the dictionary. Returns a list of messages that can be logged on debug.
- parameter items: The dictionary representation of the data to store to keychain
- returns: An array of strings containing log messages
*/
func updateFromStorableItems(items: [String: NSCoding]) -> [String] {
var messages = [String]()
if let id = items["id"] as? String {
clientId = id
messages.append("Found client id")
}
if let secret = items["secret"] as? String {
clientSecret = secret
messages.append("Found client secret")
}
if let methodName = items["endpointAuthMethod"] as? String, let method = OAuth2EndpointAuthMethod(rawValue: methodName) {
endpointAuthMethod = method
}
if let token = items["accessToken"] as? String where !token.isEmpty {
if let date = items["accessTokenDate"] as? NSDate {
if date == date.laterDate(NSDate()) {
messages.append("Found access token, valid until \(date)")
accessTokenExpiry = date
accessToken = token
}
else {
messages.append("Found access token but it seems to have expired")
}
}
else if accessTokenAssumeUnexpired {
messages.append("Found access token but no expiration date, assuming unexpired (set `accessTokenAssumeUnexpired` to false to discard)")
accessToken = token
}
else {
messages.append("Found access token but no expiration date, discarding (set `accessTokenAssumeUnexpired` to true to still use it)")
}
}
if let token = items["refreshToken"] as? String where !token.isEmpty {
messages.append("Found refresh token")
refreshToken = token
}
return messages
}
/** Forgets the configuration's client id and secret. */
public func forgetCredentials() {
clientId = nil
clientSecret = nil
}
/** Forgets the configuration's current tokens. */
public func forgetTokens() {
accessToken = nil
accessTokenExpiry = nil
refreshToken = nil
}
}
| mit | efbda58c3e5c7d9bba90e23a668ab591 | 29.874439 | 139 | 0.708061 | 3.943299 | false | false | false | false |
robertofrontado/RxGcm-iOS | iOS/Pods/Nimble/Sources/Nimble/Matchers/PostNotification.swift | 144 | 2431 | import Foundation
internal class NotificationCollector {
private(set) var observedNotifications: [Notification]
private let notificationCenter: NotificationCenter
#if _runtime(_ObjC)
private var token: AnyObject?
#else
private var token: NSObjectProtocol?
#endif
required init(notificationCenter: NotificationCenter) {
self.notificationCenter = notificationCenter
self.observedNotifications = []
}
func startObserving() {
self.token = self.notificationCenter.addObserver(forName: nil, object: nil, queue: nil) {
// linux-swift gets confused by .append(n)
[weak self] n in self?.observedNotifications.append(n)
}
}
deinit {
#if _runtime(_ObjC)
if let token = self.token {
self.notificationCenter.removeObserver(token)
}
#else
if let token = self.token as? AnyObject {
self.notificationCenter.removeObserver(token)
}
#endif
}
}
private let mainThread = pthread_self()
let notificationCenterDefault = NotificationCenter.default
public func postNotifications<T>(
_ notificationsMatcher: T,
fromNotificationCenter center: NotificationCenter = notificationCenterDefault)
-> MatcherFunc<Any>
where T: Matcher, T.ValueType == [Notification]
{
let _ = mainThread // Force lazy-loading of this value
let collector = NotificationCollector(notificationCenter: center)
collector.startObserving()
var once: Bool = false
return MatcherFunc { actualExpression, failureMessage in
let collectorNotificationsExpression = Expression(memoizedExpression: { _ in
return collector.observedNotifications
}, location: actualExpression.location, withoutCaching: true)
assert(pthread_equal(mainThread, pthread_self()) != 0, "Only expecting closure to be evaluated on main thread.")
if !once {
once = true
_ = try actualExpression.evaluate()
}
let match = try notificationsMatcher.matches(collectorNotificationsExpression, failureMessage: failureMessage)
if collector.observedNotifications.isEmpty {
failureMessage.actualValue = "no notifications"
} else {
failureMessage.actualValue = "<\(stringify(collector.observedNotifications))>"
}
return match
}
}
| apache-2.0 | 59fdda58721a68ac5713a8e1946189a6 | 33.728571 | 120 | 0.667626 | 5.475225 | false | false | false | false |
BananosTeam/CreativeLab | Assistant/Trello/Models/BoardMember.swift | 1 | 1076 | //
// BoardMember.swift
// Assistant
//
// Created by Dmitrii Celpan on 5/14/16.
// Copyright © 2016 Bananos. All rights reserved.
//
import Foundation
enum MemberType: String {
case Normal = "normal"
case Admin = "admin"
}
final class BoardMember {
var id: String?
var memberId: String?
var memberType: MemberType?
var orgMemberType: MemberType?
}
final class BoardMemberParser {
func boardMembersFromDictionaties(dictionaries: [NSDictionary]) -> [BoardMember] {
return dictionaries.map() { boardMembersFromDictionary($0) }
}
func boardMembersFromDictionary(dictionary: NSDictionary) -> BoardMember {
let boardMember = BoardMember()
boardMember.id = dictionary["id"] as? String
boardMember.memberId = dictionary["idMember"] as? String
boardMember.memberType = MemberType(rawValue: (dictionary["memberType"] as? String) ?? "")
boardMember.orgMemberType = MemberType(rawValue: (dictionary["orgMemberType"] as? String) ?? "")
return boardMember
}
}
| mit | 25f453bab279c9d518addd1e212317c0 | 26.564103 | 104 | 0.669767 | 4.282869 | false | false | false | false |
natecook1000/swift-compiler-crashes | crashes-duplicates/08925-swift-type-transform.swift | 11 | 2555 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum S<U : T
func a<h : a
protocol A : AnyObject.b
switch x }
var f = compose<h: A.b<T where h: Array) {
class B
func g<T> : Any, A: d
let c : T
class b<T where h: T> : Any, A: String = compose<T where S<T where H.B : T
class func g<T where A.B : a = nil
let a = T
protocol A {
class d
struct A {
}
}
enum B {
return "[1)
class func b<T {
}
class func a<T where S<h: AnyObject, x }
}
}
struct c>: A: Any, x }
struct S<T: a
let a = "\(e: AnyObject.dynamicType)"\(e: T>
var f = nil
var f = compose<T where A.b: a
enum S<T where A: T
}
func a<T: T
}
func a<T where h: a
func a
}
class func a<T>: B<T where H.b: A.dynamicType)"\(e: AnyObject, A.b
class a {
class a {
return "\(e: Any, A? {
class a = T> : a
class func a
return "
protocol A {
struct D : A? {
enum S<c>
class b
protocol A {
protocol A {
protocol A : Array) {
protocol A : B
struct S<T where H.dynamicType)"
if true {
func b: B<c>
}
func g<T: d = "[1)
return "[1)"\(e: B
}
}
switch x }
func a
enum S<T {
struct S<h : AnyObject.B : T
class B<T where H.dynamicType)
}
class b
let a = compose<h : a<U : T: a = compose<T
struct D : NSManagedObject {
class func a
}
func a<h : a
struct D : A? {
let c : T
class A : a = compose<T where S<h: a
enum B : Any, A.dynamicType)""
}
let c : B
struct c>: a
let c : a<U : String = nil
func a
class d
func a
class d
enum S<h : d
class B
class d
struct c<T where h: d = "[1)
func b: String = compose<T where H.b: a {
struct c>
}
switch x in 0
var f = compose<U : T> : a
if true {
struct c>
var f = "
let a {
}
func a
class func a
switch x in 0
class A : NSManagedObject {
class B
class B
struct A : B<T where h: AnyObject.dynamicType)
class a {
class b
class B
if true {
protocol A : NSManagedObject {
return "[1)"
struct c<h: A? {
func a
class d
class func a
struct A : d
struct D : Array) {
let a {
class A {
class func g<T where A? {
switch x in 0
protocol A {
func b
enum S<h: B<h: Array) {
struct D : a {
protocol A {
let a {
func a<U : Any, x in 0
class func a<h : String = "[1)"
struct A : AnyObject.b
protocol A : d<U : a = compose<h: String = ""[1)""\(e: String = nil
struct D : d
let a {
class a {
let a {
struct A : d = "
}
struct D : NSManagedObject {
func a
class a {
class B
let a = T
class d<T where h: d = compose<T {
struct A : A: d = T
}
}
var f = T: Any, x }
let a = nil
struct A : T
}
class b<h : Array) {
class B
class A {
func a
struct A {
class d
}
class A {
}
enum S<T
| mit | 3a27d290f35a948bf0051173fa8622c1 | 14.771605 | 87 | 0.62544 | 2.53221 | false | false | false | false |
inacioferrarini/York | Classes/DeepLinkingNavigation/PresentationPath.swift | 1 | 3268 | // The MIT License (MIT)
//
// Copyright (c) 2016 Inácio Ferrarini
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
open class PresentationPath: NSObject {
// MARK: - Constants
open let presentationParameterPath = "/:presentation"
open static let presentationParameterPathKey = "presentation"
// MARK: - Properties
open fileprivate (set) var pattern: String
// MARK: - Class Methods
open class func presentationMode(_ parameters: [AnyHashable: Any]) -> PresentationMode {
var mode: PresentationMode = .Push
if let presentationModeValue = parameters[presentationParameterPathKey] as? String,
let value = PresentationMode(rawValue: presentationModeValue) {
mode = value
}
return mode
}
// MARK: - Initialization
public init(pattern: String) {
self.pattern = pattern
super.init()
}
// MARK: - Public Methods
open func absoluteString() -> String {
return self.removeLastPathSeparator(self.pattern) + self.presentationParameterPath
}
open func replacingValues(_ mode: PresentationMode) -> String {
return self.replacingValues(nil, mode: mode)
}
open func replacingValues(_ values: [String : String]?, mode: PresentationMode) -> String {
var replacedValuesPath = self.removeLastPathSeparator(self.pattern)
if let values = values {
for (key, value) in values {
let range = replacedValuesPath.range(of: key)
replacedValuesPath = replacedValuesPath.replacingOccurrences(of: key, with: value, options: .caseInsensitive, range: range)
}
}
return self.removeLastPathSeparator(replacedValuesPath) + "/" + mode.rawValue
}
open func removeLastPathSeparator(_ path: String) -> String {
var cleanPath = path
let lastIndex = path.characters.index(before: path.endIndex)
if lastIndex > path.startIndex {
let lastChar = path[lastIndex]
if lastChar == "/" {
cleanPath = path.substring(to: lastIndex)
}
}
return cleanPath
}
}
| mit | f9c610889bdc11509a97fd1b642ffc80 | 33.755319 | 139 | 0.667891 | 4.790323 | false | false | false | false |
rodrigo-lima/ThenKit | Tests/ThenKitTests/ThenKitTestHelpers.swift | 1 | 3588 | //
// ThenKitTestHelpers.swift
// ThenKit
//
// Created by Rodrigo Lima on 8/18/15.
// Copyright © 2015 Rodrigo. All rights reserved.
//
import Foundation
@testable import ThenKit
extension Logger {
public static func runningTest<T>(_ object: T, newLine: Bool = false) {
if newLine { print("") } // or it will not escape correctly
print(Escape.escaped(color: .cyan, ".🏃. \(object)"))
}
}
// ---------------------------------------------------------------------------------------------------------------------
// MARK: -
let thenKitTestsError1 = NSError(domain: "ThenKitTests.Error.1", code: 1, userInfo: nil)
let thenKitTestsError2 = NSError(domain: "ThenKitTests.Error.2", code: 2, userInfo: nil)
// MARK: -
public func dispatch_after(_ interval: TimeInterval, _ block: @escaping () -> Void) {
// millisec or sec ?
dispatch_after(interval, DispatchQueue.main, block)
}
public func dispatch_after(_ interval: TimeInterval, _ queue: DispatchQueue, _ block: @escaping () -> Void) {
// millisec or sec ?
let precision = interval < 1 ? Double(NSEC_PER_MSEC) : Double(NSEC_PER_SEC)
let adjusted_interval = interval < 1 ? interval * 1000 : interval
let when = DispatchTime.now() + Double(Int64(adjusted_interval * precision)) / Double(NSEC_PER_SEC)
queue.asyncAfter(deadline: when, execute: block)
}
// ---------------------------------------------------------------------------------------------------------------------
// MARK: -
func testDebugPrint(_ someMsg: @autoclosure () -> String?) {
if let msg = someMsg() {
Logger.runningTest(">> \(msg) <<")
}
}
func fetchRandom(_ name: String) -> Thenable {
let p = Promise()
p.name = name
dispatch_after(2) {
testDebugPrint(".... FULFILL fetchRandom \(p)")
p.fulfill(fulfilledValue: arc4random()/100000)
}
testDebugPrint(".... created fetchRandom \(p)")
return p.promise
}
func fetchNotSoRandom(_ name: String, value: Int) -> Thenable {
let p = Promise()
p.name = name
dispatch_after(2) {
testDebugPrint(".... FULFILL fetchNotSoRandom \(p)")
p.fulfill(fulfilledValue: value)
}
testDebugPrint(".... created fetchNotSoRandom \(p)")
return p.promise
}
func failRandom(name: String) -> Thenable {
let p = Promise()
p.name = name
dispatch_after(2) {
testDebugPrint(".... REJECT failRandom \(p)")
p.reject(reasonRejected: thenKitTestsError1)
}
testDebugPrint(".... created failRandom \(p)")
return p.promise
}
func httpGetPromise(someURL: String) -> Thenable {
let p = Promise("HTTP_GET_PROMISE")
guard let url = URL(string: someURL) else {
let badURLErr = NSError(domain: "ThenKitTests.Error.BadURL", code: 100, userInfo: nil)
p.reject(reasonRejected: badURLErr)
return p.promise // rejected promise
}
let request = URLRequest(url: url)
let session = URLSession.shared
let task = session.dataTask(with: request) { (_, response, error) in
if error != nil {
p.reject(reasonRejected: error!)
} else if let r = response as? HTTPURLResponse, r.statusCode < 300 {
// wraps NSData & NSHTTPURLResponse to return
p.fulfill(fulfilledValue: response)
} else {
let r = response as? HTTPURLResponse
let code = r?.statusCode ?? -1
let e = NSError(domain: NSURLErrorDomain, code: code, userInfo: nil)
p.reject(reasonRejected: e)
}
}
task.resume()
return p.promise
}
/** EOF **/
| mit | bd10e018dc2552879f91f4edabc47ecf | 31.581818 | 120 | 0.587333 | 4.114811 | false | true | false | false |
rudkx/swift | test/Concurrency/Runtime/async_properties_actor.swift | 1 | 4865 | // RUN: %target-run-simple-swift(-parse-as-library -Xfrontend -enable-copy-propagation -Xfrontend -enable-lexical-lifetimes=false -Xfrontend -disable-availability-checking %import-libdispatch) | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// rdar://76038845
// REQUIRES: concurrency_runtime
// UNSUPPORTED: back_deployment_runtime
struct Container {
@MainActor static var counter: Int = 10
@MainActor static var this: Container?
var noniso: Int = 20
static func getCount() async -> Int {
return await counter
}
static func getValue() async -> Int? {
return await this?.noniso
}
}
@propertyWrapper
struct SuccessTracker {
private var _stored: Bool
private var numReads : Int = 0 // an unchecked statistic to exercise mutating get
init(initially: Bool) {
self._stored = initially
}
var wrappedValue: Bool {
mutating get {
numReads += 1
return _stored
}
set { _stored = newValue }
}
}
func writeToBool(_ b : inout Bool, _ val : Bool) {
b = val
}
actor List<T : Sendable> {
var head : T
var tail : List<T>?
lazy var hasTail : Bool = (tail != nil)
var computedTail : List<T>? {
get { tail }
}
subscript(_ offset : Int) -> T? {
// since we don't have async subscripts, we just return nil for non-zero inputs! :)
if offset != 0 {
return nil
}
return head
}
/// this silly property is here just for testing wrapped-property access
@SuccessTracker(initially: true) var success : Bool
func setSuccess(_ b : Bool) { writeToBool(&success, b) }
init(_ value : T) {
self.head = value
self.tail = nil
}
init(_ value : T, _ tail : List<T>) {
self.head = value
self.tail = tail
}
func last() async -> T {
switch tail {
case .none:
return head
case .some(let tl):
if await tl.hasTail {
return await tl.last()
}
return await tl.head
}
}
static func tabulate(_ n : Int, _ f : (Int) -> T) -> List<T> {
if n == 0 {
return List<T>(f(n))
}
return List<T>(f(n), tabulate(n-1, f))
}
static func foldr<R>(_ f : (T, R) -> R, _ start : R, _ lst : List<T>) async -> R {
switch await lst.tail {
case .none:
return f(await lst.head, start)
case .some(let tl):
return f(await lst.head, await foldr(f, start, tl))
}
}
}
actor Tester {
/// returns true iff success
func doListTest() async -> Bool {
let n = 4 // if you change this, you'll have to update other stuff too
let ints = List<Int>.tabulate(n, { $0 })
let last1 = await ints.tail!.computedTail!.tail!.tail![0]
let last2 = await ints.last()
guard last1 == last2 else {
print("fail 1")
return false
}
let expected = (n * (n + 1)) / 2
let sum = await List<Int>.foldr({ $0 + $1 }, 0, ints)
guard sum == expected else {
print("fail 2")
return false
}
// CHECK: done list test
// CHECK-NOT: fail
print("done list test")
return true
}
func doPropertyWrapperTest() async -> Bool {
let actor = List<String>("blah")
await actor.setSuccess(false)
guard await actor.success == false else {
print("fail 3")
return false
}
await actor.setSuccess(true)
guard await actor.success == true else {
print("fail 4")
return false
}
// CHECK: done property wrapper test
// CHECK-NOT: fail
print("done property wrapper test")
return true
}
func doContainerTest() async -> Bool {
var total: Int = 0
total += await Container.getCount()
total += await Container.getValue() ?? 0
return total == 10
}
}
@globalActor
struct SillyActor {
actor _Impl {}
static let shared = _Impl()
}
@SillyActor
var test : Tester = Tester()
@SillyActor
var expectedResult : Bool {
get { true }
set {}
}
@main struct RunIt {
static func main() async {
let success = await expectedResult
guard await test.doListTest() == success else {
fatalError("fail list test")
}
guard await test.doPropertyWrapperTest() == success else {
fatalError("fail property wrapper test")
}
guard await test.doContainerTest() == success else {
fatalError("fail container test")
}
// CHECK: done all testing
print("done all testing")
}
}
| apache-2.0 | 4d73fe62b966f53f8cd06819ca8be285 | 22.965517 | 209 | 0.547379 | 4.143952 | false | true | false | false |
jayrparro/iOS11-Examples | Vision/TextDetectionSamp/TextDetectionSamp/ViewController.swift | 1 | 5586 | //
// ViewController.swift
// TextDetectionSamp
//
// Created by Leonardo Parro on 27/7/17.
// Copyright © 2017 Leonardo Parro. All rights reserved.
//
import UIKit
import AVFoundation
import Vision
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var session = AVCaptureSession()
var requests = [VNRequest]()
// MARK: - View Cycle Methods
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
startLiveVideo()
startTextDetection()
}
override func viewDidLayoutSubviews() {
imageView.layer.sublayers?[0].frame = imageView.bounds
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Private Methods
private func startLiveVideo() {
session.sessionPreset = AVCaptureSession.Preset.photo
let captureDevice = AVCaptureDevice.default(for: .video)
let deviceInput = try! AVCaptureDeviceInput(device: captureDevice!)
let deviceOutput = AVCaptureVideoDataOutput()
deviceOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_32BGRA)]
deviceOutput.setSampleBufferDelegate(self, queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.default))
session.addInput(deviceInput)
session.addOutput(deviceOutput)
let imageLayer = AVCaptureVideoPreviewLayer(session: session)
imageLayer.frame = imageView.bounds
imageView.layer.addSublayer(imageLayer)
session.startRunning()
}
private func startTextDetection() {
let textRequest = VNDetectTextRectanglesRequest { (request, error) in
guard let observations = request.results else { return }
let result = observations.map({ $0 as? VNTextObservation })
DispatchQueue.main.async() {
self.imageView.layer.sublayers?.removeSubrange(1...)
for region in result {
guard let rg = region else {
continue
}
self.highlightWord(box: rg)
if let boxes = region?.characterBoxes {
for characterBox in boxes {
self.highlightLetters(box: characterBox)
}
}
}
}
}
textRequest.reportCharacterBoxes = true
self.requests = [textRequest]
}
private func highlightWord(box: VNTextObservation) {
guard let boxes = box.characterBoxes else {
return
}
var maxX: CGFloat = 9999.0
var minX: CGFloat = 0.0
var maxY: CGFloat = 9999.0
var minY: CGFloat = 0.0
for char in boxes {
if char.bottomLeft.x < maxX {
maxX = char.bottomLeft.x
}
if char.bottomRight.x > minX {
minX = char.bottomRight.x
}
if char.bottomRight.y < maxY {
maxY = char.bottomRight.y
}
if char.topRight.y > minY {
minY = char.topRight.y
}
}
let xCord = maxX * imageView.frame.size.width
let yCord = (1 - minY) * imageView.frame.size.height
let width = (minX - maxX) * imageView.frame.size.width
let height = (minY - maxY) * imageView.frame.size.height
let outline = CALayer()
outline.frame = CGRect(x: xCord, y: yCord, width: width, height: height)
outline.borderWidth = 2.0
outline.borderColor = UIColor.red.cgColor
imageView.layer.addSublayer(outline)
}
private func highlightLetters(box: VNRectangleObservation) {
let xCord = box.topLeft.x * imageView.frame.size.width
let yCord = (1 - box.topLeft.y) * imageView.frame.size.height
let width = (box.topRight.x - box.bottomLeft.x) * imageView.frame.size.width
let height = (box.topLeft.y - box.bottomLeft.y) * imageView.frame.size.height
let outline = CALayer()
outline.frame = CGRect(x: xCord, y: yCord, width: width, height: height)
outline.borderWidth = 1.0
outline.borderColor = UIColor.blue.cgColor
imageView.layer.addSublayer(outline)
}
}
// MARK: - AVCaptureVideoDataOutputSampleBufferDelegate
extension ViewController: AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(_ output: AVCaptureOutput,
didOutput sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection) {
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
return
}
var requestOptions:[VNImageOption : Any] = [:]
if let camData = CMGetAttachment(sampleBuffer, kCMSampleBufferAttachmentKey_CameraIntrinsicMatrix, nil) {
requestOptions = [.cameraIntrinsics:camData]
}
let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: 6, options: requestOptions)
do {
try imageRequestHandler.perform(self.requests)
} catch {
print(error)
}
}
}
| mit | 3188d9cd5e42fabc5ae34bbb695797fb | 32.443114 | 124 | 0.585855 | 5.229401 | false | false | false | false |
daniel-barros/TV-Calendar | TraktKit/Common/Shows.swift | 1 | 10872 | //
// Shows.swift
// TraktKit
//
// Created by Maximilian Litteral on 11/26/15.
// Copyright © 2015 Maximilian Litteral. All rights reserved.
//
import Foundation
public enum Period: String {
case Weekly = "weekly"
case Monthly = "monthly"
case All = "all"
}
extension TraktManager {
// MARK: - Trending
/**
Returns all shows being watched right now. Shows with the most users are returned first.
📄 Pagination
*/
@discardableResult
public func getTrendingShows(page: Int, limit: Int, extended: [ExtendedType] = [.Min], completion: @escaping TrendingShowsCompletionHandler) -> URLSessionDataTask? {
return getTrending(.Shows, page: page, limit: limit, extended: extended, completion: completion)
}
// MARK: - Popular
/**
Returns the most popular shows. Popularity is calculated using the rating percentage and the number of ratings.
📄 Pagination
*/
@discardableResult
public func getPopularShows(page: Int, limit: Int, extended: [ExtendedType] = [.Min], completion: @escaping ShowsCompletionHandler) -> URLSessionDataTask? {
return getPopular(.Shows, page: page, limit: limit, extended: extended, completion: completion)
}
// MARK: - Played
/**
Returns the most played (a single user can watch multiple episodes multiple times) shows in the specified time `period`, defaulting to `weekly`. All stats are relative to the specific time `period`.
📄 Pagination
*/
@discardableResult
public func getPlayedShows(page: Int, limit: Int, period: Period = .Weekly, completion: @escaping MostShowsCompletionHandler) -> URLSessionDataTask? {
return getPlayed(.Shows, page: page, limit: limit, period: period, completion: completion)
}
// MARK: - Watched
/**
Returns the most watched (unique users) shows in the specified time `period`, defaulting to `weekly`. All stats are relative to the specific time `period`.
📄 Pagination
*/
@discardableResult
public func getWatchedShows(page: Int, limit: Int, period: Period = .Weekly, completion: @escaping MostShowsCompletionHandler) -> URLSessionDataTask? {
return getWatched(.Shows, page: page, limit: limit, period: period, completion: completion)
}
// MARK: - Collected
/**
Returns the most collected (unique episodes per unique users) shows in the specified time `period`, defaulting to `weekly`. All stats are relative to the specific time `period`.
📄 Pagination
*/
@discardableResult
public func getCollectedShows(page: Int, limit: Int, period: Period = .Weekly, completion: @escaping MostShowsCompletionHandler) -> URLSessionDataTask? {
return getCollected(.Shows, page: page, limit: limit, completion: completion)
}
// MARK: - Anticipated
/**
Returns the most anticipated shows based on the number of lists a show appears on.
📄 Pagination
*/
@discardableResult
public func getAnticipatedShows(page: Int, limit: Int, period: Period = .Weekly, extended: [ExtendedType] = [.Min], completion: @escaping AnticipatedShowCompletionHandler) -> URLSessionDataTask? {
return getAnticipated(.Shows, page: page, limit: limit, extended: extended, completion: completion)
}
// MARK: - Updates
/**
Returns all shows updated since the specified date. We recommended storing the date you can be efficient using this method moving forward.
📄 Pagination
*/
@discardableResult
public func getUpdatedShows(page: Int, limit: Int, startDate: Date?, completion: @escaping ArrayCompletionHandler) -> URLSessionDataTask? {
return getUpdated(.Shows, page: page, limit: limit, startDate: startDate, completion: completion)
}
// MARK: - Summary
/**
Returns a single shows's details. If you get extended info, the `airs` object is relative to the show's country. You can use the `day`, `time`, and `timezone` to construct your own date then convert it to whatever timezone your user is in.
**Note**: When getting `full` extended info, the `status` field can have a value of `returning series` (airing right now), `in production` (airing soon), `planned` (in development), `canceled`, or `ended`.
*/
@discardableResult
public func getShowSummary<T: CustomStringConvertible>(showID id: T, extended: [ExtendedType] = [.Min], completion: @escaping ShowCompletionHandler) -> URLSessionDataTask? {
return getSummary(.Shows, id: id, extended: extended, completion: completion)
}
// MARK: - Aliases
/**
Returns all title aliases for a show. Includes country where name is different.
- parameter id: Trakt.tv ID, Trakt.tv slug, or IMDB ID
*/
@discardableResult
public func getShowAliases<T: CustomStringConvertible>(showID id: T, completion: @escaping ArrayCompletionHandler) -> URLSessionDataTask? {
return getAliases(.Shows, id: id, completion: completion)
}
// MARK: - Translations
/**
Returns all translations for a show, including language and translated values for title and overview.
- parameter id: Trakt.tv ID, Trakt.tv slug, or IMDB ID
- parameter language: 2 character language code. Example: `es`
*/
@discardableResult
public func getShowTranslations<T: CustomStringConvertible>(showID id: T, language: String?, completion: @escaping ShowTranslationsCompletionHandler) -> URLSessionDataTask? {
return getTranslations(.Shows, id: id, language: language, completion: completion)
}
// MARK: - Comments
/**
Returns all top level comments for a show. Most recent comments returned first.
📄 Pagination
*/
@discardableResult
public func getShowComments<T: CustomStringConvertible>(showID id: T, completion: @escaping CommentsCompletionHandler) -> URLSessionDataTask? {
return getComments(.Shows, id: id, completion: completion)
}
// MARK: - Collection Progress
/**
Returns collection progress for show including details on all seasons and episodes. The `next_episode` will be the next episode the user should collect, if there are no upcoming episodes it will be set to `null`. By default, any hidden seasons will be removed from the response and stats. To include these and adjust the completion stats, set the `hidden` flag to `true`.
🔒 OAuth: Required
*/
@discardableResult
public func getShowCollectionProgress<T: CustomStringConvertible>(showID id: T, hidden: Bool = false, specials: Bool = false, completion: @escaping ResultCompletionHandler) -> URLSessionDataTask? {
guard
let request = mutableRequest(forPath: "shows/\(id)/progress/collection",
withQuery: ["hidden": "\(hidden)",
"specials": "\(specials)"],
isAuthorized: true,
withHTTPMethod: .GET) else { return nil }
return performRequest(request: request, expectingStatusCode: StatusCodes.Success, completion: completion)
}
// MARK: - Watched Progress
/**
Returns watched progress for show including details on all seasons and episodes. The `next_episode` will be the next episode the user should watch, if there are no upcoming episodes it will be set to `null`. By default, any hidden seasons will be removed from the response and stats. To include these and adjust the completion stats, set the `hidden` flag to `true`.
🔒 OAuth: Required
*/
@discardableResult
public func getShowWatchedProgress<T: CustomStringConvertible>(showID id: T, hidden: Bool = false, specials: Bool = false, completion: @escaping ShowWatchedProgressCompletionHandler) -> URLSessionDataTask? {
guard
let request = mutableRequest(forPath: "shows/\(id)/progress/watched",
withQuery: ["hidden": "\(hidden)",
"specials": "\(specials)"],
isAuthorized: true,
withHTTPMethod: .GET) else { return nil }
return performRequest(request: request, expectingStatusCode: StatusCodes.Success, completion: completion)
}
// MARK: - People
/**
Returns all `cast` and `crew` for a show. Each `cast` member will have a `character` and a standard `person` object.
The `crew` object will be broken up into `production`, `art`, `crew`, `costume & make-up`, `directing`, `writing`, `sound`, and `camera` (if there are people for those crew positions). Each of those members will have a `job` and a standard `person` object.
*/
@discardableResult
public func getPeopleInShow<T: CustomStringConvertible>(showID id: T, extended: [ExtendedType] = [.Min], completion: @escaping CastCrewCompletionHandler) -> URLSessionDataTask? {
return getPeople(.Shows, id: id, extended: extended, completion: completion)
}
// MARK: - Ratings
/**
Returns rating (between 0 and 10) and distribution for a show.
*/
@discardableResult
public func getShowRatings<T: CustomStringConvertible>(showID id: T, completion: @escaping ResultCompletionHandler) -> URLSessionDataTask? {
return getRatings(.Shows, id: id, completion: completion)
}
// MARK: - Related
/**
Returns related and similar shows. By default, 10 related shows will returned. You can send a `limit` to get up to `100` items.
**Note**: We are continuing to improve this algorithm.
*/
@discardableResult
public func getRelatedShows<T: CustomStringConvertible>(showID id: T, extended: [ExtendedType] = [.Min], completion: @escaping ShowsCompletionHandler) -> URLSessionDataTask? {
return getRelated(.Shows, id: id, extended: extended, completion: completion)
}
// MARK: - Stats
/**
Returns lots of show stats.
*/
@discardableResult
public func getShowStatistics<T: CustomStringConvertible>(showID id: T, completion: @escaping statsCompletionHandler) -> URLSessionDataTask? {
return getStatistics(.Shows, id: id, completion: completion)
}
// MARK: - Watching
/**
Returns all users watching this show right now.
*/
@discardableResult
public func getUsersWatchingShow<T: CustomStringConvertible>(showID id: T, completion: @escaping ArrayCompletionHandler) -> URLSessionDataTask? {
return getUsersWatching(.Shows, id: id, completion: completion)
}
}
| gpl-3.0 | ec2ce362aa872d5ad91238f028bb887f | 43.983402 | 376 | 0.663223 | 4.984368 | false | false | false | false |
AaronMT/firefox-ios | ClientTests/TabEventHandlerTests.swift | 7 | 1164 | /* 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
@testable import Client
import WebKit
import XCTest
class TabEventHandlerTests: XCTestCase {
func testEventDelivery() {
let tab = Tab(bvc: BrowserViewController.foregroundBVC(), configuration: WKWebViewConfiguration())
let handler = DummyHandler()
XCTAssertNil(handler.isFocused)
TabEvent.post(.didGainFocus, for: tab)
XCTAssertTrue(handler.isFocused!)
TabEvent.post(.didLoseFocus, for: tab)
XCTAssertFalse(handler.isFocused!)
}
}
class DummyHandler: TabEventHandler {
// This is not how this should be written in production — the handler shouldn't be keeping track
// of individual tab state.
var isFocused: Bool? = nil
init() {
register(self, forTabEvents: .didGainFocus, .didLoseFocus)
}
func tabDidGainFocus(_ tab: Tab) {
isFocused = true
}
func tabDidLoseFocus(_ tab: Tab) {
isFocused = false
}
}
| mpl-2.0 | ff61095fcc8925aaf529a6dfd627f24c | 25.409091 | 106 | 0.67642 | 4.539063 | false | true | false | false |
edwinyoung/flickster | Flickster/MoviesViewController.swift | 1 | 5030 | //
// MoviesViewController.swift
// Flickster
//
// Created by Edwin Young on 1/26/17.
// Copyright © 2017 Test Org Pls Ignore. All rights reserved.
//
import UIKit
import AFNetworking
class MoviesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var loadingView: UIView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var splashLoading: UIActivityIndicatorView!
var movies : [NSDictionary]?
var endpoint : String!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.splashLoading.startAnimating()
// Initialize a UIRefreshControl
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refreshControlAction(_:)), for: UIControlEvents.valueChanged)
// add refresh control to table view
tableView.insertSubview(refreshControl, at: 0)
tableView.dataSource = self
tableView.delegate = self
let apiKey = "8c196c3c0b660eff61aa8b14f87d402e"
let url = URL(string: "https://api.themoviedb.org/3/movie/\(endpoint!)?api_key=\(apiKey)")!
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
let task: URLSessionDataTask = session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if let data = data {
if let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
print(dataDictionary)
self.movies = dataDictionary["results"] as! [NSDictionary]
self.tableView.reloadData()
self.splashLoading.stopAnimating()
self.loadingView.alpha = 0
}
}
}
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let movies = movies {
return movies.count
} else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MovieCell", for: indexPath) as! MovieCell
let movie = movies![indexPath.row]
let title = movie["title"] as! String
let overview = movie["overview"] as! String
cell.titleLabel.text = title
cell.overviewLabel.text = overview
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.blue
cell.selectedBackgroundView = backgroundView
if let posterPath = movie["poster_path"] as? String {
let baseImgUrl = "https://image.tmdb.org/t/p/w500"
let imgUrl = URL(string: baseImgUrl + posterPath)
cell.posterView.setImageWith(imgUrl!)
print(imgUrl?.absoluteString)
}
return cell
}
// Makes a network request to get updated data
// Updates the tableView with the new data
// Hides the RefreshControl
func refreshControlAction(_ refreshControl: UIRefreshControl) {
// ... Create the URLRequest ...
let apiKey = "8c196c3c0b660eff61aa8b14f87d402e"
let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=\(apiKey)")!
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
// Configure session so that completion handler is executed on main UI thread
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
let task: URLSessionDataTask = session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
// ... Use the new data to update the data source ...
if let data = data {
if let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
print(dataDictionary)
self.movies = dataDictionary["results"] as! [NSDictionary]
self.tableView.reloadData()
}
}
// Reload the tableView now that there is new data
self.tableView.reloadData()
// Tell the refreshControl to stop spinning
refreshControl.endRefreshing()
}
task.resume()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let cell = sender as! UITableViewCell
let indexPath = tableView.indexPath(for: cell)
let movie = movies![indexPath!.row]
let detailViewController = segue.destination as! DetailViewController
detailViewController.movie = movie
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
}
| apache-2.0 | 718e3af2911b9ad91dedec0e9d907b50 | 33.210884 | 122 | 0.725989 | 4.156198 | false | false | false | false |
codeforgreenville/trolley-tracker-ios-client | TrolleyTracker/Models/TrolleyStop.swift | 1 | 2099 | //
// TrolleyStop.swift
// TrolleyTracker
//
// Created by Austin Younts on 6/16/15.
// Copyright (c) 2015 Code For Greenville. All rights reserved.
//
import Foundation
import MapKit
/// Represents a point where the Trolleys stop for passengers.
class TrolleyStop: NSObject {
let stopID: Int
let name: String
let stopDescription: String
let nextTrolleyArrivals: [TrolleyArrivalTime]
let color: UIColor
private let _coordinate: Coordinate
var location: CLLocation {
return _coordinate.location
}
init(name: String,
latitude: Double,
longitude: Double,
description: String,
ID: Int,
lastTrolleyArrivals: [Int: String],
color: UIColor) {
self.name = name
self._coordinate = Coordinate(latitude: latitude, longitude: longitude)
self.stopDescription = description
self.stopID = ID
self.nextTrolleyArrivals = TrolleyArrivalTime.from(lastTrolleyArrivals)
self.color = color
}
override func isEqual(_ object: Any?) -> Bool {
if let object = object as? TrolleyStop , object.stopID == self.stopID { return true }
return false
}
}
extension TrolleyStop: MKAnnotation {
var coordinate: CLLocationCoordinate2D {
return location.coordinate
}
var title: String? {
return name
}
var subtitle: String? {
return ""
}
}
struct TrolleyArrivalTime {
let trolleyID: Int
let date: Date
private static var formatter: DateFormatter = {
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
return df
}()
static func from(_ values: [Int : String]) -> [TrolleyArrivalTime] {
return values.compactMap {
let string = Array($0.1.components(separatedBy: ".")).dropLast().joined()
guard let date = TrolleyArrivalTime.formatter.date(from: string) else {
return nil
}
return TrolleyArrivalTime(trolleyID: $0.key, date: date)
}
}
}
| mit | 1b32dd1e3205a24efb33a3305cc2cb22 | 23.988095 | 93 | 0.617437 | 4.465957 | false | false | false | false |
VanHack/binners-project-ios | ios-binners-project/BPPageContainerLoginDescriptionViewController.swift | 1 | 4973 | //
// BPPageContainerLoginDescriptionViewController.swift
// ios-binners-project
//
// Created by Matheus Ruschel on 2/2/16.
// Copyright © 2016 Rodrigo de Souza Reis. All rights reserved.
import UIKit
protocol PageControlDataSource {
var pageIndex: Int? {get set}
}
class BPPageContainerLoginDescriptionViewController: UIViewController, UIPageViewControllerDataSource {
@IBOutlet weak var skipButton: UIButton!
var pageViewController: UIPageViewController?
var pages = 3
override func viewDidLoad() {
super.viewDidLoad()
self.pageViewController = self.storyboard?.instantiateViewController(withIdentifier: "ProjectDescriptionPageViewController")
as? UIPageViewController
self.pageViewController!.dataSource = self
let startingViewController = self.viewControllerAtIndex(0)!
let viewControllers = [startingViewController]
self.pageViewController?.setViewControllers(
viewControllers,
direction: .forward,
animated: true,
completion: nil)
self.pageViewController!.view.backgroundColor = UIColor.binnersGreenColor()
self.addChildViewController(self.pageViewController!)
self.view.addSubview(self.pageViewController!.view)
self.pageViewController!.didMove(toParentViewController: self)
// configure skip button font
self.skipButton.tintColor = UIColor.binnersSkipButtonColor()
self.skipButton.titleLabel?.font = UIFont.binnersFont()
self.view.bringSubview(toFront: self.skipButton)
// configure page control
let pageControl = UIPageControl.appearance()
pageControl.pageIndicatorTintColor = UIColor.binnersSkipButtonColor()
pageControl.currentPageIndicatorTintColor = UIColor.white
pageControl.backgroundColor = UIColor.clear
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func skipButtonPressed(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerAfter
viewController: UIViewController) -> UIViewController? {
let index = (viewController as? PageControlDataSource)?.pageIndex
guard var indexUw = index else {
return nil
}
indexUw += 1
if indexUw == self.pages {
return nil
}
return self.viewControllerAtIndex(indexUw)
}
func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerBefore
viewController: UIViewController) -> UIViewController? {
let index = (viewController as? PageControlDataSource)?.pageIndex
guard var indexUw = index else {
return nil
}
if indexUw == self.pages {
return nil
}
indexUw -= 1
return self.viewControllerAtIndex(indexUw)
}
func viewControllerAtIndex(_ index: Int) -> UIViewController?
{
var pageContentVC: UIViewController?
switch index {
case 0: pageContentVC = self.storyboard?.instantiateViewController(
withIdentifier: "PageTwoContentDescriptionViewController")
as? BPPageTwoContentDescriptionLoginViewController
case 1: pageContentVC = self.storyboard?.instantiateViewController(
withIdentifier: "PageThreeContentDescriptionViewController")
as? BPPageThreeContentDescriptionLoginViewController
case 2: pageContentVC = self.storyboard?.instantiateViewController(
withIdentifier: "PageFourContentDescriptionViewController")
as? BPPageFourContentDescriptionLoginViewController
default: pageContentVC = nil
}
if var page = pageContentVC as? PageControlDataSource {
page.pageIndex = index
}
return pageContentVC
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return self.pages
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return 0
}
/*
// 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 | 9711fb409d5d2feb92a424e92405e5cd | 30.871795 | 132 | 0.644409 | 6.374359 | false | false | false | false |
blokadaorg/blokada | ios/App/Repository/AppRepo.swift | 1 | 7824 | //
// This file is part of Blokada.
//
// 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 https://mozilla.org/MPL/2.0/.
//
// Copyright © 2021 Blocka AB. All rights reserved.
//
// @author Karol Gusak
//
import Foundation
import Combine
import UIKit
// Contains "main app state" mostly used in Home screen.
class AppRepo: Startable {
var appStateHot: AnyPublisher<AppState, Never> {
self.writeAppState.compactMap { $0 }.removeDuplicates().eraseToAnyPublisher()
}
var workingHot: AnyPublisher<Bool, Never> {
self.writeWorking.compactMap { $0 }.removeDuplicates().eraseToAnyPublisher()
}
var pausedUntilHot: AnyPublisher<Date?, Never> {
self.writePausedUntil.removeDuplicates().eraseToAnyPublisher()
}
var accountTypeHot: AnyPublisher<AccountType, Never> {
self.writeAccountType.compactMap { $0 }.removeDuplicates().eraseToAnyPublisher()
}
private lazy var timer = Services.timer
private lazy var currentlyOngoingHot = Repos.processingRepo.currentlyOngoingHot
private lazy var accountHot = Repos.accountRepo.accountHot
private lazy var cloudRepo = Repos.cloudRepo
fileprivate let writeAppState = CurrentValueSubject<AppState?, Never>(nil)
fileprivate let writeWorking = CurrentValueSubject<Bool?, Never>(nil)
fileprivate let writePausedUntil = CurrentValueSubject<Date?, Never>(nil)
fileprivate let writeAccountType = CurrentValueSubject<AccountType?, Never>(nil)
fileprivate let pauseAppT = Tasker<Date?, Ignored>("pauseApp")
fileprivate let unpauseAppT = SimpleTasker<Ignored>("unpauseApp")
private var cancellables = Set<AnyCancellable>()
private let recentAccountType = Atomic<AccountType>(AccountType.Libre)
func start() {
onPauseApp()
onUnpauseApp()
onAnythingThatAffectsAppState_UpdateIt()
onAccountChange_UpdateAccountType()
onCurrentlyOngoing_ChangeWorkingState()
onPause_WaitForExpirationToUnpause()
loadPauseTimerState()
emitWorkingStateOnStart()
}
func pauseApp(until: Date?) -> AnyPublisher<Ignored, Error> {
return pauseAppT.send(until)
}
func unpauseApp() -> AnyPublisher<Ignored, Error> {
return unpauseAppT.send()
}
// App can be paused with a timer (Date), or indefinitely (nil)
private func onPauseApp() { // TODO: also pause plus
pauseAppT.setTask { until in
return self.appStateHot.first()
.flatMap { it -> AnyPublisher<Ignored, Error> in
// App is already paused, only update timer
if it == .Paused {
guard let until = until else {
// Pause indefinitely instead
return self.timer.cancelTimer(NOTIF_PAUSE)
}
return self.timer.createTimer(NOTIF_PAUSE, when: until)
} else if it == .Activated {
guard let until = until else {
// Just pause indefinitely
return self.cloudRepo.setPaused(true)
}
return self.cloudRepo.setPaused(true)
.flatMap { _ in self.timer.createTimer(NOTIF_PAUSE, when: until) }
.eraseToAnyPublisher()
} else {
return Fail(error: "cannot pause, app in wrong state")
.eraseToAnyPublisher()
}
}
.map { _ in
self.writePausedUntil.send(until)
return true
}
.eraseToAnyPublisher()
}
}
private func onUnpauseApp() {
unpauseAppT.setTask { _ in
return self.appStateHot.first()
.flatMap { it -> AnyPublisher<Ignored, Error> in
if it == .Paused || it == .Deactivated {
return self.cloudRepo.setPaused(false)
.flatMap { _ in self.timer.cancelTimer(NOTIF_PAUSE) }
.eraseToAnyPublisher()
} else {
return Fail(error: "cannot unpause, app in wrong state")
.eraseToAnyPublisher()
}
}
.map { _ in
self.writePausedUntil.send(nil)
return true
}
.eraseToAnyPublisher()
}
}
private func onAnythingThatAffectsAppState_UpdateIt() {
Publishers.CombineLatest4(
accountTypeHot,
pausedUntilHot,
cloudRepo.dnsProfileActivatedHot,
cloudRepo.adblockingPausedHot
)
.map { it -> AppState in
let (accountType, pausedUntil, dnsProfileActivated, adblockingPaused) = it
if !accountType.isActive() {
return AppState.Deactivated
}
if adblockingPaused && pausedUntil != nil {
return AppState.Paused
}
if adblockingPaused {
return AppState.Deactivated
}
if dnsProfileActivated {
return AppState.Activated
}
return AppState.Deactivated
}
.sink(onValue: { it in self.writeAppState.send(it) })
.store(in: &cancellables)
}
private func onAccountChange_UpdateAccountType() {
accountHot.compactMap { it in it.account.type }
.map { it in mapAccountType(it) }
.sink(onValue: { it in
self.recentAccountType.value = it
self.writeAccountType.send(it)
})
.store(in: &cancellables)
}
private func onCurrentlyOngoing_ChangeWorkingState() {
let tasksThatMarkWorkingState = Set([
"accountInit", "refreshAccount", "restoreAccount",
"pauseApp", "unpauseApp",
"newPlus", "clearPlus", "switchPlusOn", "switchPlusOff",
"consumePurchase"
])
currentlyOngoingHot
.map { it in Set(it.map { $0.component }) }
.map { it in !it.intersection(tasksThatMarkWorkingState).isEmpty }
.sink(onValue: { it in self.writeWorking.send(it) })
.store(in: &cancellables)
}
private func onPause_WaitForExpirationToUnpause() {
pausedUntilHot
.compactMap { $0 }
.flatMap { _ in
// This cold producer will finish once the timer expires.
// It will error out whenever this timer is modified.
self.timer.obtainTimer(NOTIF_PAUSE)
}
.flatMap { _ in
self.unpauseApp()
}
.sink(
onFailure: { err in Logger.w("AppRepo", "Pause timer failed: \(err)")}
)
.store(in: &cancellables)
}
private func loadPauseTimerState() {
timer.getTimerDate(NOTIF_PAUSE)
.tryMap { it in self.writePausedUntil.send(it) }
.sink()
.store(in: &cancellables)
}
private func emitWorkingStateOnStart() {
writeAppState.send(.Deactivated)
writeWorking.send(true)
}
}
func getDateInTheFuture(seconds: Int) -> Date {
let date = Date()
var components = DateComponents()
components.setValue(seconds, for: .second)
let dateInTheFuture = Calendar.current.date(byAdding: components, to: date)
return dateInTheFuture!
}
class DebugAppRepo: AppRepo {
private let log = Logger("App")
private var cancellables = Set<AnyCancellable>()
override func start() {
super.start()
writeAppState.sink(
onValue: { it in
self.log.v("App state: \(it)")
}
)
.store(in: &cancellables)
}
}
| mpl-2.0 | 0da5a9a31abe391d59e169f96f2db287 | 31.732218 | 88 | 0.587498 | 4.784709 | false | false | false | false |
A-Kod/vkrypt | Pods/SwiftyVK/Library/Sources/Sessions/SessionState.swift | 4 | 576 | /// State of user session
/// initiated: Session is created and user not authorized ywt
/// authorized: Session is created and user authorized
/// destroyed: User logged out and session destroyed
public enum SessionState: Int, Comparable, Codable {
case destroyed = -1
case initiated = 0
case authorized = 1
public static func == (lhs: SessionState, rhs: SessionState) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static func < (lhs: SessionState, rhs: SessionState) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
| apache-2.0 | c35c14504e77783b9d02548a9eb31811 | 32.882353 | 74 | 0.678819 | 4.645161 | false | false | false | false |
ennioma/arek | Example/arek_example/ArekCellVMServiceProgrammatically.swift | 1 | 7846 | //
// ArekCellVMServiceProgrammatically.swift
// arek_example
//
// Copyright (c) 2016 Ennio Masi
//
// 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 arek
import HealthKit
class ArekCellVMServiceProgrammatically {
static private var permissions = [
["popupDataTitle": "Media Library Access - native", "allowButtonTitle": "Allow 👍🏼", "denyButtonTitle": "No! 👎🏼", "enableTitle": "Please!", "reEnableTitle": "Re-enable please!"],
["popupDataTitle": "Camera Access - PMAlertController", "allowButtonTitle": "Allow 👍🏼", "denyButtonTitle": "No! 👎🏼", "enableTitle": "Please!", "reEnableTitle": "Re-enable please!"],
["popupDataTitle": "Location Always Access - native", "allowButtonTitle": "Allow 👍🏼", "denyButtonTitle": "No! 👎🏼", "enableTitle": "Please!", "reEnableTitle": "Re-enable please!"],
["popupDataTitle": "Motion - PMAlertController", "allowButtonTitle": "Allow 👍🏼", "denyButtonTitle": "No! 👎🏼", "enableTitle": "Please!", "reEnableTitle": "Re-enable please!"],
["popupDataTitle": "Notification - native", "allowButtonTitle": "Allow 👍🏼", "denyButtonTitle": "No! 👎🏼", "enableTitle": "Please!", "reEnableTitle": "Re-enable please!"],
["popupDataTitle": "Health - PMAlertController", "allowButtonTitle": "Allow 👍🏼", "denyButtonTitle": "No! 👎🏼", "enableTitle": "Please!", "reEnableTitle": "Re-enable please!"]
]
static func numberOfVMs() -> Int {
return self.permissions.count
}
static func buildVM(index: Int) -> ArekCellVM {
let data = permissions[index]
let configuration = ArekConfiguration(frequency: .Always, presentInitialPopup: true, presentReEnablePopup: true)
let initialPopupData = ArekPopupData(title: data["popupDataTitle"]!,
message: data["enableTitle"]!,
image: "",
allowButtonTitle: data["allowButtonTitle"]!,
denyButtonTitle: data["denyButtonTitle"]!,
type: getPopupType(index: index),
styling: ArekPopupStyle(cornerRadius: 0.9,
maskBackgroundColor: UIColor.lightGray,
maskBackgroundAlpha: 1.0,
titleTextColor: UIColor.green,
titleFont: nil,
descriptionFont: nil,
descriptionLineHeight: nil,
headerViewHeightConstraint: nil,
allowButtonTitleColor: nil,
allowButtonTitleFont: nil,
denyButtonTitleColor: UIColor.brown,
denyButtonTitleFont: nil,
headerViewTopSpace: 20,
descriptionLeftSpace: 20,
descriptionRightSpace: 20,
descriptionTopSpace: 20,
buttonsLeftSpace: 0,
buttonsRightSpace: 0,
buttonsTopSpace: 20,
buttonsBottomSpace: 0))
let reenablePopupData = ArekPopupData(title: data["popupDataTitle"]!, message: data["reEnableTitle"]!, image: "", allowButtonTitle: data["allowButtonTitle"]!, denyButtonTitle: data["denyButtonTitle"]!, type: getPopupType(index: index), styling: nil)
let permission = getPermissionType(index: index, configuration: configuration, initialPopupData: initialPopupData, reEnablePopupData: reenablePopupData)
return ArekCellVM(permission: permission!, title: data["popupDataTitle"]!)
}
static private func getPopupType(index: Int) -> ArekPopupType {
switch index {
case 0, 2, 4:
return .native
case 1, 3, 5:
return .codeido
default:
return .native
}
}
static private func getPermissionType(index: Int, configuration: ArekConfiguration, initialPopupData: ArekPopupData, reEnablePopupData: ArekPopupData) -> ArekPermissionProtocol? {
switch index {
case 0:
return ArekMediaLibrary(configuration: configuration, initialPopupData: initialPopupData, reEnablePopupData: reEnablePopupData)
case 1:
return ArekCamera(configuration: configuration, initialPopupData: initialPopupData, reEnablePopupData: reEnablePopupData)
case 2:
return ArekLocationAlways(configuration: configuration, initialPopupData: initialPopupData, reEnablePopupData: reEnablePopupData)
case 3:
return ArekMotion(configuration: configuration, initialPopupData: initialPopupData, reEnablePopupData: reEnablePopupData)
case 4:
return ArekNotifications(configuration: configuration, initialPopupData: initialPopupData, reEnablePopupData: reEnablePopupData)
case 5:
let myType = HKObjectType.activitySummaryType()
var dataToRead = Set<HKObjectType>()
dataToRead.insert(HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.dateOfBirth)!)
let heightType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height)!
let weightType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)!
let dataToShare: Set<HKSampleType> = [heightType, weightType]
return ArekHealth(configuration: configuration, initialPopupData: initialPopupData, reEnablePopupData: reEnablePopupData, arekHealthConfiguration: ArekHealth.ArekHealthConfiguration(hkObjectType: myType, hkSampleTypesToShare: dataToShare, hkSampleTypesToRead: dataToRead))
default:
return nil
}
}
}
| mit | d38fba7bebebf3fe62c8406df6941e7e | 63.783333 | 284 | 0.573579 | 6.304947 | false | true | false | false |
julienbodet/wikipedia-ios | Wikipedia/Code/EnumCollection.swift | 1 | 742 | public protocol EnumCollection: Hashable {
static func cases() -> AnySequence<Self>
static var allCases: [Self] { get }
}
public extension EnumCollection {
public static func cases() -> AnySequence<Self> {
return AnySequence { () -> AnyIterator<Self> in
var raw = 0
return AnyIterator {
let current: Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: self, capacity: 1) { $0.pointee } }
guard current.hashValue == raw else {
return nil
}
raw += 1
return current
}
}
}
public static var allCases: [Self] {
return Array(self.cases())
}
}
| mit | 488d711cba684e34be6485d5a9c47263 | 28.68 | 126 | 0.526954 | 4.849673 | false | false | false | false |
alessandrostone/RealmObjectEditor | Realm Object Editor/AttributeType.swift | 4 | 3894 | //
// TypeDescriptor.swift
// Realm Object Editor
//
// Created by Ahmed Ali on 12/26/14.
// Copyright (c) 2014 Ahmed Ali. All rights reserved.
//
//Supported types
//BOOL, bool, int, NSInteger, long, long long, float, double, CGFloat, NSString, NSDate, and NSData
import Foundation
//var allTypeStrings : [String]{
// return ["Undefined",
// "Bool",
// "Int",
// "Long",
// "Float",
// "Double",
// "String",
// "NSDate",
// "NSData"]
//}
//MARK: - Helpers
let NoDefaultValue = "<!#NoDefault#!>"
let arrayOfSupportedTypes : [TypeDescriptor] = [InvalidType(),
IntType(),
LongType(),
FloatType(),
DoubleType(),
StringType(),
DateType(),
BinaryDataType()]
func indexOfType(type : TypeDescriptor) -> Int?
{
for i in 0 ..< arrayOfSupportedTypes.count{
let t = arrayOfSupportedTypes[i]
if t.techName == type.techName{
return i
}
}
return nil
}
func supportedTypesAsStringsArray() -> [String]
{
let typesAsStrings = arrayOfSupportedTypes.map {
(type) -> String in
type.typeName
}
return typesAsStrings
}
func findTypeByTypeName(typeName: String) -> TypeDescriptor?
{
for type in arrayOfSupportedTypes{
if type.typeName == typeName{
return type
}
}
return nil
}
//MARK: - Types
@objc protocol TypeDescriptor {
var typeName : String {get}
var techName : String {get}
var canBePrimaryKey : Bool {get}
var defaultValue : String {get}
}
class BaseType : NSObject, TypeDescriptor
{
var typeName : String {
return "undefined"
}
var techName : String{
return "undefined"
}
var defaultValue : String{
return NoDefaultValue
}
var canBePrimaryKey : Bool{
return false
}
}
class InvalidType : BaseType
{
}
class BoolType : BaseType
{
override var typeName : String {
return "Bool"
}
override var techName : String{
return "boolType"
}
override var defaultValue : String{
return "false"
}
}
class IntType : BaseType
{
override var typeName : String {
return "Integer"
}
override var techName : String{
return "intType"
}
override var canBePrimaryKey : Bool{
return true
}
override var defaultValue : String{
return "0"
}
}
class LongType : BaseType
{
override var typeName : String {
return "Long"
}
override var techName : String{
return "longType"
}
override var defaultValue : String{
return "0"
}
}
class FloatType : BaseType
{
override var typeName : String {
return "Float"
}
override var techName : String{
return "floatType"
}
override var defaultValue : String{
return "0.0"
}
}
class DoubleType : BaseType
{
override var typeName : String {
return "Double"
}
override var techName : String{
return "doubleType"
}
override var defaultValue : String{
return "0"
}
}
class StringType : BaseType
{
override var typeName : String {
return "String"
}
override var techName : String{
return "stringType"
}
override var defaultValue : String{
return ""
}
override var canBePrimaryKey : Bool{
return true
}
}
class DateType : BaseType
{
override var typeName : String {
return "Date"
}
override var techName : String{
return "dateType"
}
}
class BinaryDataType : BaseType
{
override var typeName : String {
return "Binary Data"
}
override var techName : String{
return "dataType"
}
}
| mit | 0b1e37c95c8b486c58a016779765d601 | 15.641026 | 99 | 0.570108 | 4.302762 | false | false | false | false |
wesj/firefox-ios-1 | Utils/Prefs.swift | 1 | 2376 | /* 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 Prefs {
func setLong(value: Int64, forKey defaultName: String)
func setObject(value: AnyObject?, forKey defaultName: String)
func stringForKey(defaultName: String) -> String?
func boolForKey(defaultName: String) -> Bool?
func longForKey(defaultName: String) -> Int64?
func stringArrayForKey(defaultName: String) -> [String]?
func arrayForKey(defaultName: String) -> [AnyObject]?
func dictionaryForKey(defaultName: String) -> [String : AnyObject]?
func removeObjectForKey(defaultName: String)
func clearAll()
}
public class MockProfilePrefs : Prefs {
var things: NSMutableDictionary = NSMutableDictionary()
public init() {
}
public func setLong(value: Int64, forKey defaultName: String) {
setObject(NSNumber(longLong: value), forKey: defaultName)
}
public func setObject(value: AnyObject?, forKey defaultName: String) {
things[defaultName] = value
}
public func stringForKey(defaultName: String) -> String? {
return things[defaultName] as? String
}
public func boolForKey(defaultName: String) -> Bool? {
return things[defaultName] as? Bool
}
public func longForKey(defaultName: String) -> Int64? {
let num = things[defaultName] as? NSNumber
if let num = num {
return num.longLongValue
}
return nil
}
public func stringArrayForKey(defaultName: String) -> [String]? {
return self.arrayForKey(defaultName) as [String]?
}
public func arrayForKey(defaultName: String) -> [AnyObject]? {
let r: AnyObject? = things.objectForKey(defaultName)
if (r == nil) {
return nil
}
if let arr = r as? [AnyObject] {
return arr
}
return nil
}
public func dictionaryForKey(defaultName: String) -> [String : AnyObject]? {
return things.objectForKey(defaultName) as? [String: AnyObject]
}
public func removeObjectForKey(defaultName: String) {
self.things[defaultName] = nil
}
public func clearAll() {
self.things.removeAllObjects()
}
}
| mpl-2.0 | 723faf9cd556613f594f2f7d5294811d | 30.263158 | 80 | 0.65404 | 4.622568 | false | false | false | false |
adrfer/swift | validation-test/compiler_crashers_fixed/00371-swift-archetypetype-setnestedtypes.swift | 3 | 654 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func g<H : T! {
b
self.E == A> {
typealias R = b: a {
struct d<T
}
return nil
class func g.E == c> T! {
}
static let t: d = b<T>) -> Int = b
}
protocol P {
typealias e : a {
protocol a {
c(self.b = nil
if true {
func call(array: e: c: T where H.e where H.a
func b
}
typealias F = a
func call(x: A()
}
[T>("")("")
S<U : Int
}
struct S<T>) -> Int = nil
}
let d.B<T
convenience init(self)
class C<T, AnyObject, f()
}
}(f: A")
class func a
re
| apache-2.0 | 7af37405a8bd856d43b65bf648739db2 | 15.35 | 87 | 0.62844 | 2.647773 | false | false | false | false |
ChrisAU/Papyrus | Papyrus/ViewControllers/PreferencesDataSource.swift | 2 | 3246 | //
// PreferencesDataSource.swift
// Papyrus
//
// Created by Chris Nevin on 30/07/2017.
// Copyright © 2017 CJNevin. All rights reserved.
//
import UIKit
class PreferencesDataSource : NSObject, UITableViewDataSource, UITableViewDelegate {
private let preferences: Preferences
init(preferences: Preferences = .sharedInstance) {
self.preferences = preferences
}
func value(for section: Int) -> Int {
return preferences.values[section]!
}
func setValue(for section: Int, value: Int) {
preferences.values[section] = value
}
func setValue(to indexPath: IndexPath) {
setValue(for: indexPath.section, value: indexPath.row)
}
func section(at index: Int) -> [String: [String]] {
return preferences.sections[index]
}
func numberOfSections(in tableView: UITableView) -> Int {
return preferences.sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section < 4 {
return 1
}
let rows = self.section(at: section).values.first!.count
return rows
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.section(at: section).keys.first!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
return tableView.bounds.width
} else if indexPath.section < 4 {
return 80
}
return 44
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell: BoardCell = tableView.dequeueCell(at: indexPath)
cell.configure(index: value(for: indexPath.section))
return cell
} else if indexPath.section < 4 {
let cell: SliderCell = tableView.dequeueCell(at: indexPath)
cell.configure(index: value(for: indexPath.section),
values: section(at: indexPath.section).values.first!,
onChange: { [weak self] newIndex in
self?.setValue(for: indexPath.section, value: newIndex)
})
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = Array(section(at: indexPath.section).values.first!)[indexPath.row]
cell.accessoryType = value(for: indexPath.section) == indexPath.row ? .checkmark : .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell: BoardCell = tableView.cell(at: indexPath), indexPath.section == 0 {
cell.nextBoard()
setValue(for: indexPath.section, value: cell.gameTypeIndex)
tableView.deselectRow(at: indexPath, animated: true)
return
}
if indexPath.section < 4 {
return
}
setValue(to: indexPath)
tableView.reloadSections(IndexSet(integer: indexPath.section), with: .fade)
}
}
| mit | 94775c5331319665509ce744830f7a6a | 34.271739 | 100 | 0.6151 | 4.821694 | false | false | false | false |
zhuyunfeng1224/XiheMtxx | XiheMtxx/VC/ToolBarView.swift | 1 | 1615 | //
// ToolBarView.swift
// EasyCard
//
// Created by echo on 2017/2/14.
// Copyright © 2017年 羲和. All rights reserved.
//
import UIKit
let height: CGFloat = 50
class ToolBarView: UIView {
lazy var toolBarScrollView: UIScrollView = {
let _toolBarScrollView = UIScrollView(frame: CGRect.zero)
_toolBarScrollView.alwaysBounceHorizontal = true
_toolBarScrollView.backgroundColor = UIColor.colorWithHexString(hex: "ffffff")
return _toolBarScrollView
}()
override init(frame: CGRect) {
super.init(frame: frame)
}
// 根据ToolBarItemObject对象创建item
convenience init(items: [ToolBarItemObject]) {
let rect = CGRect(x: 0,
y: (UIScreen.main.bounds.size.height - height),
width: UIScreen.main.bounds.size.width,
height: height)
self.init(frame: rect)
self.toolBarScrollView.frame = CGRect(x: 0, y: 0, width: rect.size.width, height: rect.size.height)
self.addSubview(self.toolBarScrollView)
for i in 0...(items.count - 1) {
let itemObject = items[i]
let w: CGFloat = 55
let x: CGFloat = CGFloat(i) * w
let h: CGFloat = height
let frame = CGRect(x: x, y: 0, width: w, height: h)
let item = ToolBarItem(frame: frame, itemObject: itemObject)
self.toolBarScrollView.addSubview(item)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | e9ad0aebdb1355d921d924351066e84d | 30.294118 | 107 | 0.591479 | 4.26738 | false | false | false | false |
k2r79/Suggestinator | Suggestinator/SuggestionsViewController.swift | 1 | 4957 | //
// ViewController.swift
// Suggestinator
//
// Created by Vincent Kelleher on 21/10/2015.
// Copyright © 2015 Vincent Kelleher. All rights reserved.
//
import UIKit
class SuggestionsViewController: UICollectionViewController {
var query = ""
var suggestions = [Suggestion]()
var suggestionDataTask:NSURLSessionDataTask?
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator.startAnimating()
let computedCellSize = (self.collectionView!.frame.size.width - 20) / 2
let layout = self.collectionView!.collectionViewLayout as! UICollectionViewFlowLayout
layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5)
layout.minimumInteritemSpacing = 5
layout.itemSize = CGSizeMake(computedCellSize, computedCellSize)
self.findSuggestions({ () -> () in
self.activityIndicator.stopAnimating()
self.collectionView?.reloadData();
}) { () -> () in
let alert = UIAlertController(title: "No results...", message: "No results have been found for your search criteria.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
let homeView = self.storyboard!.instantiateViewControllerWithIdentifier("HomeView") as! SuggestionatorViewController
self.showViewController(homeView, sender: homeView)
return nil
}()))
self.presentViewController(alert, animated: true, completion: nil)
}
}
private func findSuggestions(callback:() -> (), noResultCallback:() -> ()) {
let encodedQuery = "https://www.tastekid.com/api/similar?k=173208-Suggesti-9BWWRVBZ&verbose=1&q=" + query.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
let request = NSMutableURLRequest(URL: NSURL(string: encodedQuery)!)
request.HTTPMethod = "GET"
let session = NSURLSession.sharedSession()
suggestionDataTask = session.dataTaskWithRequest(request) { (data, response, error) in
let tasteKidJSON = JSON(data: data!)
let results = tasteKidJSON["Similar"]["Results"];
for (_, json) in results {
var suggestion = Suggestion(title: json["Name"].string!, type: json["Type"].string!, summary: json["wTeaser"].string!)
if json["yID"].string != nil {
let imageURL = "https://i.ytimg.com/vi/" + json["yID"].string! + "/hqdefault.jpg"
if let imageData = self.getDataFromUrl(imageURL) {
suggestion.image = UIImage(data: imageData)!
}
}
self.suggestions.append(suggestion)
dispatch_async(dispatch_get_main_queue(), {
callback()
})
}
if (results.isEmpty) {
noResultCallback();
}
}
suggestionDataTask!.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return suggestions.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("SuggestionCell", forIndexPath: indexPath) as! SuggestionCellViewController
let suggestion = self.suggestions[indexPath.item]
cell.suggestion = suggestion
cell.label.text = suggestion.title
cell.imageView.image = suggestion.image
return cell
}
private func getDataFromUrl(url:String) -> NSData? {
if let url = NSURL(string: url) {
if let data = NSData(contentsOfURL: url) {
return data
}
}
return nil
}
override func viewWillDisappear(animated: Bool) {
suggestionDataTask!.cancel()
super.viewWillAppear(animated)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "OpenSuggestionDetails" {
if let destination = segue.destinationViewController as? SuggestionTableViewController {
destination.suggestion = (sender as? SuggestionCellViewController)!.suggestion
}
}
}
}
| mit | 8b8fc4e66ca7805b43462a176972f7e0 | 37.418605 | 196 | 0.612591 | 5.651083 | false | false | false | false |
swift-gtk/SwiftGTK | Sources/UIKit/Size.swift | 1 | 501 |
public struct Size {
static let zero = Size(width: 0, height: 0)
public var width: Int
public var height: Int
public init(width: Int = 0, height: Int = 0) {
self.width = width
self.height = height
}
}
extension Size: CustomStringConvertible {
public var description: String {
return "(\(width), \(height))"
}
}
extension Size: CustomDebugStringConvertible {
public var debugDescription: String {
return description
}
}
| gpl-2.0 | 27cc93218c9cdfbae790ee5110191387 | 19.04 | 50 | 0.61477 | 4.394737 | false | false | false | false |
danielgindi/ios-charts | Source/Charts/Highlight/HorizontalBarHighlighter.swift | 2 | 2108 | //
// HorizontalBarHighlighter.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
@objc(HorizontalBarChartHighlighter)
open class HorizontalBarHighlighter: BarHighlighter
{
open override func getHighlight(x: CGFloat, y: CGFloat) -> Highlight?
{
guard let barData = self.chart?.data as? BarChartData else { return nil }
let pos = getValsForTouch(x: y, y: x)
guard let high = getHighlight(xValue: Double(pos.y), x: y, y: x) else { return nil }
if let set = barData[high.dataSetIndex] as? BarChartDataSetProtocol,
set.isStacked
{
return getStackedHighlight(high: high,
set: set,
xValue: Double(pos.y),
yValue: Double(pos.x))
}
return high
}
internal override func buildHighlights(
dataSet set: ChartDataSetProtocol,
dataSetIndex: Int,
xValue: Double,
rounding: ChartDataSetRounding) -> [Highlight]
{
guard let chart = self.chart as? BarLineScatterCandleBubbleChartDataProvider else { return [] }
var entries = set.entriesForXValue(xValue)
if entries.isEmpty, let closest = set.entryForXValue(xValue, closestToY: .nan, rounding: rounding)
{
// Try to find closest x-value and take all entries for that x-value
entries = set.entriesForXValue(closest.x)
}
return entries.map { e in
let px = chart.getTransformer(forAxis: set.axisDependency)
.pixelForValues(x: e.y, y: e.x)
return Highlight(x: e.x, y: e.y, xPx: px.x, yPx: px.y, dataSetIndex: dataSetIndex, axis: set.axisDependency)
}
}
internal override func getDistance(x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat) -> CGFloat
{
return abs(y1 - y2)
}
}
| apache-2.0 | aff550a5bdd18504d8cab9dc8107e4fe | 32.460317 | 120 | 0.60389 | 4.428571 | false | false | false | false |
DanielAsher/SwiftCheck | SwiftCheck/Gen.swift | 3 | 13616 | //
// Gen.swift
// SwiftCheck
//
// Created by Robert Widmann on 7/31/14.
// Copyright (c) 2015 TypeLift. All rights reserved.
//
/// `Gen` represents a generator for random arbitrary values of type `A`.
///
/// `Gen` wraps a function that, when given a random number generator and a size, can be used to
/// control the distribution of resultant values. A generator relies on its size to help control
/// aspects like the length of generated arrays and the magnitude of integral values.
public struct Gen<A> {
/// The function underlying the receiver.
///
/// +--- An RNG
/// | +--- The size of generated values.
/// | |
/// v v
let unGen : StdGen -> Int -> A
/// Generates a value.
///
/// This method exists as a convenience mostly to test generators. It will always generate with
/// size 30.
public var generate : A {
let r = newStdGen()
return unGen(r)(30)
}
/// Constructs a Generator that selects a random value from the given collection and produces
/// only that value.
///
/// The input collection is required to be non-empty.
public static func fromElementsOf<S : Indexable where S.Index : protocol<Comparable, RandomType>>(xs : S) -> Gen<S._Element> {
return Gen.fromElementsIn(xs.startIndex...xs.endIndex.advancedBy(-1)).fmap { i in
return xs[i]
}
}
/// Constructs a Generator that selects a random value from the given interval and produces only
/// that value.
///
/// The input interval is required to be non-empty.
public static func fromElementsIn<S : IntervalType where S.Bound : RandomType>(xs : S) -> Gen<S.Bound> {
assert(!xs.isEmpty, "Gen.fromElementsOf used with empty interval")
return choose((xs.start, xs.end))
}
/// Constructs a Generator that uses a given array to produce smaller arrays composed of its
/// initial segments. The size of each initial segment increases with the receiver's size
/// parameter.
///
/// The input array is required to be non-empty.
public static func fromInitialSegmentsOf(xs : [A]) -> Gen<A> {
assert(!xs.isEmpty, "Gen.fromInitialSegmentsOf used with empty list")
let k = Double(xs.count)
return sized({ n in
let m = max(1, size(k)(m: n))
return Gen.fromElementsOf(xs[0 ..< m])
})
}
/// Constructs a Generator that produces permutations of a given array.
public static func fromShufflingElementsOf(xs : [A]) -> Gen<[A]> {
if xs.isEmpty {
return Gen<[A]>.pure([])
}
return Gen<(A, [A])>.fromElementsOf(selectOne(xs)).bind { (y, ys) in
return Gen.fromShufflingElementsOf(ys).fmap { [y] + $0 }
}
}
/// Constructs a generator that depends on a size parameter.
public static func sized(f : Int -> Gen<A>) -> Gen<A> {
return Gen(unGen:{ r in
return { n in
return f(n).unGen(r)(n)
}
})
}
/// Constructs a random element in the range of two `RandomType`s.
///
/// When using this function, it is necessary to explicitly specialize the generic parameter
/// `A`. For example:
///
/// Gen<UInt32>.choose((32, 255)) >>- (Gen<Character>.pure • Character.init • UnicodeScalar.init)
public static func choose<A : RandomType>(rng : (A, A)) -> Gen<A> {
return Gen<A>(unGen: { s in
return { (_) in
let (x, _) = A.randomInRange(rng, gen: s)
return x
}
})
}
/// Constructs a Generator that randomly selects and uses a particular generator from the given
/// sequence of Generators.
///
/// If control over the distribution of generators is needed, see `Gen.frequency` or
/// `Gen.weighted`.
public static func oneOf<S : CollectionType where S.Generator.Element == Gen<A>, S.Index : protocol<RandomType, BidirectionalIndexType>>(gs : S) -> Gen<A> {
assert(gs.count != 0, "oneOf used with empty list")
return choose((gs.indices.startIndex, gs.indices.endIndex.predecessor())) >>- { x in
return gs[x]
}
}
/// Given a sequence of Generators and weights associated with them, this function randomly
/// selects and uses a Generator.
///
/// Only use this function when you need to assign uneven "weights" to each generator. If all
/// generators need to have an equal chance of being selected, use `Gen.oneOf`.
public static func frequency<S : SequenceType where S.Generator.Element == (Int, Gen<A>)>(xs : S) -> Gen<A> {
let xs: [(Int, Gen<A>)] = Array(xs)
assert(xs.count != 0, "frequency used with empty list")
return choose((1, xs.map({ $0.0 }).reduce(0, combine: +))).bind { l in
return pick(l)(lst: xs)
}
}
/// Given a list of values and weights associated with them, this function randomly selects and
/// uses a Generator wrapping one of the values.
///
/// This function operates in exactly the same manner as `Gen.frequency`, `Gen.fromElementsOf`,
/// and `Gen.fromElementsIn` but for any type rather than only Generators. It can help in cases
/// where your `Gen.from*` call contains only `Gen.pure` calls by allowing you to remove every
/// `.pure` in favor of a direct list of values.
public static func weighted<S : SequenceType where S.Generator.Element == (Int, A)>(xs : S) -> Gen<A> {
return frequency(xs.map { ($0, Gen.pure($1)) })
}
/// Zips together 2 generators of type `A` and `B` into a generator of pairs `(A, B)`.
public static func zip<A, B>(gen1 : Gen<A>, _ gen2 : Gen<B>) -> Gen<(A, B)> {
return gen1.bind { l in
return gen2.bind { r in
return Gen<(A, B)>.pure((l, r))
}
}
}
}
/// MARK: Generator Modifiers
extension Gen {
/// Shakes up the receiver's internal Random Number Generator with a seed.
public func variant<S : IntegerType>(seed : S) -> Gen<A> {
return Gen(unGen: { r in
return { n in
return self.unGen(vary(seed)(r: r))(n)
}
})
}
/// Modifies a Generator to always use a given size.
public func resize(n : Int) -> Gen<A> {
return Gen(unGen: { r in
return { (_) in
return self.unGen(r)(n)
}
})
}
/// Modifies a Generator such that it only returns values that satisfy a predicate. When the
/// predicate fails the test case is treated as though it never occured.
///
/// Because the Generator will spin until it reaches a non-failing case, executing a condition
/// that fails more often than it succeeds may result in a space leak. At that point, it is
/// better to use `suchThatOptional` or `.invert` the test case.
public func suchThat(p : A -> Bool) -> Gen<A> {
return self.suchThatOptional(p).bind { mx in
switch mx {
case .Some(let x):
return Gen.pure(x)
case .None:
return Gen.sized { n in
return self.suchThat(p).resize(n.successor())
}
}
}
}
/// Modifies a Generator such that it attempts to generate values that satisfy a predicate. All
/// attempts are encoded in the form of an `Optional` where values satisfying the predicate are
/// wrapped in `.Some` and failing values are `.None`.
public func suchThatOptional(p : A -> Bool) -> Gen<Optional<A>> {
return Gen<Optional<A>>.sized({ n in
return attemptBoundedTry(self, k: 0, n: max(n, 1), p: p)
})
}
/// Modifies a Generator such that it produces arrays with a length determined by the receiver's
/// size parameter.
public func proliferate() -> Gen<[A]> {
return Gen<[A]>.sized({ n in
return Gen.choose((0, n)) >>- self.proliferateSized
})
}
/// Modifies a Generator such that it produces non-empty arrays with a length determined by the
/// receiver's size parameter.
public func proliferateNonEmpty() -> Gen<[A]> {
return Gen<[A]>.sized({ n in
return Gen.choose((1, max(1, n))) >>- self.proliferateSized
})
}
/// Modifies a Generator such that it only produces arrays of a given length.
public func proliferateSized(k : Int) -> Gen<[A]> {
return sequence(Array<Gen<A>>(count: k, repeatedValue: self))
}
}
/// MARK: Instances
extension Gen /*: Functor*/ {
typealias B = Swift.Any
/// Returns a new generator that applies a given function to any outputs the receiver creates.
public func fmap<B>(f : (A -> B)) -> Gen<B> {
return f <^> self
}
}
/// Fmap | Returns a new generator that applies a given function to any outputs the given generator
/// creates.
///
/// This function is most useful for converting between generators of inter-related types. For
/// example, you might have a Generator of `Character` values that you then `.proliferate()` into an
/// `Array` of `Character`s. You can then use `fmap` to convert that generator of `Array`s to a
/// generator of `String`s.
public func <^> <A, B>(f : A -> B, g : Gen<A>) -> Gen<B> {
return Gen(unGen: { r in
return { n in
return f(g.unGen(r)(n))
}
})
}
extension Gen /*: Applicative*/ {
typealias FAB = Gen<A -> B>
/// Lifts a value into a generator that will only generate that value.
public static func pure(a : A) -> Gen<A> {
return Gen(unGen: { (_) in
return { (_) in
return a
}
})
}
/// Given a generator of functions, applies any generated function to any outputs the receiver
/// creates.
public func ap<B>(fn : Gen<A -> B>) -> Gen<B> {
return fn <*> self
}
}
/// Ap | Returns a Generator that uses the first given Generator to produce functions and the second
/// given Generator to produce values that it applies to those functions. It can be used in
/// conjunction with <^> to simplify the application of "combining" functions to a large amount of
/// sub-generators. For example:
///
/// struct Foo { let b : Int; let c : Int; let d : Int }
///
/// let genFoo = curry(Foo.init) <^> Int.arbitrary <*> Int.arbitrary <*> Int.arbitrary
///
/// This combinator acts like `zip`, but instead of creating pairs it creates values after applying
/// the zipped function to the zipped value.
///
/// Promotes function application to a Generator of functions applied to a Generator of values.
public func <*> <A, B>(fn : Gen<A -> B>, g : Gen<A>) -> Gen<B> {
return Gen(unGen: { r in
return { n in
return fn.unGen(r)(n)(g.unGen(r)(n))
}
})
}
extension Gen /*: Monad*/ {
/// Applies the function to any generated values to yield a new generator. This generator is
/// then given a new random seed and returned.
///
/// `bind` allows for the creation of Generators that depend on other generators. One might,
/// for example, use a Generator of integers to control the length of a Generator of strings, or
/// use it to choose a random index into a Generator of arrays.
public func bind<B>(fn : A -> Gen<B>) -> Gen<B> {
return self >>- fn
}
}
/// Applies the function to any generated values to yield a new generator. This generator is
/// then given a new random seed and returned.
///
/// `bind` allows for the creation of Generators that depend on other generators. One might,
/// for example, use a Generator of integers to control the length of a Generator of strings, or
/// use it to choose a random index into a Generator of arrays.
public func >>- <A, B>(m : Gen<A>, fn : A -> Gen<B>) -> Gen<B> {
return Gen(unGen: { r in
return { n in
let (r1, r2) = r.split
let m2 = fn(m.unGen(r1)(n))
return m2.unGen(r2)(n)
}
})
}
/// Creates and returns a Generator of arrays of values drawn from each generator in the given
/// array.
///
/// The array that is created is guaranteed to use each of the given Generators in the order they
/// were given to the function exactly once. Thus all arrays generated are of the same rank as the
/// array that was given.
public func sequence<A>(ms : [Gen<A>]) -> Gen<[A]> {
return ms.reduce(Gen<[A]>.pure([]), combine: { y, x in
return x.bind { x1 in
return y.bind { xs in
return Gen<[A]>.pure([x1] + xs)
}
}
})
}
/// Flattens a generator of generators by one level.
public func join<A>(rs : Gen<Gen<A>>) -> Gen<A> {
return rs.bind { x in
return x
}
}
/// Lifts a function from some A to some R to a function from generators of A to generators of R.
public func liftM<A, R>(f : A -> R)(m1 : Gen<A>) -> Gen<R> {
return m1.bind{ x1 in
return Gen.pure(f(x1))
}
}
/// Promotes a rose of generators to a generator of rose values.
public func promote<A>(x : Rose<Gen<A>>) -> Gen<Rose<A>> {
return delay().bind { (let eval : Gen<A> -> A) in
return Gen<Rose<A>>.pure(liftM(eval)(m1: x))
}
}
/// Promotes a function returning generators to a generator of functions.
public func promote<A, B>(m : A -> Gen<B>) -> Gen<A -> B> {
return delay().bind { (let eval : Gen<B> -> B) in
return Gen<A -> B>.pure({ x in eval(m(x)) })
}
}
internal func delay<A>() -> Gen<Gen<A> -> A> {
return Gen(unGen: { r in
return { n in
return { g in
return g.unGen(r)(n)
}
}
})
}
/// MARK: - Implementation Details
import func Darwin.log
private func vary<S : IntegerType>(k : S)(r : StdGen) -> StdGen {
let s = r.split
let gen = ((k % 2) == 0) ? s.0 : s.1
return (k == (k / 2)) ? gen : vary(k / 2)(r: r)
}
private func attemptBoundedTry<A>(gen: Gen<A>, k : Int, n : Int, p: A -> Bool) -> Gen<Optional<A>> {
if n == 0 {
return Gen.pure(.None)
}
return gen.resize(2 * k + n).bind { (let x : A) -> Gen<Optional<A>> in
if p(x) {
return Gen.pure(.Some(x))
}
return attemptBoundedTry(gen, k: k.successor(), n: n - 1, p: p)
}
}
private func size(k : Double)(m : Int) -> Int {
let n = Double(m)
return Int((log(n + 1)) * k / log(100))
}
private func selectOne<A>(xs : [A]) -> [(A, [A])] {
if xs.isEmpty {
return []
}
let y = xs.first!
let ys = Array(xs[1..<xs.endIndex])
return [(y, ys)] + selectOne(ys).map({ t in (t.0, [y] + t.1) })
}
private func pick<A>(n : Int)(lst : [(Int, Gen<A>)]) -> Gen<A> {
let (k, x) = lst[0]
let tl = Array<(Int, Gen<A>)>(lst[1..<lst.count])
if n <= k {
return x
}
return pick(n - k)(lst: tl)
}
| mit | ea8539d13698ebcb3d07610075a48fc4 | 32.038835 | 157 | 0.649354 | 3.237099 | false | false | false | false |
srn214/Floral | Floral/Pods/NVActivityIndicatorView/Source/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallGridBeat.swift | 3 | 3173 | //
// NVActivityIndicatorAnimationBallGridBeat.swift
// NVActivityIndicatorView
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
class NVActivityIndicatorAnimationBallGridBeat: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSpacing: CGFloat = 2
let circleSize = (size.width - circleSpacing * 2) / 3
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let durations = [0.96, 0.93, 1.19, 1.13, 1.34, 0.94, 1.2, 0.82, 1.19]
let beginTime = CACurrentMediaTime()
let beginTimes = [0.36, 0.4, 0.68, 0.41, 0.71, -0.15, -0.12, 0.01, 0.32]
#if swift(>=4.2)
let timingFunction = CAMediaTimingFunction(name: .default)
#else
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
#endif
// Animation
let animation = CAKeyframeAnimation(keyPath: "opacity")
animation.keyTimes = [0, 0.5, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.7, 1]
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circles
for i in 0 ..< 3 {
for j in 0 ..< 3 {
let circle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(x: x + circleSize * CGFloat(j) + circleSpacing * CGFloat(j),
y: y + circleSize * CGFloat(i) + circleSpacing * CGFloat(i),
width: circleSize,
height: circleSize)
animation.duration = durations[3 * i + j]
animation.beginTime = beginTime + beginTimes[3 * i + j]
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
}
}
| mit | 9efa7267c15cda36454cd9a3aea5d0fe | 43.069444 | 137 | 0.647337 | 4.539342 | false | false | false | false |
marty-suzuki/FluxCapacitor | Examples/Flux/FluxCapacitorSample/Sources/UI/Search/SearchViewDataSource.swift | 1 | 3684 | //
// SearchViewDataSource.swift
// FluxCapacitorSample
//
// Created by marty-suzuki on 2017/08/02.
// Copyright © 2017年 marty-suzuki. All rights reserved.
//
import UIKit
import GithubKit
import FluxCapacitor
final class SearchViewDataSource: NSObject {
fileprivate let action: UserAction
fileprivate let store: UserStore
fileprivate let loadingView = LoadingView.makeFromNib()
private let dustBuster = DustBuster()
fileprivate var isReachedBottom: Bool = false {
didSet {
if isReachedBottom && isReachedBottom != oldValue {
let query = store.lastSearchQuery.value
guard
!query.isEmpty,
let pageInfo = store.lastPageInfo.value,
pageInfo.hasNextPage,
let after = pageInfo.endCursor
else { return }
action.fetchUsers(withQuery: query, after: after)
}
}
}
init(action: UserAction = .init(), store: UserStore = .instantiate()) {
self.action = action
self.store = store
super.init()
store.isUserFetching
.observe(on: .main) { [weak self] in
self?.loadingView.isLoading = $0
}
.cleaned(by: dustBuster)
}
func configure(with tableView: UITableView) {
tableView.dataSource = self
tableView.delegate = self
tableView.register(UserViewCell.self)
tableView.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: UITableViewHeaderFooterView.className)
}
}
extension SearchViewDataSource: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return store.users.value.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeue(UserViewCell.self, for: indexPath)
cell.configure(with: store.users.value[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return nil
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: UITableViewHeaderFooterView.className) else {
return nil
}
loadingView.removeFromSuperview()
loadingView.add(to: view)
return view
}
}
extension SearchViewDataSource: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
let user = store.users.value[indexPath.row]
action.invoke(.selectedUser(user))
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UserViewCell.calculateHeight(with: store.users.value[indexPath.row], and: tableView)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return .leastNormalMagnitude
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return store.isUserFetching.value ? LoadingView.defaultHeight : .leastNormalMagnitude
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let maxScrollDistance = max(0, scrollView.contentSize.height - scrollView.bounds.size.height)
isReachedBottom = maxScrollDistance <= scrollView.contentOffset.y
}
}
| mit | 9ceae2f3f46d72b2758630ea2cfbcef5 | 33.726415 | 135 | 0.664493 | 5.311688 | false | false | false | false |
HarrisLee/Utils | MySampleCode-master/CustomTransition/CustomTransition-Swift/CustomTransition-Swift/Interactivity/InteractivityFirstViewController.swift | 1 | 4248 | //
// InteractivityFirstViewController.swift
// CustomTransition-Swift
//
// Created by 张星宇 on 16/2/8.
// Copyright © 2016年 zxy. All rights reserved.
//
import UIKit
class InteractivityFirstViewController: UIViewController {
lazy var interactivitySecondViewController: InteractivitySecondViewController = InteractivitySecondViewController()
lazy var customTransitionDelegate: InteractivityTransitionDelegate = InteractivityTransitionDelegate()
lazy var interactiveTransitionRecognizer: UIScreenEdgePanGestureRecognizer = UIScreenEdgePanGestureRecognizer.init(target: self, action: Selector("interactiveTransitionRecognizerAction:"))
override func viewDidLoad() {
super.viewDidLoad()
setupView() // 主要是一些UI控件的布局,可以无视其实现细节
/// 添加滑动交互手势
interactiveTransitionRecognizer.edges = .Right
self.view.addGestureRecognizer(interactiveTransitionRecognizer)
/// 设置动画代理
interactivitySecondViewController.transitioningDelegate = customTransitionDelegate
interactivitySecondViewController.modalPresentationStyle = .FullScreen
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - 手势识别
extension InteractivityFirstViewController {
func interactiveTransitionRecognizerAction(sender: UIScreenEdgePanGestureRecognizer) {
/**
* 在开始触发手势时,调用animationButtonDidClicked方法,只会调用一次
*/
if sender.state == .Began {
self.animationButtonDidClicked(sender)
}
}
}
// MARK: - 处理UI控件的点击事件
extension InteractivityFirstViewController {
/**
这个函数可以在按钮点击时触发,也可以在手势滑动时被触发,通过sender的类型来判断具体是那种情况
如果是通过滑动手势触发,则需要设置customTransitionDelegate的gestureRecognizer属性
:param: sender 事件的发送者,可能是button,也有可能是手势
*/
func animationButtonDidClicked(sender: AnyObject) {
if sender.isKindOfClass(UIGestureRecognizer) {
customTransitionDelegate.gestureRecognizer = interactiveTransitionRecognizer
}
else {
customTransitionDelegate.gestureRecognizer = nil
}
/// 设置targetEdge为右边,也就是检测从右边向左滑动的手势
customTransitionDelegate.targetEdge = .Right
self.presentViewController(interactivitySecondViewController, animated: true, completion: nil)
}
func leftBarButtonDidClicked() {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
// MARK: - 对视图上的基本UI控件进行初始化,读者可以忽略
extension InteractivityFirstViewController {
func setupView() {
view.backgroundColor = [224, 222, 255].color // 设置背景颜色
/// 设置navigationItem
navigationItem.title = "交互式动画"
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Menu", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("leftBarButtonDidClicked"))
/// 创建label
let label = UILabel()
label.text = "From"
label.font = UIFont(name: "Helvetica", size: 60)
view.addSubview(label)
label.snp_makeConstraints { (make) -> Void in
make.center.equalTo(view)
make.width.equalTo(150)
make.height.equalTo(60)
}
/// 创建button
let button = UIButton()
button.setTitleColor(UIColor.blueColor(), forState: .Normal)
button.setTitle("演示动画", forState: .Normal)
button.addTarget(self, action: Selector("animationButtonDidClicked:"), forControlEvents: .TouchUpInside)
view.addSubview(button)
button.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(view)
make.width.equalTo(250)
make.height.equalTo(60)
make.bottom.equalTo(view).offset(-40)
}
}
} | mit | b5467c72c60eceb6298fcc4c11c1edb0 | 35.361905 | 192 | 0.688499 | 5.048942 | false | false | false | false |
steven851007/ShoppingCart | ShoppingCart/ShoppingCart/Currencies.swift | 1 | 3326 | //
// Currencies.swift
// ShoppingCart
//
// Created by Istvan Balogh on 2017. 08. 10..
// Copyright © 2017. Balogh István. All rights reserved.
//
import Foundation
// This class holds all the available currencies. Before downloading the rest only $ available.
class Currencies {
// The currently selected currency. Only currency with a valid exchange rate can be selected
private(set) static var selectedCurrency = Currency(code: "USD", name: "United States Dollar", exchangeRate: 1) {
didSet {
guard selectedCurrency.exchangeRate != nil else {
fatalError("Only currencies with exchange rates should be selected")
}
}
}
// This property gurantees a valid exchange rate for the selected currency.
static var selectedExchangeRate: NSDecimalNumber {
guard let exchangeRate = self.selectedCurrency.exchangeRate else {
fatalError("Only currencies with exchange rates should be selected")
}
return exchangeRate
}
// Available currencies
private(set) static var currencies = [Currency(code: "USD", name: "United States Dollar", exchangeRate: 1)]
// Download the available currencies. Call this method at the beginning of the application. It will append the new currencies tu the existing array
static func downloadCurrencies() {
let currencyDownloader = CurrencyDownloader()
currencyDownloader.downloadCurrencies { (currencies, error) in
if let currencies = currencies {
self.currencies = currencies.sorted { $0.name < $1.name }
} else if let error = error {
print(error.localizedDescription)
} else {
assert(true, "Something really went wrong")
}
}
}
/** Sets the currently selected currency.
** If the exchange rate doesn't exist for the selected currency it will try to download first.
** If it succeeds sets the new selected currency, if it fails it retuns an error and does nothing.
**/
static func changeCurrency(to currency: Currency, completion: @escaping (Bool) -> Void) {
if currency.exchangeRate != nil {
// Here we could check when this was downloaded and if it's "too old" we should redownload.
self.selectedCurrency = currency
completion(true)
return
}
let currencyDownloader = CurrencyDownloader()
currencyDownloader.downloadExchangeRate(for: currency) { (exchangeRate, error) in
if let exchangeRate = exchangeRate {
if let index = currencies.index(of: currency) {
self.selectedCurrency = Currency(code: currency.code, name: currency.name, exchangeRate: exchangeRate)
currencies[index] = self.selectedCurrency
completion(true)
return
} else {
assert(true, "Currency should be in the currencies array")
}
} else if let error = error {
print(error.localizedDescription)
} else {
assert(true, "Something really went wrong")
}
completion(false)
}
}
}
| mit | 1ed1b216b0bd7b7f412c8bd58569ef2e | 40.037037 | 151 | 0.616727 | 5.292994 | false | false | false | false |
XLabKC/Badger | Badger/Badger/FirebaseObserver.swift | 1 | 3009 |
class FirebaseObserver<T: DataEntity> {
private var disposed = false
private let query: FQuery
private var started = false
private var handles = [UInt]()
private var loadedInitial = false
var afterInitial: (() -> ())?
var childAdded: ((T, previousId: String?, isInitial: Bool) -> ())?
var childChanged: ((T, previousId: String?) -> ())?
var childMoved: ((T, previousId: String?) -> ())?
var childRemoved: ((T, previousId: String?) -> ())?
init(query: FQuery) {
self.query = query
}
convenience init(query: FQuery, withBlock: T -> ()) {
self.init(query: query)
self.observe(withBlock)
}
deinit {
dispose()
}
// Starts observing the ref.
func observe(withBlock: T -> ()) {
if self.started {
return
}
self.started = true
let handle = self.query.observeEventType(.Value, withBlock: { snapshot in
if snapshot.childrenCount > 0 {
withBlock(T.createFromSnapshot(snapshot) as! T)
} else {
println("No data at: \(snapshot.ref.description())")
}
})
self.handles.append(handle)
}
// Starts observing the ref with the handlers that have been specified.
func start() {
if self.started {
return
}
self.started = true
if let childAddedFunc = self.childAdded {
var handle = self.query.observeEventType(.ChildAdded, andPreviousSiblingKeyWithBlock: { (snapshot, id) in
var data = T.createFromSnapshot(snapshot) as! T
childAddedFunc(data, previousId: id, isInitial: !self.loadedInitial)
})
self.handles.append(handle)
}
self.maybeAddObservingFunc(self.childChanged, type: .ChildChanged)
self.maybeAddObservingFunc(self.childMoved, type: .ChildMoved)
self.maybeAddObservingFunc(self.childRemoved, type: .ChildRemoved)
// After initial.
self.query.observeSingleEventOfType(.Value, withBlock: { _ in
self.loadedInitial = true
if let afterInitial = self.afterInitial {
afterInitial()
}
})
}
func isStarted() -> Bool {
return self.started
}
func hasLoadedInitial() -> Bool {
return self.loadedInitial
}
func dispose() {
if !self.disposed {
self.disposed = true
for handle in self.handles {
self.query.removeObserverWithHandle(handle)
}
}
}
private func maybeAddObservingFunc(function: ((T, previousId: String?) -> ())?, type: FEventType) {
if let observer = function {
var handle = self.query.observeEventType(type, andPreviousSiblingKeyWithBlock: { (snapshot, id) in
observer(T.createFromSnapshot(snapshot) as! T, previousId: id)
})
self.handles.append(handle)
}
}
} | gpl-2.0 | 207c0f987b81fcc5981351ebad2aa920 | 30.030928 | 117 | 0.575939 | 4.497758 | false | false | false | false |
jacobwhite/firefox-ios | ClientTests/NavigationRouterTests.swift | 1 | 3715 | /* 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
@testable import Client
import WebKit
import XCTest
class NavigationRouterTests: XCTestCase {
var appScheme: String {
let urlTypes = Bundle.main.object(forInfoDictionaryKey: "CFBundleURLTypes") as! [AnyObject]
let urlType = urlTypes.first as! [String : AnyObject]
let urlSchemes = urlType["CFBundleURLSchemes"] as! [String]
return urlSchemes.first!
}
func testOpenURLScheme() {
let url = "http://google.com?a=1&b=2&c=foo%20bar".escape()!
let appURL = "\(appScheme)://open-url?url=\(url)"
let navItem = NavigationPath(url: URL(string: appURL)!)!
XCTAssertEqual(navItem, NavigationPath.url(webURL: URL(string: url.unescape()!)!, isPrivate: false))
let emptyNav = NavigationPath(url: URL(string: "\(appScheme)://open-url?private=true")!)
XCTAssertEqual(emptyNav, NavigationPath.url(webURL: nil, isPrivate: true))
let badNav = NavigationPath(url: URL(string: "\(appScheme)://open-url?url=blah")!)
XCTAssertEqual(badNav, NavigationPath.url(webURL: URL(string: "blah"), isPrivate: false))
}
// Test EVERY deep link
func testDeepLinks() {
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/settings/clear-private-data")!), NavigationPath.deepLink(DeepLink.settings(.clearData)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/settings/newTab")!), NavigationPath.deepLink(DeepLink.settings(.newTab)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/settings/newTab/")!), NavigationPath.deepLink(DeepLink.settings(.newTab)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/settings/homePage")!), NavigationPath.deepLink(DeepLink.settings(.homePage)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/settings/mailto")!), NavigationPath.deepLink(DeepLink.settings(.mailto)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/settings/search")!), NavigationPath.deepLink(DeepLink.settings(.search)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/settings/fxa")!), NavigationPath.deepLink(DeepLink.settings(.fxa)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/homepanel/bookmarks")!), NavigationPath.deepLink(DeepLink.homePanel(.bookmarks)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/homepanel/topsites")!), NavigationPath.deepLink(DeepLink.homePanel(.topsites)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/homepanel/history")!), NavigationPath.deepLink(DeepLink.homePanel(.history)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/homepanel/readingList")!), NavigationPath.deepLink(DeepLink.homePanel(.readingList)))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://deep-link?url=/homepanel/badbad")!), nil)
}
func testFxALinks() {
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://fxa-signin?signin=coolcodes&user=foo&email=bar")!), NavigationPath.fxa(params: FxALaunchParams(query: ["user": "foo","email": "bar", "signin": "coolcodes"])))
XCTAssertEqual(NavigationPath(url: URL(string: "\(appScheme)://fxa-signin?user=foo&email=bar")!), nil)
}
}
| mpl-2.0 | 84b651402fd92593273ae4f97f1dba60 | 67.796296 | 229 | 0.70175 | 4.375736 | false | true | false | false |
Faryn/CycleMaps | Pods/Cache/Source/Shared/Library/MD5.swift | 2 | 9395 | // swiftlint:disable comma function_parameter_count variable_name syntactic_sugar function_body_length vertical_whitespace
// https://github.com/onmyway133/SwiftHash/blob/master/Sources/MD5.swift
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/**
* SwiftHash
* Copyright (c) Khoa Pham 2017
* Licensed under the MIT license. See LICENSE file.
*/
import Foundation
// MARK: - Public
public func MD5(_ input: String) -> String {
return hex_md5(input)
}
// MARK: - Functions
func hex_md5(_ input: String) -> String {
return rstr2hex(rstr_md5(str2rstr_utf8(input)))
}
func str2rstr_utf8(_ input: String) -> [CUnsignedChar] {
return Array(input.utf8)
}
func rstr2tr(_ input: [CUnsignedChar]) -> String {
var output: String = ""
input.forEach {
output.append(String(UnicodeScalar($0)))
}
return output
}
/*
* Convert a raw string to a hex string
*/
func rstr2hex(_ input: [CUnsignedChar]) -> String {
let hexTab: [Character] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
var output: [Character] = []
for i in 0..<input.count {
let x = input[i]
let value1 = hexTab[Int((x >> 4) & 0x0F)]
let value2 = hexTab[Int(Int32(x) & 0x0F)]
output.append(value1)
output.append(value2)
}
return String(output)
}
/*
* Convert a raw string to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*/
func rstr2binl(_ input: [CUnsignedChar]) -> [Int32] {
var output: [Int: Int32] = [:]
for i in stride(from: 0, to: input.count * 8, by: 8) {
let value: Int32 = (Int32(input[i/8]) & 0xFF) << (Int32(i) % 32)
output[i >> 5] = unwrap(output[i >> 5]) | value
}
return dictionary2array(output)
}
/*
* Convert an array of little-endian words to a string
*/
func binl2rstr(_ input: [Int32]) -> [CUnsignedChar] {
var output: [CUnsignedChar] = []
for i in stride(from: 0, to: input.count * 32, by: 8) {
// [i>>5] >>>
let value: Int32 = zeroFillRightShift(input[i>>5], Int32(i % 32)) & 0xFF
output.append(CUnsignedChar(value))
}
return output
}
/*
* Calculate the MD5 of a raw string
*/
func rstr_md5(_ input: [CUnsignedChar]) -> [CUnsignedChar] {
return binl2rstr(binl_md5(rstr2binl(input), input.count * 8))
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
func safe_add(_ x: Int32, _ y: Int32) -> Int32 {
let lsw = (x & 0xFFFF) + (y & 0xFFFF)
let msw = (x >> 16) + (y >> 16) + (lsw >> 16)
return (msw << 16) | (lsw & 0xFFFF)
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
func bit_rol(_ num: Int32, _ cnt: Int32) -> Int32 {
// num >>>
return (num << cnt) | zeroFillRightShift(num, (32 - cnt))
}
/*
* These funcs implement the four basic operations the algorithm uses.
*/
func md5_cmn(_ q: Int32, _ a: Int32, _ b: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 {
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b)
}
func md5_ff(_ a: Int32, _ b: Int32, _ c: Int32, _ d: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 {
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t)
}
func md5_gg(_ a: Int32, _ b: Int32, _ c: Int32, _ d: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 {
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t)
}
func md5_hh(_ a: Int32, _ b: Int32, _ c: Int32, _ d: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 {
return md5_cmn(b ^ c ^ d, a, b, x, s, t)
}
func md5_ii(_ a: Int32, _ b: Int32, _ c: Int32, _ d: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 {
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t)
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length.
*/
func binl_md5(_ input: [Int32], _ len: Int) -> [Int32] {
/* append padding */
var x: [Int: Int32] = [:]
for (index, value) in input.enumerated() {
x[index] = value
}
let value: Int32 = 0x80 << Int32((len) % 32)
x[len >> 5] = unwrap(x[len >> 5]) | value
// >>> 9
let index = (((len + 64) >> 9) << 4) + 14
x[index] = unwrap(x[index]) | Int32(len)
var a: Int32 = 1732584193
var b: Int32 = -271733879
var c: Int32 = -1732584194
var d: Int32 = 271733878
for i in stride(from: 0, to: length(x), by: 16) {
let olda: Int32 = a
let oldb: Int32 = b
let oldc: Int32 = c
let oldd: Int32 = d
a = md5_ff(a, b, c, d, unwrap(x[i + 0]), 7 , -680876936)
d = md5_ff(d, a, b, c, unwrap(x[i + 1]), 12, -389564586)
c = md5_ff(c, d, a, b, unwrap(x[i + 2]), 17, 606105819)
b = md5_ff(b, c, d, a, unwrap(x[i + 3]), 22, -1044525330)
a = md5_ff(a, b, c, d, unwrap(x[i + 4]), 7 , -176418897)
d = md5_ff(d, a, b, c, unwrap(x[i + 5]), 12, 1200080426)
c = md5_ff(c, d, a, b, unwrap(x[i + 6]), 17, -1473231341)
b = md5_ff(b, c, d, a, unwrap(x[i + 7]), 22, -45705983)
a = md5_ff(a, b, c, d, unwrap(x[i + 8]), 7 , 1770035416)
d = md5_ff(d, a, b, c, unwrap(x[i + 9]), 12, -1958414417)
c = md5_ff(c, d, a, b, unwrap(x[i + 10]), 17, -42063)
b = md5_ff(b, c, d, a, unwrap(x[i + 11]), 22, -1990404162)
a = md5_ff(a, b, c, d, unwrap(x[i + 12]), 7 , 1804603682)
d = md5_ff(d, a, b, c, unwrap(x[i + 13]), 12, -40341101)
c = md5_ff(c, d, a, b, unwrap(x[i + 14]), 17, -1502002290)
b = md5_ff(b, c, d, a, unwrap(x[i + 15]), 22, 1236535329)
a = md5_gg(a, b, c, d, unwrap(x[i + 1]), 5 , -165796510)
d = md5_gg(d, a, b, c, unwrap(x[i + 6]), 9 , -1069501632)
c = md5_gg(c, d, a, b, unwrap(x[i + 11]), 14, 643717713)
b = md5_gg(b, c, d, a, unwrap(x[i + 0]), 20, -373897302)
a = md5_gg(a, b, c, d, unwrap(x[i + 5]), 5 , -701558691)
d = md5_gg(d, a, b, c, unwrap(x[i + 10]), 9 , 38016083)
c = md5_gg(c, d, a, b, unwrap(x[i + 15]), 14, -660478335)
b = md5_gg(b, c, d, a, unwrap(x[i + 4]), 20, -405537848)
a = md5_gg(a, b, c, d, unwrap(x[i + 9]), 5 , 568446438)
d = md5_gg(d, a, b, c, unwrap(x[i + 14]), 9 , -1019803690)
c = md5_gg(c, d, a, b, unwrap(x[i + 3]), 14, -187363961)
b = md5_gg(b, c, d, a, unwrap(x[i + 8]), 20, 1163531501)
a = md5_gg(a, b, c, d, unwrap(x[i + 13]), 5 , -1444681467)
d = md5_gg(d, a, b, c, unwrap(x[i + 2]), 9 , -51403784)
c = md5_gg(c, d, a, b, unwrap(x[i + 7]), 14, 1735328473)
b = md5_gg(b, c, d, a, unwrap(x[i + 12]), 20, -1926607734)
a = md5_hh(a, b, c, d, unwrap(x[i + 5]), 4 , -378558)
d = md5_hh(d, a, b, c, unwrap(x[i + 8]), 11, -2022574463)
c = md5_hh(c, d, a, b, unwrap(x[i + 11]), 16, 1839030562)
b = md5_hh(b, c, d, a, unwrap(x[i + 14]), 23, -35309556)
a = md5_hh(a, b, c, d, unwrap(x[i + 1]), 4 , -1530992060)
d = md5_hh(d, a, b, c, unwrap(x[i + 4]), 11, 1272893353)
c = md5_hh(c, d, a, b, unwrap(x[i + 7]), 16, -155497632)
b = md5_hh(b, c, d, a, unwrap(x[i + 10]), 23, -1094730640)
a = md5_hh(a, b, c, d, unwrap(x[i + 13]), 4 , 681279174)
d = md5_hh(d, a, b, c, unwrap(x[i + 0]), 11, -358537222)
c = md5_hh(c, d, a, b, unwrap(x[i + 3]), 16, -722521979)
b = md5_hh(b, c, d, a, unwrap(x[i + 6]), 23, 76029189)
a = md5_hh(a, b, c, d, unwrap(x[i + 9]), 4 , -640364487)
d = md5_hh(d, a, b, c, unwrap(x[i + 12]), 11, -421815835)
c = md5_hh(c, d, a, b, unwrap(x[i + 15]), 16, 530742520)
b = md5_hh(b, c, d, a, unwrap(x[i + 2]), 23, -995338651)
a = md5_ii(a, b, c, d, unwrap(x[i + 0]), 6 , -198630844)
d = md5_ii(d, a, b, c, unwrap(x[i + 7]), 10, 1126891415)
c = md5_ii(c, d, a, b, unwrap(x[i + 14]), 15, -1416354905)
b = md5_ii(b, c, d, a, unwrap(x[i + 5]), 21, -57434055)
a = md5_ii(a, b, c, d, unwrap(x[i + 12]), 6 , 1700485571)
d = md5_ii(d, a, b, c, unwrap(x[i + 3]), 10, -1894986606)
c = md5_ii(c, d, a, b, unwrap(x[i + 10]), 15, -1051523)
b = md5_ii(b, c, d, a, unwrap(x[i + 1]), 21, -2054922799)
a = md5_ii(a, b, c, d, unwrap(x[i + 8]), 6 , 1873313359)
d = md5_ii(d, a, b, c, unwrap(x[i + 15]), 10, -30611744)
c = md5_ii(c, d, a, b, unwrap(x[i + 6]), 15, -1560198380)
b = md5_ii(b, c, d, a, unwrap(x[i + 13]), 21, 1309151649)
a = md5_ii(a, b, c, d, unwrap(x[i + 4]), 6 , -145523070)
d = md5_ii(d, a, b, c, unwrap(x[i + 11]), 10, -1120210379)
c = md5_ii(c, d, a, b, unwrap(x[i + 2]), 15, 718787259)
b = md5_ii(b, c, d, a, unwrap(x[i + 9]), 21, -343485551)
a = safe_add(a, olda)
b = safe_add(b, oldb)
c = safe_add(c, oldc)
d = safe_add(d, oldd)
}
return [a, b, c, d]
}
// MARK: - Helper
func length(_ dictionary: [Int: Int32]) -> Int {
return (dictionary.keys.max() ?? 0) + 1
}
func dictionary2array(_ dictionary: [Int: Int32]) -> [Int32] {
var array = Array<Int32>(repeating: 0, count: dictionary.keys.count)
for i in Array(dictionary.keys).sorted() {
array[i] = unwrap(dictionary[i])
}
return array
}
func unwrap(_ value: Int32?, _ fallback: Int32 = 0) -> Int32 {
if let value = value {
return value
}
return fallback
}
func zeroFillRightShift(_ num: Int32, _ count: Int32) -> Int32 {
let value = UInt32(bitPattern: num) >> UInt32(bitPattern: count)
return Int32(bitPattern: value)
}
| mit | a26388d49724000f195fb19d71555aae | 32.434164 | 122 | 0.556466 | 2.36174 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/WordPressTest/RegisterDomainDetailsViewModelTests.swift | 1 | 11169 | @testable import WordPress
import XCTest
extension FullyQuotedDomainSuggestion {
init(json: [String: AnyObject]) throws {
guard let domain = json["domain_name"] as? String else {
throw DomainsServiceRemote.ResponseError.decodingFailed
}
let domainName = domain
let productID = json["product_id"] as? Int ?? nil
let supportsPrivacy = json["supports_privacy"] as? Bool ?? nil
let costString = json["cost"] as? String ?? ""
let saleCostString: String? = nil
self.init(domainName: domainName, productID: productID, supportsPrivacy: supportsPrivacy, costString: costString, saleCostString: saleCostString)
}
}
extension JetpackSiteRef {
static func mock(siteID: Int = 9001, username: String = "test") -> JetpackSiteRef {
let payload: NSString = """
{
"siteID": \(siteID),
"username": "\(username)",
"homeURL": "url",
"hasBackup": true,
"hasPaidPlan": true,
"isSelfHostedWithoutJetpack": false,
"xmlRPC": null,
}
""" as NSString
return try! JSONDecoder().decode(JetpackSiteRef.self, from: payload.data(using: 8)!)
}
}
class RegisterDomainDetailsViewModelTests: XCTestCase {
typealias Change = RegisterDomainDetailsViewModel.Change
typealias CellIndex = RegisterDomainDetailsViewModel.CellIndex
typealias SectionIndex = RegisterDomainDetailsViewModel.SectionIndex
typealias RowType = RegisterDomainDetailsViewModel.RowType
typealias Localized = RegisterDomainDetailsViewModel.Localized
typealias EditableKeyValueRow = RegisterDomainDetailsViewModel.Row.EditableKeyValueRow
typealias MockData = RegisterDomainDetailsServiceProxyMock.MockData
var viewModel: RegisterDomainDetailsViewModel!
var changeArray: [Change] = []
override func setUp() {
super.setUp()
let domainSuggestion = try! FullyQuotedDomainSuggestion(json: ["domain_name": "" as AnyObject])
let siteID = 9001
viewModel = RegisterDomainDetailsViewModel(siteID: siteID, domain: domainSuggestion) { _ in return }
viewModel.onChange = { [weak self] (change: Change) in
self?.changeArray.append(change)
}
changeArray = []
}
func testEnableAddAddressRow() {
let addressSection = viewModel.sections[SectionIndex.address.rawValue]
let initialRowCount = addressSection.rows.count
viewModel.registerDomainDetailsService = RegisterDomainDetailsServiceProxyMock()
viewModel.enableAddAddressRow()
XCTAssert(addressSection.rows[1] ==
RowType.addAddressLine(title: String(format: Localized.Address.addNewAddressLine, "\(2)"))
)
XCTAssert(changeArray[0] == Change.addNewAddressLineEnabled(
indexPath: IndexPath(row: 1, section: SectionIndex.address.rawValue))
)
XCTAssert(addressSection.rows.count == initialRowCount + 1)
viewModel.enableAddAddressRow()
// we expect nothing to change
XCTAssert(changeArray.count == 1)
XCTAssert(addressSection.rows.count == initialRowCount + 1)
}
func testReplaceAddAddressRow() {
let addressSection = viewModel.sections[SectionIndex.address.rawValue]
let initialRowCount = addressSection.rows.count
viewModel.registerDomainDetailsService = RegisterDomainDetailsServiceProxyMock()
viewModel.enableAddAddressRow()
viewModel.replaceAddNewAddressLine()
XCTAssert(addressSection.rows[1] ==
RegisterDomainDetailsViewModel.addressLine(row: 1)
)
XCTAssert(changeArray[0] == Change.addNewAddressLineEnabled(
indexPath: IndexPath(row: 1, section: SectionIndex.address.rawValue))
)
XCTAssert(changeArray[1] == Change.addNewAddressLineReplaced(
indexPath: IndexPath(row: 1, section: SectionIndex.address.rawValue))
)
XCTAssert(addressSection.rows.count == initialRowCount + 1)
viewModel.enableAddAddressRow()
XCTAssert(addressSection.rows[2] ==
RowType.addAddressLine(title: String(format: Localized.Address.addNewAddressLine, "\(3)"))
)
XCTAssert(changeArray[2] == Change.addNewAddressLineEnabled(
indexPath: IndexPath(row: 2, section: SectionIndex.address.rawValue))
)
XCTAssert(addressSection.rows.count == initialRowCount + 2)
viewModel.replaceAddNewAddressLine()
XCTAssert(addressSection.rows[2] ==
RegisterDomainDetailsViewModel.addressLine(row: 2)
)
XCTAssert(addressSection.rows.count == initialRowCount + 2)
XCTAssert(changeArray[3] == Change.addNewAddressLineReplaced(indexPath: IndexPath(row: 2, section: SectionIndex.address.rawValue)))
}
func testAddAddressRowMaxLimit() {
let addressSection = viewModel.sections[SectionIndex.address.rawValue]
let initialRowCount = addressSection.rows.count
viewModel.registerDomainDetailsService = RegisterDomainDetailsServiceProxyMock()
viewModel.enableAddAddressRow()
viewModel.replaceAddNewAddressLine()
viewModel.enableAddAddressRow()
viewModel.replaceAddNewAddressLine()
viewModel.enableAddAddressRow()
viewModel.replaceAddNewAddressLine()
viewModel.enableAddAddressRow()
viewModel.replaceAddNewAddressLine()
viewModel.enableAddAddressRow()
viewModel.replaceAddNewAddressLine()
XCTAssert(addressSection.rows.count == initialRowCount + RegisterDomainDetailsViewModel.Constant.maxExtraAddressLine)
viewModel.enableAddAddressRow()
viewModel.replaceAddNewAddressLine()
viewModel.enableAddAddressRow()
viewModel.replaceAddNewAddressLine()
XCTAssert(addressSection.rows.count == initialRowCount + RegisterDomainDetailsViewModel.Constant.maxExtraAddressLine)
}
func testEnableSubmitValidation() {
viewModel.registerDomainDetailsService = RegisterDomainDetailsServiceProxyMock(emptyPrefillData: true)
XCTAssert(viewModel.isValid(inContext: .clientSide) == false)
viewModel.updateValue("firstName", at: CellIndex.ContactInformation.firstName.indexPath)
viewModel.updateValue("lastName", at: CellIndex.ContactInformation.lastName.indexPath)
viewModel.updateValue("[email protected]", at: CellIndex.ContactInformation.email.indexPath)
viewModel.updateValue("Country", at: CellIndex.ContactInformation.country.indexPath)
viewModel.updateValue("90", at: CellIndex.PhoneNumber.countryCode.indexPath)
viewModel.updateValue("1231122", at: CellIndex.PhoneNumber.number.indexPath)
viewModel.updateValue("City", at: IndexPath(row: viewModel.addressSectionIndexHelper.cityIndex, section: SectionIndex.address.rawValue))
viewModel.updateValue("State", at: IndexPath(row: viewModel.addressSectionIndexHelper.stateIndex, section: SectionIndex.address.rawValue))
viewModel.updateValue("423345", at: IndexPath(row: viewModel.addressSectionIndexHelper.postalCodeIndex, section: SectionIndex.address.rawValue))
viewModel.updateValue("address line", at: IndexPath(row: viewModel.addressSectionIndexHelper.extraAddressLineCount, section: SectionIndex.address.rawValue))
XCTAssert(viewModel.isValid(inContext: .clientSide) == true)
viewModel.enableAddAddressRow()
viewModel.replaceAddNewAddressLine()
XCTAssert(changeArray.lazy.reversed()[1] == Change.addNewAddressLineEnabled(indexPath: IndexPath(row: 1,
section: SectionIndex.address.rawValue)))
XCTAssert(changeArray.lazy.reversed()[0] == Change.addNewAddressLineReplaced(indexPath: IndexPath(row: 1,
section: SectionIndex.address.rawValue)))
XCTAssert(viewModel.isValid(inContext: .clientSide))
}
func testPrefillData() {
viewModel.registerDomainDetailsService = RegisterDomainDetailsServiceProxyMock(emptyPrefillData: false)
viewModel.prefill()
let contactInformationSection = viewModel.sections[SectionIndex.contactInformation.rawValue]
let addressSection = viewModel.sections[SectionIndex.address.rawValue]
let phoneSection = viewModel.sections[SectionIndex.phone.rawValue]
XCTAssert(contactInformationSection.rows[CellIndex.ContactInformation.country.rawValue].editableRow?.jsonValue == MockData.countryCode)
XCTAssert(contactInformationSection.rows[CellIndex.ContactInformation.country.rawValue].editableRow?.value == MockData.countryName)
XCTAssert(contactInformationSection.rows[CellIndex.ContactInformation.email.rawValue].editableRow?.value == MockData.email)
XCTAssert(contactInformationSection.rows[CellIndex.ContactInformation.firstName.rawValue].editableRow?.value == MockData.firstName)
XCTAssert(contactInformationSection.rows[CellIndex.ContactInformation.lastName.rawValue].editableRow?.value == MockData.lastName)
XCTAssert(contactInformationSection.rows[CellIndex.ContactInformation.organization.rawValue].editableRow?.value == MockData.organization)
XCTAssert(addressSection.rows[viewModel.addressSectionIndexHelper.cityIndex].editableRow?.value == MockData.city)
XCTAssert(addressSection.rows[viewModel.addressSectionIndexHelper.addressLine1].editableRow?.value == MockData.address1)
XCTAssert(addressSection.rows[viewModel.addressSectionIndexHelper.postalCodeIndex].editableRow?.value == MockData.postalCode)
XCTAssert(addressSection.rows[viewModel.addressSectionIndexHelper.stateIndex].editableRow?.jsonValue == MockData.stateCode)
XCTAssert(addressSection.rows[viewModel.addressSectionIndexHelper.stateIndex].editableRow?.value == MockData.stateName)
XCTAssert(phoneSection.rows[CellIndex.PhoneNumber.countryCode.rawValue].editableRow?.value == MockData.phoneCountryCode)
XCTAssert(phoneSection.rows[CellIndex.PhoneNumber.number.rawValue].editableRow?.value == MockData.phoneNumber)
}
func testValueSanitizer() {
let latin1SupplementAndLatinExtendedALetters = "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſ"
let latinASCIIApproximates = "AAAAAAAECEEEEIIIIDNOOOOOOUUUUYTHssaaaaaaaeceeeeiiiidnoooooouuuuythyAaAaAaCcCcCcCcDdDdEeEeEeEeEeGgGgGgGgHhHhIiIiIiIiIiIJijJjKkqLlLlLlLlLlNnNnNn'nNnOoOoOoOEoeRrRrRrSsSsSsSsTtTtTtUuUuUuUuUuUuWwYyYZzZzZzs"
let result = RegisterDomainDetailsViewModel.transformToLatinASCII(value: latin1SupplementAndLatinExtendedALetters)
XCTAssertEqual(result, latinASCIIApproximates)
}
}
| gpl-2.0 | 4d6b8fbd083beea071e011ad51e5ae27 | 48.233184 | 247 | 0.729119 | 4.802712 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Utility/BackgroundTasks/BackgroundTasksCoordinator.swift | 1 | 9119 | import BackgroundTasks
protocol BackgroundTask {
static var identifier: String { get }
// MARK: - Scheduling
/// Returns a schedule request for this task, so it can be scheduled by the coordinator.
///
func nextRunDate() -> Date?
/// This method allows the task to perform extra processing after scheduling the BG Task.
///
func didSchedule(completion: @escaping (Result<Void, Error>) -> Void)
// MARK: - Execution
func expirationHandler()
/// Runs the background task.
///
/// - Parameters:
/// - osTask: the `BGTask` associated with this `BackgroundTask`.
/// - event: called for important events in the background tasks execution.
///
func run(onError: @escaping (Error) -> Void, completion: @escaping (_ cancelled: Bool) -> Void)
}
/// Events during the execution of background tasks.
///
enum BackgroundTaskEvent {
case start(identifier: String)
case error(identifier: String, error: Error)
case expirationHandlerCalled(identifier: String)
case taskCompleted(identifier: String, cancelled: Bool)
case rescheduled(identifier: String)
}
/// An event handler for background task events.
///
protocol BackgroundTaskEventHandler {
func handle(_ event: BackgroundTaskEvent)
}
/// The task coordinator. This is the entry point for registering and scheduling background tasks.
///
class BackgroundTasksCoordinator {
enum SchedulingError: Error {
case schedulingFailed(tasksAndErrors: [String: Error])
case schedulingFailed(task: String, error: Error)
}
/// Event handler. Useful for logging or tracking purposes.
///
private let eventHandler: BackgroundTaskEventHandler
/// The task scheduler. It's a weak reference because the scheduler retains the coordinator through the
///
private let scheduler: BGTaskScheduler
/// The tasks that were registered through this coordinator on initialization.
///
private let registeredTasks: [BackgroundTask]
/// Default initializer. Immediately registers the task handlers with the scheduler.
///
/// - Parameters:
/// - scheduler: The scheduler to use.
/// - tasks: The tasks that this coordinator will manage.
///
init(
scheduler: BGTaskScheduler = BGTaskScheduler.shared,
tasks: [BackgroundTask],
eventHandler: BackgroundTaskEventHandler) {
self.eventHandler = eventHandler
self.scheduler = scheduler
self.registeredTasks = tasks
for task in tasks {
if FeatureFlag.weeklyRoundupBGProcessingTask.enabled {
// https://github.com/wordpress-mobile/WordPress-iOS/issues/18156
// we still need to register to handle the old identifier = "org.wordpress.bgtask.weeklyroundup"
// in order to handle previously scheduled app refresh tasks before this enhancement.
//
// When the old identifier AppRefreshTask is triggered this will re-schedule using the new identifier going forward
// at some point in future when this FeatureFlag is removed and most users are on new version of app this can be removed
scheduler.register(forTaskWithIdentifier: WeeklyRoundupBackgroundTask.Constants.taskIdentifier, using: nil) { osTask in
self.schedule(task) { [weak self] result in
self?.taskScheduledCompleted(osTask, identifier: type(of: task).identifier, result: result, cancelled: false)
}
}
}
scheduler.register(forTaskWithIdentifier: type(of: task).identifier, using: nil) { osTask in
guard Feature.enabled(.weeklyRoundup) && JetpackNotificationMigrationService.shared.shouldPresentNotifications() else {
osTask.setTaskCompleted(success: false)
eventHandler.handle(.taskCompleted(identifier: type(of: task).identifier, cancelled: true))
return
}
eventHandler.handle(.start(identifier: type(of: task).identifier))
osTask.expirationHandler = {
eventHandler.handle(.expirationHandlerCalled(identifier: type(of: task).identifier))
task.expirationHandler()
}
task.run(onError: { error in
eventHandler.handle(.error(identifier: type(of: task).identifier, error: error))
}) { cancelled in
eventHandler.handle(.taskCompleted(identifier: type(of: task).identifier, cancelled: cancelled))
if FeatureFlag.weeklyRoundupBGProcessingTask.enabled {
self.schedule(task) { [weak self] result in
self?.taskScheduledCompleted(osTask, identifier: type(of: task).identifier, result: result, cancelled: cancelled)
}
} else {
//TODO - remove after removing feature flag
self.schedule(task) { result in
switch result {
case .success:
eventHandler.handle(.rescheduled(identifier: type(of: task).identifier))
case .failure(let error):
eventHandler.handle(.error(identifier: type(of: task).identifier, error: error))
}
osTask.setTaskCompleted(success: !cancelled)
}
}
}
}
}
}
func taskScheduledCompleted(_ osTask: BGTask, identifier: String, result: Result<Void, Error>, cancelled: Bool) {
switch result {
case .success:
eventHandler.handle(.rescheduled(identifier: identifier))
case .failure(let error):
eventHandler.handle(.error(identifier: identifier, error: error))
}
osTask.setTaskCompleted(success: !cancelled)
}
/// Schedules the registered tasks. The reason this step is separated from the registration of the tasks, is that we need
/// to make sure the task registration completes before the App finishes launching, while scheduling can be taken care
/// of separately.
///
/// Ref: https://developer.apple.com/documentation/backgroundtasks/bgtaskscheduler
///
func scheduleTasks(completion: @escaping (Result<Void, Error>) -> Void) {
var tasksAndErrors = [String: Error]()
scheduler.getPendingTaskRequests { [weak self] scheduledRequests in
guard let self = self else {
return
}
let tasksToSchedule = self.registeredTasks.filter { task in
!scheduledRequests.contains { request in
request.identifier == type(of: task).identifier
}
}
for task in tasksToSchedule {
self.schedule(task) { result in
if case .failure(let error) = result {
tasksAndErrors[type(of: task).identifier] = error
}
}
}
if tasksAndErrors.isEmpty {
completion(.success(()))
} else {
completion(.failure(SchedulingError.schedulingFailed(tasksAndErrors: tasksAndErrors)))
}
}
}
func schedule(_ task: BackgroundTask, completion: @escaping (Result<Void, Error>) -> Void) {
guard let nextDate = task.nextRunDate() else {
return
}
let request = createBGTaskRequest(task, beginDate: nextDate)
do {
try self.scheduler.submit(request)
task.didSchedule(completion: completion)
} catch {
completion(.failure(SchedulingError.schedulingFailed(task: type(of: task).identifier, error: error)))
}
}
func createBGTaskRequest(_ task: BackgroundTask, beginDate: Date) -> BGTaskRequest {
if FeatureFlag.weeklyRoundupBGProcessingTask.enabled {
let bgProcessingTaskRequest = BGProcessingTaskRequest(identifier: type(of: task).identifier)
bgProcessingTaskRequest.requiresNetworkConnectivity = true
bgProcessingTaskRequest.earliestBeginDate = beginDate
return bgProcessingTaskRequest
}
let appRefreshTaskRequest = BGAppRefreshTaskRequest(identifier: type(of: task).identifier)
appRefreshTaskRequest.earliestBeginDate = beginDate
return appRefreshTaskRequest
}
// MARK: - Querying Data
func getScheduledExecutionDate(taskIdentifier: String, completion: @escaping (Date?) -> Void) {
scheduler.getPendingTaskRequests { requests in
guard let weeklyRoundupRequest = requests.first(where: { $0.identifier == taskIdentifier }) else {
completion(nil)
return
}
return completion(weeklyRoundupRequest.earliestBeginDate)
}
}
}
| gpl-2.0 | 4a981c230522540fda4023036a13cd9c | 39.709821 | 141 | 0.615857 | 5.345252 | false | false | false | false |
zixun/GodEye | GodEye/Classes/Main/Controller/TabController/FileController/FileBrowser/FileList/FileListPreview.swift | 1 | 1741 | //
// FileListPreview.swift
// FileBrowser
//
// Created by Roy Marmelstein on 13/02/2016.
// Copyright © 2016 Roy Marmelstein. All rights reserved.
//
import UIKit
import QuickLook
extension FileListViewController: UIViewControllerPreviewingDelegate {
//MARK: UIViewControllerPreviewingDelegate
func registerFor3DTouch() {
if #available(iOS 9.0, *) {
if self.traitCollection.forceTouchCapability == UIForceTouchCapability.available {
registerForPreviewing(with: self, sourceView: tableView)
}
}
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
if #available(iOS 9.0, *) {
if let indexPath = tableView.indexPathForRow(at: location) {
let selectedFile = fileForIndexPath(indexPath)
previewingContext.sourceRect = tableView.rectForRow(at: indexPath)
if selectedFile.isDirectory == false {
return previewManager.previewViewControllerForFile(selectedFile, fromNavigation: false)
}
}
}
return nil
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
if let previewTransitionViewController = viewControllerToCommit as? PreviewTransitionViewController {
self.navigationController?.pushViewController(previewTransitionViewController.quickLookPreviewController, animated: true)
}
else {
self.navigationController?.pushViewController(viewControllerToCommit, animated: true)
}
}
}
| mit | 44cc0d33e5210672ad62196752519258 | 35.25 | 143 | 0.68046 | 6.14841 | false | false | false | false |
lucasmpaim/GuizionCardView | guizion-card-view/Classes/CardView.swift | 1 | 6447 | //
// CardView.swift
// Pods
//
// Created by Guizion Labs on 07/07/16.
//
//
import Foundation
import UIKit
/**
CardView is a iOS UI Library for Credit Card animation
- Author: Guizion Labs
- Version: 1.0
*/
open class CardView: UIView {
public enum State {
case front
case back
}
fileprivate var frontView = CardFrontView()
fileprivate var backView = CardBackView()
fileprivate let noCardView = UIImageView(image: UIImage.loadImageFromPodBundle("no_card"))
fileprivate let cardFormatter = CardNumberFormatter()
fileprivate var lastCardType = CardTypes.None
open var state: State = .front
/**
Retrive the card type
- SeeAlso: `CardTypes`
*/
open var card: CreditCard = CreditCard()
open var bundleAnimationDuration = 2.5
open var flipAnimationDuration = 1
open override func layoutSubviews() {
noCardView.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
frontView.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
backView.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
func setupViews() {
self.addSubview(backView)
self.addSubview(noCardView)
self.addSubview(frontView)
frontView.cardNumber.textColor = UIColor(hex: "#D7D7D7")
frontView.cardName.textColor = UIColor(hex: "#D4D4D4")
frontView.validateNumber.textColor = UIColor(hex: "#D4D4D4")
}
/**
Use this function to flip de credit card to the back-side
- Throws: CreditCardErrors.NumberNotProvided
```
do{
try self.flip()
} catch CreditCardErrors.NumberNotProvided {
} catch _ {
}
```
*/
open func flip(_ onComplete: @escaping () -> Void) throws {
if frontView.image == nil || backView.image == nil {
throw CreditCardErrors.numberNotProvided
}
let transitionOptions: UIViewAnimationOptions
var views : (frontView: UIView, backView: UIView)
if state == .front {
views = (frontView: frontView, backView: backView)
transitionOptions = UIViewAnimationOptions.transitionFlipFromRight
} else {
views = (frontView: backView, backView: frontView)
transitionOptions = UIViewAnimationOptions.transitionFlipFromLeft
}
UIView.transition(from: views.frontView,
to: views.backView,
duration: 1,
options: transitionOptions,
completion: { [weak self] _ in
self?.state = self?.state == .front ? .back : .front
onComplete()
})
}
open func updateNumber(_ number: String) {
frontView.cardNumber.text = number
if number.isEmpty {
lastCardType = .None
frontView.image = nil
backView.image = nil
frontView.cardNumber.textColor = UIColor(hex: "#D7D7D7")
frontView.cardName.textColor = UIColor(hex: "#D4D4D4")
frontView.validateNumber.textColor = UIColor(hex: "#D4D4D4")
return
}
let card = self.cardFormatter.verifyPattern(number)
self.card = card
if card.cardType == .None {
frontView.image = nil
backView.image = nil
frontView.cardNumber.textColor = UIColor(hex: "#D7D7D7")
frontView.cardName.textColor = UIColor(hex: "#D4D4D4")
frontView.validateNumber.textColor = UIColor(hex: "#D4D4D4")
}
if card.cardType != lastCardType {
frontView.image = UIImage.loadImageFromPodBundle(card.card?.frontImage ?? "notrecognized_front")
backView.image = UIImage.loadImageFromPodBundle(card.card?.backImage ?? "notrecognized_back")
backView.ccvNumber.textColor = UIColor(hex: card.card?.ccvColor ?? "#4B4B4B")
frontView.cardNumber.textColor = UIColor(hex: card.card?.numberColor ?? "#434343")
frontView.cardName.textColor = UIColor(hex: card.card?.nameColor ?? "#656565")
frontView.validateNumber.textColor = UIColor(hex: card.card?.expirationColor ?? "#656565")
frontView.cardNumber.textMask = card.card?.mask ?? "#### #### #### ####"
bubbleAnimation() { }
}
lastCardType = card.cardType
}
open func updateCCVNumber(_ number: String) {
backView.ccvNumber.text = number
}
open func updateName(_ name: String) {
frontView.cardName.text = name
}
open func updateExpirationDate(_ date: String) {
frontView.validateNumber.text = date
}
func bubbleAnimation(_ onComplete: @escaping () -> Void) {
let maskLayer = CAShapeLayer()
let maskRect = CGRect(x: -25, y: bounds.maxY - 25, width: 50, height: 50);
let path = CGPath(ellipseIn: maskRect, transform: nil)
let finalRect = CGRect(x: -bounds.width*2, y: bounds.maxY - bounds.height*2, width: bounds.width * 4, height: bounds.height * 4)
let finalPath = CGPath(ellipseIn: finalRect, transform: nil)
maskLayer.path = path
frontView.layer.mask = maskLayer
CATransaction.begin()
CATransaction.setCompletionBlock({
print("completed")
onComplete()
})
let anim = CABasicAnimation(keyPath: "path")
anim.fromValue = maskLayer.path
anim.toValue = finalPath
anim.duration = 2.5
anim.isRemovedOnCompletion = true
anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
maskLayer.add(anim, forKey: nil)
maskLayer.path = finalPath
CATransaction.commit()
}
}
| mit | bbdcad3e819223712268065c7285dac1 | 31.396985 | 136 | 0.575151 | 4.772021 | false | false | false | false |
Redth/azure-mobile-services | quickstart/iOS-Swift/ZUMOAPPNAME/ZUMOAPPNAME/ToDoTableViewController.swift | 1 | 5562 | // ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import UIKit
class ToDoTableViewController: UITableViewController, ToDoItemDelegate {
var records = [NSDictionary]()
var table : MSTable?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let client = MSClient(applicationURLString: "ZUMOAPPURL", applicationKey: "ZUMOAPPKEY")
self.table = client.tableWithName("TodoItem")!
self.refreshControl?.addTarget(self, action: "onRefresh:", forControlEvents: UIControlEvents.ValueChanged)
self.refreshControl?.beginRefreshing()
self.onRefresh(self.refreshControl)
}
func onRefresh(sender: UIRefreshControl!) {
let predicate = NSPredicate(format: "complete == NO")
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.table!.readWithPredicate(predicate) {
result, totalCount, error in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if error != nil {
println("Error: " + error.description)
return
}
self.records = result as [NSDictionary]
println("Information: retrieved %d records", result.count)
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// Table
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
{
return true
}
override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle
{
return UITableViewCellEditingStyle.Delete
}
override func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String!
{
return "Complete"
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
let record = self.records[indexPath.row]
let completedItem = record.mutableCopy() as NSMutableDictionary
completedItem["complete"] = true
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.table!.update(completedItem) {
(result, error) in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if error != nil {
println("Error: " + error.description)
return
}
self.records.removeAtIndex(indexPath.row)
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.records.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellIdentifier = "Cell"
let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as UITableViewCell
let item = self.records[indexPath.row]
cell.textLabel?.text = item["text"] as? String
cell.textLabel?.textColor = UIColor.blackColor()
return cell
}
// Navigation
@IBAction func addItem(sender : AnyObject) {
self.performSegueWithIdentifier("addItem", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!)
{
if segue.identifier == "addItem" {
let todoController = segue.destinationViewController as ToDoItemViewController
todoController.delegate = self
}
}
// ToDoItemDelegate
func didSaveItem(text: String)
{
if text.isEmpty {
return
}
let itemToInsert = ["text": text, "complete": false]
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.table!.insert(itemToInsert) {
(item, error) in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if error != nil {
println("Error: " + error.description)
} else {
self.records.append(item)
self.tableView.reloadData()
}
}
}
}
| apache-2.0 | 1b591c9d7398e2931be2ac04859f658f | 35.116883 | 155 | 0.625674 | 5.967811 | false | false | false | false |
marklin2012/iOS_Animation | Section4/Chapter23/O2Logo_starter/O2Logo/MasterViewController.swift | 3 | 1770 | //
// MasterViewController.swift
// O2Logo
//
// Created by O2.LinYi on 16/3/21.
// Copyright © 2016年 jd.com. All rights reserved.
//
import UIKit
import QuartzCore
//
// Util delay function
//
func delay(seconds seconds: Double, completion:()->()) {
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64( Double(NSEC_PER_SEC) * seconds ))
dispatch_after(popTime, dispatch_get_main_queue()) {
completion()
}
}
class MasterViewController: UIViewController {
let logo = RWLogoLayer.logoLayer()
let transition = RevealAnimator()
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.delegate = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// add the tap gesture recognizer
let tap = UITapGestureRecognizer(target: self, action: "didTap")
view.addGestureRecognizer(tap)
// add the logo to the view
logo.position = CGPoint(x: view.layer.bounds.size.width/2, y: view.layer.bounds.size.height/2 + 30)
logo.fillColor = UIColor.whiteColor().CGColor
view.layer.addSublayer(logo)
}
// MARK: - Gesture
func didTap() {
performSegueWithIdentifier("details", sender: nil)
}
}
extension MasterViewController: UINavigationControllerDelegate {
func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.operation = operation
return transition
}
}
| mit | 22cf5036a2450000a1c47b8882b54818 | 24.608696 | 281 | 0.680815 | 4.827869 | false | false | false | false |
saagarjha/iina | iina/PlaySliderCell.swift | 1 | 8835 | //
// PlaySlider.swift
// iina
//
// Created by lhc on 25/7/16.
// Copyright © 2016 lhc. All rights reserved.
//
import Cocoa
// These colors are for 10.13- only
@available(macOS, obsoleted: 10.14)
fileprivate extension NSColor {
static let darkKnobColor = NSColor(calibratedRed: 1, green: 1, blue: 1, alpha: 0.5)
static let lightKnobColor = NSColor(calibratedRed: 0.3, green: 0.3, blue: 0.3, alpha: 1)
static let darkBarColorLeft = NSColor(calibratedWhite: 1, alpha: 0.3)
static let darkBarColorRight = NSColor(calibratedWhite: 1, alpha: 0.1)
static let lightBarColorLeft = NSColor(calibratedRed: 0.239, green: 0.569, blue: 0.969, alpha: 1)
static let lightBarColorRight = NSColor(calibratedWhite: 0.5, alpha: 0.5)
static let lightChapterStrokeColor = NSColor(calibratedWhite: 0.4, alpha: 1)
static let darkChapterStrokeColor = NSColor(calibratedWhite: 0.2, alpha: 1)
}
class PlaySliderCell: NSSliderCell {
weak var _playerCore: PlayerCore!
var playerCore: PlayerCore {
if let player = _playerCore { return player }
let windowController = self.controlView!.window!.windowController
if let mainWindowController = windowController as? MainWindowController {
return mainWindowController.player
}
let player = (windowController as! MiniPlayerWindowController).player
_playerCore = player
return player
}
override var knobThickness: CGFloat {
return knobWidth
}
let knobWidth: CGFloat = 3
let knobHeight: CGFloat = 15
let knobRadius: CGFloat = 1
let barRadius: CGFloat = 1.5
var isInDarkTheme: Bool = true {
didSet {
if #available(macOS 10.14, *) {} else {
self.knobColor = isInDarkTheme ? .darkKnobColor : .lightKnobColor
self.knobActiveColor = isInDarkTheme ? .darkKnobColor : .lightKnobColor
self.barColorLeft = isInDarkTheme ? .darkBarColorLeft : .lightBarColorLeft
self.barColorRight = isInDarkTheme ? .darkBarColorRight : .lightBarColorRight
self.chapterStrokeColor = isInDarkTheme ? .darkChapterStrokeColor : .lightChapterStrokeColor
}
}
}
private var knobColor: NSColor = {
if #available(macOS 10.14, *) {
return NSColor(named: .mainSliderKnob)!
} else {
return .darkKnobColor
}
}()
private var knobActiveColor: NSColor = {
if #available(macOS 10.14, *) {
return NSColor(named: .mainSliderKnobActive)!
} else {
return .darkKnobColor
}
}()
private var barColorLeft: NSColor = {
if #available(macOS 10.14, *) {
return NSColor(named: .mainSliderBarLeft)!
} else {
return .darkBarColorLeft
}
}()
private var barColorRight: NSColor = {
if #available(macOS 10.14, *) {
return NSColor(named: .mainSliderBarRight)!
} else {
return .darkBarColorRight
}
}()
private var chapterStrokeColor: NSColor = {
if #available(macOS 10.14, *) {
return NSColor(named: .mainSliderBarChapterStroke)!
} else {
return .darkChapterStrokeColor
}
}()
var drawChapters = Preference.bool(for: .showChapterPos)
var isPausedBeforeSeeking = false
override func awakeFromNib() {
minValue = 0
maxValue = 100
if #available(macOS 11, *) {
let slider = self.controlView as! NSSlider
// Apple increased the height of sliders in Big Sur. Until we have time to restructure the
// on screen controller to accommodate a larger slider reduce the size of the slider from
// regular to small. This makes the slider match the behavior seen under Catalina.
slider.controlSize = .small
}
}
override func drawKnob(_ knobRect: NSRect) {
// Round the X position for cleaner drawing
let rect = NSMakeRect(round(knobRect.origin.x),
knobRect.origin.y + 0.5 * (knobRect.height - knobHeight),
knobRect.width,
knobHeight)
let isLightTheme = !controlView!.window!.effectiveAppearance.isDark
if #available(macOS 10.14, *), isLightTheme {
NSGraphicsContext.saveGraphicsState()
let shadow = NSShadow()
shadow.shadowBlurRadius = 1
shadow.shadowColor = .controlShadowColor
shadow.shadowOffset = NSSize(width: 0, height: -0.5)
shadow.set()
}
let path = NSBezierPath(roundedRect: rect, xRadius: knobRadius, yRadius: knobRadius)
(isHighlighted ? knobActiveColor : knobColor).setFill()
path.fill()
if #available(macOS 10.14, *), isLightTheme {
path.lineWidth = 0.4
NSColor.controlShadowColor.setStroke()
path.stroke()
NSGraphicsContext.restoreGraphicsState()
}
}
override func knobRect(flipped: Bool) -> NSRect {
let slider = self.controlView as! NSSlider
let barRect = super.barRect(flipped: flipped)
let percentage = slider.doubleValue / (slider.maxValue - slider.minValue)
let pos = min(CGFloat(percentage) * barRect.width, barRect.width - 1);
let rect = super.knobRect(flipped: flipped)
let flippedMultiplier = flipped ? CGFloat(-1) : CGFloat(1)
let height: CGFloat
if #available(macOS 10.16, *) {
height = (barRect.origin.y - rect.origin.y) * 2 + barRect.height
} else {
height = rect.height
}
return NSMakeRect(pos - flippedMultiplier * 0.5 * knobWidth, rect.origin.y, knobWidth, height)
}
override func drawBar(inside rect: NSRect, flipped: Bool) {
let info = playerCore.info
let slider = self.controlView as! NSSlider
/// The position of the knob, rounded for cleaner drawing
let knobPos : CGFloat = round(knobRect(flipped: flipped).origin.x);
/// How far progressed the current video is, used for drawing the bar background
var progress : CGFloat = 0;
if info.isNetworkResource,
info.cacheTime != 0,
let duration = info.videoDuration,
duration.second != 0 {
let pos = Double(info.cacheTime) / Double(duration.second) * 100
progress = round(rect.width * CGFloat(pos / (slider.maxValue - slider.minValue))) + 2;
} else {
progress = knobPos;
}
NSGraphicsContext.saveGraphicsState()
let barRect: NSRect
if #available(macOS 10.16, *) {
barRect = rect
} else {
barRect = NSMakeRect(rect.origin.x, rect.origin.y + 1, rect.width, rect.height - 2)
}
let path = NSBezierPath(roundedRect: barRect, xRadius: barRadius, yRadius: barRadius)
// draw left
let pathLeftRect : NSRect = NSMakeRect(barRect.origin.x, barRect.origin.y, progress, barRect.height)
NSBezierPath(rect: pathLeftRect).addClip();
if #available(macOS 10.14, *), !controlView!.window!.effectiveAppearance.isDark {
// Draw knob shadow in 10.14+ light theme
} else {
// Clip 1px around the knob
path.append(NSBezierPath(rect: NSRect(x: knobPos - 1, y: barRect.origin.y, width: knobWidth + 2, height: barRect.height)).reversed);
}
barColorLeft.setFill()
path.fill()
NSGraphicsContext.restoreGraphicsState()
// draw right
NSGraphicsContext.saveGraphicsState()
let pathRight = NSMakeRect(barRect.origin.x + progress, barRect.origin.y, barRect.width - progress, barRect.height)
NSBezierPath(rect: pathRight).setClip()
barColorRight.setFill()
path.fill()
NSGraphicsContext.restoreGraphicsState()
// draw chapters
NSGraphicsContext.saveGraphicsState()
if drawChapters {
if let totalSec = info.videoDuration?.second {
chapterStrokeColor.setStroke()
var chapters = info.chapters
if chapters.count > 0 {
chapters.remove(at: 0)
chapters.forEach { chapt in
let chapPos = CGFloat(chapt.time.second) / CGFloat(totalSec) * barRect.width
let linePath = NSBezierPath()
linePath.move(to: NSPoint(x: chapPos, y: barRect.origin.y))
linePath.line(to: NSPoint(x: chapPos, y: barRect.origin.y + barRect.height))
linePath.stroke()
}
}
}
}
NSGraphicsContext.restoreGraphicsState()
}
override func barRect(flipped: Bool) -> NSRect {
let rect = super.barRect(flipped: flipped)
return NSMakeRect(0, rect.origin.y, rect.width + rect.origin.x * 2, rect.height)
}
override func startTracking(at startPoint: NSPoint, in controlView: NSView) -> Bool {
isPausedBeforeSeeking = playerCore.info.isPaused
let result = super.startTracking(at: startPoint, in: controlView)
if result {
playerCore.pause()
playerCore.mainWindow.thumbnailPeekView.isHidden = true
}
return result
}
override func stopTracking(last lastPoint: NSPoint, current stopPoint: NSPoint, in controlView: NSView, mouseIsUp flag: Bool) {
if !isPausedBeforeSeeking {
playerCore.resume()
}
super.stopTracking(last: lastPoint, current: stopPoint, in: controlView, mouseIsUp: flag)
}
}
| gpl-3.0 | 040394dda2ec11d81dfb3958dff73e9b | 33.779528 | 138 | 0.674553 | 4.23693 | false | false | false | false |
alvarozizou/Noticias-Leganes-iOS | NoticiasLeganes/Extensions/UIImageView+KingFisher.swift | 1 | 894 | //
// UIImageView+KingFisher.swift
// NoticiasLeganes
//
// Created by Alvaro Blazquez Montero on 18/6/17.
// Copyright © 2017 Alvaro Blazquez Montero. All rights reserved.
//
import UIKit
import Kingfisher
extension UIImageView {
public func setPhotoImageKf(withImage entryImage : Any?,
placeholder : UIImage?,
processor : RoundCornerImageProcessor?) {
if let image = entryImage as? URL {
var options : KingfisherOptionsInfo?
if let _processor = processor {
options = [.processor(_processor)]
}
self.kf.setImage(with: image, placeholder: placeholder, options: options)
} else if let image = entryImage as? UIImage {
self.image = image
}
}
}
| mit | 97e3e6c9c62c5e394dd55d321c94b39c | 24.514286 | 85 | 0.543113 | 5.19186 | false | false | false | false |
pixeldock/PXDToolkit | Pod/Classes/ColorExtensions.swift | 1 | 1351 | //
// ColorExtensions.swift
// PXDToolbox
//
// Created by Jörn Schoppe on 19.01.16.
//
//
import Foundation
// Utility methods to make UIColor work with hex color values
public extension UIColor {
/**
Initializes a UIColor with a hex Int value
- Parameter hex: The RGB hex Int value of the desired color
- Parameter alpha: The alpha value of the color
- Returns: A UIColor with the desired color
*/
convenience init(hex: Int, alpha: CGFloat = 1) {
let components = (
R: CGFloat((hex >> 16) & 0xff) / 255,
G: CGFloat((hex >> 08) & 0xff) / 255,
B: CGFloat((hex >> 00) & 0xff) / 255
)
self.init(red: components.R, green: components.G, blue: components.B, alpha: alpha)
}
/**
Gets the hex value string of a UIColor
- Returns: A String with the hex color value (e.g. "#ffffff" for UIColor.whiteColor())
*/
var hexString: String {
var R: CGFloat = 0
var G: CGFloat = 0
var B: CGFloat = 0
var A: CGFloat = 0
getRed(&R, green: &G, blue: &B, alpha: &A)
let RGB = Int(Int((R * 255)) << 16) | Int(Int((G * 255)) << 8) | Int(Int((B * 255)) << 0)
let hex = String(format: "#%06x", arguments: [RGB])
return hex
}
}
| mit | e2c490f9580e7d9ab0677f58aff9543c | 26.55102 | 97 | 0.542222 | 3.77095 | false | false | false | false |
Bluthwort/Bluthwort | Sources/Classes/Core/UIView.swift | 1 | 2455 | //
// UIView.swift
//
// Copyright (c) 2018 Bluthwort
//
// 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.
//
extension Bluthwort where Base: UIView {
public static var zero: UIView {
return UIView(frame: .zero)
}
/// Creates an instance with background color.
///
/// - Parameter color: The background color of `UIView`.
/// - Returns: The created `UIView`.
public static func `init`(backgroundColor color: UIColor) -> Base {
let view = Base()
view.backgroundColor = color
return view
}
public var viewController: UIViewController? {
var next = base.next
repeat {
if let next = next as? UIViewController {
return next
} else {
next = next?.next
}
} while next != nil
return nil
}
@discardableResult
public func addSubviews(_ subviews: [UIView]) -> Bluthwort {
subviews.forEach {
base.addSubview($0)
}
return self
}
@discardableResult
public func removeSubviews(_ subviews: [UIView]) -> Bluthwort {
subviews.forEach {
$0.removeFromSuperview()
}
return self
}
@discardableResult
public func removeAllSubviews() -> Bluthwort {
base.subviews.forEach {
$0.removeFromSuperview()
}
return self
}
}
| mit | b19332983bb965f25810e9719933150e | 30.883117 | 81 | 0.645214 | 4.757752 | false | false | false | false |
ceozhu/lesson_ios_mvp | Pods/PureJsonSerializer/JsonSerializer/StringUtils.swift | 3 | 1541 | //
// StringUtils.swift
// JsonSerializer
//
// Created by Fuji Goro on 2014/09/15.
// Copyright (c) 2014 Fuji Goro. All rights reserved.
//
let unescapeMapping: [UnicodeScalar: UnicodeScalar] = [
"t": "\t",
"r": "\r",
"n": "\n",
]
let escapeMapping: [Character : String] = [
"\r": "\\r",
"\n": "\\n",
"\t": "\\t",
"\\": "\\\\",
"\"": "\\\"",
"\u{2028}": "\\u2028", // LINE SEPARATOR
"\u{2029}": "\\u2029", // PARAGRAPH SEPARATOR
// XXX: countElements("\r\n") is 1 in Swift 1.0
"\r\n": "\\r\\n",
]
let hexMapping: [UnicodeScalar : UInt32] = [
"0": 0x0,
"1": 0x1,
"2": 0x2,
"3": 0x3,
"4": 0x4,
"5": 0x5,
"6": 0x6,
"7": 0x7,
"8": 0x8,
"9": 0x9,
"a": 0xA, "A": 0xA,
"b": 0xB, "B": 0xB,
"c": 0xC, "C": 0xC,
"d": 0xD, "D": 0xD,
"e": 0xE, "E": 0xE,
"f": 0xF, "F": 0xF,
]
let digitMapping: [UnicodeScalar:Int] = [
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
]
extension String {
public var escapedJsonString: String {
let mapped = characters
.map { escapeMapping[$0] ?? String($0) }
.joinWithSeparator("")
return "\"" + mapped + "\""
}
}
public func escapeAsJsonString(source : String) -> String {
return source.escapedJsonString
}
func digitToInt(b: UInt8) -> Int? {
return digitMapping[UnicodeScalar(b)]
}
func hexToDigit(b: UInt8) -> UInt32? {
return hexMapping[UnicodeScalar(b)]
}
| apache-2.0 | df20c017c20932d5334a4fef056f20f2 | 18.024691 | 59 | 0.482803 | 2.771583 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKitUI/views/map annotations/TKUIModeAnnotationView.swift | 1 | 3912 | //
// TKUIModeAnnotationView.swift
// TripKitUI-iOS
//
// Created by Adrian Schönig on 10.05.19.
// Copyright © 2019 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import MapKit
import TripKit
import MapKit
/// A annotation to display transport locations on the map.
///
/// Uses the mode icon in the centre, coloured circle around it. Also works with
/// remote icons.
public class TKUIModeAnnotationView: MKAnnotationView {
public static let defaultSize = CGSize(width: 19, height: 19)
private weak var backgroundCircle: UIView!
private weak var imageView: UIImageView!
private weak var remoteImageView: UIImageView?
@objc
public override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
frame.size = TKUIModeAnnotationView.defaultSize
centerOffset = CGPoint(x: 0, y: frame.height * -0.5)
isOpaque = true
backgroundColor = .clear
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override var annotation: MKAnnotation? {
didSet {
guard let stop = annotation as? TKUIModeAnnotation else { return }
update(for: stop)
}
}
private func update(for annotation: TKUIModeAnnotation) {
if backgroundCircle == nil {
let circleFrame = CGRect(origin: .zero, size: TKUIModeAnnotationView.defaultSize)
let circle = UIView(frame: circleFrame)
circle.layer.cornerRadius = circleFrame.width / 2
circle.layer.borderWidth = 1
circle.layer.borderColor = UIColor.tkBackground.cgColor
insertSubview(circle, at: 0)
backgroundCircle = circle
}
guard let modeInfo = annotation.modeInfo else {
assertionFailure("Missing mode info")
return
}
backgroundCircle.backgroundColor = modeInfo.color ?? modeInfo.defaultColor
guard let image = modeInfo.image else {
assertionFailure("Couldn't create image for \(annotation)")
return
}
if let imageView = self.imageView, imageView.image?.size == image.size {
imageView.image = image
} else {
self.imageView?.removeFromSuperview()
let imageView = UIImageView(image: image)
imageView.frame = backgroundCircle.frame.insetBy(dx: 3, dy: 3)
imageView.tintColor = .tkBackground
addSubview(imageView)
self.imageView = imageView
}
// Template images fit into the normal image and we can use the regular
// list style. Other's we specifically ask for the map icon, which then
// replaces the circle and default image.
showRemoteOnly = false
if modeInfo.imageURL != nil {
if modeInfo.remoteImageIsTemplate {
remoteImageView?.removeFromSuperview()
imageView.setImage(with: modeInfo.imageURL(type: .listMainMode), asTemplate: true, placeholder: image)
} else {
if remoteImageView == nil {
let remoteImage = UIImageView(frame: CGRect(origin: .zero, size: TKUIModeAnnotationView.defaultSize))
remoteImage.isHidden = true // will be shown on success
addSubview(remoteImage)
remoteImageView = remoteImage
}
remoteImageView?.setImage(with: modeInfo.imageURL(type: .mapIcon)) { [weak self] success in
self?.showRemoteOnly = success
}
}
} else {
remoteImageView?.removeFromSuperview()
}
}
private var showRemoteOnly: Bool = false {
didSet {
backgroundCircle.isHidden = showRemoteOnly
imageView.isHidden = showRemoteOnly
remoteImageView?.isHidden = !showRemoteOnly
}
}
}
fileprivate extension TKModeInfo {
var defaultColor: TKColor {
guard
let identifier = self.identifier
else { return TKStyleManager.globalTintColor }
return TKTransportMode.color(for: identifier)
}
}
| apache-2.0 | caa565832751461ab25c3326e7aee5bc | 29.310078 | 111 | 0.684399 | 4.845105 | false | false | false | false |
steve-holmes/music-app-2 | MusicApp/Modules/Rank/RankSongAction.swift | 1 | 1999 | //
// RankSongAction.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/30/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import UIKit
import RxSwift
import Action
protocol RankSongAction {
var store: RankSongStore { get }
var onLoad: Action<String, Void> { get }
func onPlayButtonPress() -> CocoaAction
var onTrackDidSelect: Action<Track, Void> { get }
var onContextButtonTap: Action<(Song, UIViewController), Void> { get }
}
class MARankSongAction: RankSongAction {
let store: RankSongStore
let service: RankSongService
init(store: RankSongStore, service: RankSongService) {
self.store = store
self.service = service
}
lazy var onLoad: Action<String, Void> = {
return Action { [weak self] country in
guard let this = self else { return .empty() }
return this.service.getTracks(country: country)
.do(onNext: { tracks in
this.store.tracks.value = tracks
})
.map { _ in }
}
}()
func onPlayButtonPress() -> CocoaAction {
return CocoaAction { [weak self] in
guard let this = self else { return .empty() }
return this.service.play(
tracks: this.store.tracks.value,
selectedTrack: this.store.tracks.value[0]
)
}
}
lazy var onTrackDidSelect: Action<Track, Void> = {
return Action { [weak self] track in
guard let this = self else { return .empty() }
return this.service.play(
tracks: this.store.tracks.value,
selectedTrack: track
)
}
}()
lazy var onContextButtonTap: Action<(Song, UIViewController), Void> = {
return Action { [weak self] song, controller in
return self?.service.openContextMenu(song, in: controller) ?? .empty()
}
}()
}
| mit | a78b2ea9817221c7ceda1fc4f6f578f8 | 25.945946 | 82 | 0.565196 | 4.431111 | false | false | false | false |
chenchangqing/travelMapMvvm | travelMapMvvm/travelMapMvvm/General/ReactiveCocoa/TableViewBindingHelper.swift | 2 | 3707 | //
// TableViewBindingHelper.swift
// ReactiveSwiftFlickrSearch
//
// Created by Colin Eberhardt on 15/07/2014.
// Copyright (c) 2014 Colin Eberhardt. All rights reserved.
//
import Foundation
import ReactiveCocoa
@objc protocol ReactiveView {
func bindViewModel(viewModel: AnyObject)
}
// a helper that makes it easier to bind to UITableView instances
// see: http://www.scottlogic.com/blog/2014/05/11/reactivecocoa-tableview-binding.html
class TableViewBindingHelper: NSObject, UITableViewDataSource, UITableViewDelegate {
//MARK: Properties
var delegate: UITableViewDelegate?
private let tableView: UITableView
private let templateCell: UITableViewCell
private let selectionCommand: RACCommand?
private var data: [AnyObject]
private var cellHeight: CGFloat?
//MARK: Public API
init(tableView: UITableView, sourceSignal: RACSignal, nibName: String, selectionCommand: RACCommand? = nil) {
self.tableView = tableView
self.data = []
self.selectionCommand = selectionCommand
let nib = UINib(nibName: nibName, bundle: nil)
// create an instance of the template cell and register with the table view
templateCell = nib.instantiateWithOwner(nil, options: nil)[0] as! UITableViewCell
tableView.registerNib(nib, forCellReuseIdentifier: templateCell.reuseIdentifier!)
super.init()
sourceSignal.subscribeNext {
(d:AnyObject!) -> () in
self.data = d as! [AnyObject]
self.tableView.reloadData()
}
tableView.dataSource = self
tableView.delegate = self
}
init(tableView: UITableView, sourceSignal: RACSignal, reuseIdentifier: String, cellHeight: CGFloat, selectionCommand: RACCommand? = nil) {
self.tableView = tableView
self.data = []
self.selectionCommand = selectionCommand
self.cellHeight = cellHeight
templateCell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as! UITableViewCell
super.init()
sourceSignal.subscribeNext {
(d:AnyObject!) -> () in
self.data = d as! [AnyObject]
self.tableView.reloadData()
}
tableView.dataSource = self
tableView.delegate = self
}
//MARK: Private
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(templateCell.reuseIdentifier!) as! UITableViewCell
// 解决模拟器越界 避免设置数据与reloadData时间差引起的错误
if indexPath.row < data.count {
let item: AnyObject = data[indexPath.row]
if let reactiveView = cell as? ReactiveView {
reactiveView.bindViewModel(item)
}
// println(indexPath)
} else {
// print(indexPath)
// print("-越界\n")
}
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if let cellHeight=cellHeight {
return cellHeight
}
return templateCell.bounds.size.height
}
func tableView(tableView: UITableView,didSelectRowAtIndexPath indexPath: NSIndexPath){
if selectionCommand != nil {
selectionCommand?.execute(data[indexPath.row])
}
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if self.delegate?.respondsToSelector(Selector("scrollViewDidScroll:")) == true {
self.delegate?.scrollViewDidScroll?(scrollView);
}
}
}
| apache-2.0 | 351952639537cd59b31bc540e17302fd | 28.747967 | 142 | 0.680241 | 5.12465 | false | false | false | false |
jmgc/swift | test/Interop/Cxx/templates/member-templates-silgen.swift | 1 | 3142 | // RUN: %target-swift-emit-sil %s -I %S/Inputs -enable-cxx-interop | %FileCheck %s
// We can't yet call member functions correctly on Windows (SR-13129).
// XFAIL: OS=windows-msvc
// REQUIRES: fixing-after-30630
import MemberTemplates
// CHECK-LABEL: sil hidden @$s4main9basicTestyyF : $@convention(thin) () -> ()
// CHECK: [[ADD:%.*]] = function_ref @_ZN18HasMemberTemplates3addIiEET_S1_S1_ : $@convention(c) (Int32, Int32, @inout HasMemberTemplates) -> Int32
// CHECK: apply [[ADD]]({{.*}}) : $@convention(c) (Int32, Int32, @inout HasMemberTemplates) -> Int32
// CHECK: [[ADD_TWO_TEMPLATES:%.*]] = function_ref @_ZN18HasMemberTemplates15addTwoTemplatesIiiEET_S1_T0_ : $@convention(c) (Int32, Int32, @inout HasMemberTemplates) -> Int32 // user: %26
// CHECK: apply [[ADD_TWO_TEMPLATES]]({{.*}}) : $@convention(c) (Int32, Int32, @inout HasMemberTemplates) -> Int32
// CHECK: [[ADD_ALL:%.*]] = function_ref @_ZN18HasMemberTemplates6addAllIiiEEiiT_T0_ : $@convention(c) (Int32, Int32, Int32, @inout HasMemberTemplates) -> Int32 // user: %39
// CHECK: apply [[ADD_ALL]]({{.*}}) : $@convention(c) (Int32, Int32, Int32, @inout HasMemberTemplates) -> Int32
// CHECK: [[DO_NOTHING:%.*]] = function_ref @_ZN18HasMemberTemplates17doNothingConstRefIiEEvRKT_ : $@convention(c) (UnsafePointer<Int32>, @inout HasMemberTemplates) -> () // user: %48
// CHECK: apply [[DO_NOTHING]]({{.*}}) : $@convention(c) (UnsafePointer<Int32>, @inout HasMemberTemplates) -> ()
// CHECK-LABEL: end sil function '$s4main9basicTestyyF'
func basicTest() {
var i: Int32 = 0
var obj = HasMemberTemplates()
obj.add(i, i)
obj.addTwoTemplates(i, i)
obj.addAll(i, i, i)
obj.doNothingConstRef(&i)
}
// CHECK-LABEL: sil hidden_external [clang HasMemberTemplates._ZN18HasMemberTemplates3addIiEET_S1_S1_] @_ZN18HasMemberTemplates3addIiEET_S1_S1_ : $@convention(c) (Int32, Int32, @inout HasMemberTemplates) -> Int32
// CHECK-LABEL: sil hidden_external [clang HasMemberTemplates._ZN18HasMemberTemplates15addTwoTemplatesIiiEET_S1_T0_] @_ZN18HasMemberTemplates15addTwoTemplatesIiiEET_S1_T0_ : $@convention(c) (Int32, Int32, @inout HasMemberTemplates) -> Int32
// CHECK-LABEL: sil hidden_external [clang HasMemberTemplates._ZN18HasMemberTemplates6addAllIiiEEiiT_T0_] @_ZN18HasMemberTemplates6addAllIiiEEiiT_T0_ : $@convention(c) (Int32, Int32, Int32, @inout HasMemberTemplates) -> Int32
// CHECK-LABEL: sil hidden_external [clang HasMemberTemplates._ZN18HasMemberTemplates17doNothingConstRefIiEEvRKT_] @_ZN18HasMemberTemplates17doNothingConstRefIiEEvRKT_ : $@convention(c) (UnsafePointer<Int32>, @inout HasMemberTemplates) -> ()
// CHECK-LABEL: sil hidden @$s4main12testSetValueyyF : $@convention(thin) () -> ()
// CHECK: [[SET_VALUE:%.*]] = function_ref @_ZN32TemplateClassWithMemberTemplatesIiE8setValueIlEEvT_ : $@convention(c) (Int, @inout __CxxTemplateInst32TemplateClassWithMemberTemplatesIiE) -> ()
// CHECK: apply [[SET_VALUE]]({{.*}}) : $@convention(c) (Int, @inout __CxxTemplateInst32TemplateClassWithMemberTemplatesIiE) -> ()
// CHECK-LABEL: end sil function '$s4main12testSetValueyyF'
func testSetValue() {
var w = IntWrapper(11)
w.setValue(42)
}
| apache-2.0 | 67874b5b8fe52761c6a8677d9d5afc38 | 61.84 | 241 | 0.724061 | 3.441402 | false | true | false | false |
crspybits/SyncServerII | Sources/Server/Database/Repositories.swift | 1 | 630 | //
// Repositories.swift
// Server
//
// Created by Christopher Prince on 2/7/17.
//
//
import Foundation
struct Repositories {
let db: Database
lazy var user = UserRepository(db)
lazy var masterVersion = MasterVersionRepository(db)
lazy var fileIndex = FileIndexRepository(db)
lazy var upload = UploadRepository(db)
lazy var deviceUUID = DeviceUUIDRepository(db)
lazy var sharing = SharingInvitationRepository(db)
lazy var sharingGroup = SharingGroupRepository(db)
lazy var sharingGroupUser = SharingGroupUserRepository(db)
init(db: Database) {
self.db = db
}
}
| mit | e012649567d82ff9de64f67f5adba3c6 | 23.230769 | 62 | 0.698413 | 4.228188 | false | false | false | false |
liuduoios/POMVVMDemo | POMVVM/View/MasterViewController.swift | 1 | 3883 | //
// MasterViewController.swift
// POMVVM
//
// Created by 刘铎 on 15/12/6.
// Copyright © 2015年 liuduoios. All rights reserved.
//
import UIKit
import Bond
// ----------------
// MARK: - Protocol
// ----------------
protocol MasterViewControllerDataSource {
var items: ObservableArray<Item> { get }
var openSwitchCount: Observable<Int> { get }
}
protocol MasterViewControllerBusinessAction {
func insertNowDate()
func deleteRowAtIndex(index: Int)
}
// -------------
// MARK: - Class
// -------------
class MasterViewController: UITableViewController, BindableView {
// ------------------
// MARK: - Properties
// ------------------
let headerLabel: UILabel = {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.size.width, height: 40))
label.text = "共有 0 个开关打开了"
label.textAlignment = .Center
return label
}()
// ---------------
// MARK: - Actions
// ---------------
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
self.tableView.tableHeaderView = headerLabel
viewModel = MasterViewModel()
bindViewModel(viewModel)
}
// ---------------
// MARK: - Actions
// ---------------
@objc private func insertNewObject(sender: AnyObject) {
viewModel.insertNowDate()
}
// ---------------------------
// MARK: - 实现BindableView协议
// ---------------------------
typealias ViewModelType = protocol <MasterViewControllerDataSource, MasterViewControllerBusinessAction, ViewModel>
var viewModel: ViewModelType!
func bindViewModel(viewModel: ViewModelType) {
// 把数据绑定到TableView上
viewModel.items.lift().bindTo(tableView, proxyDataSource: self) { (indexPath, dataSource, tableView) -> UITableViewCell in
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! DateCell
let item = dataSource[indexPath.section][indexPath.row]
// 为每个cell绑定cellViewModel
let cellViewModel = DateCellViewModel(item: item)
cell.bindViewModel(cellViewModel)
return cell
}
// 把“打开开关的总个数”绑定到headerLabel上
viewModel.openSwitchCount
.distinct()
.map { "共有 \($0) 个开关打开了" }
--> headerLabel.bnd_text
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let controller = segue.destinationViewController as! DetailViewController
// 取出viewModel.items中对应的Item,创建一个DetailViewModel
let detailViewModel = DetailViewModel(item: viewModel.items[indexPath.row])
controller.viewModel = detailViewModel
}
}
}
}
extension MasterViewController: BNDTableViewProxyDataSource {
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
viewModel.deleteRowAtIndex(indexPath.row)
}
}
}
| mit | 9e103c665aee8df4644bf8ae9cb55964 | 29.819672 | 157 | 0.599468 | 5.318246 | false | false | false | false |
groue/GRDB.swift | GRDB/QueryInterface/SQL/Table.swift | 1 | 63044 | /// A `Table` builds database queries with the Swift language instead of SQL.
///
/// ## Overview
///
/// A `Table` instance is similar to a ``TableRecord`` type. You will use one
/// when the other is impractical or impossible to use.
///
/// For example:
///
/// ```swift
/// let table = Table("player")
/// try dbQueue.read { db in
/// // SELECT * FROM player WHERE score >= 1000
/// let rows: [Row] = table.filter(Column("score") >= 1000).fetchAll(db)
/// }
/// ```
///
/// ## Topics
///
/// ### Creating a Table
///
/// - ``init(_:)-2iz5y``
/// - ``init(_:)-3mfb8``
///
/// ### Instance Properties
///
/// - ``tableName``
///
/// ### Counting Rows
///
/// - ``fetchCount(_:)``
///
/// ### Testing for Row Existence
///
/// - ``exists(_:id:)``
/// - ``exists(_:key:)-4dk7e``
/// - ``exists(_:key:)-36jtu``
///
/// ### Deleting Rows
///
/// - ``deleteAll(_:)``
/// - ``deleteAll(_:ids:)``
/// - ``deleteAll(_:keys:)-5t865``
/// - ``deleteAll(_:keys:)-28sff``
/// - ``deleteOne(_:id:)``
/// - ``deleteOne(_:key:)-404su``
/// - ``deleteOne(_:key:)-64wmq``
///
/// ### Updating Rows
///
/// - ``updateAll(_:onConflict:_:)-4w9b``
/// - ``updateAll(_:onConflict:_:)-4cvap``
///
/// ### Building Query Interface Requests
///
/// `Table` provide convenience access to most ``DerivableRequest`` and
/// ``QueryInterfaceRequest`` methods.
///
/// - ``aliased(_:)``
/// - ``all()``
/// - ``annotated(with:)-6i101``
/// - ``annotated(with:)-6x399``
/// - ``annotated(with:)-4sbgw``
/// - ``annotated(with:)-98t4p``
/// - ``annotated(withOptional:)``
/// - ``annotated(withRequired:)``
/// - ``filter(_:)``
/// - ``filter(id:)``
/// - ``filter(ids:)``
/// - ``filter(key:)-tw3i``
/// - ``filter(key:)-4sun7``
/// - ``filter(keys:)-85e0v``
/// - ``filter(keys:)-qqgf``
/// - ``filter(literal:)``
/// - ``filter(sql:arguments:)``
/// - ``having(_:)``
/// - ``including(all:)``
/// - ``including(optional:)``
/// - ``including(required:)``
/// - ``joining(optional:)``
/// - ``joining(required:)``
/// - ``limit(_:offset:)``
/// - ``none()``
/// - ``order(_:)-2gvi7``
/// - ``order(_:)-9o5bb``
/// - ``order(literal:)``
/// - ``order(sql:arguments:)``
/// - ``orderByPrimaryKey()``
/// - ``select(_:)-1599q``
/// - ``select(_:)-2cnd1``
/// - ``select(_:as:)-20ci9``
/// - ``select(_:as:)-3pr6x``
/// - ``select(literal:)``
/// - ``select(literal:as:)``
/// - ``select(sql:arguments:)``
/// - ``select(sql:arguments:as:)``
/// - ``selectPrimaryKey(as:)``
/// - ``with(_:)``
///
/// ### Defining Associations
///
/// - ``association(to:)``
/// - ``association(to:on:)``
/// - ``belongsTo(_:key:using:)-8p5xr``
/// - ``belongsTo(_:key:using:)-117wr``
/// - ``hasMany(_:key:using:)-3i6yk``
/// - ``hasMany(_:key:using:)-57dwf``
/// - ``hasMany(_:through:using:key:)``
/// - ``hasOne(_:key:using:)-81vqy``
/// - ``hasOne(_:key:using:)-3438j``
/// - ``hasOne(_:through:using:key:)``
///
/// ### Fetching Database Rows
///
/// - ``fetchCursor(_:)-1oqex``
/// - ``fetchAll(_:)-4s7yn``
/// - ``fetchSet(_:)-5lp4s``
/// - ``fetchOne(_:)-3bduz``
///
/// ### Fetching Database Values
///
/// - ``fetchCursor(_:)-65lci``
/// - ``fetchCursor(_:)-295uw``
/// - ``fetchAll(_:)-6xr01``
/// - ``fetchAll(_:)-7tjdp``
/// - ``fetchSet(_:)-3mchk``
/// - ``fetchSet(_:)-8k2uk``
/// - ``fetchOne(_:)-infc``
/// - ``fetchOne(_:)-71icb``
///
/// ### Fetching Records
///
/// - ``fetchCursor(_:)-81wuu``
/// - ``fetchAll(_:)-3l7ol``
/// - ``fetchSet(_:)-ko77``
/// - ``fetchOne(_:)-8n1q``
///
/// ### Database Observation Support
///
/// - ``databaseRegion(_:)``
public struct Table<RowDecoder> {
/// The table name.
public var tableName: String
private init(_ tableName: String, _ type: RowDecoder.Type) {
self.tableName = tableName
}
/// Creates a `Table`.
///
/// For example:
///
/// ```swift
/// let table = Table<Row>("player")
/// let table = Table<Player>("player")
/// ```
public init(_ tableName: String) {
self.init(tableName, RowDecoder.self)
}
}
extension Table where RowDecoder == Row {
/// Create a `Table<Row>`.
///
/// For example:
///
/// ```swift
/// let table = Table("player") // Table<Row>
/// ```
public init(_ tableName: String) {
self.init(tableName, Row.self)
}
}
extension Table: DatabaseRegionConvertible {
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
DatabaseRegion(table: tableName)
}
}
// MARK: Request Derivation
extension Table {
var relationForAll: SQLRelation {
.all(fromTable: tableName)
}
/// Returns a request for all rows of the table.
///
/// ```swift
/// // Fetch all players
/// let table = Table<Player>("player")
/// let request = table.all()
/// let players: [Player] = try request.fetchAll(db)
/// ```
public func all() -> QueryInterfaceRequest<RowDecoder> {
QueryInterfaceRequest(relation: relationForAll)
}
/// Returns an empty request that fetches no row.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let request = Table("player").none()
/// let rows = try request.fetchAll(db) // empty array
/// }
public func none() -> QueryInterfaceRequest<RowDecoder> {
all().none() // don't laugh
}
/// Returns a request that selects the provided result columns.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// // SELECT id, score FROM player
/// let request = playerTable.select(Column("id"), Column("score"))
/// ```
public func select(_ selection: any SQLSelectable...) -> QueryInterfaceRequest<RowDecoder> {
all().select(selection)
}
/// Returns a request that selects the provided result columns.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// // SELECT id, score FROM player
/// let request = playerTable.select([Column("id"), Column("score")])
/// ```
public func select(_ selection: [any SQLSelectable]) -> QueryInterfaceRequest<RowDecoder> {
all().select(selection)
}
/// Returns a request that selects the provided SQL string.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// // SELECT id, name FROM player
/// let request = playerTable.select(sql: "id, name")
///
/// // SELECT id, IFNULL(name, 'Anonymous') FROM player
/// let defaultName = "Anonymous"
/// let request = playerTable.select(sql: "id, IFNULL(name, ?)", arguments: [defaultName])
/// ```
public func select(
sql: String,
arguments: StatementArguments = StatementArguments())
-> QueryInterfaceRequest<RowDecoder>
{
all().select(SQL(sql: sql, arguments: arguments))
}
/// Returns a request that selects the provided ``SQL`` literal.
///
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
/// without any risk of syntax errors or SQL injection:
///
/// ```swift
/// let playerTable = Table("player")
///
/// // SELECT id, IFNULL(name, 'Anonymous') FROM player
/// let defaultName = "Anonymous"
/// let request = playerTable.select(literal: "id, IFNULL(name, \(defaultName))")
/// ```
public func select(literal sqlLiteral: SQL) -> QueryInterfaceRequest<RowDecoder> {
all().select(sqlLiteral)
}
/// Returns a request that selects the provided result columns, and defines
/// the type of decoded rows.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// let minScore = min(Column("score"))
/// let maxScore = max(Column("score"))
///
/// // SELECT MAX(score) FROM player
/// let request = playerTable.select([maxScore], as: Int.self)
/// let maxScore = try request.fetchOne(db) // Int?
///
/// // SELECT MIN(score), MAX(score) FROM player
/// let request = playerTable.select([minScore, maxScore], as: Row.self)
/// if let row = try request.fetchOne(db) {
/// let minScore: Int = row[0]
/// let maxScore: Int = row[1]
/// }
/// ```
public func select<RowDecoder>(
_ selection: [any SQLSelectable],
as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
{
all().select(selection, as: type)
}
/// Returns a request that selects the provided result columns, and defines
/// the type of decoded rows.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// let minScore = min(Column("score"))
/// let maxScore = max(Column("score"))
///
/// // SELECT MAX(score) FROM player
/// let request = playerTable.select(maxScore, as: Int.self)
/// let maxScore = try request.fetchOne(db) // Int?
///
/// // SELECT MIN(score), MAX(score) FROM player
/// let request = playerTable.select(minScore, maxScore, as: Row.self)
/// if let row = try request.fetchOne(db) {
/// let minScore: Int = row[0]
/// let maxScore: Int = row[1]
/// }
/// ```
public func select<RowDecoder>(
_ selection: any SQLSelectable...,
as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
{
all().select(selection, as: type)
}
/// Returns a request that selects the provided SQL string, and defines the
/// type of decoded rows.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// // SELECT name FROM player
/// let request = playerTable.select(sql: "name", as: String.self)
/// let names = try request.fetchAll(db) // [String]
///
/// // SELECT IFNULL(name, 'Anonymous') FROM player
/// let defaultName = "Anonymous"
/// let request = playerTable.select(sql: "IFNULL(name, ?)", arguments: [defaultName], as: String.self)
/// let names = try request.fetchAll(db) // [String]
/// ```
public func select<RowDecoder>(
sql: String,
arguments: StatementArguments = StatementArguments(),
as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
{
all().select(SQL(sql: sql, arguments: arguments), as: type)
}
/// Returns a request that selects the provided ``SQL`` literal, and defines
/// the type of decoded rows.
///
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
/// without any risk of syntax errors or SQL injection:
///
/// ```swift
/// let playerTable = Table("player")
///
/// // SELECT IFNULL(name, 'Anonymous') FROM player
/// let defaultName = "Anonymous"
/// let request = playerTable.select(literal: "IFNULL(name, \(defaultName))", as: String.self)
/// let names = try request.fetchAll(db) // [String]
/// ```
public func select<RowDecoder>(
literal sqlLiteral: SQL,
as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
{
all().select(sqlLiteral, as: type)
}
/// Returns a request that selects the primary key.
///
/// All primary keys are supported:
///
/// ```swift
/// let playerTable = Table("player")
/// let countryTable = Table("country")
/// let citizenshipTable = Table("citizenship")
///
/// // SELECT id FROM player WHERE ...
/// let request = try playerTable.selectPrimaryKey(as: Int64.self)
/// let ids = try request.fetchAll(db) // [Int64]
///
/// // SELECT code FROM country WHERE ...
/// let request = try countryTable.selectPrimaryKey(as: String.self)
/// let countryCodes = try request.fetchAll(db) // [String]
///
/// // SELECT citizenId, countryCode FROM citizenship WHERE ...
/// let request = try citizenshipTable.selectPrimaryKey(as: Row.self)
/// let rows = try request.fetchAll(db) // [Row]
/// ```
///
/// For composite primary keys, you can define a ``FetchableRecord`` type:
///
/// ```swift
/// extension Citizenship {
/// struct ID: Decodable, FetchableRecord {
/// var citizenId: Int64
/// var countryCode: String
/// }
/// }
/// let request = try citizenshipTable.selectPrimaryKey(as: Citizenship.ID.self)
/// let ids = try request.fetchAll(db) // [Citizenship.ID]
/// ```
public func selectPrimaryKey<PrimaryKey>(as type: PrimaryKey.Type = PrimaryKey.self)
-> QueryInterfaceRequest<PrimaryKey>
{
all().selectPrimaryKey(as: type)
}
/// Returns a request with the provided result columns appended to the
/// table columns.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// // SELECT *, score + bonus AS totalScore FROM player
/// let totalScore = (Column("score") + Column("bonus")).forKey("totalScore")
/// let request = playerTable.annotated(with: [totalScore])
/// ```
public func annotated(with selection: [any SQLSelectable]) -> QueryInterfaceRequest<RowDecoder> {
all().annotated(with: selection)
}
/// Returns a request with the provided result columns appended to the
/// table columns.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// // SELECT *, score + bonus AS totalScore FROM player
/// let totalScore = (Column("score") + Column("bonus")).forKey("totalScore")
/// let request = playerTable.annotated(with: totalScore)
/// ```
public func annotated(with selection: any SQLSelectable...) -> QueryInterfaceRequest<RowDecoder> {
all().annotated(with: selection)
}
/// Returns a request filtered with a boolean SQL expression.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// // SELECT * FROM player WHERE name = 'O''Brien'
/// let name = "O'Brien"
/// let request = playerTable.filter(Column("name") == name)
/// ```
public func filter(_ predicate: some SQLSpecificExpressible) -> QueryInterfaceRequest<RowDecoder> {
all().filter(predicate)
}
/// Returns a request filtered by primary key.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// let playerTable = Table("player")
/// let countryTable = Table("country")
///
/// // SELECT * FROM player WHERE id = 1
/// let request = playerTable.filter(key: 1)
///
/// // SELECT * FROM country WHERE code = 'FR'
/// let request = countryTable.filter(key: "FR")
/// ```
///
/// - parameter key: A primary key
public func filter(key: some DatabaseValueConvertible) -> QueryInterfaceRequest<RowDecoder> {
all().filter(key: key)
}
/// Returns a request filtered by primary key.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// let playerTable = Table("player")
/// let countryTable = Table("country")
///
/// // SELECT * FROM player WHERE id = IN (1, 2, 3)
/// let request = playerTable.filter(keys: [1, 2, 3])
///
/// // SELECT * FROM country WHERE code = IN ('FR', 'US')
/// let request = countryTable.filter(keys: ["FR", "US"])
/// ```
///
/// - parameter keys: A collection of primary keys
public func filter<Keys>(keys: Keys)
-> QueryInterfaceRequest<RowDecoder>
where Keys: Sequence, Keys.Element: DatabaseValueConvertible
{
all().filter(keys: keys)
}
/// Returns a request filtered by primary or unique key.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
/// let citizenshipTable = Table("citizenship")
///
/// // SELECT * FROM player WHERE id = 1
/// let request = playerTable.filter(key: ["id": 1])
///
/// // SELECT * FROM player WHERE email = '[email protected]'
/// let request = playerTable.filter(key: ["email": "[email protected]"])
///
/// // SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR'
/// let request = citizenshipTable.filter(key: [
/// "citizenId": 1,
/// "countryCode": "FR",
/// ])
/// ```
///
/// When executed, this request raises a fatal error if no unique index
/// exists on a subset of the key columns.
///
/// - parameter key: A unique key.
public func filter(key: [String: (any DatabaseValueConvertible)?]?) -> QueryInterfaceRequest<RowDecoder> {
all().filter(key: key)
}
/// Returns a request filtered by primary or unique key.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
/// let citizenshipTable = Table("citizenship")
///
/// // SELECT * FROM player WHERE id = 1
/// let request = playerTable.filter(keys: [["id": 1]])
///
/// // SELECT * FROM player WHERE email = '[email protected]'
/// let request = playerTable.filter(keys: [["email": "[email protected]"]])
///
/// // SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR'
/// let request = citizenshipTable.filter(keys: [
/// ["citizenId": 1, "countryCode": "FR"],
/// ])
/// ```
///
/// When executed, this request raises a fatal error if no unique index
/// exists on a subset of the key columns.
///
/// - parameter keys: A collection of unique keys
public func filter(keys: [[String: (any DatabaseValueConvertible)?]]) -> QueryInterfaceRequest<RowDecoder> {
all().filter(keys: keys)
}
/// Returns a request filtered with an SQL string.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// // SELECT * FROM player WHERE name = 'O''Brien'
/// let name = "O'Brien"
/// let request = playerTable.filter(sql: "name = ?", arguments: [name])
/// ```
public func filter(
sql: String,
arguments: StatementArguments = StatementArguments())
-> QueryInterfaceRequest<RowDecoder>
{
filter(SQL(sql: sql, arguments: arguments))
}
/// Returns a request filtered with an ``SQL`` literal.
///
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
/// without any risk of syntax errors or SQL injection:
///
/// ```swift
/// let playerTable = Table("player")
///
/// // SELECT * FROM player WHERE name = 'O''Brien'
/// let name = "O'Brien"
/// let request = playerTable.filter(literal: "name = \(name)")
/// ```
public func filter(literal sqlLiteral: SQL) -> QueryInterfaceRequest<RowDecoder> {
all().filter(sqlLiteral)
}
/// Returns a request sorted according to the given SQL ordering terms.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// // SELECT * FROM player ORDER BY score DESC, name
/// let request = playerTable.order(Column("score").desc, Column("name"))
/// ```
public func order(_ orderings: any SQLOrderingTerm...) -> QueryInterfaceRequest<RowDecoder> {
all().order(orderings)
}
/// Returns a request sorted according to the given SQL ordering terms.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// // SELECT * FROM player ORDER BY score DESC, name
/// let request = playerTable.order([Column("score").desc, Column("name")])
/// ```
public func order(_ orderings: [any SQLOrderingTerm]) -> QueryInterfaceRequest<RowDecoder> {
all().order(orderings)
}
/// Returns a request sorted by primary key.
///
/// All primary keys are supported:
///
/// ```swift
/// let playerTable = Table("player")
/// let countryTable = Table("country")
/// let citizenshipTable = Table("citizenship")
///
/// // SELECT * FROM player ORDER BY id
/// let request = playerTable.orderByPrimaryKey()
///
/// // SELECT * FROM country ORDER BY code
/// let request = countryTable.orderByPrimaryKey()
///
/// // SELECT * FROM citizenship ORDER BY citizenId, countryCode
/// let request = citizenshipTable.orderByPrimaryKey()
/// ```
public func orderByPrimaryKey() -> QueryInterfaceRequest<RowDecoder> {
all().orderByPrimaryKey()
}
/// Returns a request sorted according to the given SQL string.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// // SELECT * FROM player ORDER BY score DESC, name
/// let request = playerTable.order(sql: "score DESC, name")
/// ```
public func order(
sql: String,
arguments: StatementArguments = StatementArguments())
-> QueryInterfaceRequest<RowDecoder>
{
all().order(SQL(sql: sql, arguments: arguments))
}
/// Returns a request sorted according to the given ``SQL`` literal.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// // SELECT * FROM player ORDER BY score DESC, name
/// let request = playerTable.order(literal: "score DESC, name")
/// ```
public func order(literal sqlLiteral: SQL) -> QueryInterfaceRequest<RowDecoder> {
all().order(sqlLiteral)
}
/// Returns a limited request.
///
/// The returned request fetches `limit` rows, starting at `offset`. For
/// example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// // SELECT * FROM player LIMIT 10
/// let request = playerTable.limit(10)
///
/// // SELECT * FROM player LIMIT 10 OFFSET 20
/// let request = playerTable.limit(10, offset: 20)
/// ```
public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<RowDecoder> {
all().limit(limit, offset: offset)
}
/// Returns a request that can be referred to with the provided alias.
///
/// `table.aliased(alias)` is equivalent to `table.all().aliased(alias)`.
/// See ``TableRequest/aliased(_:)`` for more information.
public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest<RowDecoder> {
all().aliased(alias)
}
/// Returns a request that embeds a common table expression.
///
/// `table.with(cte)` is equivalent to `table.all().with(cte)`.
/// See ``DerivableRequest/with(_:)`` for more information.
public func with<T>(_ cte: CommonTableExpression<T>) -> QueryInterfaceRequest<RowDecoder> {
all().with(cte)
}
}
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible {
/// Returns a request filtered by primary key.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// struct Player: Identifiable {
/// var id: Int64
/// }
/// struct Country: Identifiable {
/// var id: String
/// }
///
/// let playerTable = Table<Player>("player")
/// let countryTable = Table<Country>("country")
///
/// // SELECT * FROM player WHERE id = 1
/// let request = playerTable.filter(id: 1)
///
/// // SELECT * FROM country WHERE code = 'FR'
/// let request = countryTable.filter(id: "FR")
/// ```
///
/// - parameter id: A primary key
public func filter(id: RowDecoder.ID) -> QueryInterfaceRequest<RowDecoder> {
all().filter(id: id)
}
/// Returns a request filtered by primary key.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// struct Player: Identifiable {
/// var id: Int64
/// }
/// struct Country: Identifiable {
/// var id: String
/// }
///
/// let playerTable = Table<Player>("player")
/// let countryTable = Table<Country>("country")
///
/// // SELECT * FROM player WHERE id = IN (1, 2, 3)
/// let request = playerTable.filter(ids: [1, 2, 3])
///
/// // SELECT * FROM country WHERE code = IN ('FR', 'US')
/// let request = countryTable.filter(ids: ["FR", "US"])
/// ```
///
/// - parameter ids: A collection of primary keys
public func filter<IDS>(ids: IDS) -> QueryInterfaceRequest<RowDecoder>
where IDS: Collection, IDS.Element == RowDecoder.ID
{
all().filter(ids: ids)
}
}
extension Table {
// MARK: - Counting All
/// Returns the number of rows in the database table.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// try dbQueue.read { db in
/// // SELECT COUNT(*) FROM player
/// let count = try playerTable.fetchCount(db)
/// }
/// ```
///
/// - parameter db: A database connection.
public func fetchCount(_ db: Database) throws -> Int {
try all().fetchCount(db)
}
}
// MARK: - Fetching Records from Table
extension Table where RowDecoder: FetchableRecord {
/// Returns a cursor over all records fetched from the database.
///
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord { }
/// let playerTable = Table<Player>("player")
///
/// try dbQueue.read { db in
/// // SELECT * FROM player
/// let players = try playerTable.fetchCursor(db)
/// while let player = try players.next() {
/// print(player.name)
/// }
/// }
/// ```
///
/// The order in which the records are returned is undefined
/// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)).
///
/// The returned cursor is valid only during the remaining execution of the
/// database access. Do not store or return the cursor for later use.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// - parameter db: A database connection.
/// - returns: A ``RecordCursor`` over fetched records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder> {
try all().fetchCursor(db)
}
/// Returns an array of all records fetched from the database.
///
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord { }
/// let playerTable = Table<Player>("player")
///
/// try dbQueue.read { db in
/// // SELECT * FROM player
/// let players = try playerTable.fetchAll(db)
/// }
/// ```
///
/// The order in which the records are returned is undefined
/// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)).
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
try all().fetchAll(db)
}
/// Returns a single record fetched from the database.
///
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord { }
/// let playerTable = Table<Player>("player")
///
/// try dbQueue.read { db in
/// // SELECT * FROM player LIMIT 1
/// let player = try playerTable.fetchOne(db)
/// }
/// ```
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
try all().fetchOne(db)
}
}
extension Table where RowDecoder: FetchableRecord & Hashable {
/// Returns a set of all records fetched from the database.
///
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, Hashable { }
/// let playerTable = Table<Player>("player")
///
/// try dbQueue.read { db in
/// // SELECT * FROM player
/// let players = try playerTable.fetchSet(db)
/// }
/// ```
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
try all().fetchSet(db)
}
}
// MARK: - Fetching Rows from Table
extension Table where RowDecoder == Row {
/// Returns a cursor over all rows fetched from the database.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// try dbQueue.read { db in
/// // SELECT * FROM player
/// let rows = try playerTable.fetchCursor(db)
/// while let row = try rows.next() {
/// let id: Int64 = row["id"]
/// let name: String = row["name"]
/// }
/// }
/// ```
///
/// The order in which the rows are returned is undefined
/// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)).
///
/// The returned cursor is valid only during the remaining execution of the
/// database access. Do not store or return the cursor for later use.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// - parameter db: A database connection.
/// - returns: A ``RowCursor`` over fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> RowCursor {
try all().fetchCursor(db)
}
/// Returns an array of all rows fetched from the database.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// try dbQueue.read { db in
/// // SELECT * FROM player
/// let rows = try playerTable.fetchAll(db)
/// }
/// ```
///
/// The order in which the rows are returned is undefined
/// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)).
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [Row] {
try all().fetchAll(db)
}
/// Returns a single row fetched from the database.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// try dbQueue.read { db in
/// // SELECT * FROM player LIMIT 1
/// let row = try playerTable.fetchOne(db)
/// }
/// ```
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> Row? {
try all().fetchOne(db)
}
/// Returns a set of all rows fetched from the database.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// try dbQueue.read { db in
/// // SELECT * FROM player
/// let rows = try playerTable.fetchSet(db)
/// }
/// ```
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<Row> {
try all().fetchSet(db)
}
}
// MARK: - Fetching Values from Table
extension Table where RowDecoder: DatabaseValueConvertible {
/// Returns a cursor over fetched values.
///
/// The order in which the values are returned is undefined
/// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)).
///
/// Values are decoded from the leftmost column.
///
/// The returned cursor is valid only during the remaining execution of the
/// database access. Do not store or return the cursor for later use.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// - parameter db: A database connection.
/// - returns: A ``DatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder> {
try all().fetchCursor(db)
}
/// Returns an array of fetched values.
///
/// Values are decoded from the leftmost column.
///
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
try all().fetchAll(db)
}
/// Returns a single fetched value.
///
/// The value is decoded from the leftmost column.
///
/// The result is nil if the request returns no row, or one row with a
/// `NULL` value.
///
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
try all().fetchOne(db)
}
}
extension Table where RowDecoder: DatabaseValueConvertible & Hashable {
/// Returns a set of fetched values.
///
/// Values are decoded from the leftmost column.
///
/// - parameter db: A database connection.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
try all().fetchSet(db)
}
}
// MARK: - Fetching Fast Values from Table
extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible {
/// Returns a cursor over fetched values.
///
/// The order in which the values are returned is undefined
/// ([ref](https://www.sqlite.org/lang_select.html#the_order_by_clause)).
///
/// Values are decoded from the leftmost column.
///
/// The returned cursor is valid only during the remaining execution of the
/// database access. Do not store or return the cursor for later use.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// - parameter db: A database connection.
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor<RowDecoder> {
try all().fetchCursor(db)
}
/// Returns an array of fetched values.
///
/// Values are decoded from the leftmost column.
///
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
try all().fetchAll(db)
}
/// Returns a single fetched value.
///
/// The value is decoded from the leftmost column.
///
/// The result is nil if the request returns no row, or one row with a
/// `NULL` value.
///
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
try all().fetchOne(db)
}
}
extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible & Hashable {
/// Returns a set of fetched values.
///
/// Values are decoded from the leftmost column.
///
/// - parameter db: A database connection.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
try all().fetchSet(db)
}
}
// MARK: - Associations to TableRecord
extension Table {
/// Creates a ``BelongsToAssociation`` between this table and the
/// destination `TableRecord` type.
///
/// For more information, see ``TableRecord/belongsTo(_:key:using:)-13t5r``.
///
/// - parameters:
/// - destination: The record type at the other side of the association.
/// - key: The association key. By default, it
/// is `Destination.databaseTableName`.
/// - foreignKey: An eventual foreign key. You need to provide one when
/// no foreign key exists to the destination table, or several foreign
/// keys exist.
public func belongsTo<Destination>(
_ destination: Destination.Type,
key: String? = nil,
using foreignKey: ForeignKey? = nil)
-> BelongsToAssociation<RowDecoder, Destination>
where Destination: TableRecord
{
BelongsToAssociation(
to: Destination.relationForAll,
key: key,
using: foreignKey)
}
/// Creates a ``HasManyAssociation`` between this table and the
/// destination `TableRecord` type.
///
/// For more information, see ``TableRecord/hasMany(_:key:using:)-45axo``.
///
/// - parameters:
/// - destination: The record type at the other side of the association.
/// - key: The association key. By default, it
/// is `Destination.databaseTableName`.
/// - foreignKey: An eventual foreign key. You need to provide one when
/// no foreign key exists to the destination table, or several foreign
/// keys exist.
public func hasMany<Destination>(
_ destination: Destination.Type,
key: String? = nil,
using foreignKey: ForeignKey? = nil)
-> HasManyAssociation<RowDecoder, Destination>
where Destination: TableRecord
{
HasManyAssociation(
to: Destination.relationForAll,
key: key,
using: foreignKey)
}
/// Creates a ``HasOneAssociation`` between this table and the
/// destination `TableRecord` type.
///
/// For more information, see ``TableRecord/hasOne(_:key:using:)-4g9tm``.
///
/// - parameters:
/// - destination: The record type at the other side of the association.
/// - key: The association key. By default, it
/// is `Destination.databaseTableName`.
/// - foreignKey: An eventual foreign key. You need to provide one when
/// no foreign key exists to the destination table, or several foreign
/// keys exist.
public func hasOne<Destination>(
_ destination: Destination.Type,
key: String? = nil,
using foreignKey: ForeignKey? = nil)
-> HasOneAssociation<RowDecoder, Destination>
where Destination: TableRecord
{
HasOneAssociation(
to: Destination.relationForAll,
key: key,
using: foreignKey)
}
}
// MARK: - Associations to Table
extension Table {
/// Creates a ``BelongsToAssociation`` between this table and the
/// destination `Table`.
///
/// For more information, see ``TableRecord/belongsTo(_:key:using:)-13t5r``.
///
/// - parameters:
/// - destination: The table at the other side of the association.
/// - key: The association key. By default, it
/// is `destination.tableName`.
/// - foreignKey: An eventual foreign key. You need to provide one when
/// no foreign key exists to the destination table, or several foreign
/// keys exist.
public func belongsTo<Destination>(
_ destination: Table<Destination>,
key: String? = nil,
using foreignKey: ForeignKey? = nil)
-> BelongsToAssociation<RowDecoder, Destination>
{
BelongsToAssociation(
to: destination.relationForAll,
key: key,
using: foreignKey)
}
/// Creates a ``HasManyAssociation`` between this table and the
/// destination `Table`.
///
/// For more information, see ``TableRecord/hasMany(_:key:using:)-45axo``.
///
/// - parameters:
/// - destination: The table at the other side of the association.
/// - key: The association key. By default, it
/// is `destination.tableName`.
/// - foreignKey: An eventual foreign key. You need to provide one when
/// no foreign key exists to the destination table, or several foreign
/// keys exist.
public func hasMany<Destination>(
_ destination: Table<Destination>,
key: String? = nil,
using foreignKey: ForeignKey? = nil)
-> HasManyAssociation<RowDecoder, Destination>
{
HasManyAssociation(
to: destination.relationForAll,
key: key,
using: foreignKey)
}
/// Creates a ``HasOneAssociation`` between this table and the
/// destination `Table`.
///
/// For more information, see ``TableRecord/hasOne(_:key:using:)-4g9tm``.
///
/// - parameters:
/// - destination: The table at the other side of the association.
/// - key: The association key. By default, it
/// is `destination.tableName`.
/// - foreignKey: An eventual foreign key. You need to provide one when
/// no foreign key exists to the destination table, or several foreign
/// keys exist.
public func hasOne<Destination>(
_ destination: Table<Destination>,
key: String? = nil,
using foreignKey: ForeignKey? = nil)
-> HasOneAssociation<RowDecoder, Destination>
{
HasOneAssociation(
to: destination.relationForAll,
key: key,
using: foreignKey)
}
}
// MARK: - Associations to CommonTableExpression
extension Table {
/// Creates an association to a common table expression.
///
/// For more information, see ``TableRecord/association(to:on:)``.
///
/// - parameter cte: A common table expression.
/// - parameter condition: A function that returns the joining clause.
/// - parameter left: A `TableAlias` for the left table.
/// - parameter right: A `TableAlias` for the right table.
/// - returns: An association to the common table expression.
public func association<Destination>(
to cte: CommonTableExpression<Destination>,
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
{
JoinAssociation(
to: cte.relationForAll,
condition: .expression { condition($0, $1).sqlExpression })
}
/// Creates an association to a common table expression.
///
/// For more information, see ``TableRecord/association(to:)``.
///
/// - parameter cte: A common table expression.
/// - returns: An association to the common table expression.
public func association<Destination>(
to cte: CommonTableExpression<Destination>)
-> JoinAssociation<RowDecoder, Destination>
{
JoinAssociation(to: cte.relationForAll, condition: .none)
}
}
// MARK: - "Through" Associations
extension Table {
/// Creates a ``HasManyThroughAssociation`` between this table and the
/// destination type.
///
/// For more information, see ``TableRecord/hasMany(_:through:using:key:)``.
///
/// - parameters:
/// - destination: The record type at the other side of the association.
/// - pivot: An association from `Self` to the intermediate type.
/// - target: A target association from the intermediate type to the
/// destination type.
/// - key: The association key. By default, it is the key of the target.
public func hasMany<Pivot, Target>(
_ destination: Target.RowDecoder.Type,
through pivot: Pivot,
using target: Target,
key: String? = nil)
-> HasManyThroughAssociation<RowDecoder, Target.RowDecoder>
where Pivot: Association,
Target: Association,
Pivot.OriginRowDecoder == RowDecoder,
Pivot.RowDecoder == Target.OriginRowDecoder
{
let association = HasManyThroughAssociation(through: pivot, using: target)
if let key = key {
return association.forKey(key)
} else {
return association
}
}
/// Creates a ``HasOneThroughAssociation`` between this table and the
/// destination type.
///
/// For more information, see ``TableRecord/hasOne(_:through:using:key:)``.
///
/// - parameters:
/// - destination: The record type at the other side of the association.
/// - pivot: An association from Self to the intermediate type.
/// - target: A target association from the intermediate type to the
/// destination type.
/// - key: An eventual decoding key for the association. By default, it
/// is the same key as the target.
public func hasOne<Pivot, Target>(
_ destination: Target.RowDecoder.Type,
through pivot: Pivot,
using target: Target,
key: String? = nil)
-> HasOneThroughAssociation<RowDecoder, Target.RowDecoder>
where Pivot: AssociationToOne,
Target: AssociationToOne,
Pivot.OriginRowDecoder == RowDecoder,
Pivot.RowDecoder == Target.OriginRowDecoder
{
let association = HasOneThroughAssociation(through: pivot, using: target)
if let key = key {
return association.forKey(key)
} else {
return association
}
}
}
// MARK: - Joining Methods
extension Table {
/// Returns a request that fetches all rows associated with each row
/// in this request.
///
/// See the ``TableRecord`` method ``TableRecord/including(all:)``
/// for more information.
public func including<A: AssociationToMany>(all association: A)
-> QueryInterfaceRequest<RowDecoder>
where A.OriginRowDecoder == RowDecoder
{
all().including(all: association)
}
/// Returns a request that fetches the eventual row associated with each
/// row of this request.
///
/// See the ``TableRecord`` method ``TableRecord/including(optional:)``
/// for more information.
public func including<A: Association>(optional association: A)
-> QueryInterfaceRequest<RowDecoder>
where A.OriginRowDecoder == RowDecoder
{
all().including(optional: association)
}
/// Returns a request that fetches the row associated with each row in
/// this request. Rows that do not have an associated row are discarded.
///
/// See the ``TableRecord`` method ``TableRecord/including(required:)``
/// for more information.
public func including<A: Association>(required association: A)
-> QueryInterfaceRequest<RowDecoder>
where A.OriginRowDecoder == RowDecoder
{
all().including(required: association)
}
/// Returns a request that joins each row of this request to its
/// eventual associated row.
///
/// See the ``TableRecord`` method ``TableRecord/including(optional:)``
/// for more information.
public func joining<A: Association>(optional association: A)
-> QueryInterfaceRequest<RowDecoder>
where A.OriginRowDecoder == RowDecoder
{
all().joining(optional: association)
}
/// Returns a request that joins each row of this request to its
/// associated row. Rows that do not have an associated row are discarded.
///
/// See the ``TableRecord`` method ``TableRecord/including(required:)``
/// for more information.
public func joining<A: Association>(required association: A)
-> QueryInterfaceRequest<RowDecoder>
where A.OriginRowDecoder == RowDecoder
{
all().joining(required: association)
}
/// Returns a request with the columns of the eventual associated row
/// appended to the table columns.
///
/// See the ``TableRecord`` method ``TableRecord/annotated(withOptional:)``
/// for more information.
public func annotated<A: Association>(withOptional association: A)
-> QueryInterfaceRequest<RowDecoder>
where A.OriginRowDecoder == RowDecoder
{
all().annotated(withOptional: association)
}
/// Returns a request with the columns of the associated row appended to
/// the table columns. Rows that do not have an associated row
/// are discarded.
///
/// See the ``TableRecord`` method ``TableRecord/annotated(withRequired:)``
/// for more information.
public func annotated<A: Association>(withRequired association: A)
-> QueryInterfaceRequest<RowDecoder>
where A.OriginRowDecoder == RowDecoder
{
all().annotated(withRequired: association)
}
}
// MARK: - Association Aggregates
extension Table {
/// Returns a request with the given association aggregates appended to
/// the table colums.
///
/// See the ``TableRecord`` method ``TableRecord/annotated(with:)-4xoen``
/// for more information.
public func annotated(with aggregates: AssociationAggregate<RowDecoder>...) -> QueryInterfaceRequest<RowDecoder> {
all().annotated(with: aggregates)
}
/// Returns a request with the given association aggregates appended to
/// the table colums.
///
/// See the ``TableRecord`` method ``TableRecord/annotated(with:)-8ce7u``
/// for more information.
public func annotated(with aggregates: [AssociationAggregate<RowDecoder>]) -> QueryInterfaceRequest<RowDecoder> {
all().annotated(with: aggregates)
}
/// Returns a request filtered according to the provided
/// association aggregate.
///
/// See the ``TableRecord`` method ``TableRecord/having(_:)``
/// for more information.
public func having(_ predicate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest<RowDecoder> {
all().having(predicate)
}
}
// MARK: - Batch Delete
extension Table {
/// Deletes all rows, and returns the number of deleted rows.
///
/// - parameter db: A database connection.
/// - returns: The number of deleted rows
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public func deleteAll(_ db: Database) throws -> Int {
try all().deleteAll(db)
}
}
// MARK: - Check Existence by Single-Column Primary Key
extension Table {
/// Returns whether a row exists for this primary key.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// let playerTable = Table("player")
/// let countryTable = Table("country")
///
/// try dbQueue.read { db in
/// let playerExists = try playerTable.exists(db, key: 1)
/// let countryExists = try countryTable.exists(db, key: "FR")
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - key: A primary key value.
/// - returns: Whether a row exists for this primary key.
public func exists(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool {
try !filter(key: key).isEmpty(db)
}
}
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
extension Table
where RowDecoder: Identifiable,
RowDecoder.ID: DatabaseValueConvertible
{
/// Returns whether a row exists for this primary key.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// struct Player: Identifiable {
/// var id: Int64
/// }
/// struct Country: Identifiable {
/// var id: String
/// }
///
/// let playerTable = Table<Player>("player")
/// let countryTable = Table<Country>("country")
///
/// try dbQueue.read { db in
/// let playerExists = try playerTable.exists(db, id: 1)
/// let countryExists = try countryTable.exists(db, id: "FR")
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - id: A primary key value.
/// - returns: Whether a row exists for this primary key.
public func exists(_ db: Database, id: RowDecoder.ID) throws -> Bool {
if id.databaseValue.isNull {
// Don't hit the database
return false
}
return try !filter(id: id).isEmpty(db)
}
}
// MARK: - Check Existence by Key
extension Table {
/// Returns whether a row exists for this primary or unique key.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
/// let citizenshipTable = Table("citizenship")
///
/// try dbQueue.read { db in
/// let playerExists = playerTable.exists(db, key: ["id": 1])
/// let playerExists = playerTable.exists(db, key: ["email": "[email protected]"])
/// let citizenshipExists = citizenshipTable.exists(db, key: [
/// "citizenId": 1,
/// "countryCode": "FR",
/// ])
/// }
/// ```
///
/// A fatal error is raised if no unique index exists on a subset of the
/// key columns.
///
/// - parameters:
/// - db: A database connection.
/// - key: A unique key.
/// - returns: Whether a row exists for this key.
public func exists(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool {
try !filter(key: key).isEmpty(db)
}
}
// MARK: - Deleting by Single-Column Primary Key
extension Table {
/// Deletes rows identified by their primary keys, and returns the number
/// of deleted rows.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// let playerTable = Table("player")
/// let countryTable = Table("country")
///
/// try dbQueue.write { db in
/// // DELETE FROM player WHERE id IN (1, 2, 3)
/// try playerTable.deleteAll(db, keys: [1, 2, 3])
///
/// // DELETE FROM country WHERE code IN ('FR', 'US')
/// try countryTable.deleteAll(db, keys: ["FR", "US"])
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - keys: A sequence of primary keys.
/// - returns: The number of deleted rows.
@discardableResult
public func deleteAll<Keys>(_ db: Database, keys: Keys)
throws -> Int
where Keys: Sequence, Keys.Element: DatabaseValueConvertible
{
let keys = Array(keys)
if keys.isEmpty {
// Avoid hitting the database
return 0
}
return try filter(keys: keys).deleteAll(db)
}
/// Deletes the row identified by its primary key, and returns whether a
/// row was deleted.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// let playerTable = Table("player")
/// let countryTable = Table("country")
///
/// try dbQueue.write { db in
/// // DELETE FROM player WHERE id = 1
/// try playerTable.deleteOne(db, key: 1)
///
/// // DELETE FROM country WHERE code = 'FR'
/// try countryTable.deleteOne(db, key: "FR")
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - key: A primary key value.
/// - returns: Whether a row was deleted.
@discardableResult
public func deleteOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool {
if key.databaseValue.isNull {
// Don't hit the database
return false
}
return try deleteAll(db, keys: [key]) > 0
}
}
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
extension Table
where RowDecoder: Identifiable,
RowDecoder.ID: DatabaseValueConvertible
{
/// Deletes rows identified by their primary keys, and returns the number
/// of deleted rows.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// struct Player: Identifiable {
/// var id: Int64
/// }
/// struct Country: Identifiable {
/// var id: String
/// }
///
/// let playerTable = Table<Player>("player")
/// let countryTable = Table<Country>("country")
///
/// try dbQueue.write { db in
/// // DELETE FROM player WHERE id IN (1, 2, 3)
/// try playerTable.deleteAll(db, ids: [1, 2, 3])
///
/// // DELETE FROM country WHERE code IN ('FR', 'US')
/// try countryTable.deleteAll(db, ids: ["FR", "US"])
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - ids: A collection of primary keys.
/// - returns: The number of deleted rows.
@discardableResult
public func deleteAll<IDS>(_ db: Database, ids: IDS) throws -> Int
where IDS: Collection, IDS.Element == RowDecoder.ID
{
if ids.isEmpty {
// Avoid hitting the database
return 0
}
return try filter(ids: ids).deleteAll(db)
}
/// Deletes the row identified by its primary key, and returns whether a
/// row was deleted.
///
/// All single-column primary keys are supported:
///
/// ```swift
/// struct Player: Identifiable {
/// var id: Int64
/// }
/// struct Country: Identifiable {
/// var id: String
/// }
///
/// let playerTable = Table<Player>("player")
/// let countryTable = Table<Country>("country")
///
/// try dbQueue.write { db in
/// // DELETE FROM player WHERE id = 1
/// try playerTable.deleteOne(db, id: 1)
///
/// // DELETE FROM country WHERE code = 'FR'
/// try countryTable.deleteOne(db, id: "FR")
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - id: A primary key value.
/// - returns: Whether a row was deleted.
@discardableResult
public func deleteOne(_ db: Database, id: RowDecoder.ID) throws -> Bool {
if id.databaseValue.isNull {
// Don't hit the database
return false
}
return try deleteAll(db, ids: [id]) > 0
}
}
// MARK: - Deleting by Key
extension Table {
/// Deletes rows identified by their primary or unique keys, and returns
/// the number of deleted rows.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
/// let citizenshipTable = Table("citizenship")
///
/// try dbQueue.write { db in
/// // DELETE FROM player WHERE id = 1
/// try playerTable.deleteAll(db, keys: [["id": 1]])
///
/// // DELETE FROM player WHERE email = '[email protected]'
/// try playerTable.deleteAll(db, keys: [["email": "[email protected]"]])
///
/// // DELETE FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR'
/// try citizenshipTable.deleteAll(db, keys: [
/// ["citizenId": 1, "countryCode": "FR"],
/// ])
/// }
/// ```
///
/// A fatal error is raised if no unique index exists on a subset of the
/// key columns.
///
/// - parameters:
/// - db: A database connection.
/// - keys: An array of key dictionaries.
/// - returns: The number of deleted rows.
@discardableResult
public func deleteAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Int {
if keys.isEmpty {
// Avoid hitting the database
return 0
}
return try filter(keys: keys).deleteAll(db)
}
/// Deletes the row identified by its primary or unique keys, and returns
/// whether a row was deleted.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
/// let citizenshipTable = Table("citizenship")
///
/// try dbQueue.write { db in
/// // DELETE FROM player WHERE id = 1
/// try playerTable.deleteOne(db, key: ["id": 1])
///
/// // DELETE FROM player WHERE email = '[email protected]'
/// try playerTable.deleteOne(db, key: ["email": "[email protected]"])
///
/// // DELETE FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR'
/// try citizenshipTable.deleteOne(db, key: [
/// "citizenId": 1,
/// "countryCode": "FR",
/// ])
/// }
/// ```
///
/// A fatal error is raised if no unique index exists on a subset of the
/// key columns.
/// - parameters:
/// - db: A database connection.
/// - key: A dictionary of values.
/// - returns: Whether a row was deleted.
@discardableResult
public func deleteOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool {
try deleteAll(db, keys: [key]) > 0
}
}
// MARK: - Batch Update
extension Table {
/// Updates all rows, and returns the number of updated rows.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = 0
/// try playerTable.updateAll(db, [Column("score").set(to: 0)])
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: An array of column assignments.
/// - returns: The number of updated rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> Int
{
try all().updateAll(db, onConflict: conflictResolution, assignments)
}
/// Updates all rows, and returns the number of updated rows.
///
/// For example:
///
/// ```swift
/// let playerTable = Table("player")
///
/// try dbQueue.write { db in
/// // UPDATE player SET score = 0
/// try playerTable.updateAll(db, Column("score").set(to: 0))
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: An array of column assignments.
/// - returns: The number of updated rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: ColumnAssignment...)
throws -> Int
{
try updateAll(db, onConflict: conflictResolution, assignments)
}
}
| mit | 299a35b2332c7e53f5b9280354d93029 | 31.990058 | 118 | 0.585639 | 4.387501 | false | false | false | false |
AlicJ/CPUSimulator | CPUSimulator/Util.swift | 1 | 1341 | //
// Util.swift
// CPUSimulator
//
// Created by Alic on 2017-03-04.
// Copyright © 2017 4ZC3. All rights reserved.
// https://ktrkathir.wordpress.com/2015/12/29/draw-or-set-a-border-for-particular-side-of-uiview-using-swift/comment-page-1/#comment-228
import UIKit
import Foundation
class Util {
static func setBottomBorder(view: UIView)->UIView{
return setBottomBorder(view: view, color: UIColor.black.cgColor, thickness: 1);
}
static func setBottomBorder(view: UIView, color: CGColor, thickness: Int) -> UIView {
let bottomBorder = CALayer()
bottomBorder.frame = CGRect(x: 0, y: view.frame.height-1, width: view.frame.width, height: CGFloat(thickness))
bottomBorder.backgroundColor = color
view.layer.addSublayer(bottomBorder)
return view;
}
static func makeColorGradient(frequency1: Double, frequency2: Double , frequency3: Double, phase1: Double, phase2: Double, phase3: Double, len: Double, center: Double = 128.0, width: Double = 127.0) -> UIColor {
let r = sin(frequency1 * len + phase1) * width + center;
let g = sin(frequency2 * len + phase2) * width + center;
let b = sin(frequency3 * len + phase3) * width + center;
return UIColor(red: Int(r), green: Int(g), blue: Int(b))
}
}
| mit | 5459566a8bbbb34ff2260742b8a34506 | 36.222222 | 215 | 0.652985 | 3.602151 | false | false | false | false |
Antidote-for-Tox/Antidote | Antidote/QRScannerController.swift | 1 | 5233 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import UIKit
import AVFoundation
class QRScannerController: UIViewController {
var didScanStringsBlock: (([String]) -> Void)?
var cancelBlock: (() -> Void)?
fileprivate let theme: Theme
fileprivate var previewLayer: AVCaptureVideoPreviewLayer!
fileprivate var captureSession: AVCaptureSession!
fileprivate var aimView: QRScannerAimView!
var pauseScanning: Bool = false {
didSet {
pauseScanning ? captureSession.stopRunning() : captureSession.startRunning()
if !pauseScanning {
aimView.frame = CGRect.zero
}
}
}
init(theme: Theme) {
self.theme = theme
super.init(nibName: nil, bundle: nil)
createCaptureSession()
createBarButtonItems()
NotificationCenter.default.addObserver(
self,
selector: #selector(QRScannerController.applicationDidEnterBackground),
name: NSNotification.Name.UIApplicationDidEnterBackground,
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(QRScannerController.applicationWillEnterForeground),
name: NSNotification.Name.UIApplicationWillEnterForeground,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
required convenience init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
loadViewWithBackgroundColor(theme.colorForType(.NormalBackground))
createViewsAndLayers()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
captureSession.startRunning()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
captureSession.stopRunning()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
previewLayer.frame = view.bounds
}
}
// MARK: Actions
extension QRScannerController {
@objc func cancelButtonPressed() {
cancelBlock?()
}
}
// MARK: Notifications
extension QRScannerController {
@objc func applicationDidEnterBackground() {
captureSession.stopRunning()
}
@objc func applicationWillEnterForeground() {
if !pauseScanning {
captureSession.startRunning()
}
}
}
extension QRScannerController: AVCaptureMetadataOutputObjectsDelegate {
func metadataOutput(_ captureOutput: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
let readableObjects = metadataObjects.filter {
$0 is AVMetadataMachineReadableCodeObject
}.map {
previewLayer.transformedMetadataObject(for: $0 ) as! AVMetadataMachineReadableCodeObject
}
guard !readableObjects.isEmpty else {
return
}
aimView.frame = readableObjects[0].bounds
let strings = readableObjects.map {
$0.stringValue!
}
didScanStringsBlock?(strings)
}
}
private extension QRScannerController {
func createCaptureSession() {
captureSession = AVCaptureSession()
let input = captureSessionInput()
let output = AVCaptureMetadataOutput()
if (input != nil) && captureSession.canAddInput(input!) {
captureSession.addInput(input!)
}
if captureSession.canAddOutput(output) {
captureSession.addOutput(output)
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
if output.availableMetadataObjectTypes.contains({ AVMetadataObject.ObjectType.qr }()) {
output.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
}
}
}
func captureSessionInput() -> AVCaptureDeviceInput? {
guard let device = AVCaptureDevice.default(for: AVMediaType.video) else {
return nil
}
if device.isAutoFocusRangeRestrictionSupported {
do {
try device.lockForConfiguration()
device.autoFocusRangeRestriction = .near
device.unlockForConfiguration()
}
catch {
// nop
}
}
return try? AVCaptureDeviceInput(device: device)
}
func createBarButtonItems() {
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(QRScannerController.cancelButtonPressed))
}
func createViewsAndLayers() {
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
view.layer.addSublayer(previewLayer)
aimView = QRScannerAimView(theme: theme)
view.addSubview(aimView)
view.bringSubview(toFront: aimView)
}
}
| mpl-2.0 | 06545d5846e8726fbde867298c2be036 | 28.234637 | 162 | 0.652207 | 5.78232 | false | false | false | false |
inaturalist/INaturalistIOS | INaturalistIOS/Controllers/Onboarding/OnboardingReauthenticateViewController.swift | 1 | 4889 | //
// OnboardingReauthenticateViewController.swift
// iNaturalist
//
// Created by Alex Shepard on 9/12/22.
// Copyright © 2022 iNaturalist. All rights reserved.
//
import Foundation
import UIKit
import FBSDKLoginKit
import GoogleSignIn
@objc
class OnboardingReauthenticateViewController: UIViewController {
@IBOutlet weak var infoLabel: UILabel!
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var googleLoginButton: GIDSignInButton!
@IBOutlet weak var facebookLoginButton: FBSDKLoginButton!
@IBOutlet weak var stackview: UIStackView!
@objc var loginAction: (() -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
infoLabel.text = NSLocalizedString("You must re-authenticate to delete your account.", comment: "Reauthentication to delete account tip.")
if let appDelegate = UIApplication.shared.delegate as? INaturalistAppDelegate,
let login = appDelegate.loginController
{
usernameField.text = login.meUserLocal().login
login.delegate = self
self.facebookLoginButton.delegate = login
}
let cancel = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel))
navigationItem.rightBarButtonItem = cancel
loginButton.setTitleColor(.inatTint(), for: .normal)
if #available(iOS 13.0, *) {
let signInWithAppleButton = ASAuthorizationAppleIDButton(authorizationButtonType: .signIn, authorizationButtonStyle: .black)
signInWithAppleButton.addTarget(self, action: #selector(appleLoginPressed), for: .touchUpInside)
signInWithAppleButton.heightAnchor.constraint(equalToConstant: 44).isActive = true
self.stackview .addArrangedSubview(signInWithAppleButton)
}
}
@objc func appleLoginPressed(_ sender: Any) {
guard let appDelegate = UIApplication.shared.delegate as? INaturalistAppDelegate,
let login = appDelegate.loginController else
{
return
}
if #available(iOS 13.0, *) {
let provider = ASAuthorizationAppleIDProvider()
let request = provider.createRequest()
request.requestedScopes = [.email, .fullName]
let authController = ASAuthorizationController(authorizationRequests: [request])
authController.delegate = login
authController.presentationContextProvider = self
authController.performRequests()
}
}
@IBAction func googleLoginPressed(_ sender: Any) {
if GIDSignIn.sharedInstance.hasPreviousSignIn() {
GIDSignIn.sharedInstance.signOut()
}
if let appDelegate = UIApplication.shared.delegate as? INaturalistAppDelegate,
let login = appDelegate.loginController
{
login.loginWithGoogle(withPresentingVC: self)
}
}
@objc func cancel(_ sender: UIBarButtonItem) {
dismiss(animated: true)
}
@IBAction func loginButtonTapped(_ sender: UIButton) {
if let appDelegate = UIApplication.shared.delegate as? INaturalistAppDelegate,
let login = appDelegate.loginController
{
login.delegate = self
login.login(withUsername: usernameField.text, password: passwordField.text)
}
}
}
extension OnboardingReauthenticateViewController: INatAuthenticationDelegate {
func loginSuccess() {
if let action = self.loginAction {
action()
}
}
func delayForSettingUpAccount() { }
func loginFailedWithError(_ error: Error!) {
let alertTitle = NSLocalizedString("Oops", comment: "Title error with oops text.")
var alertMsg = NSLocalizedString("Failed to log in to iNaturalist. Please try again.", comment: "Unknown iNat login error")
if let error = error as? NSError {
if error.code == 401 {
alertMsg = NSLocalizedString("Incorrect username or password.", comment: "Error msg when we get a 401 from the server")
}
}
let alert = UIAlertController(title: alertTitle, message: alertMsg, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alert, animated: true)
}
}
extension OnboardingReauthenticateViewController: ASAuthorizationControllerPresentationContextProviding {
@available(iOS 13.0, *)
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
return self.view.window!
}
}
| mit | 1e13b232fc271f3db300dca3c46420dd | 35.207407 | 146 | 0.652209 | 5.353779 | false | false | false | false |
BeitIssieShapiro/IssieBoard | ConfigurableKeyboard/KeyboardKeyBackground.swift | 2 | 9719 |
import UIKit
class KeyboardKeyBackground: UIView, Connectable {
var fillPath: UIBezierPath?
var underPath: UIBezierPath?
var edgePaths: [UIBezierPath]?
// do not set this manually
var cornerRadius: CGFloat
var underOffset: CGFloat
var startingPoints: [CGPoint]
var segmentPoints: [(CGPoint, CGPoint)]
var arcCenters: [CGPoint]
var arcStartingAngles: [CGFloat]
var dirty: Bool
var attached: Direction? {
didSet {
self.dirty = true
self.setNeedsLayout()
}
}
var hideDirectionIsOpposite: Bool {
didSet {
self.dirty = true
self.setNeedsLayout()
}
}
init(cornerRadius: CGFloat, underOffset: CGFloat) {
attached = nil
hideDirectionIsOpposite = false
dirty = false
startingPoints = []
segmentPoints = []
arcCenters = []
arcStartingAngles = []
startingPoints.reserveCapacity(4)
segmentPoints.reserveCapacity(4)
arcCenters.reserveCapacity(4)
arcStartingAngles.reserveCapacity(4)
for _ in 0..<4 {
startingPoints.append(CGPoint.zero)
segmentPoints.append((CGPoint.zero, CGPoint.zero))
arcCenters.append(CGPoint.zero)
arcStartingAngles.append(0)
}
self.cornerRadius = cornerRadius
self.underOffset = underOffset
super.init(frame: CGRect.zero)
self.isUserInteractionEnabled = false
}
required init?(coder: NSCoder) {
fatalError("NSCoding not supported")
}
var oldBounds: CGRect?
override func layoutSubviews() {
if !self.dirty {
if self.bounds.width == 0 || self.bounds.height == 0 {
return
}
if oldBounds != nil && self.bounds.equalTo(oldBounds!) {
return
}
}
oldBounds = self.bounds
super.layoutSubviews()
self.generatePointsForDrawing(self.bounds)
self.dirty = false
}
let floatPi = CGFloat(M_PI)
let floatPiDiv2 = CGFloat(M_PI/2.0)
let floatPiDivNeg2 = -CGFloat(M_PI/2.0)
func generatePointsForDrawing(_ bounds: CGRect) {
let segmentWidth = bounds.width
let segmentHeight = bounds.height - CGFloat(underOffset)
// base, untranslated corner points
self.startingPoints[0] = CGPoint(x: 0, y: segmentHeight)
self.startingPoints[1] = CGPoint(x: 0, y: 0)
self.startingPoints[2] = CGPoint(x: segmentWidth, y: 0)
self.startingPoints[3] = CGPoint(x: segmentWidth, y: segmentHeight)
self.arcStartingAngles[0] = floatPiDiv2
self.arcStartingAngles[2] = floatPiDivNeg2
self.arcStartingAngles[1] = floatPi
self.arcStartingAngles[3] = 0
for i in 0 ..< self.startingPoints.count {
let currentPoint = self.startingPoints[i]
let nextPoint = self.startingPoints[(i + 1) % self.startingPoints.count]
var floatXCorner: CGFloat = 0
var floatYCorner: CGFloat = 0
if (i == 1) {
floatXCorner = cornerRadius
}
else if (i == 3) {
floatXCorner = -cornerRadius
}
if (i == 0) {
floatYCorner = -cornerRadius
}
else if (i == 2) {
floatYCorner = cornerRadius
}
let p0 = CGPoint(
x: currentPoint.x + (floatXCorner),
y: currentPoint.y + underOffset + (floatYCorner))
let p1 = CGPoint(
x: nextPoint.x - (floatXCorner),
y: nextPoint.y + underOffset - (floatYCorner))
self.segmentPoints[i] = (p0, p1)
let c = CGPoint(
x: p0.x - (floatYCorner),
y: p0.y + (floatXCorner))
self.arcCenters[i] = c
}
// order of edge drawing: left edge, down edge, right edge, up edge
// We need to have separate paths for all the edges so we can toggle them as needed.
// Unfortunately, it doesn't seem possible to assemble the connected fill path
// by simply using CGPathAddPath, since it closes all the subpaths, so we have to
// duplicate the code a little bit.
let fillPath = UIBezierPath()
var edgePaths: [UIBezierPath] = []
var prevPoint: CGPoint?
for i in 0..<4 {
var edgePath: UIBezierPath?
let segmentPoint = self.segmentPoints[i]
if self.attached != nil && (self.hideDirectionIsOpposite ? self.attached!.rawValue != i : self.attached!.rawValue == i) {
if !self.hideDirectionIsOpposite {
continue
}
}
else {
edgePath = UIBezierPath()
if prevPoint == nil {
prevPoint = segmentPoint.0
fillPath.move(to: prevPoint!)
}
fillPath.addLine(to: segmentPoint.0)
fillPath.addLine(to: segmentPoint.1)
edgePath!.move(to: segmentPoint.0)
edgePath!.addLine(to: segmentPoint.1)
prevPoint = segmentPoint.1
}
let shouldDrawArcInOppositeMode = (self.attached != nil ? (self.attached!.rawValue == i) || (self.attached!.rawValue == ((i + 1) % 4)) : false)
if (self.attached != nil && (self.hideDirectionIsOpposite ? !shouldDrawArcInOppositeMode : self.attached!.rawValue == ((i + 1) % 4))) {
} else {
edgePath = (edgePath == nil ? UIBezierPath() : edgePath)
if prevPoint == nil {
prevPoint = segmentPoint.1
fillPath.move(to: prevPoint!)
}
let startAngle = self.arcStartingAngles[(i + 1) % 4]
let endAngle = startAngle + floatPiDiv2
let arcCenter = self.arcCenters[(i + 1) % 4]
fillPath.addLine(to: prevPoint!)
fillPath.addArc(withCenter: arcCenter, radius: self.cornerRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
edgePath!.move(to: prevPoint!)
edgePath!.addArc(withCenter: arcCenter, radius: self.cornerRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
prevPoint = self.segmentPoints[(i + 1) % 4].0
}
edgePath?.apply(CGAffineTransform(translationX: 0, y: -self.underOffset))
if edgePath != nil { edgePaths.append(edgePath!) }
}
fillPath.close()
fillPath.apply(CGAffineTransform(translationX: 0, y: -self.underOffset))
let underPath = { () -> UIBezierPath in
let underPath = UIBezierPath()
underPath.move(to: self.segmentPoints[2].1)
var startAngle = self.arcStartingAngles[3]
var endAngle = startAngle + CGFloat(M_PI/2.0)
underPath.addArc(withCenter: self.arcCenters[3], radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: true)
underPath.addLine(to: self.segmentPoints[3].1)
startAngle = self.arcStartingAngles[0]
endAngle = startAngle + CGFloat(M_PI/2.0)
underPath.addArc(withCenter: self.arcCenters[0], radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: true)
underPath.addLine(to: CGPoint(x: self.segmentPoints[0].0.x, y: self.segmentPoints[0].0.y - self.underOffset))
startAngle = self.arcStartingAngles[1]
endAngle = startAngle - CGFloat(M_PI/2.0)
underPath.addArc(withCenter: CGPoint(x: self.arcCenters[0].x, y: self.arcCenters[0].y - self.underOffset), radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: false)
underPath.addLine(to: CGPoint(x: self.segmentPoints[2].1.x - self.cornerRadius, y: self.segmentPoints[2].1.y + self.cornerRadius - self.underOffset))
startAngle = self.arcStartingAngles[0]
endAngle = startAngle - CGFloat(M_PI/2.0)
underPath.addArc(withCenter: CGPoint(x: self.arcCenters[3].x, y: self.arcCenters[3].y - self.underOffset), radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: false)
underPath.close()
return underPath
}()
self.fillPath = fillPath
self.edgePaths = edgePaths
self.underPath = underPath
}
func attachmentPoints(_ direction: Direction) -> (CGPoint, CGPoint) {
let returnValue = (
self.segmentPoints[direction.clockwise().rawValue].0,
self.segmentPoints[direction.counterclockwise().rawValue].1)
return returnValue
}
func attachmentDirection() -> Direction? {
return self.attached
}
func attach(_ direction: Direction?) {
self.attached = direction
}
}
| apache-2.0 | 407bb5d56f622922d02ec535cf92bca5 | 35.537594 | 216 | 0.545838 | 5.054082 | false | false | false | false |
CodeInventorGroup/CIComponentKit | Sources/CICExtensions/AutoLayout+CIKit.swift | 1 | 2958 | //
// AutoLayout+CIKit.swift
// CIComponentKit
//
// Created by ManoBoo on 2017/9/26.
// Copyright © 2017年 club.codeinventor. All rights reserved.
// NOTICE
import UIKit
import Foundation
public protocol CICLayoutPropertyProtocol {
associatedtype type
var base: type {get}
static var screenScale: CGFloat { get }
static var screenWidth: CGFloat { get }
static var screenHeight: CGFloat { get }
static var screenSize: CGSize { get }
// eg: 50.makeSize == CGSize.init(width: 50, height: 50)
var makeSize: CGSize { get }
// eg: 50.makeRect == CGRect.init(origin: .zero, size: CGSize.init(width: 50, height: 50))
var makeRect: CGRect { get }
// eg 20.makeEdgeInsets = UIEdgeInsets.init(top: 20, left: 20, bottom: 20, right: 20)
var makeEdgeInsets: UIEdgeInsets { get }
}
extension CICLayoutPropertyProtocol {
public static var screenScale: CGFloat { return UIScreen.main.scale }
public static var screenSize: CGSize { return UIScreen.main.bounds.size }
public static var screenHeight: CGFloat { return UIScreen.main.bounds.height }
public static var screenWidth: CGFloat { return UIScreen.main.bounds.width }
public var makeSize: CGSize {
if let base = base as? CGFloat {
return CGSize.init(width: base, height: base)
} else if let base = base as? Double {
return CGSize.init(width: base, height: base)
} else if let base = base as? Int {
return CGSize.init(width: base, height: base)
}
return .zero
}
public var makeRect: CGRect {
return CGRect.init(origin: .zero, size: self.makeSize)
}
public var makeEdgeInsets: UIEdgeInsets {
if let base = base as? CGFloat {
return UIEdgeInsets.init(top: base, left: base, bottom: base, right: base)
}
return UIEdgeInsets.zero
}
}
extension Int: CICLayoutPropertyProtocol {
public var base: Int { return self }
public typealias type = Int
}
extension CGFloat: CICLayoutPropertyProtocol {
public var base: CGFloat { return self }
public typealias type = CGFloat
}
extension Double: CICLayoutPropertyProtocol {
public var base: Double { return self }
public typealias type = Double
}
extension CGSize: CICLayoutPropertyProtocol {
public var base: CGSize { return self }
public typealias type = CGSize
}
extension CGSize {
func valid() -> Bool {
if width > 0 && height > 0 {
return true
}
return false
}
func add(_ size: CGSize) -> CGSize {
return CGSize(width: self.width + size.width, height: self.height + size.height)
}
public func multiply(_ mutiplier: CGFloat) -> CGSize {
return CGSize.init(width: width * mutiplier, height: height * mutiplier)
}
}
extension UIEdgeInsets {
public static var layoutMargins: UIEdgeInsets {
return UIWindow().layoutMargins
}
}
| mit | 021125111dcf6adf70de387af239c393 | 27.68932 | 94 | 0.65753 | 4.264069 | false | false | false | false |
ikemai/ColorAdjuster | ColorAdjuster/ColorAdjuster.swift | 1 | 5914 | //
// ColorAdjuster.swift
// ColorAdjuster
//
// Created by Mai Ikeda on 2015/10/15.
// Copyright © 2015年 mai_ikeda. All rights reserved.
//
import UIKit
open class ColorAdjuster: UIView {
/**
Value of HBS
*/
public struct HBSProperties {
public var hue: CGFloat = 0
public var brightness: CGFloat = 0
public var saturation: CGFloat = 0
public var alpha: CGFloat = 1
}
/**
Value of RGB
*/
public struct RGBProperties {
public var red: CGFloat = 0
public var green: CGFloat = 0
public var blue: CGFloat = 0
public var alpha: CGFloat = 1
}
}
open class ColorAdjusterGradientView {
public enum Angle {
case zero, fortyFive, ninety
}
fileprivate weak var view: UIView?
fileprivate weak var gradientLayer: CAGradientLayer?
init(view: UIView) {
self.view = view
}
/**
Create gradation view
- parameter colors: [CGClor], locations: [CGFloat] = Please the same count.
*/
open func insertLayerVerticallyGradient(colors: [CGColor], locations: [CGFloat]) {
insertLayerVerticallyGradient(colors, locations: locations)
}
/**
Create gradation view
- parameter colors: [CGClor], startPoint: CGPoint, endPoint: CGPoint
*/
open func insertLayerVerticallyGradient(colors: [CGColor], startPoint: CGPoint, endPoint: CGPoint) {
insertLayerVerticallyGradient(colors, startPoint: startPoint, endPoint: endPoint)
}
/**
Create gradation view
- parameter colors: [CGClor], angle: Angle
*/
open func insertLayerVerticallyGradient(colors: [CGColor], angle: Angle) {
insertLayerVerticallyGradient(colors, angle: angle)
}
fileprivate func insertLayerVerticallyGradient(_ colors: [CGColor], locations: [CGFloat]? = nil, startPoint: CGPoint? = nil, endPoint: CGPoint? = nil, angle: Angle? = nil) {
guard let view = view else { return }
let layer = CAGradientLayer()
layer.frame = CGRect(origin: CGPoint.zero, size: view.frame.size)
layer.colors = colors as [AnyObject]
if let locations = locations {
layer.locations = locations as [NSNumber]?
}
if let startPoint = startPoint, let endPoint = endPoint {
layer.startPoint = startPoint
layer.endPoint = endPoint
}
if let angle = angle {
let points = getAnglePoint(angle)
layer.startPoint = points[0]
layer.endPoint = points[1]
}
gradientLayer?.removeFromSuperlayer()
gradientLayer = layer
view.layer.insertSublayer(layer, at: 0)
}
fileprivate func getAnglePoint(_ angle: Angle) -> [CGPoint] {
var startPoint: CGPoint
var endPoint: CGPoint
switch angle {
case .zero:
startPoint = CGPoint(x: 0.5, y: 0)
endPoint = CGPoint(x: 0.5, y: 1)
case .fortyFive:
startPoint = CGPoint(x: 1, y: 0)
endPoint = CGPoint(x: 0, y: 1)
case .ninety:
startPoint = CGPoint(x: 1, y: 0.5)
endPoint = CGPoint(x: 0, y: 0.5)
}
return [startPoint, endPoint]
}
}
extension UIColor {
/**
Appoint it in hexadecimal and create UIColor.
*/
public convenience init(hex: Int, alpha: CGFloat = 1) {
let red = CGFloat((hex & 0xFF0000) >> 16) / 255
let green = CGFloat((hex & 0x00FF00) >> 8 ) / 255
let blue = CGFloat((hex & 0x0000FF) >> 0 ) / 255
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
// MARK: - Change a value of HBS
extension UIColor {
/**
Adjustment color by HBS
- parameter hue, brightness, saturation = 0~1
*/
public func colorWithHBSComponent(hue: CGFloat, brightness: CGFloat, saturation: CGFloat) -> UIColor? {
if let hbs = colorHBS() {
return UIColor(hue: (hbs.hue * hue), saturation: (hbs.saturation * saturation), brightness: (hbs.brightness * brightness), alpha: hbs.alpha)
}
return nil
}
/**
Get color HBS
*/
public func colorHBS() -> ColorAdjuster.HBSProperties? {
var hbs = ColorAdjuster.HBSProperties()
let converted = getHue(&hbs.hue, saturation: &hbs.saturation, brightness: &hbs.brightness, alpha: &hbs.alpha)
if converted {
return hbs
}
return nil
}
}
// MARK: - Change a value of RGB
extension UIColor {
/**
Adjustment color by RGB
- parameter hue, brightness, saturation = 0~1
*/
public func colorWithRGBComponent(red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor? {
if let rgb = colorRGB() {
return UIColor(red: (rgb.red * red), green: (rgb.green * green), blue: (rgb.blue * blue), alpha: rgb.alpha)
}
return nil
}
/**
Get color RGB
*/
public func colorRGB() -> ColorAdjuster.RGBProperties? {
var rgb = ColorAdjuster.RGBProperties()
let converted = getRed(&rgb.red, green: &rgb.green, blue: &rgb.blue, alpha: &rgb.alpha)
if converted {
return rgb
}
return nil
}
}
var colorAdjusterGradientViewAssociationKey = "colorAdjusterGradientViewAssociation"
// MARK: - Create gradation view
extension UIView {
public var gradientLayer: ColorAdjusterGradientView {
get {
if let instance = objc_getAssociatedObject(self, &colorAdjusterGradientViewAssociationKey) as? ColorAdjusterGradientView {
return instance
}
let instance = ColorAdjusterGradientView(view: self)
objc_setAssociatedObject(self, &colorAdjusterGradientViewAssociationKey, instance, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return instance
}
}
}
| mit | d48cb5048fd728e7642d0a2a0253f65a | 29.626943 | 177 | 0.605481 | 4.47803 | false | false | false | false |
Tj3n/TVNExtensions | Rx/CLLocationManager+Rx.swift | 1 | 7359 | //
// CLLocationManager+Rx.swift
// RxExample
//
// Created by Carlos García on 8/7/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import CoreLocation
import RxSwift
import RxCocoa
extension Reactive where Base: CLLocationManager {
/**
Reactive wrapper for `delegate`.
For more information take a look at `DelegateProxyType` protocol documentation.
*/
public var delegate: DelegateProxy<CLLocationManager, CLLocationManagerDelegate> {
return RxCLLocationManagerDelegateProxy.proxy(for: base)
}
// MARK: Responding to Location Events
/**
Reactive wrapper for `delegate` message.
*/
public var didUpdateLocations: Observable<[CLLocation]> {
return RxCLLocationManagerDelegateProxy.proxy(for: base).didUpdateLocationsSubject.asObservable()
}
/**
Reactive wrapper for `delegate` message.
*/
public var didFailWithError: Observable<Error> {
return RxCLLocationManagerDelegateProxy.proxy(for: base).didFailWithErrorSubject.asObservable()
}
#if os(iOS) || os(macOS)
/**
Reactive wrapper for `delegate` message.
*/
public var didFinishDeferredUpdatesWithError: Observable<Error?> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didFinishDeferredUpdatesWithError:)))
.map { a in
return try castOptionalOrThrow(Error.self, a[1])
}
}
#endif
#if os(iOS)
// MARK: Pausing Location Updates
/**
Reactive wrapper for `delegate` message.
*/
public var didPauseLocationUpdates: Observable<Void> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManagerDidPauseLocationUpdates(_:)))
.map { _ in
return ()
}
}
/**
Reactive wrapper for `delegate` message.
*/
public var didResumeLocationUpdates: Observable<Void> {
return delegate.methodInvoked( #selector(CLLocationManagerDelegate.locationManagerDidResumeLocationUpdates(_:)))
.map { _ in
return ()
}
}
// MARK: Responding to Heading Events
/**
Reactive wrapper for `delegate` message.
*/
public var didUpdateHeading: Observable<CLHeading> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didUpdateHeading:)))
.map { a in
return try castOrThrow(CLHeading.self, a[1])
}
}
// MARK: Responding to Region Events
/**
Reactive wrapper for `delegate` message.
*/
public var didEnterRegion: Observable<CLRegion> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didEnterRegion:)))
.map { a in
return try castOrThrow(CLRegion.self, a[1])
}
}
/**
Reactive wrapper for `delegate` message.
*/
public var didExitRegion: Observable<CLRegion> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didExitRegion:)))
.map { a in
return try castOrThrow(CLRegion.self, a[1])
}
}
#endif
#if os(iOS) || os(macOS)
/**
Reactive wrapper for `delegate` message.
*/
@available(OSX 10.10, *)
public var didDetermineStateForRegion: Observable<(state: CLRegionState, region: CLRegion)> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didDetermineState:for:)))
.map { a in
let stateNumber = try castOrThrow(NSNumber.self, a[1])
let state = CLRegionState(rawValue: stateNumber.intValue) ?? CLRegionState.unknown
let region = try castOrThrow(CLRegion.self, a[2])
return (state: state, region: region)
}
}
/**
Reactive wrapper for `delegate` message.
*/
public var monitoringDidFailForRegionWithError: Observable<(region: CLRegion?, error: Error)> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:monitoringDidFailFor:withError:)))
.map { a in
let region = try castOptionalOrThrow(CLRegion.self, a[1])
let error = try castOrThrow(Error.self, a[2])
return (region: region, error: error)
}
}
/**
Reactive wrapper for `delegate` message.
*/
public var didStartMonitoringForRegion: Observable<CLRegion> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didStartMonitoringFor:)))
.map { a in
return try castOrThrow(CLRegion.self, a[1])
}
}
#endif
#if os(iOS)
// MARK: Responding to Ranging Events
/**
Reactive wrapper for `delegate` message.
*/
public var didRangeBeaconsInRegion: Observable<(beacons: [CLBeacon], region: CLBeaconRegion)> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didRangeBeacons:in:)))
.map { a in
let beacons = try castOrThrow([CLBeacon].self, a[1])
let region = try castOrThrow(CLBeaconRegion.self, a[2])
return (beacons: beacons, region: region)
}
}
/**
Reactive wrapper for `delegate` message.
*/
public var rangingBeaconsDidFailForRegionWithError: Observable<(region: CLBeaconRegion, error: Error)> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:rangingBeaconsDidFailFor:withError:)))
.map { a in
let region = try castOrThrow(CLBeaconRegion.self, a[1])
let error = try castOrThrow(Error.self, a[2])
return (region: region, error: error)
}
}
// MARK: Responding to Visit Events
/**
Reactive wrapper for `delegate` message.
*/
@available(iOS 8.0, *)
public var didVisit: Observable<CLVisit> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didVisit:)))
.map { a in
return try castOrThrow(CLVisit.self, a[1])
}
}
#endif
// MARK: Responding to Authorization Changes
/**
Reactive wrapper for `delegate` message.
*/
public var didChangeAuthorizationStatus: Observable<CLAuthorizationStatus> {
return delegate.methodInvoked(#selector(CLLocationManagerDelegate.locationManager(_:didChangeAuthorization:)))
.map { a in
let number = try castOrThrow(NSNumber.self, a[1])
return CLAuthorizationStatus(rawValue: Int32(number.intValue)) ?? .notDetermined
}
}
}
private func castOrThrow<T>(_ resultType: T.Type, _ object: Any) throws -> T {
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
private func castOptionalOrThrow<T>(_ resultType: T.Type, _ object: Any) throws -> T? {
if NSNull().isEqual(object) {
return nil
}
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
| mit | 685e054e84b35ecceb19b290af062d33 | 32.593607 | 130 | 0.641702 | 5.184637 | false | false | false | false |
ngquerol/Diurna | App/Sources/Views/CommentsOutlineView.swift | 1 | 2063 | //
// CommentsOutlineView.swift
// Diurna
//
// Created by Nicolas Gaulard-Querol on 25/02/2016.
// Copyright © 2016 Nicolas Gaulard-Querol. All rights reserved.
//
import AppKit
import HackerNewsAPI
class CommentsOutlineView: NSOutlineView {
// MARK: Properties
private let outlineCellWidth: CGFloat = 16
// MARK: Methods
// Remove disclosure triangle ("outline cell")
override func frameOfOutlineCell(atRow _: Int) -> NSRect {
.zero
}
override func frameOfCell(atColumn column: Int, row: Int) -> NSRect {
let frame = super.frameOfCell(atColumn: column, row: row)
return NSRect(
x: frame.origin.x - outlineCellWidth,
y: frame.origin.y,
width: frame.width + outlineCellWidth,
height: frame.height
)
}
override func drawGrid(inClipRect clipRect: NSRect) {}
override func menu(for event: NSEvent) -> NSMenu? {
let point = convert(event.locationInWindow, from: nil)
let rowAtPoint = row(at: point)
guard
rowAtPoint != -1,
let comment = item(atRow: rowAtPoint) as? Comment
else {
return nil
}
let menu = NSMenu(title: "Comment Context Menu")
let menuItem =
menu
.addItem(withTitle: "Open in browser", action: .openCommentInBrowser, keyEquivalent: "")
menuItem.representedObject = comment
return menu
}
@objc func openCommentInBrowser(_ sender: NSMenuItem) {
guard let comment = sender.representedObject as? Comment else { return }
let commentURL = HNWebpage.item(comment.id).path
do {
try NSWorkspace.shared.open(commentURL, options: .withoutActivation, configuration: [:])
} catch let error as NSError {
NSAlert(error: error).runModal()
}
}
}
// MARK: - Selectors
extension Selector {
fileprivate static let openCommentInBrowser = #selector(
CommentsOutlineView
.openCommentInBrowser(_:))
}
| mit | c44ce525384bd08f24a79884eb72e34a | 25.779221 | 100 | 0.620757 | 4.602679 | false | false | false | false |
ming1016/smck | smck/Lib/RxSwift/ReplaySubject.swift | 15 | 6821 | //
// ReplaySubject.swift
// RxSwift
//
// Created by Krunoslav Zaher on 4/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/// Represents an object that is both an observable sequence as well as an observer.
///
/// Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
public class ReplaySubject<Element>
: Observable<Element>
, SubjectType
, ObserverType
, Disposable {
public typealias SubjectObserverType = ReplaySubject<Element>
/// Indicates whether the subject has any observers
public var hasObservers: Bool {
_lock.lock()
let value = _observers.count > 0
_lock.unlock()
return value
}
fileprivate let _lock = RecursiveLock()
// state
fileprivate var _isDisposed = false
fileprivate var _isStopped = false
fileprivate var _stoppedEvent = nil as Event<Element>? {
didSet {
_isStopped = _stoppedEvent != nil
}
}
fileprivate var _observers = Bag<(Event<Element>) -> ()>()
typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType
func unsubscribe(_ key: DisposeKey) {
abstractMethod()
}
final var isStopped: Bool {
return _isStopped
}
/// Notifies all subscribed observers about next event.
///
/// - parameter event: Event to send to the observers.
public func on(_ event: Event<E>) {
abstractMethod()
}
/// Returns observer interface for subject.
public func asObserver() -> SubjectObserverType {
return self
}
/// Unsubscribe all observers and release resources.
public func dispose() {
}
/// Creates new instance of `ReplaySubject` that replays at most `bufferSize` last elements of sequence.
///
/// - parameter bufferSize: Maximal number of elements to replay to observer after subscription.
/// - returns: New instance of replay subject.
public static func create(bufferSize: Int) -> ReplaySubject<Element> {
if bufferSize == 1 {
return ReplayOne()
}
else {
return ReplayMany(bufferSize: bufferSize)
}
}
/// Creates a new instance of `ReplaySubject` that buffers all the elements of a sequence.
/// To avoid filling up memory, developer needs to make sure that the use case will only ever store a 'reasonable'
/// number of elements.
public static func createUnbounded() -> ReplaySubject<Element> {
return ReplayAll()
}
}
fileprivate class ReplayBufferBase<Element>
: ReplaySubject<Element>
, SynchronizedUnsubscribeType {
func trim() {
abstractMethod()
}
func addValueToBuffer(_ value: Element) {
abstractMethod()
}
func replayBuffer<O: ObserverType>(_ observer: O) where O.E == Element {
abstractMethod()
}
override func on(_ event: Event<Element>) {
dispatch(_synchronized_on(event), event)
}
func _synchronized_on(_ event: Event<E>) -> Bag<(Event<Element>) -> ()> {
_lock.lock(); defer { _lock.unlock() }
if _isDisposed {
return Bag()
}
if _isStopped {
return Bag()
}
switch event {
case .next(let value):
addValueToBuffer(value)
trim()
return _observers
case .error, .completed:
_stoppedEvent = event
trim()
let observers = _observers
_observers.removeAll()
return observers
}
}
override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element {
_lock.lock()
let subscription = _synchronized_subscribe(observer)
_lock.unlock()
return subscription
}
func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E {
if _isDisposed {
observer.on(.error(RxError.disposed(object: self)))
return Disposables.create()
}
let anyObserver = observer.asObserver()
replayBuffer(anyObserver)
if let stoppedEvent = _stoppedEvent {
observer.on(stoppedEvent)
return Disposables.create()
}
else {
let key = _observers.insert(observer.on)
return SubscriptionDisposable(owner: self, key: key)
}
}
func synchronizedUnsubscribe(_ disposeKey: DisposeKey) {
_lock.lock()
_synchronized_unsubscribe(disposeKey)
_lock.unlock()
}
func _synchronized_unsubscribe(_ disposeKey: DisposeKey) {
if _isDisposed {
return
}
_ = _observers.removeKey(disposeKey)
}
override func dispose() {
super.dispose()
synchronizedDispose()
}
func synchronizedDispose() {
_lock.lock()
_synchronized_dispose()
_lock.unlock()
}
func _synchronized_dispose() {
_isDisposed = true
_observers.removeAll()
}
}
final class ReplayOne<Element> : ReplayBufferBase<Element> {
private var _value: Element?
override init() {
super.init()
}
override func trim() {
}
override func addValueToBuffer(_ value: Element) {
_value = value
}
override func replayBuffer<O: ObserverType>(_ observer: O) where O.E == Element {
if let value = _value {
observer.on(.next(value))
}
}
override func _synchronized_dispose() {
super._synchronized_dispose()
_value = nil
}
}
class ReplayManyBase<Element> : ReplayBufferBase<Element> {
fileprivate var _queue: Queue<Element>
init(queueSize: Int) {
_queue = Queue(capacity: queueSize + 1)
}
override func addValueToBuffer(_ value: Element) {
_queue.enqueue(value)
}
override func replayBuffer<O: ObserverType>(_ observer: O) where O.E == Element {
for item in _queue {
observer.on(.next(item))
}
}
override func _synchronized_dispose() {
super._synchronized_dispose()
_queue = Queue(capacity: 0)
}
}
final class ReplayMany<Element> : ReplayManyBase<Element> {
private let _bufferSize: Int
init(bufferSize: Int) {
_bufferSize = bufferSize
super.init(queueSize: bufferSize)
}
override func trim() {
while _queue.count > _bufferSize {
_ = _queue.dequeue()
}
}
}
final class ReplayAll<Element> : ReplayManyBase<Element> {
init() {
super.init(queueSize: 0)
}
override func trim() {
}
}
| apache-2.0 | 63bfd083d20f41e6264d0cdf30cf4446 | 25.030534 | 118 | 0.585777 | 4.854093 | false | false | false | false |
priyax/TextToSpeech | textToTableViewController/textToTableViewController/ArchiveRecipe.swift | 1 | 821 | //
// ArchiveRecipe.swift
// textToTableViewController
//
// Created by Priya Xavier on 6/1/17.
// Copyright © 2017 Guild/SA. All rights reserved.
//
import UIKit
class ArchiveRecipe: NSObject {
// Archiver properties
var title :String?
var ingredients :[String]?
var instructions :[String]?
var recipeUrl : String?
var thumbnailUrl :String?
// Archiving paths
static var DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiverUrl = DocumentsDirectory.appendPathComponent("recipe")
struct PropertyKey {
static let titleKey = "title"
static let ingredientsKey = "ingredients"
static let instructionsKey = "instructions"
static let recipeUrlKey = "recipeUrl"
static let thumbnailUrlKey = "thumbnailUrl"
}
}
| mit | d6fa9fd5462eb59ac138fcc6e84f07cc | 24.625 | 105 | 0.719512 | 4.361702 | false | false | false | false |
ThreeMillion/StretchyHeaders | StretchyHeaders/StretchyHeaders/NewsItemCell.swift | 1 | 693 | //
// NewsItemCell.swift
// StretchyHeaders
//
// Created by shibin on 16/1/9.
// Copyright © 2016年 啾三万. All rights reserved.
//
import UIKit
class NewsItemCell: UITableViewCell {
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var summaryLabel: UILabel!
var newsItem: NewsItem? {
didSet {
if let item = newsItem {
categoryLabel.text = item.category.toString()
categoryLabel.textColor = item.category.toColor()
summaryLabel.text = item.summary
} else {
categoryLabel.text = nil
summaryLabel.text = nil
}
}
}
}
| mit | e6dfbd848ee6d7552f5a7fb0f08b62c8 | 23.428571 | 65 | 0.568713 | 4.5 | false | false | false | false |
rhodgkins/RDHCommonCrypto | RDHCommonCrypto/Cryptor.swift | 1 | 22644 | //
// Cryptor.swift
// RDHCommonCrypto
//
// Created by Richard Hodgkins on 15/09/2014.
// Copyright (c) 2014 Rich Hodgkins. All rights reserved.
//
import Foundation
import Security
/// Operations that an CCCryptor can perform.
public enum Operation : Int {
/// Symmetric encryption.
case Encrypt
/// Symmetric decryption.
case Decrypt
private var cValue: CCOperation {
switch (self) {
case .Encrypt:
return CCOperation(kCCEncrypt)
case .Decrypt:
return CCOperation(kCCDecrypt)
}
}
};
private extension CCAlgorithm
{
/// @returns the block size for the algorithm
private var blockSize: Int {
switch(Int(self)) {
case kCCAlgorithmAES:
fallthrough
case kCCAlgorithmAES128:
return RDHBlockSizeAES128.value
case kCCAlgorithmDES:
return RDHBlockSizeDES.value
case kCCAlgorithm3DES:
return RDHBlockSizeTripleDES.value
case kCCAlgorithmCAST:
return RDHBlockSizeCAST.value
case kCCAlgorithmRC2:
return RDHBlockSizeRC2.value
case kCCAlgorithmBlowfish:
return RDHBlockSizeBlowfish.value
case kCCAlgorithmRC4:
// Stream ciphers have no block size
return 0
default:
return 0
}
}
private var contextSize: Int {
switch(Int(self)) {
case kCCAlgorithmAES:
fallthrough
case kCCAlgorithmAES128:
return RDHContextSizeAES128.value
case kCCAlgorithmDES:
return RDHContextSizeDES.value
case kCCAlgorithm3DES:
return RDHContextSizeTripleDES.value
case kCCAlgorithmCAST:
return RDHContextSizeCAST.value
case kCCAlgorithmRC4:
return RDHContextSizeRC4.value
case kCCAlgorithmRC2:
return 128
case kCCAlgorithmBlowfish:
return 128
default:
return 0
}
}
}
private extension RDHAlgorithm
{
/// @returns the block size for the algorithm
private var blockSize: Int {
return self.toRaw().blockSize
}
/// @returns the memory size needed to create the CryptorRef for the algorithm
private var contextSize: Int {
return self.toRaw().contextSize
}
}
public extension CCAlgorithm
{
public func randomIV() -> NSData? {
if (self == CCAlgorithm(kCCAlgorithmRC4)) {
// Stream cipher return nil
return nil
} else {
return secureRandomData(self.blockSize)
}
}
}
public extension RDHAlgorithm
{
public func randomIV() -> NSData? {
return self.toRaw().randomIV()
}
}
/// Options, passed to cryptor.
public struct Option
{
/// Perform PKCS7 padding.
public static let PKCS7Padding = Option(kCCOptionPKCS7Padding)
/// Electronic Code Book Mode. Default is CBC.
public static let ECBMode = Option(kCCOptionECBMode)
private let ccValue: CCOptions
/// A new Option can be created in case newer options are ever added and this library has not yet been updated.
public init(_ ccValue: Int) {
self.ccValue = CCOptions(ccValue);
}
/// Converts the specified options to the CC value.
private static func CCValue(options: [Option]?) -> CCOptions {
var ccOptions: CCOptions = 0;
if let unwrappedOptions = options {
for option in unwrappedOptions {
ccOptions |= option.ccValue;
}
}
return ccOptions;
}
}
@objc public class Cryptor: NSObject {
/// Explicity unwrapped optional as its required
private let cryptor: CCCryptorRef!
/// Only used when creating a Cryptor with data
private let memoryForCryptor: NSMutableData?
// MARK: Cryptor objects
/// Init.
public convenience init(operation: Operation, algorithm: RDHAlgorithm, options: [Option]?, key: NSData, initialisationVector: NSData? = nil) {
let ccOptions = Option.CCValue(options)
self.init(operation: operation.cValue, algorithm: algorithm.toRaw(), options: ccOptions, key: key, initialisationVector: initialisationVector)
}
/// Init for Objective-C. Marked as internal for Swift as there is a Swift specific init.
@objc convenience init(operation: CCOperation, algorithm: CCAlgorithm, options: CCOptions, key: NSData, initialisationVector: NSData? = nil) {
// Key
let ccKeyLength = UInt(key.length)
// IV
let ccIV = (initialisationVector != nil) ? initialisationVector!.bytes : nil
self.init({
var cryptor: CCCryptorRef = nil
// Creator a cryptor
let status = RDHStatus.statusForOperation {
CCCryptorCreate(operation, algorithm, options, key.bytes, ccKeyLength, ccIV, &cryptor)
}
if (status != RDHStatus.Success) {
cryptor = nil
}
return cryptor
})
}
/// Init with data.
public convenience init(operation: Operation, algorithm: RDHAlgorithm, options: [Option]?, key: NSData, initialisationVector: NSData?, inout returningDataForMemory location: NSMutableData?) {
let ccOptions = Option.CCValue(options)
self.init(operation: operation.cValue, algorithm: algorithm.toRaw(), options: ccOptions, key: key, initialisationVector: initialisationVector, returningDataForMemory: &location)
}
/// Init with data for Objective-C. Marked as internal for Swift as there is a Swift specific init.
@objc convenience init(operation: CCOperation, algorithm: CCAlgorithm, options: CCOptions, key: NSData, initialisationVector: NSData?, returningDataForMemory location: AutoreleasingUnsafeMutablePointer<NSMutableData?>)
{
assert(location != nil, "returningDataForMemory must be specified")
// Key
let ccKeyLength = UInt(key.length)
// IV
let ccIV = (initialisationVector != nil) ? initialisationVector!.bytes : nil
// Data used
var dataUsed: UInt = 0
var ccDataLength = algorithm.contextSize
var memoryLocation: NSMutableData
// Use the data if some has been provided otherwise create some
if let actualLocal = location.memory {
memoryLocation = actualLocal
memoryLocation.length = ccDataLength
} else {
memoryLocation = NSMutableData(length: ccDataLength)
}
location.memory = memoryLocation
var ccData = memoryLocation.bytes
self.init({
var cryptor: CCCryptorRef = nil
// Creator a cryptor
let status = RDHStatus.statusForOperation {
CCCryptorCreateFromData(operation, algorithm, options, key.bytes, ccKeyLength, ccIV, ccData, UInt(ccDataLength), &cryptor, &dataUsed)
}
if status == RDHStatus.Success {
memoryLocation.length = Int(dataUsed)
} else if status == RDHStatus.BufferTooSmall {
// Repeat with returned size
ccDataLength = Int(dataUsed)
memoryLocation.length = ccDataLength
// Try creating a cryptor again
let repeatedStatus = RDHStatus.statusForOperation {
CCCryptorCreateFromData(operation, algorithm, options, key.bytes, ccKeyLength, ccIV, ccData, UInt(ccDataLength), &cryptor, &dataUsed)
}
if repeatedStatus != RDHStatus.Success {
memoryLocation.length = Int(dataUsed)
cryptor = nil
}
} else {
cryptor = nil
}
return cryptor
}, optionMemoryLocation: memoryLocation)
}
/// Init with mode.
public convenience init(operation: Operation, mode: RDHMode, algorithm: RDHAlgorithm, padding: RDHPadding, key: NSData, initialisationVector: NSData?, tweakMaterial: NSData, numberOfRounds: Int = 0) {
self.init(operation: operation.cValue, mode: mode.toRaw(), algorithm: algorithm.toRaw(), padding: padding.toRaw(), key: key, initialisationVector: initialisationVector, tweakMaterial: tweakMaterial, numberOfRounds: numberOfRounds)
}
/// Init with mode for Objective-C. Marked as internal for Swift as there is a Swift specific init.
@objc convenience init(operation: CCOperation, mode: CCMode, algorithm: CCAlgorithm, padding: CCPadding, key: NSData, initialisationVector: NSData?, tweakMaterial: NSData, numberOfRounds: Int = 0)
{
// IV
let ccIV = (initialisationVector != nil) ? initialisationVector!.bytes : nil
// Key
let ccKeyLength = UInt(key.length)
// Tweak material
let ccTweak = tweakMaterial.bytes
let ccTweakLength = UInt(tweakMaterial.length)
self.init({
var cryptor: CCCryptorRef = nil
// Create a cryptor
let status = RDHStatus.statusForOperation {
CCCryptorCreateWithMode(operation, mode, algorithm, padding, ccIV, key.bytes, ccKeyLength, ccTweak, ccTweakLength, Int32(numberOfRounds), 0, &cryptor)
}
if (status != RDHStatus.Success) {
cryptor = nil
}
return cryptor
})
}
/// Designated initialiser which sets the cryptor object to be used from the closure that creates one
private init(_ cryptorCreationBlock: () -> CCCryptorRef!, optionMemoryLocation memoryForCryptor: NSMutableData? = nil) {
let cryptor = cryptorCreationBlock()
// Unwrap to see if the backing pointer is nil (NULL) if it is then use nil and unwrap again to raise a fatal error
self.cryptor = ((cryptor!) != nil ? cryptor : nil)!
self.memoryForCryptor = memoryForCryptor
// if (cryptor!) != nil {
// self.cryptor = cryptor
// } else {
// self.cryptor = nil
// // TODO: eventually return nil
// }
}
deinit {
CCCryptorRelease(self.cryptor)
if let actualMemory = self.memoryForCryptor {
// Zero out the memory
actualMemory.setData(NSMutableData(length: actualMemory.length))
actualMemory.length = 0
}
}
/// @returns the required output size for the specificed input length.
private func outputSizeForDataInLength(dataInLength: UInt, isFinal final: Bool) -> UInt
{
return CCCryptorGetOutputLength(self.cryptor, dataInLength, final)
}
/// @returns the possible data out and possible error. If dataOut is nil then there will be an error.
public func updateWithData(dataIn: NSData) -> (dataOut: NSData?, error: NSError?) {
var resultantError: NSError?
let resultantData = update(dataIn, error: &resultantError)
return (dataOut: resultantData, error: resultantError)
}
/// Update for Objective-C. Marked as internal for Swift as there is a Swift specific function. @returns the data out, if this is nil then error is set.
@objc func update(dataIn: NSData, error: NSErrorPointer = nil) -> NSData? {
// Data in
let ccDataIn = dataIn.bytes
let ccDataInLength = UInt(dataIn.length)
// Data out
let dataOutAvailable = outputSizeForDataInLength(ccDataInLength, isFinal: false)
var dataOut: NSMutableData? = NSMutableData(length: Int(dataOutAvailable))
var dataOutMoved: UInt = 0
// Pointer to data out - we can explicitly unwrap as we just created it above
var ccDataOut = dataOut!.mutableBytes
// Perform the cryptor operation
let (status, success, resultantError) = cryptoBlockReturningData {
let intStatus = CCCryptorUpdate(self.cryptor, ccDataIn, ccDataInLength, &ccDataOut, dataOutAvailable, &dataOutMoved)
return (intStatus, dataOut, dataOutMoved)
}
if (error != nil) {
error.memory = resultantError
}
if success {
// Nothing to do
} else if status == RDHStatus.BufferTooSmall {
// Repeat with returned size
// cryptoBlockReturningData sets the needed size
// Perform the cryptor operation
let (_, repeatedSuccess, repeatedResultantError) = cryptoBlockReturningData {
let intStatus = CCCryptorUpdate(self.cryptor, ccDataIn, ccDataInLength, &ccDataOut, dataOutMoved, &dataOutMoved)
return (intStatus, dataOut, dataOutMoved)
}
if (error != nil) {
error.memory = repeatedResultantError
}
if (!repeatedSuccess) {
// Error - zero out data
dataOut!.length = 0
dataOut!.setData(NSData())
dataOut = nil
}
} else {
// Error
dataOut = nil
}
return dataOut
}
/// @returns the possible final data out and possible error. If dataOut is nil then there will be an error.
public func final() -> (dataOut: NSData?, error: NSError?) {
var resultantError: NSError?
let resultantData = final(&resultantError)
return (dataOut: resultantData, error: resultantError)
}
/// Final for Objective-C. Marked as internal for Swift as there is a Swift specific function. @returns the final data out, if this is nil then error is set.
@objc func final(error: NSErrorPointer) -> NSData? {
// Data out
let dataOutAvailable = outputSizeForDataInLength(0, isFinal: true)
var dataOut: NSMutableData? = NSMutableData(length: Int(dataOutAvailable))
var dataOutMoved: UInt = 0
// Pointer to data out - we can explicitly unwrap as we just created it above
var ccDataOut = dataOut!.mutableBytes
// Perform the cryptor operation
let (status, success, resultantError) = cryptoBlockReturningData {
let intStatus = CCCryptorFinal(self.cryptor, &ccDataOut, dataOutAvailable, &dataOutMoved)
return (intStatus, dataOut, dataOutMoved)
}
if (error != nil) {
error.memory = resultantError
}
if success {
// Nothing to do
} else if status == RDHStatus.BufferTooSmall {
// Repeat with returned size
// cryptoBlockReturningData sets the needed size
// Perform the cryptor operation
let (_, repeatedSuccess, repeatedResultantError) = cryptoBlockReturningData {
let intStatus = CCCryptorFinal(self.cryptor, &ccDataOut, dataOutMoved, &dataOutMoved)
return (intStatus, dataOut, dataOutMoved)
}
if (error != nil) {
error.memory = repeatedResultantError
}
if (!repeatedSuccess) {
// Error - zero out data
dataOut!.length = 0
dataOut!.setData(NSData())
dataOut = nil
}
} else {
// Error
dataOut = nil
}
return dataOut
}
/// @returns true if reset was successful. false will have an error set.
public func resetWithInitialisationVector(_ initialisationVector: NSData? = nil) -> (result: Bool, error: NSError?) {
var resultantError: NSError?
let result = resetWithInitialisationVector(initialisationVector, error: &resultantError)
return (result: result, error: resultantError)
}
/// Reset for Objective-C. Marked as internal for Swift as there is a Swift specific function. @returns true if reset was successful. false will have an error set.
@objc func resetWithInitialisationVector(_ initialisationVector: NSData? = nil, error: NSErrorPointer = nil) -> Bool {
// IV
let ccIV = (initialisationVector != nil) ? initialisationVector!.bytes : nil
// Crypto operation
let status = RDHStatus.statusForOperation {
CCCryptorReset(self.cryptor, ccIV)
}
if error != nil {
error.memory = status.error()
}
return status == RDHStatus.Success
}
// MARK: - Single shot encryption Swift functions
public class func encrypt(algorithm: RDHAlgorithm, usingOptions options: [Option]?, withKey key: NSData, initialisationVector: NSData?, dataIn: NSData) -> (dataOut: NSData?, error: NSError?) {
return cryptOperation(Operation.Encrypt, usingAlgorithm: algorithm, options: options, withKey: key, initialisationVector: initialisationVector, dataIn: dataIn)
}
public class func decrypt(algorithm: RDHAlgorithm, usingOptions options: [Option]?, withKey key: NSData, initialisationVector: NSData?, dataIn: NSData) -> (dataOut: NSData?, error: NSError?) {
return cryptOperation(Operation.Decrypt, usingAlgorithm: algorithm, options: options, withKey: key, initialisationVector: initialisationVector, dataIn: dataIn)
}
/// Root Swift crypt function
private class func cryptOperation(operation: Operation, usingAlgorithm algorithm: RDHAlgorithm, options: [Option]?, withKey key: NSData, initialisationVector: NSData?, dataIn: NSData) -> (dataOut: NSData?, error: NSError?) {
let ccOptions = Option.CCValue(options)
var resultantError: NSError?
let resultantData = cryptOperation(operation.cValue, usingAlgorithm: algorithm.toRaw(), options: ccOptions, withKey: key, initialisationVector: initialisationVector, dataIn: dataIn, error: &resultantError)
return (dataOut: resultantData, error: resultantError)
}
// MARK: - Single shot encryption Objective-C methods
/// Marked as internal for Swift as there is a Swift specific function. @returns the encrypted data, if this is nil then error is set.
@objc class func encrypt(algorithm: CCAlgorithm, usingOptions options: CCOptions, key: NSData, initialisationVector: NSData?, dataIn: NSData, error: NSErrorPointer = nil) -> NSData? {
return cryptOperation(Operation.Encrypt.cValue, usingAlgorithm: algorithm, options: options, withKey: key, initialisationVector: initialisationVector, dataIn: dataIn, error: error)
}
/// Marked as internal for Swift as there is a Swift specific function. @returns the decrypted data, if this is nil then error is set.
@objc class func decrypt(algorithm: CCAlgorithm, usingOptions options: CCOptions, key: NSData, initialisationVector: NSData?, dataIn: NSData, error: NSErrorPointer = nil) -> NSData? {
return cryptOperation(Operation.Decrypt.cValue, usingAlgorithm: algorithm, options: options, withKey: key, initialisationVector: initialisationVector, dataIn: dataIn, error: error)
}
/// Exposed as the root function - this matches the API of the C CCCrypt function. Marked as internal for Swift as there is a Swift specific function. @returns the out data, if this is nil then error is set.
@objc class func cryptOperation(operation: CCOperation, usingAlgorithm algorithm: CCAlgorithm, options: CCOptions, withKey key: NSData, initialisationVector: NSData?, dataIn: NSData, error: NSErrorPointer = nil) -> NSData? {
// Key
let ccKey = key.bytes;
let ccKeyLength = UInt(key.length);
// IV
let ccIV = (initialisationVector != nil) ? initialisationVector!.bytes : nil
// Data in
let ccDataIn = dataIn.bytes
let ccDataInLength = UInt(dataIn.length)
// Data out
let dataOutAvailable = ccDataInLength + algorithm.blockSize
var dataOut: NSMutableData? = NSMutableData(length: Int(dataOutAvailable))
var dataOutMoved: UInt = 0
// Pointer to data out - we can explicitly unwrap as we just created it above
var ccDataOut = dataOut!.mutableBytes
// Perform the cryptor operation
let (status, success, resultantError) = cryptoBlockReturningData {
let intStatus = CCCrypt(operation, algorithm, options, ccKey, ccKeyLength, ccIV, ccDataIn, ccDataInLength, ccDataOut, dataOutAvailable, &dataOutMoved)
return (intStatus, dataOut, dataOutMoved)
}
if (error != nil) {
error.memory = resultantError
}
if success {
// Nothing to do
} else if status == RDHStatus.BufferTooSmall {
// cryptoBlockReturningData with returned size
// Cleanup sets the needed size
// Perform the cryptor operation
let (_, repeatedSuccess, repeatedResultantError) = cryptoBlockReturningData {
let intStatus = CCCrypt(operation, algorithm, options, ccKey, ccKeyLength, ccIV, ccDataIn, ccDataInLength, ccDataOut, dataOutMoved, &dataOutMoved)
return (intStatus, dataOut, dataOutMoved)
}
if (error != nil) {
error.memory = repeatedResultantError
}
if (!repeatedSuccess) {
// Error - zero out data
dataOut!.length = 0
dataOut!.setData(NSData())
dataOut = nil
}
} else {
// Error
dataOut = nil
}
return dataOut
}
}
/// Closure that can return and clean up the data
private func cryptoBlockReturningData(block: () -> (CCStatus, NSMutableData?, UInt)) -> (status: RDHStatus, success: Bool, error: NSError?) {
let (intStatus, dataOut, dataOutMoved) = block()
let status = RDHStatus.fromInt(intStatus)
let (resultSuccess, resultantError) = cleanUpOutData(dataOut, movedOutLength: dataOutMoved, forResultStatus: status)
return (status, resultSuccess, resultantError)
}
| mit | 21730cf26c53034d87d9daa982ed2d56 | 38.726316 | 238 | 0.616278 | 5.43543 | false | false | false | false |
DanielSmith1239/KosherSwift | KosherSwift/Core/Solar/KSGeoLocation.swift | 1 | 10170 | //
// Created by Daniel Smith on 3/9/16.
// Copyright (c) 2016 Dani Smith. All rights reserved.
//
import Foundation
public class GeoLocation
{
public var longitude : Double = 0
public var locationName : String?
public var latitude : Double = 0
public var altitude : Double = 0
public var timeZone : NSTimeZone?
let trig = trigonometry()
public init(name: String, latitude: Double, longitude: Double, elevation: Double, timeZone: NSTimeZone)
{
self.locationName = name
self.longitude = longitude
self.latitude = latitude
self.altitude = elevation
self.timeZone = timeZone
}
convenience public init(latitude: Double, longitude: Double, timeZone: NSTimeZone)
{
self.init(name: "Unspecified Location", latitude: latitude, longitude: longitude, elevation: 0, timeZone: timeZone)
}
convenience public init(latitude: Double, longitude: Double, elevation: Double, timezone: NSTimeZone)
{
self.init(name: "Unspecified Location", latitude: latitude, longitude: longitude, elevation: elevation, timeZone: timezone)
}
convenience public init(name: String, latitude: Double, longitude: Double, timeZone: NSTimeZone)
{
self.init(name: name, latitude: latitude, longitude: longitude, elevation: 0, timeZone: timeZone)
}
convenience public init()
{
self.init(name: "Greenwich, England", latitude: 0, longitude: 51.4772, timeZone: NSTimeZone(abbreviation: "GMT")!)
}
public func setLatitudeWithDegrees(_degrees: Int, andMinutes _minutes: Int, andSeconds _seconds: Double, inDirection _direction: String)
{
var tempLat: Double = Double(_degrees) + ((Double(_minutes) + (_seconds / 60.0)) / 60.0)
if tempLat > 90 || tempLat < 0
{
fatalError("KosherSwift Error: Latitude must be between 0 and 90. USe direction of S instead of negative.")
}
if (_direction == "S")
{
tempLat = tempLat - 1
}
else if (_direction != "N")
{
fatalError("KosherSwift Error: Latitude direction must be N or S.")
}
latitude = tempLat
}
public func setLongitudeWithDegrees(_degrees: Int, andMinutes _minutes: Int, andSeconds _seconds: Double, inDirection _direction: String) throws
{
var longTemp: Double = Double(_degrees) + ((Double(_minutes) + (_seconds / 60.0)) / 60.0)
if longTemp > 180 || longTemp < 0
{
fatalError("KosherSwift Error: Longitude must be between 0 and 180. Use the direction of W instead of negative.")
}
if (_direction == "W")
{
longTemp = longTemp - 1
}
else if !(_direction == "E")
{
fatalError("KosherSwift Error: Longitude direction must be E or W.")
}
longitude = longTemp
}
let kMillisecondsInAMinute = 60 * 1000
/**
* A method that will return the location's local mean time
* offset in milliseconds from local
* <a href="http://en.wikipedia.org/wiki/Standard_time"> standard time</a>.
* The globe is split into 360°, with
* 15° per hour of the day. For a local that is at a longitude that
* is evenly divisible by 15 (longitude % 15 == 0), at solar noon (with
* adjustment for the
* <a href="http://en.wikipedia.org/wiki/Equation_of_time">equation of time</a>) the sun
* should be directly overhead, so a user who is 1° west of this will have noon at 4
* minutes after standard time noon, and conversely, a user
* who is 1° east of the 15° longitude will have noon at 11:56 AM. Lakewood, N.J.,
* whose longitude is -74.2094, is 0.7906 away from the closest multiple of 15 at -75°.
* This is multiplied by 4 to yield 3 minutes and 10 seconds earlier than standard time.
* The offset returned does not account for the
* <a href="http://en.wikipedia.org/wiki/Daylight_saving_time">Daylight saving time</a>
* offset since this class is unaware of dates.
*
* - returns: the offset in milliseconds not accounting for Daylight saving time. A positive
* value will be returned East of the 15° timezone line, and a negative value West of i
*/
public func localMeanTimeOffset() -> Int
{
return Int(longitude) * 4 * kMillisecondsInAMinute - (timeZone!.secondsFromGMT * 1000)
}
public func getGeodesicInitialBearingForLocation(location: GeoLocation) -> Double
{
return vincentyFormulaForLocation(location, withBearing: kInitialBearing)!
}
public func getGeodesicFinalBearingForLocation(location: GeoLocation) -> Double
{
return vincentyFormulaForLocation(location, withBearing: kFinalBearing)!
}
public func getGeodesicDistanceForLocation(location: GeoLocation) -> Double
{
return vincentyFormulaForLocation(location, withBearing: kDistance)!
}
/**
* Calculate <a
* href="http://en.wikipedia.org/wiki/Great-circle_distance">geodesic
* distance</a> in Meters between this Object and a second Object passed to
* this method using <a
* href="http://en.wikipedia.org/wiki/Thaddeus_Vincenty">Thaddeus Vincenty's</a>
* inverse formula See T Vincenty, "<a
* href="http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf">Direct and Inverse
* Solutions of Geodesics on the Ellipsoid with application of nested
* equations</a>", Survey Review, vol XXII no 176, 1975.
*
* - parameter location: the destination location
* - parameter formula: This formula calculates initial bearing InitialBearing, final bearing ({@link #FINAL_BEARING}) and distance ({@link #DISTANCE}).
*
* - returns The value of the formula with the location.
*/
public func vincentyFormulaForLocation(location: GeoLocation, withBearing formula: Int) -> Double?
{
let a: Double = 6378137
let b: Double = 6356752.3142
let f: Double = 1 / 298.257223563; // WGS-84 ellipsiod
let L = trig.toRadians(location.longitude - longitude)
let U1 = atan((1 - f) * tan(trig.toRadians(latitude)))
let U2 = atan((1 - f) * tan(trig.toRadians(location.latitude)))
let sinU1 = sin(U1)
let cosU1 = cos(U1)
let sinU2 = sin(U2)
let cosU2 = cos(U2)
var lambda = L
var lambdaP = 2.0 * M_PI
var iterLimit: Double = 20
var sinLambda: Double = 0
var cosLambda: Double = 0
var sinSigma: Double = 0
var cosSigma: Double = 0
var sigma: Double = 0
var sinAlpha: Double = 0
var cosSqAlpha: Double = 0
var cos2SigmaM: Double = 0
var C: Double = 0
while fabs(lambda - lambdaP) > 1e-12 && iterLimit > 0
{
sinLambda = sin(lambda)
cosLambda = cos(lambda)
sinSigma = sqrt((cosU2 * sinLambda) * (cosU2 * sinLambda) + (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) * (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda))
if sinSigma == 0
{
return 0;
} // co-incident points
cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda
sigma = atan2(sinSigma, cosSigma)
sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma
cosSqAlpha = 1 - sinAlpha * sinAlpha
cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha
//Check if this is correct
if isnan(cos2SigmaM){
cos2SigmaM = 0; // equatorial line: cosSqAlpha=0 (ß6)
}
C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha))
lambdaP = lambda
lambda = L + (1 - C) * f * sinAlpha * (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)))
iterLimit-=1
}
if iterLimit == 0
{
return nil // formula failed to converge
}
let uSq: Double = cosSqAlpha * (a * a - b * b) / (b * b)
let A: Double = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)))
let B: Double = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)))
let deltaSigma: Double = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) - B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM)))
let distance: Double = b * A * (sigma - deltaSigma)
// initial bearing
let fwdAz: Double = trig.toDegrees(atan2(cosU2 * sinLambda, cosU1 * sinU2 - sinU1 * cosU2 * cosLambda))
// final bearing
let revAz: Double = trig.toDegrees(atan2(cosU1 * sinLambda, -sinU1 * cosU2 + cosU1 * sinU2 * cosLambda))
if formula == kDistance
{
return distance
}
else if formula == kInitialBearing
{
return fwdAz
}
else if formula == kFinalBearing
{
return revAz
}
else
{
return nil
}
}
public func getRhumbLineBearingForLocation(location: GeoLocation) -> Double
{
var dLon: Double = trig.toRadians(location.longitude - longitude)
let dPhi: Double = log(tan(trig.toRadians(location.latitude) / 2 + M_PI / 4) / tan(trig.toRadians(latitude) / 2 + M_PI / 4))
if fabs(dLon) > M_PI{
dLon = dLon > 0 ? -(2 * M_PI - dLon) : (2 * M_PI + dLon)
}
return trig.toDegrees(atan2(dLon, dPhi))
}
public func getRhumbLineDistanceForLocation(location: GeoLocation) -> Double
{
let R: Double = 6371; // earth's mean radius in km
let dLat: Double = trig.toRadians(location.latitude - latitude)
var dLon: Double = trig.toRadians(fabs(location.longitude - longitude))
let dPhi: Double = log(tan(trig.toRadians(location.longitude) / 2 + M_PI / 4) / tan(trig.toRadians(latitude) / 2 + M_PI / 4))
let q: Double = (fabs(dLat) > 1e-10) ? dLat / dPhi : cos(trig.toRadians(latitude))
// if dLon over 180° take shorter rhumb across 180∞ meridian:
if dLon > M_PI
{
dLon = 2 * M_PI - dLon
}
let d: Double = sqrt(dLat * dLat + q * q * dLon * dLon)
return d * R
}
public func description() -> String
{
return String(format:"<GeoLocation:> ----\nName: %@ \nLatitude: %f, \nLongitude: %f \nAltitude: %f", locationName!, latitude, longitude, altitude)
}
} | lgpl-3.0 | d57a4cb3e28e2f1c66f77791eccabd1f | 37.078652 | 206 | 0.627976 | 3.777778 | false | false | false | false |
PoissonBallon/EasyRealm | EasyRealm/Classes/Variable.swift | 1 | 1243 | //
// ER_Variable.swift
// Pods
//
// Created by Allan Vialatte on 05/03/2017.
//
import Foundation
import Realm
import RealmSwift
extension EasyRealm where T: Object {
public var isManaged: Bool {
return (self.base.realm != nil)
}
public var managed: T? {
guard let realm = try? Realm(), let key = T.primaryKey() else { return nil }
let object = realm.object(ofType: T.self, forPrimaryKey: self.base.value(forKey: key))
return object
}
public var unmanaged:T {
return self.base.easyDetached()
}
func detached() -> T {
return self.base.easyDetached()
}
}
fileprivate extension Object {
fileprivate func easyDetached() -> Self {
let detached = type(of: self).init()
for property in objectSchema.properties {
guard let value = value(forKey: property.name) else { continue }
if let detachable = value as? Object {
detached.setValue(detachable.easyDetached(), forKey: property.name)
} else if let detachable = value as? EasyRealmList {
detached.setValue(detachable.children().compactMap { $0.easyDetached() },forKey: property.name)
} else {
detached.setValue(value, forKey: property.name)
}
}
return detached
}
}
| mit | f47c86a4a56df6463d32428a4939ddb3 | 24.367347 | 103 | 0.658085 | 3.860248 | false | false | false | false |
hilenium/HISwiftExtensions | Pod/Classes/String.swift | 1 | 4461 | //
// Extensions.swift
// Hilenium
//
// Created by Matthew on 15/02/2015.
// Copyright (c) 2015 PHilenium Pty Ltd. All rights reserved.
//
import UIKit
public extension String {
/**
Changes underscores to camelCase
- Returns: String with all instances of `_char` replaced with `Char`
*/
public var underscoreToCamelCase: String {
let items = self.components(separatedBy: "_")
var camelCase = ""
items.enumerated().forEach {
camelCase += 0 == $0 ? $1 : $1.capitalized
}
return camelCase
}
/**
Sets the first character in a string to uppercase.
- Returns: String
*/
public var uppercaseFirst: String {
let first = String(characters.prefix(1)).capitalized
let other = String(characters.dropFirst())
return first + other
}
/**
Removes white spaces from a string.
- Returns: String
*/
public var trim: String {
return self.trimmingCharacters(in: CharacterSet.whitespaces)
}
/**
Truncates a string and appends trailing characters if the number of characters in the string exceeds truncated length
- Parameter length: int the number of characters from the start where the trucation occurs
- Parameter trailing: string to append to the end of the turncation (if required). Defaults to `...`
- Returns: String
*/
public func truncate(_ length: Int, trailing: String? = "...") -> String {
return self.characters.count > length
? self.substring(to: self.characters.index(self.startIndex, offsetBy: length)) + (trailing)!
: self
}
/**
Url encodes a string
*/
public var urlEncode: String {
return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
}
/**
Splits a string into an array by the given delimiter
- Parameter delimiter: string to use as the splitter
- Returns: [String]
*/
public func split(_ delimiter: String) -> [String] {
return self.components(separatedBy: delimiter)
}
/**
Determines if a string is a valid email address
- Returns: Bool
*/
public var isValidEmail:Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: self)
}
/**
Counts the number of charaters in a string
- Returns: Int - the number of characters
*/
public var count:Int { return self.characters.count }
/**
Converts a string to NSDate if possible
- Parameter format: the date format. The default is ISO `yyyy-MM-dd'T'HH:mm:ssZZZZ`
- Returns: NSDate?
*/
public func toDate(_ format:String = "yyyy-MM-dd'T'HH:mm:ssZZZZ") -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.date(from: self)
}
public func boldStrongTags(_ size:CGFloat, color:UIColor = UIColor.black) -> NSAttributedString {
let attributes = [NSFontAttributeName : UIFont.systemFont(ofSize: size), NSForegroundColorAttributeName : color]
let attributed = NSMutableAttributedString(string: self)
return attributed.replaceHTMLTag("strong", withAttributes: attributes)
}
/**
Subscript a string e.g. "foo"[0] == "f"
- Returns: Character
*/
public subscript (i: Int) -> Character {
return Array(self.characters)[i]
}
/**
Removes all html from a string
- Returns: String?
*/
public var stripHTML: String? {
let encodedData = self.data(using: String.Encoding.utf8)!
let attributedOptions:[String: AnyObject] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType as AnyObject,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8 as AnyObject
]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
return attributedString.string
}
catch {
return nil
}
}
}
| mit | 7c254bcab1ae6e84ffd741a8777db84b | 26.537037 | 129 | 0.599193 | 4.940199 | false | false | false | false |
krimpedance/KRActivityIndicator | KRActivityIndicatorView/Classes/KRActivityIndicatorView.swift | 2 | 7569 | //
// KRActivityIndicatorView.swift
// KRActivityIndicatorView
//
// Copyright © 2016 Krimpedance. All rights reserved.
//
import UIKit
/// KRActivityIndicatorView is a simple and customizable activity indicator
@IBDesignable
public final class KRActivityIndicatorView: UIView {
private let animationKey = "KRActivityIndicatorViewAnimationKey"
private var animationLayer = CALayer()
/// Activity indicator's head color (read-only).
/// You can set head color from IB.
/// If you want to change color from code, use colors property.
@IBInspectable public fileprivate(set) var headColor: UIColor {
get { return colors.first ?? .black }
set { colors = [newValue, tailColor] }
}
/// Activity indicator's tail color (read-only).
/// You can set tail color from IB.
/// If you want to change color from code, use colors property.
@IBInspectable public fileprivate(set) var tailColor: UIColor {
get { return colors.last ?? .black }
set { colors = [headColor, newValue] }
}
/// Number of dots
@IBInspectable public var numberOfDots: Int = 8 {
didSet { drawIndicatorPath() }
}
// Duration for one rotation
@IBInspectable public var duration: Double = 1.0 {
didSet {
guard isAnimating else { return }
stopAnimating()
startAnimating()
}
}
/// Animation of activity indicator when it's shown.
@IBInspectable public var animating: Bool = true {
didSet { animating ? startAnimating() : stopAnimating() }
}
/// set `true` to `isHidden` when call `stopAnimating()`
@IBInspectable public var hidesWhenStopped: Bool = false {
didSet { animationLayer.isHidden = !isAnimating && hidesWhenStopped }
}
/// Activity indicator gradient colors.
public var colors: [UIColor] = [.black, .lightGray] {
didSet { drawIndicatorPath() }
}
/// Whether view performs animation
public var isAnimating: Bool {
return animationLayer.animation(forKey: animationKey) != nil
}
// Initializer ----------
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
layer.addSublayer(animationLayer)
}
public override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
layer.addSublayer(animationLayer)
}
/// Initializer
public convenience init() {
self.init(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
}
/// Initializer with colors
///
/// - Parameter colors: Activity indicator gradient colors.
public convenience init(colors: [UIColor]) {
self.init(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
self.colors = colors
}
// Deprecated ----------
/// Activity indicator color style.
@available(*, deprecated)
public var style = KRActivityIndicatorViewStyle.gradationColor(head: .black, tail: .lightGray) {
didSet { colors = [style.headColor, style.tailColor] }
}
/// Initialize with style.
/// - Parameter style: Activity indicator default color use of KRActivityIndicatorViewStyle
@available(*, deprecated)
public convenience init(style: KRActivityIndicatorViewStyle) {
self.init(colors: [style.headColor, style.tailColor])
}
// Lyfecycle ----------
public override func layoutSubviews() {
super.layoutSubviews()
viewResized()
}
}
// MARK: - Private actions ------------
private extension KRActivityIndicatorView {
func viewResized() {
animationLayer.frame = layer.bounds
animationLayer.isHidden = !isAnimating && hidesWhenStopped
drawIndicatorPath()
if animating { startAnimating() }
}
func drawIndicatorPath() {
animationLayer.sublayers?.forEach { $0.removeFromSuperlayer() }
let width = Double(min(animationLayer.bounds.width, animationLayer.bounds.height))
// 各ドットの直径を求めるためのベースとなる比率
let diff = 0.6 / Double(numberOfDots-1)
let baseRatio = 100 / (1.8 * Double(numberOfDots) - Double(numberOfDots * (numberOfDots - 1)) * diff)
// ベースとなる円の直径(レイヤー内にドットが収まるように調整する)
var diameter = width
while true {
let circumference = diameter * Double.pi
let dotDiameter = baseRatio * 0.9 * circumference / 100
let space = width - diameter - dotDiameter
if space > 0 { break }
diameter -= 2
}
let colors = getGradientColors(dividedIn: numberOfDots)
let circumference = diameter * Double.pi
let spaceRatio = 50 / Double(numberOfDots) / 100
var degree = Double(20) // 全体を 20° 傾ける
(0..<numberOfDots).forEach {
let number = Double($0)
let ratio = (0.9 - diff * number) * baseRatio / 100
let dotDiameter = circumference * ratio
let rect = CGRect(
x: (width - dotDiameter) / 2,
y: (width - diameter - dotDiameter) / 2,
width: dotDiameter,
height: dotDiameter
)
if number != 0 {
let preRatio = (0.9 - diff * (number - 1)) * baseRatio / 100
let arc = (preRatio / 2 + spaceRatio + ratio / 2) * circumference
degree += 360 * arc / circumference
}
let pathLayer = CAShapeLayer()
pathLayer.frame.size = CGSize(width: width, height: width)
pathLayer.position = animationLayer.position
pathLayer.fillColor = colors[$0].cgColor
pathLayer.lineWidth = 0
pathLayer.path = UIBezierPath(ovalIn: rect).cgPath
pathLayer.setAffineTransform(CGAffineTransform(rotationAngle: CGFloat(-degree) * CGFloat.pi / 180))
animationLayer.addSublayer(pathLayer)
}
}
func getGradientColors(dividedIn num: Int) -> [UIColor] {
let gradient = CAGradientLayer()
gradient.frame = CGRect(x: 0, y: 0, width: 2, height: (num-1) * 10 + 1)
switch colors.count {
case 0: gradient.colors = [UIColor.black.cgColor, UIColor.lightGray.cgColor]
case 1: gradient.colors = [colors.first!.cgColor, colors.first!.cgColor]
default: gradient.colors = colors.map { $0.cgColor }
}
return (0..<num).map {
let point = CGPoint(x: 1, y: 10*CGFloat($0))
return gradient.color(point: point)
}
}
}
// MARK: - Public actions ------------------
public extension KRActivityIndicatorView {
/// Start animating.
func startAnimating() {
if animationLayer.animation(forKey: animationKey) != nil { return }
let animation = CABasicAnimation(keyPath: "transform.rotation")
animation.fromValue = 0
animation.toValue = Double.pi * 2
animation.duration = duration
animation.timingFunction = CAMediaTimingFunction(name: .linear)
animation.isRemovedOnCompletion = false
animation.repeatCount = Float(NSIntegerMax)
animation.fillMode = .forwards
animation.autoreverses = false
animationLayer.isHidden = false
animationLayer.add(animation, forKey: animationKey)
}
/// Stop animating.
func stopAnimating() {
animationLayer.removeAllAnimations()
animationLayer.isHidden = hidesWhenStopped
}
}
| mit | 790821c09f43b1503f6e632734ddf967 | 32.714932 | 111 | 0.619514 | 4.71284 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.