repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
moromi/StringValidator | Sources/LengthValidator.swift | 1 | 985 | //
// LengthValidator.swift
//
// Created by Takahiro Ooishi
// Copyright (c) 2016 moromi. All rights reserved.
// Released under the MIT license.
//
import Foundation
public struct LengthValidator: Validator {
private let range: CountableClosedRange<Int>
private let ignoreWhitespaces: Bool
private let allowBlank: Bool
private let allowNil: Bool
public init(range: CountableClosedRange<Int>, ignoreWhitespaces: Bool = false, allowBlank: Bool = false, allowNil: Bool = false) {
self.range = range
self.ignoreWhitespaces = ignoreWhitespaces
self.allowBlank = allowBlank
self.allowNil = allowNil
}
public func validate(_ string: String?) -> Bool {
if allowNil && string == nil { return true }
guard var string = string else { return false }
if allowBlank && string.isEmpty { return true }
if ignoreWhitespaces {
string = string.trimmingCharacters(in: .whitespaces)
}
return range.contains(string.count)
}
}
| mit |
roddi/FURRExtensions | Sources/FURRExtensionsTests/ResultExtensionTests.swift | 1 | 3213 | //
// ResultExtensionTests.swift
//
//
// Created by Ruotger Deecke on 26.11.20.
// Copyright © 2015 Deecke,Roddi. All rights reserved.
//
// TL/DR; BSD 2-clause license
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import XCTest
import FURRTestExtensions
@testable import FURRExtensions
enum MockError: Error {
case mockError
}
typealias MockResult = Result<Int, MockError>
typealias MockArrayResult = Result<[Int], MockError>
class ResultExtensionTests: XCTestCase {
func testSuccess() {
// given
let result = MockResult.success(1)
// then
XCTAssert(result.isSuccess)
XCTAssertEqual(result.successObject(), 1)
XCTAssertNil(result.failureObject())
XCTAssertSuccess(result)
XCTAssertSuccessResultEqual(result, 1)
}
func testFailure() {
// given
let result = MockResult.failure(.mockError)
// then
XCTAssert(!result.isSuccess)
XCTAssertEqual(result.failureObject(), .mockError)
XCTAssertNil(result.successObject())
XCTAssertFailure(result)
XCTAssertFailureResultEqual(result, .mockError)
}
func testArrayOfSuccesses() {
// given
let results = [MockResult.success(1), MockResult.success(2), MockResult.success(3)]
// then
XCTAssertSuccessResultEqual(results, [1,2,3])
}
func testArrayOfFailures() {
// given
let results = [MockResult.failure(.mockError),MockResult.failure(.mockError)]
// then
XCTAssertFailureResultEqual(results, [.mockError, .mockError])
}
func testSuccessArray() {
// given
let result = MockArrayResult.success([1,2,3])
// then
XCTAssertSuccessResultEqual(result, [1,2,3])
}
func testArrayFailure() {
// given
let result = MockArrayResult.failure(.mockError)
// then
XCTAssertFailureResultEqual(result, .mockError)
}
}
| bsd-2-clause |
gvsucis/mobile-app-dev-book | iOS/ch13/TraxyApp/TraxyApp/JournalEntryConfirmationViewController.swift | 5 | 6489 | //
// JournalEntryConfirmationViewController.swift
// TraxyApp
//
// Created by Jonathan Engelsma on 4/11/17.
// Copyright © 2017 Jonathan Engelsma. All rights reserved.
//
import UIKit
import Eureka
protocol AddJournalEntryDelegate : class {
func save(entry: JournalEntry)
}
var previewImage : UIImage?
class JournalEntryConfirmationViewController: FormViewController {
var imageToConfirm : UIImage?
weak var delegate : AddJournalEntryDelegate?
var type : EntryType?
var entry : JournalEntry?
var journal : Journal!
override func viewDidLoad() {
super.viewDidLoad()
previewImage = imageToConfirm
let textRowValidationUpdate : (TextRow.Cell, TextRow) -> () = { cell, row in
if !row.isValid {
cell.titleLabel?.textColor = .red
} else {
cell.titleLabel?.textColor = .black
}
}
TextRow.defaultCellUpdate = textRowValidationUpdate
TextRow.defaultOnRowValidationChanged = textRowValidationUpdate
let dateRowValidationUpdate : (DateRow.Cell, DateRow) -> () = { cell, row in
if !row.isValid {
cell.textLabel?.textColor = .red
} else {
cell.textLabel?.textColor = .black
}
}
DateRow.defaultCellUpdate = dateRowValidationUpdate
DateRow.defaultOnRowValidationChanged = dateRowValidationUpdate
let labelRowValidationUpdate : (LabelRow.Cell, LabelRow) -> () = { cell, row in
if !row.isValid {
cell.textLabel?.textColor = .red
} else {
cell.textLabel?.textColor = .black
}
}
LabelRow.defaultCellUpdate = labelRowValidationUpdate
LabelRow.defaultOnRowValidationChanged = labelRowValidationUpdate
var textEntryLabel = "Enter caption"
if self.type == .text {
textEntryLabel = "Enter text entry"
self.navigationItem.title = "Text Entry"
}
var caption : String = ""
var date : Date = self.journal.startDate!
if let e = self.entry {
caption = e.caption!
date = e.date!
} else {
self.entry = JournalEntry(key: nil, type: self.type, caption: caption,
url: "", thumbnailUrl: "", date: date, lat: 0.0, lng: 0.0)
}
form = Section() {
$0.tag = "FirstSection"
if self.type != .text && self.type != .audio {
$0.header = HeaderFooterView<MediaPreviewView>(.class)
}
}
<<< TextAreaRow(textEntryLabel){ row in
row.placeholder = textEntryLabel
row.value = caption
row.tag = "CaptionTag"
row.add(rule: RuleRequired())
}
+++ Section("Date and Location Recorded")
<<< DateTimeInlineRow(){ row in
row.title = "Date"
row.value = date
row.tag = "DateTag"
row.maximumDate = self.journal.endDate
row.minimumDate = self.journal.startDate
row.dateFormatter?.dateStyle = .medium
row.dateFormatter?.timeStyle = .short
row.add(rule: RuleRequired())
}
<<< LabelRow () { row in
row.title = "Location"
row.value = "Tap for current"
row.tag = "LocTag"
var rules = RuleSet<String>()
rules.add(rule: RuleClosure(closure: { (loc) -> ValidationError? in
if loc == "Tap to search" {
return ValidationError(msg: "You must select a location")
} else {
return nil
}
}))
row.add(ruleSet:rules)
}.onCellSelection { cell, row in
print("TODO: will finish this next chapter!")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cancelButtonPressed(_ sender: UIBarButtonItem) {
_ = self.navigationController?.popViewController(animated: true)
}
@IBAction func saveButtonPressed(_ sender: UIBarButtonItem) {
if let del = self.delegate {
let (caption,date,_) = self.extractFormValues()
if var e = self.entry {
e.caption = caption
e.date = date
del.save(entry: e)
}
}
_ = self.navigationController?.popViewController(animated: true)
}
func extractFormValues() -> (String, Date, String)
{
let captionRow: TextAreaRow! = form.rowBy(tag: "CaptionTag")
//let locRow: LabelRow! = form.rowBy(tag: "LocTag")
let dateRow : DateTimeInlineRow! = form.rowBy(tag: "DateTag")
let locationRow : LabelRow! = form.rowBy(tag: "LocTag")
let caption = captionRow.value! as String
//let location = locRow.value! as String
let date = dateRow.value! as Date
let loc = locationRow.value! as String
return (caption,date,loc)
}
class MediaPreviewView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
// size image view to a third of available vertical space.
let screenSize: CGRect = UIScreen.main.bounds
let width = screenSize.width
let height = screenSize.height / 3.0
var image : UIImage
if let img = previewImage {
image = img
} else {
image = UIImage()
}
let imageView = UIImageView(image: image)
imageView.contentMode = .scaleAspectFill
imageView.frame = CGRect(x: 0, y: 0, width: width, height: height)
self.frame = CGRect(x: 0, y: 0, width: width, height: height)
self.clipsToBounds = true
self.addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
| gpl-3.0 |
roecrew/AudioKit | AudioKit/Common/Playgrounds/Filters.playground/Pages/Band Pass Filter.xcplaygroundpage/Contents.swift | 1 | 1887 | //: ## Band Pass Filter
//: Band-pass filters allow audio above a specified frequency range and
//: bandwidth to pass through to an output. The center frequency is the starting point
//: from where the frequency limit is set. Adjusting the bandwidth sets how far out
//: above and below the center frequency the frequency band should be.
//: Anything above that band should pass through.
import XCPlayground
import AudioKit
let file = try AKAudioFile(readFileName: filtersPlaygroundFiles[0],
baseDir: .Resources)
let player = try AKAudioPlayer(file: file)
player.looping = true
//: Next, we'll connect the audio sources to a band pass filter
var filter = AKBandPassFilter(player)
filter.centerFrequency = 5000 // Hz
filter.bandwidth = 600 // Cents
AudioKit.output = filter
AudioKit.start()
player.play()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
override func setup() {
addTitle("Band Pass Filter")
addSubview(AKResourcesAudioFileLoaderView(
player: player,
filenames: filtersPlaygroundFiles))
addSubview(AKBypassButton(node: filter))
addSubview(AKPropertySlider(
property: "Center Frequency",
format: "%0.1f Hz",
value: filter.centerFrequency, minimum: 20, maximum: 22050,
color: AKColor.greenColor()
) { sliderValue in
filter.centerFrequency = sliderValue
})
addSubview(AKPropertySlider(
property: "Bandwidth",
format: "%0.1f Hz",
value: filter.bandwidth, minimum: 100, maximum: 1200,
color: AKColor.redColor()
) { sliderValue in
filter.bandwidth = sliderValue
})
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
| mit |
shamugia/WatchKit-TicTacToe-Game | Tic-Tac-Toe WatchKit Extension/ResultInterfaceController.swift | 1 | 1358 | //
// ResultInterfaceController.swift
// Tic-Tac-Toe
//
// Created by George Shamugia on 26/11/2014.
// Copyright (c) 2014 George Shamugia. All rights reserved.
//
import WatchKit
import Foundation
class ResultInterfaceController: WKInterfaceController {
@IBOutlet weak var background:WKInterfaceGroup!
@IBOutlet weak var resultLabel:WKInterfaceLabel!
@IBOutlet weak var winStatsLabel:WKInterfaceLabel!
@IBOutlet weak var lossStatsLabel:WKInterfaceLabel!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
if WKInterfaceDevice.currentDevice().screenBounds.size.width > 136 //42mm
{
background.setBackgroundImageNamed("42_boardbg")
}
else
{
background.setBackgroundImageNamed("38_boardbg")
}
if let displayData:[String:String] = context as? Dictionary
{
resultLabel.setText(displayData["winner"])
var win = displayData["win"]
var loss = displayData["loss"]
winStatsLabel.setText("Win: \(win!)")
lossStatsLabel.setText("Loss: \(loss!)")
}
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
super.didDeactivate()
}
}
| unlicense |
blstream/TOZ_iOS | TOZ_iOS/TabBarViewController.swift | 1 | 2327 | //
// TabBarViewController.swift
// TOZ_iOS
//
// Copyright © 2017 intive. All rights reserved.
//
import UIKit
final class TabBarViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(switchAccountTab), name: .backendAuthStateChanged, object: nil)
switchAccountTab()
}
@objc func switchAccountTab() {
// When user signs in/out remove last viewcontroller(s) from viewControllers
// so the correct one(s) can be added later
if self.viewControllers?.count == 5 {
self.viewControllers?.remove(at: 4)
self.viewControllers?.remove(at: 3)
} else if self.viewControllers?.count == 4 {
self.viewControllers?.remove(at: 3)
}
var viewControllers: [UIViewController] = self.viewControllers!
let accountStoryboard: UIStoryboard = UIStoryboard(name: "Account", bundle: nil)
let accountTabBarItemIcon = UITabBarItem(title: "KONTO", image: UIImage(named: "tab-bar-user.png"), selectedImage: UIImage(named: "tab-bar-user.png"))
var targetNavigationController: UIViewController
let calendarStoryboard: UIStoryboard = UIStoryboard(name: "Calendar", bundle: nil)
let calendarTabBarItemIcon = UITabBarItem(title: "GRAFIK", image: UIImage(named: "tab-bar-cal.png"), selectedImage: UIImage(named: "tab-bar-cal.png"))
let calendarNavigationController: UIViewController
if BackendAuth.shared.token != nil {
targetNavigationController = accountStoryboard.instantiateViewController(withIdentifier: "ChangePasswordNavigationController")
calendarNavigationController = calendarStoryboard.instantiateViewController(withIdentifier: "CalendarNavigationController")
calendarNavigationController.tabBarItem = calendarTabBarItemIcon
viewControllers.append(calendarNavigationController)
} else {
targetNavigationController = accountStoryboard.instantiateViewController(withIdentifier: "LoginNavigationController")
}
targetNavigationController.tabBarItem = accountTabBarItemIcon
viewControllers.append(targetNavigationController)
self.viewControllers = viewControllers
}
}
| apache-2.0 |
wordpress-mobile/AztecEditor-iOS | AztecTests/TextKit/UnsupportedHTMLTests.swift | 2 | 1684 | import XCTest
@testable import Aztec
// MARK: - UnsupportedHTMLTests
//
class UnsupportedHTMLTests: XCTestCase {
/// Verifies that a UnsupportedHTML Instance can get properly serialized back and forth
///
func testSnippetsGetProperlyEncodedAndDecoded() {
let unsupported = UnsupportedHTML(representations: [sampleRepresentation, sampleRepresentation])
let data = NSKeyedArchiver.archivedData(withRootObject: unsupported)
guard let restored = NSKeyedUnarchiver.unarchiveObject(with: data) as? UnsupportedHTML else {
XCTFail()
return
}
XCTAssert(restored.representations.count == 2)
for representation in restored.representations {
XCTAssert(representation == sampleRepresentation)
}
}
}
// MARK: - Helpers
//
private extension UnsupportedHTMLTests {
var sampleCSS: CSSAttribute {
return CSSAttribute(name: "text", value: "bold")
}
var sampleAttributes: [Attribute] {
return [
Attribute(name: "someBoolAttribute", value: .none),
Attribute(name: "someStringAttribute", value: .string("value")),
Attribute(type: .style, value: .inlineCss([self.sampleCSS]))
]
}
var sampleChildren: [Node] {
return [
TextNode(text: "Some Text"),
CommentNode(text: "Some Comment"),
]
}
var sampleElement: ElementNode {
return ElementNode(name: "Test", attributes: self.sampleAttributes, children: self.sampleChildren)
}
var sampleRepresentation: HTMLElementRepresentation {
return HTMLElementRepresentation(self.sampleElement)
}
}
| mpl-2.0 |
sschiau/swift | test/SILGen/read_accessor.swift | 6 | 9321 | // RUN: %target-swift-emit-silgen %s | %FileCheck %s
struct SimpleTest {
var stored: String
var readable: String {
// CHECK-LABEL: sil hidden [ossa] @$s13read_accessor10SimpleTestV8readableSSvr
// CHECK-SAME: : $@yield_once @convention(method) (@guaranteed SimpleTest) -> @yields @guaranteed String {
// CHECK: [[T0:%.*]] = struct_extract %0 : $SimpleTest, #SimpleTest.stored
// CHECK-NEXT: yield [[T0]] : $String, resume bb1, unwind bb2
// CHECK: bb1:
// CHECK-NEXT: [[RET:%.*]] = tuple ()
// CHECK-NEXT: return [[RET]] : $()
// CHECK: bb2:
// CHECK-NEXT: unwind
_read {
yield stored
}
}
// CHECK-LABEL: sil hidden [ossa] @$s13read_accessor10SimpleTestV3getSSyF
// CHECK: [[T0:%.*]] = begin_access [read] [unknown] %0
// CHECK-NEXT: [[SELF:%.*]] = load [copy] [[T0]] : $*SimpleTest
// CHECK-NEXT: end_access [[T0]]
// CHECK-NEXT: [[SELF_BORROW:%.*]] = begin_borrow [[SELF]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[READFN:%.*]] = function_ref @$s13read_accessor10SimpleTestV8readableSSvr : $@yield_once @convention(method) (@guaranteed SimpleTest) -> @yields @guaranteed String
// CHECK-NEXT: ([[VALUE:%.*]], [[TOKEN:%.*]]) = begin_apply [[READFN]]([[SELF_BORROW]])
// CHECK-NEXT: [[RET:%.*]] = copy_value [[VALUE]] : $String
// CHECK-NEXT: end_apply [[TOKEN]]
// CHECK-NEXT: end_borrow [[SELF_BORROW]]
// CHECK-NEXT: destroy_value [[SELF]]
// CHECK-NEXT: return [[RET]] : $String
mutating func get() -> String {
return readable
}
}
class GetterSynthesis {
var stored: String = "hello"
var readable: String {
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s13read_accessor15GetterSynthesisC8readableSSvg
// CHECK: [[READFN:%.*]] = function_ref @$s13read_accessor15GetterSynthesisC8readableSSvr
// CHECK-NEXT: ([[VALUE:%.*]], [[TOKEN:%.*]]) = begin_apply [[READFN]](%0)
// CHECK-NEXT: [[RET:%.*]] = copy_value [[VALUE]] : $String
// CHECK-NEXT: end_apply [[TOKEN]]
// CHECK-NEXT: return [[RET]] : $String
_read {
yield stored
}
}
}
func void() {}
struct TupleReader {
var stored: String
subscript(i: Int) -> String {
_read { yield stored }
}
func compute() -> String { return stored }
func index() -> Int { return 0 }
var readable: ((String, ()), String, ()) {
// CHECK-LABEL: sil hidden [ossa] @$s13read_accessor11TupleReaderV8readableSS_ytt_SSyttvr
// CHECK: debug_value %0
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[INDEXFN:%.*]] = function_ref @$s13read_accessor11TupleReaderV5indexSiyF
// CHECK-NEXT: [[INDEX:%.*]] = apply [[INDEXFN]](%0)
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[COMPUTEFN:%.*]] = function_ref @$s13read_accessor11TupleReaderV7computeSSyF
// CHECK-NEXT: [[COMPUTE:%.*]] = apply [[COMPUTEFN]](%0)
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[VOIDFN:%.*]] = function_ref @$s13read_accessor4voidyyF
// CHECK-NEXT: apply [[VOIDFN]]()
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[SUBREADFN:%.*]] = function_ref @$s13read_accessor11TupleReaderVySSSicir
// CHECK-NEXT: ([[SUBREAD:%.*]], [[SUBTOKEN:%.*]]) = begin_apply [[SUBREADFN]]([[INDEX]], %0)
// CHECK-NEXT: yield ([[SUBREAD]] : $String, [[COMPUTE]] : $String), resume bb1, unwind bb2
// CHECK: bb1:
// CHECK-NEXT: end_apply [[SUBTOKEN]]
// CHECK-NEXT: destroy_value [[COMPUTE]] : $String
// CHECK-NEXT: [[T0:%.*]] = tuple ()
// CHECK-NEXT: return [[T0]] : $()
// CHECK: bb2:
// Should this be an abort_apply?
// CHECK-NEXT: end_apply [[SUBTOKEN]]
// CHECK-NEXT: destroy_value [[COMPUTE]] : $String
// CHECK-NEXT: unwind
// CHECK-LABEL: } // end sil function '$s13read_accessor11TupleReaderV8readableSS_ytt_SSyttvr'
_read {
yield (((self[index()], ()), compute(), void()))
}
}
// CHECK-LABEL: sil hidden [ossa] @$s13read_accessor11TupleReaderV11useReadableyyF
// CHECK: [[READFN:%.*]] = function_ref @$s13read_accessor11TupleReaderV8readableSS_ytt_SSyttvr
// CHECK-NEXT: ([[FIRST:%.*]], [[SECOND:%.*]], [[TOKEN:%.*]]) = begin_apply [[READFN]](%0)
// FIXME: this materialization is silly
// CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $((String, ()), String, ())
// CHECK-NEXT: [[TEMP_0:%.*]] = tuple_element_addr [[TEMP]] : $*((String, ()), String, ()), 0
// CHECK-NEXT: [[TEMP_1:%.*]] = tuple_element_addr [[TEMP]] : $*((String, ()), String, ()), 1
// CHECK-NEXT: [[TEMP_2:%.*]] = tuple_element_addr [[TEMP]] : $*((String, ()), String, ()), 2
// CHECK-NEXT: [[TEMP_0_0:%.*]] = tuple_element_addr [[TEMP_0]] : $*(String, ()), 0
// CHECK-NEXT: [[TEMP_0_1:%.*]] = tuple_element_addr [[TEMP_0]] : $*(String, ()), 1
// CHECK-NEXT: [[T0:%.*]] = copy_value [[FIRST]] : $String
// CHECK-NEXT: store [[T0]] to [init] [[TEMP_0_0]]
// CHECK-NEXT: [[T0:%.*]] = copy_value [[SECOND]] : $String
// CHECK-NEXT: store [[T0]] to [init] [[TEMP_1]]
// CHECK-NEXT: [[TUPLE:%.*]] = load [copy] [[TEMP]]
// CHECK-NEXT: destructure_tuple
// CHECK-NEXT: destructure_tuple
// CHECK-NEXT: end_apply
// CHECK-LABEL: } // end sil function '$s13read_accessor11TupleReaderV11useReadableyyF'
func useReadable() {
var v = readable
}
var computed: String {
return compute()
}
// CHECK-LABEL: sil hidden [ossa] @$s13read_accessor11TupleReaderV0A8ComputedSSvr
// CHECK: [[GETTER:%.*]] = function_ref @$s13read_accessor11TupleReaderV8computedSSvg
// CHECK-NEXT: [[VALUE:%.]] = apply [[GETTER]](%0)
// CHECK-NEXT: [[BORROW:%.*]] = begin_borrow [[VALUE]] : $String
// CHECK-NEXT: yield [[BORROW]] : $String, resume bb1
// CHECK: bb1:
// CHECK-NEXT: end_borrow [[BORROW]] : $String
// CHECK-NEXT: destroy_value [[VALUE]] : $String
var readComputed : String {
_read {
yield computed
}
}
}
struct TestKeyPath {
var readable: String {
_read {
yield ""
}
}
func useKeyPath() -> String {
return self[keyPath: \.readable]
}
}
// Key-path getter for TestKeyPath.readable
// CHECK-LABEL: sil shared [thunk] [ossa] @$s13read_accessor11TestKeyPathV8readableSSvpACTK
// CHECK: bb0(%0 : $*String, %1 : $*TestKeyPath):
// CHECK-NEXT: [[SELF:%.*]] = load [trivial] %1
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[READ:%.*]] = function_ref @$s13read_accessor11TestKeyPathV8readableSSvr
// CHECK-NEXT: ([[VALUE:%.*]], [[TOKEN:%.*]]) = begin_apply [[READ]]([[SELF]])
// CHECK-NEXT: [[COPY:%.*]] = copy_value [[VALUE]]
// CHECK-NEXT: end_apply [[TOKEN]]
// CHECK-NEXT: store [[COPY]] to [init] %0 : $*String
// CHECK-NEXT: [[RET:%.*]] = tuple ()
// CHECK-NEXT: return [[RET]] : $()
// CHECK-LABEL: } // end sil function '$s13read_accessor11TestKeyPathV8readableSSvpACTK'
// Check that we emit a read coroutine but not a getter for this.
// This test assumes that we emit accessors in a particular order.
// CHECK-LABEL: sil [transparent] [ossa] @$s13read_accessor20TestBorrowedPropertyV14borrowedStringSSvpfi
// CHECK-NOT: sil [transparent] [serialized] [ossa] @$s13read_accessor20TestBorrowedPropertyV14borrowedStringSSvg
// CHECK: sil [transparent] [serialized] [ossa] @$s13read_accessor20TestBorrowedPropertyV14borrowedStringSSvr
// CHECK-NOT: sil [transparent] [serialized] [ossa] @$s13read_accessor20TestBorrowedPropertyV14borrowedStringSSvg
// CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s13read_accessor20TestBorrowedPropertyV14borrowedStringSSvs
public struct TestBorrowedProperty {
@_borrowed
public var borrowedString = ""
}
protocol ReadableTitle {
@_borrowed
var title: String { get }
}
class OverridableGetter : ReadableTitle {
var title: String = ""
}
// The read witness thunk does a direct call to the concrete read accessor.
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s13read_accessor17OverridableGetterCAA13ReadableTitleA2aDP5titleSSvrTW
// CHECK: function_ref @$s13read_accessor17OverridableGetterC5titleSSvr
// CHECK-LABEL: // end sil function '$s13read_accessor17OverridableGetterCAA13ReadableTitleA2aDP5titleSSvrTW'
// The concrete read accessor is generated on-demand and does a class dispatch to the getter.
// CHECK-LABEL: sil shared [ossa] @$s13read_accessor17OverridableGetterC5titleSSvr
// CHECK: class_method %0 : $OverridableGetter, #OverridableGetter.title!getter.1
// CHECK-LABEL: // end sil function '$s13read_accessor17OverridableGetterC5titleSSvr'
protocol GettableTitle {
var title: String { get }
}
class OverridableReader : GettableTitle {
@_borrowed
var title: String = ""
}
// The getter witness thunk does a direct call to the concrete getter.
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s13read_accessor17OverridableReaderCAA13GettableTitleA2aDP5titleSSvgTW
// CHECK: function_ref @$s13read_accessor17OverridableReaderC5titleSSvg
// CHECK-LABEL: // end sil function '$s13read_accessor17OverridableReaderCAA13GettableTitleA2aDP5titleSSvgTW'
// The concrete getter is generated on-demand and does a class dispatch to the read accessor.
// CHECK-LABEL: sil shared [ossa] @$s13read_accessor17OverridableReaderC5titleSSvg
// CHECK: class_method %0 : $OverridableReader, #OverridableReader.title!read.1
// CHECK-LABEL: // end sil function '$s13read_accessor17OverridableReaderC5titleSSvg'
| apache-2.0 |
zapdroid/RXWeather | Pods/RxTest/Platform/DataStructures/PriorityQueue.swift | 4 | 3363 | //
// PriorityQueue.swift
// Platform
//
// Created by Krunoslav Zaher on 12/27/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
struct PriorityQueue<Element> {
private let _hasHigherPriority: (Element, Element) -> Bool
private let _isEqual: (Element, Element) -> Bool
fileprivate var _elements = [Element]()
init(hasHigherPriority: @escaping (Element, Element) -> Bool, isEqual: @escaping (Element, Element) -> Bool) {
_hasHigherPriority = hasHigherPriority
_isEqual = isEqual
}
mutating func enqueue(_ element: Element) {
_elements.append(element)
bubbleToHigherPriority(_elements.count - 1)
}
func peek() -> Element? {
return _elements.first
}
var isEmpty: Bool {
return _elements.count == 0
}
mutating func dequeue() -> Element? {
guard let front = peek() else {
return nil
}
removeAt(0)
return front
}
mutating func remove(_ element: Element) {
for i in 0 ..< _elements.count {
if _isEqual(_elements[i], element) {
removeAt(i)
return
}
}
}
private mutating func removeAt(_ index: Int) {
let removingLast = index == _elements.count - 1
if !removingLast {
swap(&_elements[index], &_elements[_elements.count - 1])
}
_ = _elements.popLast()
if !removingLast {
bubbleToHigherPriority(index)
bubbleToLowerPriority(index)
}
}
private mutating func bubbleToHigherPriority(_ initialUnbalancedIndex: Int) {
precondition(initialUnbalancedIndex >= 0)
precondition(initialUnbalancedIndex < _elements.count)
var unbalancedIndex = initialUnbalancedIndex
while unbalancedIndex > 0 {
let parentIndex = (unbalancedIndex - 1) / 2
guard _hasHigherPriority(_elements[unbalancedIndex], _elements[parentIndex]) else { break }
swap(&_elements[unbalancedIndex], &_elements[parentIndex])
unbalancedIndex = parentIndex
}
}
private mutating func bubbleToLowerPriority(_ initialUnbalancedIndex: Int) {
precondition(initialUnbalancedIndex >= 0)
precondition(initialUnbalancedIndex < _elements.count)
var unbalancedIndex = initialUnbalancedIndex
while true {
let leftChildIndex = unbalancedIndex * 2 + 1
let rightChildIndex = unbalancedIndex * 2 + 2
var highestPriorityIndex = unbalancedIndex
if leftChildIndex < _elements.count && _hasHigherPriority(_elements[leftChildIndex], _elements[highestPriorityIndex]) {
highestPriorityIndex = leftChildIndex
}
if rightChildIndex < _elements.count && _hasHigherPriority(_elements[rightChildIndex], _elements[highestPriorityIndex]) {
highestPriorityIndex = rightChildIndex
}
guard highestPriorityIndex != unbalancedIndex else { break }
swap(&_elements[highestPriorityIndex], &_elements[unbalancedIndex])
unbalancedIndex = highestPriorityIndex
}
}
}
extension PriorityQueue: CustomDebugStringConvertible {
var debugDescription: String {
return _elements.debugDescription
}
}
| mit |
kaunteya/ProgressKit | InDeterminate/Spinner.swift | 1 | 3192 | //
// Spinner.swift
// ProgressKit
//
// Created by Kauntey Suryawanshi on 28/07/15.
// Copyright (c) 2015 Kauntey Suryawanshi. All rights reserved.
//
import Foundation
import Cocoa
@IBDesignable
open class Spinner: IndeterminateAnimation {
var basicShape = CAShapeLayer()
var containerLayer = CAShapeLayer()
var starList = [CAShapeLayer]()
var animation: CAKeyframeAnimation = {
var animation = CAKeyframeAnimation(keyPath: "transform.rotation")
animation.repeatCount = .infinity
animation.calculationMode = .discrete
return animation
}()
@IBInspectable open var starSize:CGSize = CGSize(width: 6, height: 15) {
didSet {
notifyViewRedesigned()
}
}
@IBInspectable open var roundedCorners: Bool = true {
didSet {
notifyViewRedesigned()
}
}
@IBInspectable open var distance: CGFloat = CGFloat(20) {
didSet {
notifyViewRedesigned()
}
}
@IBInspectable open var starCount: Int = 10 {
didSet {
notifyViewRedesigned()
}
}
@IBInspectable open var duration: Double = 1 {
didSet {
animation.duration = duration
}
}
@IBInspectable open var clockwise: Bool = false {
didSet {
notifyViewRedesigned()
}
}
override func configureLayers() {
super.configureLayers()
containerLayer.frame = self.bounds
containerLayer.cornerRadius = frame.width / 2
self.layer?.addSublayer(containerLayer)
animation.duration = duration
}
override func notifyViewRedesigned() {
super.notifyViewRedesigned()
starList.removeAll(keepingCapacity: true)
containerLayer.sublayers = nil
animation.values = [Double]()
var i = 0.0
while i < 360 {
var iRadian = CGFloat(i * Double.pi / 180.0)
if clockwise { iRadian = -iRadian }
animation.values?.append(iRadian)
let starShape = CAShapeLayer()
starShape.cornerRadius = roundedCorners ? starSize.width / 2 : 0
let centerLocation = CGPoint(x: frame.width / 2 - starSize.width / 2, y: frame.width / 2 - starSize.height / 2)
starShape.frame = CGRect(origin: centerLocation, size: starSize)
starShape.backgroundColor = foreground.cgColor
starShape.anchorPoint = CGPoint(x: 0.5, y: 0)
var rotation: CATransform3D = CATransform3DMakeTranslation(0, 0, 0.0);
rotation = CATransform3DRotate(rotation, -iRadian, 0.0, 0.0, 1.0);
rotation = CATransform3DTranslate(rotation, 0, distance, 0.0);
starShape.transform = rotation
starShape.opacity = Float(360 - i) / 360
containerLayer.addSublayer(starShape)
starList.append(starShape)
i = i + Double(360 / starCount)
}
}
override func startAnimation() {
containerLayer.add(animation, forKey: "rotation")
}
override func stopAnimation() {
containerLayer.removeAllAnimations()
}
}
| mit |
AlesTsurko/DNMKit | DNMModel/GCDHelper.swift | 1 | 1036 | //
// GCDHelper.swift
// denm_utility
//
// Created by James Bean on 9/24/15.
// Copyright © 2015 James Bean. All rights reserved.
//
// REPLACE WITH ASYNC
import Foundation
public var GlobalMainQueue: dispatch_queue_t {
return dispatch_get_main_queue()
}
public var GlobalUserInteractiveQueue: dispatch_queue_t {
return dispatch_get_global_queue(Int(QOS_CLASS_USER_INTERACTIVE.rawValue), 0)
}
public var GlobalUserInitiatedQueue: dispatch_queue_t {
return dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0)
}
public var GlobalUtilityQueue: dispatch_queue_t {
return dispatch_get_global_queue(Int(QOS_CLASS_UTILITY.rawValue), 0)
}
public var GlobalBackgroundQueue: dispatch_queue_t {
return dispatch_get_global_queue(Int(QOS_CLASS_BACKGROUND.rawValue), 0)
}
public func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
} | gpl-2.0 |
iOSWizards/AwesomeMedia | Example/Pods/AwesomeCore/AwesomeCore/Classes/DataAccess/QuestMarkerDA.swift | 1 | 3003 | //
// QuestMarkerDA.swift
// AwesomeCore
//
// Created by Antonio on 12/15/17.
//
//import Foundation
//
//class QuestMarkerDA {
//
// // MARK: - Parser
//
// func parseToCoreData(_ marker: QuestMarker, result: @escaping (CDMarker) -> Void) {
// AwesomeCoreDataAccess.shared.backgroundContext.perform {
// let cdMarker = self.parseToCoreData(marker)
// result(cdMarker)
// }
// }
//
// private func parseToCoreData(_ marker: QuestMarker) -> CDMarker {
//
// guard let markerId = marker.id else {
// fatalError("CDMarker object can't be created without id.")
// }
// let p = predicate(markerId, marker.assetId ?? "")
// let cdMarker = CDMarker.getObjectAC(predicate: p, createIfNil: true) as! CDMarker
//
// cdMarker.id = marker.id
// cdMarker.name = marker.name
// cdMarker.status = marker.status
// cdMarker.time = marker.time
// return cdMarker
// }
//
// func parseFromCoreData(_ cdMarker: CDMarker) -> QuestMarker {
// return QuestMarker(
// id: cdMarker.id,
// name: cdMarker.name,
// status: cdMarker.status,
// time: cdMarker.time,
// assetId: cdMarker.asset?.id
// )
// }
//
// // MARK: - Fetch
//
// func loadBy(markerId: String, assetId: String, result: @escaping (CDMarker?) -> Void) {
// func perform() {
// let p = predicate(markerId, assetId)
// guard let cdMarker = CDMarker.listAC(predicate: p).first as? CDMarker else {
// result(nil)
// return
// }
// result(cdMarker)
// }
// AwesomeCoreDataAccess.shared.performBackgroundBatchOperation({ (workerContext) in
// perform()
// })
// }
//
// // MARK: - Helpers
//
// /// Extract the given QuestMarker array as a NSSet (CoreData) objects.
// /// - Important: _This method must be called from within a BackgroundContext._
// ///
// /// - Parameter questMarkers: Array of QuestMarkers
// /// - Returns: a NSSet of CoreData CDMarkers or an empty NSSet.
// func extractCDMarkers(_ questMarkers: [QuestMarker]?) -> NSSet {
// var markers = NSSet()
// guard let questMarkers = questMarkers else { return markers }
// for qm in questMarkers {
// markers = markers.adding(parseToCoreData(qm)) as NSSet
// }
// return markers
// }
//
// func extractQuestMarkers(_ questMarkers: NSSet?) -> [QuestMarker]? {
// guard let questMarkers = questMarkers else { return nil }
// var markers = [QuestMarker]()
// for qm in questMarkers {
// markers.append(parseFromCoreData(qm as! CDMarker))
// }
// return markers
// }
//
// private func predicate(_ markerId: String, _ assetId: String) -> NSPredicate {
// return NSPredicate(format: "id == %@ AND asset.id == %@", markerId, assetId)
// }
//
//}
| mit |
blkbrds/intern09_final_project_tung_bien | MyApp/ViewModel/Home/HomeViewModel.swift | 1 | 1517 | //
// HotViewModel.swift
// MyApp
//
// Created by asiantech on 8/9/17.
// Copyright © 2017 Asian Tech Co., Ltd. All rights reserved.
//
import Foundation
import MVVM
import RealmSwift
import RealmS
final class HomeViewModel: MVVM.ViewModel {
// MARK: - Properties
enum GetItemResult {
case success
case failure(Error)
}
typealias GetItemCompletion = (GetItemResult) -> Void
var index = 0
var menus: Results<Menu>?
// MARK: - Public
func numberOfSections() -> Int {
return 1
}
func numberOfItems(inSection section: Int) -> Int {
guard let menus = menus else {
return 0
}
return menus[index].menuItems.count
}
func viewModelForItem(at indexPath: IndexPath) -> HomeCellViewModel {
guard let menus = menus else {
fatalError("Please call `fetch()` first.")
}
if indexPath.row <= menus[index].menuItems.count {
return HomeCellViewModel(item: menus[index].menuItems[indexPath.row])
}
return HomeCellViewModel(item: nil)
}
func fetch(id: Int) {
self.index = id
menus = RealmS().objects(Menu.self)
}
func getItem(completion: @escaping GetItemCompletion) {
Api.Item.itemQuery { (result) in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(_):
completion(.success)
}
}
}
}
| mit |
networkextension/SFSocket | SFSocket/HTTPProxyServer/GCDProxyServer.swift | 1 | 3071 | import Foundation
import CocoaAsyncSocket
/// Proxy server which listens on some port by GCDAsyncSocket.
///
/// This shoule be the base class for any concrete implemention of proxy server (e.g., HTTP or SOCKS5) which needs to listen on some port.
open class GCDProxyServer: ProxyServer, GCDAsyncSocketDelegate {
fileprivate let listenQueue: DispatchQueue = DispatchQueue(label: "NEKit.GCDProxyServer.listenQueue", attributes: [])
fileprivate var listenSocket: GCDAsyncSocket!
fileprivate var pendingSocket: [GCDTCPSocket] = []
fileprivate var canHandleNewSocket: Bool {
return Opt.ProxyActiveSocketLimit <= 0 || tunnels.value.count < Opt.ProxyActiveSocketLimit
}
/**
Start the proxy server which creates a GCDAsyncSocket listening on specific port.
- throws: The error occured when starting the proxy server.
*/
override open func start() throws {
listenSocket = GCDAsyncSocket(delegate: self, delegateQueue: listenQueue)
try listenSocket.accept(onInterface: address?.presentation, port: port.value)
try super.start()
}
/**
Stop the proxy server.
*/
override open func stop() {
listenQueue.sync {
for socket in self.pendingSocket {
socket.disconnect()
}
}
pendingSocket.removeAll()
listenSocket?.setDelegate(nil, delegateQueue: nil)
listenSocket?.disconnect()
listenSocket = nil
super.stop()
}
/**
Delegate method to handle the newly accepted GCDTCPSocket.
Only this method should be overrided in any concrete implemention of proxy server which listens on some port with GCDAsyncSocket.
- parameter socket: The accepted socket.
*/
func handleNewGCDSocket(_ socket: GCDTCPSocket) {
}
/**
GCDAsyncSocket delegate callback.
- parameter sock: The listening GCDAsyncSocket.
- parameter newSocket: The accepted new GCDAsyncSocket.
- warning: Do not call this method. This should be marked private but have to be marked public since the `GCDAsyncSocketDelegate` is public.
*/
open func socket(_ sock: GCDAsyncSocket, didAcceptNewSocket newSocket: GCDAsyncSocket) {
let gcdTCPSocket = GCDTCPSocket(socket: newSocket)
if canHandleNewSocket {
handleNewGCDSocket(gcdTCPSocket)
} else {
pendingSocket.append(gcdTCPSocket)
NSLog("Current Pending socket \(pendingSocket.count)")
}
}
override func tunnelDidClose(_ tunnel: Tunnel) {
super.tunnelDidClose(tunnel)
processPendingSocket()
}
func processPendingSocket() {
listenQueue.async {
while self.pendingSocket.count > 0 && self.canHandleNewSocket {
let socket = self.pendingSocket.removeFirst()
if socket.isConnected {
self.handleNewGCDSocket(socket)
}
NSLog("Current Pending socket \(self.pendingSocket.count)")
}
}
}
}
| bsd-3-clause |
ludoded/ReceiptBot | ReceiptBot/Scene/DetailInvoice/DetailInvoicePresenter.swift | 1 | 4270 | //
// DetailInvoicePresenter.swift
// ReceiptBot
//
// Created by Haik Ampardjian on 4/13/17.
// Copyright (c) 2017 receiptbot. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
import Kingfisher
protocol DetailInvoicePresenterOutput: class, Errorable, Spinnable {
func displayInitial(viewModel: DetailInvoice.Setup.ViewModel)
func goBack()
}
class DetailInvoicePresenter {
weak var output: DetailInvoicePresenterOutput!
// MARK: - Presentation logic
func presentInitialSetup(response: DetailInvoice.Setup.Response) {
switch response.invoice {
case .none(let message): output.show(type: .error(message: message))
case .value(let invoice): passInitialSetup(from: invoice)
}
}
func passInitialSetup(from invoice: SyncConvertedInvoiceResponse) {
let invoiceDate = invoice.invoiceDateMobile != nil ? DateFormatters.mdySpaceFormatter.string(from: invoice.invoiceDateMobile!) : ""
let dueDate = invoice.dueDate != nil ? DateFormatters.mdySpaceFormatter.string(from: invoice.dueDate!) : ""
let supplierName = AppSettings.shared.config.supplierName(for: invoice.supplierId)
let categoryName = AppSettings.shared.config.categoryName(for: invoice.categoryId)
let paymentMethod = AppSettings.shared.config.paymentName(for: invoice.paymentMethodId)
let taxPercentage = AppSettings.shared.config.taxName(for: invoice.taxPercentage)
guard let imageURL = invoice.fullMediaUrl else { output.show(type: .error(message: "Can't load the image")); return }
let type: DetailInvoice.Setup.InvoiceType
/// If pdf
if invoice.isPdf {
type = .pdf(URLRequest(url: imageURL))
}
else { /// If image: png, jpeg, jpg etc
type = .image(ImageResource(downloadURL: imageURL))
}
/// If editable
let invType = RebotInvoiceStatusMapper.toFrontEnd(from: invoice.type).lowercased()
let validation: DetailInvoice.Setup.Validation
if invType == "processing" { validation = DetailInvoice.Setup.Validation(isEditable: false, error: nil) }
else if invType == "rejected" { validation = DetailInvoice.Setup.Validation(isEditable: false, error: "This document is rejected due to: \"\(invoice.invoiceComment)\"") }
else { validation = DetailInvoice.Setup.Validation(isEditable: true, error: nil) }
let viewModel = DetailInvoice.Setup.ViewModel(type: type,
supplierName: supplierName,
invoiceDate: invoiceDate,
invoiceNumber: invoice.invoiceNumber,
paymentMethod: paymentMethod,
category: categoryName,
taxRate: taxPercentage,
taxAmount: invoice.taxAmount,
grossAmount: invoice.grossAmount,
netAmount: invoice.netAmount,
dueDate: dueDate,
dueDateMin: invoice.invoiceDateMobile ?? Date(),
validation: validation)
output.displayInitial(viewModel: viewModel)
}
func presentSave(response: DetailInvoice.Save.Response) {
output.stopSpinning()
switch response.data {
case .none(let message): output.show(type: .error(message: message))
case .value: output.goBack()
}
}
func presentReject(response: DetailInvoice.Reject.Response) {
output.stopSpinning()
switch response.data {
case .none(let message): output.show(type: .error(message: message))
case .value: output.goBack()
}
}
}
| lgpl-3.0 |
HamzaGhazouani/HGCircularSlider | Example/Tests/CircularSliderHelperTests.swift | 1 | 2187 | //
// CircularSliderHelperTests.swift
// HGCircularSlider_Tests
//
// Created by Hamza GHAZOUANI on 24/07/2019.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import XCTest
@testable import HGCircularSlider
extension CGFloat {
var toDegrees: CGFloat {
return self * 180.0 / CGFloat(Double.pi)
}
}
class CircularSliderHelperTests: XCTestCase {
let cirlceInterval = Interval(min: 0 , max: CGFloat(2 * Double.pi))
let valuesInterval = Interval(min: 0, max: 1.2)
func testInitialValueScale() {
// Given
let value = valuesInterval.min
// Thene
let angle = CircularSliderHelper.scaleValue(value, fromInterval: valuesInterval, toInterval: cirlceInterval).toDegrees
XCTAssertEqual(angle, 0)
}
func testFinalValueScale() {
// Given
let value: CGFloat = valuesInterval.max
// Thene
let angle = CircularSliderHelper.scaleValue(value, fromInterval: valuesInterval, toInterval: cirlceInterval).toDegrees
XCTAssertEqual(angle, 360)
}
func testMedianValueScale() {
// Given
let value: CGFloat = valuesInterval.max / 2
// Thene
let angle = CircularSliderHelper.scaleValue(value, fromInterval: valuesInterval, toInterval: cirlceInterval).toDegrees
XCTAssertEqual(angle, 180)
}
func testValueFromRangeToAnotherRangeMinValueEqualToZero() {
let oldRange = Interval(min: 0, max: 100)
let newRange = Interval(min: 10, max: 20)
let value: CGFloat = 10
let newValue = CircularSliderHelper.scaleValue(value, fromInterval: oldRange, toInterval: newRange)
XCTAssertEqual(newValue, 11)
}
func testValueFromRangeToAnotherRangeMinValueGratherThanZero() {
let oldRange = Interval(min: 5, max: 30)
let newRange = Interval(min: 0, max: 100)
let value: CGFloat = 10
let newValue = CircularSliderHelper.scaleValue(value, fromInterval: oldRange, toInterval: newRange)
XCTAssertEqual(newValue, 20)
}
}
| mit |
amrap-labs/TeamupKit | Sources/TeamupKitTests/TeamupKitRequestTests.swift | 1 | 2325 | //
// TeamupKitRequestTests.swift
// TeamupKitTests
//
// Created by Merrick Sapsford on 26/07/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import XCTest
@testable import TeamupKit
class TeamupKitRequestTests: TeamupKitTests {
// MARK: UrlBuilder
/// Test UrlBuilder generates a URL successfully for an endpoint.
func testUrlBuilderGeneration() {
let urlBuilder = teamup.requestBuilder.urlBuilder
let url = urlBuilder.build(for: .logIn)
let path = Endpoint.logIn.path
let baseUrl = teamup.config.api.url.absoluteString
XCTAssertTrue(url.absoluteString.contains(path) && url.absoluteString.contains(baseUrl))
}
// MARK: RequestBuilder
/// Test request builder will successfully generate a valid request.
func testRequestEndpointGeneration() {
let headers = ["test" : "header"]
let parameters = ["test" : "parameter"]
let request = teamup.requestBuilder.build(for: .sessions,
method: .get,
headers: headers,
parameters: parameters,
authentication: .none)
XCTAssertEqual(headers, request.headers!)
XCTAssertEqual(parameters.count, request.parameters?.count)
}
/// Test request builder will inject API token authentication headers correctly.
func testRequestEndpointGenerationApiTokenAuthentication() {
let request = teamup.requestBuilder.build(for: .sessions,
method: .get,
authentication: .apiToken)
XCTAssertNotEqual(0, request.headers?.count)
}
/// Test request builder will inject user token authentication headers correctly.
func testRequestEndpointGenerationUserTokenAuthentication() {
let request = teamup.requestBuilder.build(for: .sessions,
method: .get,
authentication: .userToken)
XCTAssertNotEqual(0, request.headers?.count)
}
}
| mit |
juliensagot/JSNavigationController | JSNavigationController/Sources/JSNavigationBarController.swift | 1 | 5120 | //
// JSNavigationBarController.swift
// JSNavigationController
//
// Created by Julien Sagot on 14/05/16.
// Copyright © 2016 Julien Sagot. All rights reserved.
//
import AppKit
open class JSNavigationBarController: JSViewControllersStackManager {
open var viewControllers: [NSViewController] = []
open weak var contentView: NSView?
// MARK: - Initializers
public init(view: NSView) {
contentView = view
}
// MARK: - Default animations
open func defaultPushAnimation() -> AnimationBlock {
return { [weak self] (_, _) in
let containerViewBounds = self?.contentView?.bounds ?? .zero
let slideToLeftTransform = CATransform3DMakeTranslation(-containerViewBounds.width / 2, 0, 0)
let slideToLeftAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform))
slideToLeftAnimation.fromValue = NSValue(caTransform3D: CATransform3DIdentity)
slideToLeftAnimation.toValue = NSValue(caTransform3D: slideToLeftTransform)
slideToLeftAnimation.duration = 0.25
slideToLeftAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
slideToLeftAnimation.fillMode = CAMediaTimingFillMode.forwards
slideToLeftAnimation.isRemovedOnCompletion = false
let slideFromRightTransform = CATransform3DMakeTranslation(containerViewBounds.width / 2, 0, 0)
let slideFromRightAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform))
slideFromRightAnimation.fromValue = NSValue(caTransform3D: slideFromRightTransform)
slideFromRightAnimation.toValue = NSValue(caTransform3D: CATransform3DIdentity)
slideFromRightAnimation.duration = 0.25
slideFromRightAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
slideFromRightAnimation.fillMode = CAMediaTimingFillMode.forwards
slideFromRightAnimation.isRemovedOnCompletion = false
let fadeInAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.opacity))
fadeInAnimation.fromValue = 0.0
fadeInAnimation.toValue = 1.0
fadeInAnimation.duration = 0.25
fadeInAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
fadeInAnimation.fillMode = CAMediaTimingFillMode.forwards
fadeInAnimation.isRemovedOnCompletion = false
let fadeOutAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.opacity))
fadeOutAnimation.fromValue = 1.0
fadeOutAnimation.toValue = 0.0
fadeOutAnimation.duration = 0.25
fadeOutAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
fadeOutAnimation.fillMode = CAMediaTimingFillMode.forwards
fadeOutAnimation.isRemovedOnCompletion = false
return ([slideToLeftAnimation, fadeOutAnimation], [slideFromRightAnimation, fadeInAnimation])
}
}
open func defaultPopAnimation() -> AnimationBlock {
return { [weak self] (_, _) in
let containerViewBounds = self?.contentView?.bounds ?? .zero
let slideToRightTransform = CATransform3DMakeTranslation(-containerViewBounds.width / 2, 0, 0)
let slideToRightAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform))
slideToRightAnimation.fromValue = NSValue(caTransform3D: slideToRightTransform)
slideToRightAnimation.toValue = NSValue(caTransform3D: CATransform3DIdentity)
slideToRightAnimation.duration = 0.25
slideToRightAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
slideToRightAnimation.fillMode = CAMediaTimingFillMode.forwards
slideToRightAnimation.isRemovedOnCompletion = false
let slideToRightFromCenterTransform = CATransform3DMakeTranslation(containerViewBounds.width / 2, 0, 0)
let slideToRightFromCenterAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.transform))
slideToRightFromCenterAnimation.fromValue = NSValue(caTransform3D: CATransform3DIdentity)
slideToRightFromCenterAnimation.toValue = NSValue(caTransform3D: slideToRightFromCenterTransform)
slideToRightFromCenterAnimation.duration = 0.35
slideToRightFromCenterAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
slideToRightFromCenterAnimation.fillMode = CAMediaTimingFillMode.forwards
slideToRightFromCenterAnimation.isRemovedOnCompletion = false
let fadeInAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.opacity))
fadeInAnimation.fromValue = 0.0
fadeInAnimation.toValue = 1.0
fadeInAnimation.duration = 0.25
fadeInAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
fadeInAnimation.fillMode = CAMediaTimingFillMode.forwards
fadeInAnimation.isRemovedOnCompletion = false
let fadeOutAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.opacity))
fadeOutAnimation.fromValue = 1.0
fadeOutAnimation.toValue = 0.0
fadeOutAnimation.duration = 0.25
fadeOutAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
fadeOutAnimation.fillMode = CAMediaTimingFillMode.forwards
fadeOutAnimation.isRemovedOnCompletion = false
return ([slideToRightFromCenterAnimation, fadeOutAnimation], [slideToRightAnimation, fadeInAnimation])
}
}
}
| mit |
mrlegowatch/RolePlayingCore | RolePlayingCore/RolePlayingCore/Player/Classes.swift | 1 | 735 | //
// Classes.swift
// RolePlayingCore
//
// Created by Brian Arnold on 11/13/16.
// Copyright © 2016 Brian Arnold. All rights reserved.
//
// A set of class traits
public struct Classes: Codable {
public var classes = [ClassTraits]()
public var experiencePoints: [Int]?
private enum CodingKeys: String, CodingKey {
case classes
case experiencePoints = "experience points"
}
public func find(_ className: String?) -> ClassTraits? {
return classes.first(where: { $0.name == className })
}
public var count: Int { return classes.count }
public subscript(index: Int) -> ClassTraits? {
get {
return classes[index]
}
}
}
| mit |
vapor/vapor | Sources/Vapor/Utilities/DotEnv.swift | 1 | 12728 | #if os(Linux)
import Glibc
#else
import Darwin
#endif
/// Reads dotenv (`.env`) files and loads them into the current process.
///
/// let fileio: NonBlockingFileIO
/// let elg: EventLoopGroup
/// let file = try DotEnvFile.read(path: ".env", fileio: fileio, on: elg.next()).wait()
/// for line in file.lines {
/// print("\(line.key)=\(line.value)")
/// }
/// file.load(overwrite: true) // loads all lines into the process
///
/// Dotenv files are formatted using `KEY=VALUE` syntax. They support comments using the `#` symbol.
/// They also support strings, both single and double-quoted.
///
/// FOO=BAR
/// STRING='Single Quote String'
/// # Comment
/// STRING2="Double Quoted\nString"
///
/// Single-quoted strings are parsed literally. Double-quoted strings may contain escaped newlines
/// that will be converted to actual newlines.
public struct DotEnvFile {
/// Reads the dotenv files relevant to the environment and loads them into the process.
///
/// let environment: Environment
/// let elgp: EventLoopGroupProvider
/// let fileio: NonBlockingFileIO
/// let logger: Logger
/// try DotEnvFile.load(for: .development, on: elgp, fileio: fileio, logger: logger)
/// print(Environment.process.FOO) // BAR
///
/// - parameters:
/// - environment: current environment, selects which .env file to use.
/// - eventLoopGroupProvider: Either provides an EventLoopGroup or tells the function to create a new one.
/// - fileio: NonBlockingFileIO that is used to read the .env file(s).
/// - logger: Optionally provide an existing logger.
public static func load(
for environment: Environment = .development,
on eventLoopGroupProvider: Application.EventLoopGroupProvider = .createNew,
fileio: NonBlockingFileIO,
logger: Logger = Logger(label: "dot-env-loggger")
) {
let eventLoopGroup: EventLoopGroup
switch eventLoopGroupProvider {
case .shared(let group):
eventLoopGroup = group
case .createNew:
eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
}
defer {
switch eventLoopGroupProvider {
case .shared:
logger.trace("Running on shared EventLoopGroup. Not shutting down EventLoopGroup.")
case .createNew:
logger.trace("Shutting down EventLoopGroup")
do {
try eventLoopGroup.syncShutdownGracefully()
} catch {
logger.warning("Shutting down EventLoopGroup failed: \(error)")
}
}
}
// Load specific .env first since values are not overridden.
DotEnvFile.load(path: ".env.\(environment.name)", on: .shared(eventLoopGroup), fileio: fileio, logger: logger)
DotEnvFile.load(path: ".env", on: .shared(eventLoopGroup), fileio: fileio, logger: logger)
}
/// Reads the dotenv files relevant to the environment and loads them into the process.
///
/// let path: String
/// let elgp: EventLoopGroupProvider
/// let fileio: NonBlockingFileIO
/// let logger: Logger
/// try DotEnvFile.load(path: path, on: elgp, fileio: filio, logger: logger)
/// print(Environment.process.FOO) // BAR
///
/// - parameters:
/// - path: Absolute or relative path of the dotenv file.
/// - eventLoopGroupProvider: Either provides an EventLoopGroup or tells the function to create a new one.
/// - fileio: NonBlockingFileIO that is used to read the .env file(s).
/// - logger: Optionally provide an existing logger.
public static func load(
path: String,
on eventLoopGroupProvider: Application.EventLoopGroupProvider = .createNew,
fileio: NonBlockingFileIO,
logger: Logger = Logger(label: "dot-env-loggger")
) {
let eventLoopGroup: EventLoopGroup
switch eventLoopGroupProvider {
case .shared(let group):
eventLoopGroup = group
case .createNew:
eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
}
defer {
switch eventLoopGroupProvider {
case .shared:
logger.trace("Running on shared EventLoopGroup. Not shutting down EventLoopGroup.")
case .createNew:
logger.trace("Shutting down EventLoopGroup")
do {
try eventLoopGroup.syncShutdownGracefully()
} catch {
logger.warning("Shutting down EventLoopGroup failed: \(error)")
}
}
}
do {
try load(path: path, fileio: fileio, on: eventLoopGroup.next()).wait()
} catch {
logger.debug("Could not load \(path) file: \(error)")
}
}
/// Reads a dotenv file from the supplied path and loads it into the process.
///
/// let fileio: NonBlockingFileIO
/// let elg: EventLoopGroup
/// try DotEnvFile.load(path: ".env", fileio: fileio, on: elg.next()).wait()
/// print(Environment.process.FOO) // BAR
///
/// Use `DotEnvFile.read` to read the file without loading it.
///
/// - parameters:
/// - path: Absolute or relative path of the dotenv file.
/// - fileio: File loader.
/// - eventLoop: Eventloop to perform async work on.
/// - overwrite: If `true`, values already existing in the process' env
/// will be overwritten. Defaults to `false`.
public static func load(
path: String,
fileio: NonBlockingFileIO,
on eventLoop: EventLoop,
overwrite: Bool = false
) -> EventLoopFuture<Void> {
return self.read(path: path, fileio: fileio, on: eventLoop)
.map { $0.load(overwrite: overwrite) }
}
/// Reads a dotenv file from the supplied path.
///
/// let fileio: NonBlockingFileIO
/// let elg: EventLoopGroup
/// let file = try DotEnvFile.read(path: ".env", fileio: fileio, on: elg.next()).wait()
/// for line in file.lines {
/// print("\(line.key)=\(line.value)")
/// }
/// file.load(overwrite: true) // loads all lines into the process
/// print(Environment.process.FOO) // BAR
///
/// Use `DotEnvFile.load` to read and load with one method.
///
/// - parameters:
/// - path: Absolute or relative path of the dotenv file.
/// - fileio: File loader.
/// - eventLoop: Eventloop to perform async work on.
public static func read(
path: String,
fileio: NonBlockingFileIO,
on eventLoop: EventLoop
) -> EventLoopFuture<DotEnvFile> {
return fileio.openFile(path: path, eventLoop: eventLoop).flatMap { arg -> EventLoopFuture<ByteBuffer> in
return fileio.read(fileRegion: arg.1, allocator: .init(), eventLoop: eventLoop)
.flatMapThrowing
{ buffer in
try arg.0.close()
return buffer
}
}.map { buffer in
var parser = Parser(source: buffer)
return .init(lines: parser.parse())
}
}
/// Represents a `KEY=VALUE` pair in a dotenv file.
public struct Line: CustomStringConvertible, Equatable {
/// The key.
public let key: String
/// The value.
public let value: String
/// `CustomStringConvertible` conformance.
public var description: String {
return "\(self.key)=\(self.value)"
}
}
/// All `KEY=VALUE` pairs found in the file.
public let lines: [Line]
/// Creates a new DotEnvFile
init(lines: [Line]) {
self.lines = lines
}
/// Loads this file's `KEY=VALUE` pairs into the current process.
///
/// let file: DotEnvFile
/// file.load(overwrite: true) // loads all lines into the process
///
/// - parameters:
/// - overwrite: If `true`, values already existing in the process' env
/// will be overwritten. Defaults to `false`.
public func load(overwrite: Bool = false) {
for line in self.lines {
setenv(line.key, line.value, overwrite ? 1 : 0)
}
}
}
// MARK: Parser
extension DotEnvFile {
struct Parser {
var source: ByteBuffer
init(source: ByteBuffer) {
self.source = source
}
mutating func parse() -> [Line] {
var lines: [Line] = []
while let next = self.parseNext() {
lines.append(next)
}
return lines
}
private mutating func parseNext() -> Line? {
self.skipSpaces()
guard let peek = self.peek() else {
return nil
}
switch peek {
case .octothorpe:
// comment following, skip it
self.skipComment()
// then parse next
return self.parseNext()
case .newLine:
// empty line, skip
self.pop() // \n
// then parse next
return self.parseNext()
default:
// this is a valid line, parse it
return self.parseLine()
}
}
private mutating func skipComment() {
let commentLength: Int
if let toNewLine = self.countDistance(to: .newLine) {
commentLength = toNewLine + 1 // include newline
} else {
commentLength = self.source.readableBytes
}
self.source.moveReaderIndex(forwardBy: commentLength)
}
private mutating func parseLine() -> Line? {
guard let keyLength = self.countDistance(to: .equal) else {
return nil
}
guard let key = self.source.readString(length: keyLength) else {
return nil
}
self.pop() // =
guard let value = self.parseLineValue() else {
return nil
}
return Line(key: key, value: value)
}
private mutating func parseLineValue() -> String? {
let valueLength: Int
if let toNewLine = self.countDistance(to: .newLine) {
valueLength = toNewLine
} else {
valueLength = self.source.readableBytes
}
guard let value = self.source.readString(length: valueLength) else {
return nil
}
guard let first = value.first, let last = value.last else {
return value
}
// check for quoted strings
switch (first, last) {
case ("\"", "\""):
// double quoted strings support escaped \n
return value.dropFirst().dropLast()
.replacingOccurrences(of: "\\n", with: "\n")
case ("'", "'"):
// single quoted strings just need quotes removed
return value.dropFirst().dropLast() + ""
default: return value
}
}
private mutating func skipSpaces() {
scan: while let next = self.peek() {
switch next {
case .space: self.pop()
default: break scan
}
}
}
private func peek() -> UInt8? {
return self.source.getInteger(at: self.source.readerIndex)
}
private mutating func pop() {
self.source.moveReaderIndex(forwardBy: 1)
}
private func countDistance(to byte: UInt8) -> Int? {
var copy = self.source
var found = false
scan: while let next = copy.readInteger(as: UInt8.self) {
if next == byte {
found = true
break scan
}
}
guard found else {
return nil
}
let distance = copy.readerIndex - source.readerIndex
guard distance != 0 else {
return nil
}
return distance - 1
}
}
}
private extension UInt8 {
static var newLine: UInt8 {
return 0xA
}
static var space: UInt8 {
return 0x20
}
static var octothorpe: UInt8 {
return 0x23
}
static var equal: UInt8 {
return 0x3D
}
}
| mit |
alberttra/A-Framework | Example/A-Framework/FadeInOutViewController.swift | 1 | 1166 | //
// FadeInOutViewController.swift
// A-Framework
//
// Created by Albert Tra on 03/03/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
class FadeInOutViewController: UIViewController {
@IBOutlet weak var box: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
box.layer.cornerRadius = 5
box.clipsToBounds = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func toggleButtonPressed(sender: AnyObject) {
if box.alpha == 0 {
box.fadeIn()
} else {
box.fadeOut()
}
}
}
| mit |
BitBaum/Swift-Big-Integer | Tools/MG SuperSwift.swift | 1 | 4848 | /*
* ————————————————————————————————————————————————————————————————————————————
* SuperSwift.swift
* ————————————————————————————————————————————————————————————————————————————
* SuperSwift is a file that aims to improve the swift programming language. It
* adds missing functionality and convenient syntax to make the language more
* versatile.
* ————————————————————————————————————————————————————————————————————————————
* Created by Marcel Kröker on 18.02.2017.
* Copyright © 2017 Marcel Kröker. All rights reserved.
*/
import Foundation
//
////
//////
//MARK: - Snippets
//////
////
//
/*
Some snippets are essential to use SuperSwift. It defines some operators that are not
typeable (or too hard to find) on a normal keyboard, thus it is recommended to use snippets
in your IDE or xcode to have easy access to those operators.
*/
// The cartesian product
// Shortcut: $cp
// Operator: ×
// The dot product, or scalar product
// Shortcut: $dot
// Operator: •
// The element operator (same functionality as X.contains(y))
// Shortcut: $in
// Operator: ∈
// The not element operator (same functionality as !X.contains(y))
// Shortcut: $notin
// Operator: ∉
//
////
//////
//MARK: - Overview
//////
////
//
/*
This is an overview of all functionality of SuperSwift.
*/
//
////
//////
//MARK: - Extensions
//////
////
//
public extension String
{
/// Returns character at index i as String.
subscript(i: Int) -> String
{
return String(self[index(startIndex, offsetBy: i)])
}
/// Returns characters in range as string.
subscript(r: Range<Int>) -> String
{
let start = index(startIndex, offsetBy: r.lowerBound)
let end = index(start, offsetBy: r.upperBound - r.lowerBound)
return String(self[start..<end])
}
/// If possible, returns index of first ocurrence of char.
subscript(char: Character) -> Int?
{
return self.index(of: char)?.encodedOffset
}
// Make this function work with normal ranges.
mutating func removeSubrange(_ bounds: CountableClosedRange<Int>)
{
let start = self.index(self.startIndex, offsetBy: bounds.lowerBound)
let end = self.index(self.startIndex, offsetBy: bounds.upperBound)
self.removeSubrange(start...end)
}
// Make this function work with normal ranges.
mutating func removeSubrange(_ bounds: CountableRange<Int>)
{
let start = self.index(self.startIndex, offsetBy: bounds.lowerBound)
let end = self.index(self.startIndex, offsetBy: bounds.upperBound)
self.removeSubrange(start..<end)
}
}
//
////
//////
//MARK: - Operators
//////
////
//
precedencegroup CartesianProductPrecedence
{
associativity: left
lowerThan: RangeFormationPrecedence
}
infix operator × : CartesianProductPrecedence
/**
Calculate the cartesian product of two sequences. With a left precedence you can iterate
over the product:
// Will print all numbers from 0000 to 9999
for (((i, j), k), l) in 0...9 × 0...9 × 0...9 × 0...9
{
print("\(i)\(j)\(k)\(l)")
}
- Parameter lhs: An array.
- Parameter rhs: An array.
- returns: [(l, r)] where l ∈ lhs and r ∈ rhs.
*/
func ×<T1: Any, T2: Any>(lhs: [T1], rhs: [T2]) -> [(T1, T2)]
{
var res = [(T1, T2)]()
for l in lhs
{
for r in rhs
{
res.append((l, r))
}
}
return res
}
func ×(lhs: CountableRange<Int>, rhs: CountableRange<Int>) -> [(Int, Int)]
{
return lhs.map{$0} × rhs.map{$0}
}
func ×(lhs: CountableRange<Int>, rhs: CountableClosedRange<Int>) -> [(Int, Int)]
{
return lhs.map{$0} × rhs.map{$0}
}
func ×(lhs: CountableClosedRange<Int>, rhs: CountableRange<Int>) -> [(Int, Int)]
{
return lhs.map{$0} × rhs.map{$0}
}
func ×(lhs: CountableClosedRange<Int>, rhs: CountableClosedRange<Int>) -> [(Int, Int)]
{
return lhs.map{$0} × rhs.map{$0}
}
func ×<T: Any>(lhs: [T], rhs: CountableRange<Int>) -> [(T, Int)]
{
return lhs × rhs.map{$0}
}
func ×<T: Any>(lhs: [T], rhs: CountableClosedRange<Int>) -> [(T, Int)]
{
return lhs × rhs.map{$0}
}
// Better syntax for contains. Works for sets and arrays
infix operator ∈
func ∈<T: Any>(lhs: T, rhs: Set<T>) -> Bool
{
return rhs.contains(lhs)
}
func ∈<T: Any & Equatable>(lhs: T, rhs: Array<T>) -> Bool
{
return rhs.contains(lhs)
}
infix operator ∉
func ∉<T: Any & Equatable>(lhs: T, rhs: Array<T>) -> Bool
{
return !rhs.contains(lhs)
}
func ∉<T: Any>(lhs: T, rhs: Set<T>) -> Bool
{
return !rhs.contains(lhs)
}
| mit |
skofgar/KGFloatingDrawer | Example/KGFloatingDrawer-Example/AppDelegate.swift | 1 | 6472 | //
// AppDelegate.swift
// KGDrawerViewController
//
// Created by Kyle Goddard on 2015-02-10.
// Copyright (c) 2015 Kyle Goddard. All rights reserved.
//
import UIKit
import KGFloatingDrawer
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let kKGDrawersStoryboardName = "Drawers"
let kKGDrawerSettingsViewControllerStoryboardId = "KGDrawerSettingsViewControllerStoryboardId"
let kKGDrawerWebViewViewControllerStoryboardId = "KGDrawerWebViewControllerStoryboardId"
let kKGLeftDrawerStoryboardId = "KGLeftDrawerViewControllerStoryboardId"
let kKGRightDrawerStoryboardId = "KGRightDrawerViewControllerStoryboardId"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: Any]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = drawerViewController
window?.makeKeyAndVisible()
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 throttle down OpenGL ES frame rates. 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 inactive 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:.
}
fileprivate var _drawerViewController: KGDrawerViewController?
var drawerViewController: KGDrawerViewController {
get {
if let viewController = _drawerViewController {
return viewController
}
return prepareDrawerViewController()
}
}
func prepareDrawerViewController() -> KGDrawerViewController {
let drawerViewController = KGDrawerViewController()
drawerViewController.centerViewController = drawerSettingsViewController()
drawerViewController.leftViewController = leftViewController()
drawerViewController.rightViewController = rightViewController()
drawerViewController.backgroundImage = UIImage(named: "sky3")
_drawerViewController = drawerViewController
return drawerViewController
}
fileprivate func drawerStoryboard() -> UIStoryboard {
let storyboard = UIStoryboard(name: kKGDrawersStoryboardName, bundle: nil)
return storyboard
}
fileprivate func viewControllerForStoryboardId(_ storyboardId: String) -> UIViewController {
let viewController: UIViewController = drawerStoryboard().instantiateViewController(withIdentifier: storyboardId)
return viewController
}
func drawerSettingsViewController() -> UIViewController {
let viewController = viewControllerForStoryboardId(kKGDrawerSettingsViewControllerStoryboardId)
setStatusBarBackgroundColor(for: viewController)
return viewController
}
func sourcePageViewController() -> UIViewController {
let viewController = viewControllerForStoryboardId(kKGDrawerWebViewViewControllerStoryboardId)
return viewController
}
fileprivate func leftViewController() -> UIViewController {
let viewController = viewControllerForStoryboardId(kKGLeftDrawerStoryboardId)
return viewController
}
fileprivate func rightViewController() -> UIViewController {
let viewController = viewControllerForStoryboardId(kKGRightDrawerStoryboardId)
return viewController
}
func toggleLeftDrawer(_ sender:AnyObject, animated:Bool) {
_drawerViewController?.toggleDrawer(side: .left, animated: true, complete: { (finished) -> Void in
// do nothing
})
}
func toggleRightDrawer(_ sender:AnyObject, animated:Bool) {
_drawerViewController?.toggleDrawer(side: .right, animated: true, complete: { (finished) -> Void in
// do nothing
})
}
func setStatusBarBackgroundColor(for viewController: UIViewController) {
if let navigation = viewController as? UINavigationController {
navigation.view.backgroundColor = navigation.navigationBar.barTintColor // navController.navigationBar.backgroundColor ??
}
}
fileprivate var _centerViewController: UIViewController?
var centerViewController: UIViewController {
get {
if let viewController = _centerViewController {
return viewController
}
return drawerSettingsViewController()
}
set {
if let drawerViewController = _drawerViewController {
drawerViewController.closeDrawer(side: drawerViewController.currentlyOpenedSide, animated: true) { finished in }
if drawerViewController.centerViewController != newValue {
drawerViewController.centerViewController = newValue
}
}
setStatusBarBackgroundColor(for: newValue)
_centerViewController = newValue
}
}
}
| mit |
alessiobrozzi/firefox-ios | Client/Frontend/Browser/TabToolbar.swift | 1 | 14646 | /* 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 UIKit
import SnapKit
import Shared
import XCGLogger
private let log = Logger.browserLogger
protocol TabToolbarProtocol: class {
weak var tabToolbarDelegate: TabToolbarDelegate? { get set }
var shareButton: UIButton { get }
var bookmarkButton: UIButton { get }
var menuButton: UIButton { get }
var forwardButton: UIButton { get }
var backButton: UIButton { get }
var stopReloadButton: UIButton { get }
var homePageButton: UIButton { get }
var actionButtons: [UIButton] { get }
func updateBackStatus(_ canGoBack: Bool)
func updateForwardStatus(_ canGoForward: Bool)
func updateBookmarkStatus(_ isBookmarked: Bool)
func updateReloadStatus(_ isLoading: Bool)
func updatePageStatus(_ isWebPage: Bool)
}
protocol TabToolbarDelegate: class {
func tabToolbarDidPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton)
func tabToolbarDidPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton)
func tabToolbarDidLongPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton)
func tabToolbarDidLongPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton)
func tabToolbarDidPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton)
func tabToolbarDidLongPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton)
func tabToolbarDidPressStop(_ tabToolbar: TabToolbarProtocol, button: UIButton)
func tabToolbarDidPressMenu(_ tabToolbar: TabToolbarProtocol, button: UIButton)
func tabToolbarDidPressBookmark(_ tabToolbar: TabToolbarProtocol, button: UIButton)
func tabToolbarDidLongPressBookmark(_ tabToolbar: TabToolbarProtocol, button: UIButton)
func tabToolbarDidPressShare(_ tabToolbar: TabToolbarProtocol, button: UIButton)
func tabToolbarDidPressHomePage(_ tabToolbar: TabToolbarProtocol, button: UIButton)
}
@objc
open class TabToolbarHelper: NSObject {
let toolbar: TabToolbarProtocol
let ImageReload = UIImage.templateImageNamed("bottomNav-refresh")
let ImageReloadPressed = UIImage.templateImageNamed("bottomNav-refresh")
let ImageStop = UIImage.templateImageNamed("stop")
let ImageStopPressed = UIImage.templateImageNamed("stopPressed")
var buttonTintColor = UIColor.darkGray {
didSet {
setTintColor(buttonTintColor, forButtons: toolbar.actionButtons)
}
}
var loading: Bool = false {
didSet {
if loading {
toolbar.stopReloadButton.setImage(ImageStop, for: .normal)
toolbar.stopReloadButton.setImage(ImageStopPressed, for: .highlighted)
toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Stop", comment: "Accessibility Label for the tab toolbar Stop button")
} else {
toolbar.stopReloadButton.setImage(ImageReload, for: .normal)
toolbar.stopReloadButton.setImage(ImageReloadPressed, for: .highlighted)
toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Reload", comment: "Accessibility Label for the tab toolbar Reload button")
}
}
}
fileprivate func setTintColor(_ color: UIColor, forButtons buttons: [UIButton]) {
buttons.forEach { $0.tintColor = color }
}
init(toolbar: TabToolbarProtocol) {
self.toolbar = toolbar
super.init()
toolbar.backButton.setImage(UIImage.templateImageNamed("bottomNav-back"), for: .normal)
toolbar.backButton.setImage(UIImage(named: "bottomNav-backEngaged"), for: .highlighted)
toolbar.backButton.accessibilityLabel = NSLocalizedString("Back", comment: "Accessibility label for the Back button in the tab toolbar.")
//toolbar.backButton.accessibilityHint = NSLocalizedString("Double tap and hold to open history", comment: "Accessibility hint, associated to the Back button in the tab toolbar, used by assistive technology to describe the result of a double tap.")
let longPressGestureBackButton = UILongPressGestureRecognizer(target: self, action: #selector(TabToolbarHelper.SELdidLongPressBack(_:)))
toolbar.backButton.addGestureRecognizer(longPressGestureBackButton)
toolbar.backButton.addTarget(self, action: #selector(TabToolbarHelper.SELdidClickBack), for: UIControlEvents.touchUpInside)
toolbar.forwardButton.setImage(UIImage.templateImageNamed("bottomNav-forward"), for: .normal)
toolbar.forwardButton.setImage(UIImage(named: "bottomNav-forwardEngaged"), for: .highlighted)
toolbar.forwardButton.accessibilityLabel = NSLocalizedString("Forward", comment: "Accessibility Label for the tab toolbar Forward button")
//toolbar.forwardButton.accessibilityHint = NSLocalizedString("Double tap and hold to open history", comment: "Accessibility hint, associated to the Back button in the tab toolbar, used by assistive technology to describe the result of a double tap.")
let longPressGestureForwardButton = UILongPressGestureRecognizer(target: self, action: #selector(TabToolbarHelper.SELdidLongPressForward(_:)))
toolbar.forwardButton.addGestureRecognizer(longPressGestureForwardButton)
toolbar.forwardButton.addTarget(self, action: #selector(TabToolbarHelper.SELdidClickForward), for: UIControlEvents.touchUpInside)
toolbar.stopReloadButton.setImage(UIImage.templateImageNamed("bottomNav-refresh"), for: .normal)
toolbar.stopReloadButton.setImage(UIImage(named: "bottomNav-refreshEngaged"), for: .highlighted)
toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Reload", comment: "Accessibility Label for the tab toolbar Reload button")
let longPressGestureStopReloadButton = UILongPressGestureRecognizer(target: self, action: #selector(TabToolbarHelper.SELdidLongPressStopReload(_:)))
toolbar.stopReloadButton.addGestureRecognizer(longPressGestureStopReloadButton)
toolbar.stopReloadButton.addTarget(self, action: #selector(TabToolbarHelper.SELdidClickStopReload), for: UIControlEvents.touchUpInside)
toolbar.shareButton.setImage(UIImage.templateImageNamed("bottomNav-send"), for: .normal)
toolbar.shareButton.setImage(UIImage(named: "bottomNav-sendEngaged"), for: .highlighted)
toolbar.shareButton.accessibilityLabel = NSLocalizedString("Share", comment: "Accessibility Label for the tab toolbar Share button")
toolbar.shareButton.addTarget(self, action: #selector(TabToolbarHelper.SELdidClickShare), for: UIControlEvents.touchUpInside)
toolbar.homePageButton.setImage(UIImage.templateImageNamed("menu-Home"), for: .normal)
toolbar.homePageButton.setImage(UIImage(named: "menu-Home-Engaged"), for: .highlighted)
toolbar.homePageButton.accessibilityLabel = NSLocalizedString("Toolbar.OpenHomePage.AccessibilityLabel", value: "Homepage", comment: "Accessibility Label for the tab toolbar Homepage button")
toolbar.homePageButton.addTarget(self, action: #selector(TabToolbarHelper.SELdidClickHomePage), for: UIControlEvents.touchUpInside)
toolbar.menuButton.contentMode = UIViewContentMode.center
toolbar.menuButton.setImage(UIImage.templateImageNamed("bottomNav-menu"), for: .normal)
toolbar.menuButton.accessibilityLabel = AppMenuConfiguration.MenuButtonAccessibilityLabel
toolbar.menuButton.addTarget(self, action: #selector(TabToolbarHelper.SELdidClickMenu), for: UIControlEvents.touchUpInside)
toolbar.menuButton.accessibilityIdentifier = "TabToolbar.menuButton"
setTintColor(buttonTintColor, forButtons: toolbar.actionButtons)
}
func SELdidClickBack() {
toolbar.tabToolbarDelegate?.tabToolbarDidPressBack(toolbar, button: toolbar.backButton)
}
func SELdidLongPressBack(_ recognizer: UILongPressGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.began {
toolbar.tabToolbarDelegate?.tabToolbarDidLongPressBack(toolbar, button: toolbar.backButton)
}
}
func SELdidClickShare() {
toolbar.tabToolbarDelegate?.tabToolbarDidPressShare(toolbar, button: toolbar.shareButton)
}
func SELdidClickForward() {
toolbar.tabToolbarDelegate?.tabToolbarDidPressForward(toolbar, button: toolbar.forwardButton)
}
func SELdidLongPressForward(_ recognizer: UILongPressGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.began {
toolbar.tabToolbarDelegate?.tabToolbarDidLongPressForward(toolbar, button: toolbar.forwardButton)
}
}
func SELdidClickBookmark() {
toolbar.tabToolbarDelegate?.tabToolbarDidPressBookmark(toolbar, button: toolbar.bookmarkButton)
}
func SELdidLongPressBookmark(_ recognizer: UILongPressGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.began {
toolbar.tabToolbarDelegate?.tabToolbarDidLongPressBookmark(toolbar, button: toolbar.bookmarkButton)
}
}
func SELdidClickMenu() {
toolbar.tabToolbarDelegate?.tabToolbarDidPressMenu(toolbar, button: toolbar.menuButton)
}
func SELdidClickStopReload() {
if loading {
toolbar.tabToolbarDelegate?.tabToolbarDidPressStop(toolbar, button: toolbar.stopReloadButton)
} else {
toolbar.tabToolbarDelegate?.tabToolbarDidPressReload(toolbar, button: toolbar.stopReloadButton)
}
}
func SELdidLongPressStopReload(_ recognizer: UILongPressGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.began && !loading {
toolbar.tabToolbarDelegate?.tabToolbarDidLongPressReload(toolbar, button: toolbar.stopReloadButton)
}
}
func SELdidClickHomePage() {
toolbar.tabToolbarDelegate?.tabToolbarDidPressHomePage(toolbar, button: toolbar.homePageButton)
}
func updateReloadStatus(_ isLoading: Bool) {
loading = isLoading
}
}
class TabToolbar: Toolbar, TabToolbarProtocol {
weak var tabToolbarDelegate: TabToolbarDelegate?
let shareButton: UIButton
let bookmarkButton: UIButton
let menuButton: UIButton
let forwardButton: UIButton
let backButton: UIButton
let stopReloadButton: UIButton
let homePageButton: UIButton
let actionButtons: [UIButton]
var helper: TabToolbarHelper?
static let Themes: [String: Theme] = {
var themes = [String: Theme]()
var theme = Theme()
theme.buttonTintColor = UIConstants.PrivateModeActionButtonTintColor
themes[Theme.PrivateMode] = theme
theme = Theme()
theme.buttonTintColor = UIColor.darkGray
themes[Theme.NormalMode] = theme
return themes
}()
// This has to be here since init() calls it
fileprivate override init(frame: CGRect) {
// And these have to be initialized in here or the compiler will get angry
backButton = UIButton()
backButton.accessibilityIdentifier = "TabToolbar.backButton"
forwardButton = UIButton()
forwardButton.accessibilityIdentifier = "TabToolbar.forwardButton"
stopReloadButton = UIButton()
stopReloadButton.accessibilityIdentifier = "TabToolbar.stopReloadButton"
shareButton = UIButton()
shareButton.accessibilityIdentifier = "TabToolbar.shareButton"
bookmarkButton = UIButton()
bookmarkButton.accessibilityIdentifier = "TabToolbar.bookmarkButton"
menuButton = UIButton()
menuButton.accessibilityIdentifier = "TabToolbar.menuButton"
homePageButton = UIButton()
menuButton.accessibilityIdentifier = "TabToolbar.homePageButton"
actionButtons = [backButton, forwardButton, menuButton, stopReloadButton, shareButton, homePageButton]
super.init(frame: frame)
self.helper = TabToolbarHelper(toolbar: self)
addButtons(backButton, forwardButton, menuButton, stopReloadButton, shareButton, homePageButton)
accessibilityNavigationStyle = .combined
accessibilityLabel = NSLocalizedString("Navigation Toolbar", comment: "Accessibility label for the navigation toolbar displayed at the bottom of the screen.")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateBackStatus(_ canGoBack: Bool) {
backButton.isEnabled = canGoBack
}
func updateForwardStatus(_ canGoForward: Bool) {
forwardButton.isEnabled = canGoForward
}
func updateBookmarkStatus(_ isBookmarked: Bool) {
bookmarkButton.isSelected = isBookmarked
}
func updateReloadStatus(_ isLoading: Bool) {
helper?.updateReloadStatus(isLoading)
}
func updatePageStatus(_ isWebPage: Bool) {
stopReloadButton.isEnabled = isWebPage
shareButton.isEnabled = isWebPage
}
override func draw(_ rect: CGRect) {
if let context = UIGraphicsGetCurrentContext() {
drawLine(context, start: CGPoint(x: 0, y: 0), end: CGPoint(x: frame.width, y: 0))
}
}
fileprivate func drawLine(_ context: CGContext, start: CGPoint, end: CGPoint) {
context.setStrokeColor(UIColor.black.withAlphaComponent(0.05).cgColor)
context.setLineWidth(2)
context.move(to: CGPoint(x: start.x, y: start.y))
context.addLine(to: CGPoint(x: end.x, y: end.y))
context.strokePath()
}
}
// MARK: UIAppearance
extension TabToolbar {
dynamic var actionButtonTintColor: UIColor? {
get { return helper?.buttonTintColor }
set {
guard let value = newValue else { return }
helper?.buttonTintColor = value
}
}
}
extension TabToolbar: Themeable {
func applyTheme(_ themeName: String) {
guard let theme = TabToolbar.Themes[themeName] else {
log.error("Unable to apply unknown theme \(themeName)")
return
}
actionButtonTintColor = theme.buttonTintColor!
}
}
extension TabToolbar: AppStateDelegate {
func appDidUpdateState(_ state: AppState) {
let showHomepage = !HomePageAccessors.isButtonInMenu(state)
homePageButton.removeFromSuperview()
shareButton.removeFromSuperview()
if showHomepage {
homePageButton.isEnabled = HomePageAccessors.isButtonEnabled(state)
addButtons(homePageButton)
} else {
addButtons(shareButton)
}
updateConstraints()
}
}
| mpl-2.0 |
gregttn/GTProgressBar | GTProgressBar/Classes/GTProgressBarCornerType.swift | 1 | 194 | //
// GTProgressBarCornerType.swift
// GTProgressBar
//
// Created by greg on 12/04/2018.
//
import Foundation
public enum GTProgressBarCornerType: Int {
case square
case rounded
}
| mit |
zjzsliyang/Potions | Paging/Paging/LinkedList.swift | 1 | 3797 | //
// LinkedList.swift
// Paging
//
// Created by Yang Li on 24/05/2017.
// Copyright © 2017 Yang Li. All rights reserved.
//
// Reference: https://hugotunius.se/2016/07/17/implementing-a-linked-list-in-swift.html
import Foundation
public class Node<T: Equatable> {
typealias NodeType = Node<T>
public let value: T
var next: NodeType? = nil
var previous: NodeType? = nil
public init(value: T) {
self.value = value
}
}
extension Node: CustomStringConvertible {
public var description: String {
get {
return "Node(\(value))"
}
}
}
public final class LinkedList<T: Equatable> {
public typealias NodeType = Node<T>
fileprivate var start: NodeType? {
didSet {
if end == nil {
end = start
}
}
}
fileprivate var end: NodeType? {
didSet {
if start == nil {
start = end
}
}
}
public fileprivate(set) var count: Int = 0
public var isEmpty: Bool {
get {
return count == 0
}
}
public init() {
}
public init<S: Sequence>(_ elements: S) where S.Iterator.Element == T {
for element in elements {
append(value: element)
}
}
}
extension LinkedList {
public func append(value: T) {
let previousEnd = end
end = NodeType(value: value)
end?.previous = previousEnd
previousEnd?.next = end
count += 1
}
}
extension LinkedList {
fileprivate func iterate(block: (_ node: NodeType, _ index: Int) throws -> NodeType?) rethrows -> NodeType? {
var node = start
var index = 0
while node != nil {
let result = try block(node!, index)
if result != nil {
return result
}
index += 1
node = node?.next
}
return nil
}
}
extension LinkedList {
public func nodeAt(index: Int) -> NodeType {
precondition(index >= 0 && index < count, "Index \(index) out of bounds")
let result = iterate {
if $1 == index {
return $0
}
return nil
}
return result!
}
public func valueAt(index: Int) -> T {
let node = nodeAt(index: index)
return node.value
}
}
extension LinkedList {
public func remove(node: NodeType) {
let nextNode = node.next
let previousNode = node.previous
if node === start && node === end {
start = nil
end = nil
} else if node === start {
start = node.next
} else if node === end {
end = node.previous
} else {
previousNode?.next = nextNode
nextNode?.previous = previousNode
}
count -= 1
assert(
(end != nil && start != nil && count >= 1) || (end == nil && start == nil && count == 0),
"Internal invariant not upheld at the end of remove"
)
}
public func remove(atIndex index: Int) {
precondition(index >= 0 && index < count, "Index \(index) out of bounds")
let result = iterate {
if $1 == index {
return $0
}
return nil
}
remove(node: result!)
}
}
public struct LinkedListIterator<T: Equatable>: IteratorProtocol {
public typealias Element = Node<T>
fileprivate var currentNode: Element?
fileprivate init(startNode: Element?) {
currentNode = startNode
}
public mutating func next() -> LinkedListIterator.Element? {
let node = currentNode
currentNode = currentNode?.next
return node
}
}
extension LinkedList: Sequence {
public typealias Iterator = LinkedListIterator<T>
public func makeIterator() -> LinkedList.Iterator {
return LinkedListIterator(startNode: start)
}
}
extension LinkedList {
func copy() -> LinkedList<T> {
let newList = LinkedList<T>()
for element in self {
newList.append(value: element.value)
}
return newList
}
}
| mit |
jspahrsummers/Pistachio | PistachioTests/LensSpec.swift | 1 | 6623 | //
// LensSpec.swift
// Pistachio
//
// Created by Robert Böhnke on 1/17/15.
// Copyright (c) 2015 Robert Böhnke. All rights reserved.
//
import Quick
import Nimble
import LlamaKit
import Pistachio
struct Inner: Equatable {
var count: Int
}
func == (lhs: Inner, rhs: Inner) -> Bool {
return lhs.count == rhs.count
}
struct Outer: Equatable {
var count: Int
var inner: Inner
init(count: Int = 0, inner: Inner = Inner(count: 0)) {
self.count = count
self.inner = inner
}
}
func == (lhs: Outer, rhs: Outer) -> Bool {
return lhs.count == rhs.count && lhs.inner == rhs.inner
}
struct OuterLenses {
static let count = Lens<Outer, Int>(get: { $0.count }, set: { (inout outer: Outer, count) in
outer.count = count
})
static let inner = Lens<Outer, Inner>(get: { $0.inner }, set: { (inout outer: Outer, inner) in
outer.inner = inner
})
}
struct InnerLenses {
static let count = Lens<Inner, Int>(get: { $0.count }, set: { (inout inner: Inner, count) in
inner.count = count
})
}
class LensSpec: QuickSpec {
override func spec() {
describe("A Lens") {
let example: Outer = Outer(count: 2)
let count = OuterLenses.count
it("should get values") {
expect(get(count, example)!).to(equal(2))
}
it("should set values") {
expect(set(count, example, 4)).to(equal(Outer(count: 4)))
}
it("should modify values") {
expect(mod(count, example, { $0 + 2 })).to(equal(Outer(count: 4)))
}
}
describe("A composed Lens") {
let example = Outer(count: 0, inner: Inner(count: 2))
let innerCount = OuterLenses.inner >>> InnerLenses.count
it("should get values") {
expect(get(innerCount, example)!).to(equal(2))
}
it("should set values") {
expect(set(innerCount, example, 4)).to(equal(Outer(count: 0, inner: Inner(count: 4))))
}
it("should modify values") {
expect(mod(innerCount, example, { $0 + 2 })).to(equal(Outer(count: 0, inner: Inner(count: 4))))
}
}
describe("Lifted lenses") {
context("for arrays") {
let inner = [
Inner(count: 1),
Inner(count: 2),
Inner(count: 3),
Inner(count: 4)
]
let lifted = lift(InnerLenses.count)
it("should get values") {
let result = get(lifted, inner)
expect(result).to(equal([ 1, 2, 3, 4 ]))
}
it("should set values") {
let result = set(lifted, inner, [ 2, 4, 6, 8 ])
expect(result).to(equal([
Inner(count: 2),
Inner(count: 4),
Inner(count: 6),
Inner(count: 8)
]))
}
it("should reduce the resulting array size accordingly") {
// Does this make sense?
let result = set(lifted, inner, [ 42 ])
expect(result).to(equal([
Inner(count: 42)
]))
}
}
context("for results") {
let inner = Inner(count: 5)
let error = NSError()
let lifted: Lens<Result<Inner, NSError>, Result<Int, NSError>> = lift(InnerLenses.count)
it("should get values") {
let result = get(lifted, success(inner))
expect(result.value).to(equal(5))
}
it("should return structure failures on get") {
let result = get(lifted, failure(error))
expect(result.error).to(beIdenticalTo(error))
}
it("should set values") {
let result = set(lifted, success(inner), success(3))
expect(result.value?.count).to(equal(3))
}
it("should return structure failures on set") {
let result = set(lifted, failure(error), success(3))
expect(result.error).to(beIdenticalTo(error))
}
it("should return value failures on set") {
let result = set(lifted, success(inner), failure(error))
expect(result.error).to(beIdenticalTo(error))
}
}
}
describe("Transformed lenses") {
let outer = Outer(count: 0)
let transformed = transform(lift(OuterLenses.count), ValueTransformers.string)
it("should get values") {
let result = get(transformed, success(outer))
expect(result.value).to(equal("0"))
}
it("should set values") {
let result = set(transformed, success(outer), success("2"))
expect(result.value?.count).to(equal(2))
}
}
describe("Split lenses") {
let outer = Outer(count: 2, inner: Inner(count: 4))
let inner = Inner(count: 9)
let both = OuterLenses.count *** InnerLenses.count
it("should get values") {
let result = get(both, (outer, inner))
expect(result.0).to(equal(2))
expect(result.1).to(equal(9))
}
it("should set values") {
let result = set(both, (outer, inner), (12, 34))
expect(result.0.count).to(equal(12))
expect(result.0.inner.count).to(equal(4))
expect(result.1.count).to(equal(34))
}
}
describe("Fanned out lenses") {
let example = Outer(count: 0, inner: Inner(count: 2))
let both = OuterLenses.count &&& (OuterLenses.inner >>> InnerLenses.count)
it("should get values") {
let result = get(both, example)
expect(result.0).to(equal(0))
expect(result.1).to(equal(2))
}
it("should set values") {
let result = set(both, example, (12, 34))
expect(result.count).to(equal(12))
expect(result.inner.count).to(equal(34))
}
}
}
}
| mit |
Appsaurus/Infinity | InfinitySample/Main1TableViewController.swift | 2 | 2085 | //
// Samples1TableViewController.swift
// InfinitySample
//
// Created by Danis on 15/12/22.
// Copyright © 2015年 danis. All rights reserved.
//
import UIKit
enum AnimatorType: Int, CustomStringConvertible{
case Default = 0
case GIF
case Circle
case Arrow
case Snake
case Spark
var description:String {
switch self {
case .Default:
return "Default"
case .GIF:
return "GIF"
case .Circle:
return "Circle"
case .Arrow:
return "Arrow"
case .Snake:
return "Snake"
case .Spark:
return "Spark"
}
}
}
class Main1TableViewController: UITableViewController {
var samples = [AnimatorType.Default,.GIF,.Circle,.Arrow,.Snake,.Spark]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return samples.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SampleCell", for: indexPath)
cell.textLabel?.text = samples[indexPath.row].description
if indexPath.row <= 1 {
cell.detailTextLabel?.text = "Built-In"
}else {
cell.detailTextLabel?.text = nil
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let sampleVC = AddSamplesTableViewController()
sampleVC.hidesBottomBarWhenPushed = true
sampleVC.type = self.samples[indexPath.row]
self.show(sampleVC, sender: self)
}
}
| mit |
stripe/stripe-ios | Stripe/STPPaymentMethod+BasicUI.swift | 1 | 2517 | //
// STPPaymentMethod+BasicUI.swift
// StripeiOS
//
// Created by David Estes on 6/30/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) import StripeCore
@_spi(STP) import StripePayments
@_spi(STP) import StripePaymentsUI
import UIKit
extension STPPaymentMethod: STPPaymentOption {
// MARK: - STPPaymentOption
@objc public var image: UIImage {
if type == .card, let card = card {
return STPImageLibrary.cardBrandImage(for: card.brand)
} else {
return STPImageLibrary.cardBrandImage(for: .unknown)
}
}
@objc public var templateImage: UIImage {
if type == .card, let card = card {
return STPImageLibrary.templatedBrandImage(for: card.brand)
} else {
return STPImageLibrary.templatedBrandImage(for: .unknown)
}
}
@objc public var label: String {
switch type {
case .card:
if let card = card {
let brand = STPCardBrandUtilities.stringFrom(card.brand)
return "\(brand ?? "") \(card.last4 ?? "")"
} else {
return STPCardBrandUtilities.stringFrom(.unknown) ?? ""
}
case .FPX:
if let fpx = fpx {
return STPFPXBank.stringFrom(STPFPXBank.brandFrom(fpx.bankIdentifierCode)) ?? ""
} else {
fallthrough
}
case .USBankAccount:
if let usBankAccount = usBankAccount {
return String(
format: String.Localized.bank_name_account_ending_in_last_4,
usBankAccount.bankName,
usBankAccount.last4
)
} else {
fallthrough
}
default:
return type.displayName
}
}
@objc public var isReusable: Bool {
switch type {
case .card, .link, .USBankAccount:
return true
case .alipay, // Careful! Revisit this if/when we support recurring Alipay
.AUBECSDebit,
.bacsDebit, .SEPADebit, .iDEAL, .FPX, .cardPresent, .giropay, .EPS, .payPal,
.przelewy24, .bancontact,
.OXXO, .sofort, .grabPay, .netBanking, .UPI, .afterpayClearpay, .blik,
.weChatPay, .boleto, .klarna, .linkInstantDebit, .affirm, // fall through
.unknown:
return false
@unknown default:
return false
}
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/01120-clang-codegen-codegenfunction-emitlvalueforfield.swift | 12 | 2403 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
}
b() {
}
protocol d {
}
}
}
func a: A, T) {
}
struct A {
let end = i()
func a<T : a = D>?) in 0)([0x31] = T, V, 3] as String)
enum b = {
enum a
return ")
enum S<H : String {
}
class B {
func c
enum B : [Int) {
protocol P {
return "a())
let foo as String) -> U)
extension String {
class A where T -> U) -> Any) in a {
func c, V>) {
let v: a {
}
return self.d.init(T: A> S(v: a {
protocol C {
}
protocol a {
class func ^(#object1, range.c, q:
}
}
case c(a(start: A, q:
self] {
[0x31] in
()
protocol b = {
}
}
}
return p: a {
}
func d, d: SequenceType> {
}
f = b> : Any, Any) {}
extension String = b
init(x()
}
struct B
convenience init()()
}
protocol c {
func b)
typealias f : ExtensibleCollectionType>(x, range.E == [Int
println(self.b {
return self.E
protocol A {
}
}
}
func c) {
typealias B
typealias B
class A where d
class A, T : c(T! {
func i<j : A> T>() { self.c] = A, b = { c
}
}
class B : c: A> {
return $0.Type) -> {
}
}
class a():
func b> {
}
extension Array {
struct c : Array<T>?) -> String {
}
}
enum A {
protocol a {
class a([self.b in
func e() {
let start = "\(i: a {
protocol B {
}
protocol a {
extension NSData {
protocol c {
return "
}
protocol b = B<T
protocol A {
case C
typealias B {
protocol P {
import Foundation
}
class d<d == b
}
}
var f : String = true {
func g, 3] {
let t: T.C> (z(range: [unowned self.startIndex)
let foo as [$0
func a
enum A = e(bytes: a {
enum A {
})
var d where B = i<T> Any) {
}
init() -> T : (c(T: b: Array) -> String {
protocol a {
}
extension A {
}
typealias g, U.Generator.<c<T>()
import Foundation
}
(h> String {
}
()
class a
typealias f = B
func f(a(")
A<Int>(z(a
struct S {
class func b> T>) -> Any) -> {
func f<b)
}
return { c, let h, a)
}
}
func compose<U>(Any, g<T>(AnyObject) + seq: e: () {
struct A {
case s: A {
}
class A = 1))
class c
}
func i> e: c> T>(s: a {}
println(f: T) -> {
}
}
class A? {
import Foundation
}
protocol d = e(T, f() -> String {
println(")
struct c: Bool], object2: A, e, length: start, T][c<T where T>) -> (".Type) -> {
}
println(n: String
}
S.e == []
typealias e : () {
}
class b
}
protocol B {
let f == g: Range<h : T] in
import Foundation
}
import Foundation
}
}
public var b, V, Bool) {
struct X.E
}
let foo as BooleanType, AnyObject, T : B<Q<h
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/20258-swift-sourcemanager-getmessage.swift | 11 | 240 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
h ( [ {
class A
{
let h {
protocol A {
extension String {
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/19884-swift-nominaltypedecl-computeinterfacetype.swift | 10 | 237 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class c<T where g:g
protocol B{
protocol c{}
protocol c:c
}
var d=c{ | mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/02540-swift-sourcemanager-getmessage.swift | 11 | 219 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol A {
{
}
class a {
let c {
{
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/27200-swift-abstractclosureexpr-setparams.swift | 4 | 240 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class S<T{func a<h{func b<T where h.g=a{}{(a{{{T{{{{{{{{{{{{let t=B<T{
| mit |
eurofurence/ef-app_ios | Packages/EurofurenceModel/Sources/EurofurenceModel/Public/Session/Services/RefreshService.swift | 1 | 513 | import Foundation
public enum RefreshServiceError: Equatable, Error {
case apiError
case conventionIdentifierMismatch
case collaborationError
}
public protocol RefreshService {
func add(_ observer: RefreshServiceObserver)
@discardableResult
func refreshLocalStore(completionHandler: @escaping (RefreshServiceError?) -> Void) -> Progress
}
public protocol RefreshServiceObserver {
func refreshServiceDidBeginRefreshing()
func refreshServiceDidFinishRefreshing()
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/17048-swift-metatypetype-get.swift | 11 | 219 | // 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 f<T {
struct A {
class func b(T.B)
var d = b
| mit |
PETERZer/SingularityIMClient-PeterZ | SingularityIMClient-PeterZDemo/SingularityIMClient/SingularityIMClient/ChatListModel.swift | 1 | 4895 | //
// ChatListModel.swift
// SingularityIMClient
//
// Created by apple on 1/14/16.
// Copyright © 2016 张勇. All rights reserved.
//
import UIKit
class ChatListModel: NSObject {
var _chat_session_id:String?
var _chat_session_type:String?
var _last_message:String?
var _last_message_id:String?
var _last_message_time:String?
var _last_message_type:String?
var _last_sender_id:String?
var _message_count:String?
var _target_id:String?
var _target_name:String?
var _target_online_status:String?
var _target_picture:String?
var chat_session_id:String?{
get{
if self._chat_session_id == nil {
print("_chat_session_id没有值")
return nil
}else {
return self._chat_session_id
}
}
set(newChatSID){
self._chat_session_id = newChatSID
}
}
var chat_session_type:String?{
get{
if self._chat_session_type == nil {
print("_chat_session_type没有值")
return nil
}else {
return self._chat_session_type
}
}
set(newChatSType){
self._chat_session_type = newChatSType
}
}
var last_message:String?{
get{
if self._last_message == nil {
print("_last_message没有值")
return nil
}else {
return self._last_message
}
}
set(newLastMessage){
self._last_message = newLastMessage
}
}
var last_message_id:String?{
get{
if self._last_message_id == nil {
print("_last_message_id没有值")
return nil
}else {
return self._last_message_id
}
}
set(newLastMessageId){
self._last_message_id = newLastMessageId
}
}
var last_message_time:String?{
get{
if self._last_message_time == nil {
print("_last_message_time没有值")
return nil
}else {
return self._last_message_time
}
}
set(newLastMessageTime){
self._last_message_time = newLastMessageTime
}
}
var last_message_type:String?{
get{
if self._last_message_type == nil {
print("_last_message_type没有值")
return nil
}else {
return self._last_message_type
}
}
set(newLastMessageType){
self._last_message_type = newLastMessageType
}
}
var last_sender_id:String?{
get{
if self._last_sender_id == nil {
print("_last_sender_id没有值")
return nil
}else {
return self._last_sender_id
}
}
set(newLasterSenderId){
self._last_sender_id = newLasterSenderId
}
}
var message_count:String?{
get{
if self._message_count == nil {
print("_message_count没有值")
return nil
}else {
return self._message_count
}
}
set(newMessageCount){
self._message_count = newMessageCount
}
}
var target_id:String?{
get{
if self._target_id == nil {
print("_target_id没有值")
return nil
}else {
return self._target_id
}
}
set(newTargetId){
self._target_id = newTargetId
}
}
var target_name:String?{
get{
if self._target_name == nil {
print("_target_name没有值")
return nil
}else {
return self._target_name
}
}
set(newTargetName){
self._target_name = newTargetName
}
}
var target_online_status:String?{
get{
if self._target_online_status == nil {
print("_target_online_status没有值")
return nil
}else {
return self._target_online_status
}
}
set(newTargetOS){
self._target_online_status = newTargetOS
}
}
var target_picture:String?{
get{
if self._target_picture == nil {
print("_target_picture没有值")
return nil
}else {
return self._target_picture
}
}
set(newTargetPicture){
self._target_picture = newTargetPicture
}
}
} | mit |
xiaoxionglaoshi/DNSwiftProject | DNSwiftProject/DNSwiftProject/Classes/Expend/DNExtensions/UIImageExtension.swift | 1 | 4477 | //
// UIImageExtension.swift
// DNSwiftProject
//
// Created by mainone on 16/12/20.
// Copyright © 2016年 wjn. All rights reserved.
//
import UIKit
extension UIImage {
// 压缩图片
public func compressImage(rate: CGFloat) -> Data? {
return UIImageJPEGRepresentation(self, rate)
}
// 返回图片大小 Bytes
public func getSizeAsBytes() -> Int {
return UIImageJPEGRepresentation(self, 1)?.count ?? 0
}
// 返回图片大小 Kilobytes
public func getSizeAsKilobytes() -> Int {
let sizeAsBytes = getSizeAsBytes()
return sizeAsBytes != 0 ? sizeAsBytes / 1024 : 0
}
// 裁剪图片大小
public func scaleTo(w: CGFloat, h: CGFloat) -> UIImage {
let newSize = CGSize(width: w, height: h)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
// 切圆角图片
public func roundCorners(_ cornerRadius: CGFloat) -> UIImage {
let w = self.size.width * self.scale
let h = self.size.height * self.scale
let rect = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(w), height: CGFloat(h))
UIGraphicsBeginImageContextWithOptions(CGSize(width: CGFloat(w), height: CGFloat(h)), false, 1.0)
UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip()
self.draw(in: rect)
let ret = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return ret
}
// 添加边框
public func apply(border: CGFloat, color: UIColor) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let width = self.cgImage?.width
let height = self.cgImage?.height
let bits = self.cgImage?.bitsPerComponent
let colorSpace = self.cgImage?.colorSpace
let bitmapInfo = self.cgImage?.bitmapInfo
let context = CGContext(data: nil, width: width!, height: height!, bitsPerComponent: bits!, bytesPerRow: 0, space: colorSpace!, bitmapInfo: (bitmapInfo?.rawValue)!)
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
context?.setStrokeColor(red: red, green: green, blue: blue, alpha: alpha)
context?.setLineWidth(border)
let rect = CGRect(x: 0, y: 0, width: size.width*scale, height: size.height*scale)
let inset = rect.insetBy(dx: border*scale, dy: border*scale)
context?.strokeEllipse(in: inset)
context?.draw(self.cgImage!, in: inset)
let image = UIImage(cgImage: (context?.makeImage()!)!)
UIGraphicsEndImageContext()
return image
}
// 使用颜色生成图片
public func withColor(_ tintColor: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: 0, y: self.size.height)
context?.scaleBy(x: 1.0, y: -1.0)
context?.setBlendMode(CGBlendMode.normal)
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) as CGRect
context?.clip(to: rect, mask: self.cgImage!)
tintColor.setFill()
context?.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()! as UIImage
UIGraphicsEndImageContext()
return newImage
}
// 返回链接的图片
public convenience init?(urlString: String) {
guard let url = URL(string: urlString) else {
self.init(data: Data())
return
}
guard let data = try? Data(contentsOf: url) else {
print("该链接没有有效的图片: \(urlString)")
self.init(data: Data())
return
}
self.init(data: data)
}
// 返回一个空图片
public class func blankImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 0.0)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
| apache-2.0 |
MaartenBrijker/project | project/Pods/SwiftyDropbox/Source/Users.swift | 5 | 27584 |
/* Autogenerated. Do not edit. */
import Foundation
/**
Datatypes and serializers for the users namespace
*/
public class Users {
/**
The amount of detail revealed about an account depends on the user being queried and the user making the query.
*/
public class Account: CustomStringConvertible {
/// The user's unique Dropbox ID.
public let accountId : String
/// Details of a user's name.
public let name : Users.Name
public init(accountId: String, name: Users.Name) {
stringValidator(minLength: 40, maxLength: 40)(value: accountId)
self.accountId = accountId
self.name = name
}
public var description : String {
return "\(prepareJSONForSerialization(AccountSerializer().serialize(self)))"
}
}
public class AccountSerializer: JSONSerializer {
public init() { }
public func serialize(value: Account) -> JSON {
let output = [
"account_id": Serialization._StringSerializer.serialize(value.accountId),
"name": Users.NameSerializer().serialize(value.name),
]
return .Dictionary(output)
}
public func deserialize(json: JSON) -> Account {
switch json {
case .Dictionary(let dict):
let accountId = Serialization._StringSerializer.deserialize(dict["account_id"] ?? .Null)
let name = Users.NameSerializer().deserialize(dict["name"] ?? .Null)
return Account(accountId: accountId, name: name)
default:
fatalError("Type error deserializing")
}
}
}
/**
What type of account this user has.
*/
public enum AccountType: CustomStringConvertible {
/**
The basic account type.
*/
case Basic
/**
The Dropbox Pro account type.
*/
case Pro
/**
The Dropbox Business account type.
*/
case Business
public var description : String {
return "\(prepareJSONForSerialization(AccountTypeSerializer().serialize(self)))"
}
}
public class AccountTypeSerializer: JSONSerializer {
public init() { }
public func serialize(value: AccountType) -> JSON {
switch value {
case .Basic:
var d = [String : JSON]()
d[".tag"] = .Str("basic")
return .Dictionary(d)
case .Pro:
var d = [String : JSON]()
d[".tag"] = .Str("pro")
return .Dictionary(d)
case .Business:
var d = [String : JSON]()
d[".tag"] = .Str("business")
return .Dictionary(d)
}
}
public func deserialize(json: JSON) -> AccountType {
switch json {
case .Dictionary(let d):
let tag = Serialization.getTag(d)
switch tag {
case "basic":
return AccountType.Basic
case "pro":
return AccountType.Pro
case "business":
return AccountType.Business
default:
fatalError("Unknown tag \(tag)")
}
default:
fatalError("Failed to deserialize")
}
}
}
/**
Basic information about any account.
*/
public class BasicAccount: Users.Account {
/// Whether this user is a teammate of the current user. If this account is the current user's account, then
/// this will be true.
public let isTeammate : Bool
public init(accountId: String, name: Users.Name, isTeammate: Bool) {
self.isTeammate = isTeammate
super.init(accountId: accountId, name: name)
}
public override var description : String {
return "\(prepareJSONForSerialization(BasicAccountSerializer().serialize(self)))"
}
}
public class BasicAccountSerializer: JSONSerializer {
public init() { }
public func serialize(value: BasicAccount) -> JSON {
let output = [
"account_id": Serialization._StringSerializer.serialize(value.accountId),
"name": Users.NameSerializer().serialize(value.name),
"is_teammate": Serialization._BoolSerializer.serialize(value.isTeammate),
]
return .Dictionary(output)
}
public func deserialize(json: JSON) -> BasicAccount {
switch json {
case .Dictionary(let dict):
let accountId = Serialization._StringSerializer.deserialize(dict["account_id"] ?? .Null)
let name = Users.NameSerializer().deserialize(dict["name"] ?? .Null)
let isTeammate = Serialization._BoolSerializer.deserialize(dict["is_teammate"] ?? .Null)
return BasicAccount(accountId: accountId, name: name, isTeammate: isTeammate)
default:
fatalError("Type error deserializing")
}
}
}
/**
Detailed information about the current user's account.
*/
public class FullAccount: Users.Account {
/// The user's e-mail address. Do not rely on this without checking the emailVerified field. Even then, it's
/// possible that the user has since lost access to their e-mail.
public let email : String
/// Whether the user has verified their e-mail address.
public let emailVerified : Bool
/// The user's two-letter country code, if available. Country codes are based on ISO 3166-1
/// http://en.wikipedia.org/wiki/ISO_3166-1.
public let country : String?
/// The language that the user specified. Locale tags will be IETF language tags
/// http://en.wikipedia.org/wiki/IETF_language_tag.
public let locale : String
/// The user's referral link https://www.dropbox.com/referrals.
public let referralLink : String
/// If this account is a member of a team, information about that team.
public let team : Users.Team?
/// Whether the user has a personal and work account. If the current account is personal, then team will always
/// be null, but isPaired will indicate if a work account is linked.
public let isPaired : Bool
/// What type of account this user has.
public let accountType : Users.AccountType
public init(accountId: String, name: Users.Name, email: String, emailVerified: Bool, locale: String, referralLink: String, isPaired: Bool, accountType: Users.AccountType, country: String? = nil, team: Users.Team? = nil) {
stringValidator()(value: email)
self.email = email
self.emailVerified = emailVerified
nullableValidator(stringValidator(minLength: 2, maxLength: 2))(value: country)
self.country = country
stringValidator(minLength: 2)(value: locale)
self.locale = locale
stringValidator()(value: referralLink)
self.referralLink = referralLink
self.team = team
self.isPaired = isPaired
self.accountType = accountType
super.init(accountId: accountId, name: name)
}
public override var description : String {
return "\(prepareJSONForSerialization(FullAccountSerializer().serialize(self)))"
}
}
public class FullAccountSerializer: JSONSerializer {
public init() { }
public func serialize(value: FullAccount) -> JSON {
let output = [
"account_id": Serialization._StringSerializer.serialize(value.accountId),
"name": Users.NameSerializer().serialize(value.name),
"email": Serialization._StringSerializer.serialize(value.email),
"email_verified": Serialization._BoolSerializer.serialize(value.emailVerified),
"locale": Serialization._StringSerializer.serialize(value.locale),
"referral_link": Serialization._StringSerializer.serialize(value.referralLink),
"is_paired": Serialization._BoolSerializer.serialize(value.isPaired),
"account_type": Users.AccountTypeSerializer().serialize(value.accountType),
"country": NullableSerializer(Serialization._StringSerializer).serialize(value.country),
"team": NullableSerializer(Users.TeamSerializer()).serialize(value.team),
]
return .Dictionary(output)
}
public func deserialize(json: JSON) -> FullAccount {
switch json {
case .Dictionary(let dict):
let accountId = Serialization._StringSerializer.deserialize(dict["account_id"] ?? .Null)
let name = Users.NameSerializer().deserialize(dict["name"] ?? .Null)
let email = Serialization._StringSerializer.deserialize(dict["email"] ?? .Null)
let emailVerified = Serialization._BoolSerializer.deserialize(dict["email_verified"] ?? .Null)
let locale = Serialization._StringSerializer.deserialize(dict["locale"] ?? .Null)
let referralLink = Serialization._StringSerializer.deserialize(dict["referral_link"] ?? .Null)
let isPaired = Serialization._BoolSerializer.deserialize(dict["is_paired"] ?? .Null)
let accountType = Users.AccountTypeSerializer().deserialize(dict["account_type"] ?? .Null)
let country = NullableSerializer(Serialization._StringSerializer).deserialize(dict["country"] ?? .Null)
let team = NullableSerializer(Users.TeamSerializer()).deserialize(dict["team"] ?? .Null)
return FullAccount(accountId: accountId, name: name, email: email, emailVerified: emailVerified, locale: locale, referralLink: referralLink, isPaired: isPaired, accountType: accountType, country: country, team: team)
default:
fatalError("Type error deserializing")
}
}
}
/**
The GetAccountArg struct
*/
public class GetAccountArg: CustomStringConvertible {
/// A user's account identifier.
public let accountId : String
public init(accountId: String) {
stringValidator(minLength: 40, maxLength: 40)(value: accountId)
self.accountId = accountId
}
public var description : String {
return "\(prepareJSONForSerialization(GetAccountArgSerializer().serialize(self)))"
}
}
public class GetAccountArgSerializer: JSONSerializer {
public init() { }
public func serialize(value: GetAccountArg) -> JSON {
let output = [
"account_id": Serialization._StringSerializer.serialize(value.accountId),
]
return .Dictionary(output)
}
public func deserialize(json: JSON) -> GetAccountArg {
switch json {
case .Dictionary(let dict):
let accountId = Serialization._StringSerializer.deserialize(dict["account_id"] ?? .Null)
return GetAccountArg(accountId: accountId)
default:
fatalError("Type error deserializing")
}
}
}
/**
The GetAccountBatchArg struct
*/
public class GetAccountBatchArg: CustomStringConvertible {
/// List of user account identifiers. Should not contain any duplicate account IDs.
public let accountIds : Array<String>
public init(accountIds: Array<String>) {
arrayValidator(minItems: 1, itemValidator: stringValidator(minLength: 40, maxLength: 40))(value: accountIds)
self.accountIds = accountIds
}
public var description : String {
return "\(prepareJSONForSerialization(GetAccountBatchArgSerializer().serialize(self)))"
}
}
public class GetAccountBatchArgSerializer: JSONSerializer {
public init() { }
public func serialize(value: GetAccountBatchArg) -> JSON {
let output = [
"account_ids": ArraySerializer(Serialization._StringSerializer).serialize(value.accountIds),
]
return .Dictionary(output)
}
public func deserialize(json: JSON) -> GetAccountBatchArg {
switch json {
case .Dictionary(let dict):
let accountIds = ArraySerializer(Serialization._StringSerializer).deserialize(dict["account_ids"] ?? .Null)
return GetAccountBatchArg(accountIds: accountIds)
default:
fatalError("Type error deserializing")
}
}
}
/**
The GetAccountBatchError union
*/
public enum GetAccountBatchError: CustomStringConvertible {
/**
The value is an account ID specified in accountIds in GetAccountBatchArg that does not exist.
*/
case NoAccount(String)
case Other
public var description : String {
return "\(prepareJSONForSerialization(GetAccountBatchErrorSerializer().serialize(self)))"
}
}
public class GetAccountBatchErrorSerializer: JSONSerializer {
public init() { }
public func serialize(value: GetAccountBatchError) -> JSON {
switch value {
case .NoAccount(let arg):
var d = ["no_account": Serialization._StringSerializer.serialize(arg)]
d[".tag"] = .Str("no_account")
return .Dictionary(d)
case .Other:
var d = [String : JSON]()
d[".tag"] = .Str("other")
return .Dictionary(d)
}
}
public func deserialize(json: JSON) -> GetAccountBatchError {
switch json {
case .Dictionary(let d):
let tag = Serialization.getTag(d)
switch tag {
case "no_account":
let v = Serialization._StringSerializer.deserialize(d["no_account"] ?? .Null)
return GetAccountBatchError.NoAccount(v)
case "other":
return GetAccountBatchError.Other
default:
return GetAccountBatchError.Other
}
default:
fatalError("Failed to deserialize")
}
}
}
/**
The GetAccountError union
*/
public enum GetAccountError: CustomStringConvertible {
/**
The specified accountId in GetAccountArg does not exist.
*/
case NoAccount
case Unknown
public var description : String {
return "\(prepareJSONForSerialization(GetAccountErrorSerializer().serialize(self)))"
}
}
public class GetAccountErrorSerializer: JSONSerializer {
public init() { }
public func serialize(value: GetAccountError) -> JSON {
switch value {
case .NoAccount:
var d = [String : JSON]()
d[".tag"] = .Str("no_account")
return .Dictionary(d)
case .Unknown:
var d = [String : JSON]()
d[".tag"] = .Str("unknown")
return .Dictionary(d)
}
}
public func deserialize(json: JSON) -> GetAccountError {
switch json {
case .Dictionary(let d):
let tag = Serialization.getTag(d)
switch tag {
case "no_account":
return GetAccountError.NoAccount
case "unknown":
return GetAccountError.Unknown
default:
return GetAccountError.Unknown
}
default:
fatalError("Failed to deserialize")
}
}
}
/**
The IndividualSpaceAllocation struct
*/
public class IndividualSpaceAllocation: CustomStringConvertible {
/// The total space allocated to the user's account (bytes).
public let allocated : UInt64
public init(allocated: UInt64) {
comparableValidator()(value: allocated)
self.allocated = allocated
}
public var description : String {
return "\(prepareJSONForSerialization(IndividualSpaceAllocationSerializer().serialize(self)))"
}
}
public class IndividualSpaceAllocationSerializer: JSONSerializer {
public init() { }
public func serialize(value: IndividualSpaceAllocation) -> JSON {
let output = [
"allocated": Serialization._UInt64Serializer.serialize(value.allocated),
]
return .Dictionary(output)
}
public func deserialize(json: JSON) -> IndividualSpaceAllocation {
switch json {
case .Dictionary(let dict):
let allocated = Serialization._UInt64Serializer.deserialize(dict["allocated"] ?? .Null)
return IndividualSpaceAllocation(allocated: allocated)
default:
fatalError("Type error deserializing")
}
}
}
/**
Representations for a person's name to assist with internationalization.
*/
public class Name: CustomStringConvertible {
/// Also known as a first name.
public let givenName : String
/// Also known as a last name or family name.
public let surname : String
/// Locale-dependent name. In the US, a person's familiar name is their givenName, but elsewhere, it could be
/// any combination of a person's givenName and surname.
public let familiarName : String
/// A name that can be used directly to represent the name of a user's Dropbox account.
public let displayName : String
public init(givenName: String, surname: String, familiarName: String, displayName: String) {
stringValidator()(value: givenName)
self.givenName = givenName
stringValidator()(value: surname)
self.surname = surname
stringValidator()(value: familiarName)
self.familiarName = familiarName
stringValidator()(value: displayName)
self.displayName = displayName
}
public var description : String {
return "\(prepareJSONForSerialization(NameSerializer().serialize(self)))"
}
}
public class NameSerializer: JSONSerializer {
public init() { }
public func serialize(value: Name) -> JSON {
let output = [
"given_name": Serialization._StringSerializer.serialize(value.givenName),
"surname": Serialization._StringSerializer.serialize(value.surname),
"familiar_name": Serialization._StringSerializer.serialize(value.familiarName),
"display_name": Serialization._StringSerializer.serialize(value.displayName),
]
return .Dictionary(output)
}
public func deserialize(json: JSON) -> Name {
switch json {
case .Dictionary(let dict):
let givenName = Serialization._StringSerializer.deserialize(dict["given_name"] ?? .Null)
let surname = Serialization._StringSerializer.deserialize(dict["surname"] ?? .Null)
let familiarName = Serialization._StringSerializer.deserialize(dict["familiar_name"] ?? .Null)
let displayName = Serialization._StringSerializer.deserialize(dict["display_name"] ?? .Null)
return Name(givenName: givenName, surname: surname, familiarName: familiarName, displayName: displayName)
default:
fatalError("Type error deserializing")
}
}
}
/**
Space is allocated differently based on the type of account.
*/
public enum SpaceAllocation: CustomStringConvertible {
/**
The user's space allocation applies only to their individual account.
*/
case Individual(Users.IndividualSpaceAllocation)
/**
The user shares space with other members of their team.
*/
case Team(Users.TeamSpaceAllocation)
case Other
public var description : String {
return "\(prepareJSONForSerialization(SpaceAllocationSerializer().serialize(self)))"
}
}
public class SpaceAllocationSerializer: JSONSerializer {
public init() { }
public func serialize(value: SpaceAllocation) -> JSON {
switch value {
case .Individual(let arg):
var d = Serialization.getFields(Users.IndividualSpaceAllocationSerializer().serialize(arg))
d[".tag"] = .Str("individual")
return .Dictionary(d)
case .Team(let arg):
var d = Serialization.getFields(Users.TeamSpaceAllocationSerializer().serialize(arg))
d[".tag"] = .Str("team")
return .Dictionary(d)
case .Other:
var d = [String : JSON]()
d[".tag"] = .Str("other")
return .Dictionary(d)
}
}
public func deserialize(json: JSON) -> SpaceAllocation {
switch json {
case .Dictionary(let d):
let tag = Serialization.getTag(d)
switch tag {
case "individual":
let v = Users.IndividualSpaceAllocationSerializer().deserialize(json)
return SpaceAllocation.Individual(v)
case "team":
let v = Users.TeamSpaceAllocationSerializer().deserialize(json)
return SpaceAllocation.Team(v)
case "other":
return SpaceAllocation.Other
default:
return SpaceAllocation.Other
}
default:
fatalError("Failed to deserialize")
}
}
}
/**
Information about a user's space usage and quota.
*/
public class SpaceUsage: CustomStringConvertible {
/// The user's total space usage (bytes).
public let used : UInt64
/// The user's space allocation.
public let allocation : Users.SpaceAllocation
public init(used: UInt64, allocation: Users.SpaceAllocation) {
comparableValidator()(value: used)
self.used = used
self.allocation = allocation
}
public var description : String {
return "\(prepareJSONForSerialization(SpaceUsageSerializer().serialize(self)))"
}
}
public class SpaceUsageSerializer: JSONSerializer {
public init() { }
public func serialize(value: SpaceUsage) -> JSON {
let output = [
"used": Serialization._UInt64Serializer.serialize(value.used),
"allocation": Users.SpaceAllocationSerializer().serialize(value.allocation),
]
return .Dictionary(output)
}
public func deserialize(json: JSON) -> SpaceUsage {
switch json {
case .Dictionary(let dict):
let used = Serialization._UInt64Serializer.deserialize(dict["used"] ?? .Null)
let allocation = Users.SpaceAllocationSerializer().deserialize(dict["allocation"] ?? .Null)
return SpaceUsage(used: used, allocation: allocation)
default:
fatalError("Type error deserializing")
}
}
}
/**
Information about a team.
*/
public class Team: CustomStringConvertible {
/// The team's unique ID.
public let id : String
/// The name of the team.
public let name : String
public init(id: String, name: String) {
stringValidator()(value: id)
self.id = id
stringValidator()(value: name)
self.name = name
}
public var description : String {
return "\(prepareJSONForSerialization(TeamSerializer().serialize(self)))"
}
}
public class TeamSerializer: JSONSerializer {
public init() { }
public func serialize(value: Team) -> JSON {
let output = [
"id": Serialization._StringSerializer.serialize(value.id),
"name": Serialization._StringSerializer.serialize(value.name),
]
return .Dictionary(output)
}
public func deserialize(json: JSON) -> Team {
switch json {
case .Dictionary(let dict):
let id = Serialization._StringSerializer.deserialize(dict["id"] ?? .Null)
let name = Serialization._StringSerializer.deserialize(dict["name"] ?? .Null)
return Team(id: id, name: name)
default:
fatalError("Type error deserializing")
}
}
}
/**
The TeamSpaceAllocation struct
*/
public class TeamSpaceAllocation: CustomStringConvertible {
/// The total space currently used by the user's team (bytes).
public let used : UInt64
/// The total space allocated to the user's team (bytes).
public let allocated : UInt64
public init(used: UInt64, allocated: UInt64) {
comparableValidator()(value: used)
self.used = used
comparableValidator()(value: allocated)
self.allocated = allocated
}
public var description : String {
return "\(prepareJSONForSerialization(TeamSpaceAllocationSerializer().serialize(self)))"
}
}
public class TeamSpaceAllocationSerializer: JSONSerializer {
public init() { }
public func serialize(value: TeamSpaceAllocation) -> JSON {
let output = [
"used": Serialization._UInt64Serializer.serialize(value.used),
"allocated": Serialization._UInt64Serializer.serialize(value.allocated),
]
return .Dictionary(output)
}
public func deserialize(json: JSON) -> TeamSpaceAllocation {
switch json {
case .Dictionary(let dict):
let used = Serialization._UInt64Serializer.deserialize(dict["used"] ?? .Null)
let allocated = Serialization._UInt64Serializer.deserialize(dict["allocated"] ?? .Null)
return TeamSpaceAllocation(used: used, allocated: allocated)
default:
fatalError("Type error deserializing")
}
}
}
}
| apache-2.0 |
DavadDi/flatbuffers | swift/Sources/FlatBuffers/Table.swift | 1 | 6006 | /*
* Copyright 2021 Google Inc. 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
public struct Table {
public private(set) var bb: ByteBuffer
public private(set) var postion: Int32
public init(bb: ByteBuffer, position: Int32 = 0) {
guard isLitteEndian else {
fatalError("Reading/Writing a buffer in big endian machine is not supported on swift")
}
self.bb = bb
postion = position
}
public func offset(_ o: Int32) -> Int32 {
let vtable = postion - bb.read(def: Int32.self, position: Int(postion))
return o < bb.read(def: VOffset.self, position: Int(vtable)) ? Int32(bb.read(
def: Int16.self,
position: Int(vtable + o))) : 0
}
public func indirect(_ o: Int32) -> Int32 { o + bb.read(def: Int32.self, position: Int(o)) }
/// String reads from the buffer with respect to position of the current table.
/// - Parameter offset: Offset of the string
public func string(at offset: Int32) -> String? {
directString(at: offset + postion)
}
/// Direct string reads from the buffer disregarding the position of the table.
/// It would be preferable to use string unless the current position of the table is not needed
/// - Parameter offset: Offset of the string
public func directString(at offset: Int32) -> String? {
var offset = offset
offset += bb.read(def: Int32.self, position: Int(offset))
let count = bb.read(def: Int32.self, position: Int(offset))
let position = offset + Int32(MemoryLayout<Int32>.size)
return bb.readString(at: position, count: count)
}
/// Reads from the buffer with respect to the position in the table.
/// - Parameters:
/// - type: Type of Element that needs to be read from the buffer
/// - o: Offset of the Element
public func readBuffer<T>(of type: T.Type, at o: Int32) -> T {
directRead(of: T.self, offset: o + postion)
}
/// Reads from the buffer disregarding the position of the table.
/// It would be used when reading from an
/// ```
/// let offset = __t.offset(10)
/// //Only used when the we already know what is the
/// // position in the table since __t.vector(at:)
/// // returns the index with respect to the position
/// __t.directRead(of: Byte.self,
/// offset: __t.vector(at: offset) + index * 1)
/// ```
/// - Parameters:
/// - type: Type of Element that needs to be read from the buffer
/// - o: Offset of the Element
public func directRead<T>(of type: T.Type, offset o: Int32) -> T {
let r = bb.read(def: T.self, position: Int(o))
return r
}
public func union<T: FlatBufferObject>(_ o: Int32) -> T {
let o = o + postion
return directUnion(o)
}
public func directUnion<T: FlatBufferObject>(_ o: Int32) -> T {
T.init(bb, o: o + bb.read(def: Int32.self, position: Int(o)))
}
public func getVector<T>(at off: Int32) -> [T]? {
let o = offset(off)
guard o != 0 else { return nil }
return bb.readSlice(index: vector(at: o), count: vector(count: o))
}
/// Vector count gets the count of Elements within the array
/// - Parameter o: start offset of the vector
/// - returns: Count of elements
public func vector(count o: Int32) -> Int32 {
var o = o
o += postion
o += bb.read(def: Int32.self, position: Int(o))
return bb.read(def: Int32.self, position: Int(o))
}
/// Vector start index in the buffer
/// - Parameter o:start offset of the vector
/// - returns: the start index of the vector
public func vector(at o: Int32) -> Int32 {
var o = o
o += postion
return o + bb.read(def: Int32.self, position: Int(o)) + 4
}
}
extension Table {
static public func indirect(_ o: Int32, _ fbb: ByteBuffer) -> Int32 { o + fbb.read(
def: Int32.self,
position: Int(o)) }
static public func offset(_ o: Int32, vOffset: Int32, fbb: ByteBuffer) -> Int32 {
let vTable = Int32(fbb.capacity) - o
return vTable + Int32(fbb.read(
def: Int16.self,
position: Int(vTable + vOffset - fbb.read(def: Int32.self, position: Int(vTable)))))
}
static public func compare(_ off1: Int32, _ off2: Int32, fbb: ByteBuffer) -> Int32 {
let memorySize = Int32(MemoryLayout<Int32>.size)
let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1))
let _off2 = off2 + fbb.read(def: Int32.self, position: Int(off2))
let len1 = fbb.read(def: Int32.self, position: Int(_off1))
let len2 = fbb.read(def: Int32.self, position: Int(_off2))
let startPos1 = _off1 + memorySize
let startPos2 = _off2 + memorySize
let minValue = min(len1, len2)
for i in 0...minValue {
let b1 = fbb.read(def: Int8.self, position: Int(i + startPos1))
let b2 = fbb.read(def: Int8.self, position: Int(i + startPos2))
if b1 != b2 {
return Int32(b2 - b1)
}
}
return len1 - len2
}
static public func compare(_ off1: Int32, _ key: [Byte], fbb: ByteBuffer) -> Int32 {
let memorySize = Int32(MemoryLayout<Int32>.size)
let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1))
let len1 = fbb.read(def: Int32.self, position: Int(_off1))
let len2 = Int32(key.count)
let startPos1 = _off1 + memorySize
let minValue = min(len1, len2)
for i in 0..<minValue {
let b = fbb.read(def: Int8.self, position: Int(i + startPos1))
let byte = key[Int(i)]
if b != byte {
return Int32(b - Int8(byte))
}
}
return len1 - len2
}
}
| apache-2.0 |
nkskalyan/ganesh-yrg | EcoKitchen-iOS/EcoKitcheniOSHackathonTests/EcoKitcheniOSHackathonTests.swift | 1 | 1011 | //
// EcoKitcheniOSHackathonTests.swift
// EcoKitcheniOSHackathonTests
//
// Created by mh53653 on 11/12/16.
// Copyright © 2016 madan. All rights reserved.
//
import XCTest
@testable import EcoKitcheniOS
class EcoKitcheniOSHackathonTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| apache-2.0 |
paulotam/SportsFaceOverlay | SportsFaceOverlay/OverlayCellType.swift | 1 | 260 | //
// OverlayCellType.swift
// SportsFaceOverlay
//
// Created by Paulo Tam on 2/06/2016.
// Copyright © 2016 Paulo Tam. All rights reserved.
//
protocol OverlayCellType {
var title: String? { get set }
var icon: UIImage? { get set }
}
import UIKit
| mit |
kaojohnny/CoreStore | Sources/Fetching and Querying/Concrete Clauses/GroupBy.swift | 1 | 3108 | //
// GroupBy.swift
// CoreStore
//
// Copyright © 2015 John Rommel Estropia
//
// 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 CoreData
// MARK: - GroupBy
/**
The `GroupBy` clause specifies that the result of a query be grouped accoording to the specified key path.
*/
public struct GroupBy: QueryClause, Hashable {
/**
The list of key path strings to group results with
*/
public let keyPaths: [KeyPath]
/**
Initializes a `GroupBy` clause with an empty list of key path strings
*/
public init() {
self.init([])
}
/**
Initializes a `GroupBy` clause with a list of key path strings
- parameter keyPath: a key path string to group results with
- parameter keyPaths: a series of key path strings to group results with
*/
public init(_ keyPath: KeyPath, _ keyPaths: KeyPath...) {
self.init([keyPath] + keyPaths)
}
/**
Initializes a `GroupBy` clause with a list of key path strings
- parameter keyPaths: a list of key path strings to group results with
*/
public init(_ keyPaths: [KeyPath]) {
self.keyPaths = keyPaths
}
// MARK: QueryClause
public func applyToFetchRequest(fetchRequest: NSFetchRequest) {
if let keyPaths = fetchRequest.propertiesToGroupBy as? [String] where keyPaths != self.keyPaths {
CoreStore.log(
.Warning,
message: "An existing \"propertiesToGroupBy\" for the \(cs_typeName(NSFetchRequest)) was overwritten by \(cs_typeName(self)) query clause."
)
}
fetchRequest.propertiesToGroupBy = self.keyPaths
}
// MARK: Hashable
public var hashValue: Int {
return (self.keyPaths as NSArray).hashValue
}
}
// MARK: - GroupBy: Equatable
@warn_unused_result
public func == (lhs: GroupBy, rhs: GroupBy) -> Bool {
return lhs.keyPaths == rhs.keyPaths
}
| mit |
apple/swift | validation-test/stdlib/StringWordBreaking.swift | 5 | 3460 | // RUN: %empty-directory(%t)
// RUN: %target-run-stdlib-swift %S/Inputs/
// REQUIRES: executable_test
// REQUIRES: objc_interop
// REQUIRES: optimized_stdlib
@_spi(_Unicode)
import Swift
import StdlibUnittest
import StdlibUnicodeUnittest
import Foundation
let StringWordBreaking = TestSuite("StringWordBreaking")
// FIXME: Reenable once we figure out what to do with WordView
// @available(SwiftStdlib 5.7, *)
// extension String._WordView {
// var backwardsCount: Int {
// var c = 0
// var index = endIndex
// while index != startIndex {
// c += 1
// formIndex(before: &index)
// }
// return c
// }
// }
extension String {
@available(SwiftStdlib 5.7, *)
var _words: [String] {
var result: [String] = []
var i = startIndex
while i < endIndex {
let start = i
let end = _wordIndex(after: i)
let substr = self[start ..< end]
result.append(String(substr))
i = end
}
return result
}
@available(SwiftStdlib 5.7, *)
var _wordsBackwards: [String] {
var result: [String] = []
var i = endIndex
while i > startIndex {
let end = i
let start = _wordIndex(before: i)
let substr = self[start ..< end]
result.append(String(substr))
i = start
}
return result
}
}
if #available(SwiftStdlib 5.7, *) {
StringWordBreaking.test("word breaking") {
for wordBreakTest in wordBreakTests {
expectEqual(
wordBreakTest.1,
wordBreakTest.0._words,
"string: \(String(reflecting: wordBreakTest.0))")
expectEqual(
wordBreakTest.1.reversed(),
wordBreakTest.0._wordsBackwards,
"string: \(String(reflecting: wordBreakTest.0))")
}
}
}
// The most simple subclass of NSString that CoreFoundation does not know
// about.
class NonContiguousNSString : NSString {
required init(coder aDecoder: NSCoder) {
fatalError("don't call this initializer")
}
required init(itemProviderData data: Data, typeIdentifier: String) throws {
fatalError("don't call this initializer")
}
override init() {
_value = []
super.init()
}
init(_ value: [UInt16]) {
_value = value
super.init()
}
@objc(copyWithZone:) override func copy(with zone: NSZone?) -> Any {
// Ensure that copying this string produces a class that CoreFoundation
// does not know about.
return self
}
@objc override var length: Int {
return _value.count
}
@objc override func character(at index: Int) -> unichar {
return _value[index]
}
var _value: [UInt16]
}
extension _StringGuts {
@_silgen_name("$ss11_StringGutsV9isForeignSbvg")
func _isForeign() -> Bool
}
func getUTF16Array(from string: String) -> [UInt16] {
var result: [UInt16] = []
for cp in string.utf16 {
result.append(cp)
}
return result
}
if #available(SwiftStdlib 5.7, *) {
StringWordBreaking.test("word breaking foreign") {
for wordBreakTest in wordBreakTests {
let foreignTest = NonContiguousNSString(
getUTF16Array(from: wordBreakTest.0)
)
let test = foreignTest as String
expectTrue(test._guts._isForeign())
expectEqual(
wordBreakTest.1,
test._words,
"string: \(String(reflecting: wordBreakTest.0))")
expectEqual(
wordBreakTest.1.reversed(),
test._wordsBackwards,
"string: \(String(reflecting: wordBreakTest.0))")
}
}
}
runAllTests()
| apache-2.0 |
jbennett/Issues | IssuesKit/AddAccountCoordinator.swift | 1 | 1252 | //
// AddAccountCoordinator.swift
// Issues
//
// Created by Jonathan Bennett on 2015-12-22.
// Copyright © 2015 Jonathan Bennett. All rights reserved.
//
import Foundation
public class AddAccountCoordinator: Coordinator {
let containerViewController: UINavigationController
public init() {
containerViewController = UINavigationController()
}
public func start(presentationContext: PresentationContext) {
let serviceListViewController = ServiceListViewController.fromStoryboard()
serviceListViewController.delegate = self
containerViewController.showViewController(serviceListViewController, sender: nil)
presentationContext.presentViewController(containerViewController, containerPreferrance: .None)
}
}
extension AddAccountCoordinator: ServiceListViewControllerDelegate {
public func serviceList(serviceListViewController: ServiceListViewController, didSelectService service: TrackingService) {
let loginViewController = ServiceLoginViewControllerFactory().viewControllerForService(service)
containerViewController.showViewController(loginViewController, sender: nil)
}
public func serviceListDidCancel(serviceListViewController: ServiceListViewController) {
print("cancelled")
}
}
| mit |
ben-ng/swift | validation-test/compiler_crashers_fixed/26547-swift-sourcefile-lookupcache-lookupvalue.swift | 1 | 465 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class a<d where g:A{enum S<U:Bool
class b{
class C<T{class A{let:A
| apache-2.0 |
ivygulch/IVGAppContainer | IVGAppContainer/source/service/UserDefaultsService.swift | 1 | 2973 | //
// UserDefaultsService.swift
// IVGAppContainer
//
// Created by Douglas Sjoquist on 3/21/16.
// Copyright © 2016 Ivy Gulch LLC. All rights reserved.
//
import Foundation
public protocol UserDefaultsServiceType {
func value<T>(_ key: String, valueType: T.Type) -> T?
func setValue<T>(_ value: T, forKey key: String)
func removeValueForKey(_ key: String)
func register(defaults: [String: Any])
}
public class UserDefaultsService: UserDefaultsServiceType {
public convenience init(container: ApplicationContainerType) {
self.init(container: container, userDefaults: UserDefaults.standard)
}
public init(container: ApplicationContainerType, userDefaults: UserDefaults) {
self.container = container
self.userDefaults = userDefaults
}
public func value<T>(_ key: String, valueType: T.Type) -> T? {
if T.self == String.self {
return userDefaults.string(forKey: key) as! T?
} else if T.self == Int.self {
return userDefaults.integer(forKey: key) as? T
} else if T.self == Float.self {
return userDefaults.float(forKey: key) as? T
} else if T.self == Double.self {
return userDefaults.double(forKey: key) as? T
} else if T.self == Bool.self {
return userDefaults.bool(forKey: key) as? T
} else if T.self == URL.self {
return userDefaults.url(forKey: key) as? T
} else if T.self == Date.self {
if userDefaults.object(forKey: key) == nil {
return nil
}
let timeInterval = userDefaults.double(forKey: key) as Double
return Date(timeIntervalSinceReferenceDate: timeInterval) as? T
}
return nil
}
public func setValue<T>(_ value: T, forKey key: String) {
if let value = value as? String {
userDefaults.set(value, forKey: key)
} else if let value = value as? Int {
userDefaults.set(value, forKey: key)
} else if let value = value as? Float {
userDefaults.set(value, forKey: key)
} else if let value = value as? Double {
userDefaults.set(value, forKey: key)
} else if let value = value as? Bool {
userDefaults.set(value, forKey: key)
} else if let value = value as? URL {
userDefaults.set(value, forKey: key)
} else if let value = value as? Date {
userDefaults.set(value.timeIntervalSinceReferenceDate, forKey: key)
}
}
public func removeValueForKey(_ key: String) {
userDefaults.removeObject(forKey: key)
}
public func willResignActive() {
userDefaults.synchronize()
}
public func register(defaults: [String: Any]) {
userDefaults.register(defaults: defaults)
}
// MARK: private variables
private let container: ApplicationContainerType
private let userDefaults: UserDefaults
}
| mit |
ben-ng/swift | validation-test/compiler_crashers_fixed/02134-swift-constraints-constraintsystem-matchtypes.swift | 1 | 829 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
extension String {
typealias f = { c
func b[")
var b = d(c = [c(Any) -> a {
}
self] = {
class B : A {
}
return {
}
}
protocol a {
deinit {
}
class A, let d(Any)] == [T : a {
}
func e: S<T>Bool]
enum B {
let h == B<d, b {
}
}
struct Q<(self.startIndex)) -> {
for b : U : b<T -> : Array<Q<T> String {
public subscript () {
class func f<j : d {
}
}
}
}
}
struct c: Any, T -> String {
}
protocol P {
A> U, Any) -> {
}
}
struct c(f: b>
| apache-2.0 |
debugsquad/nubecero | nubecero/View/Store/VStore.swift | 1 | 8771 | import UIKit
class VStore:UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
private weak var controller:CStore!
private weak var viewSpinner:VSpinner?
private weak var collectionView:UICollectionView!
private let kHeaderHeight:CGFloat = 150
private let kFooterHeight:CGFloat = 70
private let kInterLine:CGFloat = 1
private let kCollectionBottom:CGFloat = 10
convenience init(controller:CStore)
{
self.init()
clipsToBounds = true
backgroundColor = UIColor.background
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let barHeight:CGFloat = controller.parentController.viewParent.kBarHeight
let viewSpinner:VSpinner = VSpinner()
self.viewSpinner = viewSpinner
let flow:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
flow.headerReferenceSize = CGSize(width:0, height:kHeaderHeight)
flow.minimumLineSpacing = kInterLine
flow.minimumInteritemSpacing = 0
flow.scrollDirection = UICollectionViewScrollDirection.vertical
flow.sectionInset = UIEdgeInsets(top:kInterLine, left:0, bottom:kCollectionBottom, right:0)
let collectionView:UICollectionView = UICollectionView(frame:CGRect.zero, collectionViewLayout:flow)
collectionView.isHidden = true
collectionView.clipsToBounds = true
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = UIColor.clear
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.alwaysBounceVertical = true
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(
VStoreCellNotAvailable.self,
forCellWithReuseIdentifier:
VStoreCellNotAvailable.reusableIdentifier)
collectionView.register(
VStoreCellDeferred.self,
forCellWithReuseIdentifier:
VStoreCellDeferred.reusableIdentifier)
collectionView.register(
VStoreCellNew.self,
forCellWithReuseIdentifier:
VStoreCellNew.reusableIdentifier)
collectionView.register(
VStoreCellPurchased.self,
forCellWithReuseIdentifier:
VStoreCellPurchased.reusableIdentifier)
collectionView.register(
VStoreCellPurchasing.self,
forCellWithReuseIdentifier:
VStoreCellPurchasing.reusableIdentifier)
collectionView.register(
VStoreHeader.self,
forSupplementaryViewOfKind:UICollectionElementKindSectionHeader,
withReuseIdentifier:
VStoreHeader.reusableIdentifier)
collectionView.register(
VStoreFooter.self,
forSupplementaryViewOfKind:UICollectionElementKindSectionFooter,
withReuseIdentifier:
VStoreFooter.reusableIdentifier)
self.collectionView = collectionView
addSubview(collectionView)
addSubview(viewSpinner)
let views:[String:UIView] = [
"viewSpinner":viewSpinner,
"collectionView":collectionView]
let metrics:[String:CGFloat] = [
"barHeight":barHeight]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[viewSpinner]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[collectionView]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-(barHeight)-[viewSpinner]-0-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-(barHeight)-[collectionView]-0-|",
options:[],
metrics:metrics,
views:views))
}
override func layoutSubviews()
{
collectionView.collectionViewLayout.invalidateLayout()
super.layoutSubviews()
}
//MARK: private
private func modelAtIndex(index:IndexPath) -> MStoreItem
{
let itemId:MStore.PurchaseId = controller.model.references[index.section]
let item:MStoreItem = controller.model.mapItems[itemId]!
return item
}
//MARK: public
func refreshStore()
{
DispatchQueue.main.async
{ [weak self] in
self?.viewSpinner?.removeFromSuperview()
self?.collectionView.reloadData()
self?.collectionView.isHidden = false
guard
let errorMessage:String = self?.controller.model.error
else
{
return
}
VAlert.message(message:errorMessage)
}
}
//MARK: collection delegate
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, referenceSizeForFooterInSection section:Int) -> CGSize
{
let indexPath:IndexPath = IndexPath(item:0, section:section)
let item:MStoreItem = modelAtIndex(index:indexPath)
let size:CGSize
if item.status?.restorable == true
{
size = CGSize(width:0, height:kFooterHeight)
}
else
{
size = CGSize.zero
}
return size
}
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize
{
let item:MStoreItem = modelAtIndex(index:indexPath)
let cellHeight:CGFloat = item.status!.cellHeight
let width:CGFloat = collectionView.bounds.maxX
let size:CGSize = CGSize(width:width, height:cellHeight)
return size
}
func numberOfSections(in collectionView:UICollectionView) -> Int
{
let count:Int = controller.model.references.count
return count
}
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int
{
let indexPath:IndexPath = IndexPath(item:0, section:section)
let item:MStoreItem = modelAtIndex(index:indexPath)
guard
let _:MStoreItemStatus = item.status
else
{
return 0
}
return 1
}
func collectionView(_ collectionView:UICollectionView, viewForSupplementaryElementOfKind kind:String, at indexPath:IndexPath) -> UICollectionReusableView
{
let reusable:UICollectionReusableView
if kind == UICollectionElementKindSectionHeader
{
let item:MStoreItem = modelAtIndex(index:indexPath)
let header:VStoreHeader = collectionView.dequeueReusableSupplementaryView(
ofKind:kind,
withReuseIdentifier:
VStoreHeader.reusableIdentifier,
for:indexPath) as! VStoreHeader
header.config(model:item)
reusable = header
}
else
{
let footer:VStoreFooter = collectionView.dequeueReusableSupplementaryView(
ofKind:kind,
withReuseIdentifier:
VStoreFooter.reusableIdentifier,
for:indexPath) as! VStoreFooter
footer.config(controller:controller)
reusable = footer
}
return reusable
}
func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
{
let item:MStoreItem = modelAtIndex(index:indexPath)
let reusableIdentifier:String = item.status!.reusableIdentifier
let cell:VStoreCell = collectionView.dequeueReusableCell(
withReuseIdentifier:
reusableIdentifier,
for:indexPath) as! VStoreCell
cell.config(controller:controller, model:item)
return cell
}
func collectionView(_ collectionView:UICollectionView, shouldSelectItemAt indexPath:IndexPath) -> Bool
{
return false
}
func collectionView(_ collectionView:UICollectionView, shouldHighlightItemAt indexPath:IndexPath) -> Bool
{
return false
}
}
| mit |
KyoheiG3/RxSwift | RxExample/RxExample/Examples/GitHubSignup/UsingVanillaObservables/GitHubSignupViewController1.swift | 8 | 3739 | //
// GitHubSignupViewController1.swift
// RxExample
//
// Created by Krunoslav Zaher on 4/25/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
class GitHubSignupViewController1 : ViewController {
@IBOutlet weak var usernameOutlet: UITextField!
@IBOutlet weak var usernameValidationOutlet: UILabel!
@IBOutlet weak var passwordOutlet: UITextField!
@IBOutlet weak var passwordValidationOutlet: UILabel!
@IBOutlet weak var repeatedPasswordOutlet: UITextField!
@IBOutlet weak var repeatedPasswordValidationOutlet: UILabel!
@IBOutlet weak var signupOutlet: UIButton!
@IBOutlet weak var signingUpOulet: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
let viewModel = GithubSignupViewModel1(
input: (
username: usernameOutlet.rx.text.orEmpty.asObservable(),
password: passwordOutlet.rx.text.orEmpty.asObservable(),
repeatedPassword: repeatedPasswordOutlet.rx.text.orEmpty.asObservable(),
loginTaps: signupOutlet.rx.tap.asObservable()
),
dependency: (
API: GitHubDefaultAPI.sharedAPI,
validationService: GitHubDefaultValidationService.sharedValidationService,
wireframe: DefaultWireframe.sharedInstance
)
)
// bind results to {
viewModel.signupEnabled
.subscribe(onNext: { [weak self] valid in
self?.signupOutlet.isEnabled = valid
self?.signupOutlet.alpha = valid ? 1.0 : 0.5
})
.addDisposableTo(disposeBag)
viewModel.validatedUsername
.bindTo(usernameValidationOutlet.rx.validationResult)
.addDisposableTo(disposeBag)
viewModel.validatedPassword
.bindTo(passwordValidationOutlet.rx.validationResult)
.addDisposableTo(disposeBag)
viewModel.validatedPasswordRepeated
.bindTo(repeatedPasswordValidationOutlet.rx.validationResult)
.addDisposableTo(disposeBag)
viewModel.signingIn
.bindTo(signingUpOulet.rx.isAnimating)
.addDisposableTo(disposeBag)
viewModel.signedIn
.subscribe(onNext: { signedIn in
print("User signed in \(signedIn)")
})
.addDisposableTo(disposeBag)
//}
let tapBackground = UITapGestureRecognizer()
tapBackground.rx.event
.subscribe(onNext: { [weak self] _ in
self?.view.endEditing(true)
})
.addDisposableTo(disposeBag)
view.addGestureRecognizer(tapBackground)
}
// This is one of the reasons why it's a good idea for disposal to be detached from allocations.
// If resources weren't disposed before view controller is being deallocated, signup alert view
// could be presented on top of the wrong screen or could crash your app if it was being presented
// while navigation stack is popping.
// This will work well with UINavigationController, but has an assumption that view controller will
// never be added as a child view controller. If we didn't recreate the dispose bag here,
// then our resources would never be properly released.
override func willMove(toParentViewController parent: UIViewController?) {
if let parent = parent {
if parent as? UINavigationController == nil {
assert(false, "something")
}
}
else {
self.disposeBag = DisposeBag()
}
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/24606-swift-constraints-constraintsystem-solve.swift | 9 | 243 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class B<T where B:A{let a{struct c
struct d{let e=c
var d=e
typealias e=B
| mit |
teriiehina/ParauParau | ParauParau/AppDelegate.swift | 1 | 2166 | //
// AppDelegate.swift
// ParauParau
//
// Created by teriiehina on 08/06/2014.
// Copyright (c) 2014 teriiehina. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. 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 inactive 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:.
}
}
| mit |
SteveBarnegren/TweenKit | TweenKit/TweenKit/ActionScheduler.swift | 1 | 4058 | //
// Scheduler.swift
// TweenKit
//
// Created by Steve Barnegren on 18/03/2017.
// Copyright © 2017 Steve Barnegren. All rights reserved.
//
import Foundation
import QuartzCore
@objc public class ActionScheduler : NSObject {
// MARK: - Public
public init(automaticallyAdvanceTime: Bool = true) {
self.automaticallyAdvanceTime = automaticallyAdvanceTime
super.init()
}
/**
Run an action
- Parameter action: The action to run
- Returns: Animation instance. You may wish to keep this, so that you can remove the animation later using the remove(animation:) method
*/
@discardableResult public func run(action: SchedulableAction) -> Animation {
let animation = Animation(action: action)
add(animation: animation)
return animation
}
/**
Adds an Animation to the scheduler. Usually you don't need to construct animations yourself, you can run the action directly.
- Parameter animation: The animation to run
*/
public func add(animation: Animation) {
animations.append(animation)
animation.willStart()
if automaticallyAdvanceTime {
startLoop()
}
}
/**
Removes a currently running animation
- Parameter animation: The animation to remove
*/
public func remove(animation: Animation) {
guard let index = animations.firstIndex(of: animation) else {
print("Can't find animation to remove")
return
}
animation.didFinish()
animations.remove(at: index)
if animations.isEmpty {
stopLoop()
}
}
/**
Removes all animations
*/
public func removeAll() {
let allAnimations = animations
allAnimations.forEach{
self.remove(animation: $0)
}
}
/**
The number of animations that are currently running
*/
public var numRunningAnimations: Int {
return self.animations.count
}
// MARK: - Properties
private var animations = [Animation]()
private var animationsToRemove = [Animation]()
private var displayLink: DisplayLink?
private let automaticallyAdvanceTime: Bool
// MARK: - Deinit
deinit {
stopLoop()
}
// MARK: - Manage Loop
private func startLoop() {
if displayLink != nil {
return
}
displayLink = DisplayLink(handler: {[unowned self] (dt) in
self.displayLinkCallback(dt: dt)
})
}
private func stopLoop() {
displayLink?.invalidate()
displayLink = nil
}
@objc private func displayLinkCallback(dt: Double) {
// Update Animations
step(dt: dt)
}
/// Advance the scheduler's time by amount dt
public func step(dt: Double) {
for animation in animations {
// Animations containing finite time actions
if animation.hasDuration {
var remove = false
if animation.elapsedTime + dt > animation.duration {
remove = true
}
let newTime = (animation.elapsedTime + dt).constrained(max: animation.duration)
animation.update(elapsedTime: newTime)
if remove {
animationsToRemove.append(animation)
}
}
// Animations containing infinite time actions
else{
let newTime = animation.elapsedTime + dt
animation.update(elapsedTime: newTime)
}
}
// Remove finished animations
animationsToRemove.forEach{
remove(animation: $0)
}
animationsToRemove.removeAll()
}
}
| mit |
connorkrupp/Taskability | Taskability/Taskability/AppDelegate.swift | 1 | 727 | //
// AppDelegate.swift
// Taskability
//
// Created by Connor Krupp on 15/03/2016.
// Copyright © 2016 Connor Krupp. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var dataController: DataController!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UITabBar.appearance().tintColor = UIColor.whiteColor()
dataController = DataController()
let tabBarController = window?.rootViewController as? TaskabilityTabBarController
tabBarController?.dataController = dataController
return true
}
}
| mit |
abdullahselek/DragDropUI | DragDropUI/DDImageView.swift | 1 | 1835 | //
// DDImageView.swift
// DragDropUI
//
// Copyright © 2016 Abdullah Selek. All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class DDImageView: UIImageView, DDProtocol {
public var draggedPoint: CGPoint = CGPoint.zero
public var ddDelegate: DDViewDelegate?
var initialLocation: CGPoint = CGPoint.zero
override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func didMoveToSuperview() {
if self.superview != nil {
self.isUserInteractionEnabled = true
self.registerGesture()
} else {
self.removeGesture()
}
}
}
| mit |
jainsourabhgit/MyJohnDeereAPI-OAuth-Swift-Client | OAuthSwift/OAuthSwiftHTTPRequest.swift | 1 | 11455 | //
// OAuthSwiftHTTPRequest.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/21/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import Foundation
import UIKit
public class OAuthSwiftHTTPRequest: NSObject, NSURLSessionDelegate {
public typealias SuccessHandler = (data: NSData, response: NSHTTPURLResponse) -> Void
public typealias FailureHandler = (error: NSError) -> Void
var URL: NSURL
var HTTPMethod: String
var HTTPBodyMultipart: NSData?
var contentTypeMultipart: String?
var request: NSMutableURLRequest?
var session: NSURLSession!
var headers: Dictionary<String, String>
var parameters: Dictionary<String, AnyObject>
var encodeParameters: Bool
var dataEncoding: NSStringEncoding
var timeoutInterval: NSTimeInterval
var HTTPShouldHandleCookies: Bool
var response: NSHTTPURLResponse!
var responseData: NSMutableData
var successHandler: SuccessHandler?
var failureHandler: FailureHandler?
convenience init(URL: NSURL) {
self.init(URL: URL, method: "GET", parameters: [:])
}
init(URL: NSURL, method: String, parameters: Dictionary<String, AnyObject>) {
self.URL = URL
self.HTTPMethod = method
self.headers = [:]
self.parameters = parameters
self.encodeParameters = false
self.dataEncoding = NSUTF8StringEncoding
self.timeoutInterval = 60
self.HTTPShouldHandleCookies = false
self.responseData = NSMutableData()
}
init(request: NSURLRequest) {
self.request = request as? NSMutableURLRequest
self.URL = request.URL!
self.HTTPMethod = request.HTTPMethod!
self.headers = [:]
self.parameters = [:]
self.encodeParameters = false
self.dataEncoding = NSUTF8StringEncoding
self.timeoutInterval = 60
self.HTTPShouldHandleCookies = false
self.responseData = NSMutableData()
}
func start() {
if (request == nil) {
var error: NSError?
do {
self.request = try self.makeRequest()
} catch let error1 as NSError {
error = error1
self.request = nil
}
if ((error) != nil) {
print(error!.localizedDescription)
}
}
dispatch_async(dispatch_get_main_queue(), {
self.session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: self,
delegateQueue: NSOperationQueue.mainQueue())
let task: NSURLSessionDataTask = self.session.dataTaskWithRequest(self.request!) { data, response, error -> Void in
#if os(iOS)
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
#endif
self.response = response as? NSHTTPURLResponse
self.responseData.length = 0
self.responseData.appendData(data!)
if self.response.statusCode >= 400 {
let responseString = NSString(data: self.responseData, encoding: self.dataEncoding)
let localizedDescription = OAuthSwiftHTTPRequest.descriptionForHTTPStatus(self.response.statusCode, responseString: responseString! as String)
let userInfo : [NSObject : AnyObject] = [NSLocalizedDescriptionKey: localizedDescription, "Response-Headers": self.response.allHeaderFields]
let error = NSError(domain: NSURLErrorDomain, code: self.response.statusCode, userInfo: userInfo)
self.failureHandler?(error: error)
return
}
self.successHandler?(data: self.responseData, response: self.response)
}
task.resume()
#if os(iOS)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
#endif
})
}
public func makeRequest() throws -> NSMutableURLRequest {
return try OAuthSwiftHTTPRequest.makeRequest(self.URL, method: self.HTTPMethod, headers: self.headers, parameters: self.parameters, dataEncoding: self.dataEncoding, encodeParameters: self.encodeParameters, body: self.HTTPBodyMultipart, contentType: self.contentTypeMultipart)
}
public class func makeRequest(
URL: NSURL,
method: String,
headers: [String : String],
parameters: Dictionary<String, AnyObject>,
dataEncoding: NSStringEncoding,
encodeParameters: Bool,
body: NSData? = nil,
contentType: String? = nil) throws -> NSMutableURLRequest {
var error: NSError! = NSError(domain: "Migrator", code: 0, userInfo: nil)
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = method
for (key, value) in headers {
request.setValue(value, forHTTPHeaderField: key)
}
let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(dataEncoding))
let nonOAuthParameters = parameters.filter { key, _ in !key.hasPrefix("oauth_") }
if (body != nil && contentType != nil) {
request.setValue(contentType!, forHTTPHeaderField: "Content-Type")
//request!.setValue(self.HTTPBodyMultipart!.length.description, forHTTPHeaderField: "Content-Length")
request.HTTPBody = body!
} else {
if nonOAuthParameters.count > 0 {
if request.HTTPMethod == "GET" || request.HTTPMethod == "HEAD" || request.HTTPMethod == "DELETE" {
let queryString = nonOAuthParameters.urlEncodedQueryStringWithEncoding(dataEncoding)
request.URL = URL.URLByAppendingQueryString(queryString)
request.setValue("application/x-www-form-urlencoded; charset=\(charset)", forHTTPHeaderField: "Content-Type")
}
else {
if (encodeParameters) {
let queryString = nonOAuthParameters.urlEncodedQueryStringWithEncoding(dataEncoding)
//self.request!.URL = self.URL.URLByAppendingQueryString(queryString)
request.setValue("application/x-www-form-urlencoded; charset=\(charset)", forHTTPHeaderField: "Content-Type")
request.HTTPBody = queryString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
}
else {
var jsonError: NSError?
do {
let jsonData: NSData = try NSJSONSerialization.dataWithJSONObject(nonOAuthParameters, options: [])
request.setValue("application/json; charset=\(charset)", forHTTPHeaderField: "Content-Type")
request.HTTPBody = jsonData
} catch let error1 as NSError {
jsonError = error1
if (true) {
//println(jsonError!.localizedDescription)
error = jsonError
}
throw error
}
}
}
}
}
//print("\n################Request#################\n")
//print("Send HTTPRequest:\(request)")
//print("Send HTTPRequest-AllHeaders:\(request.allHTTPHeaderFields)")
//print("\n#################################\n")
return request
}
class func stringWithData(data: NSData, encodingName: String?) -> String {
var encoding: UInt = NSUTF8StringEncoding
if (encodingName != nil) {
let encodingNameString = encodingName! as NSString
encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingNameString))
if encoding == UInt(kCFStringEncodingInvalidId) {
encoding = NSUTF8StringEncoding // by default
}
}
return NSString(data: data, encoding: encoding)! as String
}
class func descriptionForHTTPStatus(status: Int, responseString: String) -> String {
var s = "HTTP Status \(status)"
var description: String?
// http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
if status == 400 { description = "Bad Request" }
if status == 401 { description = "Unauthorized" }
if status == 402 { description = "Payment Required" }
if status == 403 { description = "Forbidden" }
if status == 404 { description = "Not Found" }
if status == 405 { description = "Method Not Allowed" }
if status == 406 { description = "Not Acceptable" }
if status == 407 { description = "Proxy Authentication Required" }
if status == 408 { description = "Request Timeout" }
if status == 409 { description = "Conflict" }
if status == 410 { description = "Gone" }
if status == 411 { description = "Length Required" }
if status == 412 { description = "Precondition Failed" }
if status == 413 { description = "Payload Too Large" }
if status == 414 { description = "URI Too Long" }
if status == 415 { description = "Unsupported Media Type" }
if status == 416 { description = "Requested Range Not Satisfiable" }
if status == 417 { description = "Expectation Failed" }
if status == 422 { description = "Unprocessable Entity" }
if status == 423 { description = "Locked" }
if status == 424 { description = "Failed Dependency" }
if status == 425 { description = "Unassigned" }
if status == 426 { description = "Upgrade Required" }
if status == 427 { description = "Unassigned" }
if status == 428 { description = "Precondition Required" }
if status == 429 { description = "Too Many Requests" }
if status == 430 { description = "Unassigned" }
if status == 431 { description = "Request Header Fields Too Large" }
if status == 432 { description = "Unassigned" }
if status == 500 { description = "Internal Server Error" }
if status == 501 { description = "Not Implemented" }
if status == 502 { description = "Bad Gateway" }
if status == 503 { description = "Service Unavailable" }
if status == 504 { description = "Gateway Timeout" }
if status == 505 { description = "HTTP Version Not Supported" }
if status == 506 { description = "Variant Also Negotiates" }
if status == 507 { description = "Insufficient Storage" }
if status == 508 { description = "Loop Detected" }
if status == 509 { description = "Unassigned" }
if status == 510 { description = "Not Extended" }
if status == 511 { description = "Network Authentication Required" }
if (description != nil) {
s = s + ": " + description! + ", Response: " + responseString
}
return s
}
}
| mit |
damicreabox/Git2Swift | Sources/Git2Swift/repository/Repository+Lookup.swift | 1 | 3825 | //
// Repository+Lookup.swift
// Git2Swift
//
// Created by Dami on 31/07/2016.
//
//
import Foundation
import CLibgit2
/// Git reference lookup
///
/// - parameter repository: Libgit2 repository pointer
/// - parameter name: Reference name
///
/// - throws: GitError
///
/// - returns: Libgit2 reference pointer
internal func gitReferenceLookup(repository: UnsafeMutablePointer<OpaquePointer?>,
name: String) throws -> UnsafeMutablePointer<OpaquePointer?> {
// Find reference pointer
let reference = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1)
// Lookup reference
let error = git_reference_lookup(reference, repository.pointee, name)
if (error != 0) {
reference.deinitialize()
reference.deallocate(capacity: 1)
// 0 on success, GIT_ENOTFOUND, GIT_EINVALIDSPEC or an error code.
switch (error) {
case GIT_ENOTFOUND.rawValue :
throw GitError.notFound(ref: name)
case GIT_EINVALIDSPEC.rawValue:
throw GitError.invalidSpec(spec: name)
default:
throw gitUnknownError("Unable to lookup reference \(name)", code: error)
}
}
return reference
}
// MARK: - Repository extension for lookup
extension Repository {
/// Lookup reference
///
/// - parameter name: Refrence name
///
/// - throws: GitError
///
/// - returns: Refernce
public func referenceLookup(name: String) throws -> Reference {
return try Reference(repository: self, name: name, pointer: try gitReferenceLookup(repository: pointer, name: name))
}
/// Lookup a tree
///
/// - parameter tree_id: Tree OID
///
/// - throws: GitError
///
/// - returns: Tree
public func treeLookup(oid tree_id: OID) throws -> Tree {
// Create tree
let tree : UnsafeMutablePointer<OpaquePointer?> = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1)
var oid = tree_id.oid
let error = git_tree_lookup(tree, pointer.pointee, &oid)
if (error != 0) {
tree.deinitialize()
tree.deallocate(capacity: 1)
throw gitUnknownError("Unable to lookup tree", code: error)
}
return Tree(repository: self, tree: tree)
}
/// Lookup a commit
///
/// - parameter commit_id: OID
///
/// - throws: GitError
///
/// - returns: Commit
public func commitLookup(oid commit_id: OID) throws -> Commit {
// Create tree
let commit : UnsafeMutablePointer<OpaquePointer?> = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1)
var oid = commit_id.oid
let error = git_commit_lookup(commit, pointer.pointee, &oid)
if (error != 0) {
commit.deinitialize()
commit.deallocate(capacity: 1)
throw gitUnknownError("Unable to lookup commit", code: error)
}
return Commit(repository: self, pointer: commit, oid: OID(withGitOid: oid))
}
/// Lookup a blob
///
/// - parameter blob_id: OID
///
/// - throws: GitError
///
/// - returns: Blob
public func blobLookup(oid blob_id: OID) throws -> Blob {
// Create tree
let blob : UnsafeMutablePointer<OpaquePointer?> = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1)
var oid = blob_id.oid
let error = git_blob_lookup(blob, pointer.pointee, &oid)
if error != 0 {
blob.deinitialize()
blob.deallocate(capacity: 1)
throw gitUnknownError("Unable to lookup blob", code: error)
}
return Blob(blob: blob)
}
}
| apache-2.0 |
bvic23/VinceRP | VinceRP/Common/Core/Hub+operators.swift | 1 | 1458 | //
// Created by Viktor Belenyesi on 27/09/15.
// Copyright (c) 2015 Viktor Belenyesi. All rights reserved.
//
public extension Hub where T: BooleanType {
public func not() -> Hub<Bool> {
return self.map(!)
}
}
public extension Hub where T: Equatable {
public func ignore(ignorabeValue: T) -> Hub<T> {
return self.filter { $0 != ignorabeValue }
}
public func distinct() -> Hub<T> {
return Reducer(self) { (x, y) in
switch (x.value, y) {
case (.Success(let v1), .Success(let v2)) where v1 != v2: return UpdateState(y)
case (.Failure(_), _): return UpdateState(y)
case (_, .Failure(_)): return UpdateState(y)
default: return x
}
}
}
}
public extension Hub {
public func foreach(skipInitial: Bool = false, callback: T -> ()) -> ChangeObserver<T> {
let obs = ChangeObserver<T>(source:self, callback:{_ in callback(self.value())}, skipInitial:skipInitial)
return obs
}
public func skipErrors() -> Hub<T> {
return filterAll { $0.isSuccess() }
}
// TODO: Add test
public func flatMap<A>(f: T -> Hub<A>) -> Hub<A> {
let result: Source<A> = reactive()
self.onChange(skipInitial: false) {
let v = f($0)
v.onChange {
result <- $0
}
}
return result
}
}
| mit |
macmade/AtomicKit | AtomicKitTests/RWLock.swift | 1 | 5999 | /*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2017 Jean-David Gadina - www.xs-labs.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
import XCTest
import AtomicKit
import STDThreadKit
class RWLockTest: XCTestCase
{
override func setUp()
{
super.setUp()
}
override func tearDown()
{
super.tearDown()
}
func testSingleReader()
{
let l = try? RWLock()
XCTAssertNotNil( l )
XCTAssertTrue( l!.tryLock( for: .reading ) );
l!.unlock( for: .reading );
}
func testSingleWriter()
{
let l = try? RWLock()
XCTAssertNotNil( l )
XCTAssertTrue( l!.tryLock( for: .writing ) );
l!.unlock( for: .writing );
}
func testMultipleReaders_SameThread()
{
let l = try? RWLock()
XCTAssertNotNil( l )
XCTAssertTrue( l!.tryLock( for: .reading ) );
XCTAssertTrue( l!.tryLock( for: .reading ) );
l!.unlock( for: .reading );
l!.unlock( for: .reading );
}
func testMultipleWriters_SameThread()
{
let l = try? RWLock()
XCTAssertNotNil( l )
XCTAssertTrue( l!.tryLock( for: .writing ) );
XCTAssertTrue( l!.tryLock( for: .writing ) );
l!.unlock( for: .writing );
l!.unlock( for: .writing );
}
func testReadWrite_SameThread()
{
let l = try? RWLock()
XCTAssertNotNil( l )
XCTAssertTrue( l!.tryLock( for: .reading ) );
XCTAssertTrue( l!.tryLock( for: .writing ) );
l!.unlock( for: .reading );
l!.unlock( for: .writing );
}
func testWriteRead_SameThread()
{
let l = try? RWLock()
XCTAssertNotNil( l )
XCTAssertTrue( l!.tryLock( for: .writing ) );
XCTAssertTrue( l!.tryLock( for: .reading ) );
l!.unlock( for: .writing );
l!.unlock( for: .reading );
}
func testMultipleReaders_DifferentThreads()
{
let l = try? RWLock()
var b = false
XCTAssertNotNil( l )
l!.lock( for: .reading )
let _ = try? STDThread
{
b = l!.tryLock( for: .reading )
if( b )
{
l!.unlock( for: .reading )
}
}
.join()
XCTAssertTrue( b )
l!.unlock( for: .reading );
}
func testMultipleWriters_DifferentThreads()
{
let l = try? RWLock()
var b = false
XCTAssertNotNil( l )
l!.lock( for: .writing )
let _ = try? STDThread
{
b = l!.tryLock( for: .writing )
if( b )
{
l!.unlock( for: .writing )
}
}
.join()
XCTAssertFalse( b );
l!.unlock( for: .writing );
let _ = try? STDThread
{
b = l!.tryLock( for: .writing )
if( b )
{
l!.unlock( for: .writing )
}
}
.join()
XCTAssertTrue( b );
}
func testReadWrite_DifferentThreads()
{
let l = try? RWLock()
var b = false
XCTAssertNotNil( l )
l!.lock( for: .reading )
let _ = try? STDThread
{
b = l!.tryLock( for: .writing )
if( b )
{
l!.unlock( for: .writing )
}
}
.join()
XCTAssertFalse( b );
l!.unlock( for: .reading );
let _ = try? STDThread
{
b = l!.tryLock( for: .writing )
if( b )
{
l!.unlock( for: .writing )
}
}
.join()
XCTAssertTrue( b );
}
func testWriteRead_DifferentThreads()
{
let l = try? RWLock()
var b = false
XCTAssertNotNil( l )
l!.lock( for: .writing );
let _ = try? STDThread
{
b = l!.tryLock( for: .reading )
if( b )
{
l!.unlock( for: .reading )
}
}
.join()
XCTAssertFalse( b );
l!.unlock( for: .writing );
let _ = try? STDThread
{
b = l!.tryLock( for: .reading )
if( b )
{
l!.unlock( for: .reading )
}
}
.join()
XCTAssertTrue( b );
}
}
| mit |
Foild/SugarRecord | spec/CoreData/CoreDataFetchResultsControllerTests.swift | 1 | 2502 | //
// CoreDataFetchResultsControllerTests.swift
// SugarRecord
//
// Created by Pedro Piñera Buendía on 06/10/14.
// Copyright (c) 2014 SugarRecord. All rights reserved.
//
import Foundation
import XCTest
import CoreData
class CoreDataFetchResultsControllerTests: XCTestCase
{
var finder: SugarRecordFinder<NSManagedObject>?
override func setUp()
{
super.setUp()
let bundle: NSBundle = NSBundle(forClass: CoreDataObjectTests.classForCoder())
let modelPath: NSString = bundle.pathForResource("TestsDataModel", ofType: "momd")!
let model: NSManagedObjectModel = NSManagedObjectModel(contentsOfURL: NSURL(fileURLWithPath: modelPath as String))!
let stack: DefaultCDStack = DefaultCDStack(databaseName: "TestDB.sqlite", model: model, automigrating: true)
SugarRecord.addStack(stack)
finder = SugarRecordFinder<NSManagedObject>()
finder!.objectClass = CoreDataObject.self
finder!.addSortDescriptor(NSSortDescriptor(key: "name", ascending: true))
finder!.setPredicate("name == test")
finder!.elements = SugarRecordFinderElements.first
}
override func tearDown() {
SugarRecord.cleanup()
SugarRecord.removeDatabase()
super.tearDown()
}
func testIfFetchedResultsControllerIsCalledWithNoCache()
{
let frc: NSFetchedResultsController = finder!.fetchedResultsController("name")
XCTAssertNil(frc.cacheName, "Cahce name should be nil")
}
func testIfFetchedResultsControllerHasTheProperCache()
{
let frc: NSFetchedResultsController = finder!.fetchedResultsController("name", cacheName: "cachename")
XCTAssertEqual(frc.cacheName!, "cachename", "The cache name should be: cachename")
}
func testIfTheFetchRequestPropertiesAreTheExpected()
{
let frc: NSFetchedResultsController = finder!.fetchedResultsController("name", cacheName: "cachename")
XCTAssertEqual((frc.fetchRequest.sortDescriptors!.first! as NSSortDescriptor).key!, "name", "The sort descriptor key should be name")
XCTAssertEqual((frc.fetchRequest.sortDescriptors!.first! as NSSortDescriptor).ascending, true, "The sort descriptor ascending should be true")
XCTAssertEqual(frc.fetchRequest.predicate!.predicateFormat, "name == test", "The predicate format should be name == test")
XCTAssertEqual(frc.fetchRequest.fetchLimit, 1, "The fetchLimit should be equal to 1")
}
} | mit |
realm/SwiftLint | Source/SwiftLintFramework/Models/LinterCache.swift | 1 | 5614 | import Foundation
private enum LinterCacheError: Error {
case noLocation
}
private struct FileCacheEntry: Codable {
let violations: [StyleViolation]
let lastModification: Date
let swiftVersion: SwiftVersion
}
private struct FileCache: Codable {
var entries: [String: FileCacheEntry]
static var empty: FileCache { return Self(entries: [:]) }
}
/// A persisted cache for storing and retrieving linter results.
public final class LinterCache {
private typealias Encoder = PropertyListEncoder
private typealias Decoder = PropertyListDecoder
private static let fileExtension = "plist"
private typealias Cache = [String: FileCache]
private var lazyReadCache: Cache
private let readCacheLock = NSLock()
private var writeCache = Cache()
private let writeCacheLock = NSLock()
internal let fileManager: LintableFileManager
private let location: URL?
private let swiftVersion: SwiftVersion
internal init(fileManager: LintableFileManager = FileManager.default, swiftVersion: SwiftVersion = .current) {
location = nil
self.fileManager = fileManager
self.lazyReadCache = Cache()
self.swiftVersion = swiftVersion
}
/// Creates a `LinterCache` by specifying a SwiftLint configuration and a file manager.
///
/// - parameter configuration: The SwiftLint configuration for which this cache will be used.
/// - parameter fileManager: The file manager to use to read lintable file information.
public init(configuration: Configuration, fileManager: LintableFileManager = FileManager.default) {
location = configuration.cacheURL
lazyReadCache = Cache()
self.fileManager = fileManager
self.swiftVersion = .current
}
private init(cache: Cache, location: URL?, fileManager: LintableFileManager, swiftVersion: SwiftVersion) {
self.lazyReadCache = cache
self.location = location
self.fileManager = fileManager
self.swiftVersion = swiftVersion
}
internal func cache(violations: [StyleViolation], forFile file: String, configuration: Configuration) {
guard let lastModification = fileManager.modificationDate(forFileAtPath: file) else {
return
}
let configurationDescription = configuration.cacheDescription
writeCacheLock.lock()
var filesCache = writeCache[configurationDescription] ?? .empty
filesCache.entries[file] = FileCacheEntry(violations: violations, lastModification: lastModification,
swiftVersion: swiftVersion)
writeCache[configurationDescription] = filesCache
writeCacheLock.unlock()
}
internal func violations(forFile file: String, configuration: Configuration) -> [StyleViolation]? {
guard let lastModification = fileManager.modificationDate(forFileAtPath: file),
let entry = fileCache(cacheDescription: configuration.cacheDescription).entries[file],
entry.lastModification == lastModification,
entry.swiftVersion == swiftVersion
else {
return nil
}
return entry.violations
}
/// Persists the cache to disk.
///
/// - throws: Throws if the linter cache doesn't have a `location` value, if the cache couldn't be serialized, or if
/// the contents couldn't be written to disk.
public func save() throws {
guard let url = location else {
throw LinterCacheError.noLocation
}
writeCacheLock.lock()
defer {
writeCacheLock.unlock()
}
guard writeCache.isNotEmpty else {
return
}
readCacheLock.lock()
let readCache = lazyReadCache
readCacheLock.unlock()
let encoder = Encoder()
for (description, writeFileCache) in writeCache where writeFileCache.entries.isNotEmpty {
let fileCacheEntries = readCache[description]?.entries.merging(writeFileCache.entries) { _, write in write }
let fileCache = fileCacheEntries.map(FileCache.init) ?? writeFileCache
let data = try encoder.encode(fileCache)
let file = url.appendingPathComponent(description).appendingPathExtension(Self.fileExtension)
try data.write(to: file, options: .atomic)
}
}
internal func flushed() -> LinterCache {
return Self(cache: mergeCaches(), location: location, fileManager: fileManager, swiftVersion: swiftVersion)
}
private func fileCache(cacheDescription: String) -> FileCache {
readCacheLock.lock()
defer {
readCacheLock.unlock()
}
if let fileCache = lazyReadCache[cacheDescription] {
return fileCache
}
guard let location = location else {
return .empty
}
let file = location.appendingPathComponent(cacheDescription).appendingPathExtension(Self.fileExtension)
let data = try? Data(contentsOf: file)
let fileCache = data.flatMap { try? Decoder().decode(FileCache.self, from: $0) } ?? .empty
lazyReadCache[cacheDescription] = fileCache
return fileCache
}
private func mergeCaches() -> Cache {
readCacheLock.lock()
writeCacheLock.lock()
defer {
readCacheLock.unlock()
writeCacheLock.unlock()
}
return lazyReadCache.merging(writeCache) { read, write in
FileCache(entries: read.entries.merging(write.entries) { _, write in write })
}
}
}
| mit |
jingyaokuku/JYweibo05 | JYSinaWeibo/JYSinaWeibo/Classse/Module/Main/View/JYMainTabBar.swift | 1 | 190 | //
// JYMainTabBar.swift
// JYSinaWeibo
//
// Created by apple on 15/10/28.
// Copyright © 2015年 Jingyao. All rights reserved.
//
import UIKit
class JYMainTabBar: UITabBar {
}
| apache-2.0 |
dreamsxin/swift | stdlib/public/core/CollectionOfOne.swift | 1 | 4101 | //===--- CollectionOfOne.swift - A Collection with one element ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// An iterator that produces one or fewer instances of `Element`.
public struct IteratorOverOne<Element> : IteratorProtocol, Sequence {
/// Construct an instance that generates `_element!`, or an empty
/// sequence if `_element == nil`.
public // @testable
init(_elements: Element?) {
self._elements = _elements
}
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made.
public mutating func next() -> Element? {
let result = _elements
_elements = nil
return result
}
internal var _elements: Element?
}
/// A collection containing a single element of type `Element`.
public struct CollectionOfOne<Element>
: MutableCollection, RandomAccessCollection {
/// Construct an instance containing just `element`.
public init(_ element: Element) {
self._element = element
}
public typealias Index = Int
/// The position of the first element.
public var startIndex: Int {
return 0
}
/// The "past the end" position---that is, the position one greater than the
/// last valid subscript argument.
///
/// In a `CollectionOfOne` instance, `endIndex` is always identical to
/// `index(after: startIndex)`.
public var endIndex: Int {
return 1
}
/// Always returns `endIndex`.
public func index(after i: Int) -> Int {
_precondition(i == startIndex)
return endIndex
}
/// Always returns `startIndex`.
public func index(before i: Int) -> Int {
_precondition(i == endIndex)
return startIndex
}
public typealias Indices = CountableRange<Int>
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
public func makeIterator() -> IteratorOverOne<Element> {
return IteratorOverOne(_elements: _element)
}
/// Access the element at `position`.
///
/// - Precondition: `position == 0`.
public subscript(position: Int) -> Element {
get {
_precondition(position == 0, "Index out of range")
return _element
}
set {
_precondition(position == 0, "Index out of range")
_element = newValue
}
}
public subscript(bounds: Range<Int>)
-> MutableRandomAccessSlice<CollectionOfOne<Element>> {
get {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return MutableRandomAccessSlice(base: self, bounds: bounds)
}
set {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
_precondition(bounds.count == newValue.count,
"CollectionOfOne can't be resized")
if let newElement = newValue.first {
_element = newElement
}
}
}
/// The number of elements (always one).
public var count: Int {
return 1
}
internal var _element: Element
}
extension CollectionOfOne : CustomDebugStringConvertible {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
return "CollectionOfOne(\(String(reflecting: _element)))"
}
}
extension CollectionOfOne : CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: ["element": _element])
}
}
@available(*, unavailable, renamed: "IteratorOverOne")
public struct GeneratorOfOne<Element> {}
extension IteratorOverOne {
@available(*, unavailable, renamed: "makeIterator")
public func generate() -> IteratorOverOne<Element> {
Builtin.unreachable()
}
}
| apache-2.0 |
YangYouYong/SwiftLearnLog01 | SongsPlayer/SongsPlayer/Classes/DetailViewController.swift | 1 | 1004 | //
// DetailViewController.swift
// SongsPlayer
//
// Created by yangyouyong on 15/8/7.
// Copyright © 2015年 SongsPlayer. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var detailDescriptionLabel: UILabel!
var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail = self.detailItem {
if let label = self.detailDescriptionLabel {
label.text = detail.description
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 |
PlayApple/SwiftySegmentedControl | SwiftySegmentedControlExample/SwiftySegmentedControlExampleUITests/SwiftySegmentedControlExampleUITests.swift | 1 | 1314 | //
// SwiftySegmentedControlExampleUITests.swift
// SwiftySegmentedControlExampleUITests
//
// Created by LiuYanghui on 2017/1/10.
// Copyright © 2017年 Yanghui.Liu. All rights reserved.
//
import XCTest
class SwiftySegmentedControlExampleUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
avito-tech/Paparazzo | Paparazzo/Core/VIPER/MediaPicker/View/Controls/CameraControlsView.swift | 1 | 8701 | import JNWSpringAnimation
import ImageSource
import UIKit
final class CameraControlsView: UIView, ThemeConfigurable {
typealias ThemeType = MediaPickerRootModuleUITheme
var onShutterButtonTap: (() -> ())?
var onPhotoLibraryButtonTap: (() -> ())?
var onCameraToggleButtonTap: (() -> ())?
var onFlashToggle: ((Bool) -> ())?
// MARK: - Subviews
private let photoView = UIImageView()
private let photoOverlayView = UIView()
private let shutterButton = UIButton()
private let cameraToggleButton = UIButton()
private let flashButton = UIButton()
// MARK: - Constants
private let insets = UIEdgeInsets(top: 4, left: 16, bottom: 4, right: 16)
private let shutterButtonMinDiameter = CGFloat(44)
private let shutterButtonMaxDiameter = CGFloat(64)
private let photoViewDiameter = CGFloat(44)
private var photoViewPlaceholder: UIImage?
// Параметры анимации кнопки съемки (подобраны ikarpov'ым)
private let shutterAnimationMinScale = CGFloat(0.842939)
private let shutterAnimationDamping = CGFloat(18.6888)
private let shutterAnimationStiffness = CGFloat(366.715)
private let shutterAnimationMass = CGFloat(0.475504)
// MARK: - UIView
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
photoView.backgroundColor = .lightGray
photoView.contentMode = .scaleAspectFill
photoView.layer.cornerRadius = photoViewDiameter / 2
photoView.clipsToBounds = true
photoView.isUserInteractionEnabled = true
photoView.addGestureRecognizer(UITapGestureRecognizer(
target: self,
action: #selector(onPhotoViewTap(_:))
))
photoOverlayView.backgroundColor = .black
photoOverlayView.alpha = 0.04
photoOverlayView.layer.cornerRadius = photoViewDiameter / 2
photoOverlayView.clipsToBounds = true
photoOverlayView.isUserInteractionEnabled = false
shutterButton.backgroundColor = .blue
shutterButton.clipsToBounds = false
shutterButton.addTarget(
self,
action: #selector(onShutterButtonTouchDown(_:)),
for: .touchDown
)
shutterButton.addTarget(
self,
action: #selector(onShutterButtonTouchUp(_:)),
for: .touchUpInside
)
flashButton.addTarget(
self,
action: #selector(onFlashButtonTap(_:)),
for: .touchUpInside
)
cameraToggleButton.addTarget(
self,
action: #selector(onCameraToggleButtonTap(_:)),
for: .touchUpInside
)
addSubview(photoView)
addSubview(photoOverlayView)
addSubview(shutterButton)
addSubview(flashButton)
addSubview(cameraToggleButton)
setUpAccessibilityIdentifiers()
}
private func setUpAccessibilityIdentifiers() {
photoView.setAccessibilityId(.photoView)
shutterButton.setAccessibilityId(.shutterButton)
cameraToggleButton.setAccessibilityId(.cameraToggleButton)
flashButton.setAccessibilityId(.flashButton)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let contentHeight = bounds.inset(by: insets).size.height
let shutterButtonDiameter = max(shutterButtonMinDiameter, min(shutterButtonMaxDiameter, contentHeight))
let shutterButtonSize = CGSize(width: shutterButtonDiameter, height: shutterButtonDiameter)
let centerY = bounds.centerY
shutterButton.frame = CGRect(origin: .zero, size: shutterButtonSize)
shutterButton.center = CGPoint(x: bounds.midX, y: centerY)
shutterButton.layer.cornerRadius = shutterButtonDiameter / 2
flashButton.size = CGSize.minimumTapAreaSize
flashButton.centerX = bounds.right - 30
flashButton.centerY = centerY
cameraToggleButton.size = CGSize.minimumTapAreaSize
cameraToggleButton.centerX = flashButton.centerX - 54
cameraToggleButton.centerY = flashButton.centerY
photoView.size = CGSize(width: photoViewDiameter, height: photoViewDiameter)
photoView.left = bounds.left + insets.left
photoView.centerY = centerY
photoOverlayView.frame = photoView.frame
}
// MARK: - CameraControlsView
func setControlsTransform(_ transform: CGAffineTransform) {
flashButton.transform = transform
cameraToggleButton.transform = transform
photoView.transform = transform
}
func setLatestPhotoLibraryItemImage(_ imageSource: ImageSource?) {
photoView.setImage(
fromSource: imageSource,
size: CGSize(width: photoViewDiameter, height: photoViewDiameter),
placeholder: photoViewPlaceholder,
placeholderDeferred: false
)
}
func setCameraControlsEnabled(_ enabled: Bool) {
shutterButton.isEnabled = enabled
cameraToggleButton.isEnabled = enabled
flashButton.isEnabled = enabled
adjustShutterButtonColor()
}
func setFlashButtonVisible(_ visible: Bool) {
flashButton.isHidden = !visible
}
func setFlashButtonOn(_ isOn: Bool) {
flashButton.isSelected = isOn
}
func setCameraToggleButtonVisible(_ visible: Bool) {
cameraToggleButton.isHidden = !visible
}
func setShutterButtonEnabled(_ enabled: Bool) {
shutterButton.isEnabled = enabled
}
func setPhotoLibraryButtonEnabled(_ enabled: Bool) {
photoView.isUserInteractionEnabled = enabled
}
func setPhotoLibraryButtonVisible(_ visible: Bool) {
photoOverlayView.isHidden = !visible
photoView.isHidden = !visible
}
// MARK: - ThemeConfigurable
func setTheme(_ theme: ThemeType) {
self.theme = theme
backgroundColor = theme.cameraControlsViewBackgroundColor
flashButton.setImage(theme.flashOffIcon, for: .normal)
flashButton.setImage(theme.flashOnIcon, for: .selected)
cameraToggleButton.setImage(theme.cameraToggleIcon, for: .normal)
photoViewPlaceholder = theme.photoPeepholePlaceholder
adjustShutterButtonColor()
}
// MARK: - Private
private var theme: MediaPickerRootModuleUITheme?
@objc private func onShutterButtonTouchDown(_ button: UIButton) {
animateShutterButtonToScale(shutterAnimationMinScale)
}
@objc private func onShutterButtonTouchUp(_ button: UIButton) {
animateShutterButtonToScale(1)
onShutterButtonTap?()
}
@objc private func onPhotoViewTap(_ tapRecognizer: UITapGestureRecognizer) {
onPhotoLibraryButtonTap?()
}
@objc private func onFlashButtonTap(_ button: UIButton) {
button.isSelected = !button.isSelected
onFlashToggle?(button.isSelected)
}
@objc private func onCameraToggleButtonTap(_ button: UIButton) {
onCameraToggleButtonTap?()
}
private func animateShutterButtonToScale(_ scale: CGFloat) {
// Тут пишут о том, чем стандартная spring-анимация плоха:
// https://medium.com/@flyosity/your-spring-animations-are-bad-and-it-s-probably-apple-s-fault-784932e51733#.jr5m2x2vl
let keyPath = "transform.scale"
guard let animation = JNWSpringAnimation(keyPath: keyPath) else {
shutterButton.transform = CGAffineTransform(scaleX: scale, y: scale)
return
}
animation.damping = shutterAnimationDamping
animation.stiffness = shutterAnimationStiffness
animation.mass = shutterAnimationMass
let layer = shutterButton.layer.presentation() ?? shutterButton.layer
animation.fromValue = layer.value(forKeyPath: keyPath)
animation.toValue = scale
shutterButton.layer.setValue(animation.toValue, forKeyPath: keyPath)
shutterButton.layer.add(animation, forKey: keyPath)
}
private func adjustShutterButtonColor() {
shutterButton.backgroundColor = shutterButton.isEnabled ? theme?.shutterButtonColor : theme?.shutterButtonDisabledColor
}
}
| mit |
DanielAsher/SwiftCheck | SwiftCheck/Random.swift | 3 | 5930 | //
// Random.swift
// SwiftCheck
//
// Created by Robert Widmann on 8/3/14.
// Copyright (c) 2015 TypeLift. All rights reserved.
//
import func Darwin.time
import func Darwin.rand
/// Provides a standard interface to an underlying Random Value Generator of any type. It is
/// analogous to `GeneratorType`, but rather than consume a sequence it uses sources of randomness
/// to generate values indefinitely.
public protocol RandomGeneneratorType {
/// The next operation returns an Int that is uniformly distributed in the range returned by
/// `genRange` (including both end points), and a new generator.
var next : (Int, Self) { get }
/// The genRange operation yields the range of values returned by the generator.
///
/// This property must return integers in ascending order.
var genRange : (Int, Int) { get }
/// Splits the receiver into two distinct random value generators.
var split : (Self, Self) { get }
}
/// A library-provided standard random number generator.
public let standardRNG : StdGen = StdGen(time(nil))
public struct StdGen : RandomGeneneratorType {
let seed: Int
init(_ seed : Int) {
self.seed = seed
}
public var next : (Int, StdGen) {
let s = Int(time(nil))
return (Int(rand()), StdGen(s))
}
public var split : (StdGen, StdGen) {
let (s1, g) = self.next
let (s2, _) = g.next
return (StdGen(s1), StdGen(s2))
}
public var genRange : (Int, Int) {
return (Int.min, Int.max)
}
}
public func newStdGen() -> StdGen {
return standardRNG.split.1
}
private func mkStdRNG(seed : Int) -> StdGen {
return StdGen(seed)
}
/// Types that can generate random versions of themselves.
public protocol RandomType {
static func randomInRange<G : RandomGeneneratorType>(range : (Self, Self), gen : G) -> (Self, G)
}
/// Generates a random value from a LatticeType random type.
public func random<A : protocol<LatticeType, RandomType>, G : RandomGeneneratorType>(gen : G) -> (A, G) {
return A.randomInRange((A.min, A.max), gen: gen)
}
extension Character : RandomType {
public static func randomInRange<G : RandomGeneneratorType>(range : (Character, Character), gen : G) -> (Character, G) {
let (min, max) = range
let minc = String(min).unicodeScalars.first!
let maxc = String(max).unicodeScalars.first!
let (val, gg) = UnicodeScalar.randomInRange((minc, maxc), gen: gen)
return (Character(val), gg)
}
}
extension UnicodeScalar : RandomType {
public static func randomInRange<G : RandomGeneneratorType>(range : (UnicodeScalar, UnicodeScalar), gen : G) -> (UnicodeScalar, G) {
let (val, gg) = UInt32.randomInRange((range.0.value, range.1.value), gen: gen)
return (UnicodeScalar(val), gg)
}
}
extension Int : RandomType {
public static func randomInRange<G : RandomGeneneratorType>(range : (Int, Int), gen : G) -> (Int, G) {
let (min, max) = range
let (r, g) = gen.next
let result = (r % ((max + 1) - min)) + min;
return (result, g);
}
}
extension Int8 : RandomType {
public static func randomInRange<G : RandomGeneneratorType>(range : (Int8, Int8), gen : G) -> (Int8, G) {
let (min, max) = range
let (r, g) = gen.next
let result = (r % ((max + 1) - min)) + min;
return (result, g);
}
}
extension Int16 : RandomType {
public static func randomInRange<G : RandomGeneneratorType>(range : (Int16, Int16), gen : G) -> (Int16, G) {
let (min, max) = range
let (r, g) = gen.next
let result = (r % ((max + 1) - min)) + min;
return (result, g);
}
}
extension Int32 : RandomType {
public static func randomInRange<G : RandomGeneneratorType>(range : (Int32, Int32), gen : G) -> (Int32, G) {
let (min, max) = range
let (r, g) = gen.next
let result = (r % ((max + 1) - min)) + min;
return (result, g);
}
}
extension Int64 : RandomType {
public static func randomInRange<G : RandomGeneneratorType>(range : (Int64, Int64), gen : G) -> (Int64, G) {
let (min, max) = range
let (r, g) = gen.next
let result = (r % ((max + 1) - min)) + min;
return (result, g);
}
}
extension UInt : RandomType {
public static func randomInRange<G : RandomGeneneratorType>(range : (UInt, UInt), gen : G) -> (UInt, G) {
let (min, max) = range
let (r, g) = gen.next
let result = (UInt(r) % ((max + 1) - min)) + min;
return (result, g);
}
}
extension UInt8 : RandomType {
public static func randomInRange<G : RandomGeneneratorType>(range : (UInt8, UInt8), gen : G) -> (UInt8, G) {
let (min, max) = range
let (r, g) = gen.next
let result = (UInt8(r) % ((max + 1) - min)) + min;
return (result, g);
}
}
extension UInt16 : RandomType {
public static func randomInRange<G : RandomGeneneratorType>(range : (UInt16, UInt16), gen : G) -> (UInt16, G) {
let (min, max) = range
let (r, g) = gen.next
let result = (UInt16(r) % ((max + 1) - min)) + min;
return (result, g);
}
}
extension UInt32 : RandomType {
public static func randomInRange<G : RandomGeneneratorType>(range : (UInt32, UInt32), gen : G) -> (UInt32, G) {
let (min, max) = range
let (r, g) = gen.next
let result = (UInt32(r) % ((max + 1) - min)) + min;
return (result, g);
}
}
extension UInt64 : RandomType {
public static func randomInRange<G : RandomGeneneratorType>(range : (UInt64, UInt64), gen : G) -> (UInt64, G) {
let (min, max) = range
let (r, g) = gen.next
let result = (UInt64(r) % ((max + 1) - min)) + min;
return (result, g);
}
}
extension Float : RandomType {
public static func randomInRange<G : RandomGeneneratorType>(range : (Float, Float), gen : G) -> (Float, G) {
let (min, max) = range
let (r, g) = gen.next
let fr = Float(r)
let result = (fr % ((max + 1) - min)) + min;
return (result, g);
}
}
extension Double : RandomType {
public static func randomInRange<G : RandomGeneneratorType>(range : (Double, Double), gen : G) -> (Double, G) {
let (min, max) = range
let (r, g) = gen.next
let dr = Double(r)
let result = (dr % ((max + 1) - min)) + min;
return (result, g);
}
}
| mit |
slavapestov/swift | test/SILGen/objc_enum.swift | 4 | 2077 | // RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen > %t.out
// RUN: FileCheck -check-prefix=CHECK -check-prefix=CHECK-%target-ptrsize %s < %t.out
// RUN: FileCheck -check-prefix=NEGATIVE %s < %t.out
// REQUIRES: objc_interop
import gizmo
// CHECK-DAG: sil shared @_TFOSC16NSRuncingOptionsC
// CHECK-DAG: sil shared @_TFOSC16NSRuncingOptionsg8rawValueSi
// CHECK-DAG: sil shared @_TFOSC16NSRuncingOptionsg9hashValueSi
// Non-payload enum ctors don't need to be instantiated at all.
// NEGATIVE-NOT: sil shared [transparent] @_TFOSC16NSRuncingOptions5MinceFMS_S_
// NEGATIVE-NOT: sil shared [transparent] @_TFOSC16NSRuncingOptions12QuinceSlicedFMS_S_
// NEGATIVE-NOT: sil shared [transparent] @_TFOSC16NSRuncingOptions15QuinceJuliennedFMS_S_
// NEGATIVE-NOT: sil shared [transparent] @_TFOSC16NSRuncingOptions11QuinceDicedFMS_S_
var runcing: NSRuncingOptions = .Mince
var raw = runcing.rawValue
var eq = runcing == .QuinceSliced
var hash = runcing.hashValue
func testEm<E: Equatable>(x: E, _ y: E) {}
func hashEm<H: Hashable>(x: H) {}
func rawEm<R: RawRepresentable>(x: R) {}
testEm(NSRuncingOptions.Mince, .QuinceSliced)
hashEm(NSRuncingOptions.Mince)
rawEm(NSRuncingOptions.Mince)
rawEm(NSFungingMask.Asset)
protocol Bub {}
extension NSRuncingOptions: Bub {}
// CHECK-32-DAG: integer_literal $Builtin.Int2048, -2147483648
// CHECK-64-DAG: integer_literal $Builtin.Int2048, 2147483648
_ = NSFungingMask.ToTheMax
// CHECK-DAG: sil_witness_table shared NSRuncingOptions: RawRepresentable module gizmo
// CHECK-DAG: sil_witness_table shared NSRuncingOptions: Equatable module gizmo
// CHECK-DAG: sil_witness_table shared NSRuncingOptions: Hashable module gizmo
// CHECK-DAG: sil_witness_table shared NSFungingMask: RawRepresentable module gizmo
// CHECK-DAG: sil shared [transparent] [thunk] @_TTWOSC16NSRuncingOptionss16RawRepresentable5gizmoFS0_C
// Extension conformances get linkage according to the protocol's accessibility, as normal.
// CHECK-DAG: sil_witness_table hidden NSRuncingOptions: Bub module objc_enum
| apache-2.0 |
Bootstragram/Piggy | piggy/AddContactViewController.swift | 1 | 1999 | //
// AddContactViewController.swift
// piggy
//
// Created by Mickaël Floc'hlay on 08/12/2016.
// Copyright © 2016 Bootstragram. All rights reserved.
//
import UIKit
class AddContactViewController: UIViewController {
var eventHandler: AddContactModuleInterface?
@IBOutlet var contactNameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
contactNameTextField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// MARK: - Actions
@IBAction func didTapCancelButton() {
eventHandler?.cancelAddContactAction()
}
@IBAction func didTapSaveButton() {
if let contactNameText = contactNameTextField.text {
eventHandler?.saveAddContactAction(name: contactNameText)
}
}
}
extension AddContactViewController: AddContactViewInterface {
func showErrorMessage(errorTitle: String, errorMessage: String?) {
let alertController = UIAlertController(title: errorTitle,
message: errorMessage,
preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK",
style: .default) { (action) in
alertController.dismiss(animated: true, completion: nil)
}
alertController.addAction(okAction)
self.present(alertController, animated: true) {
// ...
}
}
}
| mit |
exevil/Keys-For-Sketch | Source/Menu/MenuObserver.swift | 1 | 2894 | //
// MenuObserver.swift
// KeysForSketch
//
// Created by Vyacheslav Dubovitsky on 04/04/2017.
// Copyright © 2017 Vyacheslav Dubovitsky. All rights reserved.
//
public class MenuObserver : NSObject {
@objc public static let shared = MenuObserver()
let notificationCenter = NotificationCenter.default
@objc public func startObserving() {
notificationCenter.addObserver(self, selector: #selector(received(notification:)), name: NSMenu.didAddItemNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(received(notification:)), name: NSMenu.didChangeItemNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(received(notification:)), name: NSMenu.didChangeItemNotification, object: nil)
}
@objc public func stopObserving() {
notificationCenter.removeObserver(self, name: NSMenu.didAddItemNotification, object: nil)
notificationCenter.removeObserver(self, name: NSMenu.didChangeItemNotification, object: nil)
notificationCenter.removeObserver(self, name: NSMenu.didChangeItemNotification, object: nil)
}
/// Handle received notifications.
@objc func received(notification: NSNotification) {
let menu = notification.object as? NSMenu
// let itemIndex = notification.userInfo?["NSMenuItemIndex"] as? Int ?? -1
// let menuItem = menu?.item(at: itemIndex)
if menu?.isChildOf(Const.Menu.main) ?? false {
// Reload outlineView for superitem if needed.
if ViewController.initialized != nil {
self.cancelPreviousPerformRequiestsAndPerform(#selector(self.reloadOutlineViewItem(for:)), with: menu, afterDelay: 0.5)
}
// Provide debug info based on notification type
switch notification.name {
case NSMenu.didAddItemNotification:
// inDebug { print("Did add menuItem: '\(menu?.title ?? "") -> \(menuItem?.title ?? "")' (index: \(itemIndex))") }
break
case NSMenu.didChangeItemNotification:
// inDebug { print("Did change menuItem: '\(menu?.title ?? "") -> \(menuItem?.title ?? "")' (index: \(itemIndex))") }
break
case NSMenu.didRemoveItemNotification:
// inDebug { print("Did remove menuItem from Menu '\(menu?.title ?? "")' at index \(itemIndex)") }
break
default:
assertionFailure("Unexpected notification type.")
}
}
}
/// Reload ViewController's Outline View item for given menu if needed.
@objc func reloadOutlineViewItem(for menu: NSMenu?) {
if let superItem = menu?.superitem {
ViewController.initialized?.outlineView.reloadItem(superItem, reloadChildren: true)
}
}
}
| mit |
hayleyqinn/windWeather | 风生/风生UITests/__UITests.swift | 1 | 1232 | //
// __UITests.swift
// 风生UITests
//
// Created by 覃红 on 2016/10/22.
// Copyright © 2016年 hayleyqin. All rights reserved.
//
import XCTest
class __UITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
cuappdev/podcast-ios | old/Podcast/PlayerControlsView.swift | 1 | 11037 | //
// PlayerControlsView.swift
// Podcast
//
// Created by Mark Bryan on 2/12/17.
// Copyright © 2017 Cornell App Development. All rights reserved.
//
import UIKit
protocol PlayerControlsDelegate: class {
func playerControlsDidTapPlayPauseButton()
func playerControlsDidTapSkipForward()
func playerControlsDidTapSkipBackward()
func playerControlsDidTapSettingsButton()
func playerControlsDidTapSpeed()
func playerControlsDidSkipNext()
func playerControlsDidScrub()
func playerControlsDidEndScrub()
func playerControlsDidTapMoreButton()
func playerControlsDidTapRecommendButton()
}
class PlayerControlsView: UIView {
let sliderHeight: CGFloat = 1.5
let marginSpacing: CGFloat = 24.5
let playerControlsViewHeight: CGFloat = 200
let playPauseButtonSize: CGSize = CGSize(width: 96, height: 96.5)
let playPauseButtonWidthMultiplier: CGFloat = 0.21
let playPauseButtonTopOffset: CGFloat = 40.0
let skipButtonSize: CGSize = CGSize(width: 56.5, height: 20)
let skipButtonWidthMultiplier: CGFloat = 0.15
let skipButtonHeightMultiplier: CGFloat = 0.354
let skipButtonSpacing: CGFloat = 40.5
let skipForwardSpacing: CGFloat = 17.5
let skipBackwardSpacing: CGFloat = 15
let skipButtonTopOffset: CGFloat = 60
let sliderTopOffset: CGFloat = 26.5
let sliderYInset: CGFloat = 132
let timeLabelSpacing: CGFloat = 8
let buttonsYInset: CGFloat = 181.5
let nextButtonSize: CGSize = CGSize(width: 12.5, height: 13)
let nextButtonLeftOffset: CGFloat = 29
let nextButtonTopOffset: CGFloat = 65.1
let recommendButtonSize: CGSize = CGSize(width: 80, height: 18)
let moreButtonSize: CGSize = CGSize(width: 35, height: 28)
let speedButtonSize: CGSize = CGSize(width: 40, height: 18)
let settingsButtonSize: CGFloat = 22
let moreButtonBottomOffset: CGFloat = 19.5
let moreButtonTrailingSpacing: CGFloat = 14.5
var slider: UISlider!
var playPauseButton: UIButton!
var forwardsButton: UIButton!
var backwardsButton: UIButton!
var rightTimeLabel: UILabel!
var leftTimeLabel: UILabel!
var recommendButton: FillNumberButton!
var moreButton: MoreButton!
var nextButton: UIButton!
var speedButton: UIButton!
var settingsButton: UIButton!
weak var delegate: PlayerControlsDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
self.frame.size.height = playerControlsViewHeight
backgroundColor = .clear
slider = Slider()
slider.setThumbImage(#imageLiteral(resourceName: "oval"), for: .normal)
slider.minimumTrackTintColor = .sea
slider.maximumTrackTintColor = .silver
addSubview(slider)
slider.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview().inset(marginSpacing)
make.top.equalToSuperview().offset(sliderTopOffset)
make.height.equalTo(sliderHeight)
}
slider.addTarget(self, action: #selector(sliderValueChanged), for: .valueChanged)
slider.addTarget(self, action: #selector(endScrubbing), for: .touchUpInside)
slider.addTarget(self, action: #selector(endScrubbing), for: .touchUpOutside)
leftTimeLabel = UILabel(frame: .zero)
leftTimeLabel.font = ._12RegularFont()
leftTimeLabel.textColor = .slateGrey
leftTimeLabel.textAlignment = .left
addSubview(leftTimeLabel)
rightTimeLabel = UILabel(frame: .zero)
rightTimeLabel.font = ._12RegularFont()
rightTimeLabel.textColor = .slateGrey
rightTimeLabel.textAlignment = .right
addSubview(rightTimeLabel)
playPauseButton = UIButton(frame: .zero)
playPauseButton.adjustsImageWhenHighlighted = false
playPauseButton.setBackgroundImage(#imageLiteral(resourceName: "pause"), for: .selected)
playPauseButton.setBackgroundImage(#imageLiteral(resourceName: "play"), for: .normal)
playPauseButton.addTarget(self, action: #selector(playPauseButtonPress), for: .touchUpInside)
addSubview(playPauseButton)
playPauseButton.snp.makeConstraints { make in
make.width.equalToSuperview().multipliedBy(playPauseButtonWidthMultiplier)
make.height.equalTo(playPauseButton.snp.width)
make.centerX.equalToSuperview()
make.top.equalTo(slider.snp.bottom).offset(playPauseButtonTopOffset)
}
forwardsButton = Button()
forwardsButton.setBackgroundImage(#imageLiteral(resourceName: "forward30"), for: .normal)
forwardsButton.adjustsImageWhenHighlighted = false
forwardsButton.addTarget(self, action: #selector(forwardButtonPress), for: .touchUpInside)
addSubview(forwardsButton)
forwardsButton.snp.makeConstraints { make in
make.width.equalToSuperview().multipliedBy(skipButtonWidthMultiplier)
make.height.equalTo(forwardsButton.snp.width).multipliedBy(skipButtonHeightMultiplier)
make.top.equalTo(slider.snp.bottom).offset(skipButtonTopOffset)
make.leading.equalTo(playPauseButton.snp.trailing).offset(skipForwardSpacing)
}
speedButton = Button()
speedButton.setTitleColor(.slateGrey, for: .normal)
speedButton.contentHorizontalAlignment = .left
speedButton.titleLabel?.font = ._14SemiboldFont()
speedButton.addTarget(self, action: #selector(speedButtonPress), for: .touchUpInside)
addSubview(speedButton)
speedButton.snp.makeConstraints { make in
make.size.equalTo(speedButtonSize)
make.leading.equalTo(slider.snp.leading)
make.centerY.equalTo(forwardsButton.snp.centerY)
}
settingsButton = Button()
settingsButton.setImage(#imageLiteral(resourceName: "settingsButton"), for: .normal)
settingsButton.addTarget(self, action: #selector(settingsButtonPress), for: .touchUpInside)
addSubview(settingsButton)
settingsButton.snp.makeConstraints { make in
make.size.equalTo(settingsButtonSize)
make.centerY.equalTo(forwardsButton.snp.centerY)
make.trailing.equalTo(slider.snp.trailing)
}
settingsButton.isHidden = false // TODO: change when we add settings to player
backwardsButton = Button()
backwardsButton.setBackgroundImage(#imageLiteral(resourceName: "back30"), for: .normal)
backwardsButton.adjustsImageWhenHighlighted = false
backwardsButton.addTarget(self, action: #selector(backwardButtonPress), for: .touchUpInside)
addSubview(backwardsButton)
backwardsButton.snp.makeConstraints { make in
make.width.equalToSuperview().multipliedBy(skipButtonWidthMultiplier)
make.height.equalTo(forwardsButton.snp.width).multipliedBy(skipButtonHeightMultiplier)
make.centerY.equalTo(forwardsButton.snp.centerY)
make.trailing.equalTo(playPauseButton.snp.leading).offset(0 - skipForwardSpacing)
}
recommendButton = FillNumberButton(type: .recommend)
recommendButton.frame = CGRect(x: marginSpacing, y: self.frame.maxY - buttonsYInset, width: recommendButtonSize.width, height: recommendButtonSize.height)
recommendButton.addTarget(self, action: #selector(recommendButtonTapped), for: .touchUpInside)
nextButton = UIButton(frame: .zero)
nextButton.setBackgroundImage(#imageLiteral(resourceName: "next"), for: .normal)
nextButton.adjustsImageWhenHighlighted = false
nextButton.addTarget(self, action: #selector(nextButtonPress), for: .touchUpInside)
addSubview(nextButton)
nextButton.snp.makeConstraints { make in
make.size.equalTo(nextButtonSize)
make.centerY.equalTo(forwardsButton.snp.centerY)
make.trailing.equalTo(slider.snp.trailing)
}
nextButton.isHidden = true // Remove this once we implement a queue
moreButton = MoreButton()
moreButton.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) // increase edge insets for larger touch radius
moreButton.addTarget(self, action: #selector(moreButtonTapped), for: .touchUpInside)
addSubview(moreButton)
moreButton.snp.makeConstraints { make in
make.size.equalTo(moreButtonSize)
make.bottom.equalTo(safeAreaLayoutGuide.snp.bottom).inset(moreButtonBottomOffset)
make.trailing.equalToSuperview().inset(moreButtonTrailingSpacing)
}
leftTimeLabel.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(marginSpacing)
make.top.equalTo(slider.snp.bottom).offset(timeLabelSpacing)
}
rightTimeLabel.snp.makeConstraints { make in
make.trailing.equalToSuperview().inset(marginSpacing)
make.top.equalTo(leftTimeLabel.snp.top)
}
updateUI(isPlaying: false, elapsedTime: "0:00", timeLeft: "0:00", progress: 0.0, isScrubbing: false, rate: .one)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateUI(isPlaying: Bool, elapsedTime: String, timeLeft: String, progress: Float, isScrubbing: Bool, rate: PlayerRate) {
playPauseButton.isSelected = isPlaying
if !isScrubbing {
slider.value = progress
}
speedButton.setTitle(rate.toString(), for: .normal)
leftTimeLabel.text = elapsedTime
rightTimeLabel.text = timeLeft
leftTimeLabel.sizeToFit()
rightTimeLabel.sizeToFit()
}
@objc func playPauseButtonPress() {
playPauseButton.isSelected = !playPauseButton.isSelected
delegate?.playerControlsDidTapPlayPauseButton()
}
@objc func forwardButtonPress() {
delegate?.playerControlsDidTapSkipForward()
}
@objc func backwardButtonPress() {
delegate?.playerControlsDidTapSkipBackward()
}
@objc func endScrubbing() {
delegate?.playerControlsDidEndScrub()
}
@objc func sliderValueChanged() {
delegate?.playerControlsDidScrub()
}
@objc func speedButtonPress() {
delegate?.playerControlsDidTapSpeed()
}
@objc func nextButtonPress() {
delegate?.playerControlsDidSkipNext()
}
@objc func moreButtonTapped() {
delegate?.playerControlsDidTapMoreButton()
}
@objc func recommendButtonTapped() {
delegate?.playerControlsDidTapRecommendButton()
}
@objc func settingsButtonPress() {
delegate?.playerControlsDidTapSettingsButton()
}
func setRecommendButtonToState(isRecommended: Bool, numberOfRecommendations: Int) {
recommendButton.setupWithNumber(isSelected: isRecommended, numberOf: numberOfRecommendations)
}
}
| mit |
danielhour/DINC | DINCTests/DINCTests.swift | 1 | 947 | //
// DINCTests.swift
// DINCTests
//
// Created by dhour on 4/14/16.
// Copyright © 2016 DHour. All rights reserved.
//
import XCTest
//@testable import DINC
class DINCTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
diegosanchezr/Chatto | ChattoAdditions/Tests/Chat Items/TextMessages/TextMessagePresenterBuilderTests.swift | 1 | 1744 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import XCTest
@testable import ChattoAdditions
class TextMessagePresenterBuilderTests: XCTestCase {
func testThat_CreatesPresenter() {
let messageModel = MessageModel(uid: "uid", senderId: "senderId", type: "text-message", isIncoming: true, date: NSDate(), status: .Success)
let textMessageModel = TextMessageModel(messageModel: messageModel, text: "Some text")
let builder = TextMessagePresenterBuilder(viewModelBuilder: TextMessageViewModelDefaultBuilder(), interactionHandler: TextMessageTestHandler())
XCTAssertNotNil(builder.createPresenterWithChatItem(textMessageModel))
}
}
| mit |
evnaz/Design-Patterns-In-Swift | Design-Patterns-CN.playground/Pages/Index.xcplaygroundpage/Contents.swift | 2 | 530 | /*:
设计模式(Swift 5.0 实现)
======================
([Design-Patterns-CN.playground.zip](https://raw.githubusercontent.com/ochococo/Design-Patterns-In-Swift/master/Design-Patterns-CN.playground.zip)).
👷 源项目由 [@nsmeme](http://twitter.com/nsmeme) (Oktawian Chojnacki) 维护。
🇨🇳 中文版由 [@binglogo](https://twitter.com/binglogo) 整理翻译。
## 目录
* [行为型模式](Behavioral)
* [创建型模式](Creational)
* [结构型模式](Structural)
*/
import Foundation
print("您好!")
| gpl-3.0 |
ESGIProjects/SwifTools | SwifTools/SwifTools/STConstraints.swift | 1 | 5455 | //
// STConstraints.swift
// SwifTools
//
// Created by Jason Pierna on 27/01/2017.
// Copyright © 2017 Jason Pierna & Kévin Le. All rights reserved.
//
import UIKit
public class STConstraints {
/**
* Enumerates the possible side of a constraint.
*/
public enum Sides {
case left, right, top, bottom, leading, trailing
}
/**
* Enumerates both size axis.
*/
public enum Sizes {
case width, height
}
/**
Creates a size constraint on the selected view.
- parameter view: The view to constraint
- parameter sizes: The desired axis
- parameter value: The size value
*/
public static func addSizeConstraints(view: UIView, sizes: [STConstraints.Sizes], value: CGFloat) {
view.translatesAutoresizingMaskIntoConstraints = false
for size in sizes {
switch size {
case .width:
view.widthAnchor.constraint(equalToConstant: value).isActive = true
case .height:
view.heightAnchor.constraint(equalToConstant: value).isActive = true
}
}
}
/**
Creates a constraint between a view and one of its parent.
- parameter parent: The view's parent
- parameter child: The view ton constraint
- parameter sides: The side to constraint
- parameter constant: The distance between both views.
*/
public static func addConstraints(parent firstView: UIView, child secondView: UIView, sides: [STConstraints.Sides], constant: CGFloat) {
firstView.translatesAutoresizingMaskIntoConstraints = false
secondView.translatesAutoresizingMaskIntoConstraints = false
for side in sides {
switch side {
case .left:
applyXAxis(first: firstView.leftAnchor, second: secondView.leftAnchor, constant: constant)
case .right:
applyXAxis(first: firstView.rightAnchor, second: secondView.rightAnchor, constant: constant)
case .leading:
applyXAxis(first: firstView.leadingAnchor, second: secondView.leadingAnchor, constant: -constant)
case .trailing:
applyXAxis(first: firstView.trailingAnchor, second: secondView.trailingAnchor, constant: constant)
case .top:
applyYAxis(first: firstView.topAnchor, second: secondView.topAnchor, constant: -constant)
case .bottom:
applyYAxis(first: firstView.bottomAnchor, second: secondView.bottomAnchor, constant: constant)
}
}
}
/**
Creates a constraint between a view and one of its parent. The constant is 0 by default.
- parameter parent: The view's parent
- parameter child: The view to constraint
- parameter sides: The side to constraint
*/
public static func addConstraints(parent firstView: UIView, child secondView: UIView, sides: [STConstraints.Sides]) {
addConstraints(parent: firstView, child: secondView, sides: sides, constant: 0)
}
/**
Creates a constraint between two child views. The constant is 0 by default.
- parameter parent: The first view.
- parameter child: The second view.
- parameter sides: The side to constraint (relative to the first view)
*/
public static func addConstraints(between firstView: UIView, and secondView: UIView, sides: [STConstraints.Sides]) {
addConstraints(between: firstView, and: secondView, sides: sides, constant: 0)
}
/**
Creates a constraint between two child views.
- parameter parent: The first view.
- parameter child: The second view.
- parameter sides: The side to constraint (relative to the first view)
- parameter constant: The distance between both views.
*/
public static func addConstraints(between firstView: UIView, and secondView: UIView, sides: [STConstraints.Sides], constant: CGFloat) {
firstView.translatesAutoresizingMaskIntoConstraints = false
secondView.translatesAutoresizingMaskIntoConstraints = false
for side in sides {
switch side {
case .left:
applyXAxis(first: firstView.leftAnchor, second: secondView.rightAnchor, constant: constant)
case .right:
applyXAxis(first: firstView.rightAnchor, second: secondView.leftAnchor, constant: -constant)
case .leading:
applyXAxis(first: firstView.leadingAnchor, second: secondView.trailingAnchor, constant: constant)
case .trailing:
applyXAxis(first: firstView.trailingAnchor, second: secondView.leadingAnchor, constant: constant)
case .top:
applyYAxis(first: firstView.topAnchor, second: secondView.bottomAnchor, constant: constant)
case .bottom:
applyYAxis(first: firstView.bottomAnchor, second: secondView.topAnchor, constant: -constant)
}
}
}
private static func applyXAxis(first: NSLayoutXAxisAnchor, second: NSLayoutXAxisAnchor, constant: CGFloat) {
first.constraint(equalTo: second, constant: constant).isActive = true
}
private static func applyYAxis(first: NSLayoutYAxisAnchor, second: NSLayoutYAxisAnchor, constant: CGFloat) {
first.constraint(equalTo: second, constant: constant).isActive = true
}
}
| bsd-3-clause |
austinzheng/swift-compiler-crashes | crashes-duplicates/10487-swift-sourcemanager-getmessage.swift | 11 | 203 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
deinit {
if true {
{
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/08607-swift-sourcemanager-getmessage.swift | 11 | 238 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class B {
func b {
for {
if c {
protocol e {
"
enum A {
class
case ,
| mit |
zhuozhuo/ZHChat | SwiftExample/ZHChatSwift/ZHCDemoMessagesViewController.swift | 1 | 11530 | //
// ZHCDemoMessagesViewController.swift
// ZHChatSwift
//
// Created by aimoke on 16/12/16.
// Copyright © 2016年 zhuo. All rights reserved.
//
import UIKit
import ZHChat
class ZHCDemoMessagesViewController: ZHCMessagesViewController {
var demoData: ZHModelData = ZHModelData.init();
var presentBool: Bool = false;
override func viewDidLoad() {
super.viewDidLoad()
demoData.loadMessages();
self.title = "ZHCMessages";
if self.automaticallyScrollsToMostRecentMessage {
self.scrollToBottom(animated: false);
}
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated);
if self.presentBool {
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.stop, target: self, action:#selector(closePressed))
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func closePressed() -> Void {
self.navigationController?.dismiss(animated: true, completion: nil);
}
// MARK: ZHCMessagesTableViewDataSource
override func senderDisplayName() -> String {
return kZHCDemoAvatarDisplayNameJobs;
}
override func senderId() -> String {
return kZHCDemoAvatarIdJobs;
}
override func tableView(_ tableView: ZHCMessagesTableView, messageDataForCellAt indexPath: IndexPath) -> ZHCMessageData {
return self.demoData.messages.object(at: indexPath.row) as! ZHCMessageData;
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
self.demoData.messages.removeObject(at: indexPath.row);
}
override func tableView(_ tableView: ZHCMessagesTableView, messageBubbleImageDataForCellAt indexPath: IndexPath) -> ZHCMessageBubbleImageDataSource? {
/**
* You may return nil here if you do not want bubbles.
* In this case, you should set the background color of your TableView view cell's textView.
*
* Otherwise, return your previously created bubble image data objects.
*/
let message: ZHCMessage = self.demoData.messages.object(at: indexPath.row) as! ZHCMessage;
if message.isMediaMessage {
print("is mediaMessage");
}
if message.senderId == self.senderId() {
return self.demoData.outgoingBubbleImageData;
}
return self.demoData.incomingBubbleImageData;
}
override func tableView(_ tableView: ZHCMessagesTableView, avatarImageDataForCellAt indexPath: IndexPath) -> ZHCMessageAvatarImageDataSource? {
/**
* Return your previously created avatar image data objects.
*
* Note: these the avatars will be sized according to these values:
*
* Override the defaults in `viewDidLoad`
*/
let message: ZHCMessage = self.demoData.messages.object(at: indexPath.row) as! ZHCMessage;
return self.demoData.avatars.object(forKey: message.senderId) as! ZHCMessageAvatarImageDataSource?;
}
override func tableView(_ tableView: ZHCMessagesTableView, attributedTextForCellTopLabelAt indexPath: IndexPath) -> NSAttributedString? {
/**
* This logic should be consistent with what you return from `heightForCellTopLabelAtIndexPath:`
* The other label text delegate methods should follow a similar pattern.
*
* Show a timestamp for every 3rd message
*/
if (indexPath.row%3==0) {
let message: ZHCMessage = (self.demoData.messages.object(at: indexPath.row) as? ZHCMessage)!;
return ZHCMessagesTimestampFormatter.shared().attributedTimestamp(for: message.date);
}
return nil;
}
override func tableView(_ tableView: ZHCMessagesTableView, attributedTextForMessageBubbleTopLabelAt indexPath: IndexPath) -> NSAttributedString? {
let message: ZHCMessage = self.demoData.messages.object(at: indexPath.row) as! ZHCMessage;
if message.senderId == self.senderId(){
return nil;
}
if (indexPath.row-1)>0 {
let preMessage: ZHCMessage = self.demoData.messages.object(at: indexPath.row-1) as! ZHCMessage;
if preMessage.senderId == message.senderId{
return nil;
}
}
return NSAttributedString.init(string: message.senderDisplayName);
}
override func tableView(_ tableView: ZHCMessagesTableView, attributedTextForCellBottomLabelAt indexPath: IndexPath) -> NSAttributedString? {
return nil;
}
// MARK: Adjusting cell label heights
override func tableView(_ tableView: ZHCMessagesTableView, heightForCellTopLabelAt indexPath: IndexPath) -> CGFloat {
/**
* Each label in a cell has a `height` delegate method that corresponds to its text dataSource method
*/
/**
* This logic should be consistent with what you return from `attributedTextForCellTopLabelAtIndexPath:`
* The other label height delegate methods should follow similarly
*
* Show a timestamp for every 3rd message
*/
var labelHeight = 0.0;
if indexPath.row%3 == 0 {
labelHeight = Double(kZHCMessagesTableViewCellLabelHeightDefault);
}
return CGFloat(labelHeight);
}
override func tableView(_ tableView: ZHCMessagesTableView, heightForMessageBubbleTopLabelAt indexPath: IndexPath) -> CGFloat {
var labelHeight = kZHCMessagesTableViewCellLabelHeightDefault;
let currentMessage: ZHCMessage = self.demoData.messages.object(at: indexPath.row) as! ZHCMessage;
if currentMessage.senderId==self.senderId(){
labelHeight = 0.0;
}
if ((indexPath.row - 1) > 0){
let previousMessage: ZHCMessage = self.demoData.messages.object(at: indexPath.row-1) as! ZHCMessage;
if (previousMessage.senderId == currentMessage.senderId) {
labelHeight = 0.0;
}
}
return CGFloat(labelHeight);
}
override func tableView(_ tableView: ZHCMessagesTableView, heightForCellBottomLabelAt indexPath: IndexPath) -> CGFloat {
let string: NSAttributedString? = self.tableView(tableView, attributedTextForCellBottomLabelAt: indexPath);
if ((string) != nil) {
return CGFloat(kZHCMessagesTableViewCellSpaceDefault);
}else{
return 0.0;
}
}
//MARK: ZHCMessagesTableViewDelegate
override func tableView(_ tableView: ZHCMessagesTableView, didTapAvatarImageView avatarImageView: UIImageView, at indexPath: IndexPath) {
super.tableView(tableView, didTapAvatarImageView: avatarImageView, at: indexPath);
}
override func tableView(_ tableView: ZHCMessagesTableView, didTapMessageBubbleAt indexPath: IndexPath) {
super.tableView(tableView, didTapMessageBubbleAt: indexPath);
}
override func tableView(_ tableView: ZHCMessagesTableView, performAction action: Selector, forcellAt indexPath: IndexPath, withSender sender: Any?) {
super.tableView(tableView, performAction: action, forcellAt: indexPath, withSender: sender);
}
//MARK:TableView datasource
override func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.demoData.messages.count;
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: ZHCMessagesTableViewCell = super.tableView(tableView, cellForRowAt: indexPath) as! ZHCMessagesTableViewCell;
self.configureCell(cell, atIndexPath: indexPath);
return cell;
}
//MARK:Configure Cell Data
func configureCell(_ cell: ZHCMessagesTableViewCell, atIndexPath indexPath: IndexPath) -> Void {
let message: ZHCMessage = self.demoData.messages.object(at: indexPath.row) as! ZHCMessage;
if !message.isMediaMessage {
if (message.senderId == self.senderId()) {
cell.textView?.textColor = UIColor.black;
}else{
cell.textView?.textColor = UIColor.white;
}
}
}
//MARK: Messages view controller
override func didPressSend(_ button: UIButton?, withMessageText text: String, senderId: String, senderDisplayName: String, date: Date) {
/**
* Sending a message. Your implementation of this method should do *at least* the following:
*
* 1. Play sound (optional)
* 2. Add new id<ZHCMessageData> object to your data source
* 3. Call `finishSendingMessage`
*/
let message: ZHCMessage = ZHCMessage.init(senderId: senderId, senderDisplayName: senderDisplayName, date: date, text: text);
self.demoData.messages.add(message);
self.finishSendingMessage(animated: true);
}
//MARK: ZHCMessagesInputToolbarDelegate
override func messagesInputToolbar(_ toolbar: ZHCMessagesInputToolbar, sendVoice voiceFilePath: String, seconds senconds: TimeInterval) {
let audioData: NSData = try!NSData.init(contentsOfFile: voiceFilePath);
let audioItem: ZHCAudioMediaItem = ZHCAudioMediaItem.init(data: audioData as Data);
let audioMessage: ZHCMessage = ZHCMessage.init(senderId: self.senderId(), displayName: self.senderDisplayName(), media: audioItem);
self.demoData.messages.add(audioMessage);
self.finishSendingMessage(animated: true);
}
//MARK: ZHCMessagesMoreViewDelegate
override func messagesMoreView(_ moreView: ZHCMessagesMoreView, selectedMoreViewItemWith index: Int) {
switch index {
case 0://Camera
self.demoData.addVideoMediaMessage();
self.messageTableView?.reloadData();
self.finishSendingMessage();
case 1://Photos
self.demoData.addPhotoMediaMessage();
self.messageTableView?.reloadData();
self.finishSendingMessage();
case 2:
self.demoData.addLocationMediaMessageCompletion {
self.messageTableView?.reloadData();
self.finishSendingMessage();
}
default:
break;
}
}
//MARK: ZHCMessagesMoreViewDataSource
override func messagesMoreViewTitles(_ moreView: ZHCMessagesMoreView) -> [Any] {
return ["Camera","Photos","Location"];
}
override func messagesMoreViewImgNames(_ moreView: ZHCMessagesMoreView) -> [Any] {
return ["chat_bar_icons_camera","chat_bar_icons_pic","chat_bar_icons_location"]
}
/*
// 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.
}
*/
}
| mit |
huangboju/Moots | Examples/Lumia/Lumia/Component/StateMachine/StateMachineVC.swift | 1 | 3086 | //
// StateMachineVC.swift
// Lumia
//
// Created by xiAo_Ju on 2019/12/31.
// Copyright © 2019 黄伯驹. All rights reserved.
//
import UIKit
class StateMachineVC: UIViewController {
var statusBarStyle: UIStatusBarStyle = .default {
didSet {
setNeedsStatusBarAppearanceUpdate()
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return statusBarStyle
}
lazy var promptLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
return label
}()
enum State: Int {
case off
case on
case broken
}
enum Transition: Int {
case turn
case cut
}
lazy var stateMachine: StateMachine<State, Transition> = {
let stateMachine = StateMachine<State, Transition>()
stateMachine.add(state: .off) { [weak self] in
self?.statusBarStyle = .lightContent
self?.view.backgroundColor = .black
self?.promptLabel.textColor = .white
self?.promptLabel.text = "Tap to turn lights on"
}
stateMachine.add(state: .on) { [weak self] in
self?.statusBarStyle = .default
self?.view.backgroundColor = .white
self?.promptLabel.textColor = .black
self?.promptLabel.text = "Tap to turn lights off"
}
stateMachine.add(state: .broken) { [weak self] in
self?.statusBarStyle = .lightContent
self?.view.backgroundColor = .black
self?.promptLabel.textColor = .white
self?.promptLabel.text = "The wire is broken :["
}
stateMachine.add(transition: .turn, fromState: .off, toState: .on)
stateMachine.add(transition: .turn, fromState: .on, toState: .off)
stateMachine.add(transition: .cut, fromStates: [.on, .off], toState: .broken)
return stateMachine
}()
override func loadView() {
super.loadView()
view.addSubview(promptLabel)
promptLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
NSLayoutConstraint(item: promptLabel, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0),
NSLayoutConstraint(item: promptLabel, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0)
]
)
}
override func viewDidLoad() {
super.viewDidLoad()
stateMachine.initialState = .off
let tap = UITapGestureRecognizer(target: self, action: #selector(tap(_:)))
view.addGestureRecognizer(tap)
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:)))
view.addGestureRecognizer(longPress)
}
@objc func tap(_ sender: UITapGestureRecognizer) {
stateMachine.fire(transition: .turn)
}
@objc func longPress(_ sender: UILongPressGestureRecognizer) {
stateMachine.fire(transition: .cut)
}
}
| mit |
NestedWorld/NestedWorld-iOS | nestedworld/nestedworld/NSDateExtension.swift | 1 | 401 | //
// NSDateExtension.swift
// nestedworld
//
// Created by Jean-Antoine Dupont on 26/04/2016.
// Copyright © 2016 NestedWorld. All rights reserved.
//
import Foundation
extension NSDate
{
func toString(format: String) -> String
{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.stringFromDate(self)
}
}
| mit |
seorenn/SRChoco | Source/StringExtensions.swift | 1 | 3196 | //
// StringExtensions.swift
// SRChoco
//
// Created by Seorenn.
// Copyright (c) 2014 Seorenn. All rights reserved.
//
import Foundation
public extension String {
init(cString: UnsafePointer<Int8>) {
self.init(cString: UnsafeRawPointer(cString).assumingMemoryBound(to: UInt8.self))
}
subscript(index: Int) -> Character {
let chrIndex: String.Index
if index >= 0 {
chrIndex = self.index(self.startIndex, offsetBy: index)
} else {
chrIndex = self.index(self.endIndex, offsetBy: index)
}
return self[chrIndex]
}
// substring with range
subscript(range: Range<Int>) -> String {
let start = self.index(self.startIndex, offsetBy: range.lowerBound)
let end = self.index(self.startIndex, offsetBy: range.upperBound)
let range: Range<Index> = start..<end
return String(self[range])
}
// substring with NSRange
subscript(range: NSRange) -> String {
if range.length <= 0 { return "" }
let startIndex = range.location
let endIndex = range.location + range.length
return self[startIndex..<endIndex]
}
func substring(startIndex: Int, length: Int) -> String {
return self[startIndex ..< (startIndex + length)]
}
func prefix(length: Int) -> String {
return self.substring(startIndex: 0, length: length)
}
func postfix(length: Int) -> String {
let si: Int = self.count - length
return self.substring(startIndex: si, length: length)
}
func trimmedString() -> String {
return self.trimmingCharacters(in: CharacterSet.whitespaces)
}
func contain(string: String, ignoreCase: Bool = false) -> Bool {
let options = ignoreCase ? NSString.CompareOptions.caseInsensitive : NSString.CompareOptions()
if let _ = self.range(of: string, options: options) {
return true
}
return false
}
func contain(strings: Array<String>, ORMode: Bool = false, ignoreCase: Bool = false) -> Bool {
for string: String in strings {
if ORMode && self.contain(string: string, ignoreCase: ignoreCase) {
return true
} else if ORMode == false && self.contain(string: string, ignoreCase: ignoreCase) == false {
return false
}
}
if ORMode {
return false
} else {
return true
}
}
func array(bySplitter: String? = nil) -> [String] {
if let s = bySplitter {
return self.components(separatedBy: s)
} else {
return self.components(separatedBy: CharacterSet.whitespacesAndNewlines)
}
}
internal static func stringWithCFStringVoidPointer(_ voidPtr: UnsafeRawPointer) -> String? {
let cfstr: CFString = unsafeBitCast(voidPtr, to: CFString.self)
let nsstr: NSString = cfstr
return nsstr as String
}
}
public extension Optional where Wrapped == String {
var isNilOrEmpty: Bool {
if self == nil { return true }
return self!.isEmpty
}
}
| mit |
iOSDevCafe/YouTube-Example-Codes | Protocol Oriented Byte/Protocol Oriented Byte/AppDelegate.swift | 1 | 2554 | //
// AppDelegate.swift
// Protocol Oriented Byte
//
// Created by iOS Café on 24/09/2017.
// Copyright © 2017 iOS Café. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// let byte = Byte(bits: [.one, .one, .one])
// print(byte.intValue)
//
let integer = Integer32(bits: [.one, .one, .zero, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .one, .zero])
print(integer.intValue)
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:.
}
}
| mit |
mightydeveloper/swift | validation-test/compiler_crashers/27200-swift-abstractclosureexpr-setparams.swift | 9 | 294 | // RUN: not --crash %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
class S<T{func a<h{func b<T where h.g=a{}{(a{{{T{{{{{{{{{{{{let t=B<T{
| apache-2.0 |
ChaoBoyan/FirstBlood | FirstBlood/FirstBlood/AppDelegate.swift | 1 | 2175 | //
// AppDelegate.swift
// FirstBlood
//
// Created by Yan Chaobo on 2017/7/11.
// Copyright © 2017年 factminr. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
morpheby/aTarantula | aTarantula/views/ViewController.swift | 1 | 6272 | //
// ViewController.swift
// aTarantula
//
// Created by Ilya Mikhaltsou on 8/18/17.
// Copyright © 2017 morpheby. All rights reserved.
//
import Cocoa
import TarantulaPluginCore
class ViewController: NSViewController {
@objc dynamic var crawler: Crawler = Crawler()
@IBOutlet var objectController: NSObjectController!
@IBOutlet var secondProgressIndicator: NSProgressIndicator!
@IBOutlet var tableLogView: NSTableView!
override func viewDidLoad() {
super.viewDidLoad()
crawler.logChangeObservable ∆= self >> { s, c in
s.tableLogView.noteHeightOfRows(withIndexesChanged: [c.log.count-1])
}
}
override func viewDidLayout() {
super.viewDidLayout()
if let layer = secondProgressIndicator.layer {
layer.anchorPoint = CGPoint(x: 1, y: 0)
layer.transform = CATransform3DMakeScale(-1.0, 1.0, 1.0)
}
}
@IBAction func start(_ sender: Any?) {
crawler.running = true
}
@IBAction func stop(_ sender: Any?) {
crawler.running = false
}
@IBAction func clearLog(_ sender: Any?) {
crawler.log = []
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
switch segue.identifier {
case .some(.pluginDrawerSegue):
crawler.running = false
default:
break
}
}
override func dismissViewController(_ viewController: NSViewController) {
super.dismissViewController(viewController)
for (_, store) in NSApplication.shared.controller.dataLoader.stores {
try? store.persistentContainer.viewContext.save()
store.repository.perform { }
crawler.resetLists()
crawler.updateCrawllist()
}
}
@IBAction func batch(_ sender: Any?) {
// FIXME: Needs separate dialogue with batch configuration
let openPanel = NSOpenPanel()
openPanel.message = "Select file for batch data"
openPanel.nameFieldLabel = "Batch file:"
openPanel.nameFieldStringValue = "Batch job"
openPanel.allowedFileTypes = nil
openPanel.allowsOtherFileTypes = true
openPanel.beginSheetModal(for: view.window!, completionHandler: { response in
switch (response) {
case .OK:
self.prepareForBatch(with: openPanel.url!)
default:
break
}
})
}
// FIXME: Needs separate location
func prepareForBatch(with fileUrl: URL) {
do {
let fileData = try String(contentsOf: fileUrl)
let values = Set(fileData.lazy.split(separator: "\n").map(String.init))
let batchPlugins = NSApplication.shared.controller.crawlers.flatMap { p in p as? TarantulaBatchCapable&TarantulaCrawlingPlugin }
for plugin in batchPlugins {
try plugin.repository?.batch { shadow in
for value in values {
try plugin.addInitialObject(by: value, shadowRepository: shadow)
}
}
}
for plugin in batchPlugins {
plugin.configureFilter(withClosure: { (s) -> Bool in
values.contains(s)
})
}
for (_, store) in NSApplication.shared.controller.dataLoader.stores {
// wait
store.repository.perform { }
crawler.resetLists()
crawler.updateCrawllist()
}
}
catch let e {
self.presentError(e)
}
}
@IBAction func exporting(_ sender: Any?) {
// FIXME: Needs separate dialogue with export configuration
let savePanel = NSSavePanel()
savePanel.message = "Select export location"
savePanel.nameFieldLabel = "Export file:"
savePanel.nameFieldStringValue = "Export" // FIXME: STUB
savePanel.allowedFileTypes = ["json"]
savePanel.allowsOtherFileTypes = false
savePanel.beginSheetModal(for: view.window!, completionHandler: { response in
switch (response) {
case .OK:
self.exportData(url: savePanel.url!)
default:
break
}
})
}
// TEMP EXPORT IMPLEMENTATION BEGIN
struct Container: Encodable {
var value: Encodable
func encode(to encoder: Encoder) throws {
try value.encode(to: encoder)
}
}
func exportData(url: URL) {
// Temporary function implementation for exporting
let tempId = ExportProfile("tempIdStub")
let exporters = NSApplication.shared.controller.crawlers.flatMap { p in p as? TarantulaExportable }
let data = exporters.flatMap { e in e.export(for: tempId) }
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
encoder.dateEncodingStrategy = .iso8601
do {
let preOutput = data.map { d in Container(value: d) }
let output = try encoder.encode(Array(preOutput))
try output.write(to: url)
}
catch let e {
self.presentError(e)
}
}
// TEMP EXPORT IMPLEMENTATION END
var autoscrollLastRow = 0
func autoscrollToBottom() {
if crawler.log.count >= 4,
let docRect = tableLogView.enclosingScrollView?.documentVisibleRect,
docRect.maxY >= tableLogView.rect(ofRow: autoscrollLastRow).minY - 20.0 {
autoscrollLastRow = crawler.log.count - 1
tableLogView.scrollRowToVisible(crawler.log.count - 1)
}
}
var rowHeights: [Int: Float] = [:]
}
extension ViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, didAdd rowView: NSTableRowView, forRow row: Int) {
rowHeights[row] = Float((rowView.view(atColumn: 0) as! NSView).fittingSize.height)
tableView.noteHeightOfRows(withIndexesChanged: [row])
autoscrollToBottom()
}
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return CGFloat(rowHeights[row] ?? Float(tableView.rowHeight))
}
}
| gpl-3.0 |
grpc/grpc-swift | Tests/GRPCTests/ClientEventLoopPreferenceTests.swift | 1 | 5255 | /*
* Copyright 2021, gRPC Authors 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 EchoImplementation
import EchoModel
import GRPC
import NIOCore
import NIOPosix
import XCTest
final class ClientEventLoopPreferenceTests: GRPCTestCase {
private var group: MultiThreadedEventLoopGroup!
private var serverLoop: EventLoop!
private var clientLoop: EventLoop!
private var clientCallbackLoop: EventLoop!
private var server: Server!
private var connection: ClientConnection!
private var echo: Echo_EchoNIOClient {
let options = CallOptions(
eventLoopPreference: .exact(self.clientCallbackLoop),
logger: self.clientLogger
)
return Echo_EchoNIOClient(channel: self.connection, defaultCallOptions: options)
}
override func setUp() {
super.setUp()
self.group = MultiThreadedEventLoopGroup(numberOfThreads: 3)
self.serverLoop = self.group.next()
self.clientLoop = self.group.next()
self.clientCallbackLoop = self.group.next()
XCTAssert(self.serverLoop !== self.clientLoop)
XCTAssert(self.serverLoop !== self.clientCallbackLoop)
XCTAssert(self.clientLoop !== self.clientCallbackLoop)
self.server = try! Server.insecure(group: self.serverLoop)
.withLogger(self.serverLogger)
.withServiceProviders([EchoProvider()])
.bind(host: "localhost", port: 0)
.wait()
self.connection = ClientConnection.insecure(group: self.clientLoop)
.withBackgroundActivityLogger(self.clientLogger)
.connect(host: "localhost", port: self.server.channel.localAddress!.port!)
}
override func tearDown() {
XCTAssertNoThrow(try self.connection.close().wait())
XCTAssertNoThrow(try self.server.close().wait())
XCTAssertNoThrow(try self.group.syncShutdownGracefully())
super.tearDown()
}
private func assertClientCallbackEventLoop(_ eventLoop: EventLoop, line: UInt = #line) {
XCTAssert(eventLoop === self.clientCallbackLoop, line: line)
}
func testUnaryWithDifferentEventLoop() throws {
let get = self.echo.get(.with { $0.text = "Hello!" })
self.assertClientCallbackEventLoop(get.eventLoop)
self.assertClientCallbackEventLoop(get.initialMetadata.eventLoop)
self.assertClientCallbackEventLoop(get.response.eventLoop)
self.assertClientCallbackEventLoop(get.trailingMetadata.eventLoop)
self.assertClientCallbackEventLoop(get.status.eventLoop)
assertThat(try get.response.wait(), .is(.with { $0.text = "Swift echo get: Hello!" }))
assertThat(try get.status.wait(), .hasCode(.ok))
}
func testClientStreamingWithDifferentEventLoop() throws {
let collect = self.echo.collect()
self.assertClientCallbackEventLoop(collect.eventLoop)
self.assertClientCallbackEventLoop(collect.initialMetadata.eventLoop)
self.assertClientCallbackEventLoop(collect.response.eventLoop)
self.assertClientCallbackEventLoop(collect.trailingMetadata.eventLoop)
self.assertClientCallbackEventLoop(collect.status.eventLoop)
XCTAssertNoThrow(try collect.sendMessage(.with { $0.text = "a" }).wait())
XCTAssertNoThrow(try collect.sendEnd().wait())
assertThat(try collect.response.wait(), .is(.with { $0.text = "Swift echo collect: a" }))
assertThat(try collect.status.wait(), .hasCode(.ok))
}
func testServerStreamingWithDifferentEventLoop() throws {
let response = self.clientCallbackLoop.makePromise(of: Void.self)
let expand = self.echo.expand(.with { $0.text = "a" }) { _ in
self.clientCallbackLoop.preconditionInEventLoop()
response.succeed(())
}
self.assertClientCallbackEventLoop(expand.eventLoop)
self.assertClientCallbackEventLoop(expand.initialMetadata.eventLoop)
self.assertClientCallbackEventLoop(expand.trailingMetadata.eventLoop)
self.assertClientCallbackEventLoop(expand.status.eventLoop)
XCTAssertNoThrow(try response.futureResult.wait())
assertThat(try expand.status.wait(), .hasCode(.ok))
}
func testBidirectionalStreamingWithDifferentEventLoop() throws {
let response = self.clientCallbackLoop.makePromise(of: Void.self)
let update = self.echo.update { _ in
self.clientCallbackLoop.preconditionInEventLoop()
response.succeed(())
}
self.assertClientCallbackEventLoop(update.eventLoop)
self.assertClientCallbackEventLoop(update.initialMetadata.eventLoop)
self.assertClientCallbackEventLoop(update.trailingMetadata.eventLoop)
self.assertClientCallbackEventLoop(update.status.eventLoop)
XCTAssertNoThrow(try update.sendMessage(.with { $0.text = "a" }).wait())
XCTAssertNoThrow(try update.sendEnd().wait())
XCTAssertNoThrow(try response.futureResult.wait())
assertThat(try update.status.wait(), .hasCode(.ok))
}
}
| apache-2.0 |
sjtu-meow/iOS | Meow/Article.swift | 1 | 1167 | //
// article.swift
// Meow
//
// Created by 林树子 on 2017/6/30.
// Copyright © 2017年 喵喵喵的伙伴. All rights reserved.
//
import SwiftyJSON
struct Article: ItemProtocol {
var id: Int!
var type: ItemType!
var profile: Profile!
var createTime: Date!
var cover: URL?
var title: String!
var summary: String?
var content: String?
var likeCount: Int!
var commentCount: Int!
var comments: [Comment]!
}
extension Article: JSONConvertible {
static func fromJSON(_ json: JSON) -> Article? {
let item = Item.fromJSON(json)!
var article = self.init()
article.id = item.id
article.type = item.type
article.profile = item.profile
article.createTime = item.createTime
article.cover <- json["cover"]
article.title <- json["title"]
article.summary <- json["summary"]
article.content <- json["content"]
article.likeCount <- json["likeCount"]
article.commentCount <- json["commentCount"]
article.comments <- json["comments"]
return article
}
}
| apache-2.0 |
Tatoeba/tatoeba-ios | Tatoeba/Application/AppDelegate.swift | 1 | 2459 | //
// AppDelegate.swift
// Tatoeba
//
// Created by Jack Cook on 8/5/17.
// Copyright © 2017 Tatoeba. All rights reserved.
//
import CoreSpotlight
import Fuji
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Set default values on first app launch
if !TatoebaUserDefaults.bool(forKey: .defaultsConfigured) {
TatoebaUserDefaults.setDefaultValues()
}
// Start Fuji if the user allows anonymous tracking
if TatoebaUserDefaults.bool(forKey: .sendAnonymousUsageData) {
do {
try Fuji.shared.start()
} catch {
print("Fuji analytics wasn't able to start")
}
}
// Add one to number of app launches
let appLaunches = TatoebaUserDefaults.integer(forKey: .appLaunches) + 1
TatoebaUserDefaults.set(appLaunches, forKey: .appLaunches)
return true
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
if #available(iOS 9.0, *) {
guard userActivity.activityType == CSSearchableItemActionType, let activityId = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String, let sentenceIdString = activityId.components(separatedBy: ".").last, let sentenceId = Int(sentenceIdString) else {
return false
}
SentenceRequest(id: sentenceId).start { sentence in
guard let sentence = sentence, let sentenceController = UIStoryboard.main.instantiateViewController(withIdentifier: .sentenceController) as? SentenceViewController else {
return
}
sentenceController.sentence = sentence
guard let topController = (self.window?.rootViewController as? UINavigationController)?.viewControllers.last else {
return
}
topController.present(sentenceController, animated: true, completion: nil)
}
return true
} else {
return false
}
}
}
| mit |
breadwallet/breadwallet-ios | breadwallet/src/Views/GradientView.swift | 1 | 2356 | //
// GradientView.swift
// breadwallet
//
// Created by Adrian Corscadden on 2016-11-22.
// Copyright © 2016-2019 Breadwinner AG. All rights reserved.
//
import UIKit
protocol GradientDrawable {
func drawGradient(_ rect: CGRect)
}
extension UIView {
func drawGradient(_ rect: CGRect) {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let colors = [UIColor.gradientStart.cgColor, UIColor.gradientEnd.cgColor] as CFArray
let locations: [CGFloat] = [0.0, 1.0]
guard let gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: locations) else { return }
guard let context = UIGraphicsGetCurrentContext() else { return }
context.drawLinearGradient(gradient,
start: CGPoint(x: 0.0, y: rect.height),
end: CGPoint(x: rect.width, y: 0.0),
options: [])
}
func drawGradient(start: UIColor, end: UIColor, _ rect: CGRect) {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let colors = [start.cgColor, end.cgColor] as CFArray
let locations: [CGFloat] = [0.0, 1.0]
guard let gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: locations) else { return }
guard let context = UIGraphicsGetCurrentContext() else { return }
context.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: rect.width, y: 0.0), options: [])
}
func drawGradient(ends: UIColor, middle: UIColor, _ rect: CGRect) {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let colors = [ends.cgColor, middle.cgColor, ends.cgColor] as CFArray
let locations: [CGFloat] = [0.0, 0.5, 1.0]
guard let gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: locations) else { return }
guard let context = UIGraphicsGetCurrentContext() else { return }
context.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: 0, y: rect.height), options: [])
}
}
class GradientView: UIView {
override func draw(_ rect: CGRect) {
drawGradient(rect)
}
}
class DoubleGradientView: UIView {
override func draw(_ rect: CGRect) {
drawGradient(ends: UIColor.white.withAlphaComponent(0.1), middle: UIColor.white.withAlphaComponent(0.6), rect)
}
}
| mit |
NUKisZ/MyTools | MyTools/MyTools/Class/ThirdVC/BKBK/NUKModels/HomePageModel.swift | 1 | 365 | //
// HomePageModel.swift
// NUK
//
// Created by NUK on 16/8/13.
// Copyright © 2016年 NUK. All rights reserved.
//
import UIKit
class HomePageModel: NSObject {
var all_comics:NSNumber?
var cover_image:String?
var id:NSNumber?
var name:String?
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
| mit |
sharath-cliqz/browser-ios | Client/Cliqz/Frontend/Browser/WebView/PrivateBrowsing.swift | 2 | 9652 | //
// PrivateBrowsing.swift
// Client
//
// Reference: https://github.com/brave/browser-ios/blob/development/brave/src/webview/PrivateBrowsing.swift
import Shared
import Deferred
private let _singleton = PrivateBrowsing()
class PrivateBrowsing {
class var singleton: PrivateBrowsing {
return _singleton
}
fileprivate(set) var isOn = false
var nonprivateCookies = [HTTPCookie: Bool]()
// On startup we are no longer in private mode, if there is a .public cookies file, it means app was killed in private mode, so restore the cookies file
func startupCheckIfKilledWhileInPBMode() {
webkitDirLocker(false)
cookiesFileDiskOperation(.restorePublicBackup)
}
enum MoveCookies {
case savePublicBackup
case restorePublicBackup
case deletePublicBackup
}
// GeolocationSites.plist cannot be blocked any other way than locking the filesystem so that webkit can't write it out
// TODO: after unlocking, verify that sites from PB are not in the written out GeolocationSites.plist, based on manual testing this
// doesn't seem to be the case, but more rigourous test cases are needed
fileprivate func webkitDirLocker(_ lock: Bool) {
let fm = FileManager.default
let baseDir = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0]
let webkitDirs = [baseDir + "/WebKit", baseDir + "/Caches"]
for dir in webkitDirs {
do {
try fm.setAttributes([FileAttributeKey.posixPermissions: (lock ? NSNumber(value: 0 as Int16) : NSNumber(value: 0o755 as Int16))], ofItemAtPath: dir)
} catch {
print(error)
}
}
}
fileprivate func cookiesFileDiskOperation( _ type: MoveCookies) {
let fm = FileManager.default
let baseDir = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0]
let cookiesDir = baseDir + "/Cookies"
let originSuffix = type == .savePublicBackup ? "cookies" : ".public"
do {
let contents = try fm.contentsOfDirectory(atPath: cookiesDir)
for item in contents {
if item.hasSuffix(originSuffix) {
if type == .deletePublicBackup {
try fm.removeItem(atPath: cookiesDir + "/" + item)
} else {
var toPath = cookiesDir + "/"
if type == .restorePublicBackup {
toPath += NSString(string: item).deletingPathExtension
} else {
toPath += item + ".public"
}
if fm.fileExists(atPath: toPath) {
do { try fm.removeItem(atPath: toPath) } catch {}
}
try fm.moveItem(atPath: cookiesDir + "/" + item, toPath: toPath)
}
}
}
} catch {
print(error)
}
}
func enter() {
if isOn {
return
}
isOn = true
getApp().tabManager.purgeTabs(includeSelectedTab: true)
self.backupNonPrivateCookies()
self.setupCacheDefaults(memoryCapacity: 0, diskCapacity: 0)
NotificationCenter.default.addObserver(self, selector: #selector(PrivateBrowsing.cookiesChanged(_:)), name: NSNotification.Name.NSHTTPCookieManagerCookiesChanged, object: nil)
webkitDirLocker(true)
}
fileprivate var exitDeferred = Deferred<Void>()
@discardableResult func exit() -> Deferred<Void> {
if !isOn {
let immediateExit = Deferred<Void>()
immediateExit.fill(())
return immediateExit
}
// Since this an instance var, it needs to be used carefully.
// The usage of this deferred, is async, and is generally handled, by a response to a notification
// if it is overwritten, it will lead to race conditions, and generally a dropped deferment, since the
// notification will be executed on _only_ the newest version of this property
exitDeferred = Deferred<Void>()
NotificationCenter.default.removeObserver(self)
NotificationCenter.default.addObserver(self, selector: #selector(allWebViewsKilled), name: NSNotification.Name(rawValue: kNotificationAllWebViewsDeallocated), object: nil)
getApp().tabManager.purgeTabs(includeSelectedTab: true)
postAsyncToMain(2) {
if !self.exitDeferred.isFilled {
self.allWebViewsKilled()
}
}
isOn = false
return exitDeferred
}
@objc func allWebViewsKilled() {
struct ReentrantGuard {
static var inFunc = false
}
if ReentrantGuard.inFunc {
// This is kind of a predicament
// On one hand, we cannot drop promises,
// on the other, if processes are killing webviews, this could end up executing logic that should not happen
// so quickly. A better refactor would be to propogate some piece of data (e.g. Bool), that indicates
// the current state of promise chain (e.g. ReentrantGuard value)
self.exitDeferred.fillIfUnfilled(())
return
}
ReentrantGuard.inFunc = true
NotificationCenter.default.removeObserver(self)
postAsyncToMain(0.1) { // just in case any other webkit object cleanup needs to complete
self.deleteAllCookies()
self.cleanStorage()
self.clearShareHistory()
self.webkitDirLocker(false)
self.cleanProfile()
self.setupCacheDefaults(memoryCapacity: 8, diskCapacity: 50)
self.restoreNonPrivateCookies()
self.exitDeferred.fillIfUnfilled(())
ReentrantGuard.inFunc = false
}
}
private func setupCacheDefaults(memoryCapacity: Int, diskCapacity: Int) { // in MB
URLCache.shared.memoryCapacity = memoryCapacity * 1024 * 1024;
URLCache.shared.diskCapacity = diskCapacity * 1024 * 1024;
}
private func deleteAllCookies() {
let storage = HTTPCookieStorage.shared
if let cookies = storage.cookies {
for cookie in cookies {
storage.deleteCookie(cookie)
}
}
}
private func cleanStorage() {
if let clazz = NSClassFromString("Web" + "StorageManager") as? NSObjectProtocol {
if clazz.responds(to: Selector("shared" + "WebStorageManager")) {
if let storage = clazz.perform(Selector("shared" + "WebStorageManager")) {
let o = storage.takeUnretainedValue()
o.perform(Selector("delete" + "AllOrigins"))
}
}
}
}
private func clearShareHistory() {
if let clazz = NSClassFromString("Web" + "History") as? NSObjectProtocol {
if clazz.responds(to: Selector("optional" + "SharedHistory")) {
if let webHistory = clazz.perform(Selector("optional" + "SharedHistory")) {
let o = webHistory.takeUnretainedValue()
o.perform(Selector("remove" + "AllItems"))
}
}
}
}
private func backupNonPrivateCookies() {
self.cookiesFileDiskOperation(.savePublicBackup)
let storage = HTTPCookieStorage.shared
if let cookies = storage.cookies {
for cookie in cookies {
self.nonprivateCookies[cookie] = true
storage.deleteCookie(cookie)
}
}
}
private func restoreNonPrivateCookies() {
self.cookiesFileDiskOperation(.deletePublicBackup)
let storage = HTTPCookieStorage.shared
for cookie in self.nonprivateCookies {
storage.setCookie(cookie.0)
}
self.nonprivateCookies = [HTTPCookie: Bool]()
}
private func cleanProfile() {
getApp().profile?.shutdown()
getApp().profile?.db.reopenIfClosed()
}
@objc func cookiesChanged(_ info: Notification) {
NotificationCenter.default.removeObserver(self)
let storage = HTTPCookieStorage.shared
var newCookies = [HTTPCookie]()
if let cookies = storage.cookies {
for cookie in cookies {
if let readOnlyProps = cookie.properties {
var props = readOnlyProps as [HTTPCookiePropertyKey: Any]
let discard = props[HTTPCookiePropertyKey.discard] as? String
if discard == nil || discard! != "TRUE" {
props.removeValue(forKey: HTTPCookiePropertyKey.expires)
props[HTTPCookiePropertyKey.discard] = "TRUE"
storage.deleteCookie(cookie)
if let newCookie = HTTPCookie(properties: props) {
newCookies.append(newCookie)
}
}
}
}
}
for c in newCookies {
storage.setCookie(c)
}
NotificationCenter.default.addObserver(self, selector: #selector(PrivateBrowsing.cookiesChanged(_:)), name: NSNotification.Name.NSHTTPCookieManagerCookiesChanged, object: nil)
}
}
| mpl-2.0 |
AndreMuis/TISensorTag | TISensorTag/Views/TSTSimpleKeyView.swift | 1 | 1625 | //
// TSTSimpleKeyView.swift
// TISensorTag
//
// Created by Andre Muis on 5/21/16.
// Copyright © 2016 Andre Muis. All rights reserved.
//
import UIKit
class TSTSimpleKeyView: UIView
{
var depressedFrame : CGRect
var pressedFrame : CGRect
required init?(coder aDecoder: NSCoder)
{
self.depressedFrame = CGRectZero
self.pressedFrame = CGRectZero
super.init(coder: aDecoder)
}
func setup()
{
self.depressedFrame = self.frame
self.pressedFrame = CGRectMake(self.frame.origin.x,
self.frame.origin.y + self.frame.size.height * TSTConstants.SimpleKeyView.depressedPercent,
self.frame.size.width,
self.frame.size.height * (1.0 - TSTConstants.SimpleKeyView.depressedPercent))
let cornerRadius : CGFloat = TSTConstants.SimpleKeyView.cornerRadius
let bezierPath : UIBezierPath = UIBezierPath(roundedRect: self.bounds,
byRoundingCorners: [UIRectCorner.TopLeft, UIRectCorner.TopRight],
cornerRadii: CGSizeMake(cornerRadius, cornerRadius))
let shapeLayer : CAShapeLayer = CAShapeLayer()
shapeLayer.frame = self.bounds
shapeLayer.path = bezierPath.CGPath
self.layer.mask = shapeLayer
}
func press()
{
self.frame = self.pressedFrame
}
func depress()
{
self.frame = self.depressedFrame
}
}
| mit |
PureSwift/Bluetooth | Sources/BluetoothGATT/ATTReadMultipleResponse.swift | 1 | 956 | //
// ATTReadMultipleResponse.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/// Read Multiple Response
///
/// The read response is sent in reply to a received *Read Multiple Request* and
/// contains the values of the attributes that have been read.
@frozen
public struct ATTReadMultipleResponse: ATTProtocolDataUnit, Equatable {
public static var attributeOpcode: ATTOpcode { return .readMultipleResponse }
public var values: Data
public init(values: Data) {
self.values = values
}
public init?(data: Data) {
guard type(of: self).validateOpcode(data)
else { return nil }
self.values = data.suffixCheckingBounds(from: 1)
}
public var data: Data {
return Data([type(of: self).attributeOpcode.rawValue]) + values
}
}
| mit |
ed-chin/EarlGrey | gem/lib/earlgrey/files/Swift-2.3/EarlGrey.swift | 4 | 4324 | //
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import EarlGrey
import Foundation
let greyFailureHandler =
NSThread.currentThread().threadDictionary
.valueForKey(kGREYFailureHandlerKey) as! GREYFailureHandler
public func EarlGrey(file: String = #file, line: UInt = #line) -> EarlGreyImpl! {
return EarlGreyImpl.invokedFromFile(file, lineNumber: line)
}
public func GREYAssert(@autoclosure expression: () -> BooleanType, reason: String) {
GREYAssert(expression, reason, details: "Expected expression to be true")
}
public func GREYAssertTrue(@autoclosure expression: () -> BooleanType, reason: String) {
GREYAssert(expression().boolValue,
reason,
details: "Expected the boolean expression to be true")
}
public func GREYAssertFalse(@autoclosure expression: () -> BooleanType, reason: String) {
GREYAssert(!expression().boolValue,
reason,
details: "Expected the boolean expression to be false")
}
public func GREYAssertNotNil(@autoclosure expression: () -> Any?, reason: String) {
GREYAssert(expression() != nil, reason, details: "Expected expression to be not nil")
}
public func GREYAssertNil(@autoclosure expression: () -> Any?, reason: String) {
GREYAssert(expression() == nil, reason, details: "Expected expression to be nil")
}
public func GREYAssertEqual(@autoclosure left: () -> AnyObject?,
@autoclosure _ right: () -> AnyObject?, reason: String) {
GREYAssert(left() === right(), reason, details: "Expected left term to be equal to right term")
}
public func GREYAssertNotEqual(@autoclosure left: () -> AnyObject?,
@autoclosure _ right: () -> AnyObject?, reason: String) {
GREYAssert(left() !== right(), reason, details: "Expected left term to not be equal to right" +
" term")
}
public func GREYAssertEqualObjects<T : Equatable>(@autoclosure left: () -> T?,
@autoclosure _ right: () -> T?, reason: String) {
GREYAssert(left() == right(), reason, details: "Expected object of the left term to be equal" +
" to the object of the right term")
}
public func GREYAssertNotEqualObjects<T : Equatable>(@autoclosure left: () -> T?,
@autoclosure _ right: () -> T?, reason: String) {
GREYAssert(left() != right(), reason, details: "Expected object of the left term to not be" +
" equal to the object of the right term")
}
public func GREYFail(reason: String) {
greyFailureHandler.handleException(GREYFrameworkException(name: kGREYAssertionFailedException,
reason: reason),
details: "")
}
@available(*, deprecated=1.2.0, message="Please use GREYFAIL::withDetails instead.")
public func GREYFail(reason: String, details: String) {
greyFailureHandler.handleException(GREYFrameworkException(name: kGREYAssertionFailedException,
reason: reason),
details: details)
}
public func GREYFailWithDetails(reason: String, details: String) {
greyFailureHandler.handleException(GREYFrameworkException(name: kGREYAssertionFailedException,
reason: reason),
details: details)
}
private func GREYAssert(@autoclosure expression: () -> BooleanType,
_ reason: String, details: String) {
GREYSetCurrentAsFailable()
GREYWaitUntilIdle()
if !expression().boolValue {
greyFailureHandler.handleException(GREYFrameworkException(name: kGREYAssertionFailedException,
reason: reason),
details: details)
}
}
private func GREYWaitUntilIdle() {
GREYUIThreadExecutor.sharedInstance().drainUntilIdle()
}
private func GREYSetCurrentAsFailable(file: String = #file, line: UInt = #line) {
let greyFailureHandlerSelector =
#selector(GREYFailureHandler.setInvocationFile(_:andInvocationLine:))
if greyFailureHandler.respondsToSelector(greyFailureHandlerSelector) {
greyFailureHandler.setInvocationFile!(file, andInvocationLine: line)
}
}
| apache-2.0 |
boxenjim/SwiftyFaker | SwiftyFakerTests/NumberTests.swift | 1 | 3086 | //
// NumberTests.swift
// SwiftyFaker
//
// Created by Jim Schultz on 10/14/15.
// Copyright © 2015 Jim Schultz. All rights reserved.
//
import XCTest
@testable import SwiftyFaker
class NumberTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testNumber() {
let number = Faker.Number.number()
XCTAssertEqual(5, "\(number)".characters.count, "number digit count should match 5")
}
func testNumberWithDigits() {
let digits = Int.random(1...10)
let number = Faker.Number.number(digits)
XCTAssertEqual(digits, "\(number)".characters.count, "number digit count should match \(digits)")
}
func testDecimal() {
let digits = Int.random(1...10)
let number = Faker.Number.decimal(digits)
XCTAssertEqual("\(number)".characters.count, digits + 2 + 1)
// let comps = "\(number)".componentsSeparatedByString(".")
// XCTAssertEqual(comps.first?.characters.count, digits, "digits count should match \(digits)")
// XCTAssertEqual(comps.last?.characters.count, 2, "digit after decimal count should match 2")
}
func testDecimalWithAfterDigits() {
let digits = Int.random(1...10)
let afterDigits = Int.random(1...(15-digits))
let number = Faker.Number.decimal(digits, digitsAfter: afterDigits)
XCTAssertEqual("\(number)".characters.count, digits + afterDigits + 1)
// let comps = "\(number)".componentsSeparatedByString(".")
// XCTAssertEqual(comps.first?.characters.count, digits, "digits count should match \(digits)")
// XCTAssertEqual(comps.last?.characters.count, afterDigits, "digit after decimal count should match \(afterDigits)")
}
func testHexadecimal() {
}
func testBetweenInts() {
let min = Int.random(0...100)
let max = Int.random(min...200)
let num = Faker.Number.between(min...max)
XCTAssertTrue(num >= min && num <= max, "betweenInt should be between \(min) and \(max)")
}
func testBetweenDoubles() {
let min = Double.random(0.0, max: 100.0)
let max = Double.random(min, max: 200.0)
let num = Faker.Number.between(min, max: max)
XCTAssertTrue(num >= min && num <= max, "betweenDouble should be between \(min) and \(max)")
}
func testPositive() {
let num = Faker.Number.positive()
XCTAssertTrue(num > 0, "positive should be > 0")
}
func testNegative() {
let num = Faker.Number.negative()
XCTAssertTrue(num < 0, "negative should be < 0")
}
func testDigit() {
let digit = Faker.Number.digit()
XCTAssertTrue(digit >= 0 && digit <= 9, "digit should be between 0 and 9")
}
}
| mit |
february29/Learning | swift/Fch_Contact/Pods/RxSwift/RxSwift/Traits/PrimitiveSequence+Zip+arity.swift | 43 | 33509 | // This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project
//
// PrimitiveSequence+Zip+arity.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/23/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
// 2
extension PrimitiveSequenceType where TraitType == SingleTrait {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, resultSelector: @escaping (E1, E2) throws -> ElementType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where ElementType == Any, TraitType == SingleTrait {
/**
Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>)
-> PrimitiveSequence<TraitType, (E1, E2)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable())
)
}
}
extension PrimitiveSequenceType where TraitType == MaybeTrait {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, resultSelector: @escaping (E1, E2) throws -> ElementType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where ElementType == Any, TraitType == MaybeTrait {
/**
Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>)
-> PrimitiveSequence<TraitType, (E1, E2)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable())
)
}
}
// 3
extension PrimitiveSequenceType where TraitType == SingleTrait {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, resultSelector: @escaping (E1, E2, E3) throws -> ElementType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where ElementType == Any, TraitType == SingleTrait {
/**
Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>)
-> PrimitiveSequence<TraitType, (E1, E2, E3)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable())
)
}
}
extension PrimitiveSequenceType where TraitType == MaybeTrait {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, resultSelector: @escaping (E1, E2, E3) throws -> ElementType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where ElementType == Any, TraitType == MaybeTrait {
/**
Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>)
-> PrimitiveSequence<TraitType, (E1, E2, E3)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable())
)
}
}
// 4
extension PrimitiveSequenceType where TraitType == SingleTrait {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>, resultSelector: @escaping (E1, E2, E3, E4) throws -> ElementType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where ElementType == Any, TraitType == SingleTrait {
/**
Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>)
-> PrimitiveSequence<TraitType, (E1, E2, E3, E4)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable())
)
}
}
extension PrimitiveSequenceType where TraitType == MaybeTrait {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>, resultSelector: @escaping (E1, E2, E3, E4) throws -> ElementType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where ElementType == Any, TraitType == MaybeTrait {
/**
Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>)
-> PrimitiveSequence<TraitType, (E1, E2, E3, E4)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable())
)
}
}
// 5
extension PrimitiveSequenceType where TraitType == SingleTrait {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>, _ source5: PrimitiveSequence<TraitType, E5>, resultSelector: @escaping (E1, E2, E3, E4, E5) throws -> ElementType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where ElementType == Any, TraitType == SingleTrait {
/**
Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>, _ source5: PrimitiveSequence<TraitType, E5>)
-> PrimitiveSequence<TraitType, (E1, E2, E3, E4, E5)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable())
)
}
}
extension PrimitiveSequenceType where TraitType == MaybeTrait {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>, _ source5: PrimitiveSequence<TraitType, E5>, resultSelector: @escaping (E1, E2, E3, E4, E5) throws -> ElementType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where ElementType == Any, TraitType == MaybeTrait {
/**
Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>, _ source5: PrimitiveSequence<TraitType, E5>)
-> PrimitiveSequence<TraitType, (E1, E2, E3, E4, E5)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable())
)
}
}
// 6
extension PrimitiveSequenceType where TraitType == SingleTrait {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5, E6>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>, _ source5: PrimitiveSequence<TraitType, E5>, _ source6: PrimitiveSequence<TraitType, E6>, resultSelector: @escaping (E1, E2, E3, E4, E5, E6) throws -> ElementType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where ElementType == Any, TraitType == SingleTrait {
/**
Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5, E6>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>, _ source5: PrimitiveSequence<TraitType, E5>, _ source6: PrimitiveSequence<TraitType, E6>)
-> PrimitiveSequence<TraitType, (E1, E2, E3, E4, E5, E6)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable())
)
}
}
extension PrimitiveSequenceType where TraitType == MaybeTrait {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5, E6>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>, _ source5: PrimitiveSequence<TraitType, E5>, _ source6: PrimitiveSequence<TraitType, E6>, resultSelector: @escaping (E1, E2, E3, E4, E5, E6) throws -> ElementType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where ElementType == Any, TraitType == MaybeTrait {
/**
Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5, E6>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>, _ source5: PrimitiveSequence<TraitType, E5>, _ source6: PrimitiveSequence<TraitType, E6>)
-> PrimitiveSequence<TraitType, (E1, E2, E3, E4, E5, E6)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable())
)
}
}
// 7
extension PrimitiveSequenceType where TraitType == SingleTrait {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5, E6, E7>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>, _ source5: PrimitiveSequence<TraitType, E5>, _ source6: PrimitiveSequence<TraitType, E6>, _ source7: PrimitiveSequence<TraitType, E7>, resultSelector: @escaping (E1, E2, E3, E4, E5, E6, E7) throws -> ElementType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(), source7.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where ElementType == Any, TraitType == SingleTrait {
/**
Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5, E6, E7>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>, _ source5: PrimitiveSequence<TraitType, E5>, _ source6: PrimitiveSequence<TraitType, E6>, _ source7: PrimitiveSequence<TraitType, E7>)
-> PrimitiveSequence<TraitType, (E1, E2, E3, E4, E5, E6, E7)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(), source7.asObservable())
)
}
}
extension PrimitiveSequenceType where TraitType == MaybeTrait {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5, E6, E7>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>, _ source5: PrimitiveSequence<TraitType, E5>, _ source6: PrimitiveSequence<TraitType, E6>, _ source7: PrimitiveSequence<TraitType, E7>, resultSelector: @escaping (E1, E2, E3, E4, E5, E6, E7) throws -> ElementType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(), source7.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where ElementType == Any, TraitType == MaybeTrait {
/**
Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5, E6, E7>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>, _ source5: PrimitiveSequence<TraitType, E5>, _ source6: PrimitiveSequence<TraitType, E6>, _ source7: PrimitiveSequence<TraitType, E7>)
-> PrimitiveSequence<TraitType, (E1, E2, E3, E4, E5, E6, E7)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(), source7.asObservable())
)
}
}
// 8
extension PrimitiveSequenceType where TraitType == SingleTrait {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5, E6, E7, E8>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>, _ source5: PrimitiveSequence<TraitType, E5>, _ source6: PrimitiveSequence<TraitType, E6>, _ source7: PrimitiveSequence<TraitType, E7>, _ source8: PrimitiveSequence<TraitType, E8>, resultSelector: @escaping (E1, E2, E3, E4, E5, E6, E7, E8) throws -> ElementType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(), source7.asObservable(), source8.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where ElementType == Any, TraitType == SingleTrait {
/**
Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5, E6, E7, E8>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>, _ source5: PrimitiveSequence<TraitType, E5>, _ source6: PrimitiveSequence<TraitType, E6>, _ source7: PrimitiveSequence<TraitType, E7>, _ source8: PrimitiveSequence<TraitType, E8>)
-> PrimitiveSequence<TraitType, (E1, E2, E3, E4, E5, E6, E7, E8)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(), source7.asObservable(), source8.asObservable())
)
}
}
extension PrimitiveSequenceType where TraitType == MaybeTrait {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5, E6, E7, E8>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>, _ source5: PrimitiveSequence<TraitType, E5>, _ source6: PrimitiveSequence<TraitType, E6>, _ source7: PrimitiveSequence<TraitType, E7>, _ source8: PrimitiveSequence<TraitType, E8>, resultSelector: @escaping (E1, E2, E3, E4, E5, E6, E7, E8) throws -> ElementType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(), source7.asObservable(), source8.asObservable(),
resultSelector: resultSelector)
)
}
}
extension PrimitiveSequenceType where ElementType == Any, TraitType == MaybeTrait {
/**
Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<E1, E2, E3, E4, E5, E6, E7, E8>(_ source1: PrimitiveSequence<TraitType, E1>, _ source2: PrimitiveSequence<TraitType, E2>, _ source3: PrimitiveSequence<TraitType, E3>, _ source4: PrimitiveSequence<TraitType, E4>, _ source5: PrimitiveSequence<TraitType, E5>, _ source6: PrimitiveSequence<TraitType, E6>, _ source7: PrimitiveSequence<TraitType, E7>, _ source8: PrimitiveSequence<TraitType, E8>)
-> PrimitiveSequence<TraitType, (E1, E2, E3, E4, E5, E6, E7, E8)> {
return PrimitiveSequence(raw: Observable.zip(
source1.asObservable(), source2.asObservable(), source3.asObservable(), source4.asObservable(), source5.asObservable(), source6.asObservable(), source7.asObservable(), source8.asObservable())
)
}
}
| mit |
ais-recognition/speaker | SpeakerClientTests/speakerTests.swift | 1 | 884 | //
// speakerTests.swift
// speakerTests
//
// Created by to0 on 2/26/15.
// Copyright (c) 2015 to0. All rights reserved.
//
import UIKit
import XCTest
class speakerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
lachatak/lift | ios/Lift/LiftServer/LiftServerURLs.swift | 2 | 8147 | import Foundation
///
/// The request to the Lift server-side code
///
struct LiftServerRequest {
var path: String
var method: Method
init(path: String, method: Method) {
self.path = path
self.method = method
}
}
///
/// Defines mechanism to convert a request to LiftServerRequest
///
protocol LiftServerRequestConvertible {
var Request: LiftServerRequest { get }
}
///
/// The Lift server URLs and request data mappers
///
enum LiftServerURLs : LiftServerRequestConvertible {
///
/// Register the user
///
case UserRegister()
///
/// Login the user
///
case UserLogin()
///
/// Adds an iOS device for the user identified by ``userId``
///
case UserRegisterDevice(/*userId: */NSUUID)
///
/// Retrieves the user's profile for the ``userId``
///
case UserGetPublicProfile(/*userId: */NSUUID)
///
/// Sets the user's profile for the ``userId``
///
case UserSetPublicProfile(/*userId: */NSUUID)
///
/// Gets the user's profile image
///
case UserGetProfileImage(/*userId: */NSUUID)
///
/// Sets the user's profile image
///
case UserSetProfileImage(/*userId: */NSUUID)
///
/// Checks that the account is still there
///
case UserCheckAccount(/*userId: */NSUUID)
///
/// Get supported muscle groups
///
case ExerciseGetMuscleGroups()
///
/// Retrieves all the exercises for the given ``userId`` and ``date``
///
case ExerciseGetExerciseSessionsSummary(/*userId: */NSUUID, /*date: */NSDate)
///
/// Retrieves all the session dates for the given ``userId``
///
case ExerciseGetExerciseSessionsDates(/*userId: */NSUUID)
///
/// Retrieves all the exercises for the given ``userId`` and ``sessionId``
///
case ExerciseGetExerciseSession(/*userId: */NSUUID, /*sessionId: */NSUUID)
///
/// Deletes all the exercises for the given ``userId`` and ``sessionId``
///
case ExerciseDeleteExerciseSession(/*userId: */NSUUID, /*sessionId: */NSUUID)
///
/// Starts an exercise session for the given ``userId``
///
case ExerciseSessionStart(/*userId: */NSUUID)
///
/// Abandons the exercise session for the given ``userId`` and ``sessionId``.
///
case ExerciseSessionAbandon(/*userId: */NSUUID, /*sessionId: */NSUUID)
///
/// Starts the replay of an existing session for the given user
///
case ExerciseSessionReplayStart(/*userId: */NSUUID, /* sessionId */ NSUUID)
///
/// Replays the exercise session for the given ``userId`` and ``sessionId``.
///
case ExerciseSessionReplayData(/*userId: */NSUUID, /*sessionId: */NSUUID)
///
/// Submits the data (received from the smartwatch) for the given ``userId``, ``sessionId``
///
case ExerciseSessionSubmitData(/*userId: */NSUUID, /*sessionId: */NSUUID)
///
/// Gets exercise classification examples for the given ``userId`` and ``sessionId``
///
case ExerciseSessionGetClassificationExamples(/*userId: */NSUUID, /*sessionId: */NSUUID)
///
/// Ends the session for the given ``userId`` and ``sessionId``
///
case ExerciseSessionEnd(/*userId: */NSUUID, /*sessionId: */NSUUID)
///
/// Starts the explicit exercise classification for ``userId`` and ``sessionId``
///
case ExplicitExerciseClassificationStart(/*userId: */NSUUID, /*sessionId: */NSUUID)
///
/// Stops the explicit exercise classification for ``userId`` and ``sessionId``
///
case ExplicitExerciseClassificationStop(/*userId: */NSUUID, /*sessionId: */NSUUID)
private struct Format {
private static let simpleDateFormatter: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter
}()
static func simpleDate(date: NSDate) -> String {
return simpleDateFormatter.stringFromDate(date)
}
}
// MARK: URLStringConvertible
var Request: LiftServerRequest {
get {
let r: LiftServerRequest = {
switch self {
case let .UserRegister: return LiftServerRequest(path: "/user", method: Method.POST)
case let .UserLogin: return LiftServerRequest(path: "/user", method: Method.PUT)
case .UserRegisterDevice(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)/device/ios", method: Method.POST)
case .UserGetPublicProfile(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)", method: Method.GET)
case .UserSetPublicProfile(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)", method: Method.POST)
case .UserCheckAccount(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)/check", method: Method.GET)
case .UserGetProfileImage(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)/image", method: Method.GET)
case .UserSetProfileImage(let userId): return LiftServerRequest(path: "/user/\(userId.UUIDString)/image", method: Method.POST)
case .ExerciseGetMuscleGroups(): return LiftServerRequest(path: "/exercise/musclegroups", method: Method.GET)
case .ExerciseGetExerciseSessionsSummary(let userId, let date): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)?date=\(Format.simpleDate(date))", method: Method.GET)
case .ExerciseGetExerciseSessionsDates(let userId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)", method: Method.GET)
case .ExerciseGetExerciseSession(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)", method: Method.GET)
case .ExerciseDeleteExerciseSession(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)", method: Method.DELETE)
case .ExerciseSessionStart(let userId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/start", method: Method.POST)
case .ExerciseSessionSubmitData(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)", method: Method.PUT)
case .ExerciseSessionEnd(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/end", method: Method.POST)
case .ExerciseSessionAbandon(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/abandon", method: Method.POST)
case .ExerciseSessionReplayStart(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/replay", method: Method.POST)
case .ExerciseSessionReplayData(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/replay", method: Method.PUT)
case .ExerciseSessionGetClassificationExamples(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/classification", method: Method.GET)
case .ExplicitExerciseClassificationStart(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/classification", method: Method.POST)
case .ExplicitExerciseClassificationStop(let userId, let sessionId): return LiftServerRequest(path: "/exercise/\(userId.UUIDString)/\(sessionId.UUIDString)/classification", method: Method.DELETE)
}
}()
return r
}
}
}
| apache-2.0 |
victoraliss0n/FireRecord | FireRecord/Source/Extensions/Storage/Uploadable+Extension.swift | 2 | 124 | //
// Uploadable+Extension.swift
// FirebaseCommunity
//
// Created by David Sanford on 25/08/17.
//
import Foundation
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.