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 |
---|---|---|---|---|---|
silence0201/Swift-Study | AdvancedSwift/协议/Sequences/Sequences - Conforming to Sequence.playgroundpage/Contents.swift | 1 | 2079 | /*:
#### Conforming to Sequence
An example of an iterator that produces a finite sequence is the following
`PrefixIterator`, which generates all prefixes of a string (including the string
itself). It starts at the beginning of the string, and with each call of `next`,
increments the slice of the string it returns by one character until it reaches
the end:
*/
//#-editable-code
struct PrefixIterator: IteratorProtocol {
let string: String
var offset: String.Index
init(string: String) {
self.string = string
offset = string.startIndex
}
mutating func next() -> String? {
guard offset < string.endIndex else { return nil }
offset = string.index(after: offset)
return string[string.startIndex..<offset]
}
}
//#-end-editable-code
/*:
(`string[string.startIndex..<offset]` is a slicing operation that returns the
substring between the start and the offset — we'll talk more about slicing
later.)
With `PrefixIterator` in place, defining the accompanying `PrefixSequence` type
is easy. Again, it isn't necessary to specify the associated `Iterator` type
explicitly because the compiler can infer it from the return type of the
`makeIterator` method:
*/
//#-editable-code
struct PrefixSequence: Sequence {
let string: String
func makeIterator() -> PrefixIterator {
return PrefixIterator(string: string)
}
}
//#-end-editable-code
/*:
Now we can use a `for` loop to iterate over all the prefixes:
*/
//#-editable-code
for prefix in PrefixSequence(string: "Hello") {
print(prefix)
}
//#-end-editable-code
/*:
Or we can perform any other operation provided by `Sequence`:
*/
//#-editable-code
PrefixSequence(string: "Hello").map { $0.uppercased() }
//#-end-editable-code
/*:
We can create sequences for `ConstantIterator` and `FibsIterator` in the same
way. We're not showing them here, but you may want to try this yourself. Just
keep in mind that these iterators create infinite sequences. Use a construct
like `for i in fibsSequence.prefix(10)` to slice off a finite piece.
*/
| mit |
silence0201/Swift-Study | Swifter/05Tuple.playground/Contents.swift | 1 | 440 | //: Playground - noun: a place where people can play
import UIKit
func swapMe1<T>(a: inout T ,b: inout T) {
let temp = a
a = b
b = temp
}
func swapMe2<T>(a: inout T, b: inout T) {
(a,b) = (b,a)
}
var a = 1
var b = 2
(a,b)
swapMe1(a: &a, b: &b)
(a,b)
swapMe2(a: &a, b: &b)
(a,b)
let rect = CGRect(x: 0, y: 0, width: 100, height: 100)
let (small, large) = rect.divided(atDistance: 20, from: .minXEdge)
small
large
| mit |
frograin/FluidValidator | Pod/Classes/Core/FailMessage.swift | 1 | 1173 | //
// FailMessage.swift
// TestValidator
//
// Created by FrogRain on 31/01/16.
// Copyright © 2016 FrogRain. All rights reserved.
//
import Foundation
open class FailMessage : NSObject {
open var summary:ErrorMessage
open var localizedSubject:String?
open var errors:Array<ErrorMessage>
fileprivate var opaqueDict:Dictionary<String, FailMessage>
override init() {
self.summary = ErrorMessage()
self.errors = Array<ErrorMessage>()
self.opaqueDict = Dictionary<String, FailMessage>()
super.init()
}
open func failingFields () -> [String] {
return self.opaqueDict.keys.map { (key) -> String in
key
}
}
func setObject(_ object:FailMessage, forKey:String) {
self.opaqueDict[forKey] = object;
}
override open func value(forKeyPath keyPath: String) -> Any? {
let dict = self.opaqueDict as NSDictionary
return dict.value(forKeyPath: keyPath) as? FailMessage
}
open func failMessageForPath(_ keyPath: String) -> FailMessage? {
return self.value(forKeyPath: keyPath) as? FailMessage
}
}
| mit |
masd-duc/Keyboardy-PR1 | Keyboardy PR1Tests/Keyboardy_PR1Tests.swift | 1 | 990 | //
// Keyboardy_PR1Tests.swift
// Keyboardy PR1Tests
//
// Created by Duc iOS on 10/7/15.
// Copyright © 2015 Duc iOS. All rights reserved.
//
import XCTest
@testable import Keyboardy_PR1
class Keyboardy_PR1Tests: 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.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| gpl-2.0 |
jbgann/gratuify | gratuify/ColorSettingsViewController.swift | 1 | 6512 | //
// ColorSettingsViewController.swift
// Gratuify
//
// Created by John Gann on 12/16/15.
// Copyright © 2015 John Gann. All rights reserved.
//
import UIKit
extension UIColor {
var components:(red: CGFloat, green: CGFloat, blue: CGFloat, alpha:CGFloat){
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
return (r,g,b,a)
}
}
class ColorSettingsViewController: UIViewController, UIPickerViewDelegate,UIPickerViewDataSource {
@IBOutlet weak var compositeBlock: UIView!
@IBOutlet weak var redBlock: UIView!
@IBOutlet weak var greenBlock: UIView!
@IBOutlet weak var blueBlock: UIView!
@IBOutlet weak var colorTypePicker: UIPickerView!
var redRot = 0.5 as CGFloat
var blueRot = 0.5 as CGFloat
var greenRot = 0.5 as CGFloat
func packColor(aColor : UIColor, colorName : String){
let defaults = NSUserDefaults.standardUserDefaults()
let redString = colorName + "RED"
let greenString = colorName + "GREEN"
let blueString = colorName + "BLUE"
defaults.setObject(true, forKey: colorName)
defaults.setObject(aColor.components.red,forKey : redString)
defaults.setObject(aColor.components.green,forKey : greenString)
defaults.setObject(aColor.components.blue,forKey : blueString)
}
func unPackColor(colorName: String) -> UIColor {
var r : CGFloat
var g: CGFloat
var b: CGFloat
let defaults = NSUserDefaults.standardUserDefaults()
let redString = colorName + "RED"
let greenString = colorName + "GREEN"
let blueString = colorName + "BLUE"
r = defaults.objectForKey(redString) as! CGFloat
g = defaults.objectForKey(greenString)as! CGFloat
b = defaults.objectForKey(blueString)as! CGFloat
return UIColor(red: r, green: g, blue: b, alpha: 1.0)
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
if pickerView == colorTypePicker{
return 1
}
return 0
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
if pickerView == colorTypePicker {
return 2
}
return 0
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{
if row==1{
return "Text"
}
return "Background"
}
func pickerView(_pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){
setCompositeFromPicker()
}
override func viewDidLoad() {
super.viewDidLoad()
colorTypePicker.dataSource=self
colorTypePicker!.delegate = self
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated : Bool){
super.viewWillAppear(animated)
setCompositeFromPicker()
}
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.
}
*/
func setCompositeFromPicker(){
let choice = colorTypePicker.selectedRowInComponent(0)
if choice == 1 {
compositeBlock.backgroundColor=unPackColor("textColor")
}
if choice == 0{
compositeBlock.backgroundColor=unPackColor("backgroundColor")
}
}
func packFromPicker(){
let choice = colorTypePicker.selectedRowInComponent(0)
if choice == 1 {
packColor(compositeBlock.backgroundColor!, colorName : "textColor")
}
if choice == 0{
packColor(compositeBlock.backgroundColor!, colorName : "backgroundColor")
}
}
func updateCompositeBlock(){
var workingColor = redBlock.backgroundColor
let r = workingColor!.components.red as CGFloat
workingColor = blueBlock.backgroundColor
let b = workingColor!.components.blue
workingColor = greenBlock.backgroundColor
let g = workingColor!.components.green
compositeBlock.backgroundColor=UIColor(red: r, green: g, blue: b , alpha: 1.0)
packFromPicker()
}
func setComponentsFromComposite(){
redBlock.backgroundColor=UIColor(red:compositeBlock.backgroundColor!.components.red, green: 0.0, blue: 0.0, alpha: 1.0)
greenBlock.backgroundColor=UIColor(red : 0.0, green:compositeBlock.backgroundColor!.components.green, blue: 0.0, alpha: 1.0)
blueBlock.backgroundColor=UIColor(red: 0.0, green : 0.0, blue : compositeBlock.backgroundColor!.components.blue, alpha: 1.0)
}
@IBAction func rotateRed(sender: UIRotationGestureRecognizer) {
redBlock.backgroundColor=UIColor(red: (redRot+((sender.rotation / 4.0 ) % 1.0 ) ) % 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
updateCompositeBlock()
if sender.state == .Ended{
let savedColor = redBlock.backgroundColor
redRot = savedColor!.components.red as CGFloat
print("rotation ended")
}
}
@IBAction func rotateGreen(sender: UIRotationGestureRecognizer) {
greenBlock.backgroundColor=UIColor(red: 0.0, green: (redRot+((sender.rotation / 4.0 ) % 1.0 ) ) % 1.0, blue: 0.0, alpha: 1.0)
updateCompositeBlock()
if sender.state == .Ended{
let savedColor = greenBlock.backgroundColor
greenRot = savedColor!.components.green as CGFloat
print("rotation ended")
}
}
@IBAction func rotateBlue(sender: UIRotationGestureRecognizer) {
blueBlock.backgroundColor=UIColor(red: 0.0 , green: 0.0 , blue: (blueRot+((sender.rotation / 4.0 ) % 1.0 ) ) % 1.0,alpha: 1.0)
updateCompositeBlock()
if sender.state == .Ended{
let savedColor = blueBlock.backgroundColor
blueRot = savedColor!.components.blue as CGFloat
print("rotation ended")
}
}
}
| apache-2.0 |
PabloAlejandro/Transitions | Transitions/Controllers/TransitionViewController.swift | 1 | 1677 | //
// TransitionViewController.swift
// Transitions
//
// Created by Pau on 17/02/2017.
// Copyright © 2017 Pau. All rights reserved.
//
import Foundation
import UIKit
open class TransitionViewController: UIViewController {
fileprivate(set) var transition: ViewTransition?
public var transitionConfiguration: TransitionConfiguration! {
didSet {
self.transition = GenericTransition(withViewController: self, configuration: transitionConfiguration)
}
}
public func present(_ viewControllerToPresent: UIViewController, presentBlock: @escaping TransitionBlock, completion: (() -> Void)? = nil) {
if let transition = transition {
transition.present(viewController: viewControllerToPresent, withBlock: presentBlock, completion: completion)
} else {
super.present(viewControllerToPresent, animated: true, completion: completion)
}
}
public func dismiss(dismissBlock: @escaping TransitionBlock, completion: (() -> Void)? = nil) {
if let transition = transition {
transition.dismiss(viewController: self, withBlock: dismissBlock, completion: completion)
} else {
super.dismiss(animated: true, completion: completion)
}
}
}
extension TransitionViewController: Transition {
public var interactive: Bool {
return transition?.interactive ?? false
}
public func update(progress: Float) {
transition?.update(progress: progress)
}
public func complete() {
transition?.complete()
}
public func cancel() {
transition?.cancel()
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/06483-getselftypeforcontainer.swift | 11 | 200 | // 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 b{func b<typealias b:b | mit |
austinzheng/swift-compiler-crashes | fixed/00009-class-referencing-protocol-referencing-class.swift | 12 | 160 | // Test case submitted to project by https://github.com/practicalswift (practicalswift)
protocol b {
var a: c<b> {
get
}
}
class c<d : b> {
}
| mit |
eurofurence/ef-app_ios | Packages/EurofurenceComponents/Tests/EventFeedbackComponentTests/Presenter/Submit Feedback Tapped/WhenEventFeedbackScenePreparesFeedback_EventFeedbackPresenterShould.swift | 1 | 1011 | import EventFeedbackComponent
import XCTest
class WhenEventFeedbackScenePreparesFeedback_EventFeedbackPresenterShould: XCTestCase {
func testSubmitTheFeedback() {
let context = EventFeedbackPresenterTestBuilder().build()
context.simulateSceneDidLoad()
let expectedFeedback = String.random
let sceneRating = Float.random
let expectedRating = Int((sceneRating * 10) / 2)
context.scene.simulateFeedbackTextDidChange(expectedFeedback)
context.scene.simulateFeedbackRatioDidChange(sceneRating)
context.scene.simulateSubmitFeedbackTapped()
let feedback = context.event.lastGeneratedFeedback
XCTAssertEqual(feedback?.feedback, expectedFeedback)
XCTAssertEqual(feedback?.starRating, expectedRating)
XCTAssertEqual(feedback?.state, .submitted)
XCTAssertEqual(context.scene.feedbackState, .inProgress)
XCTAssertEqual(context.scene.navigationControlsState, .disabled)
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/02637-swift-sourcemanager-getmessage.swift | 11 | 223 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
case c,
{
let end = [Void{
struct S
{
class
case c,
| mit |
massada/swift-collections | CollectionsTests/PriorityQueueTests.swift | 1 | 6666 | //
// PriorityQueueTests.swift
// Collections
//
// Copyright (c) 2016 José Massada <jose.massada@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import XCTest
@testable import Collections
class PriorityQueueTests : XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testInitialises() {
let queue = PriorityQueue<Int>()
XCTAssertTrue(queue.isEmpty)
XCTAssertEqual(0, queue.count)
XCTAssertEqual(nil, queue.front)
}
func testInitialisesWithNaturalOrdering() {
let queue = PriorityQueue<Int>(isOrdered: <)
XCTAssertTrue(queue.isEmpty)
XCTAssertEqual(0, queue.count)
XCTAssertEqual(nil, queue.front)
}
func testInitialisesWithNonNaturalOrdering() {
let queue = PriorityQueue<Int>(isOrdered: >)
XCTAssertTrue(queue.isEmpty)
XCTAssertEqual(0, queue.count)
XCTAssertEqual(nil, queue.front)
}
func testInitialisesFromEmptyArrayLiteral() {
let queue: PriorityQueue<Int> = []
XCTAssertTrue(queue.isEmpty)
XCTAssertEqual(0, queue.count)
XCTAssertEqual(nil, queue.front)
}
func testInitialisesFromArrayLiteral() {
let queue: PriorityQueue<Int> = [1, 2, 3]
XCTAssertFalse(queue.isEmpty)
XCTAssertEqual(3, queue.count)
XCTAssertEqual(1, queue.front)
for (i, element) in queue.enumerated() {
XCTAssertEqual(i + 1, element)
}
}
func testInitialisesFromEmptySequence() {
let queue = PriorityQueue<Int>([])
XCTAssertTrue(queue.isEmpty)
XCTAssertEqual(0, queue.count)
XCTAssertEqual(nil, queue.front)
}
func testInitialisesFromEmptySequenceWithNaturalOrdering() {
let queue = PriorityQueue<Int>([], isOrdered: <)
XCTAssertTrue(queue.isEmpty)
XCTAssertEqual(0, queue.count)
XCTAssertEqual(nil, queue.front)
}
func testInitialisesFromEmptySequenceWithNonNaturalOrdering() {
let queue = PriorityQueue<Int>([], isOrdered: >)
XCTAssertTrue(queue.isEmpty)
XCTAssertEqual(0, queue.count)
XCTAssertEqual(nil, queue.front)
}
func testInitialisesFromSequence() {
let queue = PriorityQueue<Int>([1, 2, 3])
XCTAssertFalse(queue.isEmpty)
XCTAssertEqual(3, queue.count)
XCTAssertEqual(1, queue.front)
for (i, element) in queue.enumerated() {
XCTAssertEqual(i + 1, element)
}
}
func testInitialisesFromSequenceWithNaturalOrdering() {
let queue = PriorityQueue<Int>([1, 2, 3], isOrdered: <)
XCTAssertFalse(queue.isEmpty)
XCTAssertEqual(3, queue.count)
XCTAssertEqual(1, queue.front)
for (i, element) in queue.enumerated() {
XCTAssertEqual(i + 1, element)
}
}
func testInitialisesFromSequenceWithNonNaturalOrdering() {
let queue = PriorityQueue<Int>([1, 2, 3], isOrdered: >)
XCTAssertFalse(queue.isEmpty)
XCTAssertEqual(3, queue.count)
XCTAssertEqual(3, queue.front)
for (i, element) in queue.enumerated() {
XCTAssertEqual(3 - i, element)
}
}
func testClears() {
var queue: PriorityQueue = [1, 2, 3]
queue.clear()
XCTAssertTrue(queue.isEmpty)
XCTAssertEqual(0, queue.count)
XCTAssertEqual(nil, queue.front)
}
func testPushesElement() {
var queue = PriorityQueue<Int>()
queue.enqueue(1)
XCTAssertFalse(queue.isEmpty)
XCTAssertEqual(1, queue.count)
XCTAssertEqual(1, queue.front)
}
func testPushesElements() {
var queue = PriorityQueue<Int>()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
XCTAssertFalse(queue.isEmpty)
XCTAssertEqual(3, queue.count)
XCTAssertEqual(1, queue.front)
for (i, element) in queue.enumerated() {
XCTAssertEqual(i + 1, element)
}
}
func testPushesElementsWithNonNaturalOrdering() {
var queue = PriorityQueue<Int>(isOrdered: >)
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
XCTAssertFalse(queue.isEmpty)
XCTAssertEqual(3, queue.count)
XCTAssertEqual(3, queue.front)
for i in 0..<3 {
XCTAssertEqual(3 - i, queue.dequeue())
}
}
func testPopsElement() {
var queue: PriorityQueue = [1]
XCTAssertEqual(1, queue.dequeue())
XCTAssertTrue(queue.isEmpty)
XCTAssertEqual(0, queue.count)
XCTAssertEqual(nil, queue.front)
}
func testPopsElements() {
var queue: PriorityQueue = [1, 2, 3]
XCTAssertEqual(1, queue.dequeue())
XCTAssertEqual(2, queue.dequeue())
XCTAssertEqual(3, queue.dequeue())
XCTAssertTrue(queue.isEmpty)
XCTAssertEqual(0, queue.count)
XCTAssertEqual(nil, queue.front)
}
func testPopsElementsWithNonNaturalOrdering() {
var queue = PriorityQueue([1, 2, 3], isOrdered: >)
XCTAssertEqual(3, queue.dequeue())
XCTAssertEqual(2, queue.dequeue())
XCTAssertEqual(1, queue.dequeue())
XCTAssertTrue(queue.isEmpty)
XCTAssertEqual(0, queue.count)
XCTAssertEqual(nil, queue.front)
}
func testEquals() {
XCTAssertTrue(PriorityQueue<Int>() == [])
XCTAssertTrue([] == PriorityQueue<Int>([]))
XCTAssertTrue(PriorityQueue<Int>() == PriorityQueue<Int>([]))
let queue: PriorityQueue = [1, 2, 3]
var anotherQueue: PriorityQueue = [1, 2]
XCTAssertTrue(queue != anotherQueue)
anotherQueue.enqueue(3)
XCTAssertTrue(queue == anotherQueue)
}
func testPushingPerformance() {
measure {
var queue = PriorityQueue<Int>()
for i in 0..<100_000 {
queue.enqueue(i)
}
}
}
func testPushingPoppingPerformance() {
measure {
var queue = PriorityQueue<Int>()
for i in 0..<100_000 {
queue.enqueue(i)
XCTAssertEqual(i, queue.dequeue())
}
}
}
func testGetsDescriptions() {
var queue: PriorityQueue<Int> = []
XCTAssertEqual(queue.description, "[]")
XCTAssertEqual(queue.debugDescription, "PriorityQueue([])")
queue = [1, 2]
XCTAssertEqual(queue.description, "[1, 2]")
XCTAssertEqual(queue.debugDescription, "PriorityQueue([1, 2])")
}
}
| apache-2.0 |
austin226/maritime-flag-transliterator | Maritime Flag Transliterator/HeaderView.swift | 1 | 675 | //
// HeaderView.swift
// Maritime Flag Transliterator
//
// Created by Austin Almond on 1/11/16.
// Copyright © 2016 Austin Almond. All rights reserved.
//
import UIKit
class HeaderView: UICollectionReusableView {
@IBOutlet weak var headerLabel: UILabel!
@IBOutlet weak var flagTextField: UITextField!
@IBAction func clearButton(sender: AnyObject) {
flagTextField.text = ""
}
@IBAction func deleteButton(sender: AnyObject) {
if flagTextField.text?.characters.count == 0 {
return
} else {
flagTextField.text?.removeAtIndex(flagTextField.text!.endIndex.predecessor())
}
}
}
| gpl-3.0 |
raymondshadow/SwiftDemo | SwiftApp/Pods/RxSwift/RxSwift/Observables/Materialize.swift | 4 | 1539 | //
// Materialize.swift
// RxSwift
//
// Created by sergdort on 08/03/2017.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Convert any Observable into an Observable of its events.
- seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html)
- returns: An observable sequence that wraps events in an Event<E>. The returned Observable never errors, but it does complete after observing all of the events of the underlying Observable.
*/
public func materialize() -> Observable<Event<E>> {
return Materialize(source: self.asObservable())
}
}
fileprivate final class MaterializeSink<Element, O: ObserverType>: Sink<O>, ObserverType where O.E == Event<Element> {
func on(_ event: Event<Element>) {
self.forwardOn(.next(event))
if event.isStopEvent {
self.forwardOn(.completed)
self.dispose()
}
}
}
final private class Materialize<Element>: Producer<Event<Element>> {
private let _source: Observable<Element>
init(source: Observable<Element>) {
self._source = source
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E {
let sink = MaterializeSink(observer: observer, cancel: cancel)
let subscription = self._source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
| apache-2.0 |
nao1111/SlideViewControllerTest | SlideViewControllerTest/HomeViewController.swift | 1 | 478 | //
// HomeViewController.swift
// SlideViewControllerTest
//
// Created by nao on 2015/09/10.
// Copyright (c) 2015年 nao. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.yellowColor()
}
@IBAction func showMenu(sender: AnyObject) {
self.frostedViewController.presentMenuViewController()
}
}
| mit |
creatubbles/ctb-api-swift | CreatubblesAPIClient/Sources/Model/Notification.swift | 1 | 5376 | //
// Notification.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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
@objc
open class Notification: NSObject, Identifiable {
open let identifier: String
open let type: NotificationType
open let createdAt: Date
open let text: String
open let shortText: String
open let isNew: Bool
open let isUnread: Bool
open let creation: Creation?
open let user: User?
open let gallery: Gallery?
open let comment: Comment?
open let gallerySubmission: GallerySubmission?
open let userEntities: Array<NotificationTextEntity>?
open let creationEntities: Array<NotificationTextEntity>?
open let galleryEntities: Array<NotificationTextEntity>?
open let creationRelationship: Relationship?
open let userRelationship: Relationship?
open let galleryRelationship: Relationship?
open let commentRelationship: Relationship?
open let gallerySubmissionRelationship: Relationship?
open let userEntitiesRelationships: Array<Relationship>?
open let creationEntitiesRelationships: Array<Relationship>?
open let galleryEntitiesRelationships: Array<Relationship>?
open let bubbleRelationship: Relationship?
open let bubble: Bubble?
init(mapper: NotificationMapper, dataMapper: DataIncludeMapper? = nil) {
identifier = mapper.identifier!
text = mapper.text!
shortText = mapper.shortText!
isNew = mapper.isNew!
isUnread = mapper.isUnread!
createdAt = mapper.createdAt! as Date
type = mapper.parseType()
creationRelationship = MappingUtils.relationshipFromMapper(mapper.creationRelationship)
userRelationship = MappingUtils.relationshipFromMapper(mapper.userRelationship)
galleryRelationship = MappingUtils.relationshipFromMapper(mapper.galleryRelationship)
commentRelationship = MappingUtils.relationshipFromMapper(mapper.commentRelationship)
gallerySubmissionRelationship = MappingUtils.relationshipFromMapper(mapper.gallerySubmissionRelationship)
userEntitiesRelationships = mapper.userEntitiesRelationships?.flatMap({ MappingUtils.relationshipFromMapper($0) })
creationEntitiesRelationships = mapper.creationEntitiesRelationships?.flatMap({ MappingUtils.relationshipFromMapper($0) })
galleryEntitiesRelationships = mapper.galleryEntitiesRelationships?.flatMap({ MappingUtils.relationshipFromMapper($0) })
creation = MappingUtils.objectFromMapper(dataMapper, relationship: creationRelationship, type: Creation.self)
user = MappingUtils.objectFromMapper(dataMapper, relationship: userRelationship, type: User.self)
gallery = MappingUtils.objectFromMapper(dataMapper, relationship: galleryRelationship, type: Gallery.self)
comment = MappingUtils.objectFromMapper(dataMapper, relationship: commentRelationship, type: Comment.self)
gallerySubmission = MappingUtils.objectFromMapper(dataMapper, relationship: gallerySubmissionRelationship, type: GallerySubmission.self)
userEntities = userEntitiesRelationships?.flatMap({ MappingUtils.objectFromMapper(dataMapper, relationship: $0, type: NotificationTextEntity.self) }).filter({ $0.type != .unknown })
creationEntities = creationEntitiesRelationships?.flatMap({ MappingUtils.objectFromMapper(dataMapper, relationship: $0, type: NotificationTextEntity.self) }).filter({ $0.type != .unknown })
galleryEntities = galleryEntitiesRelationships?.flatMap({ MappingUtils.objectFromMapper(dataMapper, relationship: $0, type: NotificationTextEntity.self) }).filter({ $0.type != .unknown })
//Not sure if we still need this?
bubbleRelationship = MappingUtils.relationshipFromMapper(mapper.bubbleRelationship)
bubble = MappingUtils.objectFromMapper(dataMapper, relationship: bubbleRelationship, type: Bubble.self)
}
var isValid: Bool {
//Valid creation should have at least one of [creation, user, gallery, creationEntities, userEntities, galleryEntities] set and not-empty
return creation != nil || user != nil || gallery != nil ||
creationEntities?.isEmpty == false ||
galleryEntities?.isEmpty == false ||
userEntities?.isEmpty == false
}
}
| mit |
FranklinChen/type-directed-tdd-rust | presentation/Main4.swift | 1 | 93 | func runToSeq(i: Int, j: Int) -> [String] {
return Array(i...j).map(Defaults.fizzBuzzer)
}
| mit |
DarthRumata/EventsTree | Sources/EventMetadata.swift | 1 | 307 | //
// EventMetadata.swift
// EventNode
//
// Created by Rumata on 6/16/17.
// Copyright © 2017 DarthRumata. All rights reserved.
//
import Foundation
final class EventMetadata {
var isHandled: Bool = false
// TODO: add some properties to make possible other kind of event delivery and debug
}
| mit |
jeffh/Nimble | Tests/NimbleTests/Matchers/BeAnInstanceOfTest.swift | 14 | 3306 | import Foundation
import XCTest
import Nimble
fileprivate protocol TestProtocol {}
fileprivate class TestClassConformingToProtocol: TestProtocol {}
fileprivate struct TestStructConformingToProtocol: TestProtocol {}
final class BeAnInstanceOfTest: XCTestCase, XCTestCaseProvider {
static var allTests: [(String, (BeAnInstanceOfTest) -> () throws -> Void)] {
return [
("testPositiveMatch", testPositiveMatch),
("testPositiveMatchSwiftTypes", testPositiveMatchSwiftTypes),
("testFailureMessages", testFailureMessages),
("testFailureMessagesSwiftTypes", testFailureMessagesSwiftTypes),
]
}
func testPositiveMatch() {
expect(NSNull()).to(beAnInstanceOf(NSNull.self))
expect(NSNumber(value:1)).toNot(beAnInstanceOf(NSDate.self))
}
enum TestEnum {
case one, two
}
func testPositiveMatchSwiftTypes() {
expect(1).to(beAnInstanceOf(Int.self))
expect("test").to(beAnInstanceOf(String.self))
expect(TestEnum.one).to(beAnInstanceOf(TestEnum.self))
let testProtocolClass = TestClassConformingToProtocol()
expect(testProtocolClass).to(beAnInstanceOf(TestClassConformingToProtocol.self))
expect(testProtocolClass).toNot(beAnInstanceOf(TestProtocol.self))
expect(testProtocolClass).toNot(beAnInstanceOf(TestStructConformingToProtocol.self))
let testProtocolStruct = TestStructConformingToProtocol()
expect(testProtocolStruct).to(beAnInstanceOf(TestStructConformingToProtocol.self))
expect(testProtocolStruct).toNot(beAnInstanceOf(TestProtocol.self))
expect(testProtocolStruct).toNot(beAnInstanceOf(TestClassConformingToProtocol.self))
}
func testFailureMessages() {
failsWithErrorMessageForNil("expected to not be an instance of NSNull, got <nil>") {
expect(nil as NSNull?).toNot(beAnInstanceOf(NSNull.self))
}
failsWithErrorMessageForNil("expected to be an instance of NSString, got <nil>") {
expect(nil as NSString?).to(beAnInstanceOf(NSString.self))
}
#if _runtime(_ObjC)
let numberTypeName = "__NSCFNumber"
#else
let numberTypeName = "NSNumber"
#endif
failsWithErrorMessage("expected to be an instance of NSString, got <\(numberTypeName) instance>") {
expect(NSNumber(value:1)).to(beAnInstanceOf(NSString.self))
}
failsWithErrorMessage("expected to not be an instance of NSNumber, got <\(numberTypeName) instance>") {
expect(NSNumber(value:1)).toNot(beAnInstanceOf(NSNumber.self))
}
}
func testFailureMessagesSwiftTypes() {
failsWithErrorMessage("expected to not be an instance of Int, got <Int instance>") {
expect(1).toNot(beAnInstanceOf(Int.self))
}
let testClass = TestClassConformingToProtocol()
failsWithErrorMessage("expected to be an instance of \(String(describing: TestProtocol.self)), got <\(String(describing: TestClassConformingToProtocol.self)) instance>") {
expect(testClass).to(beAnInstanceOf(TestProtocol.self))
}
failsWithErrorMessage("expected to be an instance of String, got <Int instance>") {
expect(1).to(beAnInstanceOf(String.self))
}
}
}
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/27793-swift-typechecker-checkdeclattributes.swift | 1 | 502 | // 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
{
if{
struct A{
class A{class B<T where h:e{class n{
let a{
class B{
let a=f
}
}
var f:A
let b={
{
}
<f
| apache-2.0 |
cnoon/swift-compiler-crashes | crashes-duplicates/24165-swift-metatypetype-get.swift | 9 | 211 | // 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 c
{{{
class T{class A{class
case c,{
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/02770-swift-sourcemanager-getmessage.swift | 11 | 223 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
init<A.b { func c,
if true {
func b<d {
class
case c,
| mit |
lotz84/TwitterMediaTimeline | twitter-media-timeline/TwitterMediaTimeline.swift | 1 | 4222 |
import UIKit
import Social
import Accounts
typealias TMTRequest = (maxId: String?, account: ACAccount)
typealias TMTResultHandler = (idArray: [String]) -> ()
protocol TwitterMediaTimelineDataSource : class {
func getNextStatusIds(request: TMTRequest, callback: TMTResultHandler) -> ()
}
class TwitterMediaTimeline : UIViewController {
weak var dataSource: TwitterMediaTimelineDataSource?
var account : ACAccount?
var nextMaxId : String?
var statusIdArray : [String] = []
var statusMap : [String:TweetStatus] = [:]
var collectionView : UICollectionView?
let ReuseIdentifier = "cell"
override func viewDidLoad() {
super.viewDidLoad()
let layout = UICollectionViewFlowLayout()
layout.itemSize = self.view.bounds.size
layout.minimumLineSpacing = 0.0;
layout.minimumInteritemSpacing = 0.0;
layout.sectionInset = UIEdgeInsetsZero;
layout.scrollDirection = .Horizontal
collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView!.dataSource = self
collectionView!.pagingEnabled = true
collectionView!.registerClass(TweetStatusCell.classForCoder(), forCellWithReuseIdentifier:ReuseIdentifier)
view.addSubview(collectionView!)
self.dataSource?.getNextStatusIds((maxId: nextMaxId, account: account!), callback: self.resultHandler)
}
func resultHandler(idList: [String]) {
if idList.isEmpty {
nextMaxId = nil
} else {
nextMaxId = String(minElement(idList.map({(x:String) in x.toInt()!})) - 1)
}
statusIdArray += idList
dispatch_async(dispatch_get_main_queue()) {
self.collectionView?.reloadData()
}
}
}
extension TwitterMediaTimeline : UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return statusIdArray.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if indexPath.row + 1 == statusIdArray.count {
if let maxId = nextMaxId {
self.dataSource?.getNextStatusIds((maxId: maxId, account: account!), callback: self.resultHandler)
}
}
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! TweetStatusCell
self.loadStatus(statusIdArray[indexPath.row]) { status in
cell.setStatus(status)
}
return cell;
}
}
//MARK: Network
extension TwitterMediaTimeline {
func defaultRequestHandler(handler: JSON -> Void) -> SLRequestHandler {
return { body, response, error in
if (body == nil) {
println("HTTPRequest Error: \(error.localizedDescription)")
return
}
if (response.statusCode < 200 && 300 <= response.statusCode) {
println("The response status code is \(response.statusCode)")
return
}
handler(JSON(data: body!))
}
}
func loadStatus(statusId : String, completion : TweetStatus -> Void) {
if let json = statusMap[statusId] {
completion(json)
} else {
let url = "https://api.twitter.com/1.1/statuses/show/\(statusId).json"
let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .GET, URL: NSURL(string: url), parameters: nil)
request.account = self.account
request.performRequestWithHandler { body, response, error in
let json = JSON(data: body!)
if let status = TweetStatus.fromJSON(json) {
self.statusMap[statusId] = status
dispatch_async(dispatch_get_main_queue()) {
completion(status)
}
} else {
println("TweetStatus JSON parse fail")
}
}
}
}
} | mit |
digoreis/swift-proposal-analyzer | swift-proposal-analyzer.playground/Pages/SE-0064.xcplaygroundpage/Contents.swift | 1 | 2817 | /*:
# Referencing the Objective-C selector of property getters and setters
* Proposal: [SE-0064](0064-property-selectors.md)
* Author: [David Hart](https://github.com/hartbit)
* Review Manager: [Doug Gregor](https://github.com/DougGregor)
* Status: **Implemented (Swift 3)**
* Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2016-April/000102.html)
* Bug: [SR-1239](https://bugs.swift.org/browse/SR-1239)
## Introduction
Proposal [SE-0022](0022-objc-selectors.md) was accepted and implemented to provide a `#selector` expression to reference Objective-C method selectors. Unfortunately, it does not allow referencing the getter and setter methods of properties. This proposal seeks to provide a design to reference those methods for the Swift 3.0 timeframe.
* [Original swift-evolution thread](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160215/010791.html)
* [Follow-up swift-evolution thread](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160222/010960.html)
## Motivation
The `#selector` expression is very useful but does not yet cover all cases. Accessing property getter and setters requires to drop down to the string syntax and forgo type-safety. This proposal supports this special case without introducing new syntax, but by introducing new overloads to the `#selector` compiler expression.
## Proposed solution
Introduce two new overrides to the `#selector` expression that allows building a selector which points to the getter or the setter of a property.
```swift
class Person: NSObject {
dynamic var firstName: String
dynamic let lastName: String
dynamic var fullName: String {
return "\(firstName) \(lastName)"
}
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
}
let firstNameGetter = #selector(getter: Person.firstName)
let firstNameSetter = #selector(setter: Person.firstName)
```
Both overrides expect a property and the setter requires a variable property. For example, the following line of code would produce an error because the lastName property is defined with let.
```
let lastNameSetter = #selector(setter: Person.lastName)
// Argument of #selector(setter:) must refer to a variable property
```
## Impact on existing code
The introduction of the new `#selector` overrides has no impact on existing code and could improve the string-literal-as-selector to `#selector` migrator.
## Alternatives considered
A long term alternive could arrise from the design of lenses in Swift. But as this is purely hypothetical and out of scope for Swift 3, this proposal fixes the need for referencing property selectors in a type-safe way straight-away.
----------
[Previous](@previous) | [Next](@next)
*/
| mit |
abelsanchezali/ViewBuilder | ViewBuilderDemo/ViewBuilderDemo/Integration/Models/Layout+Definitions.swift | 1 | 2622 | //
// Layout+Definitions.swift
// ViewBuilderDemo
//
// Created by Abel Sanchez on 7/2/16.
// Copyright © 2016 Abel Sanchez. All rights reserved.
//
import ViewBuilder
import UIKit
public struct LayoutAnchor : OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let none = LayoutAnchor([])
public static let top = LayoutAnchor(rawValue: 1 << 0)
public static let left = LayoutAnchor(rawValue: 1 << 1)
public static let bottom = LayoutAnchor(rawValue: 1 << 2)
public static let right = LayoutAnchor(rawValue: 1 << 3)
public static let fill = LayoutAnchor([.top, .left, .bottom, .right])
public static let centerX = LayoutAnchor(rawValue: 1 << 4)
public static let centerY = LayoutAnchor(rawValue: 1 << 5)
public static let center = LayoutAnchor([.centerX, .centerY])
}
extension LayoutAnchor: NSValueConvertible {
public func convertToNSValue() -> NSValue? {
return NSNumber(value: self.rawValue as Int)
}
}
public class Anchor: Object, TextDeserializer {
private static let AnchorByText: [String: LayoutAnchor] = ["Fill": LayoutAnchor.fill,
"None": LayoutAnchor.none,
"Left": LayoutAnchor.left,
"Top": LayoutAnchor.top,
"Right": LayoutAnchor.right,
"Bottom": LayoutAnchor.bottom,
"CenterX": LayoutAnchor.centerX,
"CenterY": LayoutAnchor.centerY,
"Center": LayoutAnchor.center]
public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? {
guard let text = text else {
return nil
}
guard let words = service.parseValidWordsArray(from: text) else {
return nil
}
var value = LayoutAnchor.none
for word in words {
guard let anchor = Anchor.AnchorByText[word] else {
Log.shared.write("Warning: Ingnoring \"\(word)\" when processing LayoutAnchor deserialization.")
continue
}
value.insert(anchor)
}
return value
}
}
| mit |
APUtils/APExtensions | APExtensions/Classes/Core/_Extensions/_Foundation/Float+Utils.swift | 1 | 1610 | //
// Float+Utils.swift
// APExtensions
//
// Created by Anton Plebanovich on 3/20/21.
// Copyright © 2021 Anton Plebanovich. All rights reserved.
//
import Foundation
public extension Float {
/// Return `self` as `Double`.
var asDouble: Double {
Double(self)
}
/// Returns `self` as `Int`
var asInt: Int? { Int(exactly: rounded()) }
}
// ******************************* MARK: - As String
public extension Float {
/// Returns string representation rounded to tenth
var asCeilString: String {
NumberFormatter.ceil.string(from: self as NSNumber) ?? ""
}
/// Returns string representation rounded to tenth
var asTenthString: String {
NumberFormatter.tenth.string(from: self as NSNumber) ?? ""
}
/// Returns string representation rounded to hundredth
var asHundredthString: String {
NumberFormatter.hundredth.string(from: self as NSNumber) ?? ""
}
/// Returns string representation rounded to thousands
var asThousandsString: String {
NumberFormatter.thousands.string(from: self as NSNumber) ?? ""
}
/// Returns `self` as `String`
var asString: String {
String(self)
}
}
// ******************************* MARK: - Other
public extension Float {
/// Returns `true` if `self` is ceil. Returns `false` otherwise.
var isCeil: Bool {
floor(self) == self
}
func roundTo(precision: Int) -> Float {
let divisor = pow(10.0, Float(precision))
return (self * divisor).rounded() / divisor
}
}
| mit |
SwiftGen/templates | Pods/Stencil/Sources/Filters.swift | 6 | 826 | func capitalise(_ value: Any?) -> Any? {
return stringify(value).capitalized
}
func uppercase(_ value: Any?) -> Any? {
return stringify(value).uppercased()
}
func lowercase(_ value: Any?) -> Any? {
return stringify(value).lowercased()
}
func defaultFilter(value: Any?, arguments: [Any?]) -> Any? {
if let value = value {
return value
}
for argument in arguments {
if let argument = argument {
return argument
}
}
return nil
}
func joinFilter(value: Any?, arguments: [Any?]) throws -> Any? {
guard arguments.count < 2 else {
throw TemplateSyntaxError("'join' filter takes a single argument")
}
let separator = stringify(arguments.first ?? "")
if let value = value as? [Any] {
return value
.map(stringify)
.joined(separator: separator)
}
return value
}
| mit |
ConradoMateu/Swift-Basics | Basic/Enumerations&Structures.playground/Contents.swift | 1 | 2180 | //: Playground - noun: a place where people can play
import UIKit
// Enumerations define a common type for a group of related values. Enumerations can have methods associated with them.
// Use enum to create an enumeration.
enum Rank: Int {
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace:
return "ace"
case .Jack:
return "jack"
case .Queen:
return "queen"
case .King:
return "king"
default:
return String(self.rawValue)
}
}
}
let ace = Rank.Ace
//Use the rawValue property to access the raw value of an enumeration member.
let aceRawValue = ace.rawValue
// Use the `init?(rawValue:)` initializer to make an instance of an enumeration from a raw value.
if let convertedRank = Rank(rawValue: 3) {
let threeDescription = convertedRank.simpleDescription()
}
// In cases where there isn’t a meaningful raw value, you don’t have to provide one.
enum Suit {
case Spades, Hearts, Diamonds, Clubs
func simpleDescription() -> String {
switch self {
case .Spades:
return "spades"
case .Hearts:
return "hearts"
case .Diamonds:
return "diamonds"
case .Clubs:
return "clubs"
}
}
}
let hearts = Suit.Hearts
let heartsDescription = hearts.simpleDescription()
// One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code, but classes are passed by reference. Structures are great for defining lightweight data types that don’t need to have capabilities like inheritance and type casting.
// Use struct to create a structure.
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
}
let threeOfSpades = Card(rank: .Three, suit: .Spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
| apache-2.0 |
karivalkama/Agricola-Scripture-Editor | TranslationEditor/ConnectionUIView.swift | 1 | 14825 | //
// ConnectionUIView.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 17.5.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import Foundation
import AVFoundation
import QRCodeReader
import MessageUI
fileprivate enum ConnectionState
{
case disconnected, joined, hosting
var actionText: String
{
var text = ""
switch self
{
case .disconnected: text = "Disconnect"
case .joined: text = "Join"
case .hosting: text = "Host"
}
return NSLocalizedString(text, comment: "A label for an action that changes an online state")
}
var processingText: String
{
var text = ""
switch self
{
case .disconnected: text = "Disconnecting"
case .joined: text = "Joining"
case .hosting: text = "Hosting"
}
return NSLocalizedString(text, comment: "A label for a processing online state")
}
var ongoingText: String
{
var text = ""
switch self
{
case .disconnected: text = "Disconnected"
case .joined: text = "Joined"
case .hosting: text = "Hosting"
}
return NSLocalizedString(text, comment: "A label for an ongoing online state")
}
}
@IBDesignable class ConnectionUIView: CustomXibView, QRCodeReaderViewControllerDelegate, UITableViewDataSource, UITableViewDelegate, MFMailComposeViewControllerDelegate, ConnectionListener
{
// OUTLETS --------------
//@IBOutlet weak var hostingSwitch: UISwitch!
@IBOutlet weak var qrView: UIView!
@IBOutlet weak var qrImageView: UIImageView!
//@IBOutlet weak var joinSwitch: UISwitch!
@IBOutlet weak var onlineStatusView: OnlineStatusView!
@IBOutlet weak var hostInfoView: UIView!
@IBOutlet weak var hostImageView: UIImageView!
@IBOutlet weak var hostNameLabel: UILabel!
@IBOutlet weak var hostProjectLabel: UILabel!
@IBOutlet weak var sendEmailButton: BasicButton!
@IBOutlet weak var bookSelectionView: UIView!
@IBOutlet weak var bookSelectionTableView: UITableView!
@IBOutlet weak var connectionSegmentedControl: UISegmentedControl!
@IBOutlet weak var sharingView: UIView!
// ATTRIBUTES ----------
weak var viewController: UIViewController?
// private let canSendMail = MFMailComposeViewController.canSendMail()
private var targetTranslations = [Book]()
private var joining = false
// The reader used for capturing QR codes, initialized only when used
private lazy var readerVC: QRCodeReaderViewController =
{
let builder = QRCodeReaderViewControllerBuilder
{
$0.reader = QRCodeReader(metadataObjectTypes: [AVMetadataObject.ObjectType.qr], captureDevicePosition: .back)
}
return QRCodeReaderViewController(builder: builder)
}()
private var canHost = false
private var canJoin = false
// COMPUTED PROPERTIES ----
private var availableConnectionStates: [(ConnectionState, Int)]
{
var states = [(ConnectionState.disconnected, 0)]
var nextIndex = 1
if canJoin
{
states.add((ConnectionState.joined, nextIndex))
nextIndex += 1
}
if canHost
{
states.add((ConnectionState.hosting, nextIndex))
nextIndex += 1
}
return states
}
// INIT --------------------
override init(frame: CGRect)
{
super.init(frame: frame)
setupXib(nibName: "Connect2")
}
required init?(coder: NSCoder)
{
super.init(coder: coder)
setupXib(nibName: "Connect2")
}
override func awakeFromNib()
{
bookSelectionView.isHidden = true
bookSelectionTableView.register(UINib(nibName: "LabelCell", bundle: nil), forCellReuseIdentifier: LabelCell.identifier)
bookSelectionTableView.dataSource = self
bookSelectionTableView.delegate = self
var projectFound = false
do
{
if let projectId = Session.instance.projectId, let project = try Project.get(projectId)
{
targetTranslations = try project.targetTranslationQuery().resultObjects()
targetTranslations.sort(by: { $0.code < $1.code })
projectFound = true
}
}
catch
{
print("ERROR: Failed to read target translation data. \(error)")
}
canHost = projectFound || P2PHostSession.instance != nil
canJoin = QRCodeReader.isAvailable()
if !canHost
{
connectionSegmentedControl.removeSegment(at: 2, animated: false)
}
if !canJoin
{
connectionSegmentedControl.removeSegment(at: 1, animated: false)
}
updateStatus()
sharingView.isHidden = targetTranslations.isEmpty
}
// ACTIONS --------------
@IBAction func connectionModeChanged(_ sender: Any)
{
let newState = stateForIndex(connectionSegmentedControl.selectedSegmentIndex)
// Join
if newState == .joined
{
guard let viewController = viewController else
{
print("ERROR: No view controller to host the QR scanner")
return
}
if QRCodeReader.isAvailable()
{
joining = true
// Presents a join P2P VC
readerVC.delegate = self
readerVC.modalPresentationStyle = .formSheet
viewController.present(readerVC, animated: true, completion: nil)
}
else
{
connectionSegmentedControl.selectedSegmentIndex = 0
// TODO: Show some kind of error label
}
}
else
{
P2PClientSession.stop()
}
// Hosting
if newState == .hosting
{
if P2PHostSession.instance == nil
{
do
{
_ = try P2PHostSession.start(projectId: Session.instance.projectId, hostAvatarId: Session.instance.avatarId)
}
catch
{
print("ERROR: Failed to start a P2P hosting session")
}
}
}
else
{
P2PHostSession.stop()
}
// TODO: Animate
updateStatus()
}
/*
@IBAction func hostingSwitchChanged(_ sender: Any)
{
// TODO: Animate
if hostingSwitch.isOn
{
if P2PHostSession.instance == nil
{
do
{
_ = try P2PHostSession.start(projectId: Session.instance.projectId, hostAvatarId: Session.instance.avatarId)
}
catch
{
print("ERROR: Failed to start a P2P hosting session")
}
}
}
else
{
P2PHostSession.stop()
}
updateStatus()
}
@IBAction func joinSwitchChanged(_ sender: Any)
{
if joinSwitch.isOn
{
guard let viewController = viewController else
{
print("ERROR: No view controller to host the QR scanner")
return
}
// Presents a join P2P VC
readerVC.delegate = self
readerVC.modalPresentationStyle = .formSheet
viewController.present(readerVC, animated: true, completion: nil)
}
else
{
P2PClientSession.stop()
updateStatus()
}
}
*/
@IBAction func sendEmailButtonPressed(_ sender: Any)
{
// TODO: Animate
// When send email button is pressed, book selection is displayed
bookSelectionView.isHidden = false
sendEmailButton.isEnabled = false
}
@IBAction func cancelSendButtonPressed(_ sender: Any)
{
// TODO: Animate
// Hides the book selection
sendEmailButton.isEnabled = true
bookSelectionView.isHidden = true
}
// IMPLEMENTED METHODS ------
func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult)
{
reader.stopScanning()
print("STATUS: Scanned QR code result: \(result.value) (of type \(result.metadataType))")
viewController.or(reader).dismiss(animated: true, completion: nil)
joining = false
if let info = P2PConnectionInformation.parse(from: result.value)
{
print("STATUS: Starting P2P client session")
print("STATUS: \(info)")
P2PClientSession.start(info)
}
else
{
print("ERROR: Failed to parse connection information from \(result.value)")
}
// TODO: Animate
updateStatus()
}
func reader(_ reader: QRCodeReaderViewController, didSwitchCamera newCaptureDevice: AVCaptureDeviceInput)
{
print("STATUS: Switched camera")
}
func readerDidCancel(_ reader: QRCodeReaderViewController)
{
reader.stopScanning()
print("STATUS: QR Capture session cancelled")
viewController.or(reader).dismiss(animated: true, completion: nil)
joining = false
// connectionSegmentedControl.selectedSegmentIndex = 0
// joinSwitch.isOn = false
updateStatus()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return targetTranslations.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: LabelCell.identifier, for: indexPath) as! LabelCell
cell.configure(text: targetTranslations[indexPath.row].code.description)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
guard let viewController = viewController else
{
print("ERROR: No view controller to host the share view.")
return
}
do
{
let book = targetTranslations[indexPath.row]
let paragraphs = try ParagraphView.instance.latestParagraphQuery(bookId: book.idString).resultObjects()
let usx = USXWriter().writeUSXDocument(book: book, paragraphs: paragraphs)
guard let data = usx.data(using: .utf8) else
{
print("ERROR: Failed to generate USX data")
return
}
sendEmailButton.isEnabled = true
bookSelectionView.isHidden = true
let dir = FileManager.default.urls(for: FileManager.SearchPathDirectory.cachesDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first!
let fileurl = dir.appendingPathComponent("\(book.code.code).usx")
try data.write(to: fileurl, options: Data.WritingOptions.atomic)
let shareVC = UIActivityViewController(activityItems: [fileurl], applicationActivities: nil)
shareVC.popoverPresentationController?.sourceView = sendEmailButton
/*
let mailVC = MFMailComposeViewController()
mailVC.mailComposeDelegate = self
mailVC.addAttachmentData(data, mimeType: "application/xml", fileName: "\(book.code.code).usx")
mailVC.setSubject("\(book.code.name) - \(book.identifier) \(NSLocalizedString("USX Export", comment: "Part of the default export email subject"))")
*/
viewController.present(shareVC, animated: true, completion: nil)
// viewController.present(mailVC, animated: true, completion: nil)
}
catch
{
print("ERROR: Failed to read, parse and send translation data. \(error)")
}
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?)
{
controller.dismiss(animated: true, completion: nil)
}
func onConnectionStatusChange(newStatus status: ConnectionStatus)
{
onlineStatusView.status = status
// When in idle mode and client session is active, updates host info
if (status == .done || status == .upToDate) && P2PClientSession.isConnected
{
updateHostInfoViewStatus()
}
}
func onConnectionProgressUpdate(transferred: Int, of total: Int, progress: Double)
{
onlineStatusView.updateProgress(completed: transferred, of: total, progress: progress)
}
// OTHER METHODS -----
private func stateForIndex(_ index: Int) -> ConnectionState
{
if index <= 0
{
return .disconnected
}
else if index == 2
{
return .hosting
}
else
{
if canJoin
{
return .joined
}
else
{
return .hosting
}
}
}
private func selectConnectionState(_ selectedState: ConnectionState, isProcessing: Bool = false)
{
// Updates labels and selection
for (state, index) in availableConnectionStates
{
if state == selectedState
{
connectionSegmentedControl.setTitle(isProcessing ? state.processingText : state.ongoingText, forSegmentAt: index)
connectionSegmentedControl.selectedSegmentIndex = index
}
else
{
connectionSegmentedControl.setTitle(state.actionText, forSegmentAt: index)
}
}
}
private func updateStatus()
{
if let hostSession = P2PHostSession.instance
{
selectConnectionState(.hosting)
// QR view and the QR tag are displayed when there's an active host session
if qrView.isHidden, let qrImage = hostSession.connectionInformation?.qrCode?.image
{
qrImageView.image = qrImage
qrView.isHidden = false
}
}
else
{
qrImageView.image = nil
qrView.isHidden = true
if P2PClientSession.isConnected
{
selectConnectionState(.joined)
onlineStatusView.isHidden = false
}
else
{
onlineStatusView.isHidden = true
if joining
{
selectConnectionState(.joined, isProcessing: true)
}
else
{
selectConnectionState(.disconnected)
}
}
}
updateHostInfoViewStatus()
}
/*
private func updateHostViewStatus()
{
if let hostSession = P2PHostSession.instance
{
// QR view and the QR tag are displayed when there's an active host session
if qrView.isHidden, let qrImage = hostSession.connectionInformation?.qrCode?.image
{
qrImageView.image = qrImage
qrView.isHidden = false
hostingSwitch.isOn = true
hostingSwitch.isEnabled = true
}
}
else
{
qrImageView.image = nil
qrView.isHidden = true
hostingSwitch.isOn = false
// Hosting is disabled while there is an active client session
hostingSwitch.isEnabled = !P2PClientSession.isConnected
}
}
private func updateJoinViewStatus()
{
if P2PClientSession.isConnected
{
joinSwitch.isOn = true
joinSwitch.isEnabled = true
onlineStatusView.isHidden = false
}
else
{
joinSwitch.isOn = false
onlineStatusView.isHidden = true
// Join switch is disabled while there's a host session in place.
// Camera is required too
// TODO: Add camera check
joinSwitch.isEnabled = P2PHostSession.instance == nil
}
}*/
private func updateHostInfoViewStatus()
{
var infoFound = false
if P2PClientSession.isConnected, let clientSession = P2PClientSession.instance
{
// If correct info is already displayed, doesn't bother reading data again
if hostInfoView.isHidden
{
do
{
if let projectId = clientSession.projectId, let hostAvatarId = clientSession.hostAvatarId, let project = try Project.get(projectId), let hostAvatar = try Avatar.get(hostAvatarId), let hostInfo = try hostAvatar.info()
{
infoFound = true
hostImageView.image = hostInfo.image ?? #imageLiteral(resourceName: "userIcon")
hostNameLabel.text = "\(NSLocalizedString("Joined", comment: "Part of host info desciption. Followed by host user name.")) \(hostAvatar.name)"
hostProjectLabel.text = "\(NSLocalizedString("on project:", comment: "Part of host info description. Followed by project name")) \(project.name)"
// Makes sure the current user also has access to the project
/*
if let accountId = Session.instance.accountId
{
if !project.contributorIds.contains(accountId)
{
project.contributorIds.append(accountId)
try project.push()
}
}
*/
}
}
catch
{
print("ERROR: Failed to read host data from the database. \(error)")
}
}
else
{
infoFound = true
}
}
hostInfoView.isHidden = !infoFound
}
}
| mit |
Roosting/Index | src/Index.swift | 1 | 1875 | import Foundation
import MessagePack
class Index {
private let formatter: NSDateFormatter = NSDateFormatter()
init() {
formatter.dateFormat = "yyyy-MM-dd'T'HH-mm-ss'Z'"
}
func packPackages(packages: [Package]) {
let path = getOutputName()
if !fileManager.createFileAtPath(path, contents: nil, attributes: nil) {
printAndExit("Failed to create index file '\(path)'")
}
let file = NSFileHandle(forWritingAtPath: getOutputName())!
let header = "Roost Index Version 1\n"
file.writeData(header.dataUsingEncoding(NSUTF8StringEncoding)!)
var dictionary = [MessagePackValue : MessagePackValue]()
for package in packages {
let key = MessagePackValue.String(package.name)
let value = packedPackage(package)
dictionary[key] = value
}
let packed = MessagePack.pack(.Map(dictionary))
file.writeData(packed)
}
private func packedPackage(package: Package) -> MessagePackValue {
return MessagePackValue.Map([
.String("name") : .String(package.name),
.String("version") : .String(package.version.description),
.String("versions") : packPackageVersions(package.versions),
])
}
/**
Convert Array of Version structs into a MessagePackValue.Array of
MessagePackValue.Map instances.
*/
private func packPackageVersions(versions: [Version]) -> MessagePackValue {
let versionsValues = versions.map { (v) in
return MessagePackValue.Map([
.String("version") : .String(v.version.description),
.String("description") : .String(v.description),
])
}
return MessagePackValue.Array(versionsValues)
}
/**
Timestamped name of the file to which to write the packed index.
*/
private func getOutputName() -> String {
let date = formatter.stringFromDate(NSDate())
return "Index-\(date).bin"
}
}
| mit |
niunaruto/DeDaoAppSwift | testSwift/Pods/RxCocoa/RxCocoa/iOS/UIWebView+Rx.swift | 16 | 1418 | //
// UIWebView+Rx.swift
// RxCocoa
//
// Created by Andrew Breckenridge on 8/30/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
#if os(iOS)
import UIKit
import RxSwift
extension Reactive where Base: UIWebView {
/// Reactive wrapper for `delegate`.
/// For more information take a look at `DelegateProxyType` protocol documentation.
public var delegate: DelegateProxy<UIWebView, UIWebViewDelegate> {
return RxWebViewDelegateProxy.proxy(for: base)
}
/// Reactive wrapper for `delegate` message.
public var didStartLoad: Observable<Void> {
return delegate
.methodInvoked(#selector(UIWebViewDelegate.webViewDidStartLoad(_:)))
.map { _ in }
}
/// Reactive wrapper for `delegate` message.
public var didFinishLoad: Observable<Void> {
return delegate
.methodInvoked(#selector(UIWebViewDelegate.webViewDidFinishLoad(_:)))
.map { _ in }
}
/// Reactive wrapper for `delegate` message.
public var didFailLoad: Observable<Error> {
return delegate
.methodInvoked(#selector(UIWebViewDelegate.webView(_:didFailLoadWithError:)))
.map { a in
return try castOrThrow(Error.self, a[1])
}
}
}
#endif
| mit |
stephentyrone/swift | test/DebugInfo/modulecache.swift | 3 | 976 | // RUN: %empty-directory(%t)
// Clang-import a module.
import ClangModule
// Note: This test is highly dependent on the clang module cache
// format, but it is testing specifics of the module cache.
// 1. Test that swift-ide-test creates a thin module without debug info.
// RUN: %empty-directory(%t)
// RUN: %swift-ide-test_plain -print-usrs -target %target-triple -module-cache-path %t -I %S/Inputs -source-filename %s
// RUN: dd bs=1 count=4 < %t/*/ClangModule-*.pcm 2>/dev/null | grep -q CPCH
// 2. Test that swift is creating clang modules with debug info.
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -c -g -o %t.o -module-cache-path %t -I %S/Inputs
// RUN: llvm-readobj -h %t/*/ClangModule-*.pcm | %FileCheck %s
// CHECK: Format: {{(Mach-O|ELF|COFF)}}
// 3. Test that swift-ide-check will not share swiftc's module cache.
// RUN: %swift-ide-test_plain -print-usrs -target %target-triple -module-cache-path %t -I %S/Inputs -source-filename %s
| apache-2.0 |
hooman/swift | validation-test/stdlib/FixedPointConversion/FixedPointConversion_Debug32_ToInt16.swift | 4 | 17751 | //===----------------------------------------------------------------------===//
//
// Automatically Generated From ./Inputs/FixedPointConversion.swift.gyb
// Do Not Edit Directly!
//
//===----------------------------------------------------------------------===//
//
// REQUIRES: executable_test
// REQUIRES: PTRSIZE=32
// RUN: %target-run-simple-swift(-Onone)
// END.
//
//===----------------------------------------------------------------------===//
import StdlibUnittest
let FixedPointConversion_Debug32_ToInt16 = TestSuite(
"FixedPointConversion_Debug32_ToInt16"
)
//===----------------------------------------------------------------------===//
// MARK: UInt8: (+0)...(+255)
//===----------------------------------------------------------------------===//
FixedPointConversion_Debug32_ToInt16
.test("FromUInt8_NeverTraps")
.forEach(in: [
(getInt16(+0), getUInt8(+0)),
(getInt16(+255), getUInt8(+255)),
]) {
expectEqual($0.0, Int16($0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromUInt8_NeverFails")
.forEach(in: [
(getInt16(+0), getUInt8(+0)),
(getInt16(+255), getUInt8(+255)),
]) {
expectEqual($0.0, Int16(exactly: $0.1))
}
//===----------------------------------------------------------------------===//
// MARK: Int8: (-128)...(+127)
//===----------------------------------------------------------------------===//
FixedPointConversion_Debug32_ToInt16
.test("FromInt8_NeverTraps")
.forEach(in: [
(getInt16(-128), getInt8(-128)),
(getInt16(+0), getInt8(+0)),
(getInt16(+127), getInt8(+127)),
]) {
expectEqual($0.0, Int16($0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromInt8_NeverFails")
.forEach(in: [
(getInt16(-128), getInt8(-128)),
(getInt16(+0), getInt8(+0)),
(getInt16(+127), getInt8(+127)),
]) {
expectEqual($0.0, Int16(exactly: $0.1))
}
//===----------------------------------------------------------------------===//
// MARK: UInt16: (+0)...(+65535)
//===----------------------------------------------------------------------===//
FixedPointConversion_Debug32_ToInt16
.test("FromUInt16_NeverTraps")
.forEach(in: [
(getInt16(+0), getUInt16(+0)),
(getInt16(+32767), getUInt16(+32767)),
]) {
expectEqual($0.0, Int16($0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromUInt16_NeverFails")
.forEach(in: [
(getInt16(+0), getUInt16(+0)),
(getInt16(+32767), getUInt16(+32767)),
]) {
expectEqual($0.0, Int16(exactly: $0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromUInt16_AlwaysTraps")
.forEach(in: [
getUInt16(+32768),
getUInt16(+65535),
]) {
expectCrashLater()
_blackHole(Int16($0))
}
FixedPointConversion_Debug32_ToInt16
.test("FromUInt16_AlwaysFails")
.forEach(in: [
getUInt16(+32768),
getUInt16(+65535),
]) {
expectNil(Int16(exactly: $0))
}
//===----------------------------------------------------------------------===//
// MARK: Int16: (-32768)...(+32767)
//===----------------------------------------------------------------------===//
FixedPointConversion_Debug32_ToInt16
.test("FromInt16_NeverTraps")
.forEach(in: [
(getInt16(-32768), getInt16(-32768)),
(getInt16(+0), getInt16(+0)),
(getInt16(+32767), getInt16(+32767)),
]) {
expectEqual($0.0, Int16($0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromInt16_NeverFails")
.forEach(in: [
(getInt16(-32768), getInt16(-32768)),
(getInt16(+0), getInt16(+0)),
(getInt16(+32767), getInt16(+32767)),
]) {
expectEqual($0.0, Int16(exactly: $0.1))
}
//===----------------------------------------------------------------------===//
// MARK: UInt32: (+0)...(+4294967295)
//===----------------------------------------------------------------------===//
FixedPointConversion_Debug32_ToInt16
.test("FromUInt32_NeverTraps")
.forEach(in: [
(getInt16(+0), getUInt32(+0)),
(getInt16(+32767), getUInt32(+32767)),
]) {
expectEqual($0.0, Int16($0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromUInt32_NeverFails")
.forEach(in: [
(getInt16(+0), getUInt32(+0)),
(getInt16(+32767), getUInt32(+32767)),
]) {
expectEqual($0.0, Int16(exactly: $0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromUInt32_AlwaysTraps")
.forEach(in: [
getUInt32(+32768),
getUInt32(+4294967295),
]) {
expectCrashLater()
_blackHole(Int16($0))
}
FixedPointConversion_Debug32_ToInt16
.test("FromUInt32_AlwaysFails")
.forEach(in: [
getUInt32(+32768),
getUInt32(+4294967295),
]) {
expectNil(Int16(exactly: $0))
}
//===----------------------------------------------------------------------===//
// MARK: Int32: (-2147483648)...(+2147483647)
//===----------------------------------------------------------------------===//
FixedPointConversion_Debug32_ToInt16
.test("FromInt32_NeverTraps")
.forEach(in: [
(getInt16(-32768), getInt32(-32768)),
(getInt16(+0), getInt32(+0)),
(getInt16(+32767), getInt32(+32767)),
]) {
expectEqual($0.0, Int16($0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromInt32_NeverFails")
.forEach(in: [
(getInt16(-32768), getInt32(-32768)),
(getInt16(+0), getInt32(+0)),
(getInt16(+32767), getInt32(+32767)),
]) {
expectEqual($0.0, Int16(exactly: $0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromInt32_AlwaysTraps")
.forEach(in: [
getInt32(-2147483648),
getInt32(-32769),
getInt32(+32768),
getInt32(+2147483647),
]) {
expectCrashLater()
_blackHole(Int16($0))
}
FixedPointConversion_Debug32_ToInt16
.test("FromInt32_AlwaysFails")
.forEach(in: [
getInt32(-2147483648),
getInt32(-32769),
getInt32(+32768),
getInt32(+2147483647),
]) {
expectNil(Int16(exactly: $0))
}
//===----------------------------------------------------------------------===//
// MARK: UInt64: (+0)...(+18446744073709551615)
//===----------------------------------------------------------------------===//
FixedPointConversion_Debug32_ToInt16
.test("FromUInt64_NeverTraps")
.forEach(in: [
(getInt16(+0), getUInt64(+0)),
(getInt16(+32767), getUInt64(+32767)),
]) {
expectEqual($0.0, Int16($0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromUInt64_NeverFails")
.forEach(in: [
(getInt16(+0), getUInt64(+0)),
(getInt16(+32767), getUInt64(+32767)),
]) {
expectEqual($0.0, Int16(exactly: $0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromUInt64_AlwaysTraps")
.forEach(in: [
getUInt64(+32768),
getUInt64(+18446744073709551615),
]) {
expectCrashLater()
_blackHole(Int16($0))
}
FixedPointConversion_Debug32_ToInt16
.test("FromUInt64_AlwaysFails")
.forEach(in: [
getUInt64(+32768),
getUInt64(+18446744073709551615),
]) {
expectNil(Int16(exactly: $0))
}
//===----------------------------------------------------------------------===//
// MARK: Int64: (-9223372036854775808)...(+9223372036854775807)
//===----------------------------------------------------------------------===//
FixedPointConversion_Debug32_ToInt16
.test("FromInt64_NeverTraps")
.forEach(in: [
(getInt16(-32768), getInt64(-32768)),
(getInt16(+0), getInt64(+0)),
(getInt16(+32767), getInt64(+32767)),
]) {
expectEqual($0.0, Int16($0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromInt64_NeverFails")
.forEach(in: [
(getInt16(-32768), getInt64(-32768)),
(getInt16(+0), getInt64(+0)),
(getInt16(+32767), getInt64(+32767)),
]) {
expectEqual($0.0, Int16(exactly: $0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromInt64_AlwaysTraps")
.forEach(in: [
getInt64(-9223372036854775808),
getInt64(-32769),
getInt64(+32768),
getInt64(+9223372036854775807),
]) {
expectCrashLater()
_blackHole(Int16($0))
}
FixedPointConversion_Debug32_ToInt16
.test("FromInt64_AlwaysFails")
.forEach(in: [
getInt64(-9223372036854775808),
getInt64(-32769),
getInt64(+32768),
getInt64(+9223372036854775807),
]) {
expectNil(Int16(exactly: $0))
}
//===----------------------------------------------------------------------===//
// MARK: UInt: (+0)...(+4294967295)
//===----------------------------------------------------------------------===//
FixedPointConversion_Debug32_ToInt16
.test("FromUInt_NeverTraps")
.forEach(in: [
(getInt16(+0), getUInt(+0)),
(getInt16(+32767), getUInt(+32767)),
]) {
expectEqual($0.0, Int16($0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromUInt_NeverFails")
.forEach(in: [
(getInt16(+0), getUInt(+0)),
(getInt16(+32767), getUInt(+32767)),
]) {
expectEqual($0.0, Int16(exactly: $0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromUInt_AlwaysTraps")
.forEach(in: [
getUInt(+32768),
getUInt(+4294967295),
]) {
expectCrashLater()
_blackHole(Int16($0))
}
FixedPointConversion_Debug32_ToInt16
.test("FromUInt_AlwaysFails")
.forEach(in: [
getUInt(+32768),
getUInt(+4294967295),
]) {
expectNil(Int16(exactly: $0))
}
//===----------------------------------------------------------------------===//
// MARK: Int: (-2147483648)...(+2147483647)
//===----------------------------------------------------------------------===//
FixedPointConversion_Debug32_ToInt16
.test("FromInt_NeverTraps")
.forEach(in: [
(getInt16(-32768), getInt(-32768)),
(getInt16(+0), getInt(+0)),
(getInt16(+32767), getInt(+32767)),
]) {
expectEqual($0.0, Int16($0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromInt_NeverFails")
.forEach(in: [
(getInt16(-32768), getInt(-32768)),
(getInt16(+0), getInt(+0)),
(getInt16(+32767), getInt(+32767)),
]) {
expectEqual($0.0, Int16(exactly: $0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromInt_AlwaysTraps")
.forEach(in: [
getInt(-2147483648),
getInt(-32769),
getInt(+32768),
getInt(+2147483647),
]) {
expectCrashLater()
_blackHole(Int16($0))
}
FixedPointConversion_Debug32_ToInt16
.test("FromInt_AlwaysFails")
.forEach(in: [
getInt(-2147483648),
getInt(-32769),
getInt(+32768),
getInt(+2147483647),
]) {
expectNil(Int16(exactly: $0))
}
//===----------------------------------------------------------------------===//
// MARK: Float16: (-2047)...(+2047)
//===----------------------------------------------------------------------===//
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
if #available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) {
FixedPointConversion_Debug32_ToInt16
.test("FromFloat16_NeverTraps")
.forEach(in: [
(getInt16(-2047), getFloat16(-2047)),
(getInt16(-128), getFloat16(-128.5)),
(getInt16(+0), getFloat16(-0.5)),
(getInt16(+0), getFloat16(+0)),
(getInt16(+0), getFloat16(-0)),
(getInt16(+0), getFloat16(+0.5)),
(getInt16(+127), getFloat16(+127.5)),
(getInt16(+255), getFloat16(+255.5)),
(getInt16(+2047), getFloat16(+2047)),
]) {
expectEqual($0.0, Int16($0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromFloat16_NeverFails")
.forEach(in: [
(getInt16(-2047), getFloat16(-2047)),
(getInt16(+0), getFloat16(+0)),
(getInt16(+0), getFloat16(-0)),
(getInt16(+2047), getFloat16(+2047)),
]) {
expectEqual($0.0, Int16(exactly: $0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromFloat16_AlwaysTraps")
.forEach(in: [
getFloat16(-.infinity),
getFloat16(-.nan),
getFloat16(-.signalingNaN),
getFloat16(+.infinity),
getFloat16(+.nan),
getFloat16(+.signalingNaN),
]) {
expectCrashLater()
_blackHole(Int16($0))
}
FixedPointConversion_Debug32_ToInt16
.test("FromFloat16_AlwaysFails")
.forEach(in: [
getFloat16(-128.5),
getFloat16(-0.5),
getFloat16(+0.5),
getFloat16(+127.5),
getFloat16(+255.5),
getFloat16(-.infinity),
getFloat16(-.nan),
getFloat16(-.signalingNaN),
getFloat16(+.infinity),
getFloat16(+.nan),
getFloat16(+.signalingNaN),
]) {
expectNil(Int16(exactly: $0))
}
}
#endif // Float16
//===----------------------------------------------------------------------===//
// MARK: Float32: (-16777215)...(+16777215)
//===----------------------------------------------------------------------===//
FixedPointConversion_Debug32_ToInt16
.test("FromFloat32_NeverTraps")
.forEach(in: [
(getInt16(-32768), getFloat32(-32768.5)),
(getInt16(-32768), getFloat32(-32768)),
(getInt16(-128), getFloat32(-128.5)),
(getInt16(+0), getFloat32(-0.5)),
(getInt16(+0), getFloat32(+0)),
(getInt16(+0), getFloat32(-0)),
(getInt16(+0), getFloat32(+0.5)),
(getInt16(+127), getFloat32(+127.5)),
(getInt16(+255), getFloat32(+255.5)),
(getInt16(+32767), getFloat32(+32767)),
(getInt16(+32767), getFloat32(+32767.5)),
]) {
expectEqual($0.0, Int16($0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromFloat32_NeverFails")
.forEach(in: [
(getInt16(-32768), getFloat32(-32768)),
(getInt16(+0), getFloat32(+0)),
(getInt16(+0), getFloat32(-0)),
(getInt16(+32767), getFloat32(+32767)),
]) {
expectEqual($0.0, Int16(exactly: $0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromFloat32_AlwaysTraps")
.forEach(in: [
getFloat32(-16777215),
getFloat32(-32769),
getFloat32(+32768),
getFloat32(+65535.5),
getFloat32(+16777215),
getFloat32(-.infinity),
getFloat32(-.nan),
getFloat32(-.signalingNaN),
getFloat32(+.infinity),
getFloat32(+.nan),
getFloat32(+.signalingNaN),
]) {
expectCrashLater()
_blackHole(Int16($0))
}
FixedPointConversion_Debug32_ToInt16
.test("FromFloat32_AlwaysFails")
.forEach(in: [
getFloat32(-16777215),
getFloat32(-32769),
getFloat32(-32768.5),
getFloat32(-128.5),
getFloat32(-0.5),
getFloat32(+0.5),
getFloat32(+127.5),
getFloat32(+255.5),
getFloat32(+32767.5),
getFloat32(+32768),
getFloat32(+65535.5),
getFloat32(+16777215),
getFloat32(-.infinity),
getFloat32(-.nan),
getFloat32(-.signalingNaN),
getFloat32(+.infinity),
getFloat32(+.nan),
getFloat32(+.signalingNaN),
]) {
expectNil(Int16(exactly: $0))
}
//===----------------------------------------------------------------------===//
// MARK: Float64: (-9007199254740991)...(+9007199254740991)
//===----------------------------------------------------------------------===//
FixedPointConversion_Debug32_ToInt16
.test("FromFloat64_NeverTraps")
.forEach(in: [
(getInt16(-32768), getFloat64(-32768.5)),
(getInt16(-32768), getFloat64(-32768)),
(getInt16(-128), getFloat64(-128.5)),
(getInt16(+0), getFloat64(-0.5)),
(getInt16(+0), getFloat64(+0)),
(getInt16(+0), getFloat64(-0)),
(getInt16(+0), getFloat64(+0.5)),
(getInt16(+127), getFloat64(+127.5)),
(getInt16(+255), getFloat64(+255.5)),
(getInt16(+32767), getFloat64(+32767)),
(getInt16(+32767), getFloat64(+32767.5)),
]) {
expectEqual($0.0, Int16($0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromFloat64_NeverFails")
.forEach(in: [
(getInt16(-32768), getFloat64(-32768)),
(getInt16(+0), getFloat64(+0)),
(getInt16(+0), getFloat64(-0)),
(getInt16(+32767), getFloat64(+32767)),
]) {
expectEqual($0.0, Int16(exactly: $0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromFloat64_AlwaysTraps")
.forEach(in: [
getFloat64(-9007199254740991),
getFloat64(-32769),
getFloat64(+32768),
getFloat64(+65535.5),
getFloat64(+9007199254740991),
getFloat64(-.infinity),
getFloat64(-.nan),
getFloat64(-.signalingNaN),
getFloat64(+.infinity),
getFloat64(+.nan),
getFloat64(+.signalingNaN),
]) {
expectCrashLater()
_blackHole(Int16($0))
}
FixedPointConversion_Debug32_ToInt16
.test("FromFloat64_AlwaysFails")
.forEach(in: [
getFloat64(-9007199254740991),
getFloat64(-32769),
getFloat64(-32768.5),
getFloat64(-128.5),
getFloat64(-0.5),
getFloat64(+0.5),
getFloat64(+127.5),
getFloat64(+255.5),
getFloat64(+32767.5),
getFloat64(+32768),
getFloat64(+65535.5),
getFloat64(+9007199254740991),
getFloat64(-.infinity),
getFloat64(-.nan),
getFloat64(-.signalingNaN),
getFloat64(+.infinity),
getFloat64(+.nan),
getFloat64(+.signalingNaN),
]) {
expectNil(Int16(exactly: $0))
}
//===----------------------------------------------------------------------===//
// MARK: Float80: (-18446744073709551615)...(+18446744073709551615)
//===----------------------------------------------------------------------===//
#if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64))
FixedPointConversion_Debug32_ToInt16
.test("FromFloat80_NeverTraps")
.forEach(in: [
(getInt16(-32768), getFloat80(-32768.5)),
(getInt16(-32768), getFloat80(-32768)),
(getInt16(-128), getFloat80(-128.5)),
(getInt16(+0), getFloat80(-0.5)),
(getInt16(+0), getFloat80(+0)),
(getInt16(+0), getFloat80(-0)),
(getInt16(+0), getFloat80(+0.5)),
(getInt16(+127), getFloat80(+127.5)),
(getInt16(+255), getFloat80(+255.5)),
(getInt16(+32767), getFloat80(+32767)),
(getInt16(+32767), getFloat80(+32767.5)),
]) {
expectEqual($0.0, Int16($0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromFloat80_NeverFails")
.forEach(in: [
(getInt16(-32768), getFloat80(-32768)),
(getInt16(+0), getFloat80(+0)),
(getInt16(+0), getFloat80(-0)),
(getInt16(+32767), getFloat80(+32767)),
]) {
expectEqual($0.0, Int16(exactly: $0.1))
}
FixedPointConversion_Debug32_ToInt16
.test("FromFloat80_AlwaysTraps")
.forEach(in: [
getFloat80(-18446744073709551615),
getFloat80(-32769),
getFloat80(+32768),
getFloat80(+65535.5),
getFloat80(+18446744073709551615),
getFloat80(-.infinity),
getFloat80(-.nan),
getFloat80(-.signalingNaN),
getFloat80(+.infinity),
getFloat80(+.nan),
getFloat80(+.signalingNaN),
]) {
expectCrashLater()
_blackHole(Int16($0))
}
FixedPointConversion_Debug32_ToInt16
.test("FromFloat80_AlwaysFails")
.forEach(in: [
getFloat80(-18446744073709551615),
getFloat80(-32769),
getFloat80(-32768.5),
getFloat80(-128.5),
getFloat80(-0.5),
getFloat80(+0.5),
getFloat80(+127.5),
getFloat80(+255.5),
getFloat80(+32767.5),
getFloat80(+32768),
getFloat80(+65535.5),
getFloat80(+18446744073709551615),
getFloat80(-.infinity),
getFloat80(-.nan),
getFloat80(-.signalingNaN),
getFloat80(+.infinity),
getFloat80(+.nan),
getFloat80(+.signalingNaN),
]) {
expectNil(Int16(exactly: $0))
}
#endif // Float80
runAllTests()
| apache-2.0 |
FelixZhu/FZWebViewProgress | Demo/Demo/AppDelegate.swift | 1 | 2139 | //
// AppDelegate.swift
// Demo
//
// Created by Felix Zhu on 15/11/23.
// Copyright © 2015年 Felix Zhu. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and 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 |
PangeaSocialNetwork/PangeaGallery | PangeaMediaPicker/ImagePicker/AlbumListViewCell.swift | 1 | 2037 | //
// AlbumListViewCell.swift
// PangeaMediaPicker
//
// Created by Roger Li on 2017/8/28.
// Copyright © 2017年 Roger Li. All rights reserved.
//
import UIKit
import Photos
class AlbumListViewCell: UITableViewCell {
static let cellIdentifier = "AlbumListTableViewCellIdentifier"
let bundle = Bundle.init(identifier: "org.cocoapods.PangeaMediaPicker")
@IBOutlet var firstImageView: UIImageView!
@IBOutlet var albumTitleLabel: UILabel!
@IBOutlet var albumCountLabel: UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// Show first image and name
var asset: PHAsset? {
willSet {
if newValue == nil {
firstImageView?.image = UIImage.init(named: "l_picNil", in:bundle, compatibleWith: nil)
return
}
let defaultSize = CGSize(width: UIScreen.main.scale + bounds.height,
height: UIScreen.main.scale + bounds.height)
let options = PHImageRequestOptions()
options.isNetworkAccessAllowed = true
PHCachingImageManager.default().requestImage(for: newValue!,
targetSize: defaultSize,
contentMode: .aspectFill,
options: options,
resultHandler: { (img, _) in
self.firstImageView?.image = img
})
}
}
var albumTitleAndCount: (String?, Int)? {
willSet {
if newValue == nil {
return
}
self.albumTitleLabel?.text = (newValue!.0 ?? "")
self.albumCountLabel?.text = String(describing: newValue!.1)
self.accessoryView?.isHidden = true
self.accessoryView = UIImageView(image: UIImage(named: "checkMark", in: bundle, compatibleWith: nil))
}
}
}
| mit |
lorentey/swift | validation-test/compiler_crashers_fixed/28623-swift-tupletype-get-llvm-arrayref-swift-tupletypeelt-swift-astcontext-const.swift | 63 | 448 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -emit-ir
f#keyPath(n&_==a>c{{{{{{{{{{{{{{{{{_=b:{{{{c{{{{{{d
| apache-2.0 |
gecko655/Swifter | Sources/SwifterFavorites.swift | 2 | 4520 | //
// SwifterFavorites.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension Swifter {
/**
GET favorites/list
Returns the 20 most recent Tweets favorited by the authenticating or specified user.
If you do not provide either a user_id or screen_name to this method, it will assume you are requesting on behalf of the authenticating user. Specify one or the other for best results.
*/
public func getRecentlyFavouritedTweets(count: Int? = nil, sinceID: String? = nil, maxID: String? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) {
let path = "favorites/list.json"
var parameters = Dictionary<String, Any>()
parameters["count"] ??= count
parameters["since_id"] ??= sinceID
parameters["max_id"] ??= maxID
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure)
}
public func getRecentlyFavouritedTweets(for userTag: UserTag, count: Int? = nil, sinceID: String? = nil, maxID: String? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) {
let path = "favorites/list.json"
var parameters = Dictionary<String, Any>()
parameters[userTag.key] = userTag.value
parameters["count"] ??= count
parameters["since_id"] ??= sinceID
parameters["max_id"] ??= maxID
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure)
}
/**
POST favorites/destroy
Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful.
This process invoked by this method is asynchronous. The immediately returned status may not indicate the resultant favorited status of the tweet. A 200 OK response from this method will indicate whether the intended action was successful or not.
*/
public func unfavouriteTweet(forID id: String, includeEntities: Bool? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) {
let path = "favorites/destroy.json"
var parameters = Dictionary<String, Any>()
parameters["id"] = id
parameters["include_entities"] ??= includeEntities
self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure)
}
/**
POST favorites/create
Favorites the status specified in the ID parameter as the authenticating user. Returns the favorite status when successful.
This process invoked by this method is asynchronous. The immediately returned status may not indicate the resultant favorited status of the tweet. A 200 OK response from this method will indicate whether the intended action was successful or not.
*/
public func favouriteTweet(forID id: String, includeEntities: Bool? = nil, success: SuccessHandler? = nil, failure: HTTPRequest.FailureHandler? = nil) {
let path = "favorites/create.json"
var parameters = Dictionary<String, Any>()
parameters["id"] = id
parameters["include_entities"] ??= includeEntities
self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure)
}
}
| mit |
git-hushuai/MOMO | MMHSMeterialProject/FirstViewController.swift | 1 | 17460 | //
// FirstViewController.swift
// MMHSMeterialProject
//
// Created by hushuaike on 16/3/24.
// Copyright © 2016年 hushuaike. All rights reserved.
//
import UIKit
class FirstViewController: TKBaseViewController ,UITableViewDataSource,UITableViewDelegate{
var selectCityArray : NSMutableArray = NSMutableArray();
var selectJobListArray :NSMutableArray = NSMutableArray();
var selectJobNameList :NSMutableArray = NSMutableArray();
var selectEduListArray:NSMutableArray = NSMutableArray();
var TKTableView : UITableView = UITableView.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height), style: UITableViewStyle.Plain);
var dataSourceLists : NSMutableArray = NSMutableArray();
var db = SQLiteDB.sharedInstance();
func setUpUI(){
let notiBtn = UIButton.init(type: UIButtonType.Custom);
notiBtn.setTitle("通知", forState: UIControlState.Normal);
notiBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal);
notiBtn.titleLabel?.font = UIFont.systemFontOfSize(14.0)
notiBtn.setTitleColor(UIColor.init(red: 0xff/255.0, green: 0xff/255.0, blue: 0xff/255.0, alpha: 0.6), forState: UIControlState.Highlighted);
notiBtn.addTarget(self, action: "onClcikNotificationBtn:", forControlEvents: UIControlEvents.TouchUpInside);
notiBtn.sizeToFit();
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: notiBtn);
self.view.addSubview(self.TKTableView);
self.TKTableView.sd_layout()
.topSpaceToView(self.view,0)
.leftSpaceToView(self.view,0)
.rightEqualToView(self.view)
.bottomSpaceToView(self.view,0);
self.TKTableView.backgroundColor = RGBA(0xf3,g:0xf3,b:0xf3,a: 1.0);
self.TKTableView.delegate=self;
self.TKTableView.dataSource=self;
self.TKTableView.tableFooterView = UIView.init();
self.TKTableView.separatorStyle = UITableViewCellSeparatorStyle.None;
self.TKTableView.registerClass(ClassFromString("TKFreeRecommandCell"), forCellReuseIdentifier:"TKFreeRecommandCell");
let loadingView = DGElasticPullToRefreshLoadingViewCircle()
loadingView.tintColor = UIColor(red: 78/255.0, green: 221/255.0, blue: 200/255.0, alpha: 1.0)
self.TKTableView.dg_addPullToRefreshWithActionHandler({ [weak self] () -> Void in
self?.loadNewJobItem();
}, loadingView: loadingView)
self.TKTableView.dg_setPullToRefreshFillColor(UIColor(red: 57/255.0, green: 67/255.0, blue: 89/255.0, alpha: 1.0))
self.TKTableView.dg_setPullToRefreshBackgroundColor(self.TKTableView.backgroundColor!);
self.TKTableView.contentOffset = CGPointMake(0, 120);
// self.TKTableView.dg_headViewStrtLoading();
// self.TKTableView.addBounceHeadRefresh(self,bgColor:UIColor(red: 57/255.0, green: 67/255.0, blue: 89/255.0, alpha: 1.0),loadingColor:UIColor(red: 78/255.0, green: 221/255.0, blue: 200/255.0, alpha: 1.0), action: "loadNewJobItem");
self.TKTableView.addFootRefresh(self, action: "loadMoreData")
}
func loadMoreData(){
print("加载更多历史数据");
self.pullResumeInfo(false);
}
deinit{
self.TKTableView.dg_removePullToRefresh();
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated);
print("self navigation bar subinfo :\(self.navigationController?.navigationBar.subviews)");
self.removeNaviSingleView();
}
func removeNaviSingleView(){
let subView = self.navigationController?.navigationBar.subviews[0];
print("subView FRAME :\(subView?.subviews)");
for tSubView in subView!.subviews{
if tSubView.bounds.size.height == 0.5{
tSubView.hidden = true;
tSubView.removeFromSuperview();
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = RGBA(0xf3, g: 0xf3, b: 0xf3, a: 1.0);
self.setConfigInfo();
self.setUpUI();
dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
self.loadLocalResumeDataInfo();
}
}
func loadLocalResumeDataInfo(){
// 将本地数据取出
let dbCacheModel = TKResumeDataCacheTool();
let nowDate = NSDate.init();
let timeInterval = nowDate.timeIntervalSince1970;
let timeIntervalStr = String.init(format: "%i", Int(timeInterval) - 1);
let localResumeLists = dbCacheModel.loadLocalAllResumeInfoWithResumeCateInfo("免费推荐", timeStampInfo: timeIntervalStr);
print("localResume lists info :\(localResumeLists)");
let itemModelLists : NSArray = TKJobItemModel.parses(arr: localResumeLists) as! [TKJobItemModel];
print("first item Model lists:\(itemModelLists)");
self.dataSourceLists.removeAllObjects();
self.dataSourceLists.addObjectsFromArray(itemModelLists as [AnyObject]);
dispatch_sync(dispatch_get_main_queue()) { () -> Void in
self.TKTableView.reloadData();
}
}
func refreshTableViewInMainQueue(){
self.TKTableView.reloadData();
}
//MARK:通知
func onClcikNotificationBtn(sender:UIButton){
print("sender btn title :\(sender.titleLabel?.text)");
self.hidesBottomBarWhenPushed = true;
let notiVC = HSNotificationController();
notiVC.title = "通知";
self.navigationController?.pushViewController(notiVC, animated: true);
self.hidesBottomBarWhenPushed = false;
}
func loadNewJobItem(){
self.pullResumeInfo(true);
}
func pullResumeInfo(isFreshCopr:Bool){
print("load thread info:\(NSThread.currentThread())");
let reqDict = self.getLoadNewJobItemReqDict(isFreshCopr);
GNNetworkCenter.userLoadResumeItemBaseInfoWithReqObject(reqDict, andFunName: KAppUserLoadResumeFreeRecommandFunc) { (response:YWResponse!) -> Void in
print("reqdict :\(reqDict)---responsedata:\(response.data)");
if (Int(response.retCode) == ERROR_NOERROR){
let responseDict:Dictionary<String,AnyObject> = response.data as! Dictionary;
let itemArr : NSArray = responseDict["data"]! as! NSArray;
print("job item array :\(itemArr)");
if itemArr.count > 0{
let cityInfo = self.getUserSelectCityName();
let deleDBModel = TKResumeDataCacheTool();
deleDBModel.clearTableResumeInfoWithParms("免费推荐", cityCateInfo: cityInfo)
//加载数据成功之后将本地数据清空
let itemModel : NSArray = TKJobItemModel.parses(arr: itemArr) as! [TKJobItemModel];
for i in 0...(itemModel.count-1){
let dict = itemModel[i] as! TKJobItemModel;
dict.cellItemInfo = "免费推荐";
print("dict cell item info :\(dict)");
let dbItem = TKResumeDataCacheTool();
// 先判断本地是否有该条记录
let job_id = String.init(format: "%@", dict.id);
let cellItemCateInfo = dict.cellItemInfo;
let queryData = dbItem.checkResumeItemIsAlreadySaveInLocal(job_id, resumeItemInfo: cellItemCateInfo);
print("queryData inf0 :\(queryData)");
if(queryData.count > 0){
print("本地已经有该条记录");
}else{
// 本地没有该条数据需要缓存
dbItem.setDBItemInfoWithResumeModel(dict);
dbItem.save();
}
}
// 展示数据
print("item model info:\(itemModel)");
self.showItemInfoWithArray(itemModel,isfresh:isFreshCopr);
}
}else{
print("数据加载出错");
let errorInfo = response.msg;
SVProgressHUD.showErrorWithStatus(String.init(format: "%@", errorInfo));
dispatch_after(UInt64(1.5), dispatch_get_main_queue(), { () -> Void in
SVProgressHUD.dismiss();
});
if isFreshCopr == true{
self.TKTableView.head?.stopRefreshing();
}else{
self.TKTableView.foot?.startRefreshing();
}
}
}
}
func getUserSelectCityName()->String{
var cityInfo = NSUserDefaults.standardUserDefaults().stringForKey("kUserDidSelectCityInfoKey");
if( cityInfo == nil) {
cityInfo = "广州";
}
return cityInfo as String!;
}
func showItemInfoWithArray(itemArr : NSArray,isfresh:Bool){
print("tableview head frame:\(self.TKTableView.head?.frame)");
if isfresh == true{
print("current THREADinfo:\(NSThread.currentThread())");
self.dataSourceLists.removeAllObjects();
self.dataSourceLists.addObjectsFromArray(itemArr as [AnyObject]);
print("self dataSourceList info:\(self.dataSourceLists)");
dispatch_after(1, dispatch_get_main_queue(), { () -> Void in
self.TKTableView.reloadData();
self.TKTableView.tableHeadStopRefreshing();
self.TKTableView.dg_stopLoading();
})
}else{
self.dataSourceLists.addObjectsFromArray(itemArr as [AnyObject]);
if itemArr.count >= 20{
dispatch_after(1, dispatch_get_main_queue(), { () -> Void in
self.TKTableView.tableFootStopRefreshing();
self.TKTableView.reloadData();
})
}else{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
dispatch_after(1, dispatch_get_main_queue(), { () -> Void in
self.TKTableView.tableFootShowNomore();
self.TKTableView.reloadData();
});
})
}
}
}
func getLoadNewJobItemReqDict(isFresh : Bool)->NSMutableDictionary{
//
let reqDict = NSMutableDictionary();
let keyStr1 : String = NSString.init(format: "menu%@0", GNUserService.sharedUserService().userId) as String!;
let keyStr2 : String = NSString.init(format: "menu%@1", GNUserService.sharedUserService().userId) as String!;
let keyStr3 : String = NSString.init(format: "menu%@2", GNUserService.sharedUserService().userId) as String!;
let userSelectCityInfo = NSUserDefaults.standardUserDefaults().stringForKey(keyStr1);
let userSelectJobCateInfo = NSUserDefaults.standardUserDefaults().stringForKey(keyStr2);
let userSelectDegreeInfo = NSUserDefaults.standardUserDefaults().stringForKey(keyStr3);
var cityStr :String = "";
var jobCateStr :String = "";
var degreeStr : String = "";
if userSelectCityInfo != nil && self.selectCityArray.count>0{
cityStr = self.selectCityArray.objectAtIndex(Int(userSelectCityInfo!)!) as! String;
cityStr = (cityStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 && (cityStr=="不限")) ? "":cityStr; }
if userSelectJobCateInfo != nil && self.selectJobNameList.count>0 {
jobCateStr = self.selectJobNameList.objectAtIndex(Int(userSelectJobCateInfo!)!) as! String;
jobCateStr = (jobCateStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 && (jobCateStr=="不限")) ? "":cityStr;
for i in 1...self.selectJobListArray.count{
let dict : Dictionary<String,String> = self.selectJobListArray.objectAtIndex(i) as! Dictionary;
if dict["name"]==jobCateStr{
jobCateStr = dict["id"]!;
}
}
}
if userSelectDegreeInfo != nil && self.selectEduListArray.count>0{
degreeStr = self.selectEduListArray.objectAtIndex(Int(userSelectDegreeInfo!)!) as! String;
degreeStr = (degreeStr=="不限") ? "" : degreeStr;
}
reqDict.setObject(cityStr, forKey: "position");
reqDict.setObject(jobCateStr, forKey: "category");
reqDict.setObject(degreeStr, forKey: "degree");
if isFresh==true{
// 刷新
reqDict.setObject(NSNumber.init(integer: 0),forKey: "lastTime");
}else{
//加载更多
if self.dataSourceLists.count > 0 {
let jobItemModel = self.dataSourceLists.lastObject as! TKJobItemModel;
reqDict.setObject(jobItemModel.ts,forKey: "lastTime");
}else{
//reqDict.setObject(NSNumber.init(integer: 0),forKey: "lastTime");
}
}
return reqDict;
}
func setConfigInfo(){
let positionArray = NSUserDefaults.standardUserDefaults().objectForKey("positions");
self.selectCityArray.addObject("不限");
self.selectCityArray.addObjectsFromArray(positionArray as! Array);
let jobListArr = NSUserDefaults
.standardUserDefaults()
.objectForKey("job_category1");
self.selectJobNameList.addObject("不限");
self.selectJobListArray.addObjectsFromArray(jobListArr as! Array);
for i in 0...(self.selectJobListArray.count-1){
let dict = self.selectJobListArray.objectAtIndex(i) ;
let jobItemName = dict["name"];
self.selectJobNameList.addObject(jobItemName as! String);
}
let degreeArr = NSUserDefaults
.standardUserDefaults()
.objectForKey("degreeArray");
self.selectEduListArray.addObject("不限");
self.selectEduListArray.addObjectsFromArray(degreeArr as! Array);
}
// MARK: rgb color
func RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat)->UIColor {
return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a) }
// MARK: tableview delegate 和 datasource 方法
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
print("dataSourceList count :\(self.dataSourceLists.count)");
self.TKTableView.foot?.hidden = self.dataSourceLists.count > 0 ? false : true;
self.TKTableView.foot?.userInteractionEnabled = self.dataSourceLists.count > 0 ? true : false;
return self.dataSourceLists.count;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1;
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0{
return 0 ;
}
return 10.0
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headView = UIView.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 10.0));
headView.backgroundColor = UIColor.clearColor();
return headView;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TKFreeRecommandCell") as? TKFreeRecommandCell;
let resumeModel = self.dataSourceLists.objectAtIndex(indexPath.section);
cell!.resumeItemModel = resumeModel as? TKJobItemModel;
cell!.sd_tableView = tableView;
cell!.sd_indexPath = indexPath;
return cell!;
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let resumeModel = self.dataSourceLists.objectAtIndex(indexPath.section);
return self.TKTableView.cellHeightForIndexPath(indexPath,model: resumeModel, keyPath:"resumeItemModel", cellClass: ClassFromString("TKFreeRecommandCell"), contentViewWidth:UIScreen.mainScreen().bounds.size.width);
}
// func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
//
// let resumeModel = self.dataSourceLists.objectAtIndex(indexPath.section);
// let cell = tableView.cellForRowAtIndexPath(indexPath) as? TKFreeRecommandCell;
// cell!.resumeItemModel = resumeModel as? TKJobItemModel;
// }
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true);
print("indexPath info:\(indexPath)");
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
adorabledorks/radio.ios | R-a-dio/MasterViewController.swift | 1 | 3521 | import UIKit
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects = NSMutableArray()
override func awakeFromNib() {
super.awakeFromNib()
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.clearsSelectionOnViewWillAppear = false
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
objects.insertObject(NSDate(), atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let object = objects[indexPath.row] as NSDate
let controller = (segue.destinationViewController as UINavigationController).topViewController as DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let object = objects[indexPath.row] as NSDate
cell.textLabel!.text = object.description
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeObjectAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
}
| mit |
JanGorman/Table | Package.swift | 1 | 339 | // swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "Table",
products: [
.library(name: "Table",targets: ["Table"])
],
dependencies: [],
targets: [
.target(name: "Table", dependencies: [], path: "Sources"),
.testTarget(name: "TableTests", dependencies: ["Table"], path: "Tests")
]
)
| mit |
chatea/BulletinBoard | BulletinBoard/MsgCollection/LabelCollectionViewItemView.swift | 1 | 950 | //
import Foundation
import AppKit
class LabelCollectionViewItemView: NSView {
// MARK: properties
var selected: Bool = false {
didSet {
if selected != oldValue {
needsDisplay = true
}
}
}
var highlightState: NSCollectionViewItemHighlightState = .None {
didSet {
if highlightState != oldValue {
needsDisplay = true
}
}
}
// MARK: NSView
override var wantsUpdateLayer: Bool {
return true
}
override func updateLayer() {
if selected {
self.layer?.cornerRadius = 10
layer!.backgroundColor = NSColor.darkGrayColor().CGColor
} else {
self.layer?.cornerRadius = 0
layer!.backgroundColor = NSColor.lightGrayColor().CGColor
}
}
// MARK: init
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
wantsLayer = true
layer?.masksToBounds = true
}
required init?(coder: NSCoder) {
super.init(coder: coder)
wantsLayer = true
layer?.masksToBounds = true
}
} | apache-2.0 |
mozilla-mobile/firefox-ios | Tests/XCUITests/PrivateBrowsingTest.swift | 2 | 13307 | // 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 XCTest
let url1 = "example.com"
let url2 = path(forTestPage: "test-mozilla-org.html")
let url3 = path(forTestPage: "test-example.html")
let urlIndexedDB = path(forTestPage: "test-indexeddb-private.html")
let url1And3Label = "Example Domain"
let url2Label = "Internet for people, not profit — Mozilla"
class PrivateBrowsingTest: BaseTestCase {
typealias HistoryPanelA11y = AccessibilityIdentifiers.LibraryPanels.HistoryPanel
func testPrivateTabDoesNotTrackHistory() {
navigator.openURL(url1)
waitForTabsButton()
navigator.goto(BrowserTabMenu)
// Go to History screen
navigator.goto(LibraryPanel_History)
waitForExistence(app.tables[HistoryPanelA11y.tableView])
XCTAssertTrue(app.tables[HistoryPanelA11y.tableView].staticTexts[url1And3Label].exists)
// History without counting Clear Recent History and Recently Closed
let history = app.tables[HistoryPanelA11y.tableView].cells.count - 1
XCTAssertEqual(history, 1, "History entries in regular browsing do not match")
// Go to Private browsing to open a website and check if it appears on History
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
navigator.openURL(url2)
waitForValueContains(app.textFields["url"], value: "mozilla")
navigator.goto(LibraryPanel_History)
waitForExistence(app.tables[HistoryPanelA11y.tableView])
XCTAssertTrue(app.tables[HistoryPanelA11y.tableView].staticTexts[url1And3Label].exists)
XCTAssertFalse(app.tables[HistoryPanelA11y.tableView].staticTexts[url2Label].exists)
// Open one tab in private browsing and check the total number of tabs
let privateHistory = app.tables[HistoryPanelA11y.tableView].cells.count - 1
XCTAssertEqual(privateHistory, 1, "History entries in private browsing do not match")
}
func testTabCountShowsOnlyNormalOrPrivateTabCount() {
// Open two tabs in normal browsing and check the number of tabs open
navigator.performAction(Action.CloseURLBarOpen)
navigator.nowAt(NewTabScreen)
navigator.openNewURL(urlString: url2)
waitUntilPageLoad()
waitForTabsButton()
navigator.goto(TabTray)
waitForExistence(app.cells.staticTexts[url2Label])
let numTabs = app.otherElements["Tabs Tray"].cells.count
XCTAssertEqual(numTabs, 2, "The number of regular tabs is not correct")
// Open one tab in private browsing and check the total number of tabs
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
navigator.goto(URLBarOpen)
waitUntilPageLoad()
navigator.openURL(url3)
waitForValueContains(app.textFields["url"], value: "test-example")
navigator.nowAt(NewTabScreen)
waitForTabsButton()
navigator.goto(TabTray)
waitForExistence(app.cells.staticTexts[url1And3Label])
let numPrivTabs = app.otherElements["Tabs Tray"].cells.count
XCTAssertEqual(numPrivTabs, 1, "The number of private tabs is not correct")
// Go back to regular mode and check the total number of tabs
navigator.toggleOff(userState.isPrivate, withAction: Action.ToggleRegularMode)
waitForExistence(app.cells.staticTexts[url2Label])
waitForNoExistence(app.cells.staticTexts[url1And3Label])
let numRegularTabs = app.otherElements["Tabs Tray"].cells.count
XCTAssertEqual(numRegularTabs, 2, "The number of regular tabs is not correct")
}
func testClosePrivateTabsOptionClosesPrivateTabs() {
// Check that Close Private Tabs when closing the Private Browsing Button is off by default
navigator.performAction(Action.CloseURLBarOpen)
navigator.nowAt(NewTabScreen)
waitForExistence(app.buttons[AccessibilityIdentifiers.Toolbar.settingsMenuButton], timeout: 5)
navigator.goto(SettingsScreen)
let settingsTableView = app.tables[AccessibilityIdentifiers.Settings.tableViewController]
while settingsTableView.staticTexts["Close Private Tabs"].exists == false {
settingsTableView.swipeUp()
}
let closePrivateTabsSwitch = settingsTableView.switches["settings.closePrivateTabs"]
XCTAssertFalse(closePrivateTabsSwitch.isSelected)
// Open a Private tab
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
navigator.openURL(url2)
waitForTabsButton()
// Go back to regular browser
navigator.toggleOff(userState.isPrivate, withAction: Action.ToggleRegularMode)
// Go back to private browsing and check that the tab has not been closed
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
waitForExistence(app.cells.staticTexts[url2Label], timeout: 5)
checkOpenTabsBeforeClosingPrivateMode()
// Now the enable the Close Private Tabs when closing the Private Browsing Button
if !iPad() {
app.cells.staticTexts[url2Label].tap()
} else {
app.otherElements["Tabs Tray"].collectionViews.cells.staticTexts[url2Label].tap()
}
waitForTabsButton()
waitForExistence(app.buttons[AccessibilityIdentifiers.Toolbar.settingsMenuButton], timeout: 10)
navigator.nowAt(BrowserTab)
navigator.goto(SettingsScreen)
closePrivateTabsSwitch.tap()
navigator.goto(BrowserTab)
waitForTabsButton()
// Go back to regular browsing and check that the private tab has been closed and that the initial Private Browsing message appears when going back to Private Browsing
navigator.toggleOff(userState.isPrivate, withAction: Action.ToggleRegularMode)
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
waitForNoExistence(app.cells.staticTexts["Internet for people, not profit — Mozilla. Currently selected tab."])
checkOpenTabsAfterClosingPrivateMode()
}
/* Loads a page that checks if an db file exists already. It uses indexedDB on both the main document, and in a web worker.
The loaded page has two staticTexts that get set when the db is correctly created (because the db didn't exist in the cache)
https://bugzilla.mozilla.org/show_bug.cgi?id=1646756
*/
func testClearIndexedDB() {
navigator.performAction(Action.CloseURLBarOpen)
navigator.nowAt(NewTabScreen)
enableClosePrivateBrowsingOptionWhenLeaving()
func checkIndexedDBIsCreated() {
navigator.openURL(urlIndexedDB)
waitUntilPageLoad()
XCTAssertTrue(app.webViews.staticTexts["DB_CREATED_PAGE"].exists)
XCTAssertTrue(app.webViews.staticTexts["DB_CREATED_WORKER"].exists)
}
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
checkIndexedDBIsCreated()
navigator.toggleOff(userState.isPrivate, withAction: Action.ToggleRegularMode)
checkIndexedDBIsCreated()
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
checkIndexedDBIsCreated()
}
func testPrivateBrowserPanelView() {
navigator.performAction(Action.CloseURLBarOpen)
navigator.nowAt(NewTabScreen)
// If no private tabs are open, there should be a initial screen with label Private Browsing
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
let numPrivTabsFirstTime = app.otherElements["Tabs Tray"].cells.count
XCTAssertEqual(numPrivTabsFirstTime, 0, "The number of tabs is not correct, there should not be any private tab yet")
// If a private tab is open Private Browsing screen is not shown anymore
navigator.openURL(path(forTestPage: "test-mozilla-org.html"))
// Wait until the page loads and go to regular browser
waitUntilPageLoad()
waitForTabsButton()
navigator.toggleOff(userState.isPrivate, withAction: Action.ToggleRegularMode)
// Go back to private browsing
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
navigator.nowAt(TabTray)
let numPrivTabsOpen = app.otherElements["Tabs Tray"].cells.count
XCTAssertEqual(numPrivTabsOpen, 1, "The number of private tabs is not correct")
}
}
fileprivate extension BaseTestCase {
func checkOpenTabsBeforeClosingPrivateMode() {
if !iPad() {
let numPrivTabs = app.otherElements["Tabs Tray"].cells.count
XCTAssertEqual(numPrivTabs, 1, "The number of tabs is not correct, the private tab should not have been closed")
} else {
let numPrivTabs = app.collectionViews["Top Tabs View"].cells.count
XCTAssertEqual(numPrivTabs, 1, "The number of tabs is not correct, the private tab should not have been closed")
}
}
func checkOpenTabsAfterClosingPrivateMode() {
let numPrivTabsAfterClosing = app.otherElements["Tabs Tray"].cells.count
XCTAssertEqual(numPrivTabsAfterClosing, 0, "The number of tabs is not correct, the private tab should have been closed")
}
func enableClosePrivateBrowsingOptionWhenLeaving() {
navigator.goto(SettingsScreen)
let settingsTableView = app.tables["AppSettingsTableViewController.tableView"]
while settingsTableView.staticTexts["Close Private Tabs"].exists == false {
settingsTableView.swipeUp()
}
let closePrivateTabsSwitch = settingsTableView.switches["settings.closePrivateTabs"]
closePrivateTabsSwitch.tap()
}
}
class PrivateBrowsingTestIpad: IpadOnlyTestCase {
typealias HistoryPanelA11y = AccessibilityIdentifiers.LibraryPanels.HistoryPanel
// This test is only enabled for iPad. Shortcut does not exists on iPhone
func testClosePrivateTabsOptionClosesPrivateTabsShortCutiPad() {
if skipPlatform { return }
waitForTabsButton()
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
navigator.openURL(url2)
waitForExistence(app.buttons[AccessibilityIdentifiers.Toolbar.settingsMenuButton], timeout: 5)
enableClosePrivateBrowsingOptionWhenLeaving()
// Leave PM by tapping on PM shourt cut
navigator.toggleOff(userState.isPrivate, withAction: Action.TogglePrivateModeFromTabBarHomePanel)
waitForTabsButton()
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode)
checkOpenTabsAfterClosingPrivateMode()
}
func testiPadDirectAccessPrivateMode() {
if skipPlatform { return }
waitForTabsButton()
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateModeFromTabBarHomePanel)
// A Tab opens directly in HomePanels view
XCTAssertFalse(app.staticTexts["Private Browsing"].exists, "Private Browsing screen is not shown")
// Open website and check it does not appear under history once going back to regular mode
navigator.openURL("http://example.com")
waitUntilPageLoad()
// This action to enable private mode is defined on HomePanel Screen that is why we need to open a new tab and be sure we are on that screen to use the correct action
navigator.goto(NewTabScreen)
navigator.toggleOff(userState.isPrivate, withAction: Action.TogglePrivateModeFromTabBarHomePanel)
navigator.nowAt(NewTabScreen)
navigator.goto(LibraryPanel_History)
waitForExistence(app.tables[HistoryPanelA11y.tableView])
// History without counting Clear Recent History, Recently Closed
let history = app.tables[HistoryPanelA11y.tableView].cells.count - 2
XCTAssertEqual(history, 0, "History list should be empty")
}
func testiPadDirectAccessPrivateModeBrowserTab() {
if skipPlatform { return }
navigator.openURL("www.mozilla.org")
waitForTabsButton()
navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateModeFromTabBarBrowserTab)
// A Tab opens directly in HomePanels view
XCTAssertFalse(app.staticTexts["Private Browsing"].exists, "Private Browsing screen is not shown")
// Open website and check it does not appear under history once going back to regular mode
navigator.openURL("http://example.com")
navigator.toggleOff(userState.isPrivate, withAction: Action.TogglePrivateModeFromTabBarBrowserTab)
navigator.goto(LibraryPanel_History)
waitForExistence(app.tables[HistoryPanelA11y.tableView])
// History without counting Clear Recent History, Recently Closed
let history = app.tables[HistoryPanelA11y.tableView].cells.count - 2
XCTAssertEqual(history, 1, "There should be one entry in History")
let savedToHistory = app.tables[HistoryPanelA11y.tableView].cells.staticTexts[url2Label]
waitForExistence(savedToHistory)
XCTAssertTrue(savedToHistory.exists)
}
}
| mpl-2.0 |
google/iosched-ios | Source/IOsched/Screens/Schedule/Details/Speaker/SpeakerDetailsCollectionViewMainInfoCell.swift | 1 | 4749 | //
// Copyright (c) 2017 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 MaterialComponents
import SafariServices
class SpeakerDetailsCollectionViewMainInfoCell: MDCCollectionViewCell {
private lazy var detailsLabel: UILabel = self.setupDetailsLabel()
private lazy var twitterButton: MDCButton = self.setupTwitterButton()
private lazy var stackContainer: UIStackView = self.setupStackContainer()
private lazy var spacerView: UIView = self.setupSpacerView()
var viewModel: SpeakerDetailsMainInfoViewModel? {
didSet {
updateFromViewModel()
}
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
// MARK: - View setup
private func setupViews() {
contentView.addSubview(detailsLabel)
contentView.addSubview(stackContainer)
let views = [
"detailsLabel": detailsLabel,
"stackContainer": stackContainer
] as [String: Any]
let metrics = [
"topMargin": 20,
"bottomMargin": 20,
"leftMargin": 16,
"rightMargin": 16
]
var constraints =
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(leftMargin)-[detailsLabel]-(rightMargin)-|",
options: [],
metrics: metrics,
views: views)
constraints +=
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(leftMargin)-[stackContainer]-(rightMargin)-|",
options: [],
metrics: metrics,
views: views)
constraints +=
NSLayoutConstraint.constraints(withVisualFormat: "V:|-(topMargin)-[detailsLabel]-[stackContainer]-(bottomMargin)-|",
options: [],
metrics: metrics,
views: views)
NSLayoutConstraint.activate(constraints)
}
private func setupStackContainer() -> UIStackView {
let stackContainer = UIStackView()
stackContainer.addArrangedSubview(spacerView)
stackContainer.translatesAutoresizingMaskIntoConstraints = false
stackContainer.distribution = .fill
stackContainer.axis = .horizontal
stackContainer.spacing = 24
stackContainer.isUserInteractionEnabled = true
return stackContainer
}
private func setupSpacerView() -> UIView {
let spacerView = UIView()
spacerView.translatesAutoresizingMaskIntoConstraints = false
spacerView.backgroundColor = UIColor.clear
return spacerView
}
private func setupTwitterButton() -> MDCButton {
let twitterButton = MDCFlatButton()
twitterButton.isUppercaseTitle = false
twitterButton.translatesAutoresizingMaskIntoConstraints = false
twitterButton.contentEdgeInsets = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
twitterButton.addTarget(self, action: #selector(twitterTapped), for: .touchUpInside)
twitterButton.setImage(UIImage(named: "ic_twitter"), for: .normal)
twitterButton.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .horizontal)
return twitterButton
}
@objc func twitterTapped() {
viewModel?.twitterTapped()
}
private func setupDetailsLabel() -> UILabel {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.mdc_preferredFont(forMaterialTextStyle: .body1)
label.enableAdjustFontForContentSizeCategory()
label.textColor = MDCPalette.grey.tint800
label.numberOfLines = 0
return label
}
// MARK: - Model handling
private func updateFromViewModel() {
if let viewModel = viewModel {
detailsLabel.text = viewModel.bio
detailsLabel.setLineHeightMultiple(1.4)
if viewModel.twitterURL != nil {
stackContainer.insertArrangedSubview(twitterButton, at: 0)
}
// make cell tappable for the twitter and plus url buttons
isUserInteractionEnabled = true
setNeedsLayout()
layoutIfNeeded()
invalidateIntrinsicContentSize()
}
}
}
| apache-2.0 |
srxboys/RXSwiftExtention | Pods/SwifterSwift/Source/Extensions/DateExtensions.swift | 1 | 16168 | //
// DateExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/5/16.
// Copyright © 2016 Omar Albeik. All rights reserved.
//
import Foundation
public extension Date {
/// SwifterSwift: Day name format.
///
/// - threeLetters: 3 letter day abbreviation of day name.
/// - oneLetter: 1 letter day abbreviation of day name.
/// - full: Full day name.
public enum DayNameStyle {
case threeLetters
case oneLetter
case full
}
/// SwifterSwift: Month name format.
///
/// - threeLetters: 3 letter month abbreviation of month name.
/// - oneLetter: 1 letter month abbreviation of month name.
/// - full: Full month name.
public enum MonthNameStyle {
case threeLetters
case oneLetter
case full
}
}
// MARK: - Properties
public extension Date {
/// SwifterSwift: User’s current calendar.
public var calendar: Calendar {
return Calendar.current
}
/// SwifterSwift: Era.
public var era: Int {
return Calendar.current.component(.era, from: self)
}
/// SwifterSwift: Year.
public var year: Int {
get {
return Calendar.current.component(.year, from: self)
}
set {
if let date = Calendar.current.date(bySetting: .year, value: newValue, of: self) {
self = date
}
}
}
/// SwifterSwift: Quarter.
public var quarter: Int {
return Calendar.current.component(.quarter, from: self)
}
/// SwifterSwift: Month.
public var month: Int {
get {
return Calendar.current.component(.month, from: self)
}
set {
if let date = Calendar.current.date(bySetting: .month, value: newValue, of: self) {
self = date
}
}
}
/// SwifterSwift: Week of year.
public var weekOfYear: Int {
return Calendar.current.component(.weekOfYear, from: self)
}
/// SwifterSwift: Week of month.
public var weekOfMonth: Int {
return Calendar.current.component(.weekOfMonth, from: self)
}
/// SwifterSwift: Weekday.
public var weekday: Int {
get {
return Calendar.current.component(.weekday, from: self)
}
set {
if let date = Calendar.current.date(bySetting: .weekday, value: newValue, of: self) {
self = date
}
}
}
/// SwifterSwift: Day.
public var day: Int {
get {
return Calendar.current.component(.day, from: self)
}
set {
if let date = Calendar.current.date(bySetting: .day, value: newValue, of: self) {
self = date
}
}
}
/// SwifterSwift: Hour.
public var hour: Int {
get {
return Calendar.current.component(.hour, from: self)
}
set {
if let date = Calendar.current.date(bySetting: .hour, value: newValue, of: self) {
self = date
}
}
}
/// SwifterSwift: Minutes.
public var minute: Int {
get {
return Calendar.current.component(.minute, from: self)
}
set {
if let date = Calendar.current.date(bySetting: .minute, value: newValue, of: self) {
self = date
}
}
}
/// SwifterSwift: Seconds.
public var second: Int {
get {
return Calendar.current.component(.second, from: self)
}
set {
if let date = Calendar.current.date(bySetting: .second, value: newValue, of: self) {
self = date
}
}
}
/// SwifterSwift: Nanoseconds.
public var nanosecond: Int {
get {
return Calendar.current.component(.nanosecond, from: self)
}
set {
if let date = Calendar.current.date(bySetting: .nanosecond, value: newValue, of: self) {
self = date
}
}
}
/// SwifterSwift: Milliseconds.
public var millisecond: Int {
get {
return Calendar.current.component(.nanosecond, from: self) / 1000000
}
set {
let ns = newValue * 1000000
if let date = Calendar.current.date(bySetting: .nanosecond, value: ns, of: self) {
self = date
}
}
}
/// SwifterSwift: Check if date is in future.
public var isInFuture: Bool {
return self > Date()
}
/// SwifterSwift: Check if date is in past.
public var isInPast: Bool {
return self < Date()
}
/// SwifterSwift: Check if date is in today.
public var isInToday: Bool {
return Calendar.current.isDateInToday(self)
}
/// SwifterSwift: Check if date is within yesterday.
public var isInYesterday: Bool {
return Calendar.current.isDateInYesterday(self)
}
/// SwifterSwift: Check if date is within tomorrow.
public var isInTomorrow: Bool {
return Calendar.current.isDateInTomorrow(self)
}
/// SwifterSwift: Check if date is within a weekend period.
public var isInWeekend: Bool {
return Calendar.current.isDateInWeekend(self)
}
/// SwifterSwift: ISO8601 string of format (yyyy-MM-dd'T'HH:mm:ss.SSS) from date.
public var iso8601String: String {
// https://github.com/justinmakaila/NSDate-ISO-8601/blob/master/NSDateISO8601.swift
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
return dateFormatter.string(from: self).appending("Z")
}
/// SwifterSwift: Nearest five minutes to date.
public var nearestFiveMinutes: Date {
var components = Calendar.current.dateComponents([.year, .month , .day , .hour , .minute], from: self)
let min = components.minute!
components.minute! = min % 5 < 3 ? min - min % 5 : min + 5 - (min % 5)
components.second = 0
return Calendar.current.date(from: components)!
}
/// SwifterSwift: Nearest ten minutes to date.
public var nearestTenMinutes: Date {
var components = Calendar.current.dateComponents([.year, .month , .day , .hour , .minute], from: self)
let min = components.minute!
components.minute? = min % 10 < 6 ? min - min % 10 : min + 10 - (min % 10)
components.second = 0
return Calendar.current.date(from: components)!
}
/// SwifterSwift: Nearest quarter hour to date.
public var nearestQuarterHour: Date {
var components = Calendar.current.dateComponents([.year, .month , .day , .hour , .minute], from: self)
let min = components.minute!
components.minute! = min % 15 < 8 ? min - min % 15 : min + 15 - (min % 15)
components.second = 0
return Calendar.current.date(from: components)!
}
/// SwifterSwift: Nearest half hour to date.
public var nearestHalfHour: Date {
var components = Calendar.current.dateComponents([.year, .month , .day , .hour , .minute], from: self)
let min = components.minute!
components.minute! = min % 30 < 15 ? min - min % 30 : min + 30 - (min % 30)
components.second = 0
return Calendar.current.date(from: components)!
}
/// SwifterSwift: Nearest hour to date.
public var nearestHour: Date {
if minute >= 30 {
return beginning(of: .hour)!.adding(.hour, value: 1)
}
return beginning(of: .hour)!
}
/// SwifterSwift: Time zone used by system.
public var timeZone: TimeZone {
return Calendar.current.timeZone
}
/// SwifterSwift: UNIX timestamp from date.
public var unixTimestamp: Double {
return timeIntervalSince1970
}
}
// MARK: - Methods
public extension Date {
/// SwifterSwift: Date by adding multiples of calendar component.
///
/// - Parameters:
/// - component: component type.
/// - value: multiples of components to add.
/// - Returns: original date + multiples of component added.
public func adding(_ component: Calendar.Component, value: Int) -> Date {
return Calendar.current.date(byAdding: component, value: value, to: self)!
}
/// SwifterSwift: Add calendar component to date.
///
/// - Parameters:
/// - component: component type.
/// - value: multiples of compnenet to add.
public mutating func add(_ component: Calendar.Component, value: Int) {
self = adding(component, value: value)
}
/// SwifterSwift: Date by changing value of calendar component.
///
/// - Parameters:
/// - component: component type.
/// - value: new value of compnenet to change.
/// - Returns: original date after changing given component to given value.
public func changing(_ component: Calendar.Component, value: Int) -> Date? {
return Calendar.current.date(bySetting: component, value: value, of: self)
}
/// SwifterSwift: Data at the beginning of calendar component.
///
/// - Parameter component: calendar component to get date at the beginning of.
/// - Returns: date at the beginning of calendar component (if applicable).
public func beginning(of component: Calendar.Component) -> Date? {
switch component {
case .second:
return Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: self))
case .minute:
return Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: self))
case .hour:
return Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month, .day, .hour], from: self))
case .day:
return Calendar.current.startOfDay(for: self)
case .weekOfYear, .weekOfMonth:
return Calendar.current.date(from:
Calendar.current.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))
case .month:
return Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month], from: self))
case .year:
return Calendar.current.date(from:
Calendar.current.dateComponents([.year], from: self))
default:
return nil
}
}
/// SwifterSwift: Date at the end of calendar component.
///
/// - Parameter component: calendar component to get date at the end of.
/// - Returns: date at the end of calendar component (if applicable).
public func end(of component: Calendar.Component) -> Date? {
switch component {
case .second:
var date = adding(.second, value: 1)
date = Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date))!
date.add(.second, value: -1)
return date
case .minute:
var date = adding(.minute, value: 1)
let after = Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: date))!
date = after.adding(.second, value: -1)
return date
case .hour:
var date = adding(.hour, value: 1)
let after = Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month, .day, .hour], from: date))!
date = after.adding(.second, value: -1)
return date
case .day:
var date = adding(.day, value: 1)
date = Calendar.current.startOfDay(for: date)
date.add(.second, value: -1)
return date
case .weekOfYear, .weekOfMonth:
var date = self
let beginningOfWeek = Calendar.current.date(from:
Calendar.current.dateComponents([.yearForWeekOfYear, .weekOfYear], from: date))!
date = beginningOfWeek.adding(.day, value: 7).adding(.second, value: -1)
return date
case .month:
var date = adding(.month, value: 1)
let after = Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month], from: date))!
date = after.adding(.second, value: -1)
return date
case .year:
var date = adding(.year, value: 1)
let after = Calendar.current.date(from:
Calendar.current.dateComponents([.year], from: date))!
date = after.adding(.second, value: -1)
return date
default:
return nil
}
}
/// SwifterSwift: Date string from date.
///
/// - Parameter style: DateFormatter style (default is .medium).
/// - Returns: date string.
public func dateString(ofStyle style: DateFormatter.Style = .medium) -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .none
dateFormatter.dateStyle = style
return dateFormatter.string(from: self)
}
/// SwifterSwift: Date and time string from date.
///
/// - Parameter style: DateFormatter style (default is .medium).
/// - Returns: date and time string.
public func dateTimeString(ofStyle style: DateFormatter.Style = .medium) -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = style
dateFormatter.dateStyle = style
return dateFormatter.string(from: self)
}
/// SwifterSwift: Check if date is in current given calendar component.
///
/// - Parameter component: calendar component to check.
/// - Returns: true if date is in current given calendar component.
public func isInCurrent(_ component: Calendar.Component) -> Bool {
return calendar.isDate(self, equalTo: Date(), toGranularity: component)
}
/// SwifterSwift: Time string from date
///
/// - Parameter style: DateFormatter style (default is .medium).
/// - Returns: time string.
public func timeString(ofStyle style: DateFormatter.Style = .medium) -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = style
dateFormatter.dateStyle = .none
return dateFormatter.string(from: self)
}
/// SwifterSwift: Day name from date.
///
/// - Parameter Style: style of day name (default is DayNameStyle.full).
/// - Returns: day name string (example: W, Wed, Wednesday).
public func dayName(ofStyle style: DayNameStyle = .full) -> String {
// http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/
let dateFormatter = DateFormatter()
var format: String {
switch style {
case .oneLetter:
return "EEEEE"
case .threeLetters:
return "EEE"
case .full:
return "EEEE"
}
}
dateFormatter.setLocalizedDateFormatFromTemplate(format)
return dateFormatter.string(from: self)
}
/// SwifterSwift: Month name from date.
///
/// - Parameter Style: style of month name (default is MonthNameStyle.full).
/// - Returns: month name string (example: D, Dec, December).
public func monthName(ofStyle style: MonthNameStyle = .full) -> String {
// http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/
let dateFormatter = DateFormatter()
var format: String {
switch style {
case .oneLetter:
return "MMMMM"
case .threeLetters:
return "MMM"
case .full:
return "MMMM"
}
}
dateFormatter.setLocalizedDateFormatFromTemplate(format)
return dateFormatter.string(from: self)
}
}
// MARK: - Initializers
public extension Date {
/// SwifterSwift: Create a new date form calendar components.
///
/// - Parameters:
/// - calendar: Calendar (default is current).
/// - timeZone: TimeZone (default is current).
/// - era: Era (default is current era).
/// - year: Year (default is current year).
/// - month: Month (default is current month).
/// - day: Day (default is today).
/// - hour: Hour (default is current hour).
/// - minute: Minute (default is current minute).
/// - second: Second (default is current second).
/// - nanosecond: Nanosecond (default is current nanosecond).
public init?(
calendar: Calendar? = Calendar.current,
timeZone: TimeZone? = TimeZone.current,
era: Int? = Date().era,
year: Int? = Date().year,
month: Int? = Date().month,
day: Int? = Date().day,
hour: Int? = Date().hour,
minute: Int? = Date().minute,
second: Int? = Date().second,
nanosecond: Int? = Date().nanosecond) {
var components = DateComponents()
components.calendar = calendar
components.timeZone = timeZone
components.era = era
components.year = year
components.month = month
components.day = day
components.hour = hour
components.minute = minute
components.second = second
components.nanosecond = nanosecond
if let date = calendar?.date(from: components) {
self = date
} else {
return nil
}
}
/// SwifterSwift: Create date object from ISO8601 string.
///
/// - Parameter iso8601String: ISO8601 string of format (yyyy-MM-dd'T'HH:mm:ss.SSSZ).
public init?(iso8601String: String) {
// https://github.com/justinmakaila/NSDate-ISO-8601/blob/master/NSDateISO8601.swift
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let date = dateFormatter.date(from: iso8601String) {
self = date
} else {
return nil
}
}
/// SwifterSwift: Create new date object from UNIX timestamp.
///
/// - Parameter unixTimestamp: UNIX timestamp.
public init(unixTimestamp: Double) {
self.init(timeIntervalSince1970: unixTimestamp)
}
}
| mit |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Stats/Shared Views/TopTotalsCell.swift | 1 | 14601 | import UIKit
/// This cell type displays the top data rows for a Stat type, with optional subtitles for the items and data.
/// Ex: Insights Tags and Categories, Period Post and Pages.
/// If there are more than 6 data rows, a View more row is added to display the full list.
/// If a row is tapped, StatsTotalRowDelegate is informed to display the associated detail.
/// If the row has child rows, those child rows are added to the stack view below the selected row.
///
class TopTotalsCell: StatsBaseCell, NibLoadable {
// MARK: - Properties
@IBOutlet weak var outerStackView: UIStackView!
@IBOutlet weak var subtitleStackView: UIStackView!
@IBOutlet weak var rowsStackView: UIStackView!
@IBOutlet weak var itemSubtitleLabel: UILabel!
@IBOutlet weak var dataSubtitleLabel: UILabel!
@IBOutlet weak var topSeparatorLine: UIView!
@IBOutlet weak var bottomSeparatorLine: UIView!
private var topAccessoryView: UIView? = nil {
didSet {
oldValue?.removeFromSuperview()
if let topAccessoryView = topAccessoryView {
outerStackView.insertArrangedSubview(topAccessoryView, at: 0)
topAccessoryView.layoutMargins = subtitleStackView.layoutMargins
outerStackView.setCustomSpacing(Metrics.topAccessoryViewSpacing, after: topAccessoryView)
}
}
}
private var forDetails = false
private var limitRowsDisplayed = true
private let maxChildRowsToDisplay = 10
fileprivate var dataRows = [StatsTotalRowData]()
private var subtitlesProvided = true
private weak var siteStatsInsightsDelegate: SiteStatsInsightsDelegate?
private weak var siteStatsPeriodDelegate: SiteStatsPeriodDelegate?
private weak var siteStatsReferrerDelegate: SiteStatsReferrerDelegate?
private weak var siteStatsDetailsDelegate: SiteStatsDetailsDelegate?
private weak var postStatsDelegate: PostStatsDelegate?
private typealias Style = WPStyleGuide.Stats
// MARK: - Configure
func configure(itemSubtitle: String? = nil,
dataSubtitle: String? = nil,
dataRows: [StatsTotalRowData],
statSection: StatSection? = nil,
siteStatsInsightsDelegate: SiteStatsInsightsDelegate? = nil,
siteStatsPeriodDelegate: SiteStatsPeriodDelegate? = nil,
siteStatsReferrerDelegate: SiteStatsReferrerDelegate? = nil,
siteStatsDetailsDelegate: SiteStatsDetailsDelegate? = nil,
postStatsDelegate: PostStatsDelegate? = nil,
topAccessoryView: UIView? = nil,
limitRowsDisplayed: Bool = true,
forDetails: Bool = false) {
itemSubtitleLabel.text = itemSubtitle
dataSubtitleLabel.text = dataSubtitle
subtitlesProvided = (itemSubtitle != nil && dataSubtitle != nil)
self.dataRows = dataRows
self.statSection = statSection
self.siteStatsInsightsDelegate = siteStatsInsightsDelegate
self.siteStatsPeriodDelegate = siteStatsPeriodDelegate
self.siteStatsReferrerDelegate = siteStatsReferrerDelegate
self.siteStatsDetailsDelegate = siteStatsDetailsDelegate
self.postStatsDelegate = postStatsDelegate
self.topAccessoryView = topAccessoryView
self.limitRowsDisplayed = limitRowsDisplayed
self.forDetails = forDetails
if !forDetails {
addRows(dataRows,
toStackView: rowsStackView,
forType: siteStatsPeriodDelegate != nil ? .period : .insights,
limitRowsDisplayed: limitRowsDisplayed,
rowDelegate: self,
referrerDelegate: self,
viewMoreDelegate: self)
initChildRows()
}
setSubtitleVisibility()
applyStyles()
prepareForVoiceOver()
}
override func prepareForReuse() {
super.prepareForReuse()
rowsStackView.arrangedSubviews.forEach { subview in
// Remove granchild rows
if let row = subview as? StatsTotalRow {
removeChildRowsForRow(row)
}
// Remove child rows
if let childView = subview as? StatsChildRowsView {
removeRowsFromStackView(childView.rowsStackView)
}
}
removeRowsFromStackView(rowsStackView)
}
private enum Metrics {
static let topAccessoryViewSpacing: CGFloat = 32.0
}
}
// MARK: - Private Extension
private extension TopTotalsCell {
func applyStyles() {
Style.configureCell(self)
Style.configureLabelAsSubtitle(itemSubtitleLabel)
Style.configureLabelAsSubtitle(dataSubtitleLabel)
Style.configureViewAsSeparator(topSeparatorLine)
Style.configureViewAsSeparator(bottomSeparatorLine)
}
/// For Overview tables: Hide the subtitles if there is no data or subtitles.
/// For Details table:
/// - Hide the subtitles if none provided.
/// - Hide the stack view.
///
func setSubtitleVisibility() {
subtitleStackView.layoutIfNeeded()
if forDetails {
bottomSeparatorLine.isHidden = true
updateSubtitleConstraints(showSubtitles: subtitlesProvided)
return
}
updateSubtitleConstraints(showSubtitles: !dataRows.isEmpty && subtitlesProvided)
}
private func updateSubtitleConstraints(showSubtitles: Bool) {
if showSubtitles {
subtitleStackView.isHidden = false
} else {
subtitleStackView.isHidden = true
}
}
// MARK: - Child Row Handling
func initChildRows() {
rowsStackView.arrangedSubviews.forEach { subview in
guard let row = subview as? StatsTotalRow else {
return
}
// On the Stats Detail view, do not expand rows initially.
guard siteStatsDetailsDelegate == nil else {
row.expanded = false
return
}
toggleChildRows(for: row, didSelectRow: false)
row.childRowsView?.rowsStackView.arrangedSubviews.forEach { child in
guard let childRow = child as? StatsTotalRow else {
return
}
toggleChildRows(for: childRow, didSelectRow: false)
}
}
}
func addChildRowsForRow(_ row: StatsTotalRow) {
guard let rowIndex = indexForRow(row),
let childRows = row.rowData?.childRows else {
return
}
// Make sure we don't duplicate child rows.
removeChildRowsForRow(row)
// Add child rows to their own stack view,
// store that on the row (for possible removal later),
// and add the child view to the row stack view.
let numberOfRowsToAdd: Int = {
// If this is on Post Stats, don't limit the number of child rows
// as it needs to show a year's worth of data.
if postStatsDelegate != nil {
return childRows.count
}
return childRows.count > maxChildRowsToDisplay ? maxChildRowsToDisplay : childRows.count
}()
let containingStackView = stackViewContainingRow(row)
let childRowsView = StatsChildRowsView.loadFromNib()
for childRowsIndex in 0..<numberOfRowsToAdd {
let childRowData = childRows[childRowsIndex]
let childRow = StatsTotalRow.loadFromNib()
childRow.configure(rowData: childRowData, delegate: self, parentRow: row)
childRow.showSeparator = false
// If this child is just a child, then change the label color.
// If this child is also a parent, then leave the color as default.
if !childRow.hasChildRows {
Style.configureLabelAsChildRowTitle(childRow.itemLabel)
}
childRowsView.rowsStackView.addArrangedSubview(childRow)
}
row.childRowsView = childRowsView
containingStackView?.insertArrangedSubview(childRowsView, at: rowIndex + 1)
}
func removeChildRowsForRow(_ row: StatsTotalRow) {
guard let childRowsView = row.childRowsView,
let childRowsStackView = childRowsView.rowsStackView else {
return
}
// If the row's children have children, remove those too.
childRowsStackView.arrangedSubviews.forEach { subView in
if let subView = subView as? StatsChildRowsView {
removeRowsFromStackView(subView.rowsStackView)
}
}
removeRowsFromStackView(childRowsStackView)
stackViewContainingRow(row)?.removeArrangedSubview(childRowsView)
}
func toggleSeparatorsAroundRow(_ row: StatsTotalRow) {
toggleSeparatorsBeforeRow(row)
toggleSeparatorsAfterRow(row)
}
func toggleSeparatorsBeforeRow(_ row: StatsTotalRow) {
guard let containingStackView = stackViewContainingRow(row),
let rowIndex = indexForRow(row),
(rowIndex - 1) >= 0 else {
return
}
let previousRow = containingStackView.arrangedSubviews[rowIndex - 1]
// Toggle the indented separator line only on top level rows. Children don't show them.
if previousRow is StatsTotalRow && containingStackView == rowsStackView {
(previousRow as! StatsTotalRow).showSeparator = !row.expanded
}
// Toggle the bottom line on the previous stack view
if previousRow is StatsChildRowsView {
(previousRow as! StatsChildRowsView).showBottomSeperatorLine = !row.expanded
}
}
func toggleSeparatorsAfterRow(_ row: StatsTotalRow) {
guard let containingStackView = stackViewContainingRow(row),
let rowIndex = indexForRow(row),
(rowIndex + 1) < containingStackView.arrangedSubviews.count else {
return
}
let nextRow = containingStackView.arrangedSubviews[rowIndex + 1]
// Toggle the indented separator line only on top level rows. Children don't show them.
if nextRow is StatsTotalRow && containingStackView == rowsStackView {
row.showSeparator = !(nextRow as! StatsTotalRow).expanded
}
// If the next row is a stack view, it is the children of this row.
// Proceed to the next parent row, and toggle this row's bottom line
// according to the next parent's expanded state.
if nextRow is StatsChildRowsView {
guard (rowIndex + 2) < containingStackView.arrangedSubviews.count,
let nextParentRow = containingStackView.arrangedSubviews[rowIndex + 2] as? StatsTotalRow else {
return
}
row.childRowsView?.showBottomSeperatorLine = !nextParentRow.expanded
}
}
func indexForRow(_ row: StatsTotalRow) -> Int? {
guard let stackView = stackViewContainingRow(row),
let rowView = stackView.arrangedSubviews.first(where: ({ $0 == row })),
let rowIndex = stackView.arrangedSubviews.firstIndex(of: rowView) else {
return nil
}
return rowIndex
}
func stackViewContainingRow(_ row: StatsTotalRow) -> UIStackView? {
return row.parentRow?.childRowsView?.rowsStackView ?? rowsStackView
}
}
// MARK: - StatsTotalRowDelegate
extension TopTotalsCell: StatsTotalRowDelegate {
func displayWebViewWithURL(_ url: URL) {
siteStatsInsightsDelegate?.displayWebViewWithURL?(url)
siteStatsPeriodDelegate?.displayWebViewWithURL?(url)
siteStatsDetailsDelegate?.displayWebViewWithURL?(url)
}
func displayMediaWithID(_ mediaID: NSNumber) {
siteStatsPeriodDelegate?.displayMediaWithID?(mediaID)
siteStatsDetailsDelegate?.displayMediaWithID?(mediaID)
}
func toggleChildRows(for row: StatsTotalRow, didSelectRow: Bool) {
row.expanded ? addChildRowsForRow(row) : removeChildRowsForRow(row)
toggleSeparatorsAroundRow(row)
siteStatsInsightsDelegate?.expandedRowUpdated?(row, didSelectRow: didSelectRow)
siteStatsPeriodDelegate?.expandedRowUpdated?(row, didSelectRow: didSelectRow)
postStatsDelegate?.expandedRowUpdated?(row, didSelectRow: didSelectRow)
}
func showPostStats(postID: Int, postTitle: String?, postURL: URL?) {
siteStatsPeriodDelegate?.showPostStats?(postID: postID, postTitle: postTitle, postURL: postURL)
siteStatsDetailsDelegate?.showPostStats?(postID: postID, postTitle: postTitle, postURL: postURL)
}
func showAddInsight() {
siteStatsInsightsDelegate?.showAddInsight?()
}
}
// MARK: - StatsTotalRowReferrerDelegate
extension TopTotalsCell: StatsTotalRowReferrerDelegate {
func showReferrerDetails(_ data: StatsTotalRowData) {
siteStatsReferrerDelegate?.showReferrerDetails(data)
}
}
// MARK: - ViewMoreRowDelegate
extension TopTotalsCell: ViewMoreRowDelegate {
func viewMoreSelectedForStatSection(_ statSection: StatSection) {
siteStatsInsightsDelegate?.viewMoreSelectedForStatSection?(statSection)
siteStatsPeriodDelegate?.viewMoreSelectedForStatSection?(statSection)
postStatsDelegate?.viewMoreSelectedForStatSection?(statSection)
}
}
// MARK: - Accessibility
extension TopTotalsCell: Accessible {
func prepareForVoiceOver() {
accessibilityTraits = .summaryElement
guard dataRows.count > 0 else {
return
}
let itemTitle = itemSubtitleLabel.text
let dataTitle = dataSubtitleLabel.text
if let itemTitle = itemTitle, let dataTitle = dataTitle {
let descriptionFormat = NSLocalizedString("Table showing %@ and %@", comment: "Accessibility of stats table. Placeholders will be populated with names of data shown in table.")
accessibilityLabel = String(format: descriptionFormat, itemTitle, dataTitle)
} else {
if let title = (itemTitle ?? dataTitle) {
let descriptionFormat = NSLocalizedString("Table showing %@", comment: "Accessibility of stats table. Placeholder will be populated with name of data shown in table.")
accessibilityLabel = String(format: descriptionFormat, title)
}
}
if let sectionTitle = statSection?.title {
accessibilityLabel = "\(sectionTitle). \(accessibilityLabel ?? "")"
}
}
}
| gpl-2.0 |
TheDarkCode/Example-Swift-Apps | Exercises and Basic Principles/azure-search-basics/azure-search-basics/AZSViewController.swift | 1 | 391 | //
// AZSViewController.swift
// azure-search-basics
//
// Created by Mark Hamilton on 3/14/16.
// Copyright © 2016 dryverless. All rights reserved.
//
import UIKit
class AZSViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit |
diejmon/KanbanizeAPI | Sources/LogTime.swift | 1 | 2245 |
import Foundation
public extension Client.RequestBuilder {
public func logTime(_ loggedTime: LoggedTime,
taskID: TaskID,
description: Description? = nil) throws -> URLRequest {
guard let credentials = self.credentials else { throw Client.Error.notLoggedIn }
let request = URLRequest.create(subdomain: subdomain,
credentials: credentials,
function: .logTime,
params: [loggedTime, taskID])
return request
}
}
public extension Client {
public func logTime(_ loggedTime: LoggedTime,
taskID: TaskID,
description: Description? = nil,
completion: @escaping (Result<LogTimeResult, ClientError>) -> Void) throws
{
let request = try requestBuilder().logTime(loggedTime, taskID: taskID, description: description)
execute(request, completion: completion)
}
public struct LogTimeResult {
public let id: String
public let taskID: TaskID
public let author: String
public let details: String
public let loggedTime: LoggedTime
public let isSubTask: Bool
public let title: String
public let comment: String
public let originData: Date
}
}
extension Client.LogTimeResult: APIResult {
public init?(jsonObject: AnyObject) {
guard let json = jsonObject as? Dictionary<String, AnyObject> else { return nil }
guard let
id = json["id"] as? String,
let taskID = json["taskid"] as? String,
let author = json["author"] as? String,
let details = json["details"] as? String,
let loggedTime = json["loggedtime"] as? Double,
let isSubTask = json["issubtask"] as? Bool,
let title = json["title"] as? String,
let comment = json["comment"] as? String//,
// originData = json["origindate"] as? String
else { return nil }
self.id = id
self.taskID = TaskID(taskID)
self.author = author
self.details = details
self.loggedTime = LoggedTime(hours: loggedTime)
self.isSubTask = isSubTask
self.title = title
self.comment = comment
self.originData = Date()//TODO: parse date
}
}
| mit |
andela-jejezie/FlutterwavePaymentManager | Rave/Rave/FWHelperAndConstant/FWConstant.swift | 1 | 9163 | //
// Constant.swift
// flutterwave
//
// Created by Johnson Ejezie on 09/12/2016.
// Copyright © 2016 johnsonejezie. All rights reserved.
//
import Foundation
import UIKit
internal struct FWConstants {
internal struct Text {
static let AccountNumberTextFieldPlaceholder = "Account Number"
static let CardNumberTextFieldPlaceholder = "Card Number"
static let ExpiryDateTextFieldPlaceholder = "MM/YY"
static let CVVTextFieldPlaceholder = "CVV"
static let SegmentControlFirstIndexText = "CARD"
static let SegmentControlSecondIndexText = "ACCOUNT"
static let UserTokenTextFieldPlaceholder = "TOKEN"
}
internal struct ImageNamed {
static let CardBlack = "generic-card"
static let Cancel = "cancel"
static let BankWhite = "bankWhite"
static let BankBlack = "bankBlack"
static let DropDown = "dropdown"
static let Visa = "visa-card"
static let MasterCard = "mastercard"
}
internal struct Color {
static let BorderColor = UIColor.lightGray
static let SegmentControlTintColor = UIColor(red: 55/255.0, green: 46/255.0, blue: 76/255.0, alpha: 1)
static let flutterGreenColor = UIColor(red: 22/255.0, green: 156/255.0, blue: 129/255.0, alpha: 1)
static let ErrorColor = UIColor(red: 192/255.0, green: 57/255.0, blue: 43/255.0, alpha: 1)
}
static let CountryCode = Locale.current.regionCode
static let Ipify = "https://api.ipify.org?format=json"
static let PayEndPoint = "http://flw-pms-dev.eu-west-1.elasticbeanstalk.com/flwv3-pug/getpaidx/api/charge"
static let BaseURL = "http://flw-pms-dev.eu-west-1.elasticbeanstalk.com/"
static let ValidateAccountCharge = "http://flw-pms-dev.eu-west-1.elasticbeanstalk.com/flwv3-pug/getpaidx/api/validate"
internal static let otpOptions:[String] = ["Select OTP option","Hardware Token", "USSD"]
internal static var banks = [Bank]()
internal static var listOfBankNames = [String]()
static let countries = [
"NG": "Nigeria",
"AF": "Afghanistan",
"AX": "Åland Islands",
"AL": "Albania",
"DZ": "Algeria",
"AS": "American Samoa",
"AD": "Andorra",
"AO": "Angola",
"AI": "Anguilla",
"AQ": "Antarctica",
"AG": "Antigua and Barbuda",
"AR": "Argentina",
"AM": "Armenia",
"AW": "Aruba",
"AU": "Australia",
"AT": "Austria",
"AZ": "Azerbaijan",
"BS": "Bahamas",
"BH": "Bahrain",
"BD": "Bangladesh",
"BB": "Barbados",
"BY": "Belarus",
"BE": "Belgium",
"BZ": "Belize",
"BJ": "Benin",
"BM": "Bermuda",
"BT": "Bhutan",
"BO": "Bolivia",
"BA": "Bosnia and Herzegovina",
"BW": "Botswana",
"BV": "Bouvet Island",
"BR": "Brazil",
"IO": "British Indian Ocean Territory",
"BN": "Brunei Darussalam",
"BG": "Bulgaria",
"BF": "Burkina Faso",
"BI": "Burundi",
"KH": "Cambodia",
"CM": "Cameroon",
"CA": "Canada",
"CV": "Cape Verde",
"KY": "Cayman Islands",
"CF": "Central African Republic",
"TD": "Chad",
"CL": "Chile",
"CN": "China",
"CX": "Christmas Island",
"CC": "Cocos (Keeling) Islands",
"CO": "Colombia",
"KM": "Comoros",
"CG": "Congo",
"CD": "Congo, The Democratic Republic of the",
"CK": "Cook Islands",
"CR": "Costa Rica",
"CI": "Cote D'Ivoire",
"HR": "Croatia",
"CU": "Cuba",
"CY": "Cyprus",
"CZ": "Czech Republic",
"DK": "Denmark",
"DJ": "Djibouti",
"DM": "Dominica",
"DO": "Dominican Republic",
"EC": "Ecuador",
"EG": "Egypt",
"SV": "El Salvador",
"GQ": "Equatorial Guinea",
"ER": "Eritrea",
"EE": "Estonia",
"ET": "Ethiopia",
"FK": "Falkland Islands (Malvinas)",
"FO": "Faroe Islands",
"FJ": "Fiji",
"FI": "Finland",
"FR": "France",
"GF": "French Guiana",
"PF": "French Polynesia",
"TF": "French Southern Territories",
"GA": "Gabon",
"GM": "Gambia",
"GE": "Georgia",
"DE": "Germany",
"GH": "Ghana",
"GI": "Gibraltar",
"GR": "Greece",
"GL": "Greenland",
"GD": "Grenada",
"GP": "Guadeloupe",
"GU": "Guam",
"GT": "Guatemala",
"GG": "Guernsey",
"GN": "Guinea",
"GW": "Guinea-Bissau",
"GY": "Guyana",
"HT": "Haiti",
"HM": "Heard Island and Mcdonald Islands",
"VA": "Holy See (Vatican City State)",
"HN": "Honduras",
"HK": "Hong Kong",
"HU": "Hungary",
"IS": "Iceland",
"IN": "India",
"ID": "Indonesia",
"IR": "Iran, Islamic Republic Of",
"IQ": "Iraq",
"IE": "Ireland",
"IM": "Isle of Man",
"IL": "Israel",
"IT": "Italy",
"JM": "Jamaica",
"JP": "Japan",
"JE": "Jersey",
"JO": "Jordan",
"KZ": "Kazakhstan",
"KE": "Kenya",
"KI": "Kiribati",
"KP": "Democratic People's Republic of Korea",
"KR": "Korea, Republic of",
"XK": "Kosovo",
"KW": "Kuwait",
"KG": "Kyrgyzstan",
"LA": "Lao People's Democratic Republic",
"LV": "Latvia",
"LB": "Lebanon",
"LS": "Lesotho",
"LR": "Liberia",
"LY": "Libyan Arab Jamahiriya",
"LI": "Liechtenstein",
"LT": "Lithuania",
"LU": "Luxembourg",
"MO": "Macao",
"MK": "Macedonia, The Former Yugoslav Republic of",
"MG": "Madagascar",
"MW": "Malawi",
"MY": "Malaysia",
"MV": "Maldives",
"ML": "Mali",
"MT": "Malta",
"MH": "Marshall Islands",
"MQ": "Martinique",
"MR": "Mauritania",
"MU": "Mauritius",
"YT": "Mayotte",
"MX": "Mexico",
"FM": "Micronesia, Federated States of",
"MD": "Moldova, Republic of",
"MC": "Monaco",
"MN": "Mongolia",
"ME": "Montenegro",
"MS": "Montserrat",
"MA": "Morocco",
"MZ": "Mozambique",
"MM": "Myanmar",
"NA": "Namibia",
"NR": "Nauru",
"NP": "Nepal",
"NL": "Netherlands",
"AN": "Netherlands Antilles",
"NC": "New Caledonia",
"NZ": "New Zealand",
"NI": "Nicaragua",
"NE": "Niger",
"NU": "Niue",
"NF": "Norfolk Island",
"MP": "Northern Mariana Islands",
"NO": "Norway",
"OM": "Oman",
"PK": "Pakistan",
"PW": "Palau",
"PS": "Palestinian Territory, Occupied",
"PA": "Panama",
"PG": "Papua New Guinea",
"PY": "Paraguay",
"PE": "Peru",
"PH": "Philippines",
"PN": "Pitcairn",
"PL": "Poland",
"PT": "Portugal",
"PR": "Puerto Rico",
"QA": "Qatar",
"RE": "Reunion",
"RO": "Romania",
"RU": "Russian Federation",
"RW": "Rwanda",
"SH": "Saint Helena",
"KN": "Saint Kitts and Nevis",
"LC": "Saint Lucia",
"PM": "Saint Pierre and Miquelon",
"VC": "Saint Vincent and the Grenadines",
"WS": "Samoa",
"SM": "San Marino",
"ST": "Sao Tome and Principe",
"SA": "Saudi Arabia",
"SN": "Senegal",
"RS": "Serbia",
"SC": "Seychelles",
"SL": "Sierra Leone",
"SG": "Singapore",
"SK": "Slovakia",
"SI": "Slovenia",
"SB": "Solomon Islands",
"SO": "Somalia",
"ZA": "South Africa",
"GS": "South Georgia and the South Sandwich Islands",
"ES": "Spain",
"LK": "Sri Lanka",
"SD": "Sudan",
"SR": "Suriname",
"SJ": "Svalbard and Jan Mayen",
"SZ": "Swaziland",
"SE": "Sweden",
"CH": "Switzerland",
"SY": "Syrian Arab Republic",
"TW": "Taiwan",
"TJ": "Tajikistan",
"TZ": "Tanzania, United Republic of",
"TH": "Thailand",
"TL": "Timor-Leste",
"TG": "Togo",
"TK": "Tokelau",
"TO": "Tonga",
"TT": "Trinidad and Tobago",
"TN": "Tunisia",
"TR": "Turkey",
"TM": "Turkmenistan",
"TC": "Turks and Caicos Islands",
"TV": "Tuvalu",
"UG": "Uganda",
"UA": "Ukraine",
"AE": "United Arab Emirates",
"GB": "United Kingdom",
"US": "United States",
"UM": "United States Minor Outlying Islands",
"UY": "Uruguay",
"UZ": "Uzbekistan",
"VU": "Vanuatu",
"VE": "Venezuela",
"VN": "Viet Nam",
"VG": "Virgin Islands, British",
"VI": "Virgin Islands, U.S.",
"WF": "Wallis and Futuna",
"EH": "Western Sahara",
"YE": "Yemen",
"ZM": "Zambia",
"ZW": "Zimbabwe"
]
}
| mit |
baic989/iPhone-ANN | ANN/Modules/Drawing/DrawingInterfaces.swift | 2 | 923 | //
// DrawingInterfaces.swift
// ANN
//
// Created by user125215 on 3/26/17.
// Copyright © 2017 Hrvoje Baic. All rights reserved.
//
import UIKit
enum DrawingNavigationOption {
case back
}
protocol DrawingWireframeInterface: WireframeInterface {
func navigate(to option: DrawingNavigationOption)
}
protocol DrawingViewInterface: ViewInterface {
var trainButton: UIButton { get set }
var characterPickerView: UIPickerView { get set }
func processImage()
func classifyImage()
}
protocol DrawingPresenterInterface: PresenterInterface {
var navigationOption: MainMenuNavigationOption { get set }
func okButtonPressed()
func didPressBackButton()
func pixelize(image: UIImage) -> [Int]
func updated(characterBox: CGRect, minX: CGFloat?, maxX: CGFloat?, minY: CGFloat?, maxY: CGFloat?) -> CGRect
}
protocol DrawingInteractorInterface: InteractorInterface {
}
| mit |
lyptt/xcodegen | spec/integration/support_files/xcodeproj_writer_test_embedding/app/AppDelegate.swift | 9 | 381 | //
// AppDelegate.swift
// iOSTest
//
// Created by Rhys Cox on 02/12/2016.
// Copyright © 2016 Rhys Cox. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func applicationDidFinishLaunching(_ application: UIApplication) {
print("Application did finish launching")
}
}
| mit |
IBM-Swift/Kitura | Sources/Kitura/HTTPStatusCode.swift | 1 | 1015 | /*
* Copyright IBM Corporation 2018
*
* 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 KituraNet
/// A dummy class to get the documentation for the HTTPStatusCode below to be emitted.
private class DummyHTTPStatusCodeClass {}
/// Bridge [HTTPStatusCode](http://ibm-swift.github.io/Kitura-net/Enums/HTTPStatusCode.html)
/// from [KituraNet](http://ibm-swift.github.io/Kitura-net) so that you only need to import
/// `Kitura` to access it.
public typealias HTTPStatusCode = KituraNet.HTTPStatusCode
| apache-2.0 |
joerocca/GitHawk | Classes/Issues/Labeled/IssueLabeledSectionController.swift | 1 | 1176 | //
// IssueLabeledSectionController.swift
// Freetime
//
// Created by Ryan Nystrom on 6/6/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
import IGListKit
final class IssueLabeledSectionController: ListGenericSectionController<IssueLabeledModel> {
private let issueModel: IssueDetailsModel
init(issueModel: IssueDetailsModel) {
self.issueModel = issueModel
super.init()
}
override func sizeForItem(at index: Int) -> CGSize {
guard let width = collectionContext?.containerSize.width else { fatalError("Collection context must be set") }
return CGSize(width: width, height: object?.attributedString.textViewSize(width).height ?? 0)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
guard let cell = collectionContext?.dequeueReusableCell(of: IssueLabeledCell.self, for: self, at: index) as? IssueLabeledCell,
let object = self.object
else { fatalError("Missing collection context, cell incorrect type, or object missing") }
cell.configure(object)
cell.delegate = viewController
return cell
}
}
| mit |
seanwoodward/IBAnimatable | IBAnimatable/CALayerExtension.swift | 1 | 411 | //
// Created by Jake Lin on 2/23/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import UIKit
public extension CALayer {
class func animate(animation: AnimatableExecution, completion: AnimatableCompletion? = nil) {
CATransaction.begin()
if let completion = completion {
CATransaction.setCompletionBlock { completion() }
}
animation()
CATransaction.commit()
}
}
| mit |
icharny/CommonUtils | CommonUtils/DictionaryExtensions.swift | 1 | 1418 | public extension Dictionary {
func deepMap<nK: Hashable, nV>(keyMap: ((Key) -> nK)? = nil, valueMap: ((Value) -> nV)? = nil) -> [nK: nV] {
var newDict = [nK: nV]()
forEach { k, v in
let newKey: nK = keyMap?(k) ?? (k as! nK)
let newValue: nV = valueMap?(v) ?? (v as! nV)
newDict[newKey] = newValue
}
return newDict
}
func appending(newDict: [Key: Value]) -> [Key: Value] {
var combinedDict = self
newDict.forEach { k, v in
combinedDict[k] = v
}
return combinedDict
}
func filterToDictionary(includeElement: (Dictionary.Iterator.Element) throws -> Bool) rethrows -> [Key: Value] {
var ret = [Key: Value]()
if let tuples = try? filter(includeElement) {
tuples.forEach { k, v in
ret[k] = v
}
}
return ret
}
// NOTE: NOT COMMUTATIVE
// i.e. dict1 + dict2 != dict2 + dict1
// specifically, for common keys, rhs will overwrite lhs
static func + (lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] {
var newDict: [Key: Value] = [:]
lhs.forEach { newDict[$0.key] = $0.value }
rhs.forEach { newDict[$0.key] = $0.value }
return newDict
}
static func += (lhs: inout [Key: Value], rhs: [Key: Value]) {
rhs.forEach { lhs[$0.key] = $0.value }
}
}
| mit |
bwearley/NVActivityIndicatorView | NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationCubeTransition.swift | 1 | 3134 | //
// NVActivityIndicatorAnimationCubeTransition.swift
// NVActivityIndicatorViewDemo
//
// Created by Nguyen Vinh on 7/24/15.
// Copyright (c) 2015 Nguyen Vinh. All rights reserved.
//
import UIKit
class NVActivityIndicatorAnimationCubeTransition: NVActivityIndicatorAnimationDelegate {
func setUpAnimationInLayer(layer: CALayer, size: CGSize, color: UIColor) {
let squareSize = size.width / 5
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let deltaX = size.width - squareSize
let deltaY = size.height - squareSize
let duration: CFTimeInterval = 1.6
let beginTime = CACurrentMediaTime()
let beginTimes: [CFTimeInterval] = [0, -0.8]
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.25, 0.5, 0.75, 1]
scaleAnimation.timingFunctions = [timingFunction, timingFunction, timingFunction, timingFunction]
scaleAnimation.values = [1, 0.5, 1, 0.5, 1]
scaleAnimation.duration = duration
// Translate animation
let translateAnimation = CAKeyframeAnimation(keyPath: "transform.translation")
translateAnimation.keyTimes = scaleAnimation.keyTimes
translateAnimation.timingFunctions = scaleAnimation.timingFunctions
translateAnimation.values = [
NSValue(CGSize: CGSize(width: 0, height: 0)),
NSValue(CGSize: CGSize(width: deltaX, height: 0)),
NSValue(CGSize: CGSize(width: deltaX, height: deltaY)),
NSValue(CGSize: CGSize(width: 0, height: deltaY)),
NSValue(CGSize: CGSize(width: 0, height: 0))
]
translateAnimation.duration = duration
// Rotate animation
let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotateAnimation.keyTimes = scaleAnimation.keyTimes
rotateAnimation.timingFunctions = scaleAnimation.timingFunctions
rotateAnimation.values = [0, CGFloat(-M_PI_2), CGFloat(-M_PI), CGFloat(-1.5 * M_PI), CGFloat(-2 * M_PI)]
rotateAnimation.duration = duration
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, translateAnimation, rotateAnimation]
animation.duration = duration
animation.repeatCount = HUGE
animation.removedOnCompletion = false
// Draw squares
for i in 0..<2 {
let square = NVActivityIndicatorShape.Rectangle.createLayerWith(size: CGSize(width: squareSize, height: squareSize), color: color)
let frame = CGRect(x: x, y: y, width: squareSize, height: squareSize)
animation.beginTime = beginTime + beginTimes[i]
square.frame = frame
square.addAnimation(animation, forKey: "animation")
layer.addSublayer(square)
}
}
}
| mit |
codwam/LHDropDownTextField | Example/Tests/Tests.swift | 1 | 769 | import UIKit
import XCTest
import LHDropDownTextField
class Tests: 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.measure() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
4jchc/4jchc-BaiSiBuDeJie | 4jchc-BaiSiBuDeJie/4jchc-BaiSiBuDeJie/Class/Tool/UIImage+Extension.swift | 1 | 1860 | //
// UIImage+Extension.swift
// 4jchc-BaiSiBuDeJie
//
// Created by 蒋进 on 16/3/3.
// Copyright © 2016年 蒋进. All rights reserved.
//
import Foundation
import UIKit
extension UIImage {
//MARK: 根据网络图片的地址下载图片并且返回圆形的剪裁图片
/// 根据网络图片的地址下载图片并且返回圆形的剪裁图片
class func circleImageWithImageURL(image_url:String)->UIImage?{
//下载网络图片
let data = NSData(contentsOfURL: NSURL(string: image_url)!)
let olderImage = UIImage(data: data!)
//开启图片上下文
let contextW = olderImage?.size.width
let contextH = olderImage?.size.height
UIGraphicsBeginImageContextWithOptions(CGSizeMake(contextW!,contextH! ), false, 0.0);
//画小圆
let ctx=UIGraphicsGetCurrentContext()
CGContextAddEllipseInRect(ctx, CGRect(x: 0, y: 0, width: contextW!, height: contextH!))
CGContextClip(ctx)
olderImage?.drawInRect(CGRect(x: 0, y: 0, width: contextW!, height: contextH!))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
func circleImage()->UIImage{
// NO代表透明
UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0);
// 获得上下文
let ctx = UIGraphicsGetCurrentContext()
// 添加一个圆
let rect:CGRect = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextAddEllipseInRect(ctx, rect);
// 裁剪
CGContextClip(ctx);
// 将图片画上去
self.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage;
}
}
| apache-2.0 |
yoonapps/QPXExpressWrapper | QPXExpressWrapper/Classes/TripsDataTax.swift | 1 | 734 | //
// TripsDataTax.swift
// Flights
//
// Created by Kyle Yoon on 3/5/16.
// Copyright © 2016 Kyle Yoon. All rights reserved.
//
import Foundation
import Gloss
public struct TripsDataTax: Decodable {
public let kind: String?
public let code: String?
public let name: String?
public init?(json: JSON) {
guard let kind: String = "kind" <~~ json else {
return nil
}
self.kind = kind
self.code = "code" <~~ json
self.name = "name" <~~ json
}
}
extension TripsDataTax: Equatable {}
public func ==(lhs: TripsDataTax, rhs: TripsDataTax) -> Bool {
return lhs.kind == rhs.kind &&
lhs.code == rhs.code &&
lhs.name == rhs.name
}
| mit |
ViewModelKit/ViewModelKit | Example/Example/SimpleViewController.swift | 1 | 1097 | //
// SimpleViewController.swift
// ViewModelKit
//
// Created by Tongtong Xu on 16/2/21.
// Copyright © 2016年 Tongtong Xu. All rights reserved.
//
import Foundation
import UIKit
import ViewModelKit
class SimpleViewController: BaseViewController, BaseControllerTypeAddition {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var errorMessageLabel: UILabel!
typealias T = SimpleViewModel
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.text = viewModel.nameTitle
NSNotificationCenter.defaultCenter().addObserverForName(UITextFieldTextDidChangeNotification, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: { [weak self] in
guard let textField = $0.object as? UITextField where textField == self?.nameTextField else { return }
self?.viewModel.name = textField.text ?? ""
})
viewModel.validClosure = { [weak self] in
self?.errorMessageLabel.text = $0
}
}
}
| mit |
therealbnut/ProtocolTesting | ProtocolTestingTests/ProtocolTestingTests.swift | 1 | 1898 | //
// ProtocolTestingTests.swift
// ProtocolTestingTests
//
// Created by Andrew Bennett on 22/02/2016.
// Copyright © 2016 TeamBnut. All rights reserved.
//
import XCTest
@testable import ProtocolTesting
class ProtocolTestingTests: 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.
let summary = DebugTestReporter(fromReports: [
(context: ["a"], status: .Success),
(context: ["a", "a", "a"], status: .Failure(file: "file.swift", line: 120, reason: "it just did")),
(context: ["a", "a", "b"], status: .Failure(file: "file.swift", line: 123, reason: "it also just did")),
(context: ["a", "a", "c"], status: .Failure(file: "file.swift", line: 128, reason: "it also just did, as well")),
(context: ["a", "a", "d"], status: .Success),
(context: ["a", "a", "e"], status: .Success),
(context: ["a", "a", "f"], status: .Success),
(context: ["a", "b", "a"], status: .Success),
(context: ["a", "b", "b"], status: .Success),
(context: ["a", "c"], status: .Success),
(context: ["b", "a"], status: .Success),
])
print(summary)
}
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 |
ymkim50/MFImageSlider | Example/MFImageSlider/AppDelegate.swift | 1 | 2181 | //
// AppDelegate.swift
// MFImageSlider
//
// Created by Youngmin Kim on 12/19/2016.
// Copyright (c) 2016 Youngmin Kim. 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 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 |
steelwheels/KiwiScript | KiwiEngine/UnitTest/UnitTestExec/UTResource.swift | 1 | 174 | //
// UTResource.swift
// UnitTestExec
//
// Created by Tomoo Hamada on 2019/09/21.
// Copyright © 2019 Steel Wheels Project. All rights reserved.
//
import Foundation
| lgpl-2.1 |
steelwheels/KiwiScript | KiwiShell/Test/Shell/UTScript.swift | 1 | 1496 | /**
* @file UTScript.swift
* @brief Test function for KHScriptThread class
* @par Copyright
* Copyright (C) 2020 Steel Wheels Project
*/
import KiwiShell
import KiwiLibrary
import KiwiEngine
import CoconutData
import CoconutShell
import JavaScriptCore
import Foundation
public func UTScript(input inhdl: FileHandle, output outhdl: FileHandle, error errhdl: FileHandle, console cons: CNConsole) -> Bool
{
var result = true
let instrm : CNFileStream = .fileHandle(inhdl)
let outstrm : CNFileStream = .fileHandle(outhdl)
let errstrm : CNFileStream = .fileHandle(errhdl)
let script: String = "for(let i=0; i<1000000 ; i ++) { sleep(0.1) ; } "
let procmgr = CNProcessManager()
let env = CNEnvironment()
let config = KHConfig(applicationType: .terminal, hasMainFunction: false, doStrict: true, logLevel: .warning)
let thread = KHScriptThreadObject(sourceFile: .script(script), processManager: procmgr, input: instrm, output: outstrm, error: errstrm, externalCompiler: nil, environment: env, config: config)
/* Execute the thread */
thread.start(argument: .nullValue)
/* Check status */
Thread.sleep(forTimeInterval: 1.0)
if !thread.isRunning {
cons.print(string: "Thread is NOT running\n")
result = false
}
/* Terminate */
thread.terminate()
/* Check status */
Thread.sleep(forTimeInterval: 0.5)
if thread.isRunning {
cons.print(string: "Thread is still running\n")
result = false
}
cons.print(string: "UTScript ... done\n")
return result
}
| lgpl-2.1 |
laszlokorte/reform-swift | ReformStage/ReformStage/RuntimeStageCollector.swift | 1 | 4564 | //
// RuntimeStageCollector.swift
// ReformStage
//
// Created by Laszlo Korte on 17.08.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
import ReformMath
import ReformCore
final public class StageCollector<A:Analyzer> : RuntimeListener {
private let stage : Stage
private let analyzer : A
private let focusFilter : (Evaluatable) -> Bool
private var collected : Bool = false
private let buffer = StageBuffer()
public init(stage: Stage, analyzer: A, focusFilter: @escaping (Evaluatable) -> Bool) {
self.stage = stage
self.analyzer = analyzer
self.focusFilter = focusFilter
}
public func runtimeBeginEvaluation<R:Runtime>(_ runtime: R, withSize size: (Double, Double)) {
collected = false
buffer.clear()
buffer.size = Vec2d(x: Double(size.0), y: Double(size.1))
}
public func runtimeFinishEvaluation<R:Runtime>(_ runtime: R) {
buffer.flush(stage)
}
public func runtime<R:Runtime>(_ runtime: R, didEval instruction: Evaluatable) {
guard !collected else { return }
guard focusFilter(instruction) else { return }
defer { collected = true }
for id in runtime.getForms() {
guard let entity = entityForRuntimeForm(analyzer, runtime: runtime, formId: id) else { continue }
buffer.entities.append(entity)
guard let drawable = runtime.get(id) as? Drawable, drawable.drawingMode == .draw else {
continue
}
guard let shape = drawable.getShapeFor(runtime) else {
continue
}
let idShape = IdentifiedShape(id: id, shape: shape)
buffer.currentShapes.append(idShape)
}
}
public func runtime<R:Runtime>(_ runtime: R, exitScopeWithForms forms: [FormIdentifier]) {
for id in forms {
guard let form = runtime.get(id) as? Drawable, form.drawingMode == .draw else {
continue
}
guard let shape = form.getShapeFor(runtime) else {
continue
}
let idShape = IdentifiedShape(id: id, shape: shape)
if !collected {
buffer.currentShapes.append(idShape)
}
buffer.finalShapes.append(idShape)
}
}
public func runtime<R:Runtime>(_ runtime: R, triggeredError: RuntimeError, on instruction: Evaluatable) {
guard !collected else { return }
guard focusFilter(instruction) else { return }
buffer.error = triggeredError
}
public var recalcIntersections : Bool {
set(b) { buffer.recalcIntersections = b }
get { return buffer.recalcIntersections }
}
}
private class StageBuffer {
var recalcIntersections = true
var size : Vec2d = Vec2d()
var entities : [Entity] = []
var error : RuntimeError?
var currentShapes : [IdentifiedShape] = []
var finalShapes : [IdentifiedShape] = []
func clear() {
entities.removeAll(keepingCapacity: true)
currentShapes.removeAll(keepingCapacity: true)
finalShapes.removeAll(keepingCapacity: true)
size = Vec2d()
error = nil
}
func flush(_ stage: Stage) {
let recalcIntersections = self.recalcIntersections
DispatchQueue.main.sync {
[unowned self, stage] in
stage.size = self.size
stage.entities = self.entities.lazy.reversed()
stage.currentShapes = self.currentShapes
stage.finalShapes = self.finalShapes
stage.error = self.error
if recalcIntersections {
stage.intersections = intersectionsOf(self.entities)
self.recalcIntersections = false
}
}
}
}
func intersectionsOf(_ entities: [Entity]) -> [IntersectionSnapPoint] {
var result = [IntersectionSnapPoint]()
for (ai, a) in entities.enumerated() {
for (bi, b) in entities.enumerated()
where bi>ai && a.id != b.id {
for (index, pos) in intersect(segmentPath: a.outline, and: b.outline).enumerated() {
result.append(IntersectionSnapPoint(position: pos, label: "Intersection", point: RuntimeIntersectionPoint(formA: a.id.runtimeId, formB: b.id.runtimeId, index: index)))
}
}
}
return result
}
| mit |
yshrkt/TinyCalendar | Sources/CalendarDate.swift | 1 | 1515 | //
// CalendarDate.swift
// TinyCalendar
//
// Created by Yoshihiro Kato on 2017/08/26.
//
//
import Foundation
public struct CalendarDate {
public let year: Int
public let month: Int
public let day: Int
public let weekday: Weekday
public static func today() -> CalendarDate? {
return CalendarDate(with: Date())
}
public init(year: Int, month: Int, day: Int, weekday: Weekday) {
self.year = year
self.month = month
self.day = day
self.weekday = weekday
}
public init?(with date: Date) {
let calendar = Calendar(identifier: .gregorian)
let dateComponents = calendar.dateComponents([.year, .month, .day, .weekday], from: date)
guard let year = dateComponents.year,
let month = dateComponents.month,
let day = dateComponents.day,
let wd = dateComponents.weekday,
let weekday = Weekday(rawValue: wd)else {
return nil
}
self.year = year
self.month = month
self.day = day
self.weekday = weekday
}
}
extension CalendarDate: Equatable, Hashable {
public static func == (lhs: CalendarDate, rhs: CalendarDate) -> Bool {
return lhs.year == rhs.year
&& lhs.month == rhs.month
&& lhs.day == rhs.day
&& lhs.weekday == rhs.weekday
}
public var hashValue: Int {
return "\(year)/\(month)/\(day) \(weekday.rawValue)".hashValue
}
}
| mit |
juli1quere/templates | Tests/Expected/Strings/flat-swift2-context-localizable.swift | 1 | 2233 | // Generated using SwiftGen, by O.Halligon — https://github.com/SwiftGen/SwiftGen
import Foundation
// swiftlint:disable file_length
// swiftlint:disable identifier_name line_length type_body_length
enum L10n {
/// Some alert body there
static let AlertMessage = L10n.tr("Localizable", "alert_message")
/// Title of the alert
static let AlertTitle = L10n.tr("Localizable", "alert_title")
/// These are %3$@'s %1$d %2$@.
static func ObjectOwnership(p1: Int, p2: String, p3: String) -> String {
return L10n.tr("Localizable", "ObjectOwnership", p1, p2, p3)
}
/// Hello, my name is %@ and I'm %d
static func Private(p1: String, p2: Int) -> String {
return L10n.tr("Localizable", "private", p1, p2)
}
/// You have %d apples
static func ApplesCount(p1: Int) -> String {
return L10n.tr("Localizable", "apples.count", p1)
}
/// Those %d bananas belong to %@.
static func BananasOwner(p1: Int, p2: String) -> String {
return L10n.tr("Localizable", "bananas.owner", p1, p2)
}
/// Some Reserved Keyword there
static let SettingsNavigationBarSelf = L10n.tr("Localizable", "settings.navigation-bar.self")
/// DeepSettings
static let SettingsNavigationBarTitleDeeperThanWeCanHandleNoReallyThisIsDeep = L10n.tr("Localizable", "settings.navigation-bar.title.deeper.than.we.can.handle.no.really.this.is.deep")
/// Settings
static let SettingsNavigationBarTitleEvenDeeper = L10n.tr("Localizable", "settings.navigation-bar.title.even.deeper")
/// Here you can change some user profile settings.
static let SeTTingsUSerProFileSectioNFooterText = L10n.tr("Localizable", "seTTings.uSer-proFile-sectioN.footer_text")
/// User Profile Settings
static let SettingsUserProfileSectionHeaderTitle = L10n.tr("Localizable", "SETTINGS.USER_PROFILE_SECTION.HEADER_TITLE")
}
// swiftlint:enable identifier_name line_length type_body_length
extension L10n {
private static func tr(table: String, _ key: String, _ args: CVarArgType...) -> String {
let format = NSLocalizedString(key, tableName: table, bundle: NSBundle(forClass: BundleToken.self), comment: "")
return String(format: format, locale: NSLocale.currentLocale(), arguments: args)
}
}
private final class BundleToken {}
| mit |
ryanbaldwin/Restivus | Tests/InterceptableSpec.swift | 1 | 750 | //
// InterceptableSpec.swift
// Restivus
//
// Created by Ryan Baldwin on 2017-12-16.
//Copyright © 2017 bunnyhug.me. All rights reserved.
//
import Quick
import Nimble
class InterceptableSpec: QuickSpec {
override func spec() {
describe("An Interceptable request") {
it("Can overwrite the Accept header") {
let request = InterceptableRequest()
var task: URLSessionDataTask!
expect { task = try request.submit() }.toNot(throwError())
task.cancel()
expect(task.currentRequest).toNot(beNil())
expect(task.currentRequest?.allHTTPHeaderFields?["Accept"]) == "ANYTHING-YOU-WANT"
}
}
}
}
| apache-2.0 |
PiXeL16/BudgetShare | BudgetShare/Modules/BudgetCreate/BudgetCreateMoneyLeft/View/BudgetCreateMoneyLeftViewing.swift | 1 | 435 | //
// BudgetCreateMoneyLeftView.swift
// BudgetShare
//
// Created by Chris Jimenez on 7/29/17.
// Copyright © 2017 Chris Jimenez. All rights reserved.
//
import UIKit
protocol BudgetCreateMoneyLeftViewing: class {
var controller: UIViewController? { get }
var presenter: BudgetCreateMoneyLeftPresenter! { get }
var budgetMoneyLeft: String { get }
func didTapContinue()
func continueSuccesful()
}
| mit |
orta/pod-template | templates/swift/Tests/PROJECTTests.swift | 5 | 780 | //
// PROJECTTests.swift
// PROJECTTests
//
// Created by PROJECT_OWNER on TODAYS_DATE.
// Copyright © 2016 PROJECT_OWNER. All rights reserved.
//
import XCTest
@testable import PROJECT
class PROJECTTests: 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() {
XCTAssert(true)
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
breadwallet/breadwallet-ios | breadwallet/src/Models/MenuItem.swift | 1 | 1658 | //
// MenuItem.swift
// breadwallet
//
// Created by Adrian Corscadden on 2017-04-01.
// Copyright © 2017-2019 Breadwinner AG. All rights reserved.
//
import UIKit
struct MenuItem {
enum Icon {
static let scan = UIImage(named: "scan")
static let wallet = UIImage(named: "wallet")
static let preferences = UIImage(named: "prefs")
static let security = UIImage(named: "security")
static let support = UIImage(named: "support")
static let rewards = UIImage(named: "Star")
static let about = UIImage(named: "about")
static let atmMap = UIImage(named: "placemark")
static let export = UIImage(named: "Export")
}
var title: String
var subTitle: String?
let icon: UIImage?
let accessoryText: (() -> String)?
let callback: () -> Void
let faqButton: UIButton? = nil
var shouldShow: () -> Bool = { return true }
init(title: String, subTitle: String? = nil, icon: UIImage? = nil, accessoryText: (() -> String)? = nil, callback: @escaping () -> Void) {
self.title = title
self.subTitle = subTitle
self.icon = icon?.withRenderingMode(.alwaysTemplate)
self.accessoryText = accessoryText
self.callback = callback
}
init(title: String, icon: UIImage? = nil, subMenu: [MenuItem], rootNav: UINavigationController, faqButton: UIButton? = nil) {
let subMenuVC = MenuViewController(items: subMenu, title: title, faqButton: faqButton)
self.init(title: title, icon: icon, accessoryText: nil) {
rootNav.pushViewController(subMenuVC, animated: true)
}
}
}
| mit |
vimeo/VimeoNetworking | Sources/Shared/Models/VIMReviewPage.swift | 1 | 543 | //
// VIMReviewPage.swift
// VimeoNetworking
//
// Created by Lim, Jennifer on 3/19/18.
//
/// VIMReviewPage stores all information related to review a video
public class VIMReviewPage: VIMModelObject {
/// Represents whether the review page is active for this video
@objc dynamic public private(set) var isActive: NSNumber?
/// Represents the review page link
@objc dynamic public private(set) var link: String?
public override func getObjectMapping() -> Any {
return ["active" : "isActive"]
}
}
| mit |
eastsss/ErrorDispatching | ErrorDispatching/Classes/Moya/ErrorModifiers/MoyaNSURLErrorExtractor.swift | 1 | 714 | //
// MoyaNSURLErrorExtractor.swift
// Pods
//
// Created by Anatoliy Radchenko on 08/03/2017.
//
//
import Foundation
import Moya
open class MoyaNSURLErrorExtractor: ErrorModifying {
public init() {}
public func modify(error: Swift.Error) -> Swift.Error? {
guard let moyaError = error as? MoyaError else {
return nil
}
switch moyaError {
case .underlying(let underlyingError):
let nsError = underlyingError as NSError
guard nsError.domain == NSURLErrorDomain else {
return nil
}
return nsError
default:
return nil
}
}
}
| mit |
box/box-ios-sdk | Sources/Core/Extensions/URLSessionTaskExtension.swift | 1 | 209 | //
// URLSessionTaskExtension.swift
// BoxSDK-iOS
//
// Created by Sujay Garlanka on 5/14/20.
// Copyright © 2020 box. All rights reserved.
//
import Foundation
extension URLSessionTask: Cancellable {}
| apache-2.0 |
benlangmuir/swift | test/Interpreter/switch_default.swift | 14 | 569 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
var SwitchDefaultTestSuite = TestSuite("Switch.Default")
defer { runAllTests() }
class Klass {}
protocol Protocol {}
enum Enum {
case value1(LifetimeTracked)
case value2(Protocol)
}
SwitchDefaultTestSuite.test("do not leak default case payload") {
// We are passing in Enum.value1 so we go down the default and leak our
// lifetime tracked.
func f(_ e: Enum?) {
switch (e) {
case .value2: return
default: return
}
}
f(.value1(LifetimeTracked(0)))
}
| apache-2.0 |
dankogai/swift-genericmath | OSX.playground/Contents.swift | 1 | 612 | //: Playground - noun: a place where people can play
(Int128(1)...Int128(32)).reduce(1,combine:*)
Float128(1.0/3.0)
Float128(0.0).isPowerOf2
Float128(0.5).isPowerOf2
Float128(1.0).isPowerOf2
Float128(1.5).isPowerOf2
Float128.infinity.isPowerOf2
Float128.NaN.isPowerOf2
UInt128.max.msbAt
UInt64.max.msbAt
(UInt64.max >> 1).msbAt
UInt64(1).msbAt
UInt64(0).msbAt
UInt32.max.msbAt
UInt16.max.msbAt
UInt8.max.msbAt
UInt.max.msbAt
var m = Float128(2.0/3.0) * Float128(1.0/3.0)
m.asDouble
m._toBitPattern().toString(16)
m = Float128(0.1)*Float128(0.1)*Float128(0.1)
m = Float128(UInt64.max)
m.asUInt64 == UInt64.max
| mit |
jakerockland/Swisp | Tests/SwispTests/XCTestCase+XCTPass.swift | 1 | 1465 | //
// XCTestCase+XCTPass.swift
// SwispTests
//
// MIT License
//
// Copyright (c) 2018 Jake Rockland (http://jakerockland.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
/**
Extension for `XCTestCase` to allow for simple `XCTPass` statements
*/
extension XCTestCase {
/**
Equivalent to calling `XCTAssertTrue(true)`
*/
func XCTPass() {
XCTAssertTrue(true)
}
}
| mit |
LQJJ/demo | 86-DZMeBookRead-master/DZMeBookRead/DZMeBookRead/other/custom/DZMHaloButton.swift | 1 | 2740 | //
// DZMHaloButton.swift
// DZMeBookRead
//
// Created by 邓泽淼 on 2017/3/24.
// Copyright © 2017年 DZM. All rights reserved.
//
import UIKit
/* imageView 四周默认间距为 HJSpace_3 算宽高的时候记得加上 用于光晕范围*/
class DZMHaloButton: UIControl {
/// imageView
private(set) var imageView:UIImageView!
/// 光晕颜色
private(set) var haloColor:UIColor!
/// 默认图片
var nomalImage:UIImage?
/// 选中图片
var selectImage:UIImage?
/// 选中
override var isSelected: Bool {
didSet{
if isSelected {
if selectImage != nil {
imageView.image = selectImage
}
}else{
if nomalImage != nil {
imageView.image = nomalImage
}
}
}
}
/// 初始化方法
init(_ frame: CGRect, haloColor:UIColor) {
super.init(frame: frame)
// 记录
self.haloColor = haloColor
// 添加
addSubviews()
// 开启光晕
openHalo(haloColor)
}
/// 通过正常的Size返回对应的按钮大小
class func HaloButtonSize(_ size:CGSize) ->CGSize {
return CGSize(width: size.width + DZMSpace_5, height: size.height + DZMSpace_5)
}
/// 开启光晕
func openHalo(_ haloColor:UIColor?) {
if haloColor != nil {
self.haloColor = haloColor;
// 开启按钮闪动
imageView.startPulse(with: haloColor, scaleFrom: 1.0, to: 1.2, frequency: 1.0, opacity: 0.5, animation: .regularPulsing)
}
}
// 关闭光晕
func closeHalo() {
imageView.stopPulse()
}
private func addSubviews() {
// imageView
imageView = UIImageView()
imageView.backgroundColor = haloColor
imageView.contentMode = .center
addSubview(imageView)
// 布局
setFrame()
}
private func setFrame() {
// 布局
imageView.frame = CGRect(x: DZMSpace_4, y: DZMSpace_4, width: width - DZMSpace_5, height: height - DZMSpace_5)
// 圆角
imageView.layer.cornerRadius = (width - DZMSpace_5) / 2
}
override func layoutSubviews() {
super.layoutSubviews()
setFrame()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 |
swiftix/swift.old | test/SILPasses/let_propagation.swift | 1 | 7551 | // RUN: %target-swift-frontend -primary-file %s -disable-func-sig-opts -emit-sil -O | FileCheck %s
// Check that LoadStoreOpts can handle "let" variables properly.
// Such variables should be loaded only once and their loaded values can be reused.
// This is safe, because once assigned, these variables cannot change their value.
// Helper function, which models an external functions with unknown side-effects.
// It is calle just to trigger flushing of all known stored in LoadStore optimizations.
@inline(never)
func action() {
print("")
}
final public class A0 {
let x: Int32
let y: Int32
init(_ x: Int32, _ y: Int32) {
self.x = x
self.y = y
}
@inline(never)
func sum1() -> Int32 {
// x and y should be loaded only once.
let n = x + y
action()
let m = x - y
action()
let p = x - y + 1
return n + m + p
}
func sum2() -> Int32 {
// x and y should be loaded only once.
let n = x + y
action()
let m = x - y
action()
let p = x - y + 1
return n + m + p
}
}
/*
// DISABLE THIS TEST CASE FOR NOW. AS RLE GETS BETTER. WILL RE-ENABLE.
//
// Check that counter computation is completely evaluated
// at compile-time, because the value of a.x and a.y are known
// from the initializer and propagated into their uses, because
// we know that action() invocations do not affect their values.
//
// DISABLECHECK-LABEL: sil {{.*}}testAllocAndUseLet
// DISABLECHECK: bb0
// DISABLECHECK-NOT: ref_element_addr
// DISABLECHECK-NOT: struct_element_addr
// DISABLECHECK-NOT: bb1
// DISABLECHECK: function_ref @_TF15let_propagation6actionFT_T_
// DISABLECHECK: apply
// DISABLECHECK: apply
// DISABLECHECK: apply
// DISABLECHECK: apply
// DISABLECHECK: apply
// DISABLECHECK: apply
// DISABLECHECK: apply
// DISABLECHECK: apply
// DISABLECHECK: integer_literal $Builtin.Int32, 36
// DISABLECHECK-NEXT: struct $Int32 ({{.*}} : $Builtin.Int32)
// DISABLECHECK-NEXT: return
@inline(never)
public func testAllocAndUseLet() -> Int32 {
let a = A0(3, 1)
var counter: Int32
// a.x and a.y should be loaded only once.
counter = a.sum2() + a.sum2()
counter += a.sum2() + a.sum2()
return counter
}
*/
/*
// DISABLE THIS TEST CASE FOR NOW. AS RLE GETS BETTER. WILL RE-ENABLE.
//
// Check that a.x and a.y are loaded only once and then reused.
// DISABLECHECK-LABEL: sil {{.*}}testUseLet
// DISABLECHECK: bb0
// DISABLECHECK: ref_element_addr
// DISABLECHECK: struct_element_addr
// DISABLECHECK: load
// DISABLECHECK: ref_element_addr
// DISABLECHECK: struct_element_addr
// DISABLECHECK: load
// DISABLECHECK-NOT: bb1
// DISABLECHECK-NOT: ref_element_addr
// DISABLECHECK-NOT: struct_element_addr
// DISABLECHECK-NOT: load
// DISABLECHECK: return
@inline(never)
public func testUseLet(a:A0) -> Int32 {
var counter: Int32
// a.x and a.y should be loaded only once.
counter = a.sum2() + a.sum2()
counter += a.sum2() + a.sum2()
return counter
}
*/
struct Goo {
var x: Int32
var y: Int32
}
struct Foo {
var g: Goo
}
struct Bar {
let f: Foo
var h: Foo
@inline(never)
mutating func action() {
}
}
@inline(never)
func getVal() -> Int32 {
return 9
}
// Global let
let gx: Int32 = getVal()
let gy: Int32 = getVal()
func sum3() -> Int32 {
// gx and gy should be loaded only once.
let n = gx + gy
action()
let m = gx - gy
action()
let p = gx - gy + 1
return n + m + p
}
/*
// DISABLE THIS TEST CASE FOR NOW. AS RLE GETS BETTER. WILL RE-ENABLE.
//
// Check that gx and gy are loaded only once and then reused.
// DISABLECHECK-LABEL: sil {{.*}}testUseGlobalLet
// DISABLECHECK: bb0
// DISABLECHECK: global_addr @_Tv15let_propagation2gyVs5Int32
// DISABLECHECK: global_addr @_Tv15let_propagation2gxVs5Int32
// DISABLECHECK: struct_element_addr
// DISABLECHECK: load
// DISABLECHECK: struct_element_addr
// DISABLECHECK: load
// DISABLECHECK-NOT: bb1
// DISABLECHECK-NOT: global_addr
// DISABLECHECK-NOT: ref_element_addr
// DISABLECHECK-NOT: struct_element_addr
// DISABLECHECK-NOT: load
// DISABLECHECK: return
@inline(never)
public func testUseGlobalLet() -> Int32 {
var counter: Int32 = 0
// gx and gy should be loaded only once.
counter = sum3() + sum3() + sum3() + sum3()
return counter
}
*/
struct A1 {
let x: Int32
// Propagate the value of the initializer into all instructions
// that use it, which in turn would allow for better constant
// propagation.
let y: Int32 = 100
init(v: Int32) {
if v > 0 {
x = 1
} else {
x = -1
}
}
// CHECK-LABEL: sil hidden @_TFV15let_propagation2A12f1
// CHECK: bb0
// CHECK: struct_extract {{.*}}#A1.x
// CHECK: struct_extract {{.*}}#Int32._value
// CHECK-NOT: load
// CHECK-NOT: struct_extract
// CHECK-NOT: struct_element_addr
// CHECK-NOT: ref_element_addr
// CHECK-NOT: bb1
// CHECK: return
func f1() -> Int32 {
// x should be loaded only once.
return x + x
}
// CHECK-LABEL: sil hidden @_TFV15let_propagation2A12f2
// CHECK: bb0
// CHECK: integer_literal $Builtin.Int32, 200
// CHECK-NEXT: struct $Int32
// CHECK-NEXT: return
func f2() -> Int32 {
// load y only once.
return y + y
}
}
class A2 {
let x: B2 = B2()
// CHECK-LABEL: sil hidden @_TFC15let_propagation2A22af
// bb0
// CHECK: %[[X:[0-9]+]] = ref_element_addr {{.*}}A2.x
// CHECK-NEXT: load %[[X]]
// CHECK: ref_element_addr {{.*}}B2.i
// CHECK: %[[XI:[0-9]+]] = struct_element_addr {{.*}}#Int32._value
// CHECK-NEXT: load %[[XI]]
// return
func af() -> Int32 {
// x and x.i should be loaded only once.
return x.f() + x.f()
}
}
final class B2 {
var i: Int32 = 10
func f() -> Int32 {
return i
}
}
@inline(never)
func oops() {
}
struct S {
let elt : Int32
}
// Check that we can handle reassignments to a variable
// of struct type properly.
// CHECK-LABEL: sil {{.*}}testStructWithLetElement
// CHECK-NOT: function_ref @{{.*}}oops
// CHECK: return
public func testStructWithLetElement() -> Int32 {
var someVar = S(elt: 12)
let tmp1 = someVar.elt
someVar = S(elt: 15)
let tmp2 = someVar.elt
// This check should get eliminated
if (tmp2 == tmp1) {
// If we get here, the compiler has propagated
// the old value someVar.elt into tmp2, which
// is wrong.
oops()
}
return tmp1+tmp2
}
public typealias Tuple3 = (Int32, Int32, Int32)
final public class S3 {
let x: Tuple3
var y: Tuple3
init(x: Tuple3, y:Tuple3) {
self.x = x
self.y = y
}
}
/*
// DISABLE THIS TEST CASE FOR NOW. AS RLE GETS BETTER. WILL RE-ENABLE.
//
// Check that s.x.0 is loaded only once and then reused.
// DISABLECHECK-LABEL: sil {{.*}}testLetTuple
// DISABLECHECK: tuple_element_addr
// DISABLECHECK: %[[X:[0-9]+]] = struct_element_addr
// DISABLECHECK: load %[[X]]
// DISABLECHECK-NOT: load %[[X]]
// DISABLECHECK: return
public func testLetTuple(s: S3) ->Int32 {
var counter: Int32 = 0
counter += s.x.0
action()
counter += s.x.0
action()
counter += s.x.0
action()
counter += s.x.0
action()
return counter
}
*/
// Check that s.x.0 is reloaded every time.
// CHECK-LABEL: sil {{.*}}testVarTuple
// CHECK: tuple_element_addr
// CHECK: %[[X:[0-9]+]] = struct_element_addr
// CHECK: load %[[X]]
// CHECK: load %[[X]]
// CHECK: load %[[X]]
// CHECK: load %[[X]]
// CHECK: return
public func testVarTuple(s: S3) ->Int32 {
var counter: Int32 = 0
counter += s.y.0
action()
counter += s.y.0
action()
counter += s.y.0
action()
counter += s.y.0
action()
return counter
}
| apache-2.0 |
swiftgurmeet/LocuEx | LocuEx/LocuData.swift | 1 | 3754 | //
// LocuData.swift
// LocuEx
//
//The MIT License (MIT)
//
//Copyright (c) 2015 swiftgurmeet
//
//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 MapKit
class LocuData {
struct Settings {
static let apiUrl = "https://api.locu.com/v2/venue/search/"
}
func request(location: CLLocationCoordinate2D, callback:(NSDictionary)->()) {
var nsURL = NSURL(string: Settings.apiUrl)
var request = NSMutableURLRequest(URL: nsURL!)
var response: NSURLResponse?
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
var locationRequest = [String:AnyObject]()
locationRequest["$in_lat_lng_radius"] = [location.latitude,location.longitude,1000]
var params = [ "fields":["name", "location", "contact"],
"venue_queries":
[
[
"location" : [
"geo": locationRequest
] ,
"categories" : [
"name":"Restaurants",
// "str_id" : "chinese"
]
]
],
"api_key":""
]
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
let requestText = NSString(data: request.HTTPBody!, encoding: NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request) {
(data,response,error) in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
println("response was not 200: \(response)")
return
}
}
if (error != nil) {
println("error submitting request: \(error.localizedDescription)")
return
}
dispatch_async(dispatch_get_main_queue()) {
var error: NSError?
if let jsonData = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary {
callback(jsonData)
} else {
println("No dictionary received")
}
}
}
task.resume()
}
}
| mit |
evgenyneu/SigmaSwiftStatistics | SigmaSwiftStatisticsTests/NormalTests.swift | 1 | 3839 | import UIKit
import XCTest
import SigmaSwiftStatistics
class NormalTests: XCTestCase {
// MARK: - Normal Distribution
func testNormalDistribution_μZero_σOne() {
XCTAssertEqual(0.5, Sigma.normalDistribution(x: 0)!)
XCTAssertEqual(0.1586552539314570, Sigma.normalDistribution(x: -1)!)
XCTAssertEqual(0.8413447460685430, Sigma.normalDistribution(x: 1)!)
XCTAssertEqual(0.999999999, Helpers.round10(Sigma.normalDistribution(x: 6)!))
}
func testNormalDistribution_μσNonDefault() {
XCTAssertEqual(0.7807704106838400, Sigma.normalDistribution(x: 0.014401, μ: -2.31, σ: 3.00001)!)
}
func testNormalDistribution_σIsZero() {
XCTAssertNil(Sigma.normalDistribution(x: 0.014401, μ: -2.31, σ: 0))
}
func testNormalDistribution_σIsNegative() {
XCTAssertNil(Sigma.normalDistribution(x: 0.014401, μ: -2.31, σ: -1.23))
}
// MARK: - Normal Density
func testNormalDensity_μZero_σOne() {
XCTAssertEqual(0.3989422804014327, Sigma.normalDensity(x: 0))
XCTAssertEqual(0.2419707245191434, Helpers.round16(Sigma.normalDensity(x: 1)!))
XCTAssertEqual(0.2419707245191434, Helpers.round16(Sigma.normalDensity(x: -1)!))
}
func testNormalDensity_μσNonDefault() {
XCTAssertEqual(0.1111004887053895,
Helpers.round16(Sigma.normalDensity(x: 13.92, μ: 12.4, σ: 3.21)!))
XCTAssertEqual(0.4070839591779069,
Sigma.normalDensity(x: 2e-12, μ: 0.0000000014, σ: 0.980000001)!)
}
func testNormalDensity_σIsZero() {
XCTAssertNil(Sigma.normalDensity(x: 2e-12, μ: 0.0000000014, σ: 0))
}
func testNormalDensity_σIsNigative() {
XCTAssertNil(Sigma.normalDensity(x: 2e-12, μ: 0.0000000014, σ: -2))
}
// MARK: - Normal Quantile
func testNormalQuantile_μZero_σOne() {
XCTAssertEqual(-1.9599639845400538, Sigma.normalQuantile(p: 0.025))
XCTAssertEqual(-1.6448536269514726, Sigma.normalQuantile(p: 0.05))
XCTAssertEqual(-1.2815515655446008, Sigma.normalQuantile(p: 0.1))
XCTAssertEqual(-0.52440051270804066, Sigma.normalQuantile(p: 0.3))
XCTAssertEqual(-2.506628274566559724e-06, Sigma.normalQuantile(p: 0.499999))
XCTAssertEqual(0, Sigma.normalQuantile(p: 0.5))
XCTAssertEqual(2.5066282733116487548e-07, Sigma.normalQuantile(p: 0.5000001))
XCTAssertEqual(0.841621233572914406, Sigma.normalQuantile(p: 0.8))
XCTAssertEqual(1.959963984540053605, Sigma.normalQuantile(p: 0.975))
}
func testNormalQuantile_μZero_σOne_close_to_boundaries() {
XCTAssertEqual(-3.71901648545567997, Sigma.normalQuantile(p: 0.0001))
XCTAssertEqual(-10.4204522008030977, Sigma.normalQuantile(p: 1e-25))
XCTAssertEqual(-14.9333375347884889, Sigma.normalQuantile(p: 1e-50))
XCTAssertEqual(3.719016485455708398, Sigma.normalQuantile(p: 0.9999))
XCTAssertEqual(8.209536151601385611, Sigma.normalQuantile(p: 0.9999999999999999))
}
func testNormalQuantile_μZero_σOne_probabilityZero() {
XCTAssertEqual(-Double.infinity, Sigma.normalQuantile(p: 0))
}
func testNormalQuantile_μZero_σOne_probabilityOne() {
XCTAssertEqual(Double.infinity, Sigma.normalQuantile(p: 1))
}
func testNormalQuantile_μZero_σOne_probabilityLessThenZero() {
XCTAssertNil(Sigma.normalQuantile(p: -1))
}
func testNormalQuantile_μZero_σOne_probabilityGreaterThanOne() {
XCTAssertNil(Sigma.normalQuantile(p: 1.2))
}
func testNormalQuantile_μσNonDefault() {
XCTAssertEqual(1.9142201769251021, Sigma.normalQuantile(p: 0.412, μ: 2.0123, σ: 0.441))
}
func testNormalQuantile_μσNonDefault_σIsZero() {
XCTAssertNil(Sigma.normalQuantile(p: 0.412, μ: 2.0123, σ: 0))
}
func testNormalQuantile_μσNonDefault_σIsNegative() {
XCTAssertNil(Sigma.normalQuantile(p: 0.412, μ: 2.0123, σ: -0.3))
}
}
| mit |
kstaring/swift | validation-test/compiler_crashers_fixed/26043-swift-inflightdiagnostic-fixitreplacechars.swift | 11 | 413 | // 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
// RUN: not %target-swift-frontend %s -parse
let a{n(
class
case,
| apache-2.0 |
shaps80/Peek | Example/NotTwitter/TimelineViewController.swift | 1 | 2323 | //
// TimelineViewController.swift
// NotTwitter
//
// Created by Shaps Benkau on 10/03/2018.
// Copyright © 2018 Snippex. All rights reserved.
//
import UIKit
import SwiftUI
import Peek
public final class TimelineViewController: UITableViewController {
public override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem?.accessibilityHint = "New Message"
navigationItem.rightBarButtonItem?.accessibilityIdentifier = "navigation.newMessage"
}
public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! Cell
return cell
}
public override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if #available(iOS 13, *) {
let controller = HostingController(rootView: ProfileView())
navigationController?.pushViewController(controller, animated: true)
}
}
}
extension TimelineViewController {
@IBAction private func newMessage() { print("New message") }
@IBAction private func toggleFavourite() { print("Favourite toggled") }
@IBAction private func reshare() { print("Re-shared") }
}
// MARK: Peek
extension TimelineViewController {
public override var canBecomeFirstResponder: Bool {
return true
}
public override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
// iOS 10 now requires device motion handlers to be on a UIViewController
view.window?.peek.handleShake(motion)
}
}
@available(iOS 13, *)
final class HostingController<Content>: UIHostingController<Content> where Content: View {
public override var canBecomeFirstResponder: Bool {
return true
}
public override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
// iOS 10 now requires device motion handlers to be on a UIViewController
view.window?.peek.handleShake(motion)
}
}
| mit |
jovito-royeca/Cineko | Cineko/RTManager.swift | 1 | 622 | //
// RTManager.swift
// Cineko
//
// Created by Jovit Royeca on 14/04/2016.
// Copyright © 2016 Jovito Royeca. All rights reserved.
//
import UIKit
enum RTError: ErrorType {
case NoAPIKey
case NoSessionID
}
struct TRConstants {
static let APIKey = "api_key"
static let APIURL = "hapi.rottentomatoes.com/api/public/v1.0.json"
}
class RTManager: NSObject {
// MARK: Variables
private var apiKey:String?
// MARK: Setup
func setup(apiKey: String) {
self.apiKey = apiKey
}
// MARK: - Shared Instance
static let sharedInstance = RTManager()
}
| apache-2.0 |
wilfreddekok/Antidote | Antidote/ChatProgressProtocol.swift | 1 | 417 | // 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
protocol ChatProgressProtocol {
var updateProgress: ((progress: Float) -> Void)? { get set }
var updateEta: ((eta: CFTimeInterval, bytesPerSecond: OCTToxFileSize) -> Void)? { get set }
}
| mpl-2.0 |
keygx/SelectItemController | SelectItemController/Dialog/Protocols.swift | 1 | 355 | //
// Protocols.swift
// SelectItemController
//
// Created by keygx on 2017/04/18.
// Copyright © 2017年 keygx. All rights reserved.
//
import UIKit
@objc public protocol ItemTableViewDelegate {
@objc func didTapped(index: Int)
}
public protocol ItemTableViewType: class {
var itemTableViewDelegate: ItemTableViewDelegate? { get set }
}
| mit |
stefan-vainberg/SlidingImagePuzzle | SlidingImagePuzzle/SlidingImagePuzzle/PuzzleBoardView.swift | 1 | 5014 | //
// PuzzleBoardView.swift
// SlidingImagePuzzle
//
// Created by Stefan Vainberg on 11/8/14.
// Copyright (c) 2014 Stefan. All rights reserved.
//
import Foundation
import UIKit
class PuzzleBoardView : UIView
{
// PUBLICS
var boardGameSize:CGSize?
var board:([[UIImageView]])?
//PRIVATES
private var internalImageView:UIImageView?
private var puzzleGestureRecognizer:PuzzleGestureHandler?
// INITS
convenience init(initialImage:UIImage)
{
self.init(frame:CGRectZero)
self.initializeView(initialImage)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// GENERIC INITIALIZER
func initializeView(image:UIImage) -> Void
{
// add the reference holder of pieces
board = []
self.clipsToBounds = true
self.layer.borderColor = UIColor.blackColor().CGColor
self.layer.borderWidth = 1.0
internalImageView = UIImageView(image: image)
self.setTranslatesAutoresizingMaskIntoConstraints(false)
internalImageView!.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addSubview(internalImageView!)
self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: internalImageView!, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0))
self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: internalImageView!, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0))
self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: internalImageView!, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 0))
self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: internalImageView!, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: 0))
}
func UpdateWithPuzzlePieces(pieces:[[UIImage]]) -> Void
{
let sampleImage = pieces[0][0]
let totalHeight = CGFloat(pieces.count) * sampleImage.size.height
let totalWidth = CGFloat(pieces[0].count) * sampleImage.size.width
boardGameSize = CGSizeMake(totalWidth, totalHeight)
self.removeConstraints(self.constraints())
self.backgroundColor = UIColor.blackColor()
internalImageView!.removeFromSuperview()
var currentRow = 0
var currentColumn = 0
var fullColumn:[UIImageView] = []
var imageTag = 0
for row in pieces
{
for image in row
{
let correspondingImageView = UIImageView(image: image)
correspondingImageView.tag = imageTag
correspondingImageView.frame = CGRectMake(CGFloat(currentColumn)*(image.size.width+1), CGFloat(currentRow)*(image.size.height+1), image.size.width, image.size.height)
self.addSubview(correspondingImageView)
fullColumn.append(correspondingImageView)
currentColumn++
imageTag++
}
board!.append(fullColumn)
fullColumn = []
currentRow++
currentColumn = 0
}
}
func UpdateWithImage(image:UIImage) -> Void
{
internalImageView!.image = image
}
func BlackOutPiece(pieceLocation:(row:Int, column:Int))
{
let pieceToBlackOut = board![pieceLocation.row][pieceLocation.column]
let blackView = UIView(frame: CGRectMake(0, 0, pieceToBlackOut.bounds.size.width, pieceToBlackOut.bounds.size.height))
blackView.backgroundColor = UIColor.blackColor()
blackView.alpha = 1.0
pieceToBlackOut.addSubview(blackView)
}
func PieceAtPoint(point:CGPoint) -> UIImageView
{
let locationOfPiece = self.arrayLocationOfPiece(point)
return board![locationOfPiece.row][locationOfPiece.column]
}
func arrayLocationOfPiece(point:CGPoint) -> (row:Int, column:Int)
{
let samplePiece = board![0][0]
let samplePieceSize = samplePiece.bounds.size
// figure out which row and column the piece is in
var pieceAtPointRow:Int = Int( floor(point.y / samplePieceSize.height) )
var pieceAtPointColumn:Int = Int( floor(point.x / samplePieceSize.width) )
if (pieceAtPointColumn >= board![0].count) {
pieceAtPointColumn = board![0].count - 1
}
if (pieceAtPointRow >= board!.count) {
pieceAtPointRow = board!.count - 1
}
return (pieceAtPointRow, pieceAtPointColumn)
}
} | cc0-1.0 |
DesWurstes/CleanMyCraft | CleanMyCraft/ViewController.swift | 1 | 8371 | // MIT License
// Copyright (c) 2017 DesWurstes
// 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 Cocoa
class ViewController: NSViewController {
var path: String = "/Users/" + NSUserName() + "/Library/Application Support/minecraft"
@IBOutlet weak var quit: NSButton!
@IBOutlet weak var crashReports: NSView!
@IBOutlet weak var misc: NSButton!
@IBOutlet weak var screenshots: NSButton!
@IBOutlet weak var serverResourcePacks: NSButton!
@IBOutlet weak var crashReportsSize: NSTextField!
@IBOutlet weak var miscSize: NSTextField!
@IBOutlet weak var screenshotsSize: NSTextField!
@IBOutlet weak var serverResourceSize: NSTextField!
@IBOutlet weak var assetsSize: NSTextField!
@IBOutlet weak var librariesSize: NSTextField!
@IBAction func quit(_ sender: NSButton) {
let alert = NSAlert()
alert.messageText = "Are you sure you want to quit?"
alert.informativeText = "You may quit now."
alert.alertStyle = .informational
alert.addButton(withTitle: "Quit")
alert.addButton(withTitle: "Cancel")
if alert.runModal() == 1000 {
NSApplication.shared().terminate(self)
}
}
func fileOrFolderSize(_ fileOrFolderPath: String) -> UInt64 {
if !FileManager().fileExists(atPath: fileOrFolderPath) {
return 0
}
var bool: ObjCBool = false
if FileManager().fileExists(atPath: fileOrFolderPath, isDirectory: &bool), bool.boolValue {
// url is a folder url
do { // Source: https://stackoverflow.com/a/32814710/
// print(fileOrFolderPath)
let z: URL = URL(string: fileOrFolderPath.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!.replacingOccurrences(of: "%2F", with: "/"))! as URL
//let z: URL = URL(string: fileOrFolderPath.replacingOccurrences(of: " ", with: "%20"))! as URL
let files = try FileManager().contentsOfDirectory(at: z, includingPropertiesForKeys: nil, options: [])
//let files = try FileManager().contentsOfDirectory(at: NSURL(string: fileOrFolderPath)! as URL, includingPropertiesForKeys: nil, options: [])
var folderFileSizeInBytes: UInt64 = 0
for file in files {
var boolo: ObjCBool = false
if FileManager().fileExists(atPath: file.path, isDirectory: &boolo), boolo.boolValue {
folderFileSizeInBytes += fileOrFolderSize(file.path)
} else {
folderFileSizeInBytes += (try? FileManager.default.attributesOfItem(atPath: file.path)[.size] as? NSNumber)??.uint64Value ?? 0
}
}
// format it using NSByteCountFormatter to display it properly
/*let byteCountFormatter = ByteCountFormatter()
byteCountFormatter.allowedUnits = .useBytes
byteCountFormatter.countStyle = .file
let folderSizeToDisplay = byteCountFormatter.string(fromByteCount: Int64(folderFileSizeInBytes))
print(folderSizeToDisplay)*/ // "X,XXX,XXX bytes"
return folderFileSizeInBytes
} catch {
print(error)
}
} else {
do {
return (try FileManager.default.attributesOfItem(atPath: fileOrFolderPath)[.size] as? NSNumber)?.uint64Value ?? 0
} catch {
print(error)
}
}
print("Error! Please report it to https://github.com/DesWurstes/CleanMyCraft")
return 0
}
override func viewDidAppear() {
view.wantsLayer = true
guard let window = NSApplication.shared().windows.first else { return }
// pinky window.backgroundColor = NSColor.init(red: 1, green: 249.0/255.0, blue: 249.0/255.0, alpha: 0.7)
// yellow window.backgroundColor = NSColor.init(red: 255.0/255.0, green: 255.0/255.0, blue: 102.0/255.0, alpha: 0.6)
window.backgroundColor = NSColor.init(red: 100.0/255.0, green: 250.0/255.0, blue: 250.0/255.0, alpha: 0.675)
window.titlebarAppearsTransparent = true
window.titleVisibility = .hidden
window.isOpaque = false
/*if !(Bundle.main.resourcePath! as String).contains("Applications") {
let alert = NSAlert()
// alert.window.back
alert.messageText = "Do you want to move this app to Applications folder?"
alert.informativeText = "It may be moved automatically if you want, and it takes less than a second."
alert.alertStyle = .warning
alert.addButton(withTitle: "Move it!")
alert.addButton(withTitle: "I'll move it manually.")
if alert.runModal() == 1000 {
if FileManager().fileExists(atPath: "/Applications/CleanMyCraft.app") {
do {
try FileManager().removeItem(atPath: "/Applications/CleanMyCraft.app")
} catch let e {
print(e)
}
print("Found /Applications/CleanMyCraft.app")
}
let t = Process(), p = Pipe(), t1 = Process(), p1 = Pipe()
t.standardOutput = p
t1.standardOutput = p1
t.launchPath = "/usr/bin/env"
t1.launchPath = "/usr/bin/env"
t.arguments = ["mv", (Bundle.main.resourcePath! as String).replacingOccurrences(of: "/Contents/Resources", with: ""), "/Applications/CleanMyCraft.app"]
t.launch()
print(NSString(data: p.fileHandleForReading.readDataToEndOfFile(), encoding: String.Encoding.utf8.rawValue)!)
t1.arguments = ["open", "-n", "-a", "/Applications/CleanMyCraft.app"]
t1.launch()
print(NSString(data: p1.fileHandleForReading.readDataToEndOfFile(), encoding: String.Encoding.utf8.rawValue)!)
}
NSApplication.shared().terminate(self)
}*/
assert(FileManager().fileExists(atPath: path))
path += "/"
DispatchQueue.main.async {
var size = self.fileOrFolderSize(self.path + "crash-reports") + self.fileOrFolderSize(self.path + "logs")
for e in self.findFiles(self.path, "hs_err_pid") {
size += self.fileOrFolderSize(e)
}
self.crashReportsSize.stringValue = self.sizeCalculator(size)
size = self.fileOrFolderSize(self.path + "level.dat") + self.fileOrFolderSize(self.path + "launcher.pack.lzma") + self.fileOrFolderSize(self.path + "usercache.json") + self.fileOrFolderSize(self.path + "bin") + self.fileOrFolderSize(self.path + "resources")
for e in self.findFiles(self.path, "textures_") {
size += self.fileOrFolderSize(e)
}
self.miscSize.stringValue = self.sizeCalculator(size)
self.screenshotsSize.stringValue = self.sizeCalculator(self.fileOrFolderSize(self.path + "screenshots"))
self.serverResourceSize.stringValue = self.sizeCalculator(self.fileOrFolderSize(self.path + "server-resource-packs"))
self.assetsSize.stringValue = self.sizeCalculator(self.fileOrFolderSize(self.path + "assets"))
self.librariesSize.stringValue = self.sizeCalculator(self.fileOrFolderSize(self.path + "libraries"))
}
}
func findFiles(_ path: String, _ containing: String) -> [String] { // Inspired from https://stackoverflow.com/a/35612760/6557621
//let pathURL = NSURL(fileURLWithPath: path, isDirectory: true)
var allFiles: [String] = []
if let enumerator = FileManager().enumerator(atPath: path) {
for filet in enumerator {
if (filet as! String).contains(containing) {
allFiles.append(filet as! String)
}
}
}
print(allFiles)
return allFiles
}
func sizeCalculator(_ a: UInt64) -> String {
if a < 1024 {
return "\(a) bytes"
}
if a < 1024*1024 {
return "\(Float(UInt(Float(a)*10/1024))/10) KB"
}
if a < 1024*1024*1024 {
return "\(Float(UInt(Float(a)*10/(1024*1024)))/10) MB"
}
return "\(Float(UInt(Float(a)*10/(1024*1024*1024)))/10) GB"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
| mit |
victorchee/NavigationController | NavigationAppearance/NavigationAppearance/AppearanceNavigationController.swift | 1 | 4863 | //
// AppearanceNavigationController.swift
// NavigationAppearance
//
// Created by qihaijun on 12/2/15.
// Copyright © 2015 VictorChee. All rights reserved.
//
import UIKit
public class AppearanceNavigationController: UINavigationController, UINavigationControllerDelegate {
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delegate = self
}
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
delegate = self
}
override public init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
delegate = self
}
public convenience init() {
self.init(nibName: nil, bundle: nil)
}
// MARK: - UINavigationControllerDelegate
public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
guard let appearanceContext = viewController as? NavigationControllerAppearanceContext else {
return
}
setNavigationBarHidden(appearanceContext.prefersNavigationControllerBarHidden(navigationController: self), animated: animated)
setToolbarHidden(appearanceContext.prefersNavigationControllerToolbarHidden(navigationController: self), animated: animated)
applyAppearance(appearance: appearanceContext.preferredNavigationControllerAppearance(navigationController: self), animated: animated)
// interactive gesture requires more complex login.
guard let coordinator = viewController.transitionCoordinator, coordinator.isInteractive else {
return
}
coordinator.animate(alongsideTransition: { (_) -> Void in
}) { (context) -> Void in
if context.isCancelled, let appearanceContext = self.topViewController as? NavigationControllerAppearanceContext {
// hiding navigation bar & toolbar within interaction completion will result into inconsistent UI state
self.setNavigationBarHidden(appearanceContext.prefersNavigationControllerBarHidden(navigationController: self), animated: animated)
self.setToolbarHidden(appearanceContext.prefersNavigationControllerToolbarHidden(navigationController: self), animated: animated)
}
}
coordinator.notifyWhenInteractionEnds { (context) -> Void in
if context.isCancelled, let from = context.viewController(forKey: UITransitionContextViewControllerKey.from) as? NavigationControllerAppearanceContext {
// changing navigation bar & toolbar appearance within animate completion will result into UI glitch
self.applyAppearance(appearance: from.preferredNavigationControllerAppearance(navigationController: self), animated: true)
}
}
}
// MARK: - Appearance Applying
private var appliedAppearance: Appearance?
public var appearanceApplyingStrategy = AppearanceApplyingStrategy() {
didSet {
applyAppearance(appearance: appliedAppearance, animated: false)
}
}
private func applyAppearance(appearance: Appearance?, animated: Bool) {
if appearance != nil && appliedAppearance != appearance {
appliedAppearance = appearance
appearanceApplyingStrategy.apply(appearance: appearance, toNavigationController: self, animated: animated)
setNeedsStatusBarAppearanceUpdate()
}
}
// MARK: - Appearance Update
func updateAppearanceForViewController(viewController: UIViewController) {
guard let context = viewController as? NavigationControllerAppearanceContext, viewController == topViewController && transitionCoordinator == nil else {
return
}
setNavigationBarHidden(context.prefersNavigationControllerBarHidden(navigationController: self), animated: true)
setToolbarHidden(context.prefersNavigationControllerToolbarHidden(navigationController: self), animated: true)
applyAppearance(appearance: context.preferredNavigationControllerAppearance(navigationController: self), animated: true)
}
public func updateAppearance() {
guard let top = topViewController else {
return
}
updateAppearanceForViewController(viewController: top)
}
override public var preferredStatusBarStyle: UIStatusBarStyle {
return appliedAppearance?.statusBarStyle ?? super.preferredStatusBarStyle
}
override public var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return appliedAppearance != nil ? .fade : super.preferredStatusBarUpdateAnimation
}
}
| mit |
jcsla/MusicoAudioPlayer | MusicoAudioPlayer/Classes/player/extensions/AudioPlayer+CurrentItem.swift | 2 | 1665 | //
// AudioPlayer+CurrentItem.swift
// AudioPlayer
//
// Created by Kevin DELANNOY on 29/03/16.
// Copyright © 2016 Kevin Delannoy. All rights reserved.
//
import Foundation
public typealias TimeRange = (earliest: TimeInterval, latest: TimeInterval)
extension AudioPlayer {
/// The current item progression or nil if no item.
public var currentItemProgression: TimeInterval? {
return player?.currentItem?.currentTime().ap_timeIntervalValue
}
/// The current item duration or nil if no item or unknown duration.
public var currentItemDuration: TimeInterval? {
return player?.currentItem?.duration.ap_timeIntervalValue
}
/// The current seekable range.
public var currentItemSeekableRange: TimeRange? {
let range = player?.currentItem?.seekableTimeRanges.last?.timeRangeValue
if let start = range?.start.ap_timeIntervalValue, let end = range?.end.ap_timeIntervalValue {
return (start, end)
}
if let currentItemProgression = currentItemProgression {
// if there is no start and end point of seekable range
// return the current time, so no seeking possible
return (currentItemProgression, currentItemProgression)
}
// cannot seek at all, so return nil
return nil
}
/// The current loaded range.
public var currentItemLoadedRange: TimeRange? {
let range = player?.currentItem?.loadedTimeRanges.last?.timeRangeValue
if let start = range?.start.ap_timeIntervalValue, let end = range?.end.ap_timeIntervalValue {
return (start, end)
}
return nil
}
}
| mit |
nakiostudio/EasyPeasy | Example/EasyPeasy/FeedController.swift | 1 | 4091 | // The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import EasyPeasy
// NOTE:
// I know this controller could be easily achievable with a regular
// UITableViewController but this way is much easier to show the
// potential of EasyPeasy
class FeedController: UIViewController {
fileprivate var tweets: [TweetModel] = []
fileprivate var tweetViews: [TweetView] = []
fileprivate lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView(frame: CGRect.zero)
return scrollView
}()
fileprivate lazy var newTweetsView: UIImageView = {
let imageView = UIImageView(image: UIImage.easy_newTweets())
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
self.populateFeed()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// An example of UIView animation
self.showNewTweetsIndicator(true)
}
// MARK: Private
fileprivate func setup() {
// Set stub data
self.tweets = TweetModel.stubData()
// Background color
self.view.backgroundColor = UIColor(red: 0.937, green: 0.937, blue: 0.937, alpha: 1.0)
// Set title view
let logoImageView = UIImageView(image: UIImage.easy_twitterLogo())
self.navigationItem.titleView = logoImageView
// Scrollview
self.view.addSubview(self.scrollView)
self.scrollView.easy.layout(
Edges()
)
// New tweets indicator
self.view.addSubview(self.newTweetsView)
self.newTweetsView.easy.layout(
Size(CGSize(width: 118.0, height: 30.0)),
Top(-100),
CenterX()
)
}
fileprivate func populateFeed() {
// It creates the constraints for each entry
for (index, tweet) in self.tweets.enumerated() {
let view = TweetView(frame: CGRect.zero)
view.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .vertical)
view.setContentHuggingPriority(UILayoutPriority(rawValue: 600), for: .vertical)
self.scrollView.addSubview(view)
view.easy.layout(
Width(<=420),
Height(>=78),
CenterX(),
Left().with(.medium),
Right().with(.medium),
// Pins to top only when we place the first row
Top().when { index == 0 },
// Pins to bottom of the preivous item for the other cases
Top(1).to(self.tweetViews.last ?? self.scrollView).when { index > 0 }
)
view.configureWithModel(tweet)
self.tweetViews.append(view)
}
// Establishes constraint with the bottom of the scroll view to adjust
// the content size
self.tweetViews.last!.easy.layout(
Bottom().to(self.scrollView, .bottom)
)
}
fileprivate func showNewTweetsIndicator(_ show: Bool) {
UIView.animate(withDuration: 0.3, delay: 2.0, options: UIView.AnimationOptions(), animations: {
self.newTweetsView.easy.layout(Top(10).when { show })
self.newTweetsView.easy.layout(Top(-100).when { !show })
self.view.layoutIfNeeded()
}, completion: { complete in
if show {
self.showNewTweetsIndicator(false)
}
})
}
}
| mit |
EgeTart/MedicineDMW | DWM/DetailMeetingController.swift | 1 | 1110 | //
// DetailMeetingController.swift
// DWM
//
// Created by HM on 15/9/30.
// Copyright © 2015年 EgeTart. All rights reserved.
//
import UIKit
class DetailMeetingController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.title = "会议详情"
self.navigationController?.navigationBarHidden = false
self.navigationController?.navigationBar.backItem?.title = ""
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
braintree/braintree_ios | Sources/BraintreeSEPADirectDebit/BTSEPADirectDebitClient.swift | 1 | 10432 | import Foundation
import AuthenticationServices
#if canImport(BraintreeCore)
import BraintreeCore
#endif
/// Used to integrate with SEPA Direct Debit.
@objcMembers public class BTSEPADirectDebitClient: NSObject {
let apiClient: BTAPIClient
var webAuthenticationSession: WebAuthenticationSession
var sepaDirectDebitAPI: SEPADirectDebitAPI
/// Creates a SEPA Direct Debit client.
/// - Parameter apiClient: An instance of `BTAPIClient`
@objc(initWithAPIClient:)
public init(apiClient: BTAPIClient) {
self.apiClient = apiClient
self.sepaDirectDebitAPI = SEPADirectDebitAPI(apiClient: apiClient)
self.webAuthenticationSession = WebAuthenticationSession()
}
/// Internal for testing.
init(apiClient: BTAPIClient, webAuthenticationSession: WebAuthenticationSession, sepaDirectDebitAPI: SEPADirectDebitAPI) {
self.apiClient = apiClient
self.webAuthenticationSession = webAuthenticationSession
self.sepaDirectDebitAPI = sepaDirectDebitAPI
}
/// Initiates an `ASWebAuthenticationSession` to display a mandate to the user. Upon successful mandate creation, tokenizes the payment method and returns a result
/// - Parameters:
/// - request: a BTSEPADebitRequest
/// - context: the ASWebAuthenticationPresentationContextProviding protocol conforming ViewController
@available(iOS 13.0, *)
public func tokenize(
request: BTSEPADirectDebitRequest,
context: ASWebAuthenticationPresentationContextProviding,
completion: @escaping (BTSEPADirectDebitNonce?, Error?) -> Void
) {
apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.selected.started")
createMandate(request: request) { createMandateResult, error in
guard error == nil else {
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.failure")
completion(nil, error)
return
}
guard let createMandateResult = createMandateResult else {
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.failure")
completion(nil, SEPADirectDebitError.resultReturnedNil)
return
}
// if the SEPADirectDebitAPI.tokenize API calls returns a "null" URL, the URL has already been approved.
if createMandateResult.approvalURL == CreateMandateResult.mandateAlreadyApprovedURLString {
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.success")
self.tokenize(createMandateResult: createMandateResult, completion: completion)
return
} else if let url = URL(string: createMandateResult.approvalURL) {
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.success")
self.startAuthenticationSession(url: url, context: context) { success, error in
switch success {
case true:
self.tokenize(createMandateResult: createMandateResult, completion: completion)
return
case false:
completion(nil, error)
return
}
}
} else {
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.failure")
completion(nil, SEPADirectDebitError.approvalURLInvalid)
}
}
}
/// Initiates an `ASWebAuthenticationSession` to display a mandate to the user. Upon successful mandate creation, tokenizes the payment method and returns a result
/// - Parameters:
/// - request: a BTSEPADebitRequest
/// - Note: This function should only be used for iOS 12 support. This function cannot be invoked on a device running iOS 13 or higher.
// NEXT_MAJOR_VERSION remove this function
public func tokenize(
request: BTSEPADirectDebitRequest,
completion: @escaping (BTSEPADirectDebitNonce?, Error?) -> Void
) {
apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.selected.started")
createMandate(request: request) { createMandateResult, error in
guard error == nil else {
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.failure")
completion(nil, error)
return
}
guard let createMandateResult = createMandateResult else {
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.failure")
completion(nil, SEPADirectDebitError.resultReturnedNil)
return
}
// if the SEPADirectDebitAPI.tokenize API calls returns a "null" URL, the URL has already been approved.
if createMandateResult.approvalURL == CreateMandateResult.mandateAlreadyApprovedURLString {
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.success")
self.tokenize(createMandateResult: createMandateResult, completion: completion)
return
} else if let url = URL(string: createMandateResult.approvalURL) {
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.success")
self.startAuthenticationSessionWithoutContext(url: url) { success, error in
switch success {
case true:
self.tokenize(createMandateResult: createMandateResult, completion: completion)
return
case false:
completion(nil, error)
return
}
}
} else {
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.failure")
completion(nil, SEPADirectDebitError.approvalURLInvalid)
}
}
}
/// Calls `SEPADirectDebitAPI.createMandate` to create the mandate and returns the `approvalURL` in the `CreateMandateResult`
/// that is used to display the mandate to the user during the web flow.
func createMandate(
request: BTSEPADirectDebitRequest,
completion: @escaping (CreateMandateResult?, Error?) -> Void
) {
apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.create-mandate.requested")
sepaDirectDebitAPI.createMandate(sepaDirectDebitRequest: request) { result, error in
completion(result, error)
}
}
func tokenize(
createMandateResult: CreateMandateResult,
completion: @escaping (BTSEPADirectDebitNonce?, Error?) -> Void
) {
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.tokenize.requested")
self.sepaDirectDebitAPI.tokenize(createMandateResult: createMandateResult) { sepaDirectDebitNonce, error in
guard let sepaDirectDebitNonce = sepaDirectDebitNonce else {
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.tokenize.failure")
completion(nil, error)
return
}
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.tokenize.success")
completion(sepaDirectDebitNonce, nil)
}
}
/// Starts the web authentication session with the `approvalURL` from the `CreateMandateResult` on iOS 12
func startAuthenticationSessionWithoutContext(
url: URL,
completion: @escaping (Bool, Error?) -> Void
) {
apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.web-flow.started")
self.webAuthenticationSession.start(url: url) { url, error in
self.handleWebAuthenticationSessionResult(url: url, error: error, completion: completion)
}
}
/// Starts the web authentication session with the context with the `approvalURL` from the `CreateMandateResult` on iOS 13+
@available(iOS 13.0, *)
func startAuthenticationSession(
url: URL,
context: ASWebAuthenticationPresentationContextProviding,
completion: @escaping (Bool, Error?) -> Void
) {
apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.web-flow.started")
self.webAuthenticationSession.start(url: url, context: context) { url, error in
self.handleWebAuthenticationSessionResult(url: url, error: error, completion: completion)
}
}
/// Handles the result from the web authentication flow when returning to the app. Returns a success result or an error.
func handleWebAuthenticationSessionResult(
url: URL?,
error: Error?,
completion: @escaping (Bool, Error?) -> Void
) {
if let error = error {
switch error {
case ASWebAuthenticationSessionError.canceledLogin:
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.web-flow.canceled")
completion(false, SEPADirectDebitError.webFlowCanceled)
return
default:
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.web-flow.presentation-context-invalid")
completion(false, SEPADirectDebitError.presentationContextInvalid)
return
}
} else if let url = url {
guard url.absoluteString.contains("sepa/success"),
let queryParameter = self.getQueryStringParameter(url: url.absoluteString, param: "success"),
queryParameter.contains("true") else {
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.web-flow.failure")
completion(false, SEPADirectDebitError.resultURLInvalid)
return
}
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.web-flow.success")
completion(true, nil)
} else {
self.apiClient.sendAnalyticsEvent("ios.sepa-direct-debit.web-flow.failure")
completion(false, SEPADirectDebitError.authenticationResultNil)
}
}
private func getQueryStringParameter(url: String, param: String) -> String? {
guard let url = URLComponents(string: url) else { return nil }
return url.queryItems?.first { $0.name == param }?.value
}
}
| mit |
noppoMan/aws-sdk-swift | Sources/Soto/Services/CodePipeline/CodePipeline_Shapes.swift | 1 | 149436 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import Foundation
import SotoCore
extension CodePipeline {
// MARK: Enums
public enum ActionCategory: String, CustomStringConvertible, Codable {
case approval = "Approval"
case build = "Build"
case deploy = "Deploy"
case invoke = "Invoke"
case source = "Source"
case test = "Test"
public var description: String { return self.rawValue }
}
public enum ActionConfigurationPropertyType: String, CustomStringConvertible, Codable {
case boolean = "Boolean"
case number = "Number"
case string = "String"
public var description: String { return self.rawValue }
}
public enum ActionExecutionStatus: String, CustomStringConvertible, Codable {
case abandoned = "Abandoned"
case failed = "Failed"
case inprogress = "InProgress"
case succeeded = "Succeeded"
public var description: String { return self.rawValue }
}
public enum ActionOwner: String, CustomStringConvertible, Codable {
case aws = "AWS"
case custom = "Custom"
case thirdparty = "ThirdParty"
public var description: String { return self.rawValue }
}
public enum ApprovalStatus: String, CustomStringConvertible, Codable {
case approved = "Approved"
case rejected = "Rejected"
public var description: String { return self.rawValue }
}
public enum ArtifactLocationType: String, CustomStringConvertible, Codable {
case s3 = "S3"
public var description: String { return self.rawValue }
}
public enum ArtifactStoreType: String, CustomStringConvertible, Codable {
case s3 = "S3"
public var description: String { return self.rawValue }
}
public enum BlockerType: String, CustomStringConvertible, Codable {
case schedule = "Schedule"
public var description: String { return self.rawValue }
}
public enum EncryptionKeyType: String, CustomStringConvertible, Codable {
case kms = "KMS"
public var description: String { return self.rawValue }
}
public enum FailureType: String, CustomStringConvertible, Codable {
case configurationerror = "ConfigurationError"
case jobfailed = "JobFailed"
case permissionerror = "PermissionError"
case revisionoutofsync = "RevisionOutOfSync"
case revisionunavailable = "RevisionUnavailable"
case systemunavailable = "SystemUnavailable"
public var description: String { return self.rawValue }
}
public enum JobStatus: String, CustomStringConvertible, Codable {
case created = "Created"
case dispatched = "Dispatched"
case failed = "Failed"
case inprogress = "InProgress"
case queued = "Queued"
case succeeded = "Succeeded"
case timedout = "TimedOut"
public var description: String { return self.rawValue }
}
public enum PipelineExecutionStatus: String, CustomStringConvertible, Codable {
case failed = "Failed"
case inprogress = "InProgress"
case stopped = "Stopped"
case stopping = "Stopping"
case succeeded = "Succeeded"
case superseded = "Superseded"
public var description: String { return self.rawValue }
}
public enum StageExecutionStatus: String, CustomStringConvertible, Codable {
case failed = "Failed"
case inprogress = "InProgress"
case stopped = "Stopped"
case stopping = "Stopping"
case succeeded = "Succeeded"
public var description: String { return self.rawValue }
}
public enum StageRetryMode: String, CustomStringConvertible, Codable {
case failedActions = "FAILED_ACTIONS"
public var description: String { return self.rawValue }
}
public enum StageTransitionType: String, CustomStringConvertible, Codable {
case inbound = "Inbound"
case outbound = "Outbound"
public var description: String { return self.rawValue }
}
public enum TriggerType: String, CustomStringConvertible, Codable {
case cloudwatchevent = "CloudWatchEvent"
case createpipeline = "CreatePipeline"
case pollforsourcechanges = "PollForSourceChanges"
case putactionrevision = "PutActionRevision"
case startpipelineexecution = "StartPipelineExecution"
case webhook = "Webhook"
public var description: String { return self.rawValue }
}
public enum WebhookAuthenticationType: String, CustomStringConvertible, Codable {
case githubHmac = "GITHUB_HMAC"
case ip = "IP"
case unauthenticated = "UNAUTHENTICATED"
public var description: String { return self.rawValue }
}
// MARK: Shapes
public struct AWSSessionCredentials: AWSDecodableShape {
/// The access key for the session.
public let accessKeyId: String
/// The secret access key for the session.
public let secretAccessKey: String
/// The token for the session.
public let sessionToken: String
public init(accessKeyId: String, secretAccessKey: String, sessionToken: String) {
self.accessKeyId = accessKeyId
self.secretAccessKey = secretAccessKey
self.sessionToken = sessionToken
}
private enum CodingKeys: String, CodingKey {
case accessKeyId
case secretAccessKey
case sessionToken
}
}
public struct AcknowledgeJobInput: AWSEncodableShape {
/// The unique system-generated ID of the job for which you want to confirm receipt.
public let jobId: String
/// A system-generated random number that AWS CodePipeline uses to ensure that the job is being worked on by only one job worker. Get this number from the response of the PollForJobs request that returned this job.
public let nonce: String
public init(jobId: String, nonce: String) {
self.jobId = jobId
self.nonce = nonce
}
public func validate(name: String) throws {
try self.validate(self.jobId, name: "jobId", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
try self.validate(self.nonce, name: "nonce", parent: name, max: 50)
try self.validate(self.nonce, name: "nonce", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case jobId
case nonce
}
}
public struct AcknowledgeJobOutput: AWSDecodableShape {
/// Whether the job worker has received the specified job.
public let status: JobStatus?
public init(status: JobStatus? = nil) {
self.status = status
}
private enum CodingKeys: String, CodingKey {
case status
}
}
public struct AcknowledgeThirdPartyJobInput: AWSEncodableShape {
/// The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details.
public let clientToken: String
/// The unique system-generated ID of the job.
public let jobId: String
/// A system-generated random number that AWS CodePipeline uses to ensure that the job is being worked on by only one job worker. Get this number from the response to a GetThirdPartyJobDetails request.
public let nonce: String
public init(clientToken: String, jobId: String, nonce: String) {
self.clientToken = clientToken
self.jobId = jobId
self.nonce = nonce
}
public func validate(name: String) throws {
try self.validate(self.clientToken, name: "clientToken", parent: name, max: 256)
try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1)
try self.validate(self.jobId, name: "jobId", parent: name, max: 512)
try self.validate(self.jobId, name: "jobId", parent: name, min: 1)
try self.validate(self.nonce, name: "nonce", parent: name, max: 50)
try self.validate(self.nonce, name: "nonce", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case clientToken
case jobId
case nonce
}
}
public struct AcknowledgeThirdPartyJobOutput: AWSDecodableShape {
/// The status information for the third party job, if any.
public let status: JobStatus?
public init(status: JobStatus? = nil) {
self.status = status
}
private enum CodingKeys: String, CodingKey {
case status
}
}
public struct ActionConfiguration: AWSDecodableShape {
/// The configuration data for the action.
public let configuration: [String: String]?
public init(configuration: [String: String]? = nil) {
self.configuration = configuration
}
private enum CodingKeys: String, CodingKey {
case configuration
}
}
public struct ActionConfigurationProperty: AWSEncodableShape & AWSDecodableShape {
/// The description of the action configuration property that is displayed to users.
public let description: String?
/// Whether the configuration property is a key.
public let key: Bool
/// The name of the action configuration property.
public let name: String
/// Indicates that the property is used with PollForJobs. When creating a custom action, an action can have up to one queryable property. If it has one, that property must be both required and not secret. If you create a pipeline with a custom action type, and that custom action contains a queryable property, the value for that configuration property is subject to other restrictions. The value must be less than or equal to twenty (20) characters. The value can contain only alphanumeric characters, underscores, and hyphens.
public let queryable: Bool?
/// Whether the configuration property is a required value.
public let required: Bool
/// Whether the configuration property is secret. Secrets are hidden from all calls except for GetJobDetails, GetThirdPartyJobDetails, PollForJobs, and PollForThirdPartyJobs. When updating a pipeline, passing * * * * * without changing any other values of the action preserves the previous value of the secret.
public let secret: Bool
/// The type of the configuration property.
public let type: ActionConfigurationPropertyType?
public init(description: String? = nil, key: Bool, name: String, queryable: Bool? = nil, required: Bool, secret: Bool, type: ActionConfigurationPropertyType? = nil) {
self.description = description
self.key = key
self.name = name
self.queryable = queryable
self.required = required
self.secret = secret
self.type = type
}
public func validate(name: String) throws {
try self.validate(self.description, name: "description", parent: name, max: 160)
try self.validate(self.description, name: "description", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, max: 50)
try self.validate(self.name, name: "name", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case description
case key
case name
case queryable
case required
case secret
case type
}
}
public struct ActionContext: AWSDecodableShape {
/// The system-generated unique ID that corresponds to an action's execution.
public let actionExecutionId: String?
/// The name of the action in the context of a job.
public let name: String?
public init(actionExecutionId: String? = nil, name: String? = nil) {
self.actionExecutionId = actionExecutionId
self.name = name
}
private enum CodingKeys: String, CodingKey {
case actionExecutionId
case name
}
}
public struct ActionDeclaration: AWSEncodableShape & AWSDecodableShape {
/// Specifies the action type and the provider of the action.
public let actionTypeId: ActionTypeId
/// The action's configuration. These are key-value pairs that specify input values for an action. For more information, see Action Structure Requirements in CodePipeline. For the list of configuration properties for the AWS CloudFormation action type in CodePipeline, see Configuration Properties Reference in the AWS CloudFormation User Guide. For template snippets with examples, see Using Parameter Override Functions with CodePipeline Pipelines in the AWS CloudFormation User Guide. The values can be represented in either JSON or YAML format. For example, the JSON configuration item format is as follows: JSON: "Configuration" : { Key : Value },
public let configuration: [String: String]?
/// The name or ID of the artifact consumed by the action, such as a test or build artifact.
public let inputArtifacts: [InputArtifact]?
/// The action declaration's name.
public let name: String
/// The variable namespace associated with the action. All variables produced as output by this action fall under this namespace.
public let namespace: String?
/// The name or ID of the result of the action declaration, such as a test or build artifact.
public let outputArtifacts: [OutputArtifact]?
/// The action declaration's AWS Region, such as us-east-1.
public let region: String?
/// The ARN of the IAM service role that performs the declared action. This is assumed through the roleArn for the pipeline.
public let roleArn: String?
/// The order in which actions are run.
public let runOrder: Int?
public init(actionTypeId: ActionTypeId, configuration: [String: String]? = nil, inputArtifacts: [InputArtifact]? = nil, name: String, namespace: String? = nil, outputArtifacts: [OutputArtifact]? = nil, region: String? = nil, roleArn: String? = nil, runOrder: Int? = nil) {
self.actionTypeId = actionTypeId
self.configuration = configuration
self.inputArtifacts = inputArtifacts
self.name = name
self.namespace = namespace
self.outputArtifacts = outputArtifacts
self.region = region
self.roleArn = roleArn
self.runOrder = runOrder
}
public func validate(name: String) throws {
try self.actionTypeId.validate(name: "\(name).actionTypeId")
try self.configuration?.forEach {
try validate($0.key, name: "configuration.key", parent: name, max: 50)
try validate($0.key, name: "configuration.key", parent: name, min: 1)
try validate($0.value, name: "configuration[\"\($0.key)\"]", parent: name, max: 1000)
try validate($0.value, name: "configuration[\"\($0.key)\"]", parent: name, min: 1)
}
try self.inputArtifacts?.forEach {
try $0.validate(name: "\(name).inputArtifacts[]")
}
try self.validate(self.name, name: "name", parent: name, max: 100)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
try self.validate(self.namespace, name: "namespace", parent: name, max: 100)
try self.validate(self.namespace, name: "namespace", parent: name, min: 1)
try self.validate(self.namespace, name: "namespace", parent: name, pattern: "[A-Za-z0-9@\\-_]+")
try self.outputArtifacts?.forEach {
try $0.validate(name: "\(name).outputArtifacts[]")
}
try self.validate(self.region, name: "region", parent: name, max: 30)
try self.validate(self.region, name: "region", parent: name, min: 4)
try self.validate(self.roleArn, name: "roleArn", parent: name, max: 1024)
try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "arn:aws(-[\\w]+)*:iam::[0-9]{12}:role/.*")
try self.validate(self.runOrder, name: "runOrder", parent: name, max: 999)
try self.validate(self.runOrder, name: "runOrder", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case actionTypeId
case configuration
case inputArtifacts
case name
case namespace
case outputArtifacts
case region
case roleArn
case runOrder
}
}
public struct ActionExecution: AWSDecodableShape {
/// The details of an error returned by a URL external to AWS.
public let errorDetails: ErrorDetails?
/// The external ID of the run of the action.
public let externalExecutionId: String?
/// The URL of a resource external to AWS that is used when running the action (for example, an external repository URL).
public let externalExecutionUrl: String?
/// The last status change of the action.
public let lastStatusChange: Date?
/// The ARN of the user who last changed the pipeline.
public let lastUpdatedBy: String?
/// A percentage of completeness of the action as it runs.
public let percentComplete: Int?
/// The status of the action, or for a completed action, the last status of the action.
public let status: ActionExecutionStatus?
/// A summary of the run of the action.
public let summary: String?
/// The system-generated token used to identify a unique approval request. The token for each open approval request can be obtained using the GetPipelineState command. It is used to validate that the approval request corresponding to this token is still valid.
public let token: String?
public init(errorDetails: ErrorDetails? = nil, externalExecutionId: String? = nil, externalExecutionUrl: String? = nil, lastStatusChange: Date? = nil, lastUpdatedBy: String? = nil, percentComplete: Int? = nil, status: ActionExecutionStatus? = nil, summary: String? = nil, token: String? = nil) {
self.errorDetails = errorDetails
self.externalExecutionId = externalExecutionId
self.externalExecutionUrl = externalExecutionUrl
self.lastStatusChange = lastStatusChange
self.lastUpdatedBy = lastUpdatedBy
self.percentComplete = percentComplete
self.status = status
self.summary = summary
self.token = token
}
private enum CodingKeys: String, CodingKey {
case errorDetails
case externalExecutionId
case externalExecutionUrl
case lastStatusChange
case lastUpdatedBy
case percentComplete
case status
case summary
case token
}
}
public struct ActionExecutionDetail: AWSDecodableShape {
/// The action execution ID.
public let actionExecutionId: String?
/// The name of the action.
public let actionName: String?
/// Input details for the action execution, such as role ARN, Region, and input artifacts.
public let input: ActionExecutionInput?
/// The last update time of the action execution.
public let lastUpdateTime: Date?
/// Output details for the action execution, such as the action execution result.
public let output: ActionExecutionOutput?
/// The pipeline execution ID for the action execution.
public let pipelineExecutionId: String?
/// The version of the pipeline where the action was run.
public let pipelineVersion: Int?
/// The name of the stage that contains the action.
public let stageName: String?
/// The start time of the action execution.
public let startTime: Date?
/// The status of the action execution. Status categories are InProgress, Succeeded, and Failed.
public let status: ActionExecutionStatus?
public init(actionExecutionId: String? = nil, actionName: String? = nil, input: ActionExecutionInput? = nil, lastUpdateTime: Date? = nil, output: ActionExecutionOutput? = nil, pipelineExecutionId: String? = nil, pipelineVersion: Int? = nil, stageName: String? = nil, startTime: Date? = nil, status: ActionExecutionStatus? = nil) {
self.actionExecutionId = actionExecutionId
self.actionName = actionName
self.input = input
self.lastUpdateTime = lastUpdateTime
self.output = output
self.pipelineExecutionId = pipelineExecutionId
self.pipelineVersion = pipelineVersion
self.stageName = stageName
self.startTime = startTime
self.status = status
}
private enum CodingKeys: String, CodingKey {
case actionExecutionId
case actionName
case input
case lastUpdateTime
case output
case pipelineExecutionId
case pipelineVersion
case stageName
case startTime
case status
}
}
public struct ActionExecutionFilter: AWSEncodableShape {
/// The pipeline execution ID used to filter action execution history.
public let pipelineExecutionId: String?
public init(pipelineExecutionId: String? = nil) {
self.pipelineExecutionId = pipelineExecutionId
}
public func validate(name: String) throws {
try self.validate(self.pipelineExecutionId, name: "pipelineExecutionId", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
}
private enum CodingKeys: String, CodingKey {
case pipelineExecutionId
}
}
public struct ActionExecutionInput: AWSDecodableShape {
public let actionTypeId: ActionTypeId?
/// Configuration data for an action execution.
public let configuration: [String: String]?
/// Details of input artifacts of the action that correspond to the action execution.
public let inputArtifacts: [ArtifactDetail]?
/// The variable namespace associated with the action. All variables produced as output by this action fall under this namespace.
public let namespace: String?
/// The AWS Region for the action, such as us-east-1.
public let region: String?
/// Configuration data for an action execution with all variable references replaced with their real values for the execution.
public let resolvedConfiguration: [String: String]?
/// The ARN of the IAM service role that performs the declared action. This is assumed through the roleArn for the pipeline.
public let roleArn: String?
public init(actionTypeId: ActionTypeId? = nil, configuration: [String: String]? = nil, inputArtifacts: [ArtifactDetail]? = nil, namespace: String? = nil, region: String? = nil, resolvedConfiguration: [String: String]? = nil, roleArn: String? = nil) {
self.actionTypeId = actionTypeId
self.configuration = configuration
self.inputArtifacts = inputArtifacts
self.namespace = namespace
self.region = region
self.resolvedConfiguration = resolvedConfiguration
self.roleArn = roleArn
}
private enum CodingKeys: String, CodingKey {
case actionTypeId
case configuration
case inputArtifacts
case namespace
case region
case resolvedConfiguration
case roleArn
}
}
public struct ActionExecutionOutput: AWSDecodableShape {
/// Execution result information listed in the output details for an action execution.
public let executionResult: ActionExecutionResult?
/// Details of output artifacts of the action that correspond to the action execution.
public let outputArtifacts: [ArtifactDetail]?
/// The outputVariables field shows the key-value pairs that were output as part of that execution.
public let outputVariables: [String: String]?
public init(executionResult: ActionExecutionResult? = nil, outputArtifacts: [ArtifactDetail]? = nil, outputVariables: [String: String]? = nil) {
self.executionResult = executionResult
self.outputArtifacts = outputArtifacts
self.outputVariables = outputVariables
}
private enum CodingKeys: String, CodingKey {
case executionResult
case outputArtifacts
case outputVariables
}
}
public struct ActionExecutionResult: AWSDecodableShape {
/// The action provider's external ID for the action execution.
public let externalExecutionId: String?
/// The action provider's summary for the action execution.
public let externalExecutionSummary: String?
/// The deepest external link to the external resource (for example, a repository URL or deployment endpoint) that is used when running the action.
public let externalExecutionUrl: String?
public init(externalExecutionId: String? = nil, externalExecutionSummary: String? = nil, externalExecutionUrl: String? = nil) {
self.externalExecutionId = externalExecutionId
self.externalExecutionSummary = externalExecutionSummary
self.externalExecutionUrl = externalExecutionUrl
}
private enum CodingKeys: String, CodingKey {
case externalExecutionId
case externalExecutionSummary
case externalExecutionUrl
}
}
public struct ActionRevision: AWSEncodableShape & AWSDecodableShape {
/// The date and time when the most recent version of the action was created, in timestamp format.
public let created: Date
/// The unique identifier of the change that set the state to this revision (for example, a deployment ID or timestamp).
public let revisionChangeId: String
/// The system-generated unique ID that identifies the revision number of the action.
public let revisionId: String
public init(created: Date, revisionChangeId: String, revisionId: String) {
self.created = created
self.revisionChangeId = revisionChangeId
self.revisionId = revisionId
}
public func validate(name: String) throws {
try self.validate(self.revisionChangeId, name: "revisionChangeId", parent: name, max: 100)
try self.validate(self.revisionChangeId, name: "revisionChangeId", parent: name, min: 1)
try self.validate(self.revisionId, name: "revisionId", parent: name, max: 1500)
try self.validate(self.revisionId, name: "revisionId", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case created
case revisionChangeId
case revisionId
}
}
public struct ActionState: AWSDecodableShape {
/// The name of the action.
public let actionName: String?
/// Represents information about the version (or revision) of an action.
public let currentRevision: ActionRevision?
/// A URL link for more information about the state of the action, such as a deployment group details page.
public let entityUrl: String?
/// Represents information about the run of an action.
public let latestExecution: ActionExecution?
/// A URL link for more information about the revision, such as a commit details page.
public let revisionUrl: String?
public init(actionName: String? = nil, currentRevision: ActionRevision? = nil, entityUrl: String? = nil, latestExecution: ActionExecution? = nil, revisionUrl: String? = nil) {
self.actionName = actionName
self.currentRevision = currentRevision
self.entityUrl = entityUrl
self.latestExecution = latestExecution
self.revisionUrl = revisionUrl
}
private enum CodingKeys: String, CodingKey {
case actionName
case currentRevision
case entityUrl
case latestExecution
case revisionUrl
}
}
public struct ActionType: AWSDecodableShape {
/// The configuration properties for the action type.
public let actionConfigurationProperties: [ActionConfigurationProperty]?
/// Represents information about an action type.
public let id: ActionTypeId
/// The details of the input artifact for the action, such as its commit ID.
public let inputArtifactDetails: ArtifactDetails
/// The details of the output artifact of the action, such as its commit ID.
public let outputArtifactDetails: ArtifactDetails
/// The settings for the action type.
public let settings: ActionTypeSettings?
public init(actionConfigurationProperties: [ActionConfigurationProperty]? = nil, id: ActionTypeId, inputArtifactDetails: ArtifactDetails, outputArtifactDetails: ArtifactDetails, settings: ActionTypeSettings? = nil) {
self.actionConfigurationProperties = actionConfigurationProperties
self.id = id
self.inputArtifactDetails = inputArtifactDetails
self.outputArtifactDetails = outputArtifactDetails
self.settings = settings
}
private enum CodingKeys: String, CodingKey {
case actionConfigurationProperties
case id
case inputArtifactDetails
case outputArtifactDetails
case settings
}
}
public struct ActionTypeId: AWSEncodableShape & AWSDecodableShape {
/// A category defines what kind of action can be taken in the stage, and constrains the provider type for the action. Valid categories are limited to one of the following values.
public let category: ActionCategory
/// The creator of the action being called.
public let owner: ActionOwner
/// The provider of the service being called by the action. Valid providers are determined by the action category. For example, an action in the Deploy category type might have a provider of AWS CodeDeploy, which would be specified as CodeDeploy. For more information, see Valid Action Types and Providers in CodePipeline.
public let provider: String
/// A string that describes the action version.
public let version: String
public init(category: ActionCategory, owner: ActionOwner, provider: String, version: String) {
self.category = category
self.owner = owner
self.provider = provider
self.version = version
}
public func validate(name: String) throws {
try self.validate(self.provider, name: "provider", parent: name, max: 25)
try self.validate(self.provider, name: "provider", parent: name, min: 1)
try self.validate(self.provider, name: "provider", parent: name, pattern: "[0-9A-Za-z_-]+")
try self.validate(self.version, name: "version", parent: name, max: 9)
try self.validate(self.version, name: "version", parent: name, min: 1)
try self.validate(self.version, name: "version", parent: name, pattern: "[0-9A-Za-z_-]+")
}
private enum CodingKeys: String, CodingKey {
case category
case owner
case provider
case version
}
}
public struct ActionTypeSettings: AWSEncodableShape & AWSDecodableShape {
/// The URL returned to the AWS CodePipeline console that provides a deep link to the resources of the external system, such as the configuration page for an AWS CodeDeploy deployment group. This link is provided as part of the action display in the pipeline.
public let entityUrlTemplate: String?
/// The URL returned to the AWS CodePipeline console that contains a link to the top-level landing page for the external system, such as the console page for AWS CodeDeploy. This link is shown on the pipeline view page in the AWS CodePipeline console and provides a link to the execution entity of the external action.
public let executionUrlTemplate: String?
/// The URL returned to the AWS CodePipeline console that contains a link to the page where customers can update or change the configuration of the external action.
public let revisionUrlTemplate: String?
/// The URL of a sign-up page where users can sign up for an external service and perform initial configuration of the action provided by that service.
public let thirdPartyConfigurationUrl: String?
public init(entityUrlTemplate: String? = nil, executionUrlTemplate: String? = nil, revisionUrlTemplate: String? = nil, thirdPartyConfigurationUrl: String? = nil) {
self.entityUrlTemplate = entityUrlTemplate
self.executionUrlTemplate = executionUrlTemplate
self.revisionUrlTemplate = revisionUrlTemplate
self.thirdPartyConfigurationUrl = thirdPartyConfigurationUrl
}
public func validate(name: String) throws {
try self.validate(self.entityUrlTemplate, name: "entityUrlTemplate", parent: name, max: 2048)
try self.validate(self.entityUrlTemplate, name: "entityUrlTemplate", parent: name, min: 1)
try self.validate(self.executionUrlTemplate, name: "executionUrlTemplate", parent: name, max: 2048)
try self.validate(self.executionUrlTemplate, name: "executionUrlTemplate", parent: name, min: 1)
try self.validate(self.revisionUrlTemplate, name: "revisionUrlTemplate", parent: name, max: 2048)
try self.validate(self.revisionUrlTemplate, name: "revisionUrlTemplate", parent: name, min: 1)
try self.validate(self.thirdPartyConfigurationUrl, name: "thirdPartyConfigurationUrl", parent: name, max: 2048)
try self.validate(self.thirdPartyConfigurationUrl, name: "thirdPartyConfigurationUrl", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case entityUrlTemplate
case executionUrlTemplate
case revisionUrlTemplate
case thirdPartyConfigurationUrl
}
}
public struct ApprovalResult: AWSEncodableShape {
/// The response submitted by a reviewer assigned to an approval action request.
public let status: ApprovalStatus
/// The summary of the current status of the approval request.
public let summary: String
public init(status: ApprovalStatus, summary: String) {
self.status = status
self.summary = summary
}
public func validate(name: String) throws {
try self.validate(self.summary, name: "summary", parent: name, max: 512)
try self.validate(self.summary, name: "summary", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case status
case summary
}
}
public struct Artifact: AWSDecodableShape {
/// The location of an artifact.
public let location: ArtifactLocation?
/// The artifact's name.
public let name: String?
/// The artifact's revision ID. Depending on the type of object, this could be a commit ID (GitHub) or a revision ID (Amazon S3).
public let revision: String?
public init(location: ArtifactLocation? = nil, name: String? = nil, revision: String? = nil) {
self.location = location
self.name = name
self.revision = revision
}
private enum CodingKeys: String, CodingKey {
case location
case name
case revision
}
}
public struct ArtifactDetail: AWSDecodableShape {
/// The artifact object name for the action execution.
public let name: String?
/// The Amazon S3 artifact location for the action execution.
public let s3location: S3Location?
public init(name: String? = nil, s3location: S3Location? = nil) {
self.name = name
self.s3location = s3location
}
private enum CodingKeys: String, CodingKey {
case name
case s3location
}
}
public struct ArtifactDetails: AWSEncodableShape & AWSDecodableShape {
/// The maximum number of artifacts allowed for the action type.
public let maximumCount: Int
/// The minimum number of artifacts allowed for the action type.
public let minimumCount: Int
public init(maximumCount: Int, minimumCount: Int) {
self.maximumCount = maximumCount
self.minimumCount = minimumCount
}
public func validate(name: String) throws {
try self.validate(self.maximumCount, name: "maximumCount", parent: name, max: 5)
try self.validate(self.maximumCount, name: "maximumCount", parent: name, min: 0)
try self.validate(self.minimumCount, name: "minimumCount", parent: name, max: 5)
try self.validate(self.minimumCount, name: "minimumCount", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case maximumCount
case minimumCount
}
}
public struct ArtifactLocation: AWSDecodableShape {
/// The S3 bucket that contains the artifact.
public let s3Location: S3ArtifactLocation?
/// The type of artifact in the location.
public let type: ArtifactLocationType?
public init(s3Location: S3ArtifactLocation? = nil, type: ArtifactLocationType? = nil) {
self.s3Location = s3Location
self.type = type
}
private enum CodingKeys: String, CodingKey {
case s3Location
case type
}
}
public struct ArtifactRevision: AWSDecodableShape {
/// The date and time when the most recent revision of the artifact was created, in timestamp format.
public let created: Date?
/// The name of an artifact. This name might be system-generated, such as "MyApp", or defined by the user when an action is created.
public let name: String?
/// An additional identifier for a revision, such as a commit date or, for artifacts stored in Amazon S3 buckets, the ETag value.
public let revisionChangeIdentifier: String?
/// The revision ID of the artifact.
public let revisionId: String?
/// Summary information about the most recent revision of the artifact. For GitHub and AWS CodeCommit repositories, the commit message. For Amazon S3 buckets or actions, the user-provided content of a codepipeline-artifact-revision-summary key specified in the object metadata.
public let revisionSummary: String?
/// The commit ID for the artifact revision. For artifacts stored in GitHub or AWS CodeCommit repositories, the commit ID is linked to a commit details page.
public let revisionUrl: String?
public init(created: Date? = nil, name: String? = nil, revisionChangeIdentifier: String? = nil, revisionId: String? = nil, revisionSummary: String? = nil, revisionUrl: String? = nil) {
self.created = created
self.name = name
self.revisionChangeIdentifier = revisionChangeIdentifier
self.revisionId = revisionId
self.revisionSummary = revisionSummary
self.revisionUrl = revisionUrl
}
private enum CodingKeys: String, CodingKey {
case created
case name
case revisionChangeIdentifier
case revisionId
case revisionSummary
case revisionUrl
}
}
public struct ArtifactStore: AWSEncodableShape & AWSDecodableShape {
/// The encryption key used to encrypt the data in the artifact store, such as an AWS Key Management Service (AWS KMS) key. If this is undefined, the default key for Amazon S3 is used.
public let encryptionKey: EncryptionKey?
/// The S3 bucket used for storing the artifacts for a pipeline. You can specify the name of an S3 bucket but not a folder in the bucket. A folder to contain the pipeline artifacts is created for you based on the name of the pipeline. You can use any S3 bucket in the same AWS Region as the pipeline to store your pipeline artifacts.
public let location: String
/// The type of the artifact store, such as S3.
public let type: ArtifactStoreType
public init(encryptionKey: EncryptionKey? = nil, location: String, type: ArtifactStoreType) {
self.encryptionKey = encryptionKey
self.location = location
self.type = type
}
public func validate(name: String) throws {
try self.encryptionKey?.validate(name: "\(name).encryptionKey")
try self.validate(self.location, name: "location", parent: name, max: 63)
try self.validate(self.location, name: "location", parent: name, min: 3)
try self.validate(self.location, name: "location", parent: name, pattern: "[a-zA-Z0-9\\-\\.]+")
}
private enum CodingKeys: String, CodingKey {
case encryptionKey
case location
case type
}
}
public struct BlockerDeclaration: AWSEncodableShape & AWSDecodableShape {
/// Reserved for future use.
public let name: String
/// Reserved for future use.
public let type: BlockerType
public init(name: String, type: BlockerType) {
self.name = name
self.type = type
}
public func validate(name: String) throws {
try self.validate(self.name, name: "name", parent: name, max: 100)
try self.validate(self.name, name: "name", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case name
case type
}
}
public struct CreateCustomActionTypeInput: AWSEncodableShape {
/// The category of the custom action, such as a build action or a test action. Although Source and Approval are listed as valid values, they are not currently functional. These values are reserved for future use.
public let category: ActionCategory
/// The configuration properties for the custom action. You can refer to a name in the configuration properties of the custom action within the URL templates by following the format of {Config:name}, as long as the configuration property is both required and not secret. For more information, see Create a Custom Action for a Pipeline.
public let configurationProperties: [ActionConfigurationProperty]?
/// The details of the input artifact for the action, such as its commit ID.
public let inputArtifactDetails: ArtifactDetails
/// The details of the output artifact of the action, such as its commit ID.
public let outputArtifactDetails: ArtifactDetails
/// The provider of the service used in the custom action, such as AWS CodeDeploy.
public let provider: String
/// URLs that provide users information about this custom action.
public let settings: ActionTypeSettings?
/// The tags for the custom action.
public let tags: [Tag]?
/// The version identifier of the custom action.
public let version: String
public init(category: ActionCategory, configurationProperties: [ActionConfigurationProperty]? = nil, inputArtifactDetails: ArtifactDetails, outputArtifactDetails: ArtifactDetails, provider: String, settings: ActionTypeSettings? = nil, tags: [Tag]? = nil, version: String) {
self.category = category
self.configurationProperties = configurationProperties
self.inputArtifactDetails = inputArtifactDetails
self.outputArtifactDetails = outputArtifactDetails
self.provider = provider
self.settings = settings
self.tags = tags
self.version = version
}
public func validate(name: String) throws {
try self.configurationProperties?.forEach {
try $0.validate(name: "\(name).configurationProperties[]")
}
try self.validate(self.configurationProperties, name: "configurationProperties", parent: name, max: 10)
try self.inputArtifactDetails.validate(name: "\(name).inputArtifactDetails")
try self.outputArtifactDetails.validate(name: "\(name).outputArtifactDetails")
try self.validate(self.provider, name: "provider", parent: name, max: 25)
try self.validate(self.provider, name: "provider", parent: name, min: 1)
try self.validate(self.provider, name: "provider", parent: name, pattern: "[0-9A-Za-z_-]+")
try self.settings?.validate(name: "\(name).settings")
try self.tags?.forEach {
try $0.validate(name: "\(name).tags[]")
}
try self.validate(self.version, name: "version", parent: name, max: 9)
try self.validate(self.version, name: "version", parent: name, min: 1)
try self.validate(self.version, name: "version", parent: name, pattern: "[0-9A-Za-z_-]+")
}
private enum CodingKeys: String, CodingKey {
case category
case configurationProperties
case inputArtifactDetails
case outputArtifactDetails
case provider
case settings
case tags
case version
}
}
public struct CreateCustomActionTypeOutput: AWSDecodableShape {
/// Returns information about the details of an action type.
public let actionType: ActionType
/// Specifies the tags applied to the custom action.
public let tags: [Tag]?
public init(actionType: ActionType, tags: [Tag]? = nil) {
self.actionType = actionType
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case actionType
case tags
}
}
public struct CreatePipelineInput: AWSEncodableShape {
/// Represents the structure of actions and stages to be performed in the pipeline.
public let pipeline: PipelineDeclaration
/// The tags for the pipeline.
public let tags: [Tag]?
public init(pipeline: PipelineDeclaration, tags: [Tag]? = nil) {
self.pipeline = pipeline
self.tags = tags
}
public func validate(name: String) throws {
try self.pipeline.validate(name: "\(name).pipeline")
try self.tags?.forEach {
try $0.validate(name: "\(name).tags[]")
}
}
private enum CodingKeys: String, CodingKey {
case pipeline
case tags
}
}
public struct CreatePipelineOutput: AWSDecodableShape {
/// Represents the structure of actions and stages to be performed in the pipeline.
public let pipeline: PipelineDeclaration?
/// Specifies the tags applied to the pipeline.
public let tags: [Tag]?
public init(pipeline: PipelineDeclaration? = nil, tags: [Tag]? = nil) {
self.pipeline = pipeline
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case pipeline
case tags
}
}
public struct CurrentRevision: AWSEncodableShape {
/// The change identifier for the current revision.
public let changeIdentifier: String
/// The date and time when the most recent revision of the artifact was created, in timestamp format.
public let created: Date?
/// The revision ID of the current version of an artifact.
public let revision: String
/// The summary of the most recent revision of the artifact.
public let revisionSummary: String?
public init(changeIdentifier: String, created: Date? = nil, revision: String, revisionSummary: String? = nil) {
self.changeIdentifier = changeIdentifier
self.created = created
self.revision = revision
self.revisionSummary = revisionSummary
}
public func validate(name: String) throws {
try self.validate(self.changeIdentifier, name: "changeIdentifier", parent: name, max: 100)
try self.validate(self.changeIdentifier, name: "changeIdentifier", parent: name, min: 1)
try self.validate(self.revision, name: "revision", parent: name, max: 1500)
try self.validate(self.revision, name: "revision", parent: name, min: 1)
try self.validate(self.revisionSummary, name: "revisionSummary", parent: name, max: 2048)
try self.validate(self.revisionSummary, name: "revisionSummary", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case changeIdentifier
case created
case revision
case revisionSummary
}
}
public struct DeleteCustomActionTypeInput: AWSEncodableShape {
/// The category of the custom action that you want to delete, such as source or deploy.
public let category: ActionCategory
/// The provider of the service used in the custom action, such as AWS CodeDeploy.
public let provider: String
/// The version of the custom action to delete.
public let version: String
public init(category: ActionCategory, provider: String, version: String) {
self.category = category
self.provider = provider
self.version = version
}
public func validate(name: String) throws {
try self.validate(self.provider, name: "provider", parent: name, max: 25)
try self.validate(self.provider, name: "provider", parent: name, min: 1)
try self.validate(self.provider, name: "provider", parent: name, pattern: "[0-9A-Za-z_-]+")
try self.validate(self.version, name: "version", parent: name, max: 9)
try self.validate(self.version, name: "version", parent: name, min: 1)
try self.validate(self.version, name: "version", parent: name, pattern: "[0-9A-Za-z_-]+")
}
private enum CodingKeys: String, CodingKey {
case category
case provider
case version
}
}
public struct DeletePipelineInput: AWSEncodableShape {
/// The name of the pipeline to be deleted.
public let name: String
public init(name: String) {
self.name = name
}
public func validate(name: String) throws {
try self.validate(self.name, name: "name", parent: name, max: 100)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
}
private enum CodingKeys: String, CodingKey {
case name
}
}
public struct DeleteWebhookInput: AWSEncodableShape {
/// The name of the webhook you want to delete.
public let name: String
public init(name: String) {
self.name = name
}
public func validate(name: String) throws {
try self.validate(self.name, name: "name", parent: name, max: 100)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
}
private enum CodingKeys: String, CodingKey {
case name
}
}
public struct DeleteWebhookOutput: AWSDecodableShape {
public init() {}
}
public struct DeregisterWebhookWithThirdPartyInput: AWSEncodableShape {
/// The name of the webhook you want to deregister.
public let webhookName: String?
public init(webhookName: String? = nil) {
self.webhookName = webhookName
}
public func validate(name: String) throws {
try self.validate(self.webhookName, name: "webhookName", parent: name, max: 100)
try self.validate(self.webhookName, name: "webhookName", parent: name, min: 1)
try self.validate(self.webhookName, name: "webhookName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
}
private enum CodingKeys: String, CodingKey {
case webhookName
}
}
public struct DeregisterWebhookWithThirdPartyOutput: AWSDecodableShape {
public init() {}
}
public struct DisableStageTransitionInput: AWSEncodableShape {
/// The name of the pipeline in which you want to disable the flow of artifacts from one stage to another.
public let pipelineName: String
/// The reason given to the user that a stage is disabled, such as waiting for manual approval or manual tests. This message is displayed in the pipeline console UI.
public let reason: String
/// The name of the stage where you want to disable the inbound or outbound transition of artifacts.
public let stageName: String
/// Specifies whether artifacts are prevented from transitioning into the stage and being processed by the actions in that stage (inbound), or prevented from transitioning from the stage after they have been processed by the actions in that stage (outbound).
public let transitionType: StageTransitionType
public init(pipelineName: String, reason: String, stageName: String, transitionType: StageTransitionType) {
self.pipelineName = pipelineName
self.reason = reason
self.stageName = stageName
self.transitionType = transitionType
}
public func validate(name: String) throws {
try self.validate(self.pipelineName, name: "pipelineName", parent: name, max: 100)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, min: 1)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
try self.validate(self.reason, name: "reason", parent: name, max: 300)
try self.validate(self.reason, name: "reason", parent: name, min: 1)
try self.validate(self.reason, name: "reason", parent: name, pattern: "[a-zA-Z0-9!@ \\(\\)\\.\\*\\?\\-]+")
try self.validate(self.stageName, name: "stageName", parent: name, max: 100)
try self.validate(self.stageName, name: "stageName", parent: name, min: 1)
try self.validate(self.stageName, name: "stageName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
}
private enum CodingKeys: String, CodingKey {
case pipelineName
case reason
case stageName
case transitionType
}
}
public struct EnableStageTransitionInput: AWSEncodableShape {
/// The name of the pipeline in which you want to enable the flow of artifacts from one stage to another.
public let pipelineName: String
/// The name of the stage where you want to enable the transition of artifacts, either into the stage (inbound) or from that stage to the next stage (outbound).
public let stageName: String
/// Specifies whether artifacts are allowed to enter the stage and be processed by the actions in that stage (inbound) or whether already processed artifacts are allowed to transition to the next stage (outbound).
public let transitionType: StageTransitionType
public init(pipelineName: String, stageName: String, transitionType: StageTransitionType) {
self.pipelineName = pipelineName
self.stageName = stageName
self.transitionType = transitionType
}
public func validate(name: String) throws {
try self.validate(self.pipelineName, name: "pipelineName", parent: name, max: 100)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, min: 1)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
try self.validate(self.stageName, name: "stageName", parent: name, max: 100)
try self.validate(self.stageName, name: "stageName", parent: name, min: 1)
try self.validate(self.stageName, name: "stageName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
}
private enum CodingKeys: String, CodingKey {
case pipelineName
case stageName
case transitionType
}
}
public struct EncryptionKey: AWSEncodableShape & AWSDecodableShape {
/// The ID used to identify the key. For an AWS KMS key, you can use the key ID, the key ARN, or the alias ARN. Aliases are recognized only in the account that created the customer master key (CMK). For cross-account actions, you can only use the key ID or key ARN to identify the key.
public let id: String
/// The type of encryption key, such as an AWS Key Management Service (AWS KMS) key. When creating or updating a pipeline, the value must be set to 'KMS'.
public let type: EncryptionKeyType
public init(id: String, type: EncryptionKeyType) {
self.id = id
self.type = type
}
public func validate(name: String) throws {
try self.validate(self.id, name: "id", parent: name, max: 100)
try self.validate(self.id, name: "id", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case id
case type
}
}
public struct ErrorDetails: AWSDecodableShape {
/// The system ID or number code of the error.
public let code: String?
/// The text of the error message.
public let message: String?
public init(code: String? = nil, message: String? = nil) {
self.code = code
self.message = message
}
private enum CodingKeys: String, CodingKey {
case code
case message
}
}
public struct ExecutionDetails: AWSEncodableShape {
/// The system-generated unique ID of this action used to identify this job worker in any external systems, such as AWS CodeDeploy.
public let externalExecutionId: String?
/// The percentage of work completed on the action, represented on a scale of 0 to 100 percent.
public let percentComplete: Int?
/// The summary of the current status of the actions.
public let summary: String?
public init(externalExecutionId: String? = nil, percentComplete: Int? = nil, summary: String? = nil) {
self.externalExecutionId = externalExecutionId
self.percentComplete = percentComplete
self.summary = summary
}
public func validate(name: String) throws {
try self.validate(self.externalExecutionId, name: "externalExecutionId", parent: name, max: 1500)
try self.validate(self.externalExecutionId, name: "externalExecutionId", parent: name, min: 1)
try self.validate(self.percentComplete, name: "percentComplete", parent: name, max: 100)
try self.validate(self.percentComplete, name: "percentComplete", parent: name, min: 0)
try self.validate(self.summary, name: "summary", parent: name, max: 2048)
try self.validate(self.summary, name: "summary", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case externalExecutionId
case percentComplete
case summary
}
}
public struct ExecutionTrigger: AWSDecodableShape {
/// Detail related to the event that started a pipeline execution, such as the webhook ARN of the webhook that triggered the pipeline execution or the user ARN for a user-initiated start-pipeline-execution CLI command.
public let triggerDetail: String?
/// The type of change-detection method, command, or user interaction that started a pipeline execution.
public let triggerType: TriggerType?
public init(triggerDetail: String? = nil, triggerType: TriggerType? = nil) {
self.triggerDetail = triggerDetail
self.triggerType = triggerType
}
private enum CodingKeys: String, CodingKey {
case triggerDetail
case triggerType
}
}
public struct FailureDetails: AWSEncodableShape {
/// The external ID of the run of the action that failed.
public let externalExecutionId: String?
/// The message about the failure.
public let message: String
/// The type of the failure.
public let type: FailureType
public init(externalExecutionId: String? = nil, message: String, type: FailureType) {
self.externalExecutionId = externalExecutionId
self.message = message
self.type = type
}
public func validate(name: String) throws {
try self.validate(self.externalExecutionId, name: "externalExecutionId", parent: name, max: 1500)
try self.validate(self.externalExecutionId, name: "externalExecutionId", parent: name, min: 1)
try self.validate(self.message, name: "message", parent: name, max: 5000)
try self.validate(self.message, name: "message", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case externalExecutionId
case message
case type
}
}
public struct GetJobDetailsInput: AWSEncodableShape {
/// The unique system-generated ID for the job.
public let jobId: String
public init(jobId: String) {
self.jobId = jobId
}
public func validate(name: String) throws {
try self.validate(self.jobId, name: "jobId", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
}
private enum CodingKeys: String, CodingKey {
case jobId
}
}
public struct GetJobDetailsOutput: AWSDecodableShape {
/// The details of the job. If AWSSessionCredentials is used, a long-running job can call GetJobDetails again to obtain new credentials.
public let jobDetails: JobDetails?
public init(jobDetails: JobDetails? = nil) {
self.jobDetails = jobDetails
}
private enum CodingKeys: String, CodingKey {
case jobDetails
}
}
public struct GetPipelineExecutionInput: AWSEncodableShape {
/// The ID of the pipeline execution about which you want to get execution details.
public let pipelineExecutionId: String
/// The name of the pipeline about which you want to get execution details.
public let pipelineName: String
public init(pipelineExecutionId: String, pipelineName: String) {
self.pipelineExecutionId = pipelineExecutionId
self.pipelineName = pipelineName
}
public func validate(name: String) throws {
try self.validate(self.pipelineExecutionId, name: "pipelineExecutionId", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
try self.validate(self.pipelineName, name: "pipelineName", parent: name, max: 100)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, min: 1)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
}
private enum CodingKeys: String, CodingKey {
case pipelineExecutionId
case pipelineName
}
}
public struct GetPipelineExecutionOutput: AWSDecodableShape {
/// Represents information about the execution of a pipeline.
public let pipelineExecution: PipelineExecution?
public init(pipelineExecution: PipelineExecution? = nil) {
self.pipelineExecution = pipelineExecution
}
private enum CodingKeys: String, CodingKey {
case pipelineExecution
}
}
public struct GetPipelineInput: AWSEncodableShape {
/// The name of the pipeline for which you want to get information. Pipeline names must be unique under an AWS user account.
public let name: String
/// The version number of the pipeline. If you do not specify a version, defaults to the current version.
public let version: Int?
public init(name: String, version: Int? = nil) {
self.name = name
self.version = version
}
public func validate(name: String) throws {
try self.validate(self.name, name: "name", parent: name, max: 100)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
try self.validate(self.version, name: "version", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case name
case version
}
}
public struct GetPipelineOutput: AWSDecodableShape {
/// Represents the pipeline metadata information returned as part of the output of a GetPipeline action.
public let metadata: PipelineMetadata?
/// Represents the structure of actions and stages to be performed in the pipeline.
public let pipeline: PipelineDeclaration?
public init(metadata: PipelineMetadata? = nil, pipeline: PipelineDeclaration? = nil) {
self.metadata = metadata
self.pipeline = pipeline
}
private enum CodingKeys: String, CodingKey {
case metadata
case pipeline
}
}
public struct GetPipelineStateInput: AWSEncodableShape {
/// The name of the pipeline about which you want to get information.
public let name: String
public init(name: String) {
self.name = name
}
public func validate(name: String) throws {
try self.validate(self.name, name: "name", parent: name, max: 100)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
}
private enum CodingKeys: String, CodingKey {
case name
}
}
public struct GetPipelineStateOutput: AWSDecodableShape {
/// The date and time the pipeline was created, in timestamp format.
public let created: Date?
/// The name of the pipeline for which you want to get the state.
public let pipelineName: String?
/// The version number of the pipeline. A newly created pipeline is always assigned a version number of 1.
public let pipelineVersion: Int?
/// A list of the pipeline stage output information, including stage name, state, most recent run details, whether the stage is disabled, and other data.
public let stageStates: [StageState]?
/// The date and time the pipeline was last updated, in timestamp format.
public let updated: Date?
public init(created: Date? = nil, pipelineName: String? = nil, pipelineVersion: Int? = nil, stageStates: [StageState]? = nil, updated: Date? = nil) {
self.created = created
self.pipelineName = pipelineName
self.pipelineVersion = pipelineVersion
self.stageStates = stageStates
self.updated = updated
}
private enum CodingKeys: String, CodingKey {
case created
case pipelineName
case pipelineVersion
case stageStates
case updated
}
}
public struct GetThirdPartyJobDetailsInput: AWSEncodableShape {
/// The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details.
public let clientToken: String
/// The unique system-generated ID used for identifying the job.
public let jobId: String
public init(clientToken: String, jobId: String) {
self.clientToken = clientToken
self.jobId = jobId
}
public func validate(name: String) throws {
try self.validate(self.clientToken, name: "clientToken", parent: name, max: 256)
try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1)
try self.validate(self.jobId, name: "jobId", parent: name, max: 512)
try self.validate(self.jobId, name: "jobId", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case clientToken
case jobId
}
}
public struct GetThirdPartyJobDetailsOutput: AWSDecodableShape {
/// The details of the job, including any protected values defined for the job.
public let jobDetails: ThirdPartyJobDetails?
public init(jobDetails: ThirdPartyJobDetails? = nil) {
self.jobDetails = jobDetails
}
private enum CodingKeys: String, CodingKey {
case jobDetails
}
}
public struct InputArtifact: AWSEncodableShape & AWSDecodableShape {
/// The name of the artifact to be worked on (for example, "My App"). The input artifact of an action must exactly match the output artifact declared in a preceding action, but the input artifact does not have to be the next action in strict sequence from the action that provided the output artifact. Actions in parallel can declare different output artifacts, which are in turn consumed by different following actions.
public let name: String
public init(name: String) {
self.name = name
}
public func validate(name: String) throws {
try self.validate(self.name, name: "name", parent: name, max: 100)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[a-zA-Z0-9_\\-]+")
}
private enum CodingKeys: String, CodingKey {
case name
}
}
public struct Job: AWSDecodableShape {
/// The ID of the AWS account to use when performing the job.
public let accountId: String?
/// Other data about a job.
public let data: JobData?
/// The unique system-generated ID of the job.
public let id: String?
/// A system-generated random number that AWS CodePipeline uses to ensure that the job is being worked on by only one job worker. Use this number in an AcknowledgeJob request.
public let nonce: String?
public init(accountId: String? = nil, data: JobData? = nil, id: String? = nil, nonce: String? = nil) {
self.accountId = accountId
self.data = data
self.id = id
self.nonce = nonce
}
private enum CodingKeys: String, CodingKey {
case accountId
case data
case id
case nonce
}
}
public struct JobData: AWSDecodableShape {
/// Represents information about an action configuration.
public let actionConfiguration: ActionConfiguration?
/// Represents information about an action type.
public let actionTypeId: ActionTypeId?
/// Represents an AWS session credentials object. These credentials are temporary credentials that are issued by AWS Secure Token Service (STS). They can be used to access input and output artifacts in the S3 bucket used to store artifacts for the pipeline in AWS CodePipeline.
public let artifactCredentials: AWSSessionCredentials?
/// A system-generated token, such as a AWS CodeDeploy deployment ID, required by a job to continue the job asynchronously.
public let continuationToken: String?
/// Represents information about the key used to encrypt data in the artifact store, such as an AWS Key Management Service (AWS KMS) key.
public let encryptionKey: EncryptionKey?
/// The artifact supplied to the job.
public let inputArtifacts: [Artifact]?
/// The output of the job.
public let outputArtifacts: [Artifact]?
/// Represents information about a pipeline to a job worker. Includes pipelineArn and pipelineExecutionId for custom jobs.
public let pipelineContext: PipelineContext?
public init(actionConfiguration: ActionConfiguration? = nil, actionTypeId: ActionTypeId? = nil, artifactCredentials: AWSSessionCredentials? = nil, continuationToken: String? = nil, encryptionKey: EncryptionKey? = nil, inputArtifacts: [Artifact]? = nil, outputArtifacts: [Artifact]? = nil, pipelineContext: PipelineContext? = nil) {
self.actionConfiguration = actionConfiguration
self.actionTypeId = actionTypeId
self.artifactCredentials = artifactCredentials
self.continuationToken = continuationToken
self.encryptionKey = encryptionKey
self.inputArtifacts = inputArtifacts
self.outputArtifacts = outputArtifacts
self.pipelineContext = pipelineContext
}
private enum CodingKeys: String, CodingKey {
case actionConfiguration
case actionTypeId
case artifactCredentials
case continuationToken
case encryptionKey
case inputArtifacts
case outputArtifacts
case pipelineContext
}
}
public struct JobDetails: AWSDecodableShape {
/// The AWS account ID associated with the job.
public let accountId: String?
/// Represents other information about a job required for a job worker to complete the job.
public let data: JobData?
/// The unique system-generated ID of the job.
public let id: String?
public init(accountId: String? = nil, data: JobData? = nil, id: String? = nil) {
self.accountId = accountId
self.data = data
self.id = id
}
private enum CodingKeys: String, CodingKey {
case accountId
case data
case id
}
}
public struct ListActionExecutionsInput: AWSEncodableShape {
/// Input information used to filter action execution history.
public let filter: ActionExecutionFilter?
/// The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned nextToken value. Action execution history is retained for up to 12 months, based on action execution start times. Default value is 100. Detailed execution history is available for executions run on or after February 21, 2019.
public let maxResults: Int?
/// The token that was returned from the previous ListActionExecutions call, which can be used to return the next set of action executions in the list.
public let nextToken: String?
/// The name of the pipeline for which you want to list action execution history.
public let pipelineName: String
public init(filter: ActionExecutionFilter? = nil, maxResults: Int? = nil, nextToken: String? = nil, pipelineName: String) {
self.filter = filter
self.maxResults = maxResults
self.nextToken = nextToken
self.pipelineName = pipelineName
}
public func validate(name: String) throws {
try self.filter?.validate(name: "\(name).filter")
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2048)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, max: 100)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, min: 1)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
}
private enum CodingKeys: String, CodingKey {
case filter
case maxResults
case nextToken
case pipelineName
}
}
public struct ListActionExecutionsOutput: AWSDecodableShape {
/// The details for a list of recent executions, such as action execution ID.
public let actionExecutionDetails: [ActionExecutionDetail]?
/// If the amount of returned information is significantly large, an identifier is also returned and can be used in a subsequent ListActionExecutions call to return the next set of action executions in the list.
public let nextToken: String?
public init(actionExecutionDetails: [ActionExecutionDetail]? = nil, nextToken: String? = nil) {
self.actionExecutionDetails = actionExecutionDetails
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case actionExecutionDetails
case nextToken
}
}
public struct ListActionTypesInput: AWSEncodableShape {
/// Filters the list of action types to those created by a specified entity.
public let actionOwnerFilter: ActionOwner?
/// An identifier that was returned from the previous list action types call, which can be used to return the next set of action types in the list.
public let nextToken: String?
public init(actionOwnerFilter: ActionOwner? = nil, nextToken: String? = nil) {
self.actionOwnerFilter = actionOwnerFilter
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2048)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case actionOwnerFilter
case nextToken
}
}
public struct ListActionTypesOutput: AWSDecodableShape {
/// Provides details of the action types.
public let actionTypes: [ActionType]
/// If the amount of returned information is significantly large, an identifier is also returned. It can be used in a subsequent list action types call to return the next set of action types in the list.
public let nextToken: String?
public init(actionTypes: [ActionType], nextToken: String? = nil) {
self.actionTypes = actionTypes
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case actionTypes
case nextToken
}
}
public struct ListPipelineExecutionsInput: AWSEncodableShape {
/// The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned nextToken value. Pipeline history is limited to the most recent 12 months, based on pipeline execution start times. Default value is 100.
public let maxResults: Int?
/// The token that was returned from the previous ListPipelineExecutions call, which can be used to return the next set of pipeline executions in the list.
public let nextToken: String?
/// The name of the pipeline for which you want to get execution summary information.
public let pipelineName: String
public init(maxResults: Int? = nil, nextToken: String? = nil, pipelineName: String) {
self.maxResults = maxResults
self.nextToken = nextToken
self.pipelineName = pipelineName
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2048)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, max: 100)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, min: 1)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
}
private enum CodingKeys: String, CodingKey {
case maxResults
case nextToken
case pipelineName
}
}
public struct ListPipelineExecutionsOutput: AWSDecodableShape {
/// A token that can be used in the next ListPipelineExecutions call. To view all items in the list, continue to call this operation with each subsequent token until no more nextToken values are returned.
public let nextToken: String?
/// A list of executions in the history of a pipeline.
public let pipelineExecutionSummaries: [PipelineExecutionSummary]?
public init(nextToken: String? = nil, pipelineExecutionSummaries: [PipelineExecutionSummary]? = nil) {
self.nextToken = nextToken
self.pipelineExecutionSummaries = pipelineExecutionSummaries
}
private enum CodingKeys: String, CodingKey {
case nextToken
case pipelineExecutionSummaries
}
}
public struct ListPipelinesInput: AWSEncodableShape {
/// An identifier that was returned from the previous list pipelines call. It can be used to return the next set of pipelines in the list.
public let nextToken: String?
public init(nextToken: String? = nil) {
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2048)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case nextToken
}
}
public struct ListPipelinesOutput: AWSDecodableShape {
/// If the amount of returned information is significantly large, an identifier is also returned. It can be used in a subsequent list pipelines call to return the next set of pipelines in the list.
public let nextToken: String?
/// The list of pipelines.
public let pipelines: [PipelineSummary]?
public init(nextToken: String? = nil, pipelines: [PipelineSummary]? = nil) {
self.nextToken = nextToken
self.pipelines = pipelines
}
private enum CodingKeys: String, CodingKey {
case nextToken
case pipelines
}
}
public struct ListTagsForResourceInput: AWSEncodableShape {
/// The maximum number of results to return in a single call.
public let maxResults: Int?
/// The token that was returned from the previous API call, which would be used to return the next page of the list. The ListTagsforResource call lists all available tags in one call and does not use pagination.
public let nextToken: String?
/// The Amazon Resource Name (ARN) of the resource to get tags for.
public let resourceArn: String
public init(maxResults: Int? = nil, nextToken: String? = nil, resourceArn: String) {
self.maxResults = maxResults
self.nextToken = nextToken
self.resourceArn = resourceArn
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2048)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.resourceArn, name: "resourceArn", parent: name, pattern: "arn:aws(-[\\w]+)*:codepipeline:.+:[0-9]{12}:.+")
}
private enum CodingKeys: String, CodingKey {
case maxResults
case nextToken
case resourceArn
}
}
public struct ListTagsForResourceOutput: AWSDecodableShape {
/// If the amount of returned information is significantly large, an identifier is also returned and can be used in a subsequent API call to return the next page of the list. The ListTagsforResource call lists all available tags in one call and does not use pagination.
public let nextToken: String?
/// The tags for the resource.
public let tags: [Tag]?
public init(nextToken: String? = nil, tags: [Tag]? = nil) {
self.nextToken = nextToken
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case nextToken
case tags
}
}
public struct ListWebhookItem: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the webhook.
public let arn: String?
/// The detail returned for each webhook, such as the webhook authentication type and filter rules.
public let definition: WebhookDefinition
/// The number code of the error.
public let errorCode: String?
/// The text of the error message about the webhook.
public let errorMessage: String?
/// The date and time a webhook was last successfully triggered, in timestamp format.
public let lastTriggered: Date?
/// Specifies the tags applied to the webhook.
public let tags: [Tag]?
/// A unique URL generated by CodePipeline. When a POST request is made to this URL, the defined pipeline is started as long as the body of the post request satisfies the defined authentication and filtering conditions. Deleting and re-creating a webhook makes the old URL invalid and generates a new one.
public let url: String
public init(arn: String? = nil, definition: WebhookDefinition, errorCode: String? = nil, errorMessage: String? = nil, lastTriggered: Date? = nil, tags: [Tag]? = nil, url: String) {
self.arn = arn
self.definition = definition
self.errorCode = errorCode
self.errorMessage = errorMessage
self.lastTriggered = lastTriggered
self.tags = tags
self.url = url
}
private enum CodingKeys: String, CodingKey {
case arn
case definition
case errorCode
case errorMessage
case lastTriggered
case tags
case url
}
}
public struct ListWebhooksInput: AWSEncodableShape {
/// The maximum number of results to return in a single call. To retrieve the remaining results, make another call with the returned nextToken value.
public let maxResults: Int?
/// The token that was returned from the previous ListWebhooks call, which can be used to return the next set of webhooks in the list.
public let nextToken: String?
public init(maxResults: Int? = nil, nextToken: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 2048)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case maxResults = "MaxResults"
case nextToken = "NextToken"
}
}
public struct ListWebhooksOutput: AWSDecodableShape {
/// If the amount of returned information is significantly large, an identifier is also returned and can be used in a subsequent ListWebhooks call to return the next set of webhooks in the list.
public let nextToken: String?
/// The JSON detail returned for each webhook in the list output for the ListWebhooks call.
public let webhooks: [ListWebhookItem]?
public init(nextToken: String? = nil, webhooks: [ListWebhookItem]? = nil) {
self.nextToken = nextToken
self.webhooks = webhooks
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case webhooks
}
}
public struct OutputArtifact: AWSEncodableShape & AWSDecodableShape {
/// The name of the output of an artifact, such as "My App". The input artifact of an action must exactly match the output artifact declared in a preceding action, but the input artifact does not have to be the next action in strict sequence from the action that provided the output artifact. Actions in parallel can declare different output artifacts, which are in turn consumed by different following actions. Output artifact names must be unique within a pipeline.
public let name: String
public init(name: String) {
self.name = name
}
public func validate(name: String) throws {
try self.validate(self.name, name: "name", parent: name, max: 100)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[a-zA-Z0-9_\\-]+")
}
private enum CodingKeys: String, CodingKey {
case name
}
}
public struct PipelineContext: AWSDecodableShape {
/// The context of an action to a job worker in the stage of a pipeline.
public let action: ActionContext?
/// The Amazon Resource Name (ARN) of the pipeline.
public let pipelineArn: String?
/// The execution ID of the pipeline.
public let pipelineExecutionId: String?
/// The name of the pipeline. This is a user-specified value. Pipeline names must be unique across all pipeline names under an Amazon Web Services account.
public let pipelineName: String?
/// The stage of the pipeline.
public let stage: StageContext?
public init(action: ActionContext? = nil, pipelineArn: String? = nil, pipelineExecutionId: String? = nil, pipelineName: String? = nil, stage: StageContext? = nil) {
self.action = action
self.pipelineArn = pipelineArn
self.pipelineExecutionId = pipelineExecutionId
self.pipelineName = pipelineName
self.stage = stage
}
private enum CodingKeys: String, CodingKey {
case action
case pipelineArn
case pipelineExecutionId
case pipelineName
case stage
}
}
public struct PipelineDeclaration: AWSEncodableShape & AWSDecodableShape {
/// Represents information about the S3 bucket where artifacts are stored for the pipeline. You must include either artifactStore or artifactStores in your pipeline, but you cannot use both. If you create a cross-region action in your pipeline, you must use artifactStores.
public let artifactStore: ArtifactStore?
/// A mapping of artifactStore objects and their corresponding AWS Regions. There must be an artifact store for the pipeline Region and for each cross-region action in the pipeline. You must include either artifactStore or artifactStores in your pipeline, but you cannot use both. If you create a cross-region action in your pipeline, you must use artifactStores.
public let artifactStores: [String: ArtifactStore]?
/// The name of the action to be performed.
public let name: String
/// The Amazon Resource Name (ARN) for AWS CodePipeline to use to either perform actions with no actionRoleArn, or to use to assume roles for actions with an actionRoleArn.
public let roleArn: String
/// The stage in which to perform the action.
public let stages: [StageDeclaration]
/// The version number of the pipeline. A new pipeline always has a version number of 1. This number is incremented when a pipeline is updated.
public let version: Int?
public init(artifactStore: ArtifactStore? = nil, artifactStores: [String: ArtifactStore]? = nil, name: String, roleArn: String, stages: [StageDeclaration], version: Int? = nil) {
self.artifactStore = artifactStore
self.artifactStores = artifactStores
self.name = name
self.roleArn = roleArn
self.stages = stages
self.version = version
}
public func validate(name: String) throws {
try self.artifactStore?.validate(name: "\(name).artifactStore")
try self.artifactStores?.forEach {
try validate($0.key, name: "artifactStores.key", parent: name, max: 30)
try validate($0.key, name: "artifactStores.key", parent: name, min: 4)
try $0.value.validate(name: "\(name).artifactStores[\"\($0.key)\"]")
}
try self.validate(self.name, name: "name", parent: name, max: 100)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
try self.validate(self.roleArn, name: "roleArn", parent: name, max: 1024)
try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "arn:aws(-[\\w]+)*:iam::[0-9]{12}:role/.*")
try self.stages.forEach {
try $0.validate(name: "\(name).stages[]")
}
try self.validate(self.version, name: "version", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case artifactStore
case artifactStores
case name
case roleArn
case stages
case version
}
}
public struct PipelineExecution: AWSDecodableShape {
/// A list of ArtifactRevision objects included in a pipeline execution.
public let artifactRevisions: [ArtifactRevision]?
/// The ID of the pipeline execution.
public let pipelineExecutionId: String?
/// The name of the pipeline with the specified pipeline execution.
public let pipelineName: String?
/// The version number of the pipeline with the specified pipeline execution.
public let pipelineVersion: Int?
/// The status of the pipeline execution. InProgress: The pipeline execution is currently running. Stopped: The pipeline execution was manually stopped. For more information, see Stopped Executions. Stopping: The pipeline execution received a request to be manually stopped. Depending on the selected stop mode, the execution is either completing or abandoning in-progress actions. For more information, see Stopped Executions. Succeeded: The pipeline execution was completed successfully. Superseded: While this pipeline execution was waiting for the next stage to be completed, a newer pipeline execution advanced and continued through the pipeline instead. For more information, see Superseded Executions. Failed: The pipeline execution was not completed successfully.
public let status: PipelineExecutionStatus?
public init(artifactRevisions: [ArtifactRevision]? = nil, pipelineExecutionId: String? = nil, pipelineName: String? = nil, pipelineVersion: Int? = nil, status: PipelineExecutionStatus? = nil) {
self.artifactRevisions = artifactRevisions
self.pipelineExecutionId = pipelineExecutionId
self.pipelineName = pipelineName
self.pipelineVersion = pipelineVersion
self.status = status
}
private enum CodingKeys: String, CodingKey {
case artifactRevisions
case pipelineExecutionId
case pipelineName
case pipelineVersion
case status
}
}
public struct PipelineExecutionSummary: AWSDecodableShape {
/// The date and time of the last change to the pipeline execution, in timestamp format.
public let lastUpdateTime: Date?
/// The ID of the pipeline execution.
public let pipelineExecutionId: String?
/// A list of the source artifact revisions that initiated a pipeline execution.
public let sourceRevisions: [SourceRevision]?
/// The date and time when the pipeline execution began, in timestamp format.
public let startTime: Date?
/// The status of the pipeline execution. InProgress: The pipeline execution is currently running. Stopped: The pipeline execution was manually stopped. For more information, see Stopped Executions. Stopping: The pipeline execution received a request to be manually stopped. Depending on the selected stop mode, the execution is either completing or abandoning in-progress actions. For more information, see Stopped Executions. Succeeded: The pipeline execution was completed successfully. Superseded: While this pipeline execution was waiting for the next stage to be completed, a newer pipeline execution advanced and continued through the pipeline instead. For more information, see Superseded Executions. Failed: The pipeline execution was not completed successfully.
public let status: PipelineExecutionStatus?
/// The interaction that stopped a pipeline execution.
public let stopTrigger: StopExecutionTrigger?
/// The interaction or event that started a pipeline execution, such as automated change detection or a StartPipelineExecution API call.
public let trigger: ExecutionTrigger?
public init(lastUpdateTime: Date? = nil, pipelineExecutionId: String? = nil, sourceRevisions: [SourceRevision]? = nil, startTime: Date? = nil, status: PipelineExecutionStatus? = nil, stopTrigger: StopExecutionTrigger? = nil, trigger: ExecutionTrigger? = nil) {
self.lastUpdateTime = lastUpdateTime
self.pipelineExecutionId = pipelineExecutionId
self.sourceRevisions = sourceRevisions
self.startTime = startTime
self.status = status
self.stopTrigger = stopTrigger
self.trigger = trigger
}
private enum CodingKeys: String, CodingKey {
case lastUpdateTime
case pipelineExecutionId
case sourceRevisions
case startTime
case status
case stopTrigger
case trigger
}
}
public struct PipelineMetadata: AWSDecodableShape {
/// The date and time the pipeline was created, in timestamp format.
public let created: Date?
/// The Amazon Resource Name (ARN) of the pipeline.
public let pipelineArn: String?
/// The date and time the pipeline was last updated, in timestamp format.
public let updated: Date?
public init(created: Date? = nil, pipelineArn: String? = nil, updated: Date? = nil) {
self.created = created
self.pipelineArn = pipelineArn
self.updated = updated
}
private enum CodingKeys: String, CodingKey {
case created
case pipelineArn
case updated
}
}
public struct PipelineSummary: AWSDecodableShape {
/// The date and time the pipeline was created, in timestamp format.
public let created: Date?
/// The name of the pipeline.
public let name: String?
/// The date and time of the last update to the pipeline, in timestamp format.
public let updated: Date?
/// The version number of the pipeline.
public let version: Int?
public init(created: Date? = nil, name: String? = nil, updated: Date? = nil, version: Int? = nil) {
self.created = created
self.name = name
self.updated = updated
self.version = version
}
private enum CodingKeys: String, CodingKey {
case created
case name
case updated
case version
}
}
public struct PollForJobsInput: AWSEncodableShape {
/// Represents information about an action type.
public let actionTypeId: ActionTypeId
/// The maximum number of jobs to return in a poll for jobs call.
public let maxBatchSize: Int?
/// A map of property names and values. For an action type with no queryable properties, this value must be null or an empty map. For an action type with a queryable property, you must supply that property as a key in the map. Only jobs whose action configuration matches the mapped value are returned.
public let queryParam: [String: String]?
public init(actionTypeId: ActionTypeId, maxBatchSize: Int? = nil, queryParam: [String: String]? = nil) {
self.actionTypeId = actionTypeId
self.maxBatchSize = maxBatchSize
self.queryParam = queryParam
}
public func validate(name: String) throws {
try self.actionTypeId.validate(name: "\(name).actionTypeId")
try self.validate(self.maxBatchSize, name: "maxBatchSize", parent: name, min: 1)
try self.queryParam?.forEach {
try validate($0.key, name: "queryParam.key", parent: name, max: 50)
try validate($0.key, name: "queryParam.key", parent: name, min: 1)
try validate($0.value, name: "queryParam[\"\($0.key)\"]", parent: name, max: 50)
try validate($0.value, name: "queryParam[\"\($0.key)\"]", parent: name, min: 1)
try validate($0.value, name: "queryParam[\"\($0.key)\"]", parent: name, pattern: "[a-zA-Z0-9_-]+")
}
}
private enum CodingKeys: String, CodingKey {
case actionTypeId
case maxBatchSize
case queryParam
}
}
public struct PollForJobsOutput: AWSDecodableShape {
/// Information about the jobs to take action on.
public let jobs: [Job]?
public init(jobs: [Job]? = nil) {
self.jobs = jobs
}
private enum CodingKeys: String, CodingKey {
case jobs
}
}
public struct PollForThirdPartyJobsInput: AWSEncodableShape {
/// Represents information about an action type.
public let actionTypeId: ActionTypeId
/// The maximum number of jobs to return in a poll for jobs call.
public let maxBatchSize: Int?
public init(actionTypeId: ActionTypeId, maxBatchSize: Int? = nil) {
self.actionTypeId = actionTypeId
self.maxBatchSize = maxBatchSize
}
public func validate(name: String) throws {
try self.actionTypeId.validate(name: "\(name).actionTypeId")
try self.validate(self.maxBatchSize, name: "maxBatchSize", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case actionTypeId
case maxBatchSize
}
}
public struct PollForThirdPartyJobsOutput: AWSDecodableShape {
/// Information about the jobs to take action on.
public let jobs: [ThirdPartyJob]?
public init(jobs: [ThirdPartyJob]? = nil) {
self.jobs = jobs
}
private enum CodingKeys: String, CodingKey {
case jobs
}
}
public struct PutActionRevisionInput: AWSEncodableShape {
/// The name of the action that processes the revision.
public let actionName: String
/// Represents information about the version (or revision) of an action.
public let actionRevision: ActionRevision
/// The name of the pipeline that starts processing the revision to the source.
public let pipelineName: String
/// The name of the stage that contains the action that acts on the revision.
public let stageName: String
public init(actionName: String, actionRevision: ActionRevision, pipelineName: String, stageName: String) {
self.actionName = actionName
self.actionRevision = actionRevision
self.pipelineName = pipelineName
self.stageName = stageName
}
public func validate(name: String) throws {
try self.validate(self.actionName, name: "actionName", parent: name, max: 100)
try self.validate(self.actionName, name: "actionName", parent: name, min: 1)
try self.validate(self.actionName, name: "actionName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
try self.actionRevision.validate(name: "\(name).actionRevision")
try self.validate(self.pipelineName, name: "pipelineName", parent: name, max: 100)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, min: 1)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
try self.validate(self.stageName, name: "stageName", parent: name, max: 100)
try self.validate(self.stageName, name: "stageName", parent: name, min: 1)
try self.validate(self.stageName, name: "stageName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
}
private enum CodingKeys: String, CodingKey {
case actionName
case actionRevision
case pipelineName
case stageName
}
}
public struct PutActionRevisionOutput: AWSDecodableShape {
/// Indicates whether the artifact revision was previously used in an execution of the specified pipeline.
public let newRevision: Bool?
/// The ID of the current workflow state of the pipeline.
public let pipelineExecutionId: String?
public init(newRevision: Bool? = nil, pipelineExecutionId: String? = nil) {
self.newRevision = newRevision
self.pipelineExecutionId = pipelineExecutionId
}
private enum CodingKeys: String, CodingKey {
case newRevision
case pipelineExecutionId
}
}
public struct PutApprovalResultInput: AWSEncodableShape {
/// The name of the action for which approval is requested.
public let actionName: String
/// The name of the pipeline that contains the action.
public let pipelineName: String
/// Represents information about the result of the approval request.
public let result: ApprovalResult
/// The name of the stage that contains the action.
public let stageName: String
/// The system-generated token used to identify a unique approval request. The token for each open approval request can be obtained using the GetPipelineState action. It is used to validate that the approval request corresponding to this token is still valid.
public let token: String
public init(actionName: String, pipelineName: String, result: ApprovalResult, stageName: String, token: String) {
self.actionName = actionName
self.pipelineName = pipelineName
self.result = result
self.stageName = stageName
self.token = token
}
public func validate(name: String) throws {
try self.validate(self.actionName, name: "actionName", parent: name, max: 100)
try self.validate(self.actionName, name: "actionName", parent: name, min: 1)
try self.validate(self.actionName, name: "actionName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
try self.validate(self.pipelineName, name: "pipelineName", parent: name, max: 100)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, min: 1)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
try self.result.validate(name: "\(name).result")
try self.validate(self.stageName, name: "stageName", parent: name, max: 100)
try self.validate(self.stageName, name: "stageName", parent: name, min: 1)
try self.validate(self.stageName, name: "stageName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
try self.validate(self.token, name: "token", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
}
private enum CodingKeys: String, CodingKey {
case actionName
case pipelineName
case result
case stageName
case token
}
}
public struct PutApprovalResultOutput: AWSDecodableShape {
/// The timestamp showing when the approval or rejection was submitted.
public let approvedAt: Date?
public init(approvedAt: Date? = nil) {
self.approvedAt = approvedAt
}
private enum CodingKeys: String, CodingKey {
case approvedAt
}
}
public struct PutJobFailureResultInput: AWSEncodableShape {
/// The details about the failure of a job.
public let failureDetails: FailureDetails
/// The unique system-generated ID of the job that failed. This is the same ID returned from PollForJobs.
public let jobId: String
public init(failureDetails: FailureDetails, jobId: String) {
self.failureDetails = failureDetails
self.jobId = jobId
}
public func validate(name: String) throws {
try self.failureDetails.validate(name: "\(name).failureDetails")
try self.validate(self.jobId, name: "jobId", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
}
private enum CodingKeys: String, CodingKey {
case failureDetails
case jobId
}
}
public struct PutJobSuccessResultInput: AWSEncodableShape {
/// A token generated by a job worker, such as an AWS CodeDeploy deployment ID, that a successful job provides to identify a custom action in progress. Future jobs use this token to identify the running instance of the action. It can be reused to return more information about the progress of the custom action. When the action is complete, no continuation token should be supplied.
public let continuationToken: String?
/// The ID of the current revision of the artifact successfully worked on by the job.
public let currentRevision: CurrentRevision?
/// The execution details of the successful job, such as the actions taken by the job worker.
public let executionDetails: ExecutionDetails?
/// The unique system-generated ID of the job that succeeded. This is the same ID returned from PollForJobs.
public let jobId: String
/// Key-value pairs produced as output by a job worker that can be made available to a downstream action configuration. outputVariables can be included only when there is no continuation token on the request.
public let outputVariables: [String: String]?
public init(continuationToken: String? = nil, currentRevision: CurrentRevision? = nil, executionDetails: ExecutionDetails? = nil, jobId: String, outputVariables: [String: String]? = nil) {
self.continuationToken = continuationToken
self.currentRevision = currentRevision
self.executionDetails = executionDetails
self.jobId = jobId
self.outputVariables = outputVariables
}
public func validate(name: String) throws {
try self.validate(self.continuationToken, name: "continuationToken", parent: name, max: 2048)
try self.validate(self.continuationToken, name: "continuationToken", parent: name, min: 1)
try self.currentRevision?.validate(name: "\(name).currentRevision")
try self.executionDetails?.validate(name: "\(name).executionDetails")
try self.validate(self.jobId, name: "jobId", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
try self.outputVariables?.forEach {
try validate($0.key, name: "outputVariables.key", parent: name, pattern: "[A-Za-z0-9@\\-_]+")
}
}
private enum CodingKeys: String, CodingKey {
case continuationToken
case currentRevision
case executionDetails
case jobId
case outputVariables
}
}
public struct PutThirdPartyJobFailureResultInput: AWSEncodableShape {
/// The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details.
public let clientToken: String
/// Represents information about failure details.
public let failureDetails: FailureDetails
/// The ID of the job that failed. This is the same ID returned from PollForThirdPartyJobs.
public let jobId: String
public init(clientToken: String, failureDetails: FailureDetails, jobId: String) {
self.clientToken = clientToken
self.failureDetails = failureDetails
self.jobId = jobId
}
public func validate(name: String) throws {
try self.validate(self.clientToken, name: "clientToken", parent: name, max: 256)
try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1)
try self.failureDetails.validate(name: "\(name).failureDetails")
try self.validate(self.jobId, name: "jobId", parent: name, max: 512)
try self.validate(self.jobId, name: "jobId", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case clientToken
case failureDetails
case jobId
}
}
public struct PutThirdPartyJobSuccessResultInput: AWSEncodableShape {
/// The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details.
public let clientToken: String
/// A token generated by a job worker, such as an AWS CodeDeploy deployment ID, that a successful job provides to identify a partner action in progress. Future jobs use this token to identify the running instance of the action. It can be reused to return more information about the progress of the partner action. When the action is complete, no continuation token should be supplied.
public let continuationToken: String?
/// Represents information about a current revision.
public let currentRevision: CurrentRevision?
/// The details of the actions taken and results produced on an artifact as it passes through stages in the pipeline.
public let executionDetails: ExecutionDetails?
/// The ID of the job that successfully completed. This is the same ID returned from PollForThirdPartyJobs.
public let jobId: String
public init(clientToken: String, continuationToken: String? = nil, currentRevision: CurrentRevision? = nil, executionDetails: ExecutionDetails? = nil, jobId: String) {
self.clientToken = clientToken
self.continuationToken = continuationToken
self.currentRevision = currentRevision
self.executionDetails = executionDetails
self.jobId = jobId
}
public func validate(name: String) throws {
try self.validate(self.clientToken, name: "clientToken", parent: name, max: 256)
try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1)
try self.validate(self.continuationToken, name: "continuationToken", parent: name, max: 2048)
try self.validate(self.continuationToken, name: "continuationToken", parent: name, min: 1)
try self.currentRevision?.validate(name: "\(name).currentRevision")
try self.executionDetails?.validate(name: "\(name).executionDetails")
try self.validate(self.jobId, name: "jobId", parent: name, max: 512)
try self.validate(self.jobId, name: "jobId", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case clientToken
case continuationToken
case currentRevision
case executionDetails
case jobId
}
}
public struct PutWebhookInput: AWSEncodableShape {
/// The tags for the webhook.
public let tags: [Tag]?
/// The detail provided in an input file to create the webhook, such as the webhook name, the pipeline name, and the action name. Give the webhook a unique name that helps you identify it. You might name the webhook after the pipeline and action it targets so that you can easily recognize what it's used for later.
public let webhook: WebhookDefinition
public init(tags: [Tag]? = nil, webhook: WebhookDefinition) {
self.tags = tags
self.webhook = webhook
}
public func validate(name: String) throws {
try self.tags?.forEach {
try $0.validate(name: "\(name).tags[]")
}
try self.webhook.validate(name: "\(name).webhook")
}
private enum CodingKeys: String, CodingKey {
case tags
case webhook
}
}
public struct PutWebhookOutput: AWSDecodableShape {
/// The detail returned from creating the webhook, such as the webhook name, webhook URL, and webhook ARN.
public let webhook: ListWebhookItem?
public init(webhook: ListWebhookItem? = nil) {
self.webhook = webhook
}
private enum CodingKeys: String, CodingKey {
case webhook
}
}
public struct RegisterWebhookWithThirdPartyInput: AWSEncodableShape {
/// The name of an existing webhook created with PutWebhook to register with a supported third party.
public let webhookName: String?
public init(webhookName: String? = nil) {
self.webhookName = webhookName
}
public func validate(name: String) throws {
try self.validate(self.webhookName, name: "webhookName", parent: name, max: 100)
try self.validate(self.webhookName, name: "webhookName", parent: name, min: 1)
try self.validate(self.webhookName, name: "webhookName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
}
private enum CodingKeys: String, CodingKey {
case webhookName
}
}
public struct RegisterWebhookWithThirdPartyOutput: AWSDecodableShape {
public init() {}
}
public struct RetryStageExecutionInput: AWSEncodableShape {
/// The ID of the pipeline execution in the failed stage to be retried. Use the GetPipelineState action to retrieve the current pipelineExecutionId of the failed stage
public let pipelineExecutionId: String
/// The name of the pipeline that contains the failed stage.
public let pipelineName: String
/// The scope of the retry attempt. Currently, the only supported value is FAILED_ACTIONS.
public let retryMode: StageRetryMode
/// The name of the failed stage to be retried.
public let stageName: String
public init(pipelineExecutionId: String, pipelineName: String, retryMode: StageRetryMode, stageName: String) {
self.pipelineExecutionId = pipelineExecutionId
self.pipelineName = pipelineName
self.retryMode = retryMode
self.stageName = stageName
}
public func validate(name: String) throws {
try self.validate(self.pipelineExecutionId, name: "pipelineExecutionId", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
try self.validate(self.pipelineName, name: "pipelineName", parent: name, max: 100)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, min: 1)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
try self.validate(self.stageName, name: "stageName", parent: name, max: 100)
try self.validate(self.stageName, name: "stageName", parent: name, min: 1)
try self.validate(self.stageName, name: "stageName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
}
private enum CodingKeys: String, CodingKey {
case pipelineExecutionId
case pipelineName
case retryMode
case stageName
}
}
public struct RetryStageExecutionOutput: AWSDecodableShape {
/// The ID of the current workflow execution in the failed stage.
public let pipelineExecutionId: String?
public init(pipelineExecutionId: String? = nil) {
self.pipelineExecutionId = pipelineExecutionId
}
private enum CodingKeys: String, CodingKey {
case pipelineExecutionId
}
}
public struct S3ArtifactLocation: AWSDecodableShape {
/// The name of the S3 bucket.
public let bucketName: String
/// The key of the object in the S3 bucket, which uniquely identifies the object in the bucket.
public let objectKey: String
public init(bucketName: String, objectKey: String) {
self.bucketName = bucketName
self.objectKey = objectKey
}
private enum CodingKeys: String, CodingKey {
case bucketName
case objectKey
}
}
public struct S3Location: AWSDecodableShape {
/// The Amazon S3 artifact bucket for an action's artifacts.
public let bucket: String?
/// The artifact name.
public let key: String?
public init(bucket: String? = nil, key: String? = nil) {
self.bucket = bucket
self.key = key
}
private enum CodingKeys: String, CodingKey {
case bucket
case key
}
}
public struct SourceRevision: AWSDecodableShape {
/// The name of the action that processed the revision to the source artifact.
public let actionName: String
/// The system-generated unique ID that identifies the revision number of the artifact.
public let revisionId: String?
/// Summary information about the most recent revision of the artifact. For GitHub and AWS CodeCommit repositories, the commit message. For Amazon S3 buckets or actions, the user-provided content of a codepipeline-artifact-revision-summary key specified in the object metadata.
public let revisionSummary: String?
/// The commit ID for the artifact revision. For artifacts stored in GitHub or AWS CodeCommit repositories, the commit ID is linked to a commit details page.
public let revisionUrl: String?
public init(actionName: String, revisionId: String? = nil, revisionSummary: String? = nil, revisionUrl: String? = nil) {
self.actionName = actionName
self.revisionId = revisionId
self.revisionSummary = revisionSummary
self.revisionUrl = revisionUrl
}
private enum CodingKeys: String, CodingKey {
case actionName
case revisionId
case revisionSummary
case revisionUrl
}
}
public struct StageContext: AWSDecodableShape {
/// The name of the stage.
public let name: String?
public init(name: String? = nil) {
self.name = name
}
private enum CodingKeys: String, CodingKey {
case name
}
}
public struct StageDeclaration: AWSEncodableShape & AWSDecodableShape {
/// The actions included in a stage.
public let actions: [ActionDeclaration]
/// Reserved for future use.
public let blockers: [BlockerDeclaration]?
/// The name of the stage.
public let name: String
public init(actions: [ActionDeclaration], blockers: [BlockerDeclaration]? = nil, name: String) {
self.actions = actions
self.blockers = blockers
self.name = name
}
public func validate(name: String) throws {
try self.actions.forEach {
try $0.validate(name: "\(name).actions[]")
}
try self.blockers?.forEach {
try $0.validate(name: "\(name).blockers[]")
}
try self.validate(self.name, name: "name", parent: name, max: 100)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
}
private enum CodingKeys: String, CodingKey {
case actions
case blockers
case name
}
}
public struct StageExecution: AWSDecodableShape {
/// The ID of the pipeline execution associated with the stage.
public let pipelineExecutionId: String
/// The status of the stage, or for a completed stage, the last status of the stage.
public let status: StageExecutionStatus
public init(pipelineExecutionId: String, status: StageExecutionStatus) {
self.pipelineExecutionId = pipelineExecutionId
self.status = status
}
private enum CodingKeys: String, CodingKey {
case pipelineExecutionId
case status
}
}
public struct StageState: AWSDecodableShape {
/// The state of the stage.
public let actionStates: [ActionState]?
/// The state of the inbound transition, which is either enabled or disabled.
public let inboundTransitionState: TransitionState?
/// Information about the latest execution in the stage, including its ID and status.
public let latestExecution: StageExecution?
/// The name of the stage.
public let stageName: String?
public init(actionStates: [ActionState]? = nil, inboundTransitionState: TransitionState? = nil, latestExecution: StageExecution? = nil, stageName: String? = nil) {
self.actionStates = actionStates
self.inboundTransitionState = inboundTransitionState
self.latestExecution = latestExecution
self.stageName = stageName
}
private enum CodingKeys: String, CodingKey {
case actionStates
case inboundTransitionState
case latestExecution
case stageName
}
}
public struct StartPipelineExecutionInput: AWSEncodableShape {
/// The system-generated unique ID used to identify a unique execution request.
public let clientRequestToken: String?
/// The name of the pipeline to start.
public let name: String
public init(clientRequestToken: String? = StartPipelineExecutionInput.idempotencyToken(), name: String) {
self.clientRequestToken = clientRequestToken
self.name = name
}
public func validate(name: String) throws {
try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, max: 128)
try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, min: 1)
try self.validate(self.clientRequestToken, name: "clientRequestToken", parent: name, pattern: "^[a-zA-Z0-9-]+$")
try self.validate(self.name, name: "name", parent: name, max: 100)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
}
private enum CodingKeys: String, CodingKey {
case clientRequestToken
case name
}
}
public struct StartPipelineExecutionOutput: AWSDecodableShape {
/// The unique system-generated ID of the pipeline execution that was started.
public let pipelineExecutionId: String?
public init(pipelineExecutionId: String? = nil) {
self.pipelineExecutionId = pipelineExecutionId
}
private enum CodingKeys: String, CodingKey {
case pipelineExecutionId
}
}
public struct StopExecutionTrigger: AWSDecodableShape {
/// The user-specified reason the pipeline was stopped.
public let reason: String?
public init(reason: String? = nil) {
self.reason = reason
}
private enum CodingKeys: String, CodingKey {
case reason
}
}
public struct StopPipelineExecutionInput: AWSEncodableShape {
/// Use this option to stop the pipeline execution by abandoning, rather than finishing, in-progress actions. This option can lead to failed or out-of-sequence tasks.
public let abandon: Bool?
/// The ID of the pipeline execution to be stopped in the current stage. Use the GetPipelineState action to retrieve the current pipelineExecutionId.
public let pipelineExecutionId: String
/// The name of the pipeline to stop.
public let pipelineName: String
/// Use this option to enter comments, such as the reason the pipeline was stopped.
public let reason: String?
public init(abandon: Bool? = nil, pipelineExecutionId: String, pipelineName: String, reason: String? = nil) {
self.abandon = abandon
self.pipelineExecutionId = pipelineExecutionId
self.pipelineName = pipelineName
self.reason = reason
}
public func validate(name: String) throws {
try self.validate(self.pipelineExecutionId, name: "pipelineExecutionId", parent: name, pattern: "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
try self.validate(self.pipelineName, name: "pipelineName", parent: name, max: 100)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, min: 1)
try self.validate(self.pipelineName, name: "pipelineName", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
try self.validate(self.reason, name: "reason", parent: name, max: 200)
}
private enum CodingKeys: String, CodingKey {
case abandon
case pipelineExecutionId
case pipelineName
case reason
}
}
public struct StopPipelineExecutionOutput: AWSDecodableShape {
/// The unique system-generated ID of the pipeline execution that was stopped.
public let pipelineExecutionId: String?
public init(pipelineExecutionId: String? = nil) {
self.pipelineExecutionId = pipelineExecutionId
}
private enum CodingKeys: String, CodingKey {
case pipelineExecutionId
}
}
public struct Tag: AWSEncodableShape & AWSDecodableShape {
/// The tag's key.
public let key: String
/// The tag's value.
public let value: String
public init(key: String, value: String) {
self.key = key
self.value = value
}
public func validate(name: String) throws {
try self.validate(self.key, name: "key", parent: name, max: 128)
try self.validate(self.key, name: "key", parent: name, min: 1)
try self.validate(self.value, name: "value", parent: name, max: 256)
try self.validate(self.value, name: "value", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case key
case value
}
}
public struct TagResourceInput: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the resource you want to add tags to.
public let resourceArn: String
/// The tags you want to modify or add to the resource.
public let tags: [Tag]
public init(resourceArn: String, tags: [Tag]) {
self.resourceArn = resourceArn
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.resourceArn, name: "resourceArn", parent: name, pattern: "arn:aws(-[\\w]+)*:codepipeline:.+:[0-9]{12}:.+")
try self.tags.forEach {
try $0.validate(name: "\(name).tags[]")
}
}
private enum CodingKeys: String, CodingKey {
case resourceArn
case tags
}
}
public struct TagResourceOutput: AWSDecodableShape {
public init() {}
}
public struct ThirdPartyJob: AWSDecodableShape {
/// The clientToken portion of the clientId and clientToken pair used to verify that the calling entity is allowed access to the job and its details.
public let clientId: String?
/// The identifier used to identify the job in AWS CodePipeline.
public let jobId: String?
public init(clientId: String? = nil, jobId: String? = nil) {
self.clientId = clientId
self.jobId = jobId
}
private enum CodingKeys: String, CodingKey {
case clientId
case jobId
}
}
public struct ThirdPartyJobData: AWSDecodableShape {
/// Represents information about an action configuration.
public let actionConfiguration: ActionConfiguration?
/// Represents information about an action type.
public let actionTypeId: ActionTypeId?
/// Represents an AWS session credentials object. These credentials are temporary credentials that are issued by AWS Secure Token Service (STS). They can be used to access input and output artifacts in the S3 bucket used to store artifact for the pipeline in AWS CodePipeline.
public let artifactCredentials: AWSSessionCredentials?
/// A system-generated token, such as a AWS CodeDeploy deployment ID, that a job requires to continue the job asynchronously.
public let continuationToken: String?
/// The encryption key used to encrypt and decrypt data in the artifact store for the pipeline, such as an AWS Key Management Service (AWS KMS) key. This is optional and might not be present.
public let encryptionKey: EncryptionKey?
/// The name of the artifact that is worked on by the action, if any. This name might be system-generated, such as "MyApp", or it might be defined by the user when the action is created. The input artifact name must match the name of an output artifact generated by an action in an earlier action or stage of the pipeline.
public let inputArtifacts: [Artifact]?
/// The name of the artifact that is the result of the action, if any. This name might be system-generated, such as "MyBuiltApp", or it might be defined by the user when the action is created.
public let outputArtifacts: [Artifact]?
/// Represents information about a pipeline to a job worker. Does not include pipelineArn and pipelineExecutionId for ThirdParty jobs.
public let pipelineContext: PipelineContext?
public init(actionConfiguration: ActionConfiguration? = nil, actionTypeId: ActionTypeId? = nil, artifactCredentials: AWSSessionCredentials? = nil, continuationToken: String? = nil, encryptionKey: EncryptionKey? = nil, inputArtifacts: [Artifact]? = nil, outputArtifacts: [Artifact]? = nil, pipelineContext: PipelineContext? = nil) {
self.actionConfiguration = actionConfiguration
self.actionTypeId = actionTypeId
self.artifactCredentials = artifactCredentials
self.continuationToken = continuationToken
self.encryptionKey = encryptionKey
self.inputArtifacts = inputArtifacts
self.outputArtifacts = outputArtifacts
self.pipelineContext = pipelineContext
}
private enum CodingKeys: String, CodingKey {
case actionConfiguration
case actionTypeId
case artifactCredentials
case continuationToken
case encryptionKey
case inputArtifacts
case outputArtifacts
case pipelineContext
}
}
public struct ThirdPartyJobDetails: AWSDecodableShape {
/// The data to be returned by the third party job worker.
public let data: ThirdPartyJobData?
/// The identifier used to identify the job details in AWS CodePipeline.
public let id: String?
/// A system-generated random number that AWS CodePipeline uses to ensure that the job is being worked on by only one job worker. Use this number in an AcknowledgeThirdPartyJob request.
public let nonce: String?
public init(data: ThirdPartyJobData? = nil, id: String? = nil, nonce: String? = nil) {
self.data = data
self.id = id
self.nonce = nonce
}
private enum CodingKeys: String, CodingKey {
case data
case id
case nonce
}
}
public struct TransitionState: AWSDecodableShape {
/// The user-specified reason why the transition between two stages of a pipeline was disabled.
public let disabledReason: String?
/// Whether the transition between stages is enabled (true) or disabled (false).
public let enabled: Bool?
/// The timestamp when the transition state was last changed.
public let lastChangedAt: Date?
/// The ID of the user who last changed the transition state.
public let lastChangedBy: String?
public init(disabledReason: String? = nil, enabled: Bool? = nil, lastChangedAt: Date? = nil, lastChangedBy: String? = nil) {
self.disabledReason = disabledReason
self.enabled = enabled
self.lastChangedAt = lastChangedAt
self.lastChangedBy = lastChangedBy
}
private enum CodingKeys: String, CodingKey {
case disabledReason
case enabled
case lastChangedAt
case lastChangedBy
}
}
public struct UntagResourceInput: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the resource to remove tags from.
public let resourceArn: String
/// The list of keys for the tags to be removed from the resource.
public let tagKeys: [String]
public init(resourceArn: String, tagKeys: [String]) {
self.resourceArn = resourceArn
self.tagKeys = tagKeys
}
public func validate(name: String) throws {
try self.validate(self.resourceArn, name: "resourceArn", parent: name, pattern: "arn:aws(-[\\w]+)*:codepipeline:.+:[0-9]{12}:.+")
try self.tagKeys.forEach {
try validate($0, name: "tagKeys[]", parent: name, max: 128)
try validate($0, name: "tagKeys[]", parent: name, min: 1)
}
}
private enum CodingKeys: String, CodingKey {
case resourceArn
case tagKeys
}
}
public struct UntagResourceOutput: AWSDecodableShape {
public init() {}
}
public struct UpdatePipelineInput: AWSEncodableShape {
/// The name of the pipeline to be updated.
public let pipeline: PipelineDeclaration
public init(pipeline: PipelineDeclaration) {
self.pipeline = pipeline
}
public func validate(name: String) throws {
try self.pipeline.validate(name: "\(name).pipeline")
}
private enum CodingKeys: String, CodingKey {
case pipeline
}
}
public struct UpdatePipelineOutput: AWSDecodableShape {
/// The structure of the updated pipeline.
public let pipeline: PipelineDeclaration?
public init(pipeline: PipelineDeclaration? = nil) {
self.pipeline = pipeline
}
private enum CodingKeys: String, CodingKey {
case pipeline
}
}
public struct WebhookAuthConfiguration: AWSEncodableShape & AWSDecodableShape {
/// The property used to configure acceptance of webhooks in an IP address range. For IP, only the AllowedIPRange property must be set. This property must be set to a valid CIDR range.
public let allowedIPRange: String?
/// The property used to configure GitHub authentication. For GITHUB_HMAC, only the SecretToken property must be set.
public let secretToken: String?
public init(allowedIPRange: String? = nil, secretToken: String? = nil) {
self.allowedIPRange = allowedIPRange
self.secretToken = secretToken
}
public func validate(name: String) throws {
try self.validate(self.allowedIPRange, name: "allowedIPRange", parent: name, max: 100)
try self.validate(self.allowedIPRange, name: "allowedIPRange", parent: name, min: 1)
try self.validate(self.secretToken, name: "secretToken", parent: name, max: 100)
try self.validate(self.secretToken, name: "secretToken", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case allowedIPRange = "AllowedIPRange"
case secretToken = "SecretToken"
}
}
public struct WebhookDefinition: AWSEncodableShape & AWSDecodableShape {
/// Supported options are GITHUB_HMAC, IP, and UNAUTHENTICATED. For information about the authentication scheme implemented by GITHUB_HMAC, see Securing your webhooks on the GitHub Developer website. IP rejects webhooks trigger requests unless they originate from an IP address in the IP range whitelisted in the authentication configuration. UNAUTHENTICATED accepts all webhook trigger requests regardless of origin.
public let authentication: WebhookAuthenticationType
/// Properties that configure the authentication applied to incoming webhook trigger requests. The required properties depend on the authentication type. For GITHUB_HMAC, only the SecretToken property must be set. For IP, only the AllowedIPRange property must be set to a valid CIDR range. For UNAUTHENTICATED, no properties can be set.
public let authenticationConfiguration: WebhookAuthConfiguration
/// A list of rules applied to the body/payload sent in the POST request to a webhook URL. All defined rules must pass for the request to be accepted and the pipeline started.
public let filters: [WebhookFilterRule]
/// The name of the webhook.
public let name: String
/// The name of the action in a pipeline you want to connect to the webhook. The action must be from the source (first) stage of the pipeline.
public let targetAction: String
/// The name of the pipeline you want to connect to the webhook.
public let targetPipeline: String
public init(authentication: WebhookAuthenticationType, authenticationConfiguration: WebhookAuthConfiguration, filters: [WebhookFilterRule], name: String, targetAction: String, targetPipeline: String) {
self.authentication = authentication
self.authenticationConfiguration = authenticationConfiguration
self.filters = filters
self.name = name
self.targetAction = targetAction
self.targetPipeline = targetPipeline
}
public func validate(name: String) throws {
try self.authenticationConfiguration.validate(name: "\(name).authenticationConfiguration")
try self.filters.forEach {
try $0.validate(name: "\(name).filters[]")
}
try self.validate(self.filters, name: "filters", parent: name, max: 5)
try self.validate(self.name, name: "name", parent: name, max: 100)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
try self.validate(self.targetAction, name: "targetAction", parent: name, max: 100)
try self.validate(self.targetAction, name: "targetAction", parent: name, min: 1)
try self.validate(self.targetAction, name: "targetAction", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
try self.validate(self.targetPipeline, name: "targetPipeline", parent: name, max: 100)
try self.validate(self.targetPipeline, name: "targetPipeline", parent: name, min: 1)
try self.validate(self.targetPipeline, name: "targetPipeline", parent: name, pattern: "[A-Za-z0-9.@\\-_]+")
}
private enum CodingKeys: String, CodingKey {
case authentication
case authenticationConfiguration
case filters
case name
case targetAction
case targetPipeline
}
}
public struct WebhookFilterRule: AWSEncodableShape & AWSDecodableShape {
/// A JsonPath expression that is applied to the body/payload of the webhook. The value selected by the JsonPath expression must match the value specified in the MatchEquals field. Otherwise, the request is ignored. For more information, see Java JsonPath implementation in GitHub.
public let jsonPath: String
/// The value selected by the JsonPath expression must match what is supplied in the MatchEquals field. Otherwise, the request is ignored. Properties from the target action configuration can be included as placeholders in this value by surrounding the action configuration key with curly brackets. For example, if the value supplied here is "refs/heads/{Branch}" and the target action has an action configuration property called "Branch" with a value of "master", the MatchEquals value is evaluated as "refs/heads/master". For a list of action configuration properties for built-in action types, see Pipeline Structure Reference Action Requirements.
public let matchEquals: String?
public init(jsonPath: String, matchEquals: String? = nil) {
self.jsonPath = jsonPath
self.matchEquals = matchEquals
}
public func validate(name: String) throws {
try self.validate(self.jsonPath, name: "jsonPath", parent: name, max: 150)
try self.validate(self.jsonPath, name: "jsonPath", parent: name, min: 1)
try self.validate(self.matchEquals, name: "matchEquals", parent: name, max: 150)
try self.validate(self.matchEquals, name: "matchEquals", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case jsonPath
case matchEquals
}
}
}
| apache-2.0 |
vector-im/vector-ios | Riot/Modules/Common/Recents/Service/Mock/MockRoomListData.swift | 1 | 967 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import MatrixSDK
@objcMembers
public class MockRoomListData: MXRoomListData {
public init(withRooms rooms: [MXRoomSummaryProtocol]) {
super.init(rooms: rooms,
counts: MXStoreRoomListDataCounts(withRooms: rooms,
total: nil),
paginationOptions: .none)
}
}
| apache-2.0 |
mlibai/XZKit | Projects/Example/CarouselViewExample/CarouselViewExample/CarouselViewExample/Example3/Example3ViewController.swift | 1 | 18827 | //
// Example3ViewController.swift
// XZCarouselViewExample
//
// Created by 徐臻 on 2019/3/12.
// Copyright © 2019 mlibai. All rights reserved.
//
import UIKit
import XZKit
class Example3ViewController: UIViewController {
deinit {
print("Example3ViewController: \(#function)")
}
fileprivate class Model {
let index: Int
let title: String
let url: URL
lazy private(set) var titleWidth: CGFloat = {
return (title as NSString).boundingRect(with: CGSize.init(width: 1000, height: 40), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15.0)], context: nil).width + 10
}()
init(_ index: Int, _ title: String, _ imageURL: URL) {
self.index = index
self.title = title
self.url = imageURL
}
}
fileprivate let pages: [Model] = [
Model(0, "最新", URL(string: "https://m.ithome.com/")!),
Model(1, "排行榜", URL(string: "https://m.ithome.com/rankm/")!),
Model(2, "精读", URL(string: "https://m.ithome.com/jingdum/")!),
Model(3, "原创", URL(string: "https://m.ithome.com/originalm/")!),
Model(4, "上热评", URL(string: "https://m.ithome.com/hotcommentm/")!),
Model(5, "评测室", URL(string: "https://m.ithome.com/labsm/")!),
Model(6, "发布会", URL(string: "https://m.ithome.com/livem/")!),
Model(7, "专题", URL(string: "https://m.ithome.com/specialm/")!),
Model(8, "阳台", URL(string: "https://m.ithome.com/balconym/")!),
Model(9, "手机", URL(string: "https://m.ithome.com/phonem/")!),
Model(10, "数码", URL(string: "https://m.ithome.com/digim/")!),
Model(11, "极客学院", URL(string: "https://m.ithome.com/geekm/")!),
Model(12, "VR", URL(string: "https://m.ithome.com/vrm/")!),
Model(13, "智能汽车", URL(string: "https://m.ithome.com/autom/")!),
Model(14, "电脑", URL(string: "https://m.ithome.com/pcm/")!),
Model(15, "京东精选", URL(string: "https://m.ithome.com/jdm/")!),
Model(16, "安卓", URL(string: "https://m.ithome.com/androidm/")!),
Model(17, "苹果", URL(string: "https://m.ithome.com/iosm/")!),
Model(18, "网络焦点", URL(string: "https://m.ithome.com/internetm/")!),
Model(19, "行业前沿", URL(string: "https://m.ithome.com/itm/")!),
Model(20, "游戏电竞", URL(string: "https://m.ithome.com/gamem/")!),
Model(21, "Windows", URL(string: "https://m.ithome.com/windowsm/")!),
Model(22, "科普", URL(string: "https://m.ithome.com/discoverym/")!)
]
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var containerView: UIView!
let indicatorView = UIView.init(frame: .zero)
let carouselViewController = CarouselViewController.init()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.backBarButtonItem = UIBarButtonItem.init(title: "返回", style: .plain, target: nil, action: nil)
indicatorView.backgroundColor = UIColor(red: 0xC1 / 255.0, green: 0x06 / 255.0, blue: 0x19 / 255.0, alpha: 1.0)
indicatorView.layer.cornerRadius = 1.5
indicatorView.layer.masksToBounds = true
collectionView.addSubview(indicatorView)
carouselViewController.carouselView.transitionViewHierarchy = .navigation
addChild(carouselViewController)
carouselViewController.view.backgroundColor = .white
carouselViewController.view.frame = containerView.bounds
carouselViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
containerView.addSubview(carouselViewController.view)
carouselViewController.didMove(toParent: self)
carouselViewController.delegate = self
carouselViewController.dataSource = self
// 因为 UICollectionView 刷新页面是异步的,所以要在菜单显示后才能设置菜单的指示器位置。
collectionView.performBatchUpdates({
self.collectionView.reloadData()
}, completion: { (_) in
self.carouselViewController.reloadData()
})
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("Example3ViewController: \(#function)")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("Example3ViewController: \(#function)")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("Example3ViewController: \(#function)")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
print("Example3ViewController: \(#function)")
}
@IBAction func transitionAnimationSwitchAction(_ sender: UISwitch) {
if sender.isOn && carouselViewController.carouselView.transitioningDelegate == nil {
carouselViewController.carouselView.transitioningDelegate = self
let alertVC = UIAlertController(title: "XZKit", message: "转场 Push/Pop 特效已开启!", preferredStyle: .alert)
alertVC.addAction(.init(title: "知道了", style: .cancel, handler: nil))
present(alertVC, animated: true, completion: nil)
} else if carouselViewController.carouselView.transitioningDelegate != nil {
carouselViewController.carouselView.transitioningDelegate = nil
}
}
private var menuIndex: Int = CarouselView.notFound
// 不能重用的控制器
private var indexedViewControllers = [Int: Example3WebViewController]()
// 自定义的重用机制:重用池。
private var reusableViewControllers = [Example3WebViewController]()
}
extension Example3ViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return pages.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Example3MenuCell
cell.textLabel.text = pages[indexPath.item].title
cell.transition = (menuIndex == indexPath.item ? 1.0 : 0)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: pages[indexPath.item].titleWidth, height: 40)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
carouselViewController.setCurrentIndex(indexPath.item, animated: true)
}
}
extension Example3ViewController: CarouselViewControllerDataSource {
func numberOfViewControllers(in carouselViewController: CarouselViewController) -> Int {
return pages.count
}
func carouselViewController(_ carouselViewController: CarouselViewController, viewControllerFor index: Int, reusing reusingViewController: UIViewController?) -> UIViewController {
// 自定义重用机制。假定前 5 个栏目是专栏,使用独立的控制器,其它栏目使用相同控制器。
if index < 5 {
if let viewController = indexedViewControllers[index] {
return viewController
}
print("创建不可重用控制器:\(index)")
let webViewController = Example3WebViewController.init(index: index)
webViewController.title = pages[index].title
webViewController.load(url: pages[index].url)
indexedViewControllers[index] = webViewController
return webViewController
}
if reusableViewControllers.isEmpty {
print("创建可重用控制器:\(index)")
let webViewController = Example3WebViewController.init(index: index)
webViewController.title = pages[index].title
webViewController.load(url: pages[index].url)
return webViewController
}
let webViewController = reusableViewControllers.removeLast()
print("使用可重用控制器:\(webViewController.index) -> \(index)")
webViewController.title = pages[index].title
webViewController.load(url: pages[index].url)
return webViewController
}
func carouselViewController(_ carouselViewController: CarouselViewController, shouldEnqueue viewController: UIViewController, at index: Int) -> Bool {
guard index >= 5 else {
return false
}
let viewController = viewController as! Example3WebViewController
print("回收可重用控制器:\(viewController.index)")
viewController.prepareForReusing()
reusableViewControllers.append(viewController)
return false
}
}
extension Example3ViewController: CarouselViewControllerDelegate {
func carouselViewController(_ carouselViewController: CarouselViewController, didShow viewController: UIViewController, at index: Int) {
self.collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: true)
print("didShowItemAt: \(index)")
}
func carouselViewController(_ carouselViewController: CarouselViewController, didTransition transition: CGFloat, animated: Bool) {
let newIndex = carouselViewController.currentIndex
if menuIndex == newIndex { //
if transition > 0 { // 滚往下一个。
menuTranstion(to: menuIndex + 1, transition: transition)
} else if transition < 0 {
menuTranstion(to: menuIndex - 1, transition: -transition)
} else { // 滚动取消
menuTranstion(to: menuIndex, transition: 0)
collectionView.reloadData() // 重置菜单文字颜色。
}
} else { // 页面已跳转到新的 index 。
if (transition == 0) { // 完成跳转
menuIndex = newIndex
menuTranstion(to: menuIndex, transition: 0)
collectionView.reloadData()
} else { // 跳转中。
menuTranstion(to: newIndex, transition: 1.0 - abs(transition))
}
}
// print("Transition: \(newIndex) \(transition)")
}
private func menuTranstion(to newIndex: Int, transition: CGFloat) {
if menuIndex != newIndex, let targetMenuCell = collectionView.cellForItem(at: IndexPath(item: newIndex, section: 0)) as? Example3MenuCell {
// 菜单发生切换,且目标位置可以看到。
targetMenuCell.transition = transition
if let currentMenuCell = collectionView.cellForItem(at: IndexPath(item: menuIndex, section: 0)) as? Example3MenuCell {
currentMenuCell.transition = 1.0 - transition
let p1 = currentMenuCell.center
let p2 = targetMenuCell.center
if transition < 0.5 {
if p1.x < p2.x {
let width = (p2.x - p1.x) * transition * 2.0 + 10
indicatorView.frame = CGRect(x: p1.x - 5, y: 37, width: width, height: 3.0)
} else {
let width = (p1.x - p2.x) * transition * 2.0 + 10.0
indicatorView.frame = CGRect(x: p1.x + 5.0 - width, y: 37, width: width, height: 3.0)
}
} else {
if p1.x < p2.x {
let width = (p2.x - p1.x) * (1.0 - transition) * 2.0 + 10.0
indicatorView.frame = CGRect(x: p2.x + 5.0 - width, y: 37, width: width, height: 3.0)
} else {
let width = (p1.x - p2.x) * (1.0 - transition) * 2.0 + 10.0
indicatorView.frame = CGRect(x: p2.x - 5.0, y: 37, width: width, height: 3.0)
}
}
} else {
let p2 = targetMenuCell.center
indicatorView.frame = CGRect.init(x: p2.x - 5.0, y: 37, width: 10, height: 3.0)
}
} else if let currentMenuCell = collectionView.cellForItem(at: IndexPath(item: menuIndex, section: 0)) as? Example3MenuCell {
// 只能看到当前菜单。
currentMenuCell.transition = 1.0 - transition
let p1 = currentMenuCell.center
indicatorView.frame = CGRect.init(x: p1.x - 5.0, y: 37, width: 10, height: 3.0)
} else {
// 看不到当前菜单。
collectionView.performBatchUpdates({
self.collectionView.reloadData()
}, completion: { (_) in
self.menuTranstion(to: newIndex, transition: 0)
})
}
}
}
extension Example3ViewController: CarouselViewTransitioningDelegate {
func carouselView(_ carouselView: CarouselView, animateTransition isInteractive: Bool) {
let width: CGFloat = floor(UIScreen.main.bounds.width / 3.0)
let timingFunction = isInteractive ? nil : CAMediaTimingFunction(name: .easeInEaseOut)
let navigationAnimation = CAKeyframeAnimation(keyPath: #keyPath(CALayer.transform));
navigationAnimation.timingFunction = timingFunction
let shadowRadiusAnimation = CAKeyframeAnimation.init(keyPath: #keyPath(CALayer.shadowRadius))
shadowRadiusAnimation.timingFunction = timingFunction
let shadowOpacityAnimation = CAKeyframeAnimation.init(keyPath: #keyPath(CALayer.shadowOpacity))
shadowOpacityAnimation.timingFunction = timingFunction
let shadowColorAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.shadowColor))
shadowColorAnimation.timingFunction = timingFunction
shadowColorAnimation.fromValue = UIColor.black.cgColor
shadowColorAnimation.toValue = UIColor.black.cgColor
let shadowOffsetAnimation = CABasicAnimation.init(keyPath: #keyPath(CALayer.shadowOffset))
shadowOffsetAnimation.timingFunction = timingFunction
shadowOffsetAnimation.fromValue = NSValue(cgSize: .zero);
shadowOffsetAnimation.toValue = NSValue(cgSize: .zero);
// backwardTransitioningView
navigationAnimation.values = [
CATransform3DMakeTranslation(+width, 0, 0), CATransform3DIdentity
]
navigationAnimation.beginTime = 6.0
navigationAnimation.duration = 1.0
carouselView.backwardTransitioningView.layer.add(navigationAnimation, forKey: "transform")
// transitioningView
navigationAnimation.values = [
CATransform3DIdentity, CATransform3DMakeTranslation(+width, 0, 0)
]
navigationAnimation.beginTime = 0.0
navigationAnimation.duration = 1.0
carouselView.transitioningView.layer.add(navigationAnimation, forKey: "transform1")
navigationAnimation.values = [
CATransform3DIdentity, CATransform3DIdentity
]
navigationAnimation.beginTime = 2.0
navigationAnimation.duration = 1.0
carouselView.transitioningView.layer.add(navigationAnimation, forKey: "transform2")
shadowRadiusAnimation.values = [5.0, 10.0]
shadowOpacityAnimation.values = [0.5, 0.0]
shadowRadiusAnimation.beginTime = 2.0
shadowRadiusAnimation.duration = 1.0
carouselView.transitioningView.layer.add(shadowRadiusAnimation, forKey: "shadowRadius")
shadowOpacityAnimation.beginTime = 2.0
shadowOpacityAnimation.duration = 1.0
carouselView.transitioningView.layer.add(shadowOpacityAnimation, forKey: "shadowOpacity")
shadowColorAnimation.beginTime = 2.0
shadowColorAnimation.duration = 1.0
carouselView.transitioningView.layer.add(shadowColorAnimation, forKey: "shadowColor")
shadowOffsetAnimation.beginTime = 2.0
shadowOffsetAnimation.duration = 1.0
carouselView.transitioningView.layer.add(shadowOffsetAnimation, forKey: "shadowOffset")
// forwardTransitioningView
navigationAnimation.values = [
CATransform3DIdentity, CATransform3DIdentity
]
shadowRadiusAnimation.values = [0.0, 5.0]
shadowOpacityAnimation.values = [0.0, 0.5]
navigationAnimation.beginTime = 4.0
navigationAnimation.duration = 1.0
carouselView.forwardTransitioningView.layer.add(navigationAnimation, forKey: "transform")
shadowRadiusAnimation.beginTime = 4.0
shadowRadiusAnimation.duration = 1.0
carouselView.forwardTransitioningView.layer.add(shadowRadiusAnimation, forKey: "shadowRadius")
shadowOpacityAnimation.beginTime = 4.0
shadowOpacityAnimation.duration = 1.0
carouselView.forwardTransitioningView.layer.add(shadowOpacityAnimation, forKey: "shadowOpacity")
shadowColorAnimation.beginTime = 4.0
shadowColorAnimation.duration = 1.0
carouselView.forwardTransitioningView.layer.add(shadowColorAnimation, forKey: "shadowColor")
shadowOffsetAnimation.beginTime = 4.0
shadowOffsetAnimation.duration = 1.0
carouselView.forwardTransitioningView.layer.add(shadowOffsetAnimation, forKey: "shadowOffset")
}
func carouselView(_ carouselView: CarouselView, animationEnded transitionCompleted: Bool) {
carouselView.backwardTransitioningView.layer.removeAllAnimations()
carouselView.transitioningView.layer.removeAllAnimations()
carouselView.forwardTransitioningView.layer.removeAllAnimations()
}
}
class Example3MenuCell: UICollectionViewCell {
@IBOutlet weak var textLabel: UILabel!
var transition: CGFloat = 0 {
didSet {
textLabel.textColor = UIColor(red: transition * 0xC1 / 255.0, green: transition * 0x06 / 255.0, blue: transition * 0x19 / 255.0, alpha: 1.0)
let scale = 1.0 + transition * 0.1
textLabel.transform = CGAffineTransform(scaleX: scale, y: scale)
}
}
}
| mit |
swaruphs/Password-Validator-Swift | Password-Validator/Password-Validator.swift | 1 | 1680 | //
// Password-Validator.swift
// Password-Validator
//
// Created by Swarup on 20/2/17.
//
//
import Foundation
public enum ValidationRules {
case UpperCase
case LowerCase
case Digit
case SpecialCharacter
fileprivate var characterSet:CharacterSet {
switch self {
case .UpperCase:
return NSCharacterSet.uppercaseLetters
case .LowerCase:
return NSCharacterSet.lowercaseLetters
case .Digit:
return NSCharacterSet.decimalDigits
case .SpecialCharacter:
return NSCharacterSet.symbols
}
}
}
public struct PasswordValidator {
var minLength = 0
var maxLength = 128
var rules: [ValidationRules] = [.LowerCase]
public init(rules validationRules:[ValidationRules] = [.LowerCase], minLength min:Int = 0, maxLength max:Int = 128) {
minLength = min
maxLength = max
if validationRules.count > 0 {
rules = validationRules
}
}
public func isValid(password pwdString: String) -> Bool {
if pwdString.characters.count < minLength {
return false
}
if pwdString.characters.count > maxLength {
return false
}
for rule in self.rules {
let hasMember = pwdString.unicodeScalars.contains { ( u: UnicodeScalar) -> Bool in
rule.characterSet.contains(u)
}
if hasMember == false {
return false
}
}
return true
}
}
| apache-2.0 |
kaich/CKAlertView | CKAlertView/Classes/Core/CKAlertViewComponent.swift | 1 | 16819 | //
// CKAlertViewComponent.swift
// Pods
//
// Created by mac on 16/10/11.
//
//
import UIKit
extension UIImage {
class func imageWithColor(color :UIColor) -> UIImage? {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(color.cgColor)
context.fill(rect)
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image;
}
}
protocol CKAlertViewComponentDelegate :class {
func clickButton(at index :Int);
}
class CKAlertViewComponent: UIView {
weak var delegate :CKAlertViewComponentDelegate?
var config :(() -> CKAlertViewConfiguration)!
var textColor :UIColor?
var textFont :UIFont?
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup() {
fatalError("setup() has not been implemented")
}
func makeLayout() {
fatalError("makeLayout() has not been implemented")
}
}
class CKAlertViewComponentBaseMaker {
weak var delegate :CKAlertViewComponentDelegate?
weak var alertView :CKAlertView?
internal lazy var headerView :CKAlertViewComponent! = self.makeHeader()
internal lazy var bodyView :CKAlertViewComponent! = self.makeBody()
internal lazy var footerView :CKAlertViewComponent! = self.makeFooter()
var alertTitle :CKAlertViewStringable?
var cancelButtonTitle: CKAlertViewStringable?
var otherButtonTitles :[CKAlertViewStringable]?
private var isMakeLayoutCompleted = false
func makeComponents() {
headerView.delegate = delegate
bodyView.delegate = delegate
footerView.delegate = delegate
let finalConfig = { return (self.alertView?.config)! }
headerView.config = finalConfig
bodyView.config = finalConfig
footerView.config = finalConfig
}
func makeLayout() {
if !isMakeLayoutCompleted {
headerView.makeLayout()
bodyView.makeLayout()
footerView.makeLayout()
isMakeLayoutCompleted = true
}
}
func makeHeader() -> CKAlertViewComponent? {
fatalError("layoutHeader() has not been implemented")
}
func makeBody() -> CKAlertViewComponent? {
fatalError("layoutBody() has not been implemented")
}
func makeFooter() -> CKAlertViewComponent? {
fatalError("layoutFooter() has not been implemented")
}
}
class CKAlertViewComponentMaker : CKAlertViewComponentBaseMaker {
var alertMessages :[CKAlertViewStringable]?
var indentationPatternWidth :[String : CGFloat]? {
didSet {
if let bodyView = self.bodyView as? CKAlertViewBodyView {
bodyView.indentationPattern2WidthDic = indentationPatternWidth
}
}
}
override func makeHeader() -> CKAlertViewComponent? {
let headerView = CKAlertViewHeaderView()
headerView.alertTitle = alertTitle
return headerView
}
override func makeBody() -> CKAlertViewComponent? {
let bodyView = CKAlertViewBodyView()
bodyView.alertMessages = alertMessages
return bodyView
}
override func makeFooter() -> CKAlertViewComponent? {
let footerView = CKAlertViewFooterView()
footerView.cancelButtonTitle = cancelButtonTitle
footerView.otherButtonTitles = otherButtonTitles
return footerView
}
}
class CKAlertViewHeaderView: CKAlertViewComponent {
var alertTitle :CKAlertViewStringable?
override func setup () {
self.textColor = UIColor.black
}
override func makeLayout() {
guard alertTitle != nil else {
return
}
self.textFont = config().titleFont
let titleLabel = UILabel()
titleLabel.backgroundColor = UIColor.clear
titleLabel.numberOfLines = 0
titleLabel.textAlignment = .center
titleLabel.font = textFont
titleLabel.textColor = textColor
titleLabel.ck_setText(string: alertTitle, isCenter: true)
self.addSubview(titleLabel)
titleLabel.snp.makeConstraints { (make) in
make.top.equalTo(self).offset(20)
make.left.equalTo(self).offset(20)
make.right.equalTo(self).offset(-20)
make.bottom.equalTo(self).offset(-10)
}
}
}
class CKAlertViewBodyView: CKAlertViewComponent {
var indentationPattern2WidthDic : [String : CGFloat]?
var alertMessages :[CKAlertViewStringable]?
override func setup () {
self.textColor = UIColor.black
}
/// $ represent paragraph end
override func makeLayout() {
self.textFont = config().messageFont
if let alertMessages = alertMessages {
var isParagraphBegin = false
var lastMessageLabel :UITextView? = nil
var pureMessage :String = ""
for (index,emMessage) in alertMessages.enumerated() {
pureMessage = emMessage.ck_string()
if pureMessage == "$" {
isParagraphBegin = true
}
else {
var messageLabel :UITextView!
let checkResult = check(string: emMessage.ck_string(), indentationPattern2WidthDic: indentationPattern2WidthDic)
if checkResult.isNeedindentation {
let zeroRect = CGRect(x: 0, y: 0, width: 0, height: 0)
let textStorage = NSTextStorage()
let layoutManager = NSLayoutManager()
let textContainer = NSTextContainer(size: zeroRect.size)
textContainer.exclusionPaths = [UIBezierPath(rect: CGRect(x: 0, y: getLineHeight(string: emMessage), width: checkResult.indentationWidth, height: CGFloat.greatestFiniteMagnitude))]
textStorage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(textContainer)
messageLabel = UITextView(frame: zeroRect, textContainer: textContainer)
}
else {
messageLabel = UITextView()
}
messageLabel.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
messageLabel.textContainer.lineFragmentPadding = 0;
messageLabel.isEditable = false
messageLabel.isSelectable = false
messageLabel.isScrollEnabled = false
messageLabel.backgroundColor = UIColor.clear
messageLabel.textContainer.lineBreakMode = .byCharWrapping
messageLabel.font = textFont
messageLabel.textColor = textColor
messageLabel.textAlignment = .left
messageLabel.ck_setText(string: emMessage)
addSubview(messageLabel)
if alertMessages.count == 1 {
messageLabel.snp.makeConstraints({ (make) in
make.left.greaterThanOrEqualTo(self).offset(20)
make.right.lessThanOrEqualTo(self).offset(-20)
make.centerX.equalTo(self)
make.top.equalTo(self)
make.bottom.equalTo(self).offset(-20)
})
}
else {
messageLabel.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(20)
make.right.equalTo(self).offset(-20)
if index == 0 {
make.top.equalTo(self)
} else {
if isParagraphBegin == true {
make.top.equalTo(lastMessageLabel!.snp.bottom).offset(config().paragraphSpacing)
isParagraphBegin = false
} else {
make.top.equalTo(lastMessageLabel!.snp.bottom).offset(config().lineSpacing)
}
if index == alertMessages.count - 1 {
make.bottom.equalTo(self).offset(-20)
}
}
}
lastMessageLabel = messageLabel
}
}
}
}
}
func getLineHeight(string :CKAlertViewStringable) -> CGFloat {
var lineHeight :CGFloat = 0
if string is String {
if let textFont = textFont {
lineHeight = textFont.lineHeight
}
}
else if let attributeStr = string as? NSAttributedString {
let finalAttributes = attributeStr.attributes(at: 0, effectiveRange: nil)
if let fontSize = finalAttributes[NSAttributedString.Key.font] as? UIFont {
lineHeight = fontSize.lineHeight
}
else {
if let textFont = textFont {
lineHeight = textFont.lineHeight
}
}
if let paragraphStyle = finalAttributes[NSAttributedString.Key.paragraphStyle] as? NSMutableParagraphStyle {
lineHeight += paragraphStyle.lineSpacing
}
}
return ceil(lineHeight)
}
func check(string :String, indentationPattern2WidthDic :[String : CGFloat]?) -> (isNeedindentation :Bool, indentationWidth :CGFloat) {
var isNeedindentation = false
var indentationWidth :CGFloat = 0
if let indentationPattern2WidthDic = indentationPattern2WidthDic {
for (indentationPattern, width) in indentationPattern2WidthDic {
if let regex = try? NSRegularExpression(pattern: indentationPattern, options: .caseInsensitive) {
let count = regex.numberOfMatches(in: string, options: .anchored, range: NSMakeRange(0, string.count))
if count > 0 {
isNeedindentation = true
indentationWidth = width
}
}
}
}
return (isNeedindentation, indentationWidth)
}
}
class CKAlertViewFooterView: CKAlertViewComponent {
var cancelButton :UIButton!
var otherButtons = [UIButton]()
var cancelButtonTitle :CKAlertViewStringable?
var otherButtonTitles :[CKAlertViewStringable]?
var cancelButtonTitleFont :UIFont?
var cancelButtonTitleColor :UIColor?
override func setup () {
self.textFont = UIFont.systemFont(ofSize: 15)
self.cancelButtonTitleFont = UIFont.systemFont(ofSize: 15)
}
override func makeLayout() {
guard cancelButtonTitle != nil || otherButtons.count > 0 else {
return
}
self.textColor = config().otherTitleColor
self.cancelButtonTitleColor = config().cancelTitleColor
let _ = makeFooterTopHSplitLine()
makeButtons(cancelButtonTitle: cancelButtonTitle, otherButtonTitles: otherButtonTitles)
if otherButtons.count > 0 {
if otherButtons.count == 1 {
layoutOnlyTwoButtons()
}
else {
layoutMultiButtons()
}
}
else if cancelButtonTitle != nil {
layoutOnlyCancelButton()
}
}
func makeButtons(cancelButtonTitle: CKAlertViewStringable?,otherButtonTitles :[CKAlertViewStringable]? = nil) {
cancelButton = UIButton(type: .system)
cancelButton.setTitleColor(cancelButtonTitleColor, for: .normal)
cancelButton.backgroundColor = config().cancelBackgroundColor
cancelButton.titleLabel?.font = cancelButtonTitleFont
cancelButton.setBorder(config().cancelBorder)
cancelButton.ck_setText(string: cancelButtonTitle)
cancelButton.addTarget(self, action: #selector(clickButton(sender:)), for: .touchUpInside)
self.addSubview(cancelButton)
otherButtons = [UIButton]()
if let otherButtonTitles = otherButtonTitles {
for title in otherButtonTitles {
let otherButton = UIButton(type: .system)
otherButton.setTitleColor(textColor, for: .normal)
otherButton.backgroundColor = config().otherBackgroundColorColor
otherButton.titleLabel?.font = textFont
cancelButton.setBorder(config().cancelBorder)
otherButton.ck_setText(string: title)
otherButton.addTarget(self, action: #selector(clickButton(sender:)), for: .touchUpInside)
self.addSubview(otherButton)
otherButtons.append(otherButton)
}
}
}
func makeFooterTopHSplitLine() -> UIView? {
let splitLineView = UIView()
splitLineView.backgroundColor = config().splitLineColor
self.addSubview(splitLineView)
splitLineView.snp.makeConstraints { (make) in
make.top.right.left.equalTo(self)
make.height.equalTo(config().splitLineWidth)
}
return splitLineView
}
func layoutOnlyCancelButton() {
cancelButton.snp.makeConstraints { (make) in
make.top.bottom.left.right.equalTo(self)
make.height.equalTo(config().buttonDefaultHeight)
}
}
func layoutOnlyTwoButtons() {
let vMidSplitLineView = UIView()
vMidSplitLineView.backgroundColor = config().splitLineColor
self.addSubview(vMidSplitLineView)
cancelButton.snp.makeConstraints { (make) in
make.top.bottom.left.equalTo(self)
make.height.equalTo(config().buttonDefaultHeight)
}
vMidSplitLineView.snp.makeConstraints({ (make) in
make.left.equalTo(cancelButton.snp.right)
make.top.bottom.height.equalTo(cancelButton)
make.width.equalTo(config().splitLineWidth)
})
if let anotherButton = otherButtons.first {
anotherButton.snp.makeConstraints { (make) in
make.left.equalTo(vMidSplitLineView.snp.right)
make.top.bottom.right.equalTo(self)
make.width.height.equalTo(cancelButton)
}
}
}
func layoutMultiButtons() {
cancelButton.backgroundColor = config().multiButtonBackgroundColor
cancelButton.setTitleColor(UIColor.white, for: .normal)
cancelButton.snp.makeConstraints { (make) in
make.top.equalTo(self).offset(10)
make.left.equalTo(self).offset(20)
make.right.equalTo(self).offset(-20)
make.height.equalTo(config().multiButtonHeight)
}
for (index,emButton) in otherButtons.enumerated() {
emButton.backgroundColor = config().multiButtonBackgroundColor
emButton.setTitleColor(UIColor.white, for: .normal)
emButton.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(20)
make.right.equalTo(self).offset(-20)
make.height.equalTo(config().multiButtonHeight)
if index == 0 {
make.top.equalTo(cancelButton.snp.bottom).offset(10)
}
else {
let lastButton = otherButtons[index - 1]
make.top.equalTo(lastButton.snp.bottom).offset(10)
if index == otherButtons.count - 1 {
make.bottom.equalTo(self).offset(-20)
}
}
}
}
}
@objc func clickButton(sender :UIButton) {
//index of cancel button is 0
var index = 0
if otherButtons.contains(sender) {
index = otherButtons.index(of: sender)! + 1
}
if let delegate = delegate {
delegate.clickButton(at: index)
}
}
}
| mit |
RokkinCat/harmonic | Harmonic/UserModel.swift | 1 | 676 | //
// UserModel.swift
// Harmonic
//
// Created by Josh Holtz on 8/11/14.
// Copyright (c) 2014 Josh Holtz. All rights reserved.
//
import Foundation
class UserModel: HarmonicModel {
var firstName: String?
var lastName: String?
var bestFriend: UserModel?
var friends: Array<UserModel>?
var birthday: NSDate?
required init() {
}
func parse(json : JSONObject) {
self.firstName <*> json["first_name"]
self.lastName <*> json["last_name"]
self.bestFriend <*> json["best_friend"]
self.friends <*> json["friends"]
self.birthday <*> json["birthday"] >>> MyCustomFormatter.ToBirthday
}
} | mit |
crspybits/SMSyncServer | iOS/iOSTests/Pods/SMCoreLib/SMCoreLib/Classes/Views/SMImageTextView/SMImageTextView+JSON.swift | 3 | 4656 | //
// SMImageTextView+JSON.swift
// SMCoreLib
//
// Created by Christopher Prince on 6/2/16.
// Copyright © 2016 Spastic Muffin, LLC. All rights reserved.
//
import Foundation
public extension SMImageTextView {
public func contentsToData() -> NSData? {
guard let currentContents = self.contents
else {
return nil
}
return SMImageTextView.contentsToData(currentContents)
}
public class func contentsToData(contents:[ImageTextViewElement]) -> NSData? {
// First create array of dictionaries.
var array = [[String:AnyObject]]()
for elem in contents {
array.append(elem.toDictionary())
}
var jsonData:NSData?
do {
try jsonData = NSJSONSerialization.dataWithJSONObject(array, options: NSJSONWritingOptions(rawValue: 0))
} catch (let error) {
Log.error("Error serializing array to JSON data: \(error)")
return nil
}
let jsonString = NSString(data: jsonData!, encoding: NSUTF8StringEncoding) as? String
Log.msg("json results: \(jsonString)")
return jsonData
}
public func saveContents(toFileURL fileURL:NSURL) -> Bool {
guard let jsonData = self.contentsToData()
else {
return false
}
do {
try jsonData.writeToURL(fileURL, options: .AtomicWrite)
} catch (let error) {
Log.error("Error writing JSON data to file: \(error)")
return false
}
return true
}
// Give populateImagesUsing as non-nil to populate the images.
private class func contents(fromJSONData jsonData:NSData?, populateImagesUsing smImageTextView:SMImageTextView?) -> [ImageTextViewElement]? {
var array:[[String:AnyObject]]?
if jsonData == nil {
return nil
}
do {
try array = NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions(rawValue: 0)) as? [[String : AnyObject]]
} catch (let error) {
Log.error("Error converting JSON data to array: \(error)")
return nil
}
if array == nil {
return nil
}
var results = [ImageTextViewElement]()
for dict in array! {
if let elem = ImageTextViewElement.fromDictionary(dict) {
var elemToAdd = elem
switch elem {
case .Image(_, let uuid, let range):
if smImageTextView == nil {
elemToAdd = .Image(nil, uuid, range)
}
else {
if let image = smImageTextView!.imageDelegate?.smImageTextView(smImageTextView!, imageForUUID: uuid!) {
elemToAdd = .Image(image, uuid, range)
}
else {
return nil
}
}
default:
break
}
results.append(elemToAdd)
}
else {
return nil
}
}
return results
}
public class func contents(fromJSONData jsonData:NSData?) -> [ImageTextViewElement]? {
return self.contents(fromJSONData: jsonData, populateImagesUsing: nil)
}
// Concatenates all of the string components. Ignores the images.
public class func contentsAsConcatenatedString(fromJSONData jsonData:NSData?) -> String? {
if let contents = SMImageTextView.contents(fromJSONData: jsonData) {
var result = ""
for elem in contents {
switch elem {
case .Text(let string, _):
result += string
default:
break
}
}
return result
}
return nil
}
public func loadContents(fromJSONData jsonData:NSData?) -> Bool {
self.contents = SMImageTextView.contents(fromJSONData: jsonData, populateImagesUsing: self)
return self.contents == nil ? false : true
}
public func loadContents(fromJSONFileURL fileURL:NSURL) -> Bool {
guard let jsonData = NSData(contentsOfURL: fileURL)
else {
return false
}
return self.loadContents(fromJSONData: jsonData)
}
} | gpl-3.0 |
Sherlouk/IGListKit | Examples/Examples-iOS/IGListKitExamples/ViewControllers/SingleSectionViewController.swift | 2 | 3262 | /**
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
import IGListKit
final class SingleSectionViewController: UIViewController, IGListAdapterDataSource, IGListSingleSectionControllerDelegate {
lazy var adapter: IGListAdapter = {
return IGListAdapter(updater: IGListAdapterUpdater(), viewController: self, workingRangeSize: 0)
}()
let collectionView = IGListCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
let data = Array(0..<20)
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(collectionView)
adapter.collectionView = collectionView
adapter.dataSource = self
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.frame = view.bounds
}
//MARK: - IGListAdapterDataSource
func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] {
return data as [IGListDiffable]
}
func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController {
let configureBlock = { (item: Any, cell: UICollectionViewCell) in
guard let cell = cell as? NibCell, let number = item as? Int else { return }
cell.textLabel.text = "Cell: \(number + 1)"
}
let sizeBlock = { (item: Any, context: IGListCollectionContext?) -> CGSize in
guard let context = context else { return CGSize() }
return CGSize(width: context.containerSize.width, height: 44)
}
let sectionController = IGListSingleSectionController(nibName: NibCell.nibName,
bundle: nil,
configureBlock: configureBlock,
sizeBlock: sizeBlock)
sectionController.selectionDelegate = self
return sectionController
}
func emptyView(for listAdapter: IGListAdapter) -> UIView? { return nil }
// MARK: - IGListSingleSectionControllerDelegate
func didSelect(_ sectionController: IGListSingleSectionController) {
let section = adapter.section(for: sectionController) + 1
let alert = UIAlertController(title: "Section \(section) was selected \u{1F389}", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
| bsd-3-clause |
roambotics/swift | test/PrintAsObjC/empty.swift | 2 | 1778 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) %s -typecheck -emit-objc-header-path %t/empty.h
// RUN: %FileCheck %s < %t/empty.h
// RUN: %check-in-clang -std=c99 %t/empty.h
// RUN: %check-in-clang -std=c11 %t/empty.h
// RUN: %check-cxx-header-in-clang -x objective-c++-header -std=c++98 -D_LIBCPP_CSTDLIB %t/empty.h
// RUN: %check-cxx-header-in-clang -x objective-c++-header -std=c++11 -D_LIBCPP_CSTDLIB %t/empty.h
// RUN: %check-cxx-header-in-clang -x objective-c++-header -std=c++14 -D_LIBCPP_CSTDLIB %t/empty.h
// RUN: %check-in-clang -std=c99 -fno-modules -Qunused-arguments %t/empty.h
// RUN: not %check-in-clang -I %S/Inputs/clang-headers %t/empty.h 2>&1 | %FileCheck %s --check-prefix=CUSTOM-OBJC-PROLOGUE
// Make sure we can handle two bridging headers. rdar://problem/22702104
// RUN: %check-in-clang -include %t/empty.h -std=c99 -fno-modules -Qunused-arguments %t/empty.h
// REQUIRES: objc_interop
// CHECK-NOT: @import Swift;
// CHECK-LABEL: #if !defined(__has_feature)
// CHECK-NEXT: # define __has_feature(x) 0
// CHECK-NEXT: #endif
// CHECK-LABEL: #include <Foundation/Foundation.h>
// CHECK: #include <stdint.h>
// CHECK: #include <stddef.h>
// CHECK: #include <stdbool.h>
// CHECK: # define SWIFT_METATYPE(X)
// CHECK: # define SWIFT_CLASS
// CHECK: # define SWIFT_CLASS_NAMED
// CHECK: # define SWIFT_PROTOCOL
// CHECK: # define SWIFT_PROTOCOL_NAMED
// CHECK: # define SWIFT_EXTENSION(M)
// CHECK: # define OBJC_DESIGNATED_INITIALIZER
// CHECK-LABEL: #if __has_feature(objc_modules)
// CHECK-NEXT: #if __has_warning
// CHECK-NEXT: #pragma clang diagnostic
// CHECK-NEXT: #endif
// CHECK-NEXT: #endif
// CHECK-NOT: {{[@;{}]}}
// CUSTOM-OBJC-PROLOGUE: swift/objc-prologue.h:1:2: error: "Prologue included"
| apache-2.0 |