repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
firebase/quickstart-ios | authentication/LegacyAuthQuickstart/AuthenticationExampleSwift/UIViewController.swift | 1 | 3589 | //
// Copyright (c) 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
private class SaveAlertHandle {
static var alertHandle: UIAlertController?
class func set(_ handle: UIAlertController) {
alertHandle = handle
}
class func clear() {
alertHandle = nil
}
class func get() -> UIAlertController? {
return alertHandle
}
}
extension UIViewController {
/*! @fn showMessagePrompt
@brief Displays an alert with an 'OK' button and a message.
@param message The message to display.
*/
func showMessagePrompt(_ message: String) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
present(alert, animated: false, completion: nil)
}
/*! @fn showTextInputPromptWithMessage
@brief Shows a prompt with a text field and 'OK'/'Cancel' buttons.
@param message The message to display.
@param completion A block to call when the user taps 'OK' or 'Cancel'.
*/
func showTextInputPrompt(withMessage message: String,
completionBlock: @escaping ((Bool, String?) -> Void)) {
let prompt = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
completionBlock(false, nil)
}
weak var weakPrompt = prompt
let okAction = UIAlertAction(title: "OK", style: .default) { _ in
guard let text = weakPrompt?.textFields?.first?.text else { return }
completionBlock(true, text)
}
prompt.addTextField(configurationHandler: nil)
prompt.addAction(cancelAction)
prompt.addAction(okAction)
present(prompt, animated: true, completion: nil)
}
/*! @fn showSpinner
@brief Shows the please wait spinner.
@param completion Called after the spinner has been hidden.
*/
func showSpinner(_ completion: (() -> Void)?) {
let alertController = UIAlertController(title: nil, message: "Please Wait...\n\n\n\n",
preferredStyle: .alert)
SaveAlertHandle.set(alertController)
let spinner = UIActivityIndicatorView(style: .whiteLarge)
spinner.color = UIColor(ciColor: .black)
spinner.center = CGPoint(x: alertController.view.frame.midX,
y: alertController.view.frame.midY)
spinner.autoresizingMask = [.flexibleBottomMargin, .flexibleTopMargin,
.flexibleLeftMargin, .flexibleRightMargin]
spinner.startAnimating()
alertController.view.addSubview(spinner)
present(alertController, animated: true, completion: completion)
}
/*! @fn hideSpinner
@brief Hides the please wait spinner.
@param completion Called after the spinner has been hidden.
*/
func hideSpinner(_ completion: (() -> Void)?) {
if let controller = SaveAlertHandle.get() {
SaveAlertHandle.clear()
controller.dismiss(animated: true, completion: completion)
}
}
}
| apache-2.0 | 59439598ebd0ac629c2789aa43989b42 | 35.622449 | 90 | 0.685149 | 4.475062 | false | false | false | false |
ibhupi/cksapp | ios-app/cksapp/Classes/Datamodel/Scrubber/ObjectScrubber/BaseScrubber.swift | 1 | 1573 | //
// BaseScrubber.swift
// cksapp
//
// Created by Bhupendra Singh on 7/2/16.
// Copyright ยฉ 2016 Bhupendra Singh. All rights reserved.
//
import UIKit
class BaseScrubber: NSObject {
class internal func minimusKeys() -> [String]? {
return nil
}
class internal func mappedKeys() -> [String: String]? {
return nil
}
class internal func inValid(data: [String: AnyObject]) -> Bool {
if let keys = self.minimusKeys() {
for key in keys {
if (data[key] == nil) {
return true
}
}
}
return false
}
class func scrubObjectFromData(var data:[String: AnyObject]) -> [String: AnyObject]? {
// Check neccessary keys from server are present
if self.inValid(data) {
return nil
}
// Map server keys to objects local keys
if let mappedKeys = self.mappedKeys() {
for key in mappedKeys.keys {
if let mappedKey = mappedKeys[key], value = data.removeValueForKey(key) {
data[mappedKey] = value
}
}
}
return data
}
class func scrubObjectArrayFromData(data:[[String: AnyObject]]) -> [AnyObject]? {
var scrubbedData = [AnyObject]()
for item in data {
if let scrubbedItem = self.scrubObjectFromData(item) {
scrubbedData.append(scrubbedItem)
}
}
return scrubbedData
}
}
| apache-2.0 | 64ed03bb27b9e68d5551690cbd22ac94 | 25.2 | 90 | 0.524809 | 4.440678 | false | false | false | false |
pccole/GitHubJobs-iOS | GitHubJobs/PropertyWrappers/OptionalURLValue.swift | 1 | 616 | //
// OptionalURLValue.swift
// GitHubJobs
//
// Created by Phil Cole on 4/22/20.
// Copyright ยฉ 2020 Cole LLC. All rights reserved.
//
import Foundation
@propertyWrapper
public struct OptionalURLValue: Codable {
private let value: String?
public var wrappedValue: URL?
public init(wrappedValue: URL?) {
self.wrappedValue = wrappedValue
value = wrappedValue?.absoluteString
}
public init(from decoder: Decoder) throws {
value = try String?(from: decoder)
guard let string = value else { return }
wrappedValue = URL(string: string)
}
}
| mit | 3daa34ca7e3398a322af914d1587ca64 | 22.653846 | 51 | 0.653659 | 4.270833 | false | false | false | false |
m1entus/MZFormSheetPresentationController | Example/Swift/MZFormSheetPresentationController Swift Example/TransparentViewController.swift | 1 | 1347 | //
// TransparentViewController.swift
// MZFormSheetPresentationController Swift Example
//
// Created by Michal Zaborowski on 22.06.2015.
// Copyright (c) 2015 Michal Zaborowski. All rights reserved.
//
import UIKit
class TransparentViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func turnOnTransparencyButtonTapped() {
if let viewController = self.mz_formSheetPresentingPresentationController() {
viewController.presentationController?.backgroundColor = UIColor.clear
viewController.presentationController?.isTransparentTouchEnabled = true
}
}
@IBAction func turnOffTransparencyButtonTapped() {
if let viewController = self.mz_formSheetPresentingPresentationController() {
viewController.presentationController?.backgroundColor = UIColor.black.withAlphaComponent(0.3)
viewController.presentationController?.isTransparentTouchEnabled = false
}
}
@IBAction func dismiss() {
self.dismiss(animated: true, completion: nil)
}
}
| mit | 70bfd0161a269edccecb722c1b599bc1 | 29.613636 | 106 | 0.700074 | 5.707627 | false | false | false | false |
fienlute/programmeerproject | GOals/Goal.swift | 1 | 1533 | //
// Goal.swift
// GOals
//
// Created by Fien Lute on 13-01-17.
// Copyright ยฉ 2017 Fien Lute. All rights reserved.
//
import Foundation
import Firebase
struct Goal {
let key: String
let name: String
let addedByUser: String
let ref: FIRDatabaseReference?
var completed: Bool
let points: Int
let group: String
let completedBy: String
init(name: String, addedByUser: String, completed: Bool, points: Int, group: String, completedBy: String, key: String = "") {
self.key = key
self.name = name
self.addedByUser = addedByUser
self.completed = completed
self.points = points
self.group = group
self.completedBy = completedBy
self.ref = nil
}
init(snapshot: FIRDataSnapshot) {
key = snapshot.key
let snapshotValue = snapshot.value as! [String: AnyObject]
name = snapshotValue["name"] as! String
addedByUser = snapshotValue["addedByUser"] as! String
completed = snapshotValue["completed"] as! Bool
points = snapshotValue["points"] as! Int
group = snapshotValue["group"] as! String
completedBy = snapshotValue["completedBy"] as! String
ref = snapshot.ref
}
func toAnyObject() -> Any {
return [
"name": name,
"addedByUser": addedByUser,
"completed": completed,
"points": points,
"group": group,
"completedBy": completedBy
]
}
}
| mit | bca8e3e55fac7a825234cf23e43e5ec2 | 25.877193 | 129 | 0.591384 | 4.389685 | false | false | false | false |
Drusy/auvergne-webcams-ios | AuvergneWebcams/KeyboardLayoutConstraint.swift | 1 | 4922 | // The MIT License (MIT)
//
// Copyright (c) 2015 James Tang ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class KeyboardLayoutConstraint: NSLayoutConstraint {
private var offset: CGFloat = 0
var keyboardVisibleHeight: CGFloat = 0
var additionalHeight: CGFloat = 0
override public func awakeFromNib() {
super.awakeFromNib()
offset = constant
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardLayoutConstraint.keyboardWillShowNotification(_: )), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardLayoutConstraint.keyboardWillHideNotification(_: )), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: Notification
@objc func keyboardWillShowNotification(_ notification: Notification) {
if let userInfo = notification.userInfo {
if let frameValue = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let frame = frameValue.cgRectValue
keyboardVisibleHeight = frame.size.height
}
self.updateConstant(isShowing: true)
switch (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber, userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber) {
case let (.some(duration), .some(curve)):
let options = UIViewAnimationOptions(rawValue: curve.uintValue)
UIView.animate(
withDuration: TimeInterval(duration.doubleValue),
delay: 0,
options: options,
animations: {
UIApplication.shared.keyWindow?.layoutIfNeeded()
return
},
completion: nil)
default:
break
}
}
}
@objc func keyboardWillHideNotification(_ notification: NSNotification) {
keyboardVisibleHeight = 0
self.updateConstant(isShowing: false)
if let userInfo = notification.userInfo {
switch (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber, userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber) {
case let (.some(duration), .some(curve)):
let options = UIView.AnimationOptions(rawValue: curve.uintValue)
UIView.animate(
withDuration: TimeInterval(duration.doubleValue),
delay: 0,
options: options,
animations: {
UIApplication.shared.keyWindow?.layoutIfNeeded()
return
},
completion: nil)
default:
break
}
}
}
func updateConstant(isShowing: Bool) {
// Keyboard
self.constant = offset + keyboardVisibleHeight
if isShowing {
self.additionalHeight = 0
// Tabbar
if let rootViewController = UIApplication.shared.keyWindow?.rootViewController {
if let tabbar = rootViewController.viewIfLoaded?.get(all: UITabBar.self).first {
additionalHeight += tabbar.bounds.height
}
}
// Safe area
if #available(iOS 11.0, *) {
additionalHeight += UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0
}
self.constant -= additionalHeight
}
}
}
| apache-2.0 | 5b3ce2635176b4b223d9812160d3defc | 38.376 | 192 | 0.604632 | 5.973301 | false | false | false | false |
exoplatform/exo-ios | eXo/Sources/Controllers/AddDomainVC/CustomPopupVC/CustomPopupViewController.swift | 1 | 2415 | //
// CustomPopupViewController.swift
// IAM
//
// Created by Wajih Benabdessalem on 2/16/21.
//
import UIKit
enum ActionHandler {
case defaultAction
case delete
}
class CustomPopupViewController: UIViewController {
// MARK: - Outlets .
@IBOutlet weak var containerView: DesignableView!
@IBOutlet weak var okButton: UIButton!
@IBOutlet weak var noButton: UIButton!
@IBOutlet weak var discriptionLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
// MARK: - Variables .
var descriptionMessage:String = ""
var titleDescription:String = ""
var actionHandler:ActionHandler!
var serverToDelete:Server!
override func viewDidLoad() {
super.viewDidLoad()
initView()
}
func initView(){
okButton.addCornerRadiusWith(radius: 5.0)
noButton.addBorderWith(width: 1, color: UIColor(hex: 0x4382BF).withAlphaComponent(0.5), cornerRadius: 5.0)
discriptionLabel.text = descriptionMessage
titleLabel.text = titleDescription
switch actionHandler {
case .delete:
let okButtonTitle = "Delete".localized
let noButtonTitle = "Cancel".localized
okButton.setTitle(okButtonTitle, for: .normal)
noButton.setTitle(noButtonTitle, for: .normal)
noButton.isHidden = false
noButton.isEnabled = true
default:
okButton.frame.origin.x = containerView.frame.size.width/2 - okButton.frame.size.width/2
noButton.isHidden = true
noButton.isEnabled = false
}
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissPopup(_:)))
self.view.addGestureRecognizer(tapGesture)
}
@objc
func dismissPopup(_ sender: UITapGestureRecognizer) {
self.dismiss(animated: false, completion: nil)
}
@IBAction func okButtonTapped(_ sender: Any) {
switch actionHandler {
case .delete:
dismiss(animated: false) {
ServerManager.sharedInstance.removeServer(self.serverToDelete)
self.postNotificationWith(key: .deleteInstance)
}
default:
self.dismiss(animated:false,completion:nil)
}
}
@IBAction func noButtonTapped(_ sender: Any) {
self.dismiss(animated:false,completion:nil)
}
}
| lgpl-3.0 | 62dd341b0b10a170ebc2dea1dafeef54 | 29.56962 | 114 | 0.638095 | 4.662162 | false | false | false | false |
amberstar/the-component-pattern | ComponentKit/operators/Experimental.swift | 2 | 4289 |
//
// Component: Experimental.swift
// Copyright ยฉ 2016 SIMPLETOUCH LLC. All rights reserved.
//
//===----------------------------------------------------------------------===//
//// MARK: - Combine
//===----------------------------------------------------------------------===//
/// An operator that combined its input with the output of an embedded operator
/// producing a tuple of the initial input, and the output of the combined operator.
public struct Combine<Element, T> : OperatorProtocol {
//public typealias Output = (Element, T)
public typealias Combinator = (Element) -> (Element, T)?
var combinator: Combinator
public mutating func input(_ element: Element) -> (Element, T)? {
return combinator(element)
}
public init<O:OperatorProtocol>(with o: O) where O.Input == Element, O.Output == T {
var op = o
self.init { op.input($0) }
}
public init(with f: @escaping (Element) -> T?) {
let f: Combinator = { input in
if let nxt = f(input) {
return (input, nxt)
}
else { return nil }
}
combinator = f
}
public init(with combinator: @escaping Combinator) {
self.combinator = combinator
}
}
extension OperatorProtocol {
///combine with the output of the specified operator producing a tuple
public func combine<T, O:OperatorProtocol>(with: O) -> Operator<Input, (Output, T)> where O.Input == Output, O.Output == T {
return compose(Combine<Output, T>(with: with))
}
public func combine<T>(with: @escaping (Output) -> (Output, T)?) -> Operator<Input, (Output, T)> {
return compose(Combine<Output, T>(with: with))
}
public func combine<T>(with: @escaping (Output) ->T?) -> Operator<Input, (Output, T)> {
return compose(Combine<Output, T>(with: with))
}
}
//===----------------------------------------------------------------------===//
//// MARK: - Branch
//===----------------------------------------------------------------------===//
extension OperatorProtocol {
/// branch to another operator then continue on with original operator
public func branch<T>(_ target: Operator<Output, T>) -> Operator<Input, Output> {
var targetv = target
let branch = Operator<Output, Output> {
_ = targetv.input($0) ; return $0
}
return compose (branch)
}
}
//===----------------------------------------------------------------------===//
//// MARK: - Evaluate
//===----------------------------------------------------------------------===//
public typealias Evaluation<Element> = (value: Element, result: Bool)
public typealias Evaluator<I, O> = Operator<I, Evaluation<O>>
/// An operator that produces true if a goal has been reached
public struct Evaluate<Element> : OperatorProtocol {
var predicate : (Element) -> Bool
public func input(_ element: Element) -> Evaluation<Element>? {
return (element, predicate(element))
}
/// Creates an instance using the specified predicate function.
public init(predicate: @escaping (Element) -> Bool ) {
self.predicate = predicate
}
}
extension OperatorProtocol {
/// Produce output that satisfies a predicate.
public func evaluate(_ predicate: @escaping (Output) -> Bool ) -> Operator<Input, Evaluation<Output>> {
return compose(Evaluate(predicate: predicate))
}
// /// Produce output that satisfies a predicate.
// public func evaluate(predicate: @escaping (Value<Output>) -> Bool ) -> Function<Input, Evaluation<Output>> {
// return compose(Evaluate { predicate(Value($0))}
// )
// }
}
//===----------------------------------------------------------------------===//
//// MARK: - Default
//===----------------------------------------------------------------------===//
extension OperatorProtocol {
// ensure output by specifying a default value to produce
public func defaultTo(_ value: Output) -> Operator<Input, Output> {
var captured = self
return Operator<Input, Output> {
guard let out = captured.input($0) else { return value }
return out
}
}
}
| mit | 5730301af2cca977edf8f89b732f4cd2 | 33.031746 | 128 | 0.523321 | 4.906178 | false | false | false | false |
DesenvolvimentoSwift/Taster | Taster/PickLocationViewController.swift | 1 | 4203 | //
// PickLocationViewController.swift
// pt.fca.Taster
//
// ยฉ 2016 Luis Marcelino e Catarina Silva
// Desenvolvimento em Swift para iOS
// FCA - Editora de Informรกtica
//
import UIKit
import CoreLocation
import MapKit
class PickLocationViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var map: MKMapView!
let locationManager = CLLocationManager()
var location:CLLocationCoordinate2D?
var annotation = MKPointAnnotation()
var delegate: WriteValueBackDelegate?
@IBAction func cancelLocation(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func saveLocation(_ sender: UIButton) {
if let loc = location {
delegate?.writeValueBack(loc)
}
self.dismiss(animated: true, completion: nil)
}
@IBAction func didTapMap(_ sender: UITapGestureRecognizer) {
let tapPoint: CGPoint = sender.location(in: map)
location = map.convert(tapPoint, toCoordinateFrom: map)
if (location?.latitude != annotation.coordinate.latitude || location?.longitude != annotation.coordinate.longitude) {
map.removeAnnotation(annotation)
annotation.coordinate = location!
annotation.title = "Food location"
annotation.subtitle = " "
map.addAnnotation(annotation)
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "identifier"
var annotationView:MKPinAnnotationView?
if annotation.isKind(of: MKPointAnnotation.self) {
annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView!.canShowCallout = true
annotationView!.pinTintColor = UIColor.purple
} else {
annotationView!.annotation = annotation
}
return annotationView
}
return nil
}
override func viewDidLoad() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.requestWhenInUseAuthorization()
map.delegate = self
map.showsUserLocation = true
}
override func viewDidAppear(_ animated: Bool) {
if let loc = location {
map.setRegion(MKCoordinateRegionMake(loc, MKCoordinateSpanMake(0.1, 0.1)), animated: true)
annotation.coordinate = loc
annotation.title = "Food location"
annotation.subtitle = " "
map.addAnnotation(annotation)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locationObj = locations.last
let coord = locationObj?.coordinate
if let c = coord {
map.setRegion(MKCoordinateRegionMake(c, MKCoordinateSpanMake(0.1, 0.1)), animated: true)
}
}
/*
// 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 | 8d0f07d57fd53d12955daabbcc18c422 | 30.118519 | 125 | 0.624375 | 5.892006 | false | false | false | false |
tensorflow/swift-models | MiniGo/Strategies/RandomPolicy.swift | 1 | 2663 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// A policy generating the next move randomly.
public class RandomPolicy: Policy {
public let participantName: String
public init(participantName: String) {
self.participantName = participantName
}
public func nextMove(for boardState: BoardState, after previousMove: Move?) -> Move {
let legalMoves = boardState.legalMoves
guard !legalMoves.isEmpty else {
return .pass
}
if case .pass? = previousMove {
// If `previousMove` is nil, it means it is a new game. This does not count as opponent pass.
//
// If opponent passed, this random algorithrm should be smarter a little to avoid commiting
// stupid move lowing the current score.
return chooseMoveWithoutLoweringScore(for: boardState)
}
guard let randomMove = legalMoves.randomElement() else {
fatalError("randomElement should not return nil for non-empty legal moves: \(legalMoves).")
}
return .place(position: randomMove)
}
private func chooseMoveWithoutLoweringScore(for boardState: BoardState) -> Move {
var legalMoves = boardState.legalMoves
precondition(!legalMoves.isEmpty)
let currentPlayerColor = boardState.nextPlayerColor
let currentScore = boardState.score(for: currentPlayerColor)
// Instead of sequentially go through `legalMoves`, we sample the move each time to ensure
// randomness.
repeat {
let sampleIndex = Int.random(in: 0..<legalMoves.count)
let candidate = legalMoves[sampleIndex]
let newBoardState = try! boardState.placingNewStone(at: candidate)
let newScore = newBoardState.score(for: currentPlayerColor)
if newScore > currentScore {
return .place(position: candidate)
}
legalMoves.remove(at: sampleIndex)
} while !legalMoves.isEmpty
// If no better choice, then pass.
return .pass
}
}
| apache-2.0 | d91fc41da7c8c4a202d3f3fdd5701b68 | 37.594203 | 105 | 0.668044 | 4.696649 | false | false | false | false |
reedcwilson/sea-level | SeaLevel/SettingsViewController.swift | 1 | 2301 | //
// ViewController.swift
// SeaLevel
//
import UIKit
import Foundation
protocol SettingsViewDelegate {
func settingsViewDidFinish(controller: SettingsViewController)
func getPaddingManager() -> PaddingManager
}
class SettingsViewController: UIViewController {
@IBOutlet weak var paddingTextField: UITextField!
var delegate: SettingsViewDelegate?
var paddingManager = PaddingManager()
// validate the user's input before allowing them to exit
@IBAction func doneButtonExecute(sender: AnyObject) {
// if the the presenting view controller set itself as the delegate
if let delegate = self.delegate {
let padding = paddingTextField.text
// if there is no text, the value is not a number or the number isn't between 0 and 100
if padding == nil || Int(padding!) == nil || Int(padding!) < 0 || Int(padding!) > 100 {
let alertController = UIAlertController(title: "Invalid padding value", message: "You must enter a value between 0 and 100.", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {(alert:UIAlertAction) in self.paddingTextField.text = delegate.getPaddingManager().getDefaultPadding()}))
self.presentViewController(alertController, animated: true, completion: nil)
}
// set the default to the user's value
else {
delegate.getPaddingManager().setDefaultPadding(padding!)
self.view.endEditing(true)
submitResult()
}
}
// otherwise just close
else {
submitResult()
}
}
func submitResult() {
if let delegate = self.delegate {
delegate.settingsViewDidFinish(self)
}
}
// Clicking away from the keyboard will remove the keyboard.
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
override func viewDidLoad() {
super.viewDidLoad()
if let delegate = self.delegate {
paddingTextField.text = delegate.getPaddingManager().getDefaultPadding()
}
}
} | mit | 0644b4d6d4ef51e0ec17f4d96944e7ef | 36.129032 | 219 | 0.644937 | 5.205882 | false | false | false | false |
SheffieldKevin/swiftsvg2 | SwiftSVG/Utilities/SwiftGraphics+Extensions.swift | 1 | 3835 | //
// SwiftGraphics+Extensions.swift
// SwiftSVG
//
// Created by Jonathan Wight on 8/26/15.
// Copyright ยฉ 2015 No. All rights reserved.
//
import SwiftGraphics
public func + (lhs:CGPath, rhs:CGPath) -> CGPath {
let path = CGPathCreateMutableCopy(lhs)!
CGPathAddPath(path, nil, rhs)
return path
}
public extension CGColor {
var components:[CGFloat] {
let count = CGColorGetNumberOfComponents(self)
let componentsPointer = CGColorGetComponents(self)
let components = UnsafeBufferPointer <CGFloat> (start:componentsPointer, count:count)
return Array <CGFloat> (components)
}
var alpha:CGFloat {
return CGColorGetAlpha(self)
}
var colorSpace:CGColorSpace? {
return CGColorGetColorSpace(self)
}
var colorSpaceName:String? {
return CGColorSpaceCopyName(self.colorSpace) as? String
}
}
extension CGColor: CustomReflectable {
public func customMirror() -> Mirror {
return Mirror(self, children: [
"alpha": alpha,
"colorSpace": colorSpaceName,
"components": components,
])
}
}
extension CGColor: Equatable {
}
public func ==(lhs: CGColor, rhs: CGColor) -> Bool {
if lhs.alpha != rhs.alpha {
return false
}
if lhs.colorSpaceName != rhs.colorSpaceName {
return false
}
if lhs.components != rhs.components {
return false
}
return true
}
extension Style: Equatable {
}
public func ==(lhs: Style, rhs: Style) -> Bool {
if lhs.fillColor != rhs.fillColor {
return false
}
if lhs.strokeColor != rhs.strokeColor {
return false
}
if lhs.lineWidth != rhs.lineWidth {
return false
}
if lhs.lineCap != rhs.lineCap {
return false
}
if lhs.miterLimit != rhs.miterLimit {
return false
}
if lhs.lineDash ?? [] != rhs.lineDash ?? [] {
return false
}
if lhs.lineDashPhase != rhs.lineDashPhase {
return false
}
if lhs.flatness != rhs.flatness {
return false
}
if lhs.alpha != rhs.alpha {
return false
}
if lhs.blendMode != rhs.blendMode {
return false
}
return true
}
extension SwiftGraphics.Style {
init() {
self.init(elements: [])
}
var isEmpty: Bool {
get {
return toStyleElements().count == 0
}
}
func toStyleElements() -> [StyleElement] {
var elements: [StyleElement] = []
if let fillColor = fillColor {
elements.append(.FillColor(fillColor))
}
if let strokeColor = strokeColor {
elements.append(.StrokeColor(strokeColor))
}
if let lineWidth = lineWidth {
elements.append(.LineWidth(lineWidth))
}
if let lineCap = lineCap {
elements.append(.LineCap(lineCap))
}
if let lineJoin = lineJoin {
elements.append(.LineJoin(lineJoin))
}
if let miterLimit = miterLimit {
elements.append(.MiterLimit(miterLimit))
}
if let lineDash = lineDash {
elements.append(.LineDash(lineDash))
}
if let lineDashPhase = lineDashPhase {
elements.append(.LineDashPhase(lineDashPhase))
}
if let flatness = flatness {
elements.append(.Flatness(flatness))
}
if let alpha = alpha {
elements.append(.Alpha(alpha))
}
if let blendMode = blendMode {
elements.append(.BlendMode(blendMode))
}
return elements
}
}
func + (lhs: SwiftGraphics.Style, rhs: SwiftGraphics.Style) -> SwiftGraphics.Style {
var accumulator = lhs
accumulator.add(rhs.toStyleElements())
return accumulator
}
| bsd-2-clause | f3cdf33c751312a0166c1c1cc735fc3c | 20.784091 | 93 | 0.586072 | 4.597122 | false | false | false | false |
victore07/CineLater | CineLater/DetailsTableViewController.swift | 1 | 16296 | //
// DetailsTableViewController.swift
// CineLater
//
// Created by Victor Encarnacion on 4/10/16.
// Copyright ยฉ 2016 Victor Encarnacion. All rights reserved.
//
import CoreData
import UIKit
class DetailsTableViewController: UITableViewController, UICollectionViewDelegate, UICollectionViewDataSource {
let cellSize = MovieMediaCellSize()
var images = [Image]()
var movie: Movie!
// MARK: - IBOutlets
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var buttonLabel: UILabel!
@IBOutlet var detailsTable: UITableView!
@IBOutlet weak var imagesLabel: UILabel!
@IBOutlet weak var movieMediaCollectionView: UICollectionView!
@IBOutlet weak var movieMediaFlowLayout: UICollectionViewFlowLayout!
@IBOutlet weak var overviewLabel: UILabel!
@IBOutlet weak var posterImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var watchLaterButton: UIButton!
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Set movieMediaCollectionView delegate and data source
movieMediaCollectionView.delegate = self
movieMediaCollectionView.dataSource = self
// Save a dictionary of current movie to shared defaults object
saveMovie(movie)
// Set movie title and plot
titleLabel.text = movie.movieTitle
overviewLabel.text = movie.overview
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
buttonLabel.text = "Add to CineLater List"
watchLaterButton.setImage(UIImage(named: "StarEmpty"), forState: .Normal)
// Update button if movie has been saved
if movieHasAlreadyBeenSaved(movie) {
buttonLabel.text = "Remove from List"
watchLaterButton.setImage(UIImage(named: "StarFilled"), forState: .Normal)
}
if images.isEmpty {
// Retrieve movie info from TMDb
let id = movie.id as Int
let url = "http://api.themoviedb.org/3/movie/\(id)/images?api_key=\(TMDBClient.Constants.ApiKey)"
TMDBClient.sharedInstance.createTaskWithURL(url) { results, error in
if let error = error {
self.alertWithMessage(error.domain, viewController: self)
return
}
dispatch_async(dispatch_get_main_queue()) {
if let backdrops = results!["backdrops"] as? [[String: AnyObject]] {
for image in backdrops {
if let aspectRatio = image["aspect_ratio"] as? Double {
// Find 16:9 images
if aspectRatio > 1.77 && aspectRatio < 1.78 {
let imageName = image["file_path"] as! String
// Create an images array for current movie
let imageInstance = Image(imageName: imageName, insertIntoMangedObjectContext: self.tempContext)
self.images.append(imageInstance)
}
}
}
}
// Display new text if no images were found
if self.images.count == 0 {
self.imagesLabel.text = "Sorry, no images available."
}
self.movieMediaCollectionView.reloadData()
}
}
// Create poster image
if let posterPath = movie.posterPath {
// Start activity indicator
activityIndicator.startAnimating()
// Create imageURL
let imageURL = "http://image.tmdb.org/t/p/w154\(posterPath)"
// Request poster image from TheMovieDB
TMDBClient.sharedInstance.requestImagesWithURL(imageURL) { results, error in
if let error = error {
self.alertWithMessage(error.domain, viewController: self)
return
}
dispatch_async(dispatch_get_main_queue()) {
// Stop activity indicator
self.activityIndicator.stopAnimating()
// Draw poster image
self.posterImageView.image = UIImage(data: results!)
}
}
} else {
posterImageView.image = UIImage(named: "NoImageBW")
}
self.movieMediaCollectionView.reloadData()
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
dispatch_async(dispatch_get_main_queue()) {
// Resize table after view appears
self.sizeTableToContent()
}
}
// MARK: - IBActions
@IBAction func watchLaterButtonPressed(sender: AnyObject) {
// Cancel action if no internet
if !Reachability.isConnectedToNetwork() {
alertWithMessage("Internet required to update list", viewController: self)
return
}
// Disable button until action is finished
watchLaterButton.enabled = false
let movies = fetchAllMovies()
let currentMovieID = getCurrentMovie()["id"] as! Int
// Delete movie if has already been saved
for savedMovie in movies {
if savedMovie.id == currentMovieID {
// Update CineLater List tab bar item badgeValue
tabBarController?.tabBar.items![2].badgeValue = "\(movies.count - 1)"
// Delete saved movie
deleteMovie(savedMovie)
return
}
}
// Update CineLater List tab bar item badgeValue
tabBarController?.tabBar.items![2].badgeValue = "\(movies.count + 1)"
let dictionary = getCurrentMovie()
// Create a new Movie and save the sharedContext
let movieToBeAdded = Movie(dictionary: dictionary, insertIntoMangedObjectContext: self.sharedContext)
// Add images to Movie using the inverse relationship
for image in self.images {
let imageName = "/\(image.imageName)"
let imageToBeAdded = Image(imageName: imageName, insertIntoMangedObjectContext: self.sharedContext)
imageToBeAdded.movie = movieToBeAdded
}
// Save Movie
CoreDataStackManager.sharedInstance().saveContext()
// Save images to documents directory
if movieToBeAdded.images?.count != 0 {
saveImages(movieToBeAdded)
} else {
updateButton()
}
}
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
dispatch_async(dispatch_get_main_queue()) {
// Set the height of cell
self.cellSize.setCellHeight(self.movieMediaFlowLayout, view: self.view)
// Resize table after screen orientation change
self.sizeTableToContent()
}
}
// MARK: - Core Data Convenience
lazy var sharedContext: NSManagedObjectContext = {
return CoreDataStackManager.sharedInstance().managedObjectContext
}()
// Temporary context
lazy var tempContext: NSManagedObjectContext = {
var context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
context.persistentStoreCoordinator = CoreDataStackManager.sharedInstance().persistentStoreCoordinator
return context
}()
// MARK: - Table view delegates
// Make table row heights dynamic
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// Required for UITableViewAutomaticDimension
self.detailsTable.estimatedRowHeight = 100.0
return UITableViewAutomaticDimension
}
// MARK: - Collection view delegates
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if !Reachability.isConnectedToNetwork() {
if movieHasAlreadyBeenSaved(movie) {
// Return count of persisted images
return images.count
} else {
return 0
}
}
return images.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MovieMediaCell", forIndexPath: indexPath) as! MovieMediaCell
// Show activity indicator while images downloading
cell.movieImageActivityIndicator.startAnimating()
// Check if image data already exists
if movieHasAlreadyBeenSaved(movie) {
// Set cell image using saved data
let imageData = getSavedImageDataForCellAtIndexPath(indexPath)
cell.movieImageView.image = UIImage(data: imageData)
cell.movieImageActivityIndicator.stopAnimating()
return cell
}
/*
* Image data has not been saved yet
*/
let imageURL = images[indexPath.item].imageURL
// Request image data from TMDb
TMDBClient.sharedInstance.requestImagesWithURL(imageURL, completion: { results, error in
if let error = error {
self.alertWithMessage(error.domain, viewController: self)
return
}
dispatch_async(dispatch_get_main_queue()) {
// Set cell image using resulting image data
let image = UIImage(data: results!)
cell.movieImageView.image = image
// Stop activity indicator
cell.movieImageActivityIndicator.stopAnimating()
}
})
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("showBigImage", sender: self)
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showBigImage" {
let controller = segue.destinationViewController as! BigImageViewController
let paths = movieMediaCollectionView.indexPathsForSelectedItems()
let selectedCell = paths![0].item
controller.bigImagePath = "\(images[selectedCell].imageURL)"
}
}
}
// MARK: - Class Extension
extension DetailsTableViewController {
func saveMovie(movie: Movie) {
// Create dictionary
let dictionary = [
Movie.Keys.BackdropPath: movie.backdropPath ?? "",
Movie.Keys.ID: movie.id,
Movie.Keys.MovieTitle: movie.movieTitle,
Movie.Keys.Overview: movie.overview ?? "",
Movie.Keys.PosterPath: movie.posterPath ?? "",
Movie.Keys.VoteAverage: movie.voteAverage,
Movie.Keys.VoteCount: movie.voteCount
]
// Save dictonary to shared defaults object
NSUserDefaults.standardUserDefaults().setObject(dictionary, forKey: "movie")
}
func getCurrentMovie() -> [String: AnyObject] {
let savedMovie = NSUserDefaults.standardUserDefaults().objectForKey("movie") as! [String: AnyObject]
return savedMovie
}
func fetchAllMovies() -> [Movie] {
// Create the Fetch Request
let fetchRequest = NSFetchRequest(entityName: "Movie")
// Execute the Fetch Request
do {
return try sharedContext.executeFetchRequest(fetchRequest) as! [Movie]
} catch {
return [Movie]()
}
}
func movieHasAlreadyBeenSaved(currentMovie: Movie) -> Bool {
let movies = fetchAllMovies()
for movie in movies {
// Check if movie has already been saved
if movie.id == currentMovie.id {
// Set movie to saved version
self.movie = movie
return true
}
}
return false
}
func deleteMovie(movie: Movie) {
// Delete image data
for image in movie.images ?? [Image]() {
deleteImageData(image.imageName)
}
// Delete saved movie
sharedContext.deleteObject(movie)
CoreDataStackManager.sharedInstance().saveContext()
// Reenable button
watchLaterButton.enabled = true
buttonLabel.text = "Add to CineLater List"
watchLaterButton.setImage(UIImage(named: "StarEmpty"), forState: .Normal)
}
func saveImages(movie: Movie) {
for image in movie.images! {
let imageName = image.imageName
TMDBClient.sharedInstance.requestImagesWithURL(image.imageURL, completion: { results, error in
if let error = error {
self.alertWithMessage(error.domain, viewController: self)
return
}
// Store image data in Documents Directory
self.saveImageData(imageName, data: results!)
// Update watchLaterButton
self.updateButton()
})
}
}
func getSavedImageDataForCellAtIndexPath(indexPath: NSIndexPath) -> NSData {
let image = movie.images![indexPath.item]
// Create filePath using imageName
let fileDirectory = CoreDataStackManager.sharedInstance().applicationDocumentsDirectory
let filePath = fileDirectory.URLByAppendingPathComponent(image.imageName).path!
let fileManager = NSFileManager.defaultManager()
// Retrieve image data if image has already been downloaded
if let imageData = fileManager.contentsAtPath(filePath) {
return imageData
}
return NSData()
}
func saveImageData(imageName: String, data: NSData) {
// Create filePath using imageName
let fileDirectory = CoreDataStackManager.sharedInstance().applicationDocumentsDirectory
let filePath = fileDirectory.URLByAppendingPathComponent(imageName).path!
// Save image data
data.writeToFile(filePath, atomically: true)
// Comply with app store storage policy
excludeFromBackup(filePath)
}
func deleteImageData(imageName: String) {
// Create filePath using imageName
let fileDirectory = CoreDataStackManager.sharedInstance().applicationDocumentsDirectory
let filePath = fileDirectory.URLByAppendingPathComponent(
imageName).path!
// Check that file exists before trying to delete
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(filePath) {
do {
// Delete all photos from CoreData
try fileManager.removeItemAtPath(filePath)
} catch {
return
}
}
}
func sizeTableToContent() {
let collectionView = self.movieMediaCollectionView
let tableView = self.detailsTable
// Resize detailsTable to include collection view content
let collectionViewHeight = collectionView.collectionViewLayout.collectionViewContentSize().height
let tableSectionHeight = tableView.rectForSection(0).height
collectionView.frame.size.height = collectionViewHeight
tableView.contentSize.height = tableSectionHeight + collectionViewHeight
}
func updateButton() {
dispatch_async(dispatch_get_main_queue()) {
// Reenable watchLaterButton
self.watchLaterButton.enabled = true
self.buttonLabel.text = "Remove from List"
self.watchLaterButton.setImage(UIImage(named: "StarFilled"), forState: .Normal)
}
}
func excludeFromBackup(path:String) {
let fileToExclude = NSURL.fileURLWithPath(path)
do {
try fileToExclude.setResourceValue(NSNumber(bool: true), forKey: NSURLIsExcludedFromBackupKey)
} catch {
print(error)
}
}
}
| mit | c02b30148c2fa9f4ecf00fc1712a6596 | 33.450317 | 134 | 0.611967 | 5.636458 | false | false | false | false |
RobertBiehl/caffe2-ios | examples/Caffe2Test/Caffe2Test/ViewController.swift | 1 | 30072 | //
// ViewController.swift
// Caffe2Test
//
// Created by Robert Biehl on 21.04.17.
// Copyright ยฉ 2017 Robert Biehl. All rights reserved.
//
import UIKit
import Caffe2Kit
class ViewController: UIViewController {
@IBOutlet var textView : UITextView!
@IBOutlet var imageView : UIImageView!
var caffe : Caffe2?
override func viewDidLoad() {
super.viewDidLoad()
caffe = Caffe2("squeeze_init_net", predict:"squeeze_predict_net")
let ๐
= #imageLiteral(resourceName: "lion.png")
if let res = caffe?.predict(๐
) {
// find top 5 classes
let sorted = res
.map{$0.floatValue}
.enumerated()
.sorted(by: {$0.element > $1.element})[0...5]
// generate output
let text = sorted
.map{"\($0.offset): \(classes[$0.offset]) \($0.element*100)%"}
.joined(separator: "\n")
print("Result\n\(text)")
textView.text = text
imageView.image = ๐
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
let classes = [
"tench, Tinca tinca",
"goldfish, Carassius auratus",
"great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias",
"tiger shark, Galeocerdo cuvieri",
"hammerhead, hammerhead shark",
"electric ray, crampfish, numbfish, torpedo",
"stingray",
"cock",
"hen",
"ostrich, Struthio camelus",
"brambling, Fringilla montifringilla",
"goldfinch, Carduelis carduelis",
"house finch, linnet, Carpodacus mexicanus",
"junco, snowbird",
"indigo bunting, indigo finch, indigo bird, Passerina cyanea",
"robin, American robin, Turdus migratorius",
"bulbul",
"jay",
"magpie",
"chickadee",
"water ouzel, dipper",
"kite",
"bald eagle, American eagle, Haliaeetus leucocephalus",
"vulture",
"great grey owl, great gray owl, Strix nebulosa",
"European fire salamander, Salamandra salamandra",
"common newt, Triturus vulgaris",
"eft",
"spotted salamander, Ambystoma maculatum",
"axolotl, mud puppy, Ambystoma mexicanum",
"bullfrog, Rana catesbeiana",
"tree frog, tree-frog",
"tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui",
"loggerhead, loggerhead turtle, Caretta caretta",
"leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea",
"mud turtle",
"terrapin",
"box turtle, box tortoise",
"banded gecko",
"common iguana, iguana, Iguana iguana",
"American chameleon, anole, Anolis carolinensis",
"whiptail, whiptail lizard",
"agama",
"frilled lizard, Chlamydosaurus kingi",
"alligator lizard",
"Gila monster, Heloderma suspectum",
"green lizard, Lacerta viridis",
"African chameleon, Chamaeleo chamaeleon",
"Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis",
"African crocodile, Nile crocodile, Crocodylus niloticus",
"American alligator, Alligator mississipiensis",
"triceratops",
"thunder snake, worm snake, Carphophis amoenus",
"ringneck snake, ring-necked snake, ring snake",
"hognose snake, puff adder, sand viper",
"green snake, grass snake",
"king snake, kingsnake",
"garter snake, grass snake",
"water snake",
"vine snake",
"night snake, Hypsiglena torquata",
"boa constrictor, Constrictor constrictor",
"rock python, rock snake, Python sebae",
"Indian cobra, Naja naja",
"green mamba",
"sea snake",
"horned viper, cerastes, sand viper, horned asp, Cerastes cornutus",
"diamondback, diamondback rattlesnake, Crotalus adamanteus",
"sidewinder, horned rattlesnake, Crotalus cerastes",
"trilobite",
"harvestman, daddy longlegs, Phalangium opilio",
"scorpion",
"black and gold garden spider, Argiope aurantia",
"barn spider, Araneus cavaticus",
"garden spider, Aranea diademata",
"black widow, Latrodectus mactans",
"tarantula",
"wolf spider, hunting spider",
"tick",
"centipede",
"black grouse",
"ptarmigan",
"ruffed grouse, partridge, Bonasa umbellus",
"prairie chicken, prairie grouse, prairie fowl",
"peacock",
"quail",
"partridge",
"African grey, African gray, Psittacus erithacus",
"macaw",
"sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita",
"lorikeet",
"coucal",
"bee eater",
"hornbill",
"hummingbird",
"jacamar",
"toucan",
"drake",
"red-breasted merganser, Mergus serrator",
"goose",
"black swan, Cygnus atratus",
"tusker",
"echidna, spiny anteater, anteater",
"platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus",
"wallaby, brush kangaroo",
"koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus",
"wombat",
"jellyfish",
"sea anemone, anemone",
"brain coral",
"flatworm, platyhelminth",
"nematode, nematode worm, roundworm",
"conch",
"snail",
"slug",
"sea slug, nudibranch",
"chiton, coat-of-mail shell, sea cradle, polyplacophore",
"chambered nautilus, pearly nautilus, nautilus",
"Dungeness crab, Cancer magister",
"rock crab, Cancer irroratus",
"fiddler crab",
"king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica",
"American lobster, Northern lobster, Maine lobster, Homarus americanus",
"spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish",
"crayfish, crawfish, crawdad, crawdaddy",
"hermit crab",
"isopod",
"white stork, Ciconia ciconia",
"black stork, Ciconia nigra",
"spoonbill",
"flamingo",
"little blue heron, Egretta caerulea",
"American egret, great white heron, Egretta albus",
"bittern",
"crane",
"limpkin, Aramus pictus",
"European gallinule, Porphyrio porphyrio",
"American coot, marsh hen, mud hen, water hen, Fulica americana",
"bustard",
"ruddy turnstone, Arenaria interpres",
"red-backed sandpiper, dunlin, Erolia alpina",
"redshank, Tringa totanus",
"dowitcher",
"oystercatcher, oyster catcher",
"pelican",
"king penguin, Aptenodytes patagonica",
"albatross, mollymawk",
"grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus",
"killer whale, killer, orca, grampus, sea wolf, Orcinus orca",
"dugong, Dugong dugon",
"sea lion",
"Chihuahua",
"Japanese spaniel",
"Maltese dog, Maltese terrier, Maltese",
"Pekinese, Pekingese, Peke",
"Shih-Tzu",
"Blenheim spaniel",
"papillon",
"toy terrier",
"Rhodesian ridgeback",
"Afghan hound, Afghan",
"basset, basset hound",
"beagle",
"bloodhound, sleuthhound",
"bluetick",
"black-and-tan coonhound",
"Walker hound, Walker foxhound",
"English foxhound",
"redbone",
"borzoi, Russian wolfhound",
"Irish wolfhound",
"Italian greyhound",
"whippet",
"Ibizan hound, Ibizan Podenco",
"Norwegian elkhound, elkhound",
"otterhound, otter hound",
"Saluki, gazelle hound",
"Scottish deerhound, deerhound",
"Weimaraner",
"Staffordshire bullterrier, Staffordshire bull terrier",
"American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier",
"Bedlington terrier",
"Border terrier",
"Kerry blue terrier",
"Irish terrier",
"Norfolk terrier",
"Norwich terrier",
"Yorkshire terrier",
"wire-haired fox terrier",
"Lakeland terrier",
"Sealyham terrier, Sealyham",
"Airedale, Airedale terrier",
"cairn, cairn terrier",
"Australian terrier",
"Dandie Dinmont, Dandie Dinmont terrier",
"Boston bull, Boston terrier",
"miniature schnauzer",
"giant schnauzer",
"standard schnauzer",
"Scotch terrier, Scottish terrier, Scottie",
"Tibetan terrier, chrysanthemum dog",
"silky terrier, Sydney silky",
"soft-coated wheaten terrier",
"West Highland white terrier",
"Lhasa, Lhasa apso",
"flat-coated retriever",
"curly-coated retriever",
"golden retriever",
"Labrador retriever",
"Chesapeake Bay retriever",
"German short-haired pointer",
"vizsla, Hungarian pointer",
"English setter",
"Irish setter, red setter",
"Gordon setter",
"Brittany spaniel",
"clumber, clumber spaniel",
"English springer, English springer spaniel",
"Welsh springer spaniel",
"cocker spaniel, English cocker spaniel, cocker",
"Sussex spaniel",
"Irish water spaniel",
"kuvasz",
"schipperke",
"groenendael",
"malinois",
"briard",
"kelpie",
"komondor",
"Old English sheepdog, bobtail",
"Shetland sheepdog, Shetland sheep dog, Shetland",
"๐ collie",
"Border collie",
"Bouvier des Flandres, Bouviers des Flandres",
"Rottweiler",
"German shepherd, German shepherd dog, German police dog, alsatian",
"Doberman, Doberman pinscher",
"miniature pinscher",
"Greater Swiss Mountain dog",
"Bernese mountain dog",
"Appenzeller",
"EntleBucher",
"boxer",
"bull mastiff",
"Tibetan mastiff",
"French bulldog",
"Great Dane",
"Saint Bernard, St Bernard",
"Eskimo dog, husky",
"malamute, malemute, Alaskan malamute",
"Siberian husky",
"dalmatian, coach dog, carriage dog",
"affenpinscher, monkey pinscher, monkey dog",
"basenji",
"pug, pug-dog",
"Leonberg",
"Newfoundland, Newfoundland dog",
"Great Pyrenees",
"Samoyed, Samoyede",
"๐ถ Pomeranian",
"chow, chow chow",
"keeshond",
"Brabancon griffon",
"Pembroke, Pembroke Welsh corgi",
"Cardigan, Cardigan Welsh corgi",
"toy poodle",
"miniature poodle",
"standard poodle",
"Mexican hairless",
"timber wolf, grey wolf, gray wolf, Canis lupus",
"white wolf, Arctic wolf, Canis lupus tundrarum",
"red wolf, maned wolf, Canis rufus, Canis niger",
"coyote, prairie wolf, brush wolf, Canis latrans",
"dingo, warrigal, warragal, Canis dingo",
"dhole, Cuon alpinus",
"African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus",
"hyena, hyaena",
"red fox, Vulpes vulpes",
"kit fox, Vulpes macrotis",
"Arctic fox, white fox, Alopex lagopus",
"grey fox, gray fox, Urocyon cinereoargenteus",
"tabby, tabby cat",
"tiger cat",
"๐ Persian cat",
"Siamese cat, Siamese",
"Egyptian cat",
"cougar, puma, catamount, mountain lion, painter, panther, Felis concolor",
"lynx, catamount",
"leopard, Panthera pardus",
"snow leopard, ounce, Panthera uncia",
"jaguar, panther, Panthera onca, Felis onca",
"๐ฆ lion, king of beasts, Panthera leo",
"tiger, Panthera tigris",
"cheetah, chetah, Acinonyx jubatus",
"brown bear, bruin, Ursus arctos",
"American black bear, black bear, Ursus americanus, Euarctos americanus",
"ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus",
"sloth bear, Melursus ursinus, Ursus ursinus",
"mongoose",
"meerkat, mierkat",
"tiger beetle",
"ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle",
"ground beetle, carabid beetle",
"long-horned beetle, longicorn, longicorn beetle",
"leaf beetle, chrysomelid",
"dung beetle",
"rhinoceros beetle",
"weevil",
"fly",
"bee",
"ant, emmet, pismire",
"grasshopper, hopper",
"cricket",
"walking stick, walkingstick, stick insect",
"cockroach, roach",
"mantis, mantid",
"cicada, cicala",
"leafhopper",
"lacewing, lacewing fly",
"dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk",
"damselfly",
"admiral",
"ringlet, ringlet butterfly",
"monarch, monarch butterfly, milkweed butterfly, Danaus plexippus",
"cabbage butterfly",
"sulphur butterfly, sulfur butterfly",
"lycaenid, lycaenid butterfly",
"starfish, sea star",
"sea urchin",
"sea cucumber, holothurian",
"wood rabbit, cottontail, cottontail rabbit",
"hare",
"Angora, Angora rabbit",
"hamster",
"porcupine, hedgehog",
"fox squirrel, eastern fox squirrel, Sciurus niger",
"marmot",
"beaver",
"guinea pig, Cavia cobaya",
"sorrel",
"zebra",
"hog, pig, grunter, squealer, Sus scrofa",
"wild boar, boar, Sus scrofa",
"warthog",
"hippopotamus, hippo, river horse, Hippopotamus amphibius",
"ox",
"water buffalo, water ox, Asiatic buffalo, Bubalus bubalis",
"bison",
"ram, tup",
"bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis",
"ibex, Capra ibex",
"hartebeest",
"impala, Aepyceros melampus",
"gazelle",
"Arabian camel, dromedary, Camelus dromedarius",
"llama",
"weasel",
"mink",
"polecat, fitch, foulmart, foumart, Mustela putorius",
"black-footed ferret, ferret, Mustela nigripes",
"otter",
"skunk, polecat, wood pussy",
"badger",
"armadillo",
"three-toed sloth, ai, Bradypus tridactylus",
"orangutan, orang, orangutang, Pongo pygmaeus",
"๐ฆ gorilla, Gorilla gorilla",
"๐ต chimpanzee, chimp, Pan troglodytes",
"gibbon, Hylobates lar",
"siamang, Hylobates syndactylus, Symphalangus syndactylus",
"guenon, guenon monkey",
"๐ patas, hussar monkey, Erythrocebus patas",
"baboon",
"๐ macaque",
"๐ langur",
"colobus, colobus monkey",
"proboscis monkey, Nasalis larvatus",
"marmoset",
"๐ capuchin, ringtail, Cebus capucinus",
"howler monkey, howler",
"titi, titi monkey",
"spider monkey, Ateles geoffroyi",
"squirrel monkey, Saimiri sciureus",
"Madagascar cat, ring-tailed lemur, Lemur catta",
"indri, indris, Indri indri, Indri brevicaudatus",
"Indian elephant, Elephas maximus",
"African elephant, Loxodonta africana",
"lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens",
"giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca",
"barracouta, snoek",
"eel",
"coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch",
"rock beauty, Holocanthus tricolor",
"anemone fish",
"sturgeon",
"gar, garfish, garpike, billfish, Lepisosteus osseus",
"lionfish",
"puffer, pufferfish, blowfish, globefish",
"abacus",
"abaya",
"academic gown, academic robe, judge's robe",
"accordion, piano accordion, squeeze box",
"acoustic guitar",
"aircraft carrier, carrier, flattop, attack aircraft carrier",
"airliner",
"airship, dirigible",
"altar",
"ambulance",
"amphibian, amphibious vehicle",
"analog clock",
"apiary, bee house",
"apron",
"ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin",
"assault rifle, assault gun",
"backpack, back pack, knapsack, packsack, rucksack, haversack",
"bakery, bakeshop, bakehouse",
"balance beam, beam",
"balloon",
"ballpoint, ballpoint pen, ballpen, Biro",
"Band Aid",
"banjo",
"bannister, banister, balustrade, balusters, handrail",
"barbell",
"barber chair",
"barbershop",
"barn",
"barometer",
"barrel, cask",
"barrow, garden cart, lawn cart, wheelbarrow",
"baseball",
"basketball",
"bassinet",
"bassoon",
"bathing cap, swimming cap",
"bath towel",
"bathtub, bathing tub, bath, tub",
"beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon",
"beacon, lighthouse, beacon light, pharos",
"beaker",
"bearskin, busby, shako",
"beer bottle",
"beer glass",
"bell cote, bell cot",
"bib",
"bicycle-built-for-two, tandem bicycle, tandem",
"bikini, two-piece",
"binder, ring-binder",
"binoculars, field glasses, opera glasses",
"birdhouse",
"boathouse",
"bobsled, bobsleigh, bob",
"bolo tie, bolo, bola tie, bola",
"bonnet, poke bonnet",
"bookcase",
"bookshop, bookstore, bookstall",
"bottlecap",
"bow",
"bow tie, bow-tie, bowtie",
"brass, memorial tablet, plaque",
"brassiere, bra, bandeau",
"breakwater, groin, groyne, mole, bulwark, seawall, jetty",
"breastplate, aegis, egis",
"broom",
"bucket, pail",
"buckle",
"bulletproof vest",
"bullet train, bullet",
"butcher shop, meat market",
"cab, hack, taxi, taxicab",
"caldron, cauldron",
"candle, taper, wax light",
"cannon",
"canoe",
"can opener, tin opener",
"cardigan",
"car mirror",
"carousel, carrousel, merry-go-round, roundabout, whirligig",
"carpenter's kit, tool kit",
"carton",
"car wheel",
"cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM",
"cassette",
"cassette player",
"castle",
"catamaran",
"CD player",
"cello, violoncello",
"cellular telephone, cellular phone, cellphone, cell, mobile phone",
"chain",
"chainlink fence",
"chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour",
"chain saw, chainsaw",
"chest",
"chiffonier, commode",
"chime, bell, gong",
"china cabinet, china closet",
"Christmas stocking",
"church, church building",
"cinema, movie theater, movie theatre, movie house, picture palace",
"cleaver, meat cleaver, chopper",
"cliff dwelling",
"cloak",
"clog, geta, patten, sabot",
"cocktail shaker",
"coffee mug",
"coffeepot",
"coil, spiral, volute, whorl, helix",
"combination lock",
"computer keyboard, keypad",
"confectionery, confectionary, candy store",
"container ship, containership, container vessel",
"convertible",
"corkscrew, bottle screw",
"cornet, horn, trumpet, trump",
"cowboy boot",
"cowboy hat, ten-gallon hat",
"cradle",
"crane",
"crash helmet",
"crate",
"crib, cot",
"Crock Pot",
"croquet ball",
"crutch",
"cuirass",
"dam, dike, dyke",
"desk",
"desktop computer",
"dial telephone, dial phone",
"diaper, nappy, napkin",
"digital clock",
"digital watch",
"dining table, board",
"dishrag, dishcloth",
"dishwasher, dish washer, dishwashing machine",
"disk brake, disc brake",
"dock, dockage, docking facility",
"dogsled, dog sled, dog sleigh",
"dome",
"doormat, welcome mat",
"drilling platform, offshore rig",
"drum, membranophone, tympan",
"drumstick",
"dumbbell",
"Dutch oven",
"electric fan, blower",
"electric guitar",
"electric locomotive",
"entertainment center",
"envelope",
"espresso maker",
"face powder",
"feather boa, boa",
"file, file cabinet, filing cabinet",
"fireboat",
"fire engine, fire truck",
"fire screen, fireguard",
"flagpole, flagstaff",
"flute, transverse flute",
"folding chair",
"football helmet",
"forklift",
"fountain",
"fountain pen",
"four-poster",
"freight car",
"French horn, horn",
"frying pan, frypan, skillet",
"fur coat",
"garbage truck, dustcart",
"gasmask, respirator, gas helmet",
"gas pump, gasoline pump, petrol pump, island dispenser",
"goblet",
"go-kart",
"golf ball",
"golfcart, golf cart",
"gondola",
"gong, tam-tam",
"gown",
"grand piano, grand",
"greenhouse, nursery, glasshouse",
"grille, radiator grille",
"grocery store, grocery, food market, market",
"guillotine",
"hair slide",
"hair spray",
"half track",
"hammer",
"hamper",
"hand blower, blow dryer, blow drier, hair dryer, hair drier",
"hand-held computer, hand-held microcomputer",
"handkerchief, hankie, hanky, hankey",
"hard disc, hard disk, fixed disk",
"harmonica, mouth organ, harp, mouth harp",
"harp",
"harvester, reaper",
"hatchet",
"holster",
"home theater, home theatre",
"honeycomb",
"hook, claw",
"hoopskirt, crinoline",
"horizontal bar, high bar",
"horse cart, horse-cart",
"hourglass",
"iPod",
"iron, smoothing iron",
"jack-o'-lantern",
"jean, blue jean, denim",
"jeep, landrover",
"jersey, T-shirt, tee shirt",
"jigsaw puzzle",
"jinrikisha, ricksha, rickshaw",
"joystick",
"kimono",
"knee pad",
"knot",
"lab coat, laboratory coat",
"ladle",
"lampshade, lamp shade",
"laptop, laptop computer",
"lawn mower, mower",
"lens cap, lens cover",
"letter opener, paper knife, paperknife",
"library",
"lifeboat",
"lighter, light, igniter, ignitor",
"limousine, limo",
"liner, ocean liner",
"lipstick, lip rouge",
"Loafer",
"lotion",
"loudspeaker, speaker, speaker unit, loudspeaker system, speaker system",
"loupe, jeweler's loupe",
"lumbermill, sawmill",
"magnetic compass",
"mailbag, postbag",
"mailbox, letter box",
"maillot",
"maillot, tank suit",
"manhole cover",
"maraca",
"marimba, xylophone",
"mask",
"matchstick",
"maypole",
"maze, labyrinth",
"measuring cup",
"medicine chest, medicine cabinet",
"megalith, megalithic structure",
"microphone, mike",
"microwave, microwave oven",
"military uniform",
"milk can",
"minibus",
"miniskirt, mini",
"minivan",
"missile",
"mitten",
"mixing bowl",
"mobile home, manufactured home",
"Model T",
"modem",
"monastery",
"monitor",
"moped",
"mortar",
"mortarboard",
"mosque",
"mosquito net",
"motor scooter, scooter",
"mountain bike, all-terrain bike, off-roader",
"mountain tent",
"mouse, computer mouse",
"mousetrap",
"moving van",
"muzzle",
"nail",
"neck brace",
"necklace",
"nipple",
"notebook, notebook computer",
"obelisk",
"oboe, hautboy, hautbois",
"ocarina, sweet potato",
"odometer, hodometer, mileometer, milometer",
"oil filter",
"organ, pipe organ",
"oscilloscope, scope, cathode-ray oscilloscope, CRO",
"overskirt",
"oxcart",
"oxygen mask",
"packet",
"paddle, boat paddle",
"paddlewheel, paddle wheel",
"padlock",
"paintbrush",
"pajama, pyjama, pj's, jammies",
"palace",
"panpipe, pandean pipe, syrinx",
"paper towel",
"parachute, chute",
"parallel bars, bars",
"park bench",
"parking meter",
"passenger car, coach, carriage",
"patio, terrace",
"pay-phone, pay-station",
"pedestal, plinth, footstall",
"pencil box, pencil case",
"pencil sharpener",
"perfume, essence",
"Petri dish",
"photocopier",
"pick, plectrum, plectron",
"pickelhaube",
"picket fence, paling",
"pickup, pickup truck",
"pier",
"piggy bank, penny bank",
"pill bottle",
"pillow",
"ping-pong ball",
"pinwheel",
"pirate, pirate ship",
"pitcher, ewer",
"plane, carpenter's plane, woodworking plane",
"planetarium",
"plastic bag",
"plate rack",
"plow, plough",
"plunger, plumber's helper",
"Polaroid camera, Polaroid Land camera",
"pole",
"police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria",
"poncho",
"pool table, billiard table, snooker table",
"pop bottle, soda bottle",
"pot, flowerpot",
"potter's wheel",
"power drill",
"prayer rug, prayer mat",
"printer",
"prison, prison house",
"projectile, missile",
"projector",
"puck, hockey puck",
"punching bag, punch bag, punching ball, punchball",
"purse",
"quill, quill pen",
"quilt, comforter, comfort, puff",
"racer, race car, racing car",
"racket, racquet",
"radiator",
"radio, wireless",
"radio telescope, radio reflector",
"rain barrel",
"recreational vehicle, RV, R.V.",
"reel",
"reflex camera",
"refrigerator, icebox",
"remote control, remote",
"restaurant, eating house, eating place, eatery",
"revolver, six-gun, six-shooter",
"rifle",
"rocking chair, rocker",
"rotisserie",
"rubber eraser, rubber, pencil eraser",
"rugby ball",
"rule, ruler",
"running shoe",
"safe",
"safety pin",
"saltshaker, salt shaker",
"sandal",
"sarong",
"sax, saxophone",
"scabbard",
"scale, weighing machine",
"school bus",
"schooner",
"scoreboard",
"screen, CRT screen",
"screw",
"screwdriver",
"seat belt, seatbelt",
"sewing machine",
"shield, buckler",
"shoe shop, shoe-shop, shoe store",
"shoji",
"shopping basket",
"shopping cart",
"shovel",
"shower cap",
"shower curtain",
"ski",
"ski mask",
"sleeping bag",
"slide rule, slipstick",
"sliding door",
"slot, one-armed bandit",
"snorkel",
"snowmobile",
"snowplow, snowplough",
"soap dispenser",
"soccer ball",
"sock",
"solar dish, solar collector, solar furnace",
"sombrero",
"soup bowl",
"space bar",
"space heater",
"space shuttle",
"spatula",
"speedboat",
"spider web, spider's web",
"spindle",
"sports car, sport car",
"spotlight, spot",
"stage",
"steam locomotive",
"steel arch bridge",
"steel drum",
"stethoscope",
"stole",
"stone wall",
"stopwatch, stop watch",
"stove",
"strainer",
"streetcar, tram, tramcar, trolley, trolley car",
"stretcher",
"studio couch, day bed",
"stupa, tope",
"submarine, pigboat, sub, U-boat",
"suit, suit of clothes",
"sundial",
"sunglass",
"sunglasses, dark glasses, shades",
"sunscreen, sunblock, sun blocker",
"suspension bridge",
"swab, swob, mop",
"sweatshirt",
"swimming trunks, bathing trunks",
"swing",
"switch, electric switch, electrical switch",
"syringe",
"table lamp",
"tank, army tank, armored combat vehicle, armoured combat vehicle",
"tape player",
"teapot",
"teddy, teddy bear",
"television, television system",
"tennis ball",
"thatch, thatched roof",
"theater curtain, theatre curtain",
"thimble",
"thresher, thrasher, threshing machine",
"throne",
"tile roof",
"toaster",
"tobacco shop, tobacconist shop, tobacconist",
"toilet seat",
"torch",
"totem pole",
"tow truck, tow car, wrecker",
"toyshop",
"tractor",
"trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi",
"tray",
"trench coat",
"tricycle, trike, velocipede",
"trimaran",
"tripod",
"triumphal arch",
"trolleybus, trolley coach, trackless trolley",
"trombone",
"tub, vat",
"turnstile",
"typewriter keyboard",
"umbrella",
"unicycle, monocycle",
"upright, upright piano",
"vacuum, vacuum cleaner",
"vase",
"vault",
"velvet",
"vending machine",
"vestment",
"viaduct",
"violin, fiddle",
"volleyball",
"waffle iron",
"wall clock",
"wallet, billfold, notecase, pocketbook",
"wardrobe, closet, press",
"warplane, military plane",
"washbasin, handbasin, washbowl, lavabo, wash-hand basin",
"washer, automatic washer, washing machine",
"water bottle",
"water jug",
"water tower",
"whiskey jug",
"whistle",
"wig ๐",
"window screen",
"window shade",
"Windsor tie",
"wine bottle",
"wing",
"wok",
"wooden spoon",
"wool, woolen, woollen",
"worm fence, snake fence, snake-rail fence, Virginia fence",
"wreck",
"yawl",
"yurt",
"web site, website, internet site, site",
"comic book",
"crossword puzzle, crossword",
"street sign",
"traffic light, traffic signal, stoplight",
"book jacket, dust cover, dust jacket, dust wrapper",
"menu",
"plate",
"guacamole",
"consomme",
"hot pot, hotpot",
"trifle",
"ice cream, icecream",
"ice lolly, lolly, lollipop, popsicle",
"French loaf",
"bagel, beigel",
"pretzel",
"cheeseburger",
"hotdog, hot dog, red hot",
"mashed potato",
"head cabbage",
"broccoli",
"cauliflower",
"zucchini, courgette",
"spaghetti squash",
"acorn squash",
"butternut squash",
"cucumber, cuke",
"artichoke, globe artichoke",
"bell pepper",
"cardoon",
"mushroom",
"Granny Smith",
"strawberry",
"orange",
"lemon",
"fig",
"pineapple, ananas",
"banana",
"jackfruit, jak, jack",
"custard apple",
"pomegranate",
"hay",
"carbonara",
"chocolate sauce, chocolate syrup",
"dough",
"meat loaf, meatloaf",
"pizza, pizza pie",
"potpie",
"burrito",
"red wine",
"espresso",
"cup",
"eggnog",
"alp",
"bubble",
"cliff, drop, drop-off",
"coral reef",
"geyser",
"lakeside, lakeshore",
"promontory, headland, head, foreland",
"sandbar, sand bar",
"seashore, coast, seacoast, sea-coast",
"valley, vale",
"volcano",
"ballplayer, baseball player",
"groom, bridegroom",
"scuba diver",
"rapeseed",
"daisy",
"yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum",
"corn",
"acorn",
"hip, rose hip, rosehip",
"buckeye, horse chestnut, conker",
"coral fungus",
"agaric",
"gyromitra",
"stinkhorn, carrion fungus",
"earthstar",
"hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa",
"bolete",
"ear, spike, capitulum",
"toilet tissue, toilet paper, bathroom tissue"
]
}
| apache-2.0 | 8cdce16d8659f0dc145a5804fc32bdad | 27.302545 | 128 | 0.623764 | 3.016171 | false | false | false | false |
drmohundro/SWXMLHash | Source/String+Extensions.swift | 1 | 1528 | //
// String+Extensions.swift
// SWXMLHash
//
// Copyright (c) 2022 David Mohundro
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
internal extension String {
func compare(_ str2: String?, _ insensitive: Bool) -> Bool {
guard let str2 = str2 else {
return false
}
let str1 = self
if insensitive {
return str1.caseInsensitiveCompare(str2) == .orderedSame
}
return str1 == str2
}
}
| mit | 7bf583b2664964c8b3923db396a0ea59 | 38.179487 | 81 | 0.705497 | 4.365714 | false | false | false | false |
lexchou/swallow | stdlib/core/String.swift | 1 | 22714 | /// An arbitrary Unicode string value.
///
/// Unicode-Correct
/// ===============
///
/// Swift strings are designed to be Unicode-correct. In particular,
/// the APIs make it easy to write code that works correctly, and does
/// not surprise end-users, regardless of where you venture in the
/// Unicode character space. For example,
///
/// * The `==` operator checks for Unicode canonical equivalence,
/// so two different representations of the same string will always
/// compare equal.
///
/// * String elements are `Characters` (Unicode extended grapheme
/// clusters), a unit of text that is meaningful to most humans.
///
/// Locale-Insensitive
/// ==================
///
/// The fundamental operations on Swift strings are not sensitive to
/// locale settings. That's because, for example, the validity of a
/// `Dictionary<String, T>` in a running program depends on a given
/// string comparison having a single, stable result. Therefore,
/// Swift always uses the default, un-tailored Unicode algorithms
/// for basic string operations.
///
/// Importing `Foundation` endows swift strings with the full power of
/// the `NSString` API, which allows you to choose more complex
/// locale-sensitive operations explicitly.
///
/// Value Semantics
/// ===============
///
/// Each string variable, `let` binding, or stored property has an
/// independent value, so mutations to the string are not observable
/// through its copies::
///
/// var a = "foo"
/// var b = a
/// b[b.endIndex.predecessor()] = "x"
/// println("a=\(a), b=\(b)") // a=foo, b=fox
///
/// Strings use Copy-on-Write so that their data is only copied
/// lazily, upon mutation, when more than one string instance is using
/// the same buffer. Therefore, the first in any sequence of mutating
/// operations may cost `O(N)` time and space, where `N` is the length
/// of the string's (unspecified) underlying representation,.
///
/// Growth and Capacity
/// ===================
///
/// When a string's contiguous storage fills up, new storage must be
/// allocated and characters must be moved to the new storage.
/// `String` uses an exponential growth strategy that makes `append` a
/// constant time operation *when amortized over many invocations*.
///
/// Objective-C Bridge
/// ==================
///
/// `String` is bridged to Objective-C as `NSString`, and a `String`
/// that originated in Objective-C may store its characters in an
/// `NSString`. Since any arbitrary subclass of `NSSString` can
/// become a `String`, there are no guarantees about representation or
/// efficiency in this case. Since `NSString` is immutable, it is
/// just as though the storage was shared by some copy: the first in
/// any sequence of mutating operations causes elements to be copied
/// into unique, contiguous storage which may cost `O(N)` time and
/// space, where `N` is the length of the string representation (or
/// more, if the underlying `NSString` is has unusual performance
/// characteristics).
struct String {
init() {
//TODO
}
}
extension String : CollectionType {
/// A character position in a `String`
struct Index : BidirectionalIndexType, Comparable, Reflectable {
/// Returns the next consecutive value after `self`.
///
/// Requires: the next value is representable.
func successor() -> String.Index {
return String.Index()//TODO
}
/// Returns the previous consecutive value before `self`.
///
/// Requires: the previous value is representable.
func predecessor() -> String.Index {
return String.Index()//TODO
}
/// Returns a mirror that reflects `self`.
func getMirror() -> MirrorType {
//TODO
}
}
/// The position of the first `Character` if the `String` is
/// non-empty; identical to `endIndex` otherwise.
var startIndex: String.Index {
get {
return String.Index()//TODO
}
}
/// The `String`\ 's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
var endIndex: String.Index {
get {
return String.Index()//TODO
}
}
subscript (i: String.Index) -> Character {
get {
return Character()//TODO
}
}
/// Return a *generator* over the `Characters` in this `String`.
///
/// Complexity: O(1)
func generate() -> IndexingGenerator<String> {
return IndexingGenerator<String>()/TODO
}
}
extension String {
/// A collection of UTF-8 code units that encodes a `String` value.
struct UTF8View : CollectionType, Reflectable {
/// A position in a `String.UTF8View`
struct Index : ForwardIndexType {
/// Returns the next consecutive value after `self`.
///
/// Requires: the next value is representable.
func successor() -> String.UTF8View.Index {
return String.UTF8View.Index()//TODO
}
}
/// The position of the first code unit if the `String` is
/// non-empty; identical to `endIndex` otherwise.
var startIndex: String.UTF8View.Index {
get {
return String.UTF8View.Index()//TODO
}
}
/// The "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
var endIndex: String.UTF8View.Index {
get {
return String.UTF8View.Index()//TODO
}
}
subscript (position: String.UTF8View.Index) -> CodeUnit {
get {
return CodeUnit()//TODO
}
}
/// Return a *generator* over the code points that comprise this
/// *sequence*.
///
/// Complexity: O(1)
func generate() -> IndexingGenerator<String.UTF8View> {
//TODO
}
/// Returns a mirror that reflects `self`.
func getMirror() -> MirrorType {
//TODO
}
}
/// A UTF-8 encoding of `self`.
var utf8: String.UTF8View {
get {
//TODO
}
}
/// A contiguously-stored nul-terminated UTF-8 representation of
/// `self`.
///
/// To access the underlying memory, invoke
/// `withUnsafeBufferPointer` on the `ContiguousArray`.
var nulTerminatedUTF8: ContiguousArray<CodeUnit> {
get {
return ContiguousArray<CodeUnit>()//TODO
}
}
}
extension String {
/// A collection of Unicode scalar values that
/// encode a `String` .
struct UnicodeScalarView : Sliceable, SequenceType, Reflectable {
/// A position in a `String.UnicodeScalarView`
struct Index : BidirectionalIndexType, Comparable {
/// Returns the next consecutive value after `self`.
///
/// Requires: the next value is representable.
func successor() -> String.UnicodeScalarView.Index {
//TODO
}
/// Returns the previous consecutive value before `self`.
///
/// Requires: the previous value is representable.
func predecessor() -> String.UnicodeScalarView.Index {
//TODO
}
}
/// The position of the first `UnicodeScalar` if the `String` is
/// non-empty; identical to `endIndex` otherwise.
var startIndex: String.UnicodeScalarView.Index {
get {
//TODO
}
}
/// The "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
var endIndex: String.UnicodeScalarView.Index {
get {
//TODO
}
}
subscript (position: String.UnicodeScalarView.Index) -> UnicodeScalar {
get {
//TODO
}
}
subscript (r: Range<String.UnicodeScalarView.Index>) -> String.UnicodeScalarView {
get {
//TODO
}
}
/// A type whose instances can produce the elements of this
/// sequence, in order.
struct Generator : GeneratorType {
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// Requires: no preceding call to `self.next()` has returned
/// `nil`.
mutating func next() -> UnicodeScalar? {
return nil//TODO
}
}
/// Return a *generator* over the `UnicodeScalar`\ s that comprise
/// this *sequence*.
///
/// Complexity: O(1)
func generate() -> String.UnicodeScalarView.Generator {
return String.UnicodeScalarView.Generator()//TODO
}
/// Returns a mirror that reflects `self`.
func getMirror() -> MirrorType {
//TODO
}
}
}
extension String {
/// Creates a new `String` by copying the nul-terminated UTF-8 data
/// referenced by a `CString`.
///
/// Returns `nil` if the `CString` is `NULL` or if it contains ill-formed
/// UTF-8 code unit sequences.
static func fromCString(cs: UnsafePointer<CChar>) -> String? {
return nil//TODO
}
/// Creates a new `String` by copying the nul-terminated UTF-8 data
/// referenced by a `CString`.
///
/// Returns `nil` if the `CString` is `NULL`. If `CString` contains
/// ill-formed UTF-8 code unit sequences, replaces them with replacement
/// characters (U+FFFD).
static func fromCStringRepairingIllFormedUTF8(cs: UnsafePointer<CChar>) -> (String?, hadError: Bool) {
return (nil, false) //TODO
}
}
extension String {
/// Construct an instance containing just the given `Character`.
init(_ c: Character) {
//TODO
}
}
extension String {
/// Invoke `f` on the contents of this string, represented as
/// a nul-terminated array of char, ensuring that the array's
/// lifetime extends through the execution of `f`.
func withCString<Result>(f: (UnsafePointer<Int8>) -> Result) -> Result {
//TODO
}
}
extension String : Reflectable {
/// Returns a mirror that reflects `self`.
func getMirror() -> MirrorType {
//TODO
}
}
extension String : OutputStreamType {
mutating func write(other: String) {
//TODO
}
}
extension String : Streamable {
/// Write a textual representation of `self` into `target`
func writeTo<Target : OutputStreamType>(inout target: Target) {
//TODO
}
}
extension String {
init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {
//TODO
}
}
extension String : UnicodeScalarLiteralConvertible {
/// Create an instance initialized to `value`.
init(unicodeScalarLiteral value: String) {
//TODO
}
}
extension String {
init(_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, byteSize: Builtin.Word, isASCII: Builtin.Int1) {
//TODO
}
}
extension String : ExtendedGraphemeClusterLiteralConvertible {
/// Create an instance initialized to `value`.
init(extendedGraphemeClusterLiteral value: String) {
//TODO
}
}
extension String {
init(_builtinUTF16StringLiteral start: Builtin.RawPointer, numberOfCodeUnits: Builtin.Word) {
//TODO
}
}
extension String {
init(_builtinStringLiteral start: Builtin.RawPointer, byteSize: Builtin.Word, isASCII: Builtin.Int1) {
//TODO
}
}
extension String : StringLiteralConvertible {
/// Create an instance initialized to `value`.
init(stringLiteral value: String) {
//TODO
}
}
extension String : DebugPrintable {
/// A textual representation of `self`, suitable for debugging.
var debugDescription: String {
get {
return ""//TODO
}
}
}
extension String : Equatable {
}
extension String : Comparable {
}
extension String {
/// Append the elements of `other` to `self`.
mutating func extend(other: String) {
//TODO
}
/// Append `x` to `self`.
///
/// Complexity: amortized O(1).
mutating func append(x: UnicodeScalar) {
//TODO
}
}
extension String : Hashable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
///
/// **Note:** the hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
var hashValue: Int {
get {
return 0//TODO
}
}
}
extension String : StringInterpolationConvertible {
/// Create an instance by concatenating the elements of `strings`
static func convertFromStringInterpolation(strings: String...) -> String {
return ""//TODO
}
/// Create an instance containing `expr`\ 's `print` representation
static func convertFromStringInterpolationSegment<T>(expr: T) -> String {
return ""//TODO
}
}
extension String : Comparable {
}
extension String : Sliceable {
subscript (subRange: Range<String.Index>) -> String {
get {
return ""//TODO
}
}
}
extension String : ExtensibleCollectionType {
/// Reserve enough space to store `n` ASCII characters.
///
/// Complexity: O(`n`)
mutating func reserveCapacity(n: Int) {
//TODO
}
/// Append `c` to `self`.
///
/// Complexity: amortized O(1).
mutating func append(c: Character) {
//TODO
}
/// Append the elements of `newElements` to `self`.
mutating func extend<S : SequenceType where Character == Character>(newElements: S) {
//TODO
}
/// Create an instance containing `characters`.
init<S : SequenceType where Character == Character>(_ characters: S) {
//TODO
}
}
extension String {
/// Interpose `self` between every pair of consecutive `elements`,
/// then concatenate the result. For example::
///
/// "-|-".join(["foo", "bar", "baz"]) // "foo-|-bar-|-baz"
func join<S : SequenceType where String == String>(elements: S) -> String {
//TODO
}
}
extension String : RangeReplaceableCollectionType {
/// Replace the given `subRange` of elements with `newElements`.
///
/// Invalidates all indices with respect to `self`.
///
/// Complexity: O(\ `countElements(subRange)`\ ) if `subRange.endIndex
/// == self.endIndex` and `isEmpty(newElements)`\ , O(N) otherwise.
mutating func replaceRange<C : CollectionType where Character == Character>(subRange: Range<String.Index>, with newElements: C) {
//TODO
}
/// Insert `newElement` at index `i`.
///
/// Invalidates all indices with respect to `self`.
///
/// Complexity: O(\ `countElements(self)`\ ).
mutating func insert(newElement: Character, atIndex i: String.Index) {
//TODO
}
/// Insert `newElements` at index `i`
///
/// Invalidates all indices with respect to `self`.
///
/// Complexity: O(\ `countElements(self) + countElements(newElements)`\ ).
mutating func splice<S : CollectionType where Character == Character>(newElements: S, atIndex i: String.Index) {
//TODO
}
/// Remove and return the element at index `i`
///
/// Invalidates all indices with respect to `self`.
///
/// Complexity: O(\ `countElements(self)`\ ).
mutating func removeAtIndex(i: String.Index) -> Character {
//TODO
}
/// Remove the indicated `subRange` of characters
///
/// Invalidates all indices with respect to `self`.
///
/// Complexity: O(\ `countElements(self)`\ ).
mutating func removeRange(subRange: Range<String.Index>) {
//TODO
}
/// Remove all characters.
///
/// Invalidates all indices with respect to `self`.
///
/// :param: `keepCapacity`, if `true`, prevents the release of
//// allocated storage, which can be a useful optimization
/// when `self` is going to be grown again.
mutating func removeAll(keepCapacity: Bool = default) {
//TODO
}
}
extension String : StringInterpolationConvertible {
static func convertFromStringInterpolationSegment(expr: String) -> String {
return ""//TODO
}
static func convertFromStringInterpolationSegment(expr: Character) -> String {
return ""//TODO
}
static func convertFromStringInterpolationSegment(expr: UnicodeScalar) -> String {
return ""//TODO
}
static func convertFromStringInterpolationSegment(expr: Bool) -> String {
return ""//TODO
}
static func convertFromStringInterpolationSegment(expr: Float32) -> String {
return ""//TODO
}
static func convertFromStringInterpolationSegment(expr: Float64) -> String {
return ""//TODO
}
static func convertFromStringInterpolationSegment(expr: UInt8) -> String {
return ""//TODO
}
static func convertFromStringInterpolationSegment(expr: Int8) -> String {
return ""//TODO
}
static func convertFromStringInterpolationSegment(expr: UInt16) -> String {
return ""//TODO
}
static func convertFromStringInterpolationSegment(expr: Int16) -> String {
return ""//TODO
}
static func convertFromStringInterpolationSegment(expr: UInt32) -> String {
return ""//TODO
}
static func convertFromStringInterpolationSegment(expr: Int32) -> String {
return ""//TODO
}
static func convertFromStringInterpolationSegment(expr: UInt64) -> String {
return ""//TODO
}
static func convertFromStringInterpolationSegment(expr: Int64) -> String {
return ""//TODO
}
static func convertFromStringInterpolationSegment(expr: UInt) -> String {
return ""//TODO
}
static func convertFromStringInterpolationSegment(expr: Int) -> String {
return ""//TODO
}
}
extension String {
/// Construct an instance that is the concatenation of `sz` copies
/// of `repeatedValue`
init(count sz: Int, repeatedValue c: Character) {
//TODO
}
/// Construct an instance that is the concatenation of `sz` copies
/// of `Character(repeatedValue)`
init(count: Int, repeatedValue c: UnicodeScalar) {
//TODO
}
/// `true` iff `self` contains no characters.
var isEmpty: Bool {
get {
return false//TODO
}
}
}
extension String {
/// Return `true` iff `self` begins with `prefix`
func hasPrefix(prefix: String) -> Bool {
return false//TODO
}
/// Return `true` iff `self` ends with `suffix`
func hasSuffix(suffix: String) -> Bool {
return false//TODO
}
}
extension String {
/// Create an instance representing `v` in base 10.
init<T : _SignedIntegerType>(_ v: T) {
//TODO
}
/// Create an instance representing `v` in base 10.
init<T : _UnsignedIntegerType>(_ v: T) {
//TODO
}
/// Create an instance representing `v` in the given `radix` (base).
///
/// Numerals greater than 9 are represented as roman letters,
/// starting with `a` if `uppercase` is `false` or `A` otherwise.
init<T : _SignedIntegerType>(_ v: T, radix: Int, uppercase: Bool = default) {
//TODO
}
/// Create an instance representing `v` in the given `radix` (base).
///
/// Numerals greater than 9 are represented as roman letters,
/// starting with `a` if `uppercase` is `false` or `A` otherwise.
init<T : _UnsignedIntegerType>(_ v: T, radix: Int, uppercase: Bool = default) {
//TODO
}
}
extension String {
/// If the string represents an integer that fits into an Int, returns
/// the corresponding integer. This accepts strings that match the regular
/// expression "[-+]?[0-9]+" only.
func toInt() -> Int? {
return nil//TODO
}
}
extension String {
/// A collection of UTF-16 code units that encodes a `String` value.
struct UTF16View : Sliceable, Reflectable {
/// The position of the first code unit if the `String` is
/// non-empty; identical to `endIndex` otherwise.
var startIndex: Int {
get {
return 0//TODO
}
}
/// The "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
var endIndex: Int {
get {
return 0//TODO
}
}
/// A type whose instances can produce the elements of this
/// sequence, in order.
struct Generator : GeneratorType {
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// Requires: no preceding call to `self.next()` has returned
/// `nil`.
mutating func next() -> UnicodeScalar? {
return nil//TODO
}
}
/// Return a *generator* over the code points that comprise this
/// *sequence*.
///
/// Complexity: O(1)
func generate() -> Generator {
return Generator()//TODO
}
subscript (position: Int) -> UInt16 {
get {
return 0//TODO
}
}
subscript (subRange: Range<Int>) -> String.UTF16View {
get {
return 0//TODO
}
}
/// Returns a mirror that reflects `self`.
func getMirror() -> MirrorType {
return//TODO
}
}
/// A UTF-16 encoding of `self`.
var utf16: String.UTF16View {
get {
return String.UTF16View()//TODO
}
}
}
extension String {
/// Construct an instance given a collection of Unicode scalar
/// values.
init(_ view: String.UnicodeScalarView) {
//TODO
}
/// The value of `self` as a collection of Unicode scalar values.
var unicodeScalars: String.UnicodeScalarView
}
| bsd-3-clause | 5e1c9f86f858085e2036bda502c226b7 | 27.679293 | 133 | 0.593158 | 4.597976 | false | false | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Characteristics/Characteristic.LockTargetState.swift | 1 | 2139 | import Foundation
public extension AnyCharacteristic {
static func lockTargetState(
_ value: Enums.LockTargetState = .unsecured,
permissions: [CharacteristicPermission] = [.read, .write, .events],
description: String? = "Lock Target State",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 1,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.lockTargetState(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func lockTargetState(
_ value: Enums.LockTargetState = .unsecured,
permissions: [CharacteristicPermission] = [.read, .write, .events],
description: String? = "Lock Target State",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 1,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<Enums.LockTargetState> {
GenericCharacteristic<Enums.LockTargetState>(
type: .lockTargetState,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| mit | 410a271555444160c0f60629d95fb646 | 34.065574 | 75 | 0.589995 | 5.3475 | false | false | false | false |
proversity-org/edx-app-ios | Test/CourseCatalogDetailViewControllerTests.swift | 1 | 9006 | //
// CourseCatalogDetailViewControllerTests.swift
// edX
//
// Created by Akiva Leffert on 12/7/15.
// Copyright ยฉ 2015 edX. All rights reserved.
//
@testable import edX
class CourseCatalogDetailViewControllerTests: SnapshotTestCase {
func setupWithCourse(_ course: OEXCourse, interface: OEXInterface? = nil) -> (TestRouterEnvironment, CourseCatalogDetailViewController) {
let environment = TestRouterEnvironment(interface: interface).logInTestUser()
environment.mockEnrollmentManager.enrollments = []
environment.mockNetworkManager.interceptWhenMatching({_ in true}) {
return (nil, course)
}
let controller = CourseCatalogDetailViewController(environment: environment, courseID: course.course_id!)
return (environment, controller)
}
// MARK: Snapshots
func testSnapshotAboutScreen() {
let endDate = NSDate.stableTestDate()
let mediaInfo = ["course_video": CourseMediaInfo(name: "Video", uri: "http://example.com/image")]
let startInfo = OEXCourseStartDisplayInfo(date: nil, displayDate: "Eventually", type: .string)
let course = OEXCourse.freshCourse(
shortDescription: "This is a course that teaches you completely amazing things that you have always wanted to learn!",
overview: NSString.oex_longTest(),
effort : "Four to six weeks",
mediaInfo: mediaInfo,
startInfo: startInfo,
end: endDate as NSDate)
let (_, controller) = setupWithCourse(course)
inScreenNavigationContext(controller) {
self.waitForStream(controller.t_loaded)
stepRunLoop()
self.assertSnapshotValidWithContent(controller.navigationController!)
}
}
// MARK: Course Content
func verifyField(
effort : String? = nil,
shortDescription: String? = nil,
overview: String? = nil,
startInfo: OEXCourseStartDisplayInfo? = nil,
mediaInfo: [String:CourseMediaInfo] = [:],
endDate: NSDate? = nil,
file : StaticString = #file, line : UInt = #line,
verifier : (CourseCatalogDetailView) -> Bool)
{
let course = OEXCourse.freshCourse(
shortDescription: shortDescription,
overview: overview,
effort : effort,
mediaInfo: mediaInfo,
startInfo: startInfo,
end: endDate)
let environment = TestRouterEnvironment()
let view = CourseCatalogDetailView(frame: CGRect.zero, environment: environment)
view.applyCourse(course: course)
XCTAssertTrue(verifier(view), file:file, line:line)
}
func testHasEffortField() {
verifyField(effort:"some effort", endDate: nil) { $0.t_showingEffort }
}
func testHasNoEffortField() {
verifyField(effort:nil, endDate: nil) { !$0.t_showingEffort }
}
func testHasEndFieldNotStarted() {
verifyField(effort:nil, endDate: NSDate().addingDays(1)! as NSDate) { $0.t_showingEndDate }
}
func testHasEndFieldStarted() {
let startInfo = OEXCourseStartDisplayInfo(date: NSDate().addingDays(-1), displayDate: nil, type: .timestamp)
verifyField(effort:nil, startInfo: startInfo, endDate: NSDate().addingDays(1)! as NSDate) { !$0.t_showingEndDate }
}
func testHasNoEndFieldCourseNotStarted() {
verifyField(effort:nil, endDate: nil) { !$0.t_showingEndDate }
}
func testShortDescriptionEmpty() {
verifyField(shortDescription: "") { !$0.t_showingShortDescription }
}
func testShortDescriptionNotEmpty() {
verifyField(shortDescription: "ABC") { $0.t_showingShortDescription }
}
func testCourseOverviewEmpty() {
verifyField(mediaInfo: [:]) { !$0.t_showingPlayButton }
}
func testCourseOverviewNotEmpty() {
let mediaInfo = [
"course_video" : CourseMediaInfo(name: "course video", uri: "http://example.com/video")
]
verifyField(mediaInfo: mediaInfo) { $0.t_showingPlayButton }
}
// MARK: Enrollment
func testEnrollmentFailureShowsOverlayMessage() {
let course = OEXCourse.freshCourse()
let (environment, controller) = setupWithCourse(course)
environment.mockEnrollmentManager.enrollments = []
// load the course
inScreenDisplayContext(controller) {
waitForStream(controller.t_loaded)
// try to enroll with a bad request
environment.mockNetworkManager.interceptWhenMatching({(_ : NetworkRequest<UserCourseEnrollment>) in return true}, statusCode: 501, error: NSError.oex_unknownError())
let expectations = expectation(description: "enrollment finishes")
controller.t_enrollInCourse(completion: { () -> Void in
XCTAssertTrue(controller.t_isShowingOverlayMessage)
expectations.fulfill()
})
waitForExpectations()
}
}
func testEnrollmentFailureShowsAlertMessage() {
let course = OEXCourse.freshCourse()
let (environment, controller) = setupWithCourse(course)
environment.mockEnrollmentManager.enrollments = []
// load the course
inScreenDisplayContext(controller) {
waitForStream(controller.t_loaded)
// try to enroll with a bad request
environment.mockNetworkManager.interceptWhenMatching({(_ : NetworkRequest<UserCourseEnrollment>) in return true}, statusCode: 401, error: NSError.oex_unknownError())
let expectations = expectation(description: "enrollment finishes")
controller.t_enrollInCourse(completion: { () -> Void in
XCTAssertTrue(controller.t_isShowingAlertView())
expectations.fulfill()
})
waitForExpectations()
}
}
@discardableResult func verifyEnrollmentSuccessWithCourse(_ course: OEXCourse, message: String, setupEnvironment: ((TestRouterEnvironment) -> Void)? = nil) -> TestRouterEnvironment {
let (environment, controller) = setupWithCourse(course)
environment.mockEnrollmentManager.enrollments = []
setupEnvironment?(environment)
inScreenDisplayContext(controller) {
// load the course
waitForStream(controller.t_loaded)
// try to enroll
environment.mockNetworkManager.interceptWhenMatching({_ in true}) {
return (nil, UserCourseEnrollment(course:course, isActive: true))
}
expectation(forNotification: NSNotification.Name(rawValue:EnrollmentShared.successNotification), object: nil, handler: { (notification) -> Bool in
let enrollmentMessage = notification.object as! String
return enrollmentMessage == message
})
var completionCalled = false
controller.t_enrollInCourse {
completionCalled = true
}
waitForExpectations()
XCTAssertTrue(completionCalled)
}
return environment
}
func testEnrollmentRecognizesAlreadyEnrolled() {
let course = OEXCourse.freshCourse()
self.verifyEnrollmentSuccessWithCourse(course, message: Strings.findCoursesAlreadyEnrolledMessage) {env in
env.mockEnrollmentManager.courses = [course]
env.logInTestUser()
env.mockEnrollmentManager.feed.refresh()
}
}
func testEnrollmentNewEnrollment() {
let environment = verifyEnrollmentSuccessWithCourse(OEXCourse.freshCourse(), message: Strings.findCoursesEnrollmentSuccessfulMessage)
// and make sure the event fires
let index: Int? = environment.eventTracker.events.firstIndexMatching({ (record: MockAnalyticsRecord) -> Bool in
guard let event = record.asEvent else {
return false
}
return event.event.name == AnalyticsEventName.CourseEnrollmentSuccess.rawValue
})
XCTAssertNotNil(index)
}
func testShowsViewCourseWhenEnrolled() {
let course = OEXCourse.freshCourse()
let (environment, controller) = setupWithCourse(course)
environment.mockEnrollmentManager.courses = [course]
inScreenDisplayContext(controller) {
waitForStream(controller.t_loaded)
XCTAssertEqual(controller.t_actionText!, Strings.CourseDetail.viewCourse)
}
}
func testShowsEnrollWhenNotEnrolled() {
let course = OEXCourse.freshCourse()
let (_, controller) = setupWithCourse(course)
inScreenDisplayContext(controller) {
waitForStream(controller.t_loaded)
XCTAssertEqual(controller.t_actionText!, Strings.CourseDetail.enrollNow)
}
}
}
| apache-2.0 | d23bfeee078d6644c65aa5a465b37cd2 | 39.381166 | 186 | 0.640089 | 5.036353 | false | true | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Jetpack/Jetpack Restore/Restore Status/BaseRestoreStatusViewController.swift | 2 | 2950 | import Foundation
import CocoaLumberjack
import WordPressShared
struct JetpackRestoreStatusConfiguration {
let title: String
let iconImage: UIImage
let messageTitle: String
let messageDescription: String
let hint: String
let primaryButtonTitle: String
let placeholderProgressTitle: String?
let progressDescription: String?
}
class BaseRestoreStatusViewController: UIViewController {
// MARK: - Public Properties
lazy var statusView: RestoreStatusView = {
let statusView = RestoreStatusView.loadFromNib()
statusView.translatesAutoresizingMaskIntoConstraints = false
return statusView
}()
// MARK: - Private Properties
private(set) var site: JetpackSiteRef
private(set) var activity: Activity
private(set) var configuration: JetpackRestoreStatusConfiguration
private lazy var dateFormatter: DateFormatter = {
return ActivityDateFormatting.mediumDateFormatterWithTime(for: site)
}()
// MARK: - Initialization
init(site: JetpackSiteRef, activity: Activity) {
fatalError("A configuration struct needs to be provided")
}
init(site: JetpackSiteRef,
activity: Activity,
configuration: JetpackRestoreStatusConfiguration) {
self.site = site
self.activity = activity
self.configuration = configuration
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configureTitle()
configureNavigation()
configureRestoreStatusView()
}
// MARK: - Public
func primaryButtonTapped() {
fatalError("Must override in subclass")
}
// MARK: - Configure
private func configureTitle() {
title = configuration.title
}
private func configureNavigation() {
navigationItem.hidesBackButton = true
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done,
target: self,
action: #selector(doneTapped))
}
private func configureRestoreStatusView() {
let publishedDate = dateFormatter.string(from: activity.published)
statusView.configure(
iconImage: configuration.iconImage,
title: configuration.messageTitle,
description: String(format: configuration.messageDescription, publishedDate),
hint: configuration.hint
)
statusView.update(progress: 0, progressTitle: configuration.placeholderProgressTitle, progressDescription: nil)
view.addSubview(statusView)
view.pinSubviewToAllEdges(statusView)
}
@objc private func doneTapped() {
primaryButtonTapped()
}
}
| gpl-2.0 | 9d8b16d09a0c2f0fd977fb3b388157bc | 27.921569 | 119 | 0.660678 | 5.694981 | false | true | false | false |
narner/AudioKit | Examples/iOS/SporthEditor/SporthEditor/SporthEditorBrain.swift | 1 | 1143 | //
// SporthEditorBrain.swift
// SporthEditor
//
// Created by Kanstantsin Linou on 7/12/16.
// Copyright ยฉ 2016 AudioKit. All rights reserved.
//
import Foundation
import AudioKit
class SporthEditorBrain {
var generator: AKOperationGenerator?
var knownCodes = [String: String]()
var currentIndex = 0
var names: [String] {
return Array(knownCodes.keys)
}
func run(_ code: String) {
generator?.stop()
AudioKit.stop()
generator = AKOperationGenerator { _ in return AKOperation(code) }
AudioKit.output = generator
AudioKit.start()
generator?.start()
}
func stop() {
generator?.stop()
}
func save(_ name: String, code: String) {
let fileName = name + FileUtilities.fileExtension
let filePath = FileUtilities.filePath(fileName)
do {
try code.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
knownCodes[name] = code
NSLog("Saving was completed successfully")
} catch {
NSLog("Error during saving the file")
}
}
}
| mit | 529edcd7ce68c50df187b2c74ec07235 | 22.306122 | 94 | 0.610333 | 4.409266 | false | false | false | false |
1000copy/fin | Common/UIImage+Extension.swift | 1 | 1427 | //
// UIImage+Extension.swift
// V2ex-Swift
//
// Created by huangfeng on 2/3/16.
// Copyright ยฉ 2016 Fin. All rights reserved.
//
import UIKit
extension UIImage {
func roundedCornerImageWithCornerRadius(_ cornerRadius:CGFloat) -> UIImage {
let w = self.size.width
let h = self.size.height
var targetCornerRadius = cornerRadius
if cornerRadius < 0 {
targetCornerRadius = 0
}
if cornerRadius > min(w, h) {
targetCornerRadius = min(w,h)
}
let imageFrame = CGRect(x: 0, y: 0, width: w, height: h)
UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
UIBezierPath(roundedRect: imageFrame, cornerRadius: targetCornerRadius).addClip()
self.draw(in: imageFrame)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
class func imageUsedTemplateMode(_ named:String) -> UIImage? {
let image = UIImage(named: named)
if image == nil {
return nil
}
return image!.withRenderingMode(.alwaysTemplate)
}
class func templatedIcon(_ named:String) -> UIImage? {
let image = UIImage(named: named)
if image == nil {
return nil
}
return image!.withRenderingMode(.alwaysTemplate)
}
}
| mit | 18e988bb6b4db2694dd7296e8c56c1ee | 26.423077 | 89 | 0.603787 | 4.785235 | false | false | false | false |
tumblr/TMTumblrSDK | ExampleiOS/ExampleiOSTests/TMRequestBodyTests.swift | 1 | 3442 | //
// TMRequestBodyTests.swift
// ExampleiOS
//
// Created by Noah Hilt on 3/14/17.
// Copyright ยฉ 2017 tumblr. All rights reserved.
//
import TMTumblrSDK
import XCTest
final class TMRequestBodyTests: XCTestCase {
func testFormEncodedBody() {
let dictionary = testDictionary()
let requestBody = TMFormEncodedRequestBody(body: dictionary)
XCTAssertEqual(requestBody.parameters() as NSDictionary, dictionary as NSDictionary, "Form encoded request parameters should equal the body dictionary passed in.")
XCTAssertTrue(requestBody.encodeParameters(), "Form encoded request body should encode parameters.")
}
func testJSONRequestBody() {
let dictionary = testDictionary()
let requestBody = TMJSONEncodedRequestBody(jsonDictionary: dictionary)
XCTAssertEqual(requestBody.parameters() as NSDictionary, dictionary as NSDictionary, "JSON request parameters should equal the JSON dictionary passed in.")
XCTAssertFalse(requestBody.encodeParameters(), "JSON request body should not encode parameters.")
}
func testQueryEncodedBody() {
let dictionary = testDictionary()
let requestBody = TMQueryEncodedRequestBody(queryDictionary: dictionary)
XCTAssertEqual(requestBody.parameters() as NSDictionary, dictionary as NSDictionary, "Query encoded request parameters should equal the query dictionary passed in.")
XCTAssertTrue(requestBody.encodeParameters(), "Query encoded request body should encode parameters.")
}
func testJSONRequestContentType() {
let dictionary = testDictionary()
let requestBody = TMJSONEncodedRequestBody(jsonDictionary: dictionary)
XCTAssertEqual(requestBody.contentType() as String?, "application/json", "JSON request should have Content-Type: application/json.")
}
func testJSONRequestContentEncoding() {
let dictionary = testDictionary()
let requestBody = TMJSONEncodedRequestBody(jsonDictionary: dictionary)
XCTAssertEqual(requestBody.contentEncoding() as String?, nil, "JSON request should NOT have a Content-Encoding.")
}
func testGZIPJSONRequestContentType() {
let dictionary = testDictionary()
let requestBody = TMGZIPEncodedRequestBody(requestBody: TMJSONEncodedRequestBody(jsonDictionary: dictionary))
XCTAssertEqual(requestBody.contentType() as String?, "application/json", "GZipped JSON request should have Content-Type: application/json.")
}
func testGZIPJSONRequestContentEncoding() {
let dictionary = testDictionary()
let requestBody = TMGZIPEncodedRequestBody(requestBody: TMJSONEncodedRequestBody(jsonDictionary: dictionary))
XCTAssertEqual(requestBody.contentEncoding() as String?, "gzip", "GZipped JSON request should have Content-Encoding: gzip.")
}
func testGZIPFormEncodedBody() {
let dictionary = testDictionary()
let requestBody = TMGZIPEncodedRequestBody(requestBody: TMFormEncodedRequestBody(body: dictionary))
XCTAssertEqual(requestBody.parameters() as NSDictionary, dictionary as NSDictionary, "Form encoded request parameters should equal the body dictionary passed in.")
XCTAssertTrue(requestBody.encodeParameters(), "Form encoded request body should encode parameters.")
}
// MARK: Private
private func testDictionary() -> [AnyHashable: Any] {
return ["testing": [1,2,3]]
}
}
| apache-2.0 | 4161f5e485bdc43aa528d1896b30d5be | 48.157143 | 173 | 0.73932 | 5.285714 | false | true | false | false |
cotkjaer/Silverback | Silverback/CGVector.swift | 1 | 5880 | //
// CGVector.swift
// SilverbackFramework
//
// Created by Christian Otkjรฆr on 20/04/15.
// Copyright (c) 2015 Christian Otkjรฆr. All rights reserved.
//
import CoreGraphics
// MARK: - CGVector
public let CGVectorZero = CGVector(dx:0, dy:0)
extension CGVector
{
public init(point: CGPoint)
{
dx = point.x
dy = point.y
}
public init(from:CGPoint, to: CGPoint)
{
dx = to.x - from.x
dy = to.y - from.y
}
// MARK: with
public func with(dx dx: CGFloat) -> CGVector
{
return CGVector(dx:dx, dy:dy)
}
public func with(dy dy: CGFloat) -> CGVector
{
return CGVector(dx:dx, dy:dy)
}
// MARK: length
public var length : CGFloat { return sqrt(lengthSquared) }
public var lengthSquared : CGFloat { return dx*dx + dy*dy }
// MARK: - normalizing
public mutating func normalize()
{
self /= length
}
public var normalized : CGVector { return self / length }
// MARK: - Perpendicular
/// returns: vector from rotation this by 90 degrees either clockwise or counterclockwise
public func perpendicular(clockwise clockwise : Bool = true) -> CGVector
{
return clockwise ? CGVector(dx: dy, dy: -dx) : CGVector(dx: -dy, dy: dx)
}
// MARK: rotation
/// angle is in radians
public mutating func rotate(theta:CGFloat)
{
let sinTheta = sin(theta)
let cosTheta = cos(theta)
dx = (dx * cosTheta - dy * sinTheta)
dy = (dx * sinTheta + dy * cosTheta)
}
public var angle : CGFloat
{ return atan2(dy, dx) }
}
func length(vector: CGVector) -> CGFloat
{
return vector.length
}
func midPoint(between vector1:CGVector, and vector2:CGVector) -> CGVector
{
return CGVector(dx: (vector1.dx + vector2.dx) / 2.0, dy: (vector1.dy + vector2.dy) / 2.0)
}
// MARK: Equatable
extension CGVector//: Equatable
{
func isEqualTo(vector: CGVector, withPrecision precision:CGFloat) -> Bool
{
return (self - vector).length < abs(precision)
}
// public func isEqualTo(vector:CGVector) -> Bool
//{
// return self == vector
// }
}
//public func == (vector1: CGVector, vector2: CGVector) -> Bool
//{
// return vector1.dx == vector2.dx && vector1.dy == vector2.dy
//}
func isEqual(vector1: CGVector, vector2: CGVector, precision:CGFloat) -> Bool
{
return (vector1 - vector2).length < abs(precision)
}
// MARK: operators
public func + (vector1: CGVector, vector2: CGVector) -> CGVector
{
return CGVector(dx: vector1.dx + vector2.dx, dy: vector1.dy + vector2.dy)
}
public func += (inout vector1: CGVector, vector2: CGVector)
{
vector1.dx += vector2.dx
vector1.dy += vector2.dy
}
public func - (vector1: CGVector, vector2: CGVector) -> CGVector
{
return CGVector(dx: vector1.dx - vector2.dx, dy: vector1.dy - vector2.dy)
}
public func -= (inout vector1: CGVector, vector2: CGVector)
{
vector1.dx -= vector2.dx
vector1.dy -= vector2.dy
}
public func + (vector: CGVector, size: CGSize) -> CGVector
{
return CGVector(dx: vector.dx + size.width, dy: vector.dy + size.height)
}
public func += (inout vector: CGVector, size: CGSize)
{
vector.dx += size.width
vector.dy += size.height
}
public func - (vector: CGVector, size: CGSize) -> CGVector
{
return CGVector(dx: vector.dx - size.width, dy: vector.dy - size.height)
}
public func -= (inout vector: CGVector, size: CGSize)
{
vector.dx -= size.width
vector.dy -= size.height
}
public func * (factor: CGFloat, vector: CGVector) -> CGVector
{
return CGVector(dx: vector.dx * factor, dy: vector.dy * factor)
}
public func * (vector: CGVector, factor: CGFloat) -> CGVector
{
return CGVector(dx: vector.dx * factor, dy: vector.dy * factor)
}
public func *= (inout vector: CGVector, factor: CGFloat)
{
vector.dx *= factor
vector.dy *= factor
}
public func / (vector: CGVector, factor: CGFloat) -> CGVector
{
return CGVector(dx: vector.dx / factor, dy: vector.dy / factor)
}
public func /= (inout vector: CGVector, factor: CGFloat)
{
vector.dx /= factor
vector.dy /= factor
}
//MARK: - Draw
import UIKit
public extension CGVector
{
func draw(atPoint point: CGPoint, withColor color: UIColor = UIColor.blueColor(), inContext: CGContextRef? = UIGraphicsGetCurrentContext())
{
guard let context = inContext else { return }
let l = length
guard l > 0 else { return }
CGContextSaveGState(context)
color.setStroke()
let path = UIBezierPath()
var vectorToDraw = self
if length < 10
{
vectorToDraw *= 10 / length
}
path.moveToPoint(point)
path.addLineToPoint(point + vectorToDraw)
path.stroke()
CGContextRestoreGState(context)
}
func bezierPathWithArrowFromPoint(startPoint: CGPoint) -> UIBezierPath
{
let toPoint = startPoint + self
let tailWidth = max(1, length / 30)
let headWidth = max(3, length / 10)
let headStartPoint = lerp(startPoint, toPoint, 0.9)
let p = perpendicular().normalized
let path = UIBezierPath()
path.moveToPoint(toPoint)
path.addLineToPoint(headStartPoint + p * headWidth)
path.addLineToPoint(headStartPoint + p * tailWidth)
path.addLineToPoint(startPoint + p * tailWidth)
path.addLineToPoint(startPoint - p * tailWidth)
path.addLineToPoint(headStartPoint - p * tailWidth)
path.addLineToPoint(headStartPoint - p * headWidth)
path.closePath()
return path
}
}
| mit | ea9ef20aba678729c5097d923f3953af | 22.606426 | 143 | 0.605648 | 3.884997 | false | false | false | false |
Kushki/kushki-ios | Example/Pods/Kushki/Kushki/Classes/KushkiClient.swift | 1 | 27214 | import Foundation
import Sift
class KushkiClient {
private let environment: KushkiEnvironment
init(environment: KushkiEnvironment, regional: Bool) {
self.environment = regional ? environment == KushkiEnvironment.production ? KushkiEnvironment.production_regional : KushkiEnvironment.testing_regional : environment
}
func post(withMerchantId publicMerchantId: String, endpoint: String, requestMessage: String, withCompletion completion: @escaping (Transaction) -> ()) {
showHttpResponse(withMerchantId: publicMerchantId, endpoint: endpoint, requestBody: requestMessage) { transaction in
completion(self.parseResponse(jsonResponse: transaction))
}
}
func post(withMerchantId publicMerchantId: String, endpoint: String, requestMessage: String, withCompletion completion: @escaping (ConfrontaResponse) -> ()){
showHttpResponse(withMerchantId: publicMerchantId, endpoint: endpoint, requestBody: requestMessage) { response in
completion(self.parseValidationResponse(jsonResponse: response))
}
}
func get(withMerchantId publicMerchantId: String, endpoint: String, withCompletion completion: @escaping ([Bank]) -> ()) {
showHttpGetResponse(withMerchantId: publicMerchantId, endpoint: endpoint) {
bankList in
completion(self.parseGetBankListResponse(jsonResponse: bankList))
}
}
func get(withMerchantId publicMerchantId: String, endpoint: String, withParam param: String , withCompletion completion: @escaping (CardInfo) -> ()) {
showHttpGetResponse(withMerchantId: publicMerchantId, endpoint: endpoint, param: param) {
cardInfo in
completion(self.parseGetCardInfoResponse(jsonResponse: cardInfo))
}
}
func get(withMerchantId publicMerchantId: String, endpoint: String, withCompletion completion: @escaping(MerchantSettings) -> ()) {
showHttpGetMerchantSettings(withMerchantId: publicMerchantId, endpoint: endpoint, withCompletion: completion)
}
func initSiftScience(merchantSettings: MerchantSettings, userId: String) {
let sift = Sift.sharedInstance
sift()?.accountId = self.environment == KushkiEnvironment.production ? merchantSettings.prodAccountId : merchantSettings.sandboxAccountId
sift()?.beaconKey = self.environment == KushkiEnvironment.production ? merchantSettings.prodBaconKey : merchantSettings.sandboxBaconKey
sift()?.userId = userId
sift()?.allowUsingMotionSensors = true
}
func buildParameters(withCard card: Card, withCurrency currency: String) -> String {
let requestDictionary = buildJsonObject(withCard: card, withCurrency: currency)
let jsonData = try! JSONSerialization.data(withJSONObject: requestDictionary, options: .prettyPrinted)
let dictFromJson = String(data: jsonData, encoding: String.Encoding.utf8)
return dictFromJson!
}
func buildParameters(withCard card: Card, withCurrency currency: String, withAmount totalAmount: Double, withSiftScienceResponse siftScienceResponse: SiftScienceObject) -> String {
let requestDictionary = buildJsonObject(withCard: card, withCurrency: currency, withAmount: totalAmount, siftScienceResponse: siftScienceResponse)
let jsonData = try! JSONSerialization.data(withJSONObject: requestDictionary, options: .prettyPrinted)
let dictFromJson = String(data: jsonData, encoding: String.Encoding.utf8)
return dictFromJson!
}
func buildParameters(withAmount amount: Amount, withCallbackUrl callbackUrl:String,
withUserType userType:String,withDocumentType documentType:String,
withDocumentNumber documentNumber:String, withEmail email:String,
withCurrency currency:String) -> String {
let requestDictionary = buildJsonObject(withAmount: amount, withCallbackUrl: callbackUrl,
withUserType: userType,withDocumentType: documentType,
withDocumentNumber: documentNumber, withEmail: email,
withCurrency: currency)
let jsonData = try! JSONSerialization.data(withJSONObject: requestDictionary, options: .prettyPrinted)
let dictFromJson = String(data: jsonData, encoding: String.Encoding.utf8)
return dictFromJson!
}
func buildParameters(withAmount amount: Amount, withCallbackUrl callbackUrl:String,
withUserType userType:String,withDocumentType documentType:String,
withDocumentNumber documentNumber:String, withEmail email:String,
withCurrency currency:String, withPaymentDescription paymentDescription:String) -> String {
let requestDictionary = buildJsonObject(withAmount: amount, withCallbackUrl: callbackUrl,
withUserType: userType,withDocumentType: documentType,
withDocumentNumber: documentNumber, withEmail: email,
withCurrency: currency,withPaymentDescription: paymentDescription)
let jsonData = try! JSONSerialization.data(withJSONObject: requestDictionary, options: .prettyPrinted)
let dictFromJson = String(data: jsonData, encoding: String.Encoding.utf8)
return dictFromJson!
}
func buildParameters(
withAccountNumber accountNumber: String, withAccountType accountType: String, withBankCode bankCode: String, withCurrency currency: String, withDocumentNumber documentNumber: String, withDocumentType documentType: String, withEmail email: String, withLastName lastName: String, withName name: String, withTotalAmount totalAmount: Double) -> String{
let requestDictionary = buildJsonObject(withAccountNumber: accountNumber, withAccountType: accountType, withBankCode: bankCode, withCurrency: currency , withDocumentNumber: documentNumber, withDocumentType: documentType, withEmail: email, withLastName: lastName, withName: name, withTotalAmount: totalAmount)
let jsonData = try! JSONSerialization.data(withJSONObject: requestDictionary, options: .prettyPrinted)
let dictFromJson = String(data: jsonData, encoding: String.Encoding.utf8)
return dictFromJson!
}
func buildParameters(
withCityCode cityCode: String, withExpeditionDate expeditionDate: String, withPhone phone: String, withSecureService secureService: String,withSecureServiceId secureServiceId: String, withStateCode stateCode: String) -> String{
let requestDictionary = buildJsonObject(withCityCode: cityCode, withExpeditionDate: expeditionDate, withPhone: phone, withSecureService: secureService, withSecureServiceId: secureServiceId, withStateCode: stateCode)
let jsonData = try! JSONSerialization.data(withJSONObject: requestDictionary, options: .prettyPrinted)
let dictFromJson = String(data: jsonData, encoding: String.Encoding.utf8)
return dictFromJson!
}
func buildParameters(withAnswers answers: [[String: String]], withQuestionnarieCode questionnarieCode: String, withSecureService secureService: String, withSecureServiceId secureServiceId: String) -> String{
let requestDictionary = buildJsonObject(withAnswers: answers, withQuestionnarieCode: questionnarieCode, withSecureService: secureService, withSecureServiceId: secureServiceId)
let jsonData = try! JSONSerialization.data(withJSONObject: requestDictionary, options: .prettyPrinted)
let dictFromJson = String(data: jsonData, encoding: String.Encoding.utf8)
return dictFromJson!
}
func buildParameters(withName name : String, withLastName lastName: String, withIdentification identification: String, withTotalAmount totalAmount: Double, withCurrency currency: String, withEmail email: String) -> String{
let requestDictionary = buildJsonObject(withName: name, withLastName: lastName, withIdentification: identification, withTotalAmount: totalAmount, withCurrency: currency, withEmail: email)
let jsonData = try! JSONSerialization.data(withJSONObject: requestDictionary, options: .prettyPrinted)
let dictFromJson = String(data: jsonData, encoding: String.Encoding.utf8)
return dictFromJson!
}
func buildParameters(withCurrency currency: String, withDescription description : String, withEmail email: String, withReturnUrl returnUrl: String, withTotalAmount totalAmount: Double) -> String{
let requestDictionary = buildJsonObject(withCurrency: currency, withDescription: description, withEmail: email, withReturnUrl: returnUrl, withTotalAmount: totalAmount)
let jsonData = try! JSONSerialization.data(withJSONObject: requestDictionary, options: .prettyPrinted)
let dictFromJson = String(data: jsonData, encoding: String.Encoding.utf8)
return dictFromJson!
}
func buildParameters(withCurrency currency: String, withEmail email: String, withCallbackUrl callbackUrl: String, withCardNumber cardNumber: String) -> String{
let requestDictionary = buildJsonObject(withCurrency: currency, withEmail: email, withCallbackUrl: callbackUrl, withCardNumber: cardNumber)
let jsonData = try! JSONSerialization.data(withJSONObject: requestDictionary, options: .prettyPrinted)
let dictFromJson = String(data: jsonData, encoding: String.Encoding.utf8)
return dictFromJson!
}
func buildJsonObject(withCard card: Card, withCurrency currency: String) -> [String : Any] {
var requestDictionary:[String : Any] = [
"card": [
"name": card.name,
"number": card.number,
"expiryMonth": card.expiryMonth,
"expiryYear": card.expiryYear,
"cvv": card.cvv
],
"currency": currency
]
if card.months != 0 {
requestDictionary["months"] = card.months
}
if card.isDeferred {
requestDictionary["isDeferred"] = card.isDeferred
}
return requestDictionary
}
func buildJsonObject(withAmount amount: Amount, withCallbackUrl callbackUrl:String,
withUserType userType:String,withDocumentType documentType:String,
withDocumentNumber documentNumber:String, withEmail email:String,
withCurrency currency:String) -> [String : Any]{
let requestDictionary:[String : Any] = [
"amount": [
"subtotalIva": amount.subtotalIva,
"subtotalIva0": amount.subtotalIva0,
"iva": amount.iva,
],
"callbackUrl": callbackUrl,
"userType" : userType,
"documentType" : documentType,
"documentNumber" : documentNumber,
"email" : email,
"currency" : currency
]
return requestDictionary
}
func buildJsonObject(withAmount amount: Amount, withCallbackUrl callbackUrl:String,
withUserType userType:String,withDocumentType documentType:String,
withDocumentNumber documentNumber:String, withEmail email:String,
withCurrency currency:String, withPaymentDescription paymentDescription: String) -> [String : Any]{
var requestDictionary = buildJsonObject(withAmount: amount, withCallbackUrl: callbackUrl,
withUserType: userType,withDocumentType: documentType,
withDocumentNumber: documentNumber, withEmail: email,
withCurrency: currency)
requestDictionary["paymentDescription"] = paymentDescription
return requestDictionary
}
func buildJsonObject(withCard card: Card, withCurrency currency: String, withAmount totalAmount: Double, siftScienceResponse: SiftScienceObject) -> [String : Any] {
var requestDictionary = buildJsonObject(withCard: card, withCurrency: currency)
requestDictionary["totalAmount"] = totalAmount
requestDictionary["sessionId"] = siftScienceResponse.sessionId
requestDictionary["userId"] = siftScienceResponse.userId
return requestDictionary
}
func buildJsonObject( withAccountNumber accountNumber: String, withAccountType accountType: String, withBankCode bankCode: String, withCurrency currency: String, withDocumentNumber documentNumber: String, withDocumentType documentType: String, withEmail email: String, withLastName lastName: String, withName name: String, withTotalAmount totalAmount: Double) -> [String: Any] {
let requestDictionary:[String: Any] = [
"accountNumber": accountNumber,
"accountType": accountType,
"bankCode": bankCode,
"currency": currency,
"documentNumber": documentNumber,
"documentType": documentType,
"email": email,
"lastName": lastName,
"name": name,
"totalAmount": totalAmount,
]
return requestDictionary
}
func buildJsonObject( withCityCode cityCode: String, withExpeditionDate expeditionDate: String, withPhone phone: String, withSecureService secureService: String,withSecureServiceId secureServiceId: String, withStateCode stateCode: String) -> [String: Any] {
let confrontaInfo: [String: Any] = [
"confrontaBiometrics":
[
"cityCode": cityCode,
"stateCode": stateCode,
"phone": phone,
"expeditionDate": expeditionDate
]
]
let requestDictionary:[String: Any] = [
"secureServiceId": secureServiceId,
"secureService": secureService,
"confrontaInfo": confrontaInfo
]
return requestDictionary
}
func buildJsonObject(withAnswers answers: [[String: String]], withQuestionnarieCode questionnarieCode: String, withSecureService secureService: String, withSecureServiceId secureServiceId: String) -> [String: Any] {
let confrontaInfo: [String: Any] =
["questionnaireCode": questionnarieCode,
"answers": answers,
]
let requestDictionary:[String: Any] = [
"secureService": secureService,
"secureServiceId": secureServiceId,
"confrontaInfo": confrontaInfo
]
return requestDictionary
}
func buildJsonObject( withName name : String, withLastName lastName: String, withIdentification identification: String, withTotalAmount totalAmount: Double, withCurrency currency: String, withEmail email: String) -> [String: Any] {
let requestDictionary:[String: Any] = [
"name": name,
"lastName": lastName,
"identification": identification,
"totalAmount": totalAmount,
"currency": currency,
"email": email,
]
return requestDictionary
}
func buildJsonObject(withCurrency currency: String, withDescription description : String, withEmail email: String, withReturnUrl returnUrl: String, withTotalAmount totalAmount: Double) -> [String: Any] {
let requestDictionary:[String: Any] = [
"currency": currency,
"description": description,
"email": email,
"returnUrl": returnUrl,
"totalAmount": totalAmount
]
return requestDictionary
}
func buildJsonObject(withCurrency currency: String, withEmail email: String, withCallbackUrl callbackUrl: String, withCardNumber cardNumber: String) -> [String: Any] {
let requestDictionary:[String: Any] = [
"currency": currency,
"email": email,
"callbackUrl": callbackUrl,
"cardNumber": cardNumber
]
return requestDictionary
}
func createSiftScienceSession(withMerchantId publicMerchantId: String, card: Card, isTest: Bool, merchantSettings: MerchantSettings) -> SiftScienceObject{
let cardNumber = card.number
let firstIndex = cardNumber.index(cardNumber.startIndex, offsetBy:6)
let endIndex = cardNumber.index(cardNumber.endIndex, offsetBy:-4)
let processor = cardNumber[..<firstIndex]
let clientIdentification = cardNumber[endIndex...]
let session_id = UUID().uuidString;
let user_id = publicMerchantId + processor + clientIdentification;
return SiftScienceObject(userId: user_id, sessionId: session_id)
}
private func showHttpResponse(withMerchantId publicMerchantId: String, endpoint: String, requestBody: String, withCompletion completion: @escaping (String) -> ()) {
let url = URL(string: self.environment.rawValue + endpoint)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = requestBody.data(using: String.Encoding.utf8)
request.addValue("application/json; charset=UTF-8",
forHTTPHeaderField: "Content-Type")
request.addValue(publicMerchantId, forHTTPHeaderField: "public-merchant-id")
let task = URLSession.shared.dataTask (with: request) { data, response, error in
if let theError = error {
print(theError.localizedDescription)
return
}
let responseBody = String(data: data!, encoding: String.Encoding.utf8)!
completion(responseBody)
}
task.resume()
}
private func parseResponse(jsonResponse: String) -> Transaction {
var token = ""
var code = "000"
var message = ""
var settlement: Double?
var secureId: String?
var secureService: String?
if let responseDictionary = self.convertStringToDictionary(jsonResponse) {
if let tokenValue = responseDictionary["token"] as? String {
token = tokenValue
}
else {
code = responseDictionary["code"] as? String ?? "001"
message = responseDictionary["message"] as? String ?? "Error inesperado"
}
if let settlementValue = responseDictionary["settlement"] as? Double {
settlement = settlementValue
}
if let secureIdValue = responseDictionary["secureId"] as? String{
secureId = secureIdValue
}
if let secureServiceValue = responseDictionary["secureService"] as? String{
secureService = secureServiceValue
}
}
else {
code = "002"
message = "Hubo un error inesperado, intenta nuevamente"
}
return Transaction(code: code, message: message, token: token, settlement: settlement, secureId: secureId, secureService: secureService)
}
private func parseValidationResponse(jsonResponse: String) -> ConfrontaResponse {
var code: String = "BIO010 "
var message: String = ""
var questionnarieCode: String = ""
var questionnarie: [ConfrontaQuestionnarie] = []
if let responseDictionary = self.convertStringToDictionary(jsonResponse) {
if let codeValue = responseDictionary["code"] as? String{
code = codeValue
}
else{
code = "E002"
message = "Ocurriรณ un error inesperado"
}
if let messageValue = responseDictionary["message"] as? String{
message = messageValue
}
if let questionnarieCodeValue = responseDictionary["questionnaireCode"] as? String{
questionnarieCode = questionnarieCodeValue
}
if let questionsValue = responseDictionary["questions"] as? [AnyObject]{
for question in questionsValue {
var id: String = ""
var text: String = ""
var options: [ConfrontaQuestionOptions] = []
if let idValue = question["id"] as? String{
id = idValue
}
if let textValue = question["text"] as? String{
text = textValue
}
if let optionsValues = question["options"] as? [AnyObject]{
for option in optionsValues{
var textOption: String = ""
var idOption: String = ""
if let textOptionValue = option["text"] as? String{
textOption = textOptionValue
}
if let idOptionValue = option["id"] as? String{
idOption = idOptionValue
}
let confrontaOptionValue: ConfrontaQuestionOptions = ConfrontaQuestionOptions(text: textOption, id: idOption)
options.append(confrontaOptionValue)
}
}
questionnarie.append(ConfrontaQuestionnarie(id: id, text: text, options: options))
}
}
}
return ConfrontaResponse(code: code, message: message, questionnarieCode: questionnarieCode, questions: questionnarie)
}
// source: http://stackoverflow.com/questions/30480672/how-to-convert-a-json-string-to-a-dictionary
private func convertStringToDictionary(_ string: String) -> [String:AnyObject]? {
if let data = string.data(using: String.Encoding.utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}
private func convertStringToArrayDictionary(_ string: String) -> [[String:AnyObject]]? {
if let data = string.data(using: String.Encoding.utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [[String:AnyObject]]
} catch let error as NSError {
print(error)
}
}
return nil
}
private func showHttpGetResponse(withMerchantId publicMerchantId: String, endpoint: String, withCompletion completion: @escaping (String) -> ()) {
let url = URL(string: self.environment.rawValue + endpoint)!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue(publicMerchantId, forHTTPHeaderField: "public-merchant-id")
let task = URLSession.shared.dataTask (with: request) { data, response, error in
if let theError = error {
print(theError.localizedDescription)
return
}
let responseBody = String(data: data!, encoding: String.Encoding.utf8)!
completion(responseBody)
}
task.resume()
}
private func showHttpGetResponse(withMerchantId publicMerchantId: String, endpoint: String, param:String , withCompletion completion: @escaping (String) -> ()) {
let url = URL(string: self.environment.rawValue + endpoint + param)!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue(publicMerchantId, forHTTPHeaderField: "public-merchant-id")
let task = URLSession.shared.dataTask (with: request) { data, response, error in
if let theError = error {
print(theError.localizedDescription)
return
}
let responseBody = String(data: data!, encoding: String.Encoding.utf8)!
completion(responseBody)
}
task.resume()
}
private func showHttpGetMerchantSettings(withMerchantId publicMerchantId: String, endpoint: String, withCompletion completion: @escaping (MerchantSettings) -> ()) {
let url = URL(string: self.environment.rawValue + endpoint)!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue(publicMerchantId, forHTTPHeaderField: "public-merchant-id")
let task = URLSession.shared.dataTask (with: request) { data, response, error in
print("Data", String(data: data!, encoding: String.Encoding.utf8)!)
if let theError = error {
print(theError.localizedDescription)
return
}
guard let response = try? JSONDecoder().decode(MerchantSettings.self, from: data!) else {
print("Error decoding merchant settings")
return
}
completion(response)
}
task.resume()
}
private func parseGetBankListResponse(jsonResponse: String) -> [Bank] {
var bankList: [Bank] = []
if let responseDictionary = self.convertStringToArrayDictionary(jsonResponse) {
for responseBank in responseDictionary{
var nameBank = ""
var codeBank = ""
if let name = (responseBank["name"] as? String) ,let codeResponse = (responseBank["code"] as? String){
nameBank = name
codeBank = codeResponse
let bank = Bank(code: codeBank, name: nameBank)
bankList.append(bank)
}
}
}
return bankList;
}
private func parseGetCardInfoResponse(jsonResponse: String) -> CardInfo {
var bank = ""
var brand = ""
var cardType = ""
if let responseDictionary = self.convertStringToDictionary(jsonResponse) {
if let bankValue = (responseDictionary["bank"] as? String){
bank = bankValue
}
if let brandValue = (responseDictionary["brand"] as? String){
brand = brandValue
}
if let cardTypeValue = (responseDictionary["cardType"] as? String){
cardType = cardTypeValue
}
}
return CardInfo(bank: bank, brand: brand, cardType: cardType)
}
}
| mit | eed07ab080d9569a622eaac99b07ba21 | 49.301294 | 382 | 0.625216 | 5.38658 | false | false | false | false |
samodom/TestableUIKit | TestableUIKit/UIResponder/UIView/UITableView/UITableViewReloadSectionsSpy.swift | 1 | 3885 | //
// UITableViewReloadSectionsSpy.swift
// TestableUIKit
//
// Created by Sam Odom on 2/21/17.
// Copyright ยฉ 2017 Swagger Soft. All rights reserved.
//
import UIKit
import TestSwagger
import FoundationSwagger
public extension UITableView {
private static let reloadSectionsCalledKeyString = UUIDKeyString()
private static let reloadSectionsCalledKey =
ObjectAssociationKey(reloadSectionsCalledKeyString)
private static let reloadSectionsCalledReference =
SpyEvidenceReference(key: reloadSectionsCalledKey)
private static let reloadSectionsSectionsKeyString = UUIDKeyString()
private static let reloadSectionsSectionsKey =
ObjectAssociationKey(reloadSectionsSectionsKeyString)
private static let reloadSectionsSectionsReference =
SpyEvidenceReference(key: reloadSectionsSectionsKey)
private static let reloadSectionsAnimationKeyString = UUIDKeyString()
private static let reloadSectionsAnimationKey =
ObjectAssociationKey(reloadSectionsAnimationKeyString)
private static let reloadSectionsAnimationReference =
SpyEvidenceReference(key: reloadSectionsAnimationKey)
private static let reloadSectionsCoselectors = SpyCoselectors(
methodType: .instance,
original: #selector(UITableView.reloadSections(_:with:)),
spy: #selector(UITableView.spy_reloadSections(_:with:))
)
/// Spy controller for ensuring that a table view has had `reloadSections(_:with:)` called on it.
public enum ReloadSectionsSpyController: SpyController {
public static let rootSpyableClass: AnyClass = UITableView.self
public static let vector = SpyVector.direct
public static let coselectors: Set = [reloadSectionsCoselectors]
public static let evidence: Set = [
reloadSectionsCalledReference,
reloadSectionsSectionsReference,
reloadSectionsAnimationReference
]
public static let forwardsInvocations = true
}
/// Spy method that replaces the true implementation of `reloadSections(_:with:)`
dynamic public func spy_reloadSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) {
reloadSectionsCalled = true
reloadSectionsSections = sections
reloadSectionsAnimation = animation
spy_reloadSections(sections, with: animation)
}
/// Indicates whether the `reloadSections(_:with:)` method has been called on this object.
public final var reloadSectionsCalled: Bool {
get {
return loadEvidence(with: UITableView.reloadSectionsCalledReference) as? Bool ?? false
}
set {
saveEvidence(newValue, with: UITableView.reloadSectionsCalledReference)
}
}
/// Provides the sections passed to `reloadSections(_:with:)` if called.
public final var reloadSectionsSections: IndexSet? {
get {
return loadEvidence(with: UITableView.reloadSectionsSectionsReference) as? IndexSet
}
set {
let reference = UITableView.reloadSectionsSectionsReference
guard let sections = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(sections, with: reference)
}
}
/// Provides the animation type passed to `reloadSections(_:with:)` if called.
public final var reloadSectionsAnimation: UITableViewRowAnimation? {
get {
return loadEvidence(with: UITableView.reloadSectionsAnimationReference) as? UITableViewRowAnimation
}
set {
let reference = UITableView.reloadSectionsAnimationReference
guard let animation = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(animation, with: reference)
}
}
}
| mit | c302ac37f3a7605b925fbc0212a0b303 | 34.962963 | 111 | 0.699537 | 6.174881 | false | false | false | false |
chadoneba/MTools | MTools/Classes/Helpers/HelperDictionary.swift | 1 | 1886 |
import Foundation
// ะ ะฐััะธัะตะฝะธะต ะดะปั ะขะธะฟะฐ ัะปะพะฒะฐัะตะน
public extension Dictionary {
// ะะฝะฐะบ
public static func += (left:inout [Key:Value],right:[Key:Value]){
for obj in right {
left.updateValue(obj.value, forKey: obj.key)
}
}
// ะกัะผะธัะพะฒะฐะฝะธะต ัะปะพะฒะฐัะตะน
public static func + (left:[Key:Value],right:[Key:Value])->[Key:Value]{
var result = left
for obj in right {
result.updateValue(obj.value, forKey: obj.key)
}
return result
}
// ะะฐะผะตะฝะฐ ะบะปััะฐ ั ัะพั
ัะฐะฝะตะฝะธะตะผ ัะฒัะทะฐะฝะฝะพะณะพ ะทะฝะฐัะตะฝะธั
public mutating func updateKey(from:Key,to:Key){
guard self.index(forKey: from) != nil else {
return
}
let tmp = self.remove(at: self.index(forKey: from)!)
self.updateValue(tmp.value, forKey: to)
}
public func filterAsDict(_ isIncluded: (Key,Value?) -> Bool) -> [Key:Value?] {
var result = [Key:Value]()
for (Key,Value) in self {
if isIncluded(Key,Value) {
result.updateValue(Value, forKey: Key)
}
}
return result
}
}
public func groupArrayByKey<T>(array:[T],key:@escaping (T) -> String) -> Dictionary<String,Array<T>> {
var result:Dictionary<String,Array<T>> = [:]
for item in array {
var value = result[key(item)]
if value == nil {
value = [item]
} else {
value!.append(item)
}
result.updateValue(value!, forKey: key(item))
}
return result
}
public func groupObjectByKey<T>(array:[T],key:@escaping (T) -> String) -> Dictionary<String,T> {
var result:Dictionary<String,T> = [:]
for item in array {
result.updateValue(item, forKey: key(item))
}
return result
}
| mit | fbafc153dc769085e947fd21dcc5d1f3 | 24.309859 | 102 | 0.5665 | 3.735967 | false | false | false | false |
poetmountain/MotionMachine | Sources/EasingTypes/EasingCircular.swift | 1 | 2969 | //
// EasingCircular.swift
// MotionMachine
//
// Created by Brett Walker on 5/3/16.
// Copyright ยฉ 2016-2018 Poet & Mountain, LLC. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/**
* EasingCircular provides circular easing equations.
*
* - remark: See http://easings.net for visual examples.
*/
public struct EasingCircular {
public static func easeIn() -> EasingUpdateClosure {
func easing (_ elapsedTime: TimeInterval, startValue: Double, valueRange: Double, duration: TimeInterval) -> Double {
let time = elapsedTime / duration
let easing_value = -valueRange * (sqrt(1 - time*time) - 1) + startValue
return easing_value
}
return easing
}
public static func easeOut() -> EasingUpdateClosure {
func easing (_ elapsedTime: TimeInterval, startValue: Double, valueRange: Double, duration: TimeInterval) -> Double {
var time = elapsedTime / duration
time -= 1
let easing_value = valueRange * sqrt(1 - time*time) + startValue
return easing_value
}
return easing
}
public static func easeInOut() -> EasingUpdateClosure {
func easing (_ elapsedTime: TimeInterval, startValue: Double, valueRange: Double, duration: TimeInterval) -> Double {
var easing_value = 0.0
var time = elapsedTime / (duration * 0.5)
if (time < 1) {
easing_value = (-valueRange * 0.5) * (sqrt(1 - time*time) - 1) + startValue;
} else {
time -= 2;
easing_value = (valueRange * 0.5) * (sqrt(1 - time*time) + 1) + startValue;
}
return easing_value
}
return easing
}
}
| mit | b147d074d09659204205c632098389d3 | 35.641975 | 125 | 0.624326 | 4.688784 | false | false | false | false |
xedin/swift | benchmark/single-source/NSStringConversion.swift | 2 | 2950 | //===--- NSStringConversion.swift -----------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// <rdar://problem/19003201>
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import TestsUtils
import Foundation
fileprivate var test:NSString = ""
public let NSStringConversion = [
BenchmarkInfo(name: "NSStringConversion",
runFunction: run_NSStringConversion,
tags: [.validation, .api, .String, .bridging]),
BenchmarkInfo(name: "NSStringConversion.UTF8",
runFunction: run_NSStringConversion_nonASCII,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { test = NSString(cString: "tรซst", encoding: String.Encoding.utf8.rawValue)! }),
BenchmarkInfo(name: "NSStringConversion.Mutable",
runFunction: run_NSMutableStringConversion,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { test = NSMutableString(cString: "test", encoding: String.Encoding.ascii.rawValue)! }),
BenchmarkInfo(name: "NSStringConversion.Long",
runFunction: run_NSStringConversion_long,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { test = NSString(cString: "The quick brown fox jumps over the lazy dog", encoding: String.Encoding.ascii.rawValue)! } ),
BenchmarkInfo(name: "NSStringConversion.LongUTF8",
runFunction: run_NSStringConversion_longNonASCII,
tags: [.validation, .api, .String, .bridging],
setUpFunction: { test = NSString(cString: "Thรซ qรผick brรถwn fรถx jumps over the lazy dรถg", encoding: String.Encoding.utf8.rawValue)! })]
public func run_NSStringConversion(_ N: Int) {
let test:NSString = NSString(cString: "test", encoding: String.Encoding.ascii.rawValue)!
for _ in 1...N * 10000 {
//Doesn't test accessing the String contents to avoid changing historical benchmark numbers
blackHole(identity(test) as String)
}
}
fileprivate func innerLoop(_ str: NSString, _ N: Int, _ scale: Int = 5000) {
for _ in 1...N * scale {
for char in (identity(str) as String).utf8 {
blackHole(char)
}
}
}
public func run_NSStringConversion_nonASCII(_ N: Int) {
innerLoop(test, N, 2500)
}
public func run_NSMutableStringConversion(_ N: Int) {
innerLoop(test, N)
}
public func run_NSStringConversion_long(_ N: Int) {
innerLoop(test, N, 1000)
}
public func run_NSStringConversion_longNonASCII(_ N: Int) {
innerLoop(test, N, 300)
}
#endif
| apache-2.0 | 9d35f58131915149dd4ff11f5b86ed18 | 38.783784 | 152 | 0.641984 | 4.248196 | false | true | false | false |
DarrenKong/firefox-ios | Extensions/ShareTo/InitialViewController.swift | 2 | 5748 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Storage
private let LastUsedShareDestinationsKey = "LastUsedShareDestinations"
@objc(InitialViewController)
class InitialViewController: UIViewController, ShareControllerDelegate {
var shareDialogController: ShareDialogController!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(white: 0.0, alpha: 0.66) // TODO: Is the correct color documented somewhere?
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
ExtensionUtils.extractSharedItemFromExtensionContext(self.extensionContext, completionHandler: { (item, error) -> Void in
if let item = item, error == nil {
DispatchQueue.main.async {
guard item.isShareable else {
let alert = UIAlertController(title: Strings.SendToErrorTitle, message: Strings.SendToErrorMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Strings.SendToErrorOKButton, style: .default) { _ in self.finish() })
self.present(alert, animated: true, completion: nil)
return
}
self.presentShareDialog(item)
}
} else {
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
})
}
//
func shareControllerDidCancel(_ shareController: ShareDialogController) {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.shareDialogController.view.alpha = 0.0
}, completion: { (Bool) -> Void in
self.dismissShareDialog()
self.finish()
})
}
func finish() {
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
func shareController(_ shareController: ShareDialogController, didShareItem item: ShareItem, toDestinations destinations: NSSet) {
setLastUsedShareDestinations(destinations)
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.shareDialogController.view.alpha = 0.0
}, completion: { (Bool) -> Void in
self.dismissShareDialog()
let profile = BrowserProfile(localName: "profile")
if destinations.contains(ShareDestinationReadingList) {
profile.readingList?.createRecordWithURL(item.url, title: item.title ?? "", addedBy: UIDevice.current.name)
}
if destinations.contains(ShareDestinationBookmarks) {
_ = profile.bookmarks.shareItem(item).value // Blocks until database has settled
}
profile.shutdown()
self.finish()
})
}
//
// TODO: use Set.
func getLastUsedShareDestinations() -> NSSet {
if let destinations = UserDefaults.standard.object(forKey: LastUsedShareDestinationsKey) as? NSArray {
return NSSet(array: destinations as [AnyObject])
}
return NSSet(object: ShareDestinationBookmarks)
}
func setLastUsedShareDestinations(_ destinations: NSSet) {
UserDefaults.standard.set(destinations.allObjects, forKey: LastUsedShareDestinationsKey)
UserDefaults.standard.synchronize()
}
func presentShareDialog(_ item: ShareItem) {
shareDialogController = ShareDialogController()
shareDialogController.delegate = self
shareDialogController.item = item
shareDialogController.initialShareDestinations = getLastUsedShareDestinations()
self.addChildViewController(shareDialogController)
shareDialogController.view.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(shareDialogController.view)
shareDialogController.didMove(toParentViewController: self)
// Setup constraints for the dialog. We keep the dialog centered with 16 points of padding on both
// sides. The dialog grows to max 380 points wide so that it does not look too big on landscape or
// iPad devices.
let views: NSDictionary = ["dialog": shareDialogController.view]
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(16@751)-[dialog(<=380@1000)]-(16@751)-|",
options: [], metrics: nil, views: (views as? [String: AnyObject])!))
let cx = NSLayoutConstraint(item: shareDialogController.view, attribute: .centerX,
relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0)
cx.priority = 1000 // TODO: Why does UILayoutPriorityRequired give a linker error? SDK Bug?
view.addConstraint(cx)
view.addConstraint(NSLayoutConstraint(item: shareDialogController.view, attribute: .centerY,
relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1.0, constant: 0))
// Fade the dialog in
shareDialogController.view.alpha = 0.0
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.shareDialogController.view.alpha = 1.0
}, completion: nil)
}
func dismissShareDialog() {
shareDialogController.willMove(toParentViewController: nil)
shareDialogController.view.removeFromSuperview()
shareDialogController.removeFromParentViewController()
}
}
| mpl-2.0 | 4f74cb80044c945759f019e771269a74 | 41.264706 | 147 | 0.650835 | 5.292818 | false | false | false | false |
Antidote-for-Tox/Antidote | Antidote/KeychainManager.swift | 1 | 5876 | // 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
private struct Constants {
static let ActiveAccountDataService = "me.dvor.Antidote.KeychainManager.ActiveAccountDataService"
static let toxPasswordForActiveAccount = "toxPasswordForActiveAccount"
static let failedPinAttemptsNumber = "failedPinAttemptsNumber"
}
class KeychainManager {
/// Tox password used to encrypt/decrypt active account.
var toxPasswordForActiveAccount: String? {
get {
return getStringForKey(Constants.toxPasswordForActiveAccount)
}
set {
setString(newValue, forKey: Constants.toxPasswordForActiveAccount)
}
}
/// Number of failed enters of pin by user.
var failedPinAttemptsNumber: Int? {
get {
return getIntForKey(Constants.failedPinAttemptsNumber)
}
set {
setInt(newValue, forKey: Constants.failedPinAttemptsNumber)
}
}
/// Removes all data related to active account.
func deleteActiveAccountData() {
toxPasswordForActiveAccount = nil
failedPinAttemptsNumber = nil
}
}
private extension KeychainManager {
func getIntForKey(_ key: String) -> Int? {
guard let data = getDataForKey(key) else {
return nil
}
guard let number = NSKeyedUnarchiver.unarchiveObject(with: data) as? NSNumber else {
return nil
}
return number.intValue
}
func setInt(_ value: Int?, forKey key: String) {
guard let value = value else {
setData(nil, forKey: key)
return
}
let number = NSNumber(value: value)
let data = NSKeyedArchiver.archivedData(withRootObject: number)
setData(data, forKey: key)
}
func getStringForKey(_ key: String) -> String? {
guard let data = getDataForKey(key) else {
return nil
}
return NSString(data: data, encoding: String.Encoding.utf8.rawValue) as String?
}
func setString(_ string: String?, forKey key: String) {
let data = string?.data(using: String.Encoding.utf8)
setData(data, forKey: key)
}
func getBoolForKey(_ key: String) -> Bool? {
guard let data = getDataForKey(key) else {
return nil
}
return (data as NSData).bytes.bindMemory(to: Int.self, capacity: data.count).pointee == 1
}
func setBool(_ value: Bool?, forKey key: String) {
var data: Data? = nil
if let value = value {
var bytes = value ? 1 : 0
withUnsafePointer(to: &bytes) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
data = Data(bytes: $0, count: MemoryLayout<Int>.size)
}
}
}
setData(data, forKey: key)
}
func getDataForKey(_ key: String) -> Data? {
var query = genericQueryWithKey(key)
query[kSecMatchLimit as String] = kSecMatchLimitOne
query[kSecReturnData as String] = kCFBooleanTrue
var queryResult: AnyObject?
let status = withUnsafeMutablePointer(to: &queryResult) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
if status == errSecItemNotFound {
return nil
}
guard status == noErr else {
log("Error when getting keychain data for key \(key), status \(status)")
return nil
}
guard let data = queryResult as? Data else {
log("Unexpected data for key \(key)")
return nil
}
return data
}
func setData(_ newData: Data?, forKey key: String) {
let oldData = getDataForKey(key)
switch (oldData, newData) {
case (.some(_), .some(let data)):
// Update
let query = genericQueryWithKey(key)
var attributesToUpdate = [String : AnyObject]()
attributesToUpdate[kSecValueData as String] = data as AnyObject?
let status = SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary)
guard status == noErr else {
log("Error when updating keychain data for key \(key), status \(status)")
return
}
case (.some(_), .none):
// Delete
let query = genericQueryWithKey(key)
let status = SecItemDelete(query as CFDictionary)
guard status == noErr else {
log("Error when updating keychain data for key \(key), status \(status)")
return
}
case (.none, .some(let data)):
// Add
var query = genericQueryWithKey(key)
query[kSecValueData as String] = data as AnyObject?
let status = SecItemAdd(query as CFDictionary, nil)
guard status == noErr else {
log("Error when setting keychain data for key \(key), status \(status)")
return
}
case (.none, .none):
// Nothing to do here, no changes
break
}
}
func genericQueryWithKey(_ key: String) -> [String : AnyObject] {
var query = [String : AnyObject]()
query[kSecClass as String] = kSecClassGenericPassword
query[kSecAttrService as String] = Constants.ActiveAccountDataService as AnyObject?
query[kSecAttrAccount as String] = key as AnyObject?
query[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
return query
}
}
| mpl-2.0 | fb1345cf1aa3c5acd6c706625485bab0 | 31.285714 | 101 | 0.58322 | 4.992353 | false | false | false | false |
wscqs/FMDemo- | FMDemo/Classes/Utils/Extension/String+Extension.swift | 1 | 4498 | //
// String+Extension.swift
// QSBaoKan
//
// Created by mba on 16/6/7.
// Copyright ยฉ 2016ๅนด cqs. All rights reserved.
//
import UIKit
extension String{
// MARK: ็ผๅญ็ฎๅฝ
/**
ๅฐๅฝๅๅญ็ฌฆไธฒๆผๆฅๅฐcache็ฎๅฝๅ้ข
*/
func cacheDir() -> String{
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString
return path.appendingPathComponent((self as NSString).lastPathComponent)
}
/**
ๅฐๅฝๅๅญ็ฌฆไธฒๆผๆฅๅฐdoc็ฎๅฝๅ้ข
*/
func docDir() -> String
{
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString
return path.appendingPathComponent((self as NSString).lastPathComponent)
}
/**
ๅฐๅฝๅๅญ็ฌฆไธฒๆผๆฅๅฐdoc็ฎๅฝๅ้ข
*/
func docRecordDir() -> String
{
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString
let recordPath = path.appendingPathComponent("record")
if !FileManager.default.fileExists(atPath: recordPath) {
do{
try FileManager.default.createDirectory(atPath: recordPath, withIntermediateDirectories: false, attributes: nil)
}catch {
}
}
return (recordPath as NSString).appendingPathComponent((self as NSString).lastPathComponent)
}
/**
ๅฐๅฝๅๅญ็ฌฆไธฒๆผๆฅๅฐdoc็ฎๅฝๅ้ข
*/
func docSaveRecordDir() -> String {
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString
let recordPath = path.appendingPathComponent("saveRecord")
if !FileManager.default.fileExists(atPath: recordPath) {
do{
try FileManager.default.createDirectory(atPath: recordPath, withIntermediateDirectories: false, attributes: nil)
}catch {
}
}
return (recordPath as NSString).appendingPathComponent((self as NSString).lastPathComponent)
}
// MARK: ๆถ้ดๅค็
/**
ๆถ้ดๆณ่ฝฌไธบๆถ้ด
- returns: ๆถ้ดๅญ็ฌฆไธฒ
*/
func timeStampToString() -> String
{
let string = NSString(string: self)
let timeSta: TimeInterval = string.doubleValue
let dfmatter = DateFormatter()
dfmatter.dateFormat = "yyyyๅนดMMๆddๆฅ"
let date = Date(timeIntervalSince1970: timeSta)
return dfmatter.string(from: date)
}
/**
ๆถ้ด่ฝฌไธบๆถ้ดๆณ
- returns: ๆถ้ดๆณๅญ็ฌฆไธฒ
*/
func stringToTimeStamp()->String
{
let dfmatter = DateFormatter()
dfmatter.dateFormat = "yyyyๅนดMMๆddๆฅ"
let date = dfmatter.date(from: self)
let dateStamp: TimeInterval = date!.timeIntervalSince1970
let dateSt:Int = Int(dateStamp)
return String(dateSt)
}
// MARK: ๅคๆญ
/**
ๅคๆญๆๆบๅทๆฏๅฆๅๆณ
- returns: bool
*/
func isValidMobile() -> Bool {
// ๅคๆญๆฏๅฆๆฏๆๆบๅท
let patternString = "^1[3|4|5|7|8][0-9]\\d{8}$"
let predicate = NSPredicate(format: "SELF MATCHES %@", patternString)
return predicate.evaluate(with: self)
}
/**
ๅคๆญๅฏ็ ๆฏๅฆๅๆณ
- returns: bool
*/
func isValidPasswod() -> Bool {
// ้ช่ฏๅฏ็ ๆฏ 6 - 16 ไฝๅญๆฏๆๆฐๅญ
let patternString = "^[0-9A-Za-z]{6,16}$"
let predicate = NSPredicate(format: "SELF MATCHES %@", patternString)
return predicate.evaluate(with: self)
}
func md5() ->String{
let str = self.cString(using: String.Encoding.utf8)
let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
CC_MD5(str!, strLen, result)
let hash = NSMutableString()
for i in 0 ..< digestLen {
hash.appendFormat("%02x", result[i])
}
result.deinitialize()
return String(format: hash as String)
}
}
| apache-2.0 | 0bc79aeffbf81ee23f68e427c0ce8eac | 31.098485 | 179 | 0.632051 | 4.650933 | false | false | false | false |
giangbvnbgit128/AnViet | AnViet/Class/ViewControllers/HomeViewController/Cell/AVNewFeedFiveImageTableViewCell.swift | 1 | 5726 | //
// AVNewFeedFiveImageTableViewCell.swift
// AnViet
//
// Created by Bui Giang on 5/30/17.
// Copyright ยฉ 2017 Bui Giang. All rights reserved.
//
import UIKit
import SDWebImage
import SKPhotoBrowser
class AVNewFeedFiveImageTableViewCell: AVBaseNewFeedTableViewCell {
@IBOutlet weak var imgAvarta: UIImageView!
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var lblDetail: UILabel!
@IBOutlet weak var lblDescription: UILabel!
@IBOutlet weak var img1: UIImageView!
@IBOutlet weak var img2: UIImageView!
@IBOutlet weak var img3: UIImageView!
@IBOutlet weak var img4: UIImageView!
@IBOutlet weak var img5: UIImageView!
@IBOutlet weak var btnShare: UIButton!
@IBOutlet weak var btnLike: UIButton!
var images = [SKPhoto]()
var supperViewVC:UIViewController?
override func awakeFromNib() {
super.awakeFromNib()
let tapRecognizer = UITapGestureRecognizer( target: self, action: #selector(self.tapImg1))
self.img1.addGestureRecognizer(tapRecognizer)
let tapRecognizer2 = UITapGestureRecognizer( target: self, action: #selector(self.tapImg2))
self.img2.addGestureRecognizer(tapRecognizer2)
let tapRecognizer3 = UITapGestureRecognizer( target: self, action: #selector(self.tapImg3))
self.img3.addGestureRecognizer(tapRecognizer3)
let tapRecognizer4 = UITapGestureRecognizer( target: self, action: #selector(self.tapImg4))
self.img4.addGestureRecognizer(tapRecognizer4)
let tapRecognizer5 = UITapGestureRecognizer( target: self, action: #selector(self.tapImg5))
self.img5.addGestureRecognizer(tapRecognizer5)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func tapImg1() {
let browser = SKPhotoBrowser(photos: images)
browser.initializePageIndex(0)
self.supperViewVC?.present(browser, animated: true, completion: {})
}
func tapImg2() {
let browser = SKPhotoBrowser(photos: images)
browser.initializePageIndex(1)
self.supperViewVC?.present(browser, animated: true, completion: {})
}
func tapImg3() {
let browser = SKPhotoBrowser(photos: images)
browser.initializePageIndex(2)
self.supperViewVC?.present(browser, animated: true, completion: {})
}
func tapImg4() {
let browser = SKPhotoBrowser(photos: images)
browser.initializePageIndex(3)
self.supperViewVC?.present(browser, animated: true, completion: {})
}
func tapImg5() {
let browser = SKPhotoBrowser(photos: images)
browser.initializePageIndex(4)
self.supperViewVC?.present(browser, animated: true, completion: {})
}
override func configCell(data: DataForItem, host: String,vc:UIViewController) {
self.supperViewVC = vc
self.images.removeAll()
self.lblTitle.text = data.post.title
self.lblDetail.text = data.post.createdDate
self.lblDescription.text = data.post.content
self.btnLike.setTitle(data.post.userLike, for: .normal)
self.imgAvarta.sd_setImage(with: URL(string: host + data.user.avartar), placeholderImage: UIImage(named: "icon_avatar.png"))
self.img1.sd_setImage(with: URL(string: host + data.post.image[0].urlImage), placeholderImage: UIImage(named: "no_image.png"), options: []) { (someImage, someError, type, urlImage) in
var photo:SKPhoto?
if someImage != nil {
photo = SKPhoto.photoWithImage(someImage!)
} else {
photo = SKPhoto.photoWithImage(UIImage(named: "no_image.png")!)
}
self.images.append(photo!)
}
self.img2.sd_setImage(with: URL(string: host + data.post.image[1].urlImage), placeholderImage: UIImage(named: "no_image.png"), options: []) { (someImage, someError, type, urlImage) in
var photo:SKPhoto?
if someImage != nil {
photo = SKPhoto.photoWithImage(someImage!)
} else {
photo = SKPhoto.photoWithImage(UIImage(named: "no_image.png")!)
}
self.images.append(photo!)
}
self.img3.sd_setImage(with: URL(string: host + data.post.image[2].urlImage), placeholderImage: UIImage(named: "no_image.png"), options: []) { (someImage, someError, type, urlImage) in
var photo:SKPhoto?
if someImage != nil {
photo = SKPhoto.photoWithImage(someImage!)
} else {
photo = SKPhoto.photoWithImage(UIImage(named: "no_image.png")!)
}
self.images.append(photo!)
}
self.img4.sd_setImage(with: URL(string: host + data.post.image[3].urlImage), placeholderImage: UIImage(named: "no_image.png"), options: []) { (someImage, someError, type, urlImage) in
var photo:SKPhoto?
if someImage != nil {
photo = SKPhoto.photoWithImage(someImage!)
} else {
photo = SKPhoto.photoWithImage(UIImage(named: "no_image.png")!)
}
self.images.append(photo!)
}
self.img5.sd_setImage(with: URL(string: host + data.post.image[4].urlImage), placeholderImage: UIImage(named: "no_image.png"), options: []) { (someImage, someError, type, urlImage) in
var photo:SKPhoto?
if someImage != nil {
photo = SKPhoto.photoWithImage(someImage!)
} else {
photo = SKPhoto.photoWithImage(UIImage(named: "no_image.png")!)
}
self.images.append(photo!)
}
}
}
| apache-2.0 | c56667a4ba4ffa097d38003118622576 | 42.045113 | 191 | 0.635459 | 4.172741 | false | false | false | false |
Alex-ZHOU/XYQSwift | XYQSwiftTests/Learn-from-Imooc/Play-with-Swift-2/03-Operators/03-Ternary-Operator.playground/Contents.swift | 1 | 567 | //
// 3-3 Swift 2.0่ฟ็ฎ็ฌฆไนไธ็ฎ่ฟ็ฎ็ฌฆไธๅ้ๅๅงๅ
// 03-Ternary-Operator.playground
//
// Created by AlexZHOU on 21/05/2017.
// Copyright ยฉ 2016ๅนด AlexZHOU. All rights reserved.
//
import UIKit
var str = "03-Ternary-Operator"
print(str)
var battery = 21
var batteryColor:UIColor
if battery >= 20 {
batteryColor = UIColor.green
}else{
batteryColor = UIColor.red
}
batteryColor
let batteryColor2 = battery <= 20 ? UIColor.red : UIColor.green
batteryColor2
var batteryColor3 = battery >= 20 ? UIColor.green : UIColor.red
batteryColor3
| apache-2.0 | a1a1be97835b83e9229a339af74c32a4 | 18.071429 | 63 | 0.722846 | 3.178571 | false | false | false | false |
wibosco/FetchedResultsController | FetchedResultsControllerTests/TableView/TestTableViewFetchedResultsController.swift | 1 | 1376 | //
// TableViewFetchedResultsControllerDelegate.swift
// FetchedResultsController
//
// Created by William Boles on 04/04/2016.
// Copyright ยฉ 2016 Boles. All rights reserved.
//
import UIKit
import XCTest
class TestTableViewFetchedResultsController: NSObject, TableViewFetchedResultsControllerDelegate {
//MARK: Accessors
var didUpdateContentDelegateMethodCalled: Bool = false
var didChangeIndexPathsDelegateMethodCalled: Bool = false
var didUpdateIndexPathDelegateMethodCalled: Bool = false
var didChangeIndexPathsInsertedArray: Array<NSIndexPath>?
var didChangeIndexPathsUpdatedArray: Array<NSIndexPath>?
var didUpdateIndexPathIndexPath: NSIndexPath?
//MARK: TableViewFetchedResultsControllerDelegate
func didUpdateContent() {
self.didUpdateContentDelegateMethodCalled = true
}
func didChangeIndexPaths(insertedIndexPaths: Array<NSIndexPath>, updatedIndexPaths: Array<NSIndexPath>) {
self.didChangeIndexPathsInsertedArray = insertedIndexPaths
self.didChangeIndexPathsUpdatedArray = updatedIndexPaths
self.didChangeIndexPathsDelegateMethodCalled = true
}
func didUpdateIndexPath(indexPath: NSIndexPath) {
self.didUpdateIndexPathIndexPath = indexPath
self.didUpdateIndexPathDelegateMethodCalled = true
}
}
| mit | 528ae89132ff0ffbb6ea5a2fc5cd0b45 | 30.976744 | 109 | 0.752 | 5.826271 | false | false | false | false |
vector-im/riot-ios | Riot/Modules/KeyBackup/ManualExport/EncryptionKeysExportPresenter.swift | 1 | 5145 | /*
Copyright 2019 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 Foundation
final class EncryptionKeysExportPresenter: NSObject {
// MARK: - Constants
private enum Constants {
static let keyExportFileName = "riot-keys.txt"
}
// MARK: - Properties
// MARK: Private
private let session: MXSession
private let activityViewPresenter: ActivityIndicatorPresenterType
private let keyExportFileURL: URL
private weak var presentingViewController: UIViewController?
private weak var sourceView: UIView?
private var encryptionKeysExportView: MXKEncryptionKeysExportView?
private var documentInteractionController: UIDocumentInteractionController?
// MARK: Public
// MARK: - Setup
init(session: MXSession) {
self.session = session
self.activityViewPresenter = ActivityIndicatorPresenter()
self.keyExportFileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(Constants.keyExportFileName)
super.init()
}
deinit {
self.deleteKeyExportFile()
}
// MARK: - Public
func present(from viewController: UIViewController, sourceView: UIView?) {
self.presentingViewController = viewController
self.sourceView = sourceView
let keysExportView: MXKEncryptionKeysExportView = MXKEncryptionKeysExportView(matrixSession: self.session)
// Make sure the file is empty
self.deleteKeyExportFile()
keysExportView.show(in: viewController,
toExportKeysToFile: self.keyExportFileURL,
onLoading: { [weak self] (loading) in
guard let sself = self else {
return
}
if loading {
sself.activityViewPresenter.removeCurrentActivityIndicator(animated: false)
sself.activityViewPresenter.presentActivityIndicator(on: viewController.view, animated: true)
} else {
sself.activityViewPresenter.removeCurrentActivityIndicator(animated: true)
}
}, onComplete: { [weak self] (success) in
guard let sself = self else {
return
}
guard success else {
sself.encryptionKeysExportView = nil
return
}
sself.presentInteractionDocumentController()
})
self.encryptionKeysExportView = keysExportView
}
// MARK: - Private
private func presentInteractionDocumentController() {
let sourceRect: CGRect
guard let presentingView = self.presentingViewController?.view else {
self.encryptionKeysExportView = nil
return
}
if let sourceView = self.sourceView {
sourceRect = sourceView.convert(sourceView.bounds, to: presentingView)
} else {
sourceRect = presentingView.bounds
}
let documentInteractionController = UIDocumentInteractionController(url: self.keyExportFileURL)
documentInteractionController.delegate = self
if documentInteractionController.presentOptionsMenu(from: sourceRect, in: presentingView, animated: true) {
self.documentInteractionController = documentInteractionController
} else {
self.encryptionKeysExportView = nil
self.deleteKeyExportFile()
}
}
@objc private func deleteKeyExportFile() {
let fileManager = FileManager.default
if fileManager.fileExists(atPath: self.keyExportFileURL.path) {
try? fileManager.removeItem(atPath: self.keyExportFileURL.path)
}
}
}
// MARK: - UIDocumentInteractionControllerDelegate
extension EncryptionKeysExportPresenter: UIDocumentInteractionControllerDelegate {
// Note: This method is not called in all cases (see http://stackoverflow.com/a/21867096).
func documentInteractionController(_ controller: UIDocumentInteractionController, didEndSendingToApplication application: String?) {
self.deleteKeyExportFile()
self.documentInteractionController = nil
}
func documentInteractionControllerDidDismissOptionsMenu(_ controller: UIDocumentInteractionController) {
self.encryptionKeysExportView = nil
self.documentInteractionController = nil
}
}
| apache-2.0 | 48cc92fddbf944a813556ad8b94d0a72 | 34 | 136 | 0.648591 | 5.968677 | false | false | false | false |
JaSpa/swift | test/Serialization/serialize_attr.swift | 2 | 2193 | // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-module -parse-as-library -sil-serialize-all -o %t %s
// RUN: llvm-bcanalyzer %t/serialize_attr.swiftmodule | %FileCheck %s -check-prefix=BCANALYZER
// RUN: %target-sil-opt -new-mangling-for-tests -enable-sil-verify-all %t/serialize_attr.swiftmodule | %FileCheck %s
// BCANALYZER-NOT: UnknownCode
// @_semantics
// -----------------------------------------------------------------------------
//CHECK-DAG: @_semantics("crazy") func foo()
@_semantics("crazy") func foo() -> Int { return 5}
// @_specialize
// -----------------------------------------------------------------------------
// These lines should be contiguous.
// CHECK-DAG: @_specialize(exported: false, kind: full, where T == Int, U == Float)
// CHECK-DAG: func specializeThis<T, U>(_ t: T, u: U)
@_specialize(where T == Int, U == Float)
func specializeThis<T, U>(_ t: T, u: U) {}
protocol PP {
associatedtype PElt
}
protocol QQ {
associatedtype QElt
}
struct RR : PP {
typealias PElt = Float
}
struct SS : QQ {
typealias QElt = Int
}
struct GG<T : PP> {}
// These three lines should be contiguous, however, there is no way to
// sequence FileCheck directives while using CHECK-DAG as the outer
// label, and the declaration order is unpredictable.
//
// CHECK-DAG: class CC<T> where T : PP {
// CHECK-DAG: @_specialize(exported: false, kind: full, where T == RR, U == SS)
// CHECK-DAG: @inline(never) func foo<U>(_ u: U, g: GG<T>) -> (U, GG<T>) where U : QQ
class CC<T : PP> {
@inline(never)
@_specialize(where T==RR, U==SS)
func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>) {
return (u, g)
}
}
// CHECK-DAG: sil hidden [fragile] [_specialize exported: false, kind: full, where T == Int, U == Float] @_T014serialize_attr14specializeThisyx_q_1utr0_lF : $@convention(thin) <T, U> (@in T, @in U) -> () {
// CHECK-DAG: sil hidden [fragile] [noinline] [_specialize exported: false, kind: full, where T == RR, U == SS] @_T014serialize_attr2CCC3fooqd___AA2GGVyxGtqd___AFyxG1gtAA2QQRd__lF : $@convention(method) <T where T : PP><U where U : QQ> (@in U, GG<T>, @guaranteed CC<T>) -> (@out U, GG<T>) {
| apache-2.0 | c877993876a51869157fbc6cbcf8cf5e | 37.473684 | 290 | 0.601003 | 3.150862 | false | false | false | false |
wonderkiln/WKAwesomeMenu | WKAwesomeMenu/WKAwesomeMenuOptions.swift | 2 | 818 | //
// WKAwesomeMenuOptions.swift
// WKAwesomeMenu
//
// Created by Adrian Mateoaea on 30.01.2016.
// Copyright ยฉ 2016 Wonderkiln. All rights reserved.
//
import UIKit
public struct WKAwesomeMenuOptions {
public static func defaultOptions() -> WKAwesomeMenuOptions {
return WKAwesomeMenuOptions()
}
public var backgroundImage: UIImage?
public var cornerRadius: CGFloat = 5
public var shadowColor: UIColor = UIColor(red:0.56, green:0.77, blue:0.84, alpha:1)
public var shadowOffset: CGPoint = CGPoint(x: -10, y: 0)
public var shadowScale: CGFloat = 0.94
public var rootScale: CGFloat = 0.8
public var menuWidth: CGFloat = 250
public var menuParallax: CGFloat = -40
public var menuGripWidth: CGFloat = 50
}
| mit | 02ab97afc7c7c1d19bbedde1771c2709 | 22.342857 | 87 | 0.657283 | 4.147208 | false | false | false | false |
alvinvarghese/PERK-Swift-Demo | dummye/AppsaholicHelper.swift | 1 | 2661 | //
// AppsaholicHelper.swift
// dummye
//
// Created by Alvin Varghese on 16/12/15.
// Copyright ยฉ 2015 I Dream Code. All rights reserved.
//
import Foundation
import UIKit
class AppsaholicHelper {
//MARK: Details - Appsaholic
private enum CommonDetails : String
{
case AdClosingNotification = "SDKAdCloseNotification"
}
//MARK: Shared Instance
class var sharedInstance : AppsaholicHelper {
struct Static {
static var sharedInstance: AppsaholicHelper?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.sharedInstance = AppsaholicHelper()
}
return Static.sharedInstance!
}
//MARK: Local Variables
let appsaholicSDKInstance : AppsaholicSDK = AppsaholicSDK()
//MARK: Initialize AppsaholicSDKHelper
func initializeSDK (API_KEY : String, completion : (success : Bool, message : String) -> Void!) {
self.appsaholicSDKInstance.startSession(API_KEY) { success, value in
completion(success: success, message: value)
}
}
//MARK: Pointing View Controller to Appsaholic SDK
func pointingThisViewController(target : UIViewController)
{
self.appsaholicSDKInstance.appsaholic_rootViewController = target
}
//MARK: Track Events
func trackEvents(target : UIViewController, eventID : String, subID : String, notificationType : Bool, completion : (success : Bool) -> Void!)
{
// Use Your Own Notification Design - By passing "notificationType" true
self.appsaholicSDKInstance.trackEvent(eventID, withSubID: subID, notificationType: notificationType, withController: target) { success, value , number in
completion(success: success)
}
}
//MARK: Adding PERK Portal
func showPERKPortalHere()
{
self.appsaholicSDKInstance.showPortal()
}
//MARK: Claim Points Custom View
func claimPointsCustomView(target : UIViewController)
{
self.appsaholicSDKInstance.claimPoints(target)
}
//MARK: Advance Notification for Advertisement closing
func addObserverForAdvertisementClosing(target : UIViewController, methodName : String)
{
dispatch_async(dispatch_get_main_queue()) {
NSNotificationCenter.defaultCenter().addObserver(target, selector: Selector(methodName), name: CommonDetails.AdClosingNotification.rawValue, object: nil)
}
}
}
| mit | f3ed816ff1fdb3ffe5014b7021d9dbed | 24.825243 | 165 | 0.632707 | 4.642234 | false | false | false | false |
djschilling/SOPA-iOS | SOPA/model/game/LevelInfo.swift | 1 | 1192 | //
// LevelInfo.swift
// SOPA
//
// Created by Raphael Schilling on 31.10.17.
// Copyright ยฉ 2017 David Schilling. All rights reserved.
//
import Foundation
class LevelInfo {
let levelId: Int
var locked: Bool
var fewestMoves: Int
var stars: Int
var time: Double
init(levelId: Int, locked: Bool, fewestMoves: Int, stars: Int, time: Double) {
self.levelId = levelId
self.locked = locked
self.fewestMoves = fewestMoves
self.stars = stars
self.time = time
}
init(levelInfo: LevelInfo) {
self.levelId = levelInfo.levelId
self.locked = levelInfo.locked
self.fewestMoves = levelInfo.fewestMoves
self.stars = levelInfo.stars
self.time = levelInfo.time
}
init(levelInfoMO: LevelInfoMO) {
self.levelId = Int(levelInfoMO.id)
self.fewestMoves = Int(levelInfoMO.fewest_moves)
self.locked = levelInfoMO.locked
self.stars = Int(levelInfoMO.stars)
self.time = Double(levelInfoMO.time)
}
public func description() -> String {
return "\(levelId);\(fewestMoves);\(locked);\(stars);\(time))"
}
}
| apache-2.0 | 1827c9e7c189293bf3399b14a0bb9054 | 24.891304 | 82 | 0.61293 | 3.854369 | false | false | false | false |
mchoe/Resplendent | ResplendentiOS/UIColor+Resplendent.swift | 1 | 2821 | //
// UIColor+Resplendent.swift
// Resplendent
//
// Copyright (c) 2015 Michael Choe
// http://www.straussmade.com/
// http://www.twitter.com/_mchoe
// http://www.github.com/mchoe
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
extension UIColor {
public convenience init(r: Int, g: Int, b: Int, a: CGFloat? = nil) {
let alphaValue: CGFloat
if let alpha = a {
alphaValue = alpha
} else {
alphaValue = 1.0
}
self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alphaValue)
}
public convenience init(hexString: String) {
guard let hexColor = ResplendentHexColor(hexString: hexString) else {
self.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)
return
}
self.init(r: Int(hexColor.components.red), g: Int(hexColor.components.green), b: Int(hexColor.components.blue))
}
}
extension UIColor: CanProvideResplendentColor {
var asResplendentColor: ResplendentColor {
get {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 0.0
self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return ResplendentColor(rCGFloat: red, gCGFloat: green, bCGFloat: blue)
}
}
}
extension UIColor {
public class func randomColor() -> UIColor {
let randomResplendentColor = ResplendentColor.randomColor()
return UIColor(r: randomResplendentColor.red, g: randomResplendentColor.green, b: randomResplendentColor.blue)
}
}
| mit | 9c3138d0c374b3756b551931c7863471 | 30.696629 | 119 | 0.642325 | 3.990099 | false | false | false | false |
JustinGuedes/SwiftFeedReader | Example/Tests/RSSSourceTests.swift | 1 | 1620 | //
// RSSSourceTests.swift
// SwiftFeedReader_Tests
//
// Created by Justin Guedes on 2017/08/24.
// Copyright ยฉ 2017 CocoaPods. All rights reserved.
//
import XCTest
@testable import SwiftFeedReader
class RSSSourceTests: XCTestCase, XCTestCaseParameter {
let parameter = RSS.Source.parameter
let sourceDictionary: [String: Any] = ["source": "Example Source",
"url": "http://www.google.com"]
func testShouldThrowParameterNotFoundErrorWhenParsingEmptyDictionary() {
let emptyDict: [String: Any] = [:]
XCTAssertParameterNotFound(inDictionary: emptyDict)
}
func testShouldThrowParameterNotFoundErrorWhenParsingDictionaryWithoutSource() {
let key = "source"
var dictionaryWithoutSource = sourceDictionary
dictionaryWithoutSource.removeValue(forKey: key)
XCTAssertParameterNotFound(inDictionary: dictionaryWithoutSource)
}
func testShouldThrowParameterNotFoundErrorWhenParsingDictionaryWithoutUrl() {
let key = "url"
var dictionaryWithoutUrl = sourceDictionary
dictionaryWithoutUrl.removeValue(forKey: key)
XCTAssertParameterNotFound(inDictionary: dictionaryWithoutUrl)
}
func testShouldParseDictionaryIntoSourceObject() {
let expectedSource = RSS.Source(name: sourceDictionary["source"] as! String,
url: URL(string: sourceDictionary["url"] as! String)!)
XCTAssertEqualParameter(expectedSource, withValue: sourceDictionary)
}
}
| mit | 31017c338253e73c4a1bbf2cb699344a | 32.729167 | 94 | 0.670784 | 5.256494 | false | true | false | false |
ivanonchi/xkcd-mvvm | Carthage/Checkouts/RxAlamofire/Sources/RxAlamofire.swift | 1 | 32376 | //
// RxAlamofire.swift
// RxAlamofire
//
// Created by Junior B. (@bontojr) on 23/08/15.
// Developed with the kind help of Krunoslav Zaher (@KrunoslavZaher)
//
// Updated by Ivan ฤikiฤ for the latest version of Alamofire(3) and RxSwift(2) on 21/10/15
// Updated by Krunoslav Zaher to better wrap Alamofire (3) on 1/10/15
//
// Copyright ยฉ 2015 Bonto.ch. All rights reserved.
//
import Foundation
import Alamofire
import RxSwift
/// Default instance of unknown error
public let RxAlamofireUnknownError = NSError(domain: "RxAlamofireDomain", code: -1, userInfo: nil)
// MARK: Convenience functions
/**
Creates a NSMutableURLRequest using all necessary parameters.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- returns: An instance of `NSMutableURLRequest`
*/
public func urlRequest(_ method: Alamofire.HTTPMethod,
_ url: URLConvertible,
parameters: [String: Any]? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: [String: String]? = nil)
throws -> Foundation.URLRequest
{
var mutableURLRequest = Foundation.URLRequest(url: try url.asURL())
mutableURLRequest.httpMethod = method.rawValue
if let headers = headers {
for (headerField, headerValue) in headers {
mutableURLRequest.setValue(headerValue, forHTTPHeaderField: headerField)
}
}
if let parameters = parameters {
mutableURLRequest = try encoding.encode(mutableURLRequest, with: parameters)
}
return mutableURLRequest
}
// MARK: Request
/**
Creates an observable of the generated `Request`.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- returns: An observable of a the `Request`
*/
public func request(_ method: Alamofire.HTTPMethod,
_ url: URLConvertible,
parameters: [String: Any]? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: [String: String]? = nil)
-> Observable<DataRequest>
{
return SessionManager.default.rx.request(
method,
url,
parameters: parameters,
encoding: encoding,
headers: headers
)
}
// MARK: data
/**
Creates an observable of the `(NSHTTPURLResponse, NSData)` instance.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- returns: An observable of a tuple containing `(NSHTTPURLResponse, NSData)`
*/
public func requestData(_ method: Alamofire.HTTPMethod,
_ url: URLConvertible,
parameters: [String: Any]? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: [String: String]? = nil)
-> Observable<(HTTPURLResponse, Data)>
{
return SessionManager.default.rx.responseData(
method,
url,
parameters: parameters,
encoding: encoding,
headers: headers
)
}
/**
Creates an observable of the returned data.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- returns: An observable of `NSData`
*/
public func data(_ method: Alamofire.HTTPMethod,
_ url: URLConvertible,
parameters: [String: Any]? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: [String: String]? = nil)
-> Observable<Data>
{
return SessionManager.default.rx.data(
method,
url,
parameters: parameters,
encoding: encoding,
headers: headers
)
}
// MARK: string
/**
Creates an observable of the returned decoded string and response.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- returns: An observable of the tuple `(NSHTTPURLResponse, String)`
*/
public func requestString(_ method: Alamofire.HTTPMethod,
_ url: URLConvertible,
parameters: [String: Any]? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: [String: String]? = nil)
-> Observable<(HTTPURLResponse, String)>
{
return SessionManager.default.rx.responseString(
method,
url,
parameters: parameters,
encoding: encoding,
headers: headers
)
}
/**
Creates an observable of the returned decoded string.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- returns: An observable of `String`
*/
public func string(_ method: Alamofire.HTTPMethod,
_ url: URLConvertible,
parameters: [String: Any]? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: [String: String]? = nil)
-> Observable<String>
{
return SessionManager.default.rx.string(
method,
url,
parameters: parameters,
encoding: encoding,
headers: headers
)
}
// MARK: JSON
/**
Creates an observable of the returned decoded JSON as `AnyObject` and the response.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- returns: An observable of the tuple `(NSHTTPURLResponse, AnyObject)`
*/
public func requestJSON(_ method: Alamofire.HTTPMethod,
_ url: URLConvertible,
parameters: [String: Any]? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: [String: String]? = nil)
-> Observable<(HTTPURLResponse, Any)>
{
return SessionManager.default.rx.responseJSON(
method,
url,
parameters: parameters,
encoding: encoding,
headers: headers
)
}
/**
Creates an observable of the returned decoded JSON.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- returns: An observable of the decoded JSON as `Any`
*/
public func json(_ method: Alamofire.HTTPMethod,
_ url: URLConvertible,
parameters: [String: Any]? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: [String: String]? = nil)
-> Observable<Any>
{
return SessionManager.default.rx.json(
method,
url,
parameters: parameters,
encoding: encoding,
headers: headers
)
}
// MARK: Upload
/**
Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter urlRequest: The request object to start the upload.
- paramenter file: An instance of NSURL holding the information of the local file.
- returns: The observable of `UploadRequest` for the created request.
*/
public func upload(_ file: URL, urlRequest: URLRequestConvertible) -> Observable<UploadRequest> {
return SessionManager.default.rx.upload(file, urlRequest: urlRequest)
}
/**
Returns an observable of a request using the shared manager instance to upload any data to a specified URL.
The request is started immediately.
- parameter urlRequest: The request object to start the upload.
- paramenter data: An instance of NSData holdint the data to upload.
- returns: The observable of `UploadRequest` for the created request.
*/
public func upload(_ data: Data, urlRequest: URLRequestConvertible) -> Observable<UploadRequest> {
return SessionManager.default.rx.upload(data , urlRequest: urlRequest)
}
/**
Returns an observable of a request using the shared manager instance to upload any stream to a specified URL.
The request is started immediately.
- parameter urlRequest: The request object to start the upload.
- paramenter stream: The stream to upload.
- returns: The observable of `Request` for the created upload request.
*/
public func upload(_ stream: InputStream, urlRequest: URLRequestConvertible) -> Observable<UploadRequest> {
return SessionManager.default.rx.upload(stream, urlRequest: urlRequest)
}
// MARK: Download
/**
Creates a download request using the shared manager instance for the specified URL request.
- parameter urlRequest: The URL request.
- parameter destination: The closure used to determine the destination of the downloaded file.
- returns: The observable of `DownloadRequest` for the created download request.
*/
public func download(_ urlRequest: URLRequestConvertible,
to destination: @escaping DownloadRequest.DownloadFileDestination) -> Observable<DownloadRequest> {
return SessionManager.default.rx.download(urlRequest, to: destination)
}
// MARK: Resume Data
/**
Creates a request using the shared manager instance for downloading from the resume data produced from a
previous request cancellation.
- parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask`
when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional
information.
- parameter destination: The closure used to determine the destination of the downloaded file.
- returns: The observable of `Request` for the created download request.
*/
public func download(resumeData: Data,
to destination: @escaping DownloadRequest.DownloadFileDestination) -> Observable<DownloadRequest> {
return SessionManager.default.rx.download(resumeData: resumeData, to: destination)
}
// MARK: Manager - Extension of Manager
extension SessionManager: ReactiveCompatible {
}
protocol RxAlamofireRequest {
func responseWith(completionHandler: @escaping (RxAlamofireResponse) -> Void)
func resume()
func cancel()
}
protocol RxAlamofireResponse {
var error: Error? {get}
}
extension DefaultDataResponse: RxAlamofireResponse {}
extension DefaultDownloadResponse: RxAlamofireResponse {}
extension DataRequest: RxAlamofireRequest {
func responseWith(completionHandler: @escaping (RxAlamofireResponse) -> Void) {
response { (response) in
completionHandler(response)
}
}
}
extension DownloadRequest: RxAlamofireRequest {
func responseWith(completionHandler: @escaping (RxAlamofireResponse) -> Void) {
response { (response) in
completionHandler(response)
}
}
}
extension Reactive where Base: SessionManager {
// MARK: Generic request convenience
/**
Creates an observable of the DataRequest.
- parameter createRequest: A function used to create a `Request` using a `Manager`
- returns: A generic observable of created data request
*/
func request<R: RxAlamofireRequest>(_ createRequest: @escaping (SessionManager) throws -> R) -> Observable<R> {
return Observable.create { observer -> Disposable in
let request: R
do {
request = try createRequest(self.base)
observer.on(.next(request))
request.responseWith(completionHandler: { (response) in
if let error = response.error {
observer.onError(error)
} else {
observer.on(.completed)
}
})
if !self.base.startRequestsImmediately {
request.resume()
}
return Disposables.create {
request.cancel()
}
}
catch let error {
observer.on(.error(error))
return Disposables.create()
}
}
}
/**
Creates an observable of the `Request`.
- parameter method: Alamofire method object
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- returns: An observable of the `Request`
*/
public func request(_ method: Alamofire.HTTPMethod,
_ url: URLConvertible,
parameters: [String: Any]? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: [String: String]? = nil
)
-> Observable<DataRequest>
{
return request { manager in
return manager.request(url,
method: method,
parameters: parameters,
encoding: encoding,
headers: headers)
}
}
/**
Creates an observable of the `Request`.
- parameter URLRequest: An object adopting `URLRequestConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- returns: An observable of the `Request`
*/
public func request(urlRequest: URLRequestConvertible)
-> Observable<DataRequest>
{
return request { manager in
return manager.request(urlRequest)
}
}
// MARK: data
/**
Creates an observable of the data.
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- returns: An observable of the tuple `(NSHTTPURLResponse, NSData)`
*/
public func responseData(_ method: Alamofire.HTTPMethod,
_ url: URLConvertible,
parameters: [String: Any]? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: [String: String]? = nil
)
-> Observable<(HTTPURLResponse, Data)>
{
return request(
method,
url,
parameters: parameters,
encoding: encoding,
headers: headers
).flatMap { $0.rx.responseData() }
}
/**
Creates an observable of the data.
- parameter URLRequest: An object adopting `URLRequestConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- returns: An observable of `NSData`
*/
public func data(_ method: Alamofire.HTTPMethod,
_ url: URLConvertible,
parameters: [String: Any]? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: [String: String]? = nil
)
-> Observable<Data>
{
return request(
method,
url,
parameters: parameters,
encoding: encoding,
headers: headers
).flatMap { $0.rx.data() }
}
// MARK: string
/**
Creates an observable of the tuple `(NSHTTPURLResponse, String)`.
- parameter url: An object adopting `URLRequestConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- returns: An observable of the tuple `(NSHTTPURLResponse, String)`
*/
public func responseString(_ method: Alamofire.HTTPMethod,
_ url: URLConvertible,
parameters: [String: Any]? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: [String: String]? = nil
)
-> Observable<(HTTPURLResponse, String)>
{
return request(
method,
url,
parameters: parameters,
encoding: encoding,
headers: headers
).flatMap { $0.rx.responseString() }
}
/**
Creates an observable of the data encoded as String.
- parameter url: An object adopting `URLConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- returns: An observable of `String`
*/
public func string(_ method: Alamofire.HTTPMethod,
_ url: URLConvertible,
parameters: [String: Any]? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: [String: String]? = nil
)
-> Observable<String>
{
return request(
method,
url,
parameters: parameters,
encoding: encoding,
headers: headers
)
.flatMap { (request) -> Observable<String> in
return request.rx.string()
}
}
// MARK: JSON
/**
Creates an observable of the data decoded from JSON and processed as tuple `(NSHTTPURLResponse, AnyObject)`.
- parameter url: An object adopting `URLRequestConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- returns: An observable of the tuple `(NSHTTPURLResponse, AnyObject)`
*/
public func responseJSON(_ method: Alamofire.HTTPMethod,
_ url: URLConvertible,
parameters: [String: Any]? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: [String: String]? = nil
)
-> Observable<(HTTPURLResponse, Any)>
{
return request(method,
url,
parameters: parameters,
encoding: encoding,
headers: headers
).flatMap { $0.rx.responseJSON() }
}
/**
Creates an observable of the data decoded from JSON and processed as `AnyObject`.
- parameter URLRequest: An object adopting `URLRequestConvertible`
- parameter parameters: A dictionary containing all necessary options
- parameter encoding: The kind of encoding used to process parameters
- parameter header: A dictionary containing all the additional headers
- returns: An observable of `AnyObject`
*/
public func json(_ method: Alamofire.HTTPMethod,
_ url: URLConvertible,
parameters: [String: Any]? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: [String: String]? = nil
)
-> Observable<Any>
{
return request(
method,
url,
parameters: parameters,
encoding: encoding,
headers: headers
).flatMap { $0.rx.json() }
}
// MARK: Upload
/**
Returns an observable of a request using the shared manager instance to upload a specific file to a specified URL.
The request is started immediately.
- parameter urlRequest: The request object to start the upload.
- paramenter file: An instance of NSURL holding the information of the local file.
- returns: The observable of `AnyObject` for the created request.
*/
public func upload(_ file: URL, urlRequest: URLRequestConvertible) -> Observable<UploadRequest> {
return request { manager in
return manager.upload(file, with: urlRequest)
}
}
/**
Returns an observable of a request using the shared manager instance to upload any data to a specified URL.
The request is started immediately.
- parameter urlRequest: The request object to start the upload.
- paramenter data: An instance of Data holdint the data to upload.
- returns: The observable of `UploadRequest` for the created request.
*/
public func upload(_ data: Data, urlRequest: URLRequestConvertible) -> Observable<UploadRequest> {
return request { manager in
return manager.upload(data, with: urlRequest)
}
}
/**
Returns an observable of a request using the shared manager instance to upload any stream to a specified URL.
The request is started immediately.
- parameter urlRequest: The request object to start the upload.
- paramenter stream: The stream to upload.
- returns: The observable of `(NSData?, RxProgress)` for the created upload request.
*/
public func upload(_ stream: InputStream,
urlRequest: URLRequestConvertible) -> Observable<UploadRequest> {
return request { manager in
return manager.upload(stream, with: urlRequest)
}
}
// MARK: Download
/**
Creates a download request using the shared manager instance for the specified URL request.
- parameter urlRequest: The URL request.
- parameter destination: The closure used to determine the destination of the downloaded file.
- returns: The observable of `(NSData?, RxProgress)` for the created download request.
*/
public func download(_ urlRequest: URLRequestConvertible,
to destination: @escaping DownloadRequest.DownloadFileDestination) -> Observable<DownloadRequest> {
return request { manager in
return manager.download(urlRequest, to: destination)
}
}
/**
Creates a request using the shared manager instance for downloading with a resume data produced from a
previous request cancellation.
- parameter resumeData: The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask`
when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional
information.
- parameter destination: The closure used to determine the destination of the downloaded file.
- returns: The observable of `(NSData?, RxProgress)` for the created download request.
*/
public func download(resumeData: Data,
to destination: @escaping DownloadRequest.DownloadFileDestination) -> Observable<DownloadRequest> {
return request { manager in
return manager.download(resumingWith: resumeData, to: destination)
}
}
}
// MARK: Request - Common Response Handlers
extension Request: ReactiveCompatible {
}
extension Reactive where Base: DataRequest {
// MARK: Defaults
/// - returns: A validated request based on the status code
func validateSuccessfulResponse() -> DataRequest {
return self.base.validate(statusCode: 200 ..< 300)
}
/**
Transform a request into an observable of the response and serialized object.
- parameter queue: The dispatch queue to use.
- parameter responseSerializer: The the serializer.
- returns: The observable of `(NSHTTPURLResponse, T.SerializedObject)` for the created download request.
*/
public func responseResult<T: DataResponseSerializerProtocol>(queue: DispatchQueue? = nil,
responseSerializer: T)
-> Observable<(HTTPURLResponse, T.SerializedObject)>
{
return Observable.create { observer in
let dataRequest = self.base
.response(queue: queue, responseSerializer: responseSerializer) { (packedResponse) -> Void in
switch packedResponse.result {
case .success(let result):
if let httpResponse = packedResponse.response {
observer.on(.next(httpResponse, result))
}
else {
observer.on(.error(RxAlamofireUnknownError))
}
observer.on(.completed)
case .failure(let error):
observer.on(.error(error as Error))
}
}
return Disposables.create {
dataRequest.cancel()
}
}
}
/**
Transform a request into an observable of the serialized object.
- parameter queue: The dispatch queue to use.
- parameter responseSerializer: The the serializer.
- returns: The observable of `T.SerializedObject` for the created download request.
*/
public func result<T: DataResponseSerializerProtocol>(
queue: DispatchQueue? = nil,
responseSerializer: T)
-> Observable<T.SerializedObject>
{
return Observable.create { observer in
let dataRequest = self.validateSuccessfulResponse()
.response(queue: queue, responseSerializer: responseSerializer) { (packedResponse) -> Void in
switch packedResponse.result {
case .success(let result):
if let _ = packedResponse.response {
observer.on(.next(result))
}
else {
observer.on(.error(RxAlamofireUnknownError))
}
observer.on(.completed)
case .failure(let error):
observer.on(.error(error as Error))
}
}
return Disposables.create {
dataRequest.cancel()
}
}
}
/**
Returns an `Observable` of NSData for the current request.
- parameter cancelOnDispose: Indicates if the request has to be canceled when the observer is disposed, **default:** `false`
- returns: An instance of `Observable<NSData>`
*/
public func responseData() -> Observable<(HTTPURLResponse, Data)> {
return responseResult(responseSerializer: DataRequest.dataResponseSerializer())
}
public func data() -> Observable<Data> {
return result(responseSerializer: DataRequest.dataResponseSerializer())
}
/**
Returns an `Observable` of a String for the current request
- parameter encoding: Type of the string encoding, **default:** `nil`
- returns: An instance of `Observable<String>`
*/
public func responseString(encoding: String.Encoding? = nil) -> Observable<(HTTPURLResponse, String)> {
return responseResult(responseSerializer: Base.stringResponseSerializer(encoding: encoding))
}
public func string(encoding: String.Encoding? = nil) -> Observable<String> {
return result(responseSerializer: Base.stringResponseSerializer(encoding: encoding))
}
/**
Returns an `Observable` of a serialized JSON for the current request.
- parameter options: Reading options for JSON decoding process, **default:** `.AllowFragments`
- returns: An instance of `Observable<AnyObject>`
*/
public func responseJSON(options: JSONSerialization.ReadingOptions = .allowFragments) -> Observable<(HTTPURLResponse, Any)> {
return responseResult(responseSerializer: Base.jsonResponseSerializer(options: options))
}
/**
Returns an `Observable` of a serialized JSON for the current request.
- parameter options: Reading options for JSON decoding process, **default:** `.AllowFragments`
- returns: An instance of `Observable<AnyObject>`
*/
public func json(options: JSONSerialization.ReadingOptions = .allowFragments) -> Observable<Any> {
return result(responseSerializer: Base.jsonResponseSerializer(options: options))
}
/**
Returns and `Observable` of a serialized property list for the current request.
- parameter options: Property list reading options, **default:** `NSPropertyListReadOptions()`
- returns: An instance of `Observable<AnyData>`
*/
public func responsePropertyList(options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions()) -> Observable<(HTTPURLResponse, Any)> {
return responseResult(responseSerializer: Base.propertyListResponseSerializer(options: options))
}
public func propertyList(options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions()) -> Observable<Any> {
return result(responseSerializer: Base.propertyListResponseSerializer(options: options))
}
// MARK: Request - Upload and download progress
/**
Returns an `Observable` for the current progress status.
Parameters on observed tuple:
1. bytes written so far.
1. total bytes to write.
- returns: An instance of `Observable<RxProgress>`
*/
public func progress() -> Observable<RxProgress> {
return Observable.create { observer in
self.base.downloadProgress { progress in
let rxProgress = RxProgress(bytesWritten: progress.completedUnitCount,
totalBytes: progress.totalUnitCount)
observer.onNext(rxProgress)
if rxProgress.bytesWritten >= rxProgress.totalBytes {
observer.onCompleted()
}
}
return Disposables.create()
}
// warm up a bit :)
.startWith(RxProgress(bytesWritten: 0, totalBytes: 0))
}
}
extension Reactive where Base: DownloadRequest {
/**
Returns an `Observable` for the current progress status.
Parameters on observed tuple:
1. bytes written so far.
1. total bytes to write.
- returns: An instance of `Observable<RxProgress>`
*/
public func progress() -> Observable<RxProgress> {
return Observable.create { observer in
self.base.downloadProgress { progress in
let rxProgress = RxProgress(bytesWritten: progress.completedUnitCount,
totalBytes: progress.totalUnitCount)
observer.onNext(rxProgress)
if rxProgress.bytesWritten >= rxProgress.totalBytes {
observer.onCompleted()
}
}
return Disposables.create()
}
// warm up a bit :)
.startWith(RxProgress(bytesWritten: 0, totalBytes: 0))
}
}
// MARK: RxProgress
public struct RxProgress {
public let bytesWritten: Int64
public let totalBytes: Int64
public init(bytesWritten: Int64, totalBytes: Int64) {
self.bytesWritten = bytesWritten
self.totalBytes = totalBytes
}
}
extension RxProgress {
public var bytesRemaining: Int64 {
return totalBytes - bytesWritten
}
public var completed: Float {
if totalBytes > 0 {
return Float(bytesWritten) / Float(totalBytes)
}
else {
return 0
}
}
}
extension RxProgress: Equatable {}
public func ==(lhs: RxProgress, rhs: RxProgress) -> Bool {
return lhs.bytesWritten == rhs.bytesWritten &&
lhs.totalBytes == rhs.totalBytes
}
| mit | 2ccfa32a462362fa0854d4fb851ab1e9 | 33.734979 | 166 | 0.661199 | 5.213043 | false | false | false | false |
ledwards/ios-twitter | Twit/Tweet.swift | 2 | 1442 | //
// Tweet.swift
// Twit
//
// Created by Lee Edwards on 2/18/16.
// Copyright ยฉ 2016 Lee Edwards. All rights reserved.
//
import UIKit
class Tweet: NSObject {
var id: Int?
var user: User?
var text: String?
var createdAtString: String?
var createdAt: NSDate?
var inReplyToUsername: String?
var retweeted: Bool
var retweetCount: Int
var favorited: Bool
var favoriteCount: Int
init(dictionary: NSDictionary) {
user = User(dictionary: (dictionary["user"] as! NSDictionary))
text = dictionary["text"] as? String
createdAtString = dictionary["created_at"] as? String
id = dictionary["id"] as? Int
inReplyToUsername = dictionary["in_reply_to_screen_name"] as? String
retweeted = dictionary["retweeted"] as? Bool ?? false
favorited = dictionary["favorited"] as? Bool ?? false
retweetCount = dictionary["retweet_count"] as? Int ?? 0
favoriteCount = dictionary["favourites_count"] as? Int ?? 0
let formatter = NSDateFormatter()
formatter.dateFormat = "EEE MMM d HH:mm:ss Z y"
createdAt = formatter.dateFromString(createdAtString!)
}
class func tweetsWithArray(array: [NSDictionary]) -> [Tweet] {
var tweets = [Tweet]()
for dictionary in array {
tweets.append(Tweet(dictionary: dictionary))
}
return tweets
}
}
| mit | 826de0d35c3d0aeff1a810e5bbceacd9 | 29.020833 | 76 | 0.617627 | 4.379939 | false | false | false | false |
LiulietLee/Pick-Color | Pick Color/PixelData.swift | 1 | 2646 | //
// PixelData.swift
// Pick Color
//
// Created by Liuliet.Lee on 23/8/2016.
// Copyright ยฉ 2016 Liuliet.Lee. All rights reserved.
//
import UIKit
class PixelData {
fileprivate var data: UnsafePointer<UInt8>!
fileprivate var context: CGContext!
var image: CGImage? {
didSet {
if let image = image {
context = createBitmapContext(image)
let pixelData = context.data!.assumingMemoryBound(to: UInt8.self)
self.data = UnsafePointer<UInt8>(pixelData)
} else {
self.data = nil
}
}
}
fileprivate func createBitmapContext(_ image: CGImage) -> CGContext {
let width = image.width
let height = image.height
// TODO: Support Display P3
let bitsPerComp = 8 // image.bitsPerComponent
let bitmapBytesPerRow = width * 4 // * (bitsPerComp / 8)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue
let size = CGSize(width: width, height: height)
let context = CGContext(
data: nil, width: width, height: height,
bitsPerComponent: bitsPerComp, bytesPerRow: bitmapBytesPerRow,
space: colorSpace, bitmapInfo: bitmapInfo)!
let rect = CGRect(origin: .zero, size: size)
context.draw(image, in: rect)
return context
}
func getPartOfImage(x: Int, y: Int) -> UIImage? {
guard let image = image else { return nil }
let imageWidth = image.width
let imageHight = image.height
var rect: CGRect { // lazy initialized
return CGRect(x: x - 10, y: y - 10, width: 20, height: 20)
}
guard x >= 0 && x < imageWidth && y >= 0 && y < imageHight
, let imageRef = image.cropping(to: rect)
else { return nil }
return UIImage(cgImage: imageRef)
}
func pixelColorAt(x: Int, y: Int) -> UIColor? {
guard let image = image, let data = data else { return nil }
let imageWidth = image.width
let imageHight = image.height
if x >= 0 && x < imageWidth && y >= 0 && y < imageHight {
let pixelInfo = 4 * (imageWidth * y + x)
let r = CGFloat(data[pixelInfo + 0]) / 255
let g = CGFloat(data[pixelInfo + 1]) / 255
let b = CGFloat(data[pixelInfo + 2]) / 255
let a = CGFloat(data[pixelInfo + 3]) / 255
return UIColor(red: r, green: g, blue: b, alpha: a)
}
return nil
}
}
| mit | 050b99201df551020766e9a9b71b50b2 | 32.910256 | 81 | 0.558034 | 4.393688 | false | false | false | false |
fuzza/SwiftyJanet | Sources/ActionPipe.swift | 1 | 1835 | import Foundation
import RxSwift
public final class ActionPipe <Action: JanetAction> {
public typealias ActionSender<T: JanetAction> = (T) -> Observable<ActionState<T>>
public typealias ActionCancel<T: JanetAction> = (T) -> Void
private let bag: DisposeBag = DisposeBag()
private let defaultScheduler: SchedulerType?
private let actionSender: ActionSender<Action>
private let actionCancel: ActionCancel<Action>
private let statePipe: Observable<ActionState<Action>>
internal init(statePipe: Observable<ActionState<Action>>,
actionSender: @escaping ActionSender<Action>,
actionCancel: @escaping ActionCancel<Action>,
defaultScheduler: SchedulerType? = nil) {
self.statePipe = statePipe
self.actionSender = actionSender
self.actionCancel = actionCancel
self.defaultScheduler = defaultScheduler
}
public func observe() -> Observable<ActionState<Action>> {
return statePipe
}
public func send(_ action: Action, subscribeOn: SchedulerType? = nil) {
var scheduler = defaultScheduler
if let customScheduler = subscribeOn {
scheduler = customScheduler
}
sendDeferred(action: action, subscribeOn:scheduler)
.subscribe()
.disposed(by: bag)
}
public func sendDeferred(_ action: Action) -> Observable<ActionState<Action>> {
return sendDeferred(action: action, subscribeOn:defaultScheduler)
}
public func cancel(_ action: Action) {
actionCancel(action)
}
private func sendDeferred(action: Action,
subscribeOn: SchedulerType?)
-> Observable<ActionState<Action>> {
var observable = actionSender(action)
if let scheduler = subscribeOn {
observable = observable.subscribeOn(scheduler)
}
return observable
}
}
| mit | aaec1f54317cf47ff5dd101bbb5324fc | 31.192982 | 83 | 0.691553 | 4.669211 | false | false | false | false |
kingfree/muse | muse/AppDelegate.swift | 1 | 1262 | //
// AppDelegate.swift
// muse
//
// Created by ๅฒ่กฃๆง on 15/6/23.
// Copyright (c) 2015ๅนด Kingfree. All rights reserved.
//
import Cocoa
import AVFoundation
struct RegexHelper {
let regex: NSRegularExpression?
init(_ pattern: String) {
var error: NSError?
do {
regex = try NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
} catch let error1 as NSError {
error = error1
regex = nil
}
}
func match(input: String) -> Bool {
if let matches = regex?.matchesInString(input, options: [], range: NSMakeRange(0, input.characters.count)) {
return matches.count > 0
} else {
return false
}
}
}
infix operator =~ {
associativity none
precedence 130
}
func =~(lhs: String, rhs: String) -> Bool {
return RegexHelper(rhs).match(lhs)
}
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
@IBAction func openFileDialog(sender: NSMenuItem) {
}
}
| bsd-3-clause | 7ce33207e7eb65f42a6089193898abcf | 21.392857 | 116 | 0.625997 | 4.369338 | false | false | false | false |
qbalsdon/br.cd | brcd/brcd/ViewController/CheckListViewController.swift | 1 | 3950 | //
// CheckListViewController.swift
// brcd
//
// Created by Quintin Balsdon on 2016/01/30.
// Copyright ยฉ 2016 Balsdon. All rights reserved.
//
import UIKit
import CoreData
class CheckListViewController: UIViewController, BarcodeScannerDelegate, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var scanner: UIBarcodeScannerView!
@IBOutlet weak var barcodeList: UITableView!
var dataSource = [BarcodeEntity]()
var scannedCodes:[BarcodeEntity:Int] = [:]
override func viewDidLoad() {
super.viewDidLoad()
scanner.delegate = self
}
override func viewDidLayoutSubviews() {
if scanner != nil && scanner.previewLayer != nil {
scanner.previewLayer.frame = CGRectMake(0, 0, view.frame.width + 5, view.frame.size.height)
}
}
override func viewWillAppear(animated: Bool) {
hasCamera()
dataSource = fetchAllBarcodes((tabBarController as! GroupTabBarViewController).group)
barcodeList.reloadData()
view.bringSubviewToFront(barcodeList)
barcodeList.alpha = 0.5
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Barcode Scanning
func failed() {
}
func barcodeScanned(code: String, type: String) {
print("Scanned: \(code)")
let results = dataSource.filter { elem in elem.code == code && elem.type == type }
if results.count > 0 {
scannedCodes[results[0]] = (scannedCodes[results[0]] ?? 0) + 1
} else {
let group = (tabBarController as! GroupTabBarViewController).group
let nCode = NSEntityDescription.insertNewObjectForEntityForName("BarcodeEntity", inManagedObjectContext: CoreDataStackManager.sharedInstance.managedObjectContext) as? BarcodeEntity
nCode?.setValue(code, forKey: BarcodeEntity.FIELD.CODE.rawValue)
nCode?.setValue(type, forKey: BarcodeEntity.FIELD.TYPE.rawValue)
nCode?.setValue(group, forKey: BarcodeEntity.FIELD.GROUP.rawValue)
nCode?.setValue(1, forKey: BarcodeEntity.FIELD.QUANTITY.rawValue)
dataSource.append(nCode!)
CoreDataStackManager.sharedInstance.saveContext()
}
barcodeList.reloadData()
scanner.startRunning()
}
//MARK: - Table View
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("barcodeCell", forIndexPath: indexPath)
let code = dataSource[indexPath.row]
let count = scannedCodes[code] ?? 0
cell.textLabel!.text = "\(count) of \(code.quantity): \(getName(code))"
if count == Int(code.quantity) {
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
} else {
cell.accessoryType = UITableViewCellAccessoryType.None
}
return cell
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let deleted = dataSource[indexPath.row]
CoreDataStackManager.sharedInstance.managedObjectContext.deleteObject(deleted)
CoreDataStackManager.sharedInstance.saveContext()
dataSource.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
}
| mit | b98b9854e00418b344604e5185f5f17a | 34.258929 | 192 | 0.648012 | 5.358209 | false | false | false | false |
tinypass/piano-sdk-for-ios | PianoAPI/Models/PerformanceMetricsDto.swift | 1 | 502 | import Foundation
@objc(PianoAPIPerformanceMetricsDto)
public class PerformanceMetricsDto: NSObject, Codable {
/// GA Account
@objc public var gaAccount: String? = nil
/// Is GA enabled
@objc public var isEnabled: String? = nil
/// Track only aids
@objc public var trackOnlyAids: String? = nil
public enum CodingKeys: String, CodingKey {
case gaAccount = "ga_account"
case isEnabled = "is_enabled"
case trackOnlyAids = "track_only_aids"
}
}
| apache-2.0 | afbd31c2e19db20e7cd87a345f1b74a4 | 24.1 | 55 | 0.667331 | 4.016 | false | false | false | false |
raulriera/ForecastView | ForecastView/ForecastView/Temperature.swift | 1 | 1622 | //
// Temperature.swift
// WeatherView
//
// Created by Raul Riera on 28/07/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import Foundation
/**
A temperature value type.
*/
public struct Temperature {
let celsius: Int
let fahrenheit: Int
let format: TemperatureFormat
/// Temperature reading in the format specified.
public var value: Int {
switch format {
case .Celsius:
return celsius
case .Fahrenheit:
return fahrenheit
case .Automatic:
let isMetricSystem = NSLocale.currentLocale().objectForKey(NSLocaleUsesMetricSystem) as! Bool
if isMetricSystem {
return celsius
} else {
return fahrenheit
}
}
}
/**
Temperature format to display to the user.
- Automatic: Reads the current locale to determine the best format to display
- Celsius: Displays the temperature in celsius
- Fahrenheit: Displays the temperature in fahrenheit
*/
public enum TemperatureFormat {
case Automatic
case Celsius
case Fahrenheit
}
/**
Creates an instance of the temperature value type.
- parameter celsius: temperature reading in celsius
- parameter fahrenheit: temperature reading in fahrenheit
- parameter format: temperature format to display
*/
init(celsius: Int, fahrenheit: Int, format: TemperatureFormat = .Celsius) {
self.celsius = celsius
self.fahrenheit = fahrenheit
self.format = format
}
} | mit | 3079349fbccf630ed7998c025a4c90f3 | 25.177419 | 105 | 0.621455 | 5.165605 | false | false | false | false |
oneCup/MyWeiBo | MyWeiBoo/MyWeiBoo/Tools/String + Rex.swift | 1 | 1037 | //
// String + Rex.swift
// ๆญฃๅ่กจ่พพๅผ
//
// Created by ๆๆฐธๆน on 15/10/25.
// Copyright ยฉ 2015ๅนด ๆๆฐธๆน. All rights reserved.
//
import Foundation
extension String {
func hrefLink() ->(link: String? , text: String?) {
let pattern = "<a href=\"(.*?)\".*?>(.*?)</a>"
let regular = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators)
//ๅผๅงๅน้
if let result = regular.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) {
print(result.numberOfRanges)
//let r1 = result!.rangeAtIndex(0)
let r2 = result.rangeAtIndex(1)
let r3 = result.rangeAtIndex(2)
let link = (self as NSString).substringWithRange(r2)
let text = (self as NSString).substringWithRange(r3)
return (link,text)
}
return(nil,nil)
}
}
| mit | 8727b7006c3a658e783322490a6654e3 | 22.904762 | 145 | 0.570717 | 4.254237 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/App/Config.swift | 1 | 5603 | //
// Config.swift
// zhuishushenqi
//
// Created by Nory Cao on 16/9/17.
// Copyright ยฉ 2016ๅนด QS. All rights reserved.
//
import Foundation
import UIKit
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l >= r
default:
return !(lhs < rhs)
}
}
//MARK:- API
let BASEURL = "http://api.zhuishushenqi.com"
let IMAGE_BASEURL = "http://statics.zhuishushenqi.com"
let CHAPTERURL = "http://chapter2.zhuishushenqi.com/chapter"
let BOOKSHELF = "user/bookshelf"
let RANKING = "ranking/gender"
// db
let searchHistory = "searchHistory"
let dbName = "QS.zhuishushenqi.searchHistory"
//MARK: - ๅธธ็จframe
let BOUNDS = UIScreen.main.bounds
let ScreenWidth = UIScreen.main.bounds.size.width
let ScreenHeight = UIScreen.main.bounds.size.height
let SCALE = (ScreenWidth / 320.0)
let TOP_BAR_Height:CGFloat = 64
let FOOT_BAR_Height:CGFloat = 49
let STATEBARHEIGHT = UIApplication.shared.statusBarFrame.height
let kNavgationBarHeight:CGFloat = (IPHONEX ? 88:64)
let kTabbarBlankHeight:CGFloat = (IPHONEX ? 34:0)
let kQSReaderTopMargin:CGFloat = (IPHONEX ? 30:0)
//ๅบๅๅฑๅน
let IPHONE4 = UIScreen.instancesRespond(to: #selector(getter: RunLoop.currentMode)) ? CGSize(width: 640, height: 960).equalTo((UIScreen.main.currentMode?.size)!) : false
let IPHONE5 = UIScreen.instancesRespond(to: #selector(getter: RunLoop.currentMode)) ? CGSize(width: 640, height: 1136).equalTo((UIScreen.main.currentMode?.size)!) : false
let IPHONE6 = UIScreen.instancesRespond(to: #selector(getter: RunLoop.currentMode)) ? CGSize(width: 750, height: 1334).equalTo((UIScreen.main.currentMode?.size)!) : false
let IPHONE6Plus = UIScreen.instancesRespond(to: #selector(getter: RunLoop.currentMode)) ? CGSize(width: 1242, height: 2208).equalTo((UIScreen.main.currentMode?.size)!) : false
let IPHONEX_SMALL = UIScreen.instancesRespond(to: #selector(getter: RunLoop.currentMode)) ? CGSize(width: 828, height: 1792).equalTo((UIScreen.main.currentMode?.size)!) : false
let IPHONEX_MID = UIScreen.instancesRespond(to: #selector(getter: RunLoop.currentMode)) ? CGSize(width: 1125, height: 2436).equalTo((UIScreen.main.currentMode?.size)!) : false
let IPHONEX_BIG = UIScreen.instancesRespond(to: #selector(getter: RunLoop.currentMode)) ? CGSize(width: 1242, height: 2688).equalTo((UIScreen.main.currentMode?.size)!) : false
let IPHONEX = IPHONEX_SMALL || IPHONEX_MID || IPHONEX_BIG
//ๆ นๆฎ็ณป็ปๅคๆญ ่ทๅiPad็ๅฑๅนๅฐบๅฏธ
let IOS9_OR_LATER = (Float(UIDevice.current.systemVersion) >= 9.0)
let IOS8_OR_LATER = (Float(UIDevice.current.systemVersion) >= 8.0)
let IOS7_OR_LATER = (Float(UIDevice.current.systemVersion) >= 7.0)
let APP_DELEGATE = (UIApplication.shared.delegate as! AppDelegate)
let APP_DELEGATEKeyWindow = UIApplication.shared.delegate?.window
let USER_DEFAULTS = UserDefaults.standard
let KeyWindow = UIApplication.shared.keyWindow
let SideVC = SideViewController.shared
let ReaderBg = "ReaderBg"
let FontSize = "FontSize"
let OriginalBrightness = "OriginalBrightness"
let Brightness = "Brightness"
let ReadingProgress = "ReadingProgress"
let PostLink = "PostLink"
// notification
let SHOW_RECOMMEND = "ShowRecomend"
let BOOKSHELF_REFRESH = "BookShelfRefresh"
let BOOKSHELF_ADD = "BOOKSHELF_ADD"
let BOOKSHELF_DELETE = "BOOKSHELF_DELETE"
let RootDisappearNotificationName = "RootDisappearNotificationName"
func getAttributes(with lineSpave:CGFloat,font:UIFont)->NSDictionary{
let paraStyle = NSMutableParagraphStyle()
paraStyle.lineBreakMode = .byCharWrapping
paraStyle.alignment = .left
paraStyle.lineSpacing = lineSpave
paraStyle.hyphenationFactor = 1.0
paraStyle.firstLineHeadIndent = 0.0
paraStyle.paragraphSpacingBefore = 0.0
paraStyle.headIndent = 0
paraStyle.tailIndent = 0
let dict = [NSAttributedString.Key.font:font,NSAttributedString.Key.kern:1.5,NSAttributedString.Key.paragraphStyle:paraStyle] as [NSAttributedString.Key : Any]
return dict as NSDictionary
}
func attributeText(with lineSpace:CGFloat,text:String,font:UIFont)->NSAttributedString{
let paraStyle = NSMutableParagraphStyle()
paraStyle.lineBreakMode = .byCharWrapping
paraStyle.alignment = .left
paraStyle.hyphenationFactor = 1.0
paraStyle.firstLineHeadIndent = 0.0
paraStyle.paragraphSpacingBefore = 0.0
paraStyle.headIndent = 0
paraStyle.tailIndent = 0
let dict = [NSAttributedString.Key.font:font,NSAttributedString.Key.kern:1.5,NSAttributedString.Key.paragraphStyle:paraStyle] as [NSAttributedString.Key : Any]
let attributeStr = NSAttributedString(string: text, attributes: dict)
return attributeStr
}
func QSLog<T>(_ message:T,fileName:String = #file,lineName:Int = #line,funcName:String = #function){
#if DEBUG
print("QSLog:\((fileName as NSString).lastPathComponent)[\(lineName)]\(funcName):\n\(message)\n")
#endif
}
func calTime(_ action: @escaping () ->Void){
let startTime = CFAbsoluteTimeGetCurrent()
action()
let linkTime = (CFAbsoluteTimeGetCurrent() - startTime)
QSLog("Linked in \(linkTime * 1000.0) ms")
}
| mit | 50d6c4c42222144b4b3d99bccc4614d1 | 40.2 | 176 | 0.745595 | 3.690776 | false | false | false | false |
xiaoxionglaoshi/DNSwiftProject | DNSwiftProject/DNSwiftProject/Classes/Expend/DNExtensions/IntExtension.swift | 1 | 1234 | //
// IntExtension.swift
// DNSwiftProject
//
// Created by mainone on 16/12/22.
// Copyright ยฉ 2016ๅนด wjn. All rights reserved.
//
import UIKit
extension Int {
// ็ๆ้ๆบๆฐ
public static func randomBetween(min: Int, max: Int) -> Int {
let delta = max - min
return min + Int(arc4random_uniform(UInt32(delta)))
}
// ๆฐๅญ่ฝฌ็ฝ้ฉฌๆฐๅญ
public var romanNumeral: String? {
guard self > 0 else {
return nil
}
let romanValues = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabicValues = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var romanValue = ""
var startingValue = self
for (index, romanChar) in romanValues.enumerated() {
let arabicValue = arabicValues[index]
let div = startingValue / arabicValue
if (div > 0) {
for _ in 0..<div {
romanValue += romanChar
}
startingValue -= arabicValue * div
}
}
guard romanValue.characters.count > 0 else {
return nil
}
return romanValue
}
}
| apache-2.0 | 54384e5d5cd8c96763874f8389e1a514 | 25.822222 | 97 | 0.499586 | 3.807571 | false | false | false | false |
depl0y/pixelbits | pixelbits/Parser/PBNode.swift | 1 | 6250 | //
// PBNode.swift
// pixelbits
//
// Created by Wim Haanstra on 10/01/16.
// Copyright ยฉ 2016 Wim Haanstra. All rights reserved.
//
import UIKit
internal class PBNode: NSObject {
/// Parent `PBNode` for this node, nil if found in the root of the stylesheet.
var parent: PBNode?
var key: String
var nodes = Array<PBNode>()
var subviews = Array<PBNode>()
var properties = Array<PBProperty>()
init(key: String, parent: PBNode? = nil) {
self.key = key
self.parent = parent
super.init()
}
init(key: String, style: Dictionary<String, AnyObject>, parent: PBNode? = nil) {
self.key = key
self.parent = parent
super.init()
self.load(style)
}
func load(style: Dictionary<String, AnyObject>) {
self.properties.removeAll()
self.nodes.removeAll()
Log.debug("Loading style for \(key)")
if style.keys.count == 0 {
Log.error("Loading with key \(self.key) failed, styling missing")
return
}
let replacedStyle = self.replaceKeys(style)
for (key, value) in replacedStyle {
if let childDictionary = value as? Dictionary<String, AnyObject> {
if key.hasPrefix("@") {
let subviewKey = key.substringFromIndex(key.startIndex.advancedBy(1))
let subViewNode = PBNode(key: subviewKey, style: childDictionary, parent: self)
self.addSubview(subViewNode)
}
else {
let childNode = PBNode(key: key, style: childDictionary, parent: self)
self.nodes.append(childNode)
}
}
else {
self.addProperty(ValueToPropertyConverter.fromAnyObject(key, value: value))
}
}
}
/**
Add a property to the `properties` of this node, when a property with this key already exists, it is replaced.
- parameter key: The key of the property
- parameter value: The value for the property
- parameter type: The type of `PBPropertyType` that is stored
*/
func addProperty(key: String, value: AnyObject, type: PBPropertyType) {
let prop = PBProperty(key: key, value: value, type: type)
if self.hasProperty(prop.key) {
self.removeProperty(prop.key)
}
self.properties.append(prop)
}
/**
Add a `PBProperty` object to the `properties` collection. If a property with the key of the supplied property
already exists, the property is replaced
- parameter property: `PBProperty` object that is added
*/
func addProperty(property: PBProperty) {
if self.hasProperty(property.key) {
self.removeProperty(property.key)
}
let prop = PBProperty(key: property.key, value: property.value, type: property.type)
prop.controlState = property.controlState
self.properties.append(prop)
}
/**
Looks in the `properties` collection to see if a property with this key already exists.
- parameter key: The key of the property to look for
- returns: `true` if a property with this key already exists, otherwise `false`
*/
func hasProperty(key: String) -> Bool {
let props = self.properties.filter { (prop) -> Bool in
return prop.key == key
}
return props.count > 0
}
/**
Remove a property with supplied key from the `properties` collection
- parameter key: The key of the property to remove
*/
func removeProperty(key: String) {
let props = self.properties.filter { (prop) -> Bool in
return prop.key == key
}
for prop in props {
self.properties.removeObject(prop)
}
}
func addSubview(subview: PBNode) {
if self.hasSubview(subview.key) {
self.removeSubview(subview.key)
}
self.subviews.append(subview)
}
func hasSubview(key: String) -> Bool {
let results = self.subviews.filter { (subview) -> Bool in
return subview.key == key
}
return results.count > 0
}
func removeSubview(key: String) {
let results = self.subviews.filter { (subview) -> Bool in
return subview.key == key
}
for subview in results {
self.subviews.removeObject(subview)
}
}
/**
Apply the styling of this node to the supplied `UIView`.
- parameter view: The `UIView` this styling should be applied to
*/
func apply(view: UIView) {
for property in self.properties {
property.apply(view)
}
for subViewNode in self.subviews {
if view.respondsToSelector(Selector(subViewNode.key)) {
let value = view.valueForKey(subViewNode.key)
if let subView = value as? UIView {
subViewNode.apply(subView)
}
}
}
}
private func replaceKeys(style: Dictionary<String, AnyObject>) -> Dictionary<String, AnyObject> {
var replacedStyle = Dictionary<String, AnyObject>()
for (key, value) in style {
if let _ = value as? Dictionary<String, AnyObject> {
replacedStyle[key] = value
}
let newKey = DictionaryKeyConverter.fromString(key)
replacedStyle[newKey] = value
}
return replacedStyle
}
func pathString() -> String {
var result = ""
if parent != nil {
result = parent!.pathString()
}
result += "/" + key
return result
}
}
| mit | ec4a27fac332854d08b174a6b6da83db | 26.650442 | 115 | 0.531125 | 4.866822 | false | false | false | false |
Yalantis/PullToRefresh | PullToRefreshDemo/CollectionViewController.swift | 1 | 1616 | //
// CollectionViewController.swift
// PullToRefreshDemo
//
// Created by Sergey Prikhodko on 08.04.2020.
// Copyright ยฉ 2020 Yalantis. All rights reserved.
//
import UIKit
private let pageSize = 100
final class CollectionViewController: UIViewController, PullToRefreshPresentable {
@IBOutlet private var collectionView: UICollectionView!
private var dataSourceCount = pageSize
override func viewDidLoad() {
super.viewDidLoad()
setupPullToRefresh(on: collectionView)
}
@IBAction func refreshAction() {
collectionView.startRefreshing(at: .top)
}
@IBAction func openSettings() {
openSettings(for: collectionView)
}
func loadAction() {
dataSourceCount += pageSize
collectionView.reloadData()
}
func reloadAction() {
dataSourceCount = pageSize
collectionView.reloadData()
}
deinit {
collectionView.removeAllPullToRefresh()
}
}
// MARK: - UICollectionViewDataSource
extension CollectionViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSourceCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(NumberCollectionViewCell.self)", for: indexPath) as! NumberCollectionViewCell
cell.titleLabel.text = "\(indexPath.item)"
return cell
}
}
| mit | 174fc3c7e7086439e45c4b4cda72afb8 | 25.47541 | 155 | 0.689783 | 5.646853 | false | false | false | false |
alobanov/ALFormBuilder | Sources/FormBuilder/FormItemsComposite/rowProtocols/CompositeProtocols.swift | 1 | 2786 | //
// CompositeProtocols.swift
// ALFormBuilder
//
// Created by Lobanov Aleksey on 27/10/2017.
// Copyright ยฉ 2017 Lobanov Aleksey. All rights reserved.
//
import Foundation
/// ะัะพัะพะบะพะป ะพัะฒะตัะฐััะธะน ะทะฐ ะฒะพะทะผะพะถะฝะพััั ะฟัะตะดะตะปะธัั ะฟัะฐะฒะธะปะฐ ะฒะธะดะธะผะพััะธ ะดะปั ัะปะตะผะตะฝัะฐ ัะฐะฑะปะธัั
public protocol RowCompositeVisibleSetting: class {
var visible: ALFB.Condition {set get}
var base: ALFB.Base {set get}
var cellType: FBUniversalCellProtocol {get}
func checkStates(by source: [String: Any]) -> Bool
}
extension RowCompositeVisibleSetting {
public var cellType: FBUniversalCellProtocol {
return self.base.cellType
}
public func checkStates(by source: [String: Any]) -> Bool {
let isChangeVisible = visible.checkVisibleState(model: source)
let isChangeMandatory = visible.checkMandatoryState(model: source)
let isChangeDisable = visible.checkDisableState(model: source)
let isChangeValid = visible.checkValidState(model: source)
return (isChangeVisible || isChangeMandatory || isChangeDisable || isChangeValid) || base.isStrictReload
}
}
/// ะัะพัะพะบะพะป ะพัะฒะตัะฐััะธะน ะทะฐ ะฒะพะทะผะพะถะฝะพััั ะฒะฐะปะธะดะฐัะธะธ
public protocol RowCompositeValidationSetting: RowCompositeValueTransformable {
var validation: ALFB.Validation {set get}
func update(value: ALValueTransformable, silent: Bool, forceUpdate: Bool)
func update(value: ALValueTransformable)
func updateAndReload(value: ALValueTransformable)
@discardableResult func validate(value: ALValueTransformable) -> ALFB.ValidationState
}
extension RowCompositeValidationSetting where Self: FormItemCompositeProtocol & RowCompositeVisibleSetting {
public func updateAndReload(value: ALValueTransformable) {
self.base.needReloadModel()
self.update(value: value, silent: true, forceUpdate: true)
}
public func update(value: ALValueTransformable) {
self.update(value: value, silent: false, forceUpdate: false)
}
public func update(value: ALValueTransformable, silent: Bool = false, forceUpdate: Bool = false) {
if forceUpdate || self.value.transformForDisplay() != value.transformForDisplay() {
self.value.change(originalValue: value.retriveOriginalValue())
didChangeData?(self, silent)
}
}
}
public typealias DidChange = (FormItemCompositeProtocol, Bool) -> Void
public typealias DidChangeValidation = () -> Void
/// ะัะพัะพะบะพะป ะพัะฒะตัะฐััะธะน ะทะฐ ะฒะพะทะผะพะถะฝะพััั ั
ัะฐะฝะธัั ะทะฐะฝะฐัะตะฝะธะต ัะธะฟะฐ ValueTransformable
public protocol RowCompositeValueTransformable: class {
var value: ALValueTransformable {get}
var didChangeData: DidChange? {set get}
var didChangeValidation: [String: DidChangeValidation?] {set get}
}
| mit | f2257664751aaaf7778b084341c9218d | 36.428571 | 108 | 0.768321 | 4.049459 | false | false | false | false |
brentdax/swift | stdlib/public/core/Repeat.swift | 9 | 3763 | //===--- Repeat.swift - A Collection that repeats a value N times ---------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A collection whose elements are all identical.
///
/// You create an instance of the `Repeated` collection by calling the
/// `repeatElement(_:count:)` function. The following example creates a
/// collection containing the name "Humperdinck" repeated five times:
///
/// let repeatedName = repeatElement("Humperdinck", count: 5)
/// for name in repeatedName {
/// print(name)
/// }
/// // "Humperdinck"
/// // "Humperdinck"
/// // "Humperdinck"
/// // "Humperdinck"
/// // "Humperdinck"
@_fixed_layout
public struct Repeated<Element> {
/// The number of elements in this collection.
public let count: Int
/// The value of every element in this collection.
public let repeatedValue: Element
}
extension Repeated: RandomAccessCollection {
public typealias Indices = Range<Int>
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a "past the
/// end" position that's not valid for use as a subscript.
public typealias Index = Int
/// Creates an instance that contains `count` elements having the
/// value `repeatedValue`.
@inlinable // trivial-implementation
internal init(_repeating repeatedValue: Element, count: Int) {
_precondition(count >= 0, "Repetition count should be non-negative")
self.count = count
self.repeatedValue = repeatedValue
}
/// The position of the first element in a nonempty collection.
///
/// In a `Repeated` collection, `startIndex` is always equal to zero. If the
/// collection is empty, `startIndex` is equal to `endIndex`.
@inlinable // trivial-implementation
public var startIndex: Index {
return 0
}
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// In a `Repeated` collection, `endIndex` is always equal to `count`. If the
/// collection is empty, `endIndex` is equal to `startIndex`.
@inlinable // trivial-implementation
public var endIndex: Index {
return count
}
/// Accesses the element at the specified position.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
@inlinable // trivial-implementation
public subscript(position: Int) -> Element {
_precondition(position >= 0 && position < count, "Index out of range")
return repeatedValue
}
}
/// Creates a collection containing the specified number of the given element.
///
/// The following example creates a `Repeated<Int>` collection containing five
/// zeroes:
///
/// let zeroes = repeatElement(0, count: 5)
/// for x in zeroes {
/// print(x)
/// }
/// // 0
/// // 0
/// // 0
/// // 0
/// // 0
///
/// - Parameters:
/// - element: The element to repeat.
/// - count: The number of times to repeat `element`.
/// - Returns: A collection that contains `count` elements that are all
/// `element`.
@inlinable // trivial-implementation
public func repeatElement<T>(_ element: T, count n: Int) -> Repeated<T> {
return Repeated(_repeating: element, count: n)
}
| apache-2.0 | 1ae9fc88add1b5bf3c2096c00b6222ef | 33.522936 | 80 | 0.65586 | 4.355324 | false | false | false | false |
LamGiauKhongKhoTeam/LGKK | LGKKCoreLib/LGKKCoreLib/Modules/FlagKit/CountryPhoneHolderView.swift | 1 | 4412 | //
// CountryPhoneHolderView.swift
// drivethrough
//
// Created by Nguyen Minh on 4/3/17.
// Copyright ยฉ 2017 SP. All rights reserved.
//
import UIKit
import Reusable
import SwifterSwift
public protocol CountryPhoneHolderDelegate: class {
func countryPhoneShouldReturn() -> Bool
}
open class CountryPhoneHolderView: SPBaseView, NibOwnerLoadable {
@IBOutlet fileprivate weak var btnFlag: UIButton!
@IBOutlet fileprivate weak var lblPhoneCode: UILabel!
@IBOutlet fileprivate weak var tfPhone: UITextField!
@IBOutlet fileprivate weak var line: UIView!
@IBOutlet fileprivate weak var lineHeight: NSLayoutConstraint!
open weak var delegate: CountryPhoneHolderDelegate?
private var hiddenTfChooseCountry: UITextField?
open var phoneCode: String? = "+1" // US default
open var phone: String? {
return tfPhone.text
}
open var fullPhone: String? {
if let phoneCode = phoneCode, let text = tfPhone.text {
return "\(phoneCode)\(text)"
} else {
return nil
}
}
init() {
let rect = CGRect(x: 0, y: 0, width: 100, height: 30)
super.init(frame: rect)
self.loadNibContent()
setUI()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.loadNibContent()
setUI()
}
func setUI() {
// Trick:
hiddenTfChooseCountry = UITextField()
if let hiddenTfChooseCountry = hiddenTfChooseCountry {
addSubview(hiddenTfChooseCountry)
}
backgroundColor = .clear
tfPhone.delegate = self
tfPhone.placeholder = "Enter mobile number"
tfPhone.keyboardType = .phonePad
phoneCode = "+1"
setFlag(with: "us")
}
fileprivate func setFlag(with code: String) {
if let flagSheet = FlagIcons.sharedInstance.spriteSheet {
let image = flagSheet.getImageFor(code)
btnFlag.setImage(image, for: .normal)
}
}
@IBAction func btnFlag_Tapped(_ sender: Any) {
endEditing(true)
let countryPicker = CountryPicker(frame: CGRect(x: 0, y: 0, width: SwifterSwift.screenWidth, height: 260))
countryPicker.backgroundColor = .white
countryPicker.countryPhoneCodeDelegate = self
countryPicker.setCountry(code: "us")
hiddenTfChooseCountry?.inputView = countryPicker
hiddenTfChooseCountry?.becomeFirstResponder()
}
}
// MARK: - Country picker delegate
extension CountryPhoneHolderView: CountryPickerDelegate {
func countryPhoneCodePicker(picker: CountryPicker,
didSelectCountryCountryWithName name: String,
countryCode: String,
phoneCode: String) {
setFlag(with: countryCode)
self.phoneCode = phoneCode
lblPhoneCode.text = phoneCode
}
}
// MARK: - UITextFieldDelegate
extension CountryPhoneHolderView: UITextFieldDelegate {
public func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == tfPhone {
line.backgroundColor = UIColor.darkGray
lineHeight.constant = 2.0
line.updateConstraints()
}
}
// Pair becomeFirstResponder & countryPhoneShouldReturn
override open func becomeFirstResponder() -> Bool {
return tfPhone.becomeFirstResponder()
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let delegate = delegate, textField == tfPhone {
return delegate.countryPhoneShouldReturn()
}
return true
}
public func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
if textField == tfPhone, let text = textField.text {
return text.characters.count + (string.characters.count - range.length) <= 15
}
return true
}
public func textFieldDidEndEditing(_ textField: UITextField) {
if textField == tfPhone, let text = textField.text {
line.backgroundColor = UIColor.lightGray
lineHeight.constant = text.isEmpty ? 2.0 : 0.5
line.updateConstraints()
}
}
}
| mit | f7a885413bffd5bdf74c8ead9ae3f147 | 30.733813 | 114 | 0.623668 | 4.989819 | false | false | false | false |
zwaldowski/ParksAndRecreation | Latest/Tab Bar Palette.playground/Sources/BackgroundBlendingView.swift | 1 | 2167 | import UIKit
final class BackgroundBlendingView: UIView {
enum BlendMode: String {
// Porter-Duff compositing operations
// http://www.w3.org/TR/2014/CR-compositing-1-20140220/#porterduffcompositingoperators
case clear = "clear"
case copy = "copy"
case sourceOver = "sourceOver"
case sourceIn = "sourceIn"
case sourceOut = "sourceOut"
case sourceAtop = "sourceAtop"
case destination = "dest"
case destinationOver = "destOver"
case destinationIn = "destIn"
case destinationOut = "destOut"
case destinationAtop = "destAtop"
case xor = "xor"
case plusDarker = "plusD"
case plusLighter = "plusL"
// Separable blend-modes
// http://www.w3.org/TR/2014/CR-compositing-1-20140220/#blendingseparable
case multiply = "multiply"
case screen = "screenBlendMode"
case overlay = "overlayBlendMode"
case darken = "darkenBlendMode"
case lighten = "lightenBlendMode"
case colorDodge = "colorDodgeBlendMode"
case colorBurn = "colorBurnBlendMode"
case softLight = "softLightBlendMode"
case hardLight = "hardLightBlendMode"
case difference = "differenceBlendMode"
case exclusion = "exclusionBlendMode"
}
private let blendingLayers: [CALayer]
init(filters: (BlendMode, UIColor)...) {
blendingLayers = filters.map { (filter, color) in
let sublayer = CALayer()
sublayer.backgroundColor = color.cgColor
sublayer.compositingFilter = filter.rawValue
return sublayer
}
super.init(frame: .zero)
layer.setValue(false, forKey: "allowsGroupBlending")
blendingLayers.forEach(layer.addSublayer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) is not supported")
}
override func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
guard layer === self.layer else { return }
for sublayer in blendingLayers {
sublayer.frame = layer.bounds
}
}
}
| mit | df58846dd3d1a5cf1be42aa368f4428d | 31.343284 | 94 | 0.626211 | 4.377778 | false | false | false | false |
bgould/thrift | lib/swift/Sources/TFileTransport.swift | 12 | 2766 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import Foundation
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
import Glibc
#endif
/// TFileTransport
/// Foundation-less Swift File transport.
/// Uses C fopen/fread/fwrite,
/// provided by Glibc in linux and Darwin on OSX/iOS
public class TFileTransport: TTransport {
var fileHandle: UnsafeMutablePointer<FILE>? = nil
public init (fileHandle: UnsafeMutablePointer<FILE>) {
self.fileHandle = fileHandle
}
public convenience init(filename: String) throws {
var fileHandle: UnsafeMutablePointer<FILE>?
filename.withCString({ cFilename in
"rw".withCString({ cMode in
fileHandle = fopen(cFilename, cMode)
})
})
if let fileHandle = fileHandle {
self.init(fileHandle: fileHandle)
} else {
throw TTransportError(error: .notOpen)
}
}
deinit {
fclose(self.fileHandle)
}
public func readAll(size: Int) throws -> Data {
let read = try self.read(size: size)
if read.count != size {
throw TTransportError(error: .endOfFile)
}
return read
}
public func read(size: Int) throws -> Data {
// set up read buffer, position 0
var read = Data(capacity: size)
var position = 0
// read character buffer
var nextChar: UInt8 = 0
// continue until we've read size bytes
while read.count < size {
if fread(&nextChar, 1, 1, self.fileHandle) == 1 {
read[position] = nextChar
// Increment output byte pointer
position += 1
} else {
throw TTransportError(error: .endOfFile)
}
}
return read
}
public func write(data: Data) throws {
let bytesWritten = data.withUnsafeBytes {
fwrite($0.baseAddress!, 1, data.count, self.fileHandle)
}
if bytesWritten != data.count {
throw TTransportError(error: .unknown)
}
}
public func flush() throws {
return
}
}
| apache-2.0 | 6131ae667c4c5e84e0a0ad6f940506b3 | 26.386139 | 61 | 0.668836 | 4.146927 | false | false | false | false |
lieonCX/Live | Live/Others/Network/Network.swift | 1 | 13535 | //
// Network.swift
// Live
//
// Created by lieon on 2017/6/20.
// Copyright ยฉ 2017ๅนด ChengDuHuanLeHui. All rights reserved.
//
import Foundation
import ObjectMapper
import Device
import UIKit
import Alamofire
public class Header: Model {
public var token: String {
get { return UserSessionInfo.getSession().token ?? ""}
set { }
}
public var deviceUUID: String {
get { return AppConfig.getUUID() }
set { }
}
public var deviceType: String {
get { return UIDevice.current.systemVersion }
set { }
}
public var deviceName: String {
get { return Device.version().rawValue }
set { }
}
public var contentType: String = "application/json"
public override func mapping(map: Map) {
token <- map["token"]
deviceUUID <- map["deviceId"]
deviceType <- map["deviceType"]
deviceName <- map["deviceName"]
contentType <- map["Content-Type"]
}
}
public enum UserPath: UserEndPointProtocol {
case login
case fastLogin
case registerValidatePhone
case smsCaptcha
case checkCapcha
case register
case thirdPartyRegiseterQQ
case thirdPartyRegiseterWechat
case thirdPartyRegiseterWeibo
case findPassword
case thirdPartyLoginQQ
case thirdPartyLoginWechat
case thirdPartyLoginSina
case thirdPartyBindQQ
case thirdPartyBindWechat
case thirdPartyBindWeibo
case approve
case getInfo
case modifyUserInfo
case feedback
case approveZhima
case approveZhimaQuery
case logout
case exchangePhoneNum
var method: HTTPMethod {
switch self {
case .getInfo:
return .get
case .logout:
return .get
default:
return .post
}
}
var path: String {
return"/user"
}
var endpoint: String {
switch self {
case .login:
return "/login"
case .register:
return "/reg"
case .registerValidatePhone:
return "/reg/validatePhone"
case .smsCaptcha:
return "/sms/captcha"
case .checkCapcha:
return "/check/captcha"
case .thirdPartyRegiseterQQ:
return "/fastCreate/qq"
case .thirdPartyRegiseterWechat:
return "/fastCreate/wechat"
case .thirdPartyRegiseterWeibo:
return "/fastCreate/weibo"
case .findPassword:
return "/setPass"
case .fastLogin:
return "/login/captcha"
case .thirdPartyLoginQQ:
return "/login-qq"
case .thirdPartyLoginSina:
return "/login-weibo"
case .thirdPartyLoginWechat:
return "/login-wechat"
case .thirdPartyBindQQ:
return "/binding/qq"
case .thirdPartyBindWechat:
return "/binding/wechat"
case .thirdPartyBindWeibo:
return "/binding/weibo"
case .approve:
return "/approve"
case .getInfo:
return "/info"
case . modifyUserInfo:
return "/info"
case .feedback:
return "/recommend/add"
case .approveZhima:
return "/approveZhima"
case .approveZhimaQuery:
return "/approveZhimaQuery"
case .logout:
return "/logout"
case .exchangePhoneNum:
return "/exchangePhone"
}
}
}
class UserRequestParam: Model {
var username: String?
var password: String?
var code: String?
var accessToken: String?
var openId: String?
var unionId: String?
var thirdPartyInfo: [String: Any]?
var capchaCodeType: CaptchaType?
var phone: String?
override func mapping(map: Map) {
username <- map["username"]
password <- map["password"]
code <- map["code"]
accessToken <- map["accessToken"]
openId <- map["openId"]
unionId <- map["unionId"]
thirdPartyInfo <- map["info"]
capchaCodeType <- map["type"]
phone <- map["phone"]
}
}
/*
phone:ๆๆบๅท็
type :็ฑปๅ
code:้ช่ฏ็
*/
class SmsCaptchaParam: Model {
var type: CaptchaType = .register
var phone: String?
var code: String?
override func mapping(map: Map) {
type <- map["type"]
phone <- map["phone"]
code <- map["code"]
}
}
enum CommonPath: ContentEndPointProtocol {
case getQQValidationCode
case getWeiboValidationCode
case getWechatValidationCode
var path: String {
return "/commons"
}
var endpoint: String {
return "/validate/bindThird"
}
}
class GetValidationCodeParam: Model {
var type: ThirdPartyType = .none
var openId: String?
override func mapping(map: Map) {
type <- map["type"]
openId <- map["openId"]
}
}
class BroadcastParam: Model {
var cover: String?
var latitude: Double = 30.67
var longitude: Double = 104.06
var city: String? = "ๆ้ฝ"
var name: String?
override func mapping(map: Map) {
cover <- map["cover"]
latitude <- map["lat"]
longitude <- map["lng"]
city <- map["city"]
name <- map["name"]
}
}
enum BroadcatPath: UserEndPointProtocol {
case startLive
case endLive
case deleteeBroadcast
case comebackLive
var path: String {
return "/live"
}
var endpoint: String {
switch self {
case .startLive:
return "/startLive"
case .endLive:
return "/endLive"
case .deleteeBroadcast:
return "/" + "\(LiveListRequstParam.liveId)" + "/delete"
case .comebackLive:
return "/comebackLive"
}
}
}
enum RoomPath: UserEndPointProtocol {
case enterLiveRoom
case leaveLiveRoom
case getLiveRealTimeInfo
var path: String {
return "/live"
}
var endpoint: String {
switch self {
case .enterLiveRoom:
return "/" + "\(RoomRequstParam.RoomID ?? "")" + "/comeIn"
case .leaveLiveRoom:
return "/" + "\(RoomRequstParam.RoomID ?? "")" + "/leaveOut"
case .getLiveRealTimeInfo:
return "/" + "\(RoomRequstParam.RoomID ?? "")" + "/info"
}
}
var method: HTTPMethod {
switch self {
case .getLiveRealTimeInfo:
return .get
default:
return .post
}
}
}
enum LiveListPath: ContentEndPointProtocol {
case live
case nearby
case byUserId
var path: String {
return "/live"
}
var endpoint: String {
switch self {
case .live:
return ""
case .nearby:
return "/distance"
case .byUserId:
return "/user" + "/" + "\(LiveListRequstParam.userId)"
}
}
}
class LiveListRequstParam: Model {
static var userId: Int = 0
static var liveId: Int = 0
var page: Int = 0
var limit: Int = 20
var keywords: String?
var orderBy: OrderType?
var longitude: Double?
var latitude: Double?
var sex: Gender?
override func mapping(map: Map) {
page <- map["page"]
limit <- map["limit"]
keywords <- map["keywords"]
orderBy <- map["orderBy"]
latitude <- map["lat"]
longitude <- map["lng"]
sex <- map["sex"]
}
}
class IDVlidateRequestParam: Model {
var trueName: String?
var idCardNumber: String?
override func mapping(map: Map) {
trueName <- map["trueName"]
idCardNumber <- map["idCard"]
}
}
class ModiftUserInfoParam: Model {
var avatar: String?
var nickName: String?
var sex: Gender = .female
var birthday: String?
override func mapping(map: Map) {
avatar <- map["avastar"]
nickName <- map["nickName"]
sex <- map["sex"]
birthday <- map["birthday"]
}
}
class FeedbackRequstParam: Model {
var content: String?
var pictures: [String]?
override func mapping(map: Map) {
content <- map["content"]
pictures <- map["picture"]
}
}
class ZhimaCertifyResult: Model {
var certifyNumber: String?
var certifyURL: String?
var appId: String?
var isApprove: Bool = false
override func mapping(map: Map) {
certifyNumber <- map["bizNo"]
certifyURL <- map["generateCertifyUrl"]
appId <- map["appId"]
isApprove <- map["isApprove"]
}
}
class ZhimaCertifyResultQueryParam: Model {
var certifyNumber: String?
override func mapping(map: Map) {
certifyNumber <- map["bizNo"]
}
}
class RoomRequstParam: Model {
static var RoomID: String?
}
class AnchorRequestParm: Model {
static var anchorId: Int = 0
}
enum AnchorPath: ContentEndPointProtocol {
case getInfo
var path: String {
return "/user"
}
var endpoint: String {
switch self {
case .getInfo:
return "/" + "\(AnchorRequestParm.anchorId)" + "/info"
}
}
}
class CollectionRequstParam: Model {
var userId: Int = 0
var liveId: Int?
override func mapping(map: Map) {
userId <- map["userId"]
liveId <- map["liveId"]
}
}
enum CollectionPath: UserEndPointProtocol {
case addfollow
case disFollow
case followList
case recommendList
case userSearch
var method: HTTPMethod {
switch self {
case .followList,
.recommendList,
.userSearch:
return .get
default:
return .post
}
}
var path: String {
return "/follow"
}
var endpoint: String {
switch self {
case .addfollow:
return "/addfollow"
case .disFollow:
return "/disFollow"
case .followList:
return ""
case .recommendList:
return "/user/recommend"
case .userSearch:
return "/user/search"
}
}
}
class UserListRequstParam: Model {
var page: Int = 0
var limit: Int = 20
var userId: Int?
var type: UserListType = .fans
override func mapping(map: Map) {
page <- map["page"]
limit <- map["limit"]
userId <- map["userId"]
type <- map["type"]
}
}
enum RechargeEnvironment: Int {
case pruduct = 0
case test = 1
}
class RechargeRequestParam: Model {
var environment: RechargeEnvironment = .test
var receipt: String?
override func mapping(map: Map) {
environment <- map["chooseEnv"]
receipt <- map["receipt-data"]
}
}
enum MoneyPath: UserEndPointProtocol {
case rechargeBeans
case getPickupInfo
case applyPickUp
case getMoneyLogList
var path: String {
return "/money"
}
var endpoint: String {
switch self {
case .rechargeBeans:
return "/verifyIapCertificate"
case .getPickupInfo:
return "/getPickupInfo"
case .applyPickUp:
return "/applyPickUp" + "/" + ApplyPickUpParam.type.rawValue
case .getMoneyLogList:
return "/getMoneyLogList"
}
}
var method: HTTPMethod {
switch self {
case .getMoneyLogList:
return .get
default:
return .post
}
}
}
enum GiftPath: UserEndPointProtocol {
case getList
case give
var path: String {
return "/gift"
}
var endpoint: String {
switch self {
case .getList:
return "/list"
case .give:
return "/give"
}
}
var method: HTTPMethod {
switch self {
case .getList:
return .get
default:
return .post
}
}
}
class GiftRequstParam: Model {
var ratioType: Int = CustomKey.Ratiotype
var toId: Int?
var gitftId: Int?
var liveId: Int?
override func mapping(map: Map) {
toId <- map["toId"]
gitftId <- map["giftId"]
liveId <- map["liveId"]
ratioType <- map["ratioType"]
}
}
class ChatRequestParam: Model {
var liveId: Int = 0
override func mapping(map: Map) {
liveId <- map["liveId"]
}
}
enum ChatPath: UserEndPointProtocol {
case sendDanmaku
var path: String {
return "/chat"
}
var endpoint: String {
switch self {
case .sendDanmaku:
return "/barrage"
}
}
}
class ApplyPickUpParam: Model {
static var type: PayType = .alipay
var pickupMoney: String?
var payeeAccount: String?
var realName: String?
var mobile: String?
var code: String?
var payType: PayType = .alipay {
didSet {
ApplyPickUpParam.type = payType
}
}
override func mapping(map: Map) {
pickupMoney <- map["pickupMoney"]
payeeAccount <- map["payeeAccount"]
realName <- map["realName"]
mobile <- map["mobile"]
code <- map["code"]
}
}
class MoneyInoutRecordParam: Model {
var page: Int = 0
var limit: Int = 0
var type: MoneyRecordType = .withdraw
override func mapping(map: Map) {
page <- map["page"]
limit <- map["limit"]
type <- map["type"]
}
}
| mit | 984b4b904cf15b3079abc24ec553d292 | 21.44186 | 72 | 0.559882 | 4.287528 | false | false | false | false |
danielrhodes/Swift-ActionCableClient | Example/ActionCableClient/ChatViewController.swift | 1 | 7658 | //
// Copyright (c) 2016 Daniel Rhodes <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import UIKit
import ActionCableClient
import SnapKit
import SwiftyJSON
class ChatViewController: UIViewController {
static var MessageCellIdentifier = "MessageCell"
static var ChannelIdentifier = "ChatChannel"
static var ChannelAction = "talk"
let client = ActionCableClient(url: URL(string:"wss://actioncable-echo.herokuapp.com/cable")!)
var channel: Channel?
var history: Array<ChatMessage> = Array()
var name: String?
var chatView: ChatView?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Chat"
chatView = ChatView(frame: view.bounds)
view.addSubview(chatView!)
chatView?.snp.remakeConstraints({ (make) -> Void in
make.top.bottom.left.right.equalTo(self.view)
})
chatView?.tableView.delegate = self
chatView?.tableView.dataSource = self
chatView?.tableView.separatorInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0)
chatView?.tableView.allowsSelection = false
chatView?.tableView.register(ChatCell.self, forCellReuseIdentifier: ChatViewController.MessageCellIdentifier)
chatView?.textField.delegate = self
setupClient()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let alert = UIAlertController(title: "Chat", message: "What's Your Name?", preferredStyle: UIAlertControllerStyle.alert)
var nameTextField: UITextField?
alert.addTextField(configurationHandler: {(textField: UITextField!) in
textField.placeholder = "Name"
//๐ Forgive me father, for I have sinned. ๐
nameTextField = textField
})
alert.addAction(UIAlertAction(title: "Start", style: UIAlertActionStyle.default) {(action: UIAlertAction) in
self.name = nameTextField?.text
self.chatView?.textField.becomeFirstResponder()
})
self.present(alert, animated: true, completion: nil)
}
}
// MARK: ActionCableClient
extension ChatViewController {
func setupClient() -> Void {
self.client.willConnect = {
print("Will Connect")
}
self.client.onConnected = {
print("Connected to \(self.client.url)")
}
self.client.onDisconnected = {(error: ConnectionError?) in
print("Disconected with error: \(String(describing: error))")
}
self.client.willReconnect = {
print("Reconnecting to \(self.client.url)")
return true
}
self.channel = client.create(ChatViewController.ChannelIdentifier)
self.channel?.onSubscribed = {
print("Subscribed to \(ChatViewController.ChannelIdentifier)")
}
self.channel?.onReceive = {(data: Any?, error: Error?) in
if let error = error {
print(error.localizedDescription)
return
}
let JSONObject = JSON(data!)
let msg = ChatMessage(name: JSONObject["name"].string!, message: JSONObject["message"].string!)
self.history.append(msg)
self.chatView?.tableView.reloadData()
// Scroll to our new message!
if (msg.name == self.name) {
let indexPath = IndexPath(row: self.history.count - 1, section: 0)
self.chatView?.tableView.scrollToRow(at: indexPath, at: .bottom, animated: false)
}
}
self.client.connect()
}
func sendMessage(_ message: String) {
let prettyMessage = message.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
if (!prettyMessage.isEmpty) {
print("Sending Message: \(ChatViewController.ChannelIdentifier)#\(ChatViewController.ChannelAction)")
_ = self.channel?.action(ChatViewController.ChannelAction, with:
["name": self.name!, "message": prettyMessage]
)
}
}
}
//MARK: UITextFieldDelegate
extension ChatViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.sendMessage(textField.text!)
textField.text = ""
return true
}
}
//MARK: UITableViewDelegate
extension ChatViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let message = history[(indexPath as NSIndexPath).row]
let attrString = message.attributedString()
let width = self.chatView?.tableView.bounds.size.width;
let rect = attrString.boundingRect(with: CGSize(width: width! - (ChatCell.Inset * 2.0), height: CGFloat.greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading], context:nil)
return rect.size.height + (ChatCell.Inset * 2.0)
}
}
//MARK: UITableViewDataSource
extension ChatViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return history.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ChatViewController.MessageCellIdentifier, for: indexPath) as! ChatCell
let msg = history[(indexPath as NSIndexPath).row]
cell.message = msg
return cell
}
}
//MARK: ChatMessage
struct ChatMessage {
var name: String
var message: String
func attributedString() -> NSAttributedString {
let messageString: String = "\(self.name) \(self.message)"
let nameRange = NSRange(location: 0, length: self.name.characters.count)
let nonNameRange = NSRange(location: nameRange.length, length: messageString.characters.count - nameRange.length)
let string: NSMutableAttributedString = NSMutableAttributedString(string: messageString)
string.addAttribute(NSAttributedStringKey.font,
value: UIFont.boldSystemFont(ofSize: 18.0),
range: nameRange)
string.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 18.0), range: nonNameRange)
return string
}
}
| mit | 9711804b0108b15712373f1e6f643370 | 37.26 | 137 | 0.648327 | 5.020997 | false | false | false | false |
codeOfRobin/ShadowKit | Example/MyViewController.swift | 1 | 1977 | //
// ViewController.swift
// Example
//
// Created by Robin Malhotra on 25/12/16.
// Copyright ยฉ 2016 Robin Malhotra. All rights reserved.
//
//: Playground - noun: a place where people can play
import UIKit
import CoreImage
import ShadowKit
let saraImage = #imageLiteral(resourceName: "sara")
enum ShadowInput {
case view(view: UIView)
case image(image: UIImage)
}
func shadowMaker(input: ShadowInput) -> UIImage {
switch input {
case .view(view: let view):
return UIImage()
case .image(image: let image):
print(image)
return image
}
}
class MyViewController: UIViewController {
let imgView = UIImageView(image: saraImage)
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
view.addSubview(imgView)
imgView.frame = CGRect(x: 40, y: 80, width: 295, height: 295)
imgView.layer.cornerRadius = 8
imgView.clipsToBounds = true
let newImageView = UIImageView(frame: CGRect(x: 10, y: 60, width: 355, height: 355))
saraImage.applyingShadowBlur({ (blurredImage) in
UIView.animate(withDuration: 0.47, animations: {
self.imgView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
newImageView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
}, completion: {(completed) in
//FIXME: Chaining animations this way is terrible. Use keyframe animations instead.
newImageView.image = blurredImage
self.view.insertSubview(newImageView, belowSubview: self.imgView)
newImageView.alpha = 0.4
UIView.animate(withDuration: 0.3, delay: 0, options: [], animations: {
newImageView.layer.cornerRadius = 20
newImageView.alpha = 1.0
newImageView.transform = .identity
self.imgView.transform = .identity
}, completion: nil)
})
})
}
}
| mit | 18703bd8c0bc6223fc5c2a384d7019bf | 28.492537 | 99 | 0.631579 | 4.116667 | false | false | false | false |
alblue/swift | test/SILGen/class_bound_protocols.swift | 1 | 12236 |
// RUN: %target-swift-emit-silgen -enable-sil-ownership -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck %s
enum Optional<T> {
case some(T)
case none
}
precedencegroup AssignmentPrecedence {}
typealias AnyObject = Builtin.AnyObject
// -- Class-bound archetypes and existentials are *not* address-only and can
// be manipulated using normal reference type value semantics.
protocol NotClassBound {
func notClassBoundMethod()
}
protocol ClassBound : class {
func classBoundMethod()
}
protocol ClassBound2 : class {
func classBound2Method()
}
class ConcreteClass : NotClassBound, ClassBound, ClassBound2 {
func notClassBoundMethod() {}
func classBoundMethod() {}
func classBound2Method() {}
}
class ConcreteSubclass : ConcreteClass { }
// CHECK-LABEL: sil hidden @$ss19class_bound_generic{{[_0-9a-zA-Z]*}}F
func class_bound_generic<T : ClassBound>(x: T) -> T {
var x = x
// CHECK: bb0([[X:%.*]] : @guaranteed $T):
// CHECK: [[X_ADDR:%.*]] = alloc_box $<ฯ_0_0 where ฯ_0_0 : ClassBound> { var ฯ_0_0 } <T>
// CHECK: [[PB:%.*]] = project_box [[X_ADDR]]
// CHECK: [[X_COPY:%.*]] = copy_value [[X]]
// CHECK: store [[X_COPY]] to [init] [[PB]]
return x
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X1:%.*]] = load [copy] [[READ]]
// CHECK: destroy_value [[X_ADDR]]
// CHECK: return [[X1]]
}
// CHECK-LABEL: sil hidden @$ss21class_bound_generic_2{{[_0-9a-zA-Z]*}}F
func class_bound_generic_2<T : ClassBound & NotClassBound>(x: T) -> T {
var x = x
// CHECK: bb0([[X:%.*]] : @guaranteed $T):
// CHECK: [[X_ADDR:%.*]] = alloc_box $<ฯ_0_0 where ฯ_0_0 : ClassBound, ฯ_0_0 : NotClassBound> { var ฯ_0_0 } <T>
// CHECK: [[PB:%.*]] = project_box [[X_ADDR]]
// CHECK: [[X_COPY:%.*]] = copy_value [[X]]
// CHECK: store [[X_COPY]] to [init] [[PB]]
return x
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X1:%.*]] = load [copy] [[READ]]
// CHECK: return [[X1]]
}
// CHECK-LABEL: sil hidden @$ss20class_bound_protocol{{[_0-9a-zA-Z]*}}F
func class_bound_protocol(x: ClassBound) -> ClassBound {
var x = x
// CHECK: bb0([[X:%.*]] : @guaranteed $ClassBound):
// CHECK: [[X_ADDR:%.*]] = alloc_box ${ var ClassBound }
// CHECK: [[PB:%.*]] = project_box [[X_ADDR]]
// CHECK: [[X_COPY:%.*]] = copy_value [[X]]
// CHECK: store [[X_COPY]] to [init] [[PB]]
return x
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*ClassBound
// CHECK: [[X1:%.*]] = load [copy] [[READ]]
// CHECK: return [[X1]]
}
// CHECK-LABEL: sil hidden @$ss32class_bound_protocol_composition{{[_0-9a-zA-Z]*}}F
func class_bound_protocol_composition(x: ClassBound & NotClassBound)
-> ClassBound & NotClassBound {
var x = x
// CHECK: bb0([[X:%.*]] : @guaranteed $ClassBound & NotClassBound):
// CHECK: [[X_ADDR:%.*]] = alloc_box ${ var ClassBound & NotClassBound }
// CHECK: [[PB:%.*]] = project_box [[X_ADDR]]
// CHECK: [[X_COPY:%.*]] = copy_value [[X]]
// CHECK: store [[X_COPY]] to [init] [[PB]]
return x
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*ClassBound & NotClassBound
// CHECK: [[X1:%.*]] = load [copy] [[READ]]
// CHECK: return [[X1]]
}
// CHECK-LABEL: sil hidden @$ss19class_bound_erasure{{[_0-9a-zA-Z]*}}F
func class_bound_erasure(x: ConcreteClass) -> ClassBound {
return x
// CHECK: [[PROTO:%.*]] = init_existential_ref {{%.*}} : $ConcreteClass, $ClassBound
// CHECK: return [[PROTO]]
}
// CHECK-LABEL: sil hidden @$ss30class_bound_existential_upcast1xs10ClassBound_psAC_s0E6Bound2p_tF :
func class_bound_existential_upcast(x: ClassBound & ClassBound2)
-> ClassBound {
return x
// CHECK: bb0([[ARG:%.*]] : @guaranteed $ClassBound & ClassBound2):
// CHECK: [[OPENED:%.*]] = open_existential_ref [[ARG]] : $ClassBound & ClassBound2 to [[OPENED_TYPE:\$@opened(.*) ClassBound & ClassBound2]]
// CHECK: [[OPENED_COPY:%.*]] = copy_value [[OPENED]]
// CHECK: [[PROTO:%.*]] = init_existential_ref [[OPENED_COPY]] : [[OPENED_TYPE]] : [[OPENED_TYPE]], $ClassBound
// CHECK: return [[PROTO]]
}
// CHECK: } // end sil function '$ss30class_bound_existential_upcast1xs10ClassBound_psAC_s0E6Bound2p_tF'
// CHECK-LABEL: sil hidden @$ss41class_bound_to_unbound_existential_upcast1xs13NotClassBound_ps0hI0_sACp_tF :
// CHECK: bb0([[ARG0:%.*]] : @trivial $*NotClassBound, [[ARG1:%.*]] : @guaranteed $ClassBound & NotClassBound):
// CHECK: [[X_OPENED:%.*]] = open_existential_ref [[ARG1]] : $ClassBound & NotClassBound to [[OPENED_TYPE:\$@opened(.*) ClassBound & NotClassBound]]
// CHECK: [[PAYLOAD_ADDR:%.*]] = init_existential_addr [[ARG0]] : $*NotClassBound, [[OPENED_TYPE]]
// CHECK: [[X_OPENED_COPY:%.*]] = copy_value [[X_OPENED]]
// CHECK: store [[X_OPENED_COPY]] to [init] [[PAYLOAD_ADDR]]
func class_bound_to_unbound_existential_upcast
(x: ClassBound & NotClassBound) -> NotClassBound {
return x
}
// CHECK-LABEL: sil hidden @$ss18class_bound_method1xys10ClassBound_p_tF :
// CHECK: bb0([[ARG:%.*]] : @guaranteed $ClassBound):
func class_bound_method(x: ClassBound) {
var x = x
x.classBoundMethod()
// CHECK: [[XBOX:%.*]] = alloc_box ${ var ClassBound }, var, name "x"
// CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: store [[ARG_COPY]] to [init] [[XBOX_PB]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[XBOX_PB]] : $*ClassBound
// CHECK: [[X:%.*]] = load [copy] [[READ]] : $*ClassBound
// CHECK: [[PROJ:%.*]] = open_existential_ref [[X]] : $ClassBound to $[[OPENED:@opened(.*) ClassBound]]
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED]], #ClassBound.classBoundMethod!1
// CHECK: apply [[METHOD]]<[[OPENED]]>([[PROJ]])
// CHECK: destroy_value [[PROJ]]
// CHECK: destroy_value [[XBOX]]
}
// CHECK: } // end sil function '$ss18class_bound_method1xys10ClassBound_p_tF'
// rdar://problem/31858378
struct Value {}
protocol HasMutatingMethod {
mutating func mutateMe()
var mutatingCounter: Value { get set }
var nonMutatingCounter: Value { get nonmutating set }
}
protocol InheritsMutatingMethod : class, HasMutatingMethod {}
func takesInOut<T>(_: inout T) {}
// CHECK-LABEL: sil hidden @$ss27takesInheritsMutatingMethod1x1yys0bcD0_pz_s5ValueVtF : $@convention(thin) (@inout InheritsMutatingMethod, Value) -> () {
func takesInheritsMutatingMethod(x: inout InheritsMutatingMethod,
y: Value) {
// CHECK: [[X_ADDR:%.*]] = begin_access [modify] [unknown] %0 : $*InheritsMutatingMethod
// CHECK-NEXT: [[X_VALUE:%.*]] = load [copy] [[X_ADDR]] : $*InheritsMutatingMethod
// CHECK-NEXT: [[X_PAYLOAD:%.*]] = open_existential_ref [[X_VALUE]] : $InheritsMutatingMethod to $@opened("{{.*}}") InheritsMutatingMethod
// CHECK-NEXT: [[TEMPORARY:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod
// CHECK-NEXT: store [[X_PAYLOAD]] to [init] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod
// CHECK-NEXT: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") InheritsMutatingMethod, #HasMutatingMethod.mutateMe!1 : <Self where Self : HasMutatingMethod> (inout Self) -> () -> (), [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@convention(witness_method: HasMutatingMethod) <ฯ_0_0 where ฯ_0_0 : HasMutatingMethod> (@inout ฯ_0_0) -> ()
// CHECK-NEXT: apply [[METHOD]]<@opened("{{.*}}") InheritsMutatingMethod>([[TEMPORARY]]) : $@convention(witness_method: HasMutatingMethod) <ฯ_0_0 where ฯ_0_0 : HasMutatingMethod> (@inout ฯ_0_0) -> ()
// CHECK-NEXT: [[X_PAYLOAD:%.*]] = load [take] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod
// CHECK-NEXT: [[X_VALUE:%.*]] = init_existential_ref [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@opened("{{.*}}") InheritsMutatingMethod, $InheritsMutatingMethod
// CHECK-NEXT: assign [[X_VALUE]] to [[X_ADDR]] : $*InheritsMutatingMethod
// CHECK-NEXT: end_access [[X_ADDR]] : $*InheritsMutatingMethod
// CHECK-NEXT: dealloc_stack [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod
x.mutateMe()
// CHECK-NEXT: [[RESULT_BOX:%.*]] = alloc_stack $Value
// CHECK-NEXT: [[RESULT:%.*]] = mark_uninitialized [var] [[RESULT_BOX]] : $*Value
// CHECK-NEXT: [[X_ADDR:%.*]] = begin_access [read] [unknown] %0 : $*InheritsMutatingMethod
// CHECK-NEXT: [[X_VALUE:%.*]] = load [copy] [[X_ADDR]] : $*InheritsMutatingMethod
// CHECK-NEXT: [[X_PAYLOAD:%.*]] = open_existential_ref [[X_VALUE]] : $InheritsMutatingMethod to $@opened("{{.*}}") InheritsMutatingMethod
// CHECK-NEXT: [[TEMPORARY:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod
// CHECK-NEXT: store [[X_PAYLOAD]] to [init] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod
// CHECK-NEXT: [[X_PAYLOAD_RELOADED:%.*]] = load_borrow [[TEMPORARY]]
//
// ** *NOTE* This extra copy is here since RValue invariants enforce that all
// ** loadable objects are actually loaded. So we form the RValue and
// ** load... only to then need to store the value back in a stack location to
// ** pass to an in_guaranteed method. PredictableMemOpts is able to handle this
// ** type of temporary codegen successfully.
// CHECK-NEXT: [[TEMPORARY_2:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod
// CHECK-NEXT: store_borrow [[X_PAYLOAD_RELOADED:%.*]] to [[TEMPORARY_2]]
//
// CHECK-NEXT: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") InheritsMutatingMethod, #HasMutatingMethod.mutatingCounter!getter.1 : <Self where Self : HasMutatingMethod> (Self) -> () -> Value, [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@convention(witness_method: HasMutatingMethod) <ฯ_0_0 where ฯ_0_0 : HasMutatingMethod> (@in_guaranteed ฯ_0_0) -> Value
// CHECK-NEXT: [[RESULT_VALUE:%.*]] = apply [[METHOD]]<@opened("{{.*}}") InheritsMutatingMethod>([[TEMPORARY_2]]) : $@convention(witness_method: HasMutatingMethod) <ฯ_0_0 where ฯ_0_0 : HasMutatingMethod> (@in_guaranteed ฯ_0_0) -> Value
// CHECK-NEXT: dealloc_stack [[TEMPORARY_2]]
// CHECK-NEXT: end_borrow
// CHECK-NEXT: destroy_addr
// CHECK-NEXT: end_access [[X_ADDR]] : $*InheritsMutatingMethod
// CHECK-NEXT: assign [[RESULT_VALUE]] to [[RESULT]] : $*Value
// CHECK-NEXT: dealloc_stack [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod
// CHECK-NEXT: dealloc_stack [[RESULT_BOX]] : $*Value
_ = x.mutatingCounter
// CHECK-NEXT: [[X_ADDR:%.*]] = begin_access [modify] [unknown] %0 : $*InheritsMutatingMethod
// CHECK-NEXT: [[X_VALUE:%.*]] = load [copy] [[X_ADDR]] : $*InheritsMutatingMethod
// CHECK-NEXT: [[X_PAYLOAD:%.*]] = open_existential_ref [[X_VALUE]] : $InheritsMutatingMethod to $@opened("{{.*}}") InheritsMutatingMethod
// CHECK-NEXT: [[TEMPORARY:%.*]] = alloc_stack $@opened("{{.*}}") InheritsMutatingMethod
// CHECK-NEXT: store [[X_PAYLOAD]] to [init] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod
// CHECK-NEXT: [[METHOD:%.*]] = witness_method $@opened("{{.*}}") InheritsMutatingMethod, #HasMutatingMethod.mutatingCounter!setter.1 : <Self where Self : HasMutatingMethod> (inout Self) -> (Value) -> (), [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@convention(witness_method: HasMutatingMethod) <ฯ_0_0 where ฯ_0_0 : HasMutatingMethod> (Value, @inout ฯ_0_0) -> ()
// CHECK-NEXT: apply [[METHOD]]<@opened("{{.*}}") InheritsMutatingMethod>(%1, [[TEMPORARY]]) : $@convention(witness_method: HasMutatingMethod) <ฯ_0_0 where ฯ_0_0 : HasMutatingMethod> (Value, @inout ฯ_0_0) -> ()
// CHECK-NEXT: [[X_PAYLOAD:%.*]] = load [take] [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod
// CHECK-NEXT: [[X_VALUE:%.*]] = init_existential_ref [[X_PAYLOAD]] : $@opened("{{.*}}") InheritsMutatingMethod : $@opened("{{.*}}") InheritsMutatingMethod, $InheritsMutatingMethod
// CHECK-NEXT: assign [[X_VALUE]] to [[X_ADDR]] : $*InheritsMutatingMethod
// CHECK-NEXT: end_access [[X_ADDR]] : $*InheritsMutatingMethod
// CHECK-NEXT: dealloc_stack [[TEMPORARY]] : $*@opened("{{.*}}") InheritsMutatingMethod
x.mutatingCounter = y
takesInOut(&x.mutatingCounter)
_ = x.nonMutatingCounter
x.nonMutatingCounter = y
takesInOut(&x.nonMutatingCounter)
}
| apache-2.0 | acae0d607d5eed3247f31e4c1775470e | 54.757991 | 382 | 0.630579 | 3.680229 | false | false | false | false |
dreamsxin/swift | validation-test/compiler_crashers_fixed/00093-swift-boundgenerictype-get.swift | 11 | 808 | // 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
struct j<l : o> {
k b: l
}
func a<l>() -> [j<l>] {
return []
}
f
k)
func f<l>() -> (l, l -> l) -> l {
l j l.n = {
}
{
l) {
n }
}
protocol f {
class func n()
}
class l: f{ class func n {}
func a<i>() {
b b {
l j
}
}
class a<f : b, l : b m f.l == l> {
}
protocol b {
typealias l
typealias k
}
struct j<n : b> : b {
typealias l = n
typealias k = a<j<n>, l>
}
| apache-2.0 | e9e89910821a9bf7ad6ea8f2bb5d670c | 18.238095 | 78 | 0.57302 | 2.896057 | false | false | false | false |
kenwilcox/TheForecaster | WeatherShare/GlobalConstants.swift | 1 | 1162 | //
// GlobalConstants.swift
// TheForecaster
//
// Created by Kenneth Wilcox on 5/25/15.
// Copyright (c) 2015 Kenneth Wilcox. All rights reserved.
//
import Foundation
public struct GlobalConstants {
public struct NotificationNames {
public static let locationDidUpdate = "LOCATION_DID_UPDATE"
}
public struct LocationDictionary {
public static let latitude = "latitude"
public static let longitude = "longitude"
public static let city = "city"
public static let state = "state"
public static let country = "country"
public static let timestamp = "lastUpdatedAt"
}
public struct ForecastNetwork {
public static let currently = "currently"
public static let icon = "icon"
public static let temperature = "temperature"
public static let summary = "summary"
public static let hourly = "hourly"
public static let data = "data"
public static let time = "time"
public static let precipProbability = "precipProbability"
}
public struct NSUserDefaults {
public static let suiteName = "group.TheForecaster.k3nx.com"
public static let locationInfo = "LOCATION_INFO"
}
} | mit | e0ad079980653ba749446b079d356944 | 27.365854 | 64 | 0.70568 | 4.418251 | false | false | false | false |
jshier/SwiftyNotificationCenter | Example/ViewController.swift | 1 | 3908 | //
// ViewController.swift
// SwiftyNotificationCenterExample
//
// Created by Jon Shier on 10/31/15.
// Copyright ยฉ 2015 Jon Shier. All rights reserved.
//
import SwiftyNotificationCenter
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
SNC.addKeyboardWillShowObserver(self, handler: keyboardWillShowHandler)
SNC.addKeyboardDidShowObserver(self, handler: keyboardDidShowHandler)
SNC.addKeyboardWillHideObserver(self, handler: keyboardWillHideHandler)
SNC.addKeyboardDidHideObserver(self, handler: keyboardDidHideHandler)
SNC.addKeyboardWillChangeFrameObserver(self, handler: keyboardWillChangeFrameHandler)
SNC.addKeyboardDidChangeFrameObserver(self, handler: keyboardDidChangeFrameHandler)
}
@IBAction func endEditing(sender: UIButton) {
SNC.removeKeyboardObserver(self)
view.endEditing(true)
}
func keyboardWillShowHandler(keyboardNotification: KeyboardNotification) {
print(keyboardNotification)
// print("*** Removing willShow observer. ***")
// SNC.removeKeyboardWillShowObserver(self)
}
func keyboardDidShowHandler(keyboardNotification: KeyboardNotification) {
print(keyboardNotification)
// print("*** Removing didShow observer. ***")
// SNC.removeKeyboardDidShowObserver(self)
}
func keyboardWillHideHandler(keyboardNotification: KeyboardNotification) {
print(keyboardNotification)
// print("*** Removing willHide observer. ***")
// SNC.removeKeyboardWillHideObserver(self)
}
func keyboardDidHideHandler(keyboardNotification: KeyboardNotification) {
print(keyboardNotification)
// print("*** Removing didHide observer. ***")
// SNC.removeKeyboardDidHideObserver(self)
}
func keyboardWillChangeFrameHandler(keyboardNotification: KeyboardNotification) {
print(keyboardNotification)
// print("*** Removing willChangeFrame observer. ***")
// SNC.removeKeyboardWillChangeFrameObserver(self)
}
func keyboardDidChangeFrameHandler(keyboardNotification: KeyboardNotification) {
print(keyboardNotification)
// print("*** Removing didChangeFrame observer. ***")
// SNC.removeKeyboardDidChangeFrameObserver(self)
}
}
extension UIViewAnimationOptions : CustomStringConvertible {
public var description: String {
let propertyDescriptions = ["LayoutSubviews", "AllowUserInteraction", "BeginFromCurrentState", "Repeat", "Autoreverse", "OverrideInheritedDuration", "OverrideInheritedCurve", "AllowAnimatedContent", "ShowHideTransitionViews", "OverrideInheritedOptions"]
var properties = [String]()
for (index, description) in propertyDescriptions.enumerate() where contains(UIViewAnimationOptions(rawValue: UInt(1 << index))) {
properties.append(description)
}
let curveDescriptions = ["CurveEaseInOut", "CurveEaseIn", "CurveEaseOut", "CurveLinear"]
var curves = [String]()
for (index, description) in curveDescriptions.enumerate() where contains(UIViewAnimationOptions(rawValue: UInt(index << 16))) {
curves.append(description)
}
let transitionDescriptions = ["TransitionNone", "TransitionFlipFromLeft", "TransitionFlipFromRight", "TransitionCurlUp", "TransitionCurlDown", "TransitionCrossDissolve", "TransitionFlipFromTop", "TransitionFlipFromBottom"]
var transitions = [String]()
for (index, description) in transitionDescriptions.enumerate() where contains(UIViewAnimationOptions(rawValue: UInt(index << 20))) {
transitions.append(description)
}
return "UIViewAnimationOptions:\n\tProperties: \(properties.description)\n\tCurves: \(curves.description)\n\tTransitions: \(transitions.description)"
}
} | mit | 79fb5fa317e899c1cb75140e2c09f94b | 44.44186 | 261 | 0.713591 | 5.418863 | false | false | false | false |
fousa/trackkit | Sources/Classes/Parser/NMEA/Extensions/File+NMEA.swift | 1 | 650 | //
// TrackKit
//
// Created by Jelle Vandebeeck on 15/03/16.
//
extension File {
convenience init(nmea rawData: [[String]]) throws {
// Fetch the type version.
let version = try TrackTypeVersion(type: .nmea, version: "NMEA-0183")
self.init(type: .nmea, version: version)
let points = rawData.compactMap { Point(nmea: $0) }
let waypoints = points.filter { $0.recordType?.isWaypoint ?? false }
let records = points.filter { !($0.recordType?.isWaypoint ?? false) }
self.records = records.count > 0 ? records : nil
self.waypoints = waypoints.count > 0 ? waypoints : nil
}
}
| mit | b9763969a04255450d6f667422203780 | 28.545455 | 77 | 0.615385 | 3.611111 | false | false | false | false |
WickedColdfront/Slide-iOS | Slide for Reddit/SubredditReorderViewController.swift | 1 | 13012 | //
// SubredditReorderViewController.swift
// Slide for Reddit
//
// Created by Carlos Crane on 1/11/17.
// Copyright ยฉ 2017 Haptic Apps. All rights reserved.
//
import UIKit
class SubredditReorderViewController: UITableViewController {
var subs: [String] = []
var editItems: [UIBarButtonItem] = []
var normalItems: [UIBarButtonItem] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(SubredditCellView.classForCoder(), forCellReuseIdentifier: "sub")
self.tableView.isEditing = true
self.tableView.allowsSelectionDuringEditing = true
self.tableView.allowsMultipleSelectionDuringEditing = true
subs.append(contentsOf: Subscriptions.subreddits)
tableView.reloadData()
let sync = UIButton.init(type: .custom)
sync.setImage(UIImage.init(named: "sync"), for: UIControlState.normal)
sync.addTarget(self, action: #selector(self.sync(_:)), for: UIControlEvents.touchUpInside)
sync.frame = CGRect.init(x: -15, y: 0, width: 30, height: 30)
let syncB = UIBarButtonItem.init(customView: sync)
let top = UIButton.init(type: .custom)
top.setImage(UIImage.init(named: "upvote"), for: UIControlState.normal)
top.addTarget(self, action: #selector(self.top(_:)), for: UIControlEvents.touchUpInside)
top.frame = CGRect.init(x: -15, y: 0, width: 30, height: 30)
let topB = UIBarButtonItem.init(customView: top)
delete = UIButton.init(type: .custom)
delete.setImage(UIImage.init(named: "delete"), for: UIControlState.normal)
delete.addTarget(self, action: #selector(self.remove(_:)), for: UIControlEvents.touchUpInside)
delete.frame = CGRect.init(x: -15, y: 0, width: 30, height: 30)
let deleteB = UIBarButtonItem.init(customView: delete)
editItems = [deleteB, topB]
normalItems = [syncB]
self.navigationItem.rightBarButtonItems = normalItems
}
var delete = UIButton()
public static var changed = false
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
save(nil)
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func save(_ selector: AnyObject?){
SubredditReorderViewController.changed = true
Subscriptions.set(name: AccountController.currentName, subs: subs, completion: {
self.dismiss(animated: true, completion: nil)
})
}
override func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell?.backgroundColor = ColorUtil.foregroundColor
}
func sync(_ selector: AnyObject){
let alertController = UIAlertController(title: nil, message: "Syncing subscriptions...\n\n", preferredStyle: .alert)
let spinnerIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
spinnerIndicator.center = CGPoint(x: 135.0, y: 65.5)
spinnerIndicator.color = UIColor.black
spinnerIndicator.startAnimating()
alertController.view.addSubview(spinnerIndicator)
self.present(alertController,animated: true, completion: nil)
Subscriptions.getSubscriptionsFully(session: (UIApplication.shared.delegate as! AppDelegate).session!, completion: {(newSubs, newMultis) in
let end = self.subs.count
for s in newSubs {
if(!self.subs.contains(s.displayName)){
self.subs.append(s.displayName)
}
}
for m in newMultis {
if(!self.subs.contains("/m/" + m.displayName)){
self.subs.append("/m/" + m.displayName)
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
let indexPath = IndexPath.init(row: end, section: 0)
self.tableView.scrollToRow(at: indexPath,
at: UITableViewScrollPosition.top, animated: true)
alertController.dismiss(animated: true, completion: nil)
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: โ Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return subs.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let thing = subs[indexPath.row]
var cell: SubredditCellView?
let c = tableView.dequeueReusableCell(withIdentifier: "sub", for: indexPath) as! SubredditCellView
c.setSubreddit(subreddit: thing, nav: nil)
cell = c
cell?.backgroundColor = ColorUtil.foregroundColor
return cell!
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return .delete
}
override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return true
}
var stuck = ["all", "frontpage", "slide_ios"]
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return !stuck.contains(subs[indexPath.row])
}
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let itemToMove:String = subs[sourceIndexPath.row]
subs.remove(at: sourceIndexPath.row)
subs.insert(itemToMove, at: destinationIndexPath.row)
}
func top(_ selector: AnyObject){
if let rows = tableView.indexPathsForSelectedRows{
var top : [String] = []
for i in rows {
top.append(self.subs[i.row])
self.tableView.deselectRow(at: i, animated: true)
}
self.subs = self.subs.filter({ (input) -> Bool in
return !top.contains(input)
})
self.subs.insert(contentsOf: top, at: 0)
tableView.reloadData()
let indexPath = IndexPath.init(row: 0, section: 0)
self.tableView.scrollToRow(at: indexPath,
at: UITableViewScrollPosition.top, animated: true)
}
}
func remove(_ selector: AnyObject){
if let rows = tableView.indexPathsForSelectedRows{
let actionSheetController: UIAlertController = UIAlertController(title: "Remove subscriptions", message: "", preferredStyle: .actionSheet)
var cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel")
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "Remove and unsubscribe", style: .default) { action -> Void in
//todo unsub
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "Just remove", style: .default) { action -> Void in
var top : [String] = []
for i in rows {
top.append(self.subs[i.row])
}
self.subs = self.subs.filter({ (input) -> Bool in
return !top.contains(input)
})
self.tableView.reloadData()
}
actionSheetController.addAction(cancelActionButton)
actionSheetController.modalPresentationStyle = .popover
if let presenter = actionSheetController.popoverPresentationController {
presenter.sourceView = delete
presenter.sourceRect = delete.bounds
}
self.present(actionSheetController, animated: true, completion: nil)
}
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if(tableView.indexPathsForSelectedRows != nil && !tableView.indexPathsForSelectedRows!.isEmpty){
print(tableView.indexPathsForSelectedRows!.count)
self.navigationItem.setRightBarButtonItems(editItems, animated: true)
} else {
self.navigationItem.setRightBarButtonItems(normalItems, animated: true)
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if(!tableView.indexPathsForSelectedRows!.isEmpty){
print(tableView.indexPathsForSelectedRows!.count)
self.navigationItem.setRightBarButtonItems(editItems, animated: true)
} else {
self.navigationItem.setRightBarButtonItems(normalItems, animated: true)
}
/* deprecated tableView.deselectRow(at: indexPath, animated: true)
let item = subs[indexPath.row]
let actionSheetController: UIAlertController = UIAlertController(title: item, message: "", preferredStyle: .actionSheet)
var cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel")
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "Unsubscribe", style: .default) { action -> Void in
//todo unsub
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "Move to top", style: .default) { action -> Void in
self.subs.remove(at: indexPath.row)
self.subs.insert(item, at: 0)
tableView.reloadData()
let indexPath = IndexPath.init(row: 0, section: 0)
self.tableView.scrollToRow(at: indexPath,
at: UITableViewScrollPosition.top, animated: true)
}
actionSheetController.addAction(cancelActionButton)
self.present(actionSheetController, animated: true, completion: nil)*/
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
if editingStyle == .delete
{
subs.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .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
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 9f40b1ea98a54d9c56f7dac415c4f42c | 39.027692 | 147 | 0.634023 | 5.256162 | false | false | false | false |
roberthein/BouncyLayout | example/BouncyLayout/ViewController.swift | 1 | 5851 | import UIKit
import BouncyLayout
class ViewController: UIViewController {
let numberOfItems = 50
var randomCellStyle: CellStyle { return arc4random_uniform(10) % 2 == 0 ? .blue : .gray }
lazy var style: [CellStyle] = { (0..<self.numberOfItems).map { _ in self.randomCellStyle } }()
lazy var topOffset: [CGFloat] = { (0..<self.numberOfItems).map { _ in CGFloat(arc4random_uniform(250)) } }()
lazy var sizes: [CGSize] = {
guard let example = self.example else { return [] }
return (0..<self.numberOfItems).map { _ in
switch example {
case .chatMessage: return CGSize(width: UIScreen.main.bounds.width - 20, height: 40)
case .photosCollection: return CGSize(width: floor((UIScreen.main.bounds.width - (5 * 10)) / 4), height: floor((UIScreen.main.bounds.width - (5 * 10)) / 4))
case .barGraph: return CGSize(width: 40, height: 400)
}
}
}()
var insets: UIEdgeInsets {
guard let example = self.example else { return .zero }
switch example {
case .chatMessage: return UIEdgeInsets(top: 200, left: 0, bottom: 200, right: 0)
case .photosCollection: return UIEdgeInsets(top: 200, left: 0, bottom: 200, right: 0)
case .barGraph: return UIEdgeInsets(top: 0, left: 200, bottom: 0, right: 200)
}
}
var additionalInsets: UIEdgeInsets {
guard let example = self.example else { return .zero }
switch example {
case .chatMessage: return UIEdgeInsets(top: 5, left: 0, bottom: 5, right: 0)
case .photosCollection: return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
case .barGraph: return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
}
}
lazy var layout = BouncyLayout(style: .regular)
lazy var collectionView: UICollectionView = {
if self.example == .barGraph {
self.layout.scrollDirection = .horizontal
}
let view = UICollectionView(frame: .zero, collectionViewLayout: self.layout)
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = self.backgroundColor(for: self.example)
view.showsVerticalScrollIndicator = false
view.showsHorizontalScrollIndicator = false
view.delegate = self
view.dataSource = self
view.register(Cell.self, forCellWithReuseIdentifier: Cell.reuseIdentifier)
return view
}()
func backgroundColor(for example: Example) -> UIColor {
switch example {
case .chatMessage: return UIColor(red: 0/255, green: 98/255, blue: 239/255, alpha: 1)
case .photosCollection: return UIColor(red: 0/255, green: 153/255, blue: 202/255, alpha: 1)
case .barGraph: return UIColor(red: 0/255, green: 208/255, blue: 166/255, alpha: 1)
}
}
var example: Example!
convenience init(example: Example) {
self.init()
self.example = example
}
override func viewDidLoad() {
super.viewDidLoad()
title = example.title
view.backgroundColor = .white
view.clipsToBounds = true
collectionView.contentInset = UIEdgeInsets(top: insets.top + additionalInsets.top, left: insets.left + additionalInsets.left, bottom: insets.bottom + additionalInsets.bottom, right: insets.right + additionalInsets.right)
collectionView.scrollIndicatorInsets = UIEdgeInsets(top: insets.top, left: insets.left, bottom: insets.bottom, right: insets.right)
view.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: -insets.top),
collectionView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: -insets.left),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: insets.bottom),
collectionView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: insets.right)
])
if #available(iOS 11.0, *) {
navigationController?.navigationBar.prefersLargeTitles = false
}
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfItems
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return collectionView.dequeueReusableCell(withReuseIdentifier: Cell.reuseIdentifier, for: indexPath)
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let cell = cell as? Cell else { return }
cell.setCell(style: style[indexPath.row], example: example)
if example == .barGraph {
cell.top.constant = topOffset[indexPath.row]
}
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return sizes[indexPath.row]
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return example == .photosCollection ? 10 : 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return example == .photosCollection ? 10 : 0
}
}
| mit | 9f97229148047327fb39d3b720def839 | 41.398551 | 228 | 0.65852 | 4.950085 | false | false | false | false |
danielsanfr/hackatruck-apps-project | HACKATRUCK Apps/AppSearchTableViewCell.swift | 1 | 1026 | //
// AppSearchTableViewCell.swift
// HACKATRUCK Apps
//
// Created by Student on 3/9/17.
// Copyright ยฉ 2017 Daniel San. All rights reserved.
//
import UIKit
class AppSearchTableViewCell: UITableViewCell {
@IBOutlet weak var name: UILabel!
@IBOutlet weak var company: UILabel!
@IBOutlet weak var likes: UILabel!
private var app = App()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func onOpenInfo() {
let url = URL(string: app.relevantLink)!
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url)
}
}
func bind(_ app: App) {
self.app = app
name.text = app.name
company.text = app.company
likes.text = "\(app.likes) Likes"
}
}
| unlicense | 166726fb84303ade78a22830ce315d55 | 22.837209 | 65 | 0.612683 | 4.235537 | false | false | false | false |
dominikoledzki/TextDrawing | TextDrawingTests/SequenceExtensionsTests.swift | 1 | 938 | //
// SequenceExtensionsTests.swift
// TextDrawing
//
// Created by Dominik Olฤdzki on 04/02/2017.
// Copyright ยฉ 2017 Dominik Oledzki. All rights reserved.
//
import XCTest
class SequenceExtensionsTests: XCTestCase {
func testLastElementWhichSquareIsLessThan50() {
let x = 0..<20
let lastIntegerWhichSquareIsLessThan50 = x.last { (element) -> Bool in
return element * element < 50
}
XCTAssertEqual(lastIntegerWhichSquareIsLessThan50, 7)
}
func testNoElementPasses() {
let x = 100..<200
let lastPassing = x.last { (element) -> Bool in
return element > 300
}
XCTAssertNil(lastPassing)
}
func testAllElementsPassing() {
let x = (10..<20).map { $0 * 2 }
let lastEven = x.last { (element) -> Bool in
return element % 2 == 0
}
XCTAssertEqual(lastEven, x.last)
}
}
| mit | 2be76c142dedc8f2b51cddb38999a99c | 25 | 78 | 0.592949 | 4.069565 | false | true | false | false |
richardpiazza/SOSwift | Sources/SOSwift/ListItemOrThingOrText.swift | 1 | 2493 | import Foundation
import CodablePlus
public enum ListItemOrThingOrText: Codable {
case listItem(value: ListItem)
case thing(value: Thing)
case text(value: String)
public init(_ value: ListItem) {
self = .listItem(value: value)
}
public init(_ value: Thing) {
self = .thing(value: value)
}
public init(_ value: String) {
self = .text(value: value)
}
public init(from decoder: Decoder) throws {
var dictionary: [String : Any]?
do {
let jsonContainer = try decoder.container(keyedBy: DictionaryKeys.self)
dictionary = try jsonContainer.decode(Dictionary<String, Any>.self)
} catch {
}
guard let jsonDictionary = dictionary else {
let container = try decoder.singleValueContainer()
let value = try container.decode(String.self)
self = .text(value: value)
return
}
guard let type = jsonDictionary[SchemaKeys.type.rawValue] as? String else {
throw SchemaError.typeDecodingError
}
let container = try decoder.singleValueContainer()
switch type {
case ListItem.schemaName:
let value = try container.decode(ListItem.self)
self = .listItem(value: value)
case Thing.schemaName:
let value = try container.decode(Thing.self)
self = .thing(value: value)
default:
throw SchemaError.typeDecodingError
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .listItem(let value):
try container.encode(value)
case .thing(let value):
try container.encode(value)
case .text(let value):
try container.encode(value)
}
}
public var listItem: ListItem? {
switch self {
case .listItem(let value):
return value
default:
return nil
}
}
public var thing: Thing? {
switch self {
case .thing(let value):
return value
default:
return nil
}
}
public var text: String? {
switch self {
case .text(let value):
return value
default:
return nil
}
}
}
| mit | 863720d9fdb586d22a5d5ef06c9d540b | 25.242105 | 83 | 0.541115 | 4.936634 | false | false | false | false |
linggaozhen/Living | LivingApplication/LivingApplication/Classess/Home/View/RecommerGameView.swift | 1 | 2219 | //
// RecommerGameView.swift
// LivingApplication
//
// Created by ioser on 17/5/22.
// Copyright ยฉ 2017ๅนด ioser. All rights reserved.
//------------------้ฆ้กตๅทฆๅณๆปๅจ็ๆธธๆView-----------------
import UIKit
private let gameCollectionCellID = "gameCollectionCellID"
class RecommerGameView: UIView {
@IBOutlet weak var gameColletionView: UICollectionView!
// ๆธธๆๆงๅถๅจไผ ่ฟๆฅ็ๆฐๆฎ
var gameControllerData : [GameModel]? {
didSet{
gameColletionView.reloadData()
}
}
// ๆจ่ๆงๅถๅจไผ ้่ฟๆฅ็ๆฐๆฎ
var gameGroupData : [AnchorGorup]?{
didSet{
gameGroupData?.removeFirst()
gameGroupData?.removeFirst()
let moreAnchor = AnchorGorup()
moreAnchor.tag_name = "ๆดๅค"
gameGroupData?.append(moreAnchor)
gameColletionView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
gameColletionView.dataSource = self
let layout = gameColletionView.collectionViewLayout as? UICollectionViewFlowLayout
layout?.itemSize = CGSize(width: 80, height: 90)
layout?.scrollDirection = .Horizontal
gameColletionView.registerNib(UINib(nibName: "GameCollectionViewCell",bundle: nil), forCellWithReuseIdentifier: gameCollectionCellID)
}
class func CreaterecommerGameView() -> RecommerGameView {
return (NSBundle.mainBundle().loadNibNamed("RecommerGameView", owner: nil, options: nil).first as? RecommerGameView)!
}
}
extension RecommerGameView : UICollectionViewDataSource{
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return gameGroupData?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(gameCollectionCellID, forIndexPath: indexPath) as? GameCollectionViewCell
let anchorModel = gameGroupData![indexPath.item]
cell?.dataModel = anchorModel
return cell!
}
} | apache-2.0 | caea876fa6b169ae7c0ed10703b4b274 | 32.578125 | 146 | 0.673184 | 4.90411 | false | false | false | false |
dxdp/Stage | Stage/PropertyBindings/MKMapViewBindings.swift | 1 | 2451 | //
// MKMapViewBindings.swift
// Stage
//
// Copyright ยฉ 2016 David Parton
//
// 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
public extension StageRegister {
public class func MapView(_ registration: StagePropertyRegistration) {
tap(registration) {
$0.registerBool("pitchEnabled")
.apply { (view: MKMapView, value) in view.isPitchEnabled = value }
$0.registerBool("rotateEnabled")
.apply { (view: MKMapView, value) in view.isRotateEnabled = value }
$0.registerBool("scrollEnabled")
.apply { (view: MKMapView, value) in view.isScrollEnabled = value }
$0.registerBool("zoomEnabled")
.apply { (view: MKMapView, value) in view.isZoomEnabled = value }
$0.registerBool("showsPointsOfInterest")
.apply { (view: MKMapView, value) in view.showsPointsOfInterest = value }
$0.registerBool("showsBuildings")
.apply { (view: MKMapView, value) in view.showsBuildings = value }
$0.registerBool("showsUserLocation")
.apply { (view: MKMapView, value) in view.showsUserLocation = value }
$0.register("mapType") { scanner in try MKMapType.create(using: scanner) }
.apply { (view: MKMapView, value) in view.mapType = value }
}
}
}
| mit | aaf632d8e5c757fb6f36f739bfd76b88 | 50.041667 | 105 | 0.670204 | 4.553903 | false | false | false | false |
admkopec/BetaOS | Kernel/Swift Extensions/Frameworks/CommonExtensions/CommonExtensions/String.swift | 1 | 2626 | //
// String.swift
// Kernel
//
// Created by Adam Kopeฤ on 10/13/17.
// Copyright ยฉ 2017-2018 Adam Kopeฤ. All rights reserved.
//
public extension String {
init(_ rawPtr: UnsafeRawPointer, maxLength: Int) {
if maxLength < 0 {
self = ""
return
}
let ptr = rawPtr.bindMemory(to: UInt8.self, capacity: maxLength)
var buffer: [UInt8]
buffer = [UInt8](UnsafeBufferPointer(start: ptr, count: maxLength))
buffer.append(UInt8(0))
self = String.init(cString: buffer)
}
init?<T: Collection>(utf16Characters: T) where T.Element == UInt16 {
var str = ""
var iterator = utf16Characters.makeIterator()
var utf16 = UTF16()
var done = false
while !done {
let r = utf16.decode(&iterator)
switch r {
case .emptyInput:
done = true
case let .scalarValue(val):
if val != "\0" {
str.append(Character(val))
} else {
done = true
}
case .error:
return nil
}
}
self = str
}
init?<T: Collection>(utf8Characters: T) where T.Element == UInt8 {
var str = ""
var iterator = utf8Characters.makeIterator()
var utf8 = UTF8()
var done = false
while !done {
let r = utf8.decode(&iterator)
switch r {
case .emptyInput:
done = true
case let .scalarValue(val):
if val != "\0" {
str.append(Character(val))
} else {
done = true
}
case .error:
return nil
}
}
self = str
}
func leftPadding(toLength: Int, withPad: String = " ") -> String {
guard toLength > self.count else { return self }
let padding = String(repeating: withPad, count: toLength - self.count)
return padding + self
}
func trim() -> String {
let array = Array(self)
var i = array.count - 1
while i > 0 {
if array[i] != " " && array[i] != "\0" {
break
}
i -= 1
}
var retStr = ""
var j = 0
for elem in array {
if j == i {
retStr.append(elem)
return retStr
}
retStr.append(elem)
j += 1
}
return retStr
}
}
| apache-2.0 | 1f5c44eb28af880c4cc22b2f39c3e0bd | 25.765306 | 78 | 0.445673 | 4.476109 | false | false | false | false |
pengjinning/AppKeFu_iOS_Demo_V4 | AppKeFuDemo7Swift/AppKeFuDemo7Swift/Controllers/KFSettingsViewController.swift | 1 | 4063 | //
// SettingsViewController.swift
// AppKeFuDemo7Swift
//
// Created by jack on 16/8/5.
// Copyright ยฉ 2016ๅนด appkefu.com. All rights reserved.
//
import Foundation
class KFSettingsViewController: UITableViewController {
override init(style: UITableViewStyle) {
super.init(style: style)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "่ฎพ็ฝฎ"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3;
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
if ((indexPath as NSIndexPath).row == 0) {
cell.textLabel?.text = NSLocalizedString("PlayVoiceWhenSendMessage", comment: "")
let sendMsgRingSwitch: UISwitch = UISwitch.init()
sendMsgRingSwitch.addTarget(self, action: #selector(switchSendMsgRing(_:)), for: UIControlEvents.valueChanged)
let flag: Bool = AppKeFuLib.sharedInstance().shouldRingWhenSendMessage()
if flag != true {
sendMsgRingSwitch.setOn(false, animated: true)
}
else {
sendMsgRingSwitch.setOn(true, animated: true)
}
cell.accessoryView = sendMsgRingSwitch;
}
else if ((indexPath as NSIndexPath).row == 1) {
cell.textLabel?.text = NSLocalizedString("PlayVoiceWhenReceiveMessage", comment: "")
let receiveMsgRingSwitch: UISwitch = UISwitch.init()
receiveMsgRingSwitch.addTarget(self, action: #selector(switchReceiveMsgRing(_:)), for: UIControlEvents.valueChanged)
let flag: Bool = AppKeFuLib.sharedInstance().shouldRingWhenReceiveMessage()
if flag != true {
receiveMsgRingSwitch.setOn(false, animated: true)
}
else {
receiveMsgRingSwitch.setOn(true, animated: true)
}
cell.accessoryView = receiveMsgRingSwitch;
}
else if ((indexPath as NSIndexPath).row == 2) {
cell.textLabel?.text = NSLocalizedString("Vibrate", comment: "")
let msgVibrateSwitch: UISwitch = UISwitch.init();
msgVibrateSwitch.addTarget(self, action: #selector(switchMsgVibrate(_:)), for: UIControlEvents.valueChanged)
let flag: Bool = AppKeFuLib.sharedInstance().shouldVibrateWhenReceiveMessage()
if flag != true {
msgVibrateSwitch.setOn(false, animated: true)
}
else {
msgVibrateSwitch.setOn(true, animated: true)
}
cell.accessoryView = msgVibrateSwitch;
}
return cell;
}
func switchSendMsgRing(_ sender: UISwitch) ->Void
{
let ring: UISwitch = sender
AppKeFuLib.sharedInstance().setRingWhenSendMessage(ring.isOn)
}
func switchReceiveMsgRing(_ sender: UISwitch) ->Void
{
let ring: UISwitch = sender
AppKeFuLib.sharedInstance().setRingWhenReceiveMessage(ring.isOn)
}
func switchMsgVibrate(_ sender: UISwitch) ->Void
{
let ring: UISwitch = sender
AppKeFuLib.sharedInstance().setVibrateWhenReceiveMessage(ring.isOn)
}
}
| mit | 3f07a21f0aef0bdd3842e32b4c34e8fc | 28.823529 | 128 | 0.596893 | 5.160305 | false | false | false | false |
cuappdev/tcat-ios | TCAT/Network/ReachabilityManager.swift | 1 | 1618 | //
// ReachabilityManager.swift
// TCAT
//
// Created by Daniel Vebman on 11/6/19.
// Copyright ยฉ 2019 cuappdev. All rights reserved.
//
import Foundation
class ReachabilityManager: NSObject {
static let shared: ReachabilityManager = ReachabilityManager()
private let reachability = Reachability()
private var listeners: [Pair] = []
typealias Listener = AnyObject
typealias Closure = (Reachability.Connection) -> Void
private struct Pair {
weak var listener: Listener?
var closure: Closure
}
private override init() {
super.init()
do {
try reachability?.startNotifier()
} catch {
print("[ReachabilityManager] init: Could not start reachability notifier.")
}
NotificationCenter.default.addObserver(
self,
selector: #selector(reachabilityChanged(_:)),
name: .reachabilityChanged,
object: reachability
)
}
/// Adds a listener to reachability updates.
/// Reminder: Be sure to begin the closure with `[weak self]`.
func addListener(_ listener: Listener, _ closure: @escaping Closure) {
listeners.append(Pair(listener: listener, closure: closure))
}
@objc func reachabilityChanged(_ notification: Notification) {
guard let reachability = reachability else { return }
listeners = listeners.filter { pair -> Bool in
pair.closure(reachability.connection) // call the closures
return pair.listener != nil // remove closures for deinitialized listeners
}
}
}
| mit | 30f28886f851ddf4f247a4975562e2a9 | 27.368421 | 87 | 0.6376 | 5.182692 | false | false | false | false |
kstaring/swift | benchmark/single-source/unit-tests/StackPromo.swift | 10 | 756 | protocol Proto {
func at() -> Int
}
@inline(never)
func testStackAllocation(_ p: Proto) -> Int {
var a = [p, p, p]
var b = 0
a.withUnsafeMutableBufferPointer {
let array = $0
for i in 0..<array.count {
b += array[i].at()
}
}
return b
}
class Foo : Proto {
init() {}
func at() -> Int{
return 1
}
}
@inline(never)
func work(_ f: Foo) -> Int {
var r = 0
for _ in 0..<100_000 {
r += testStackAllocation(f)
}
return r
}
@inline(never)
func hole(_ use: Int, _ N: Int) {
if (N == 0) {
print("use: \(use)")
}
}
public func run_StackPromo(_ N: Int) {
let foo = Foo()
var r = 0
for i in 0..<N {
if i % 2 == 0 {
r += work(foo)
} else {
r -= work(foo)
}
}
hole(r, N)
}
| apache-2.0 | 954c4f4e428ed4c07be0c3eb6f99a203 | 13.538462 | 45 | 0.5 | 2.789668 | false | false | false | false |
overtake/TelegramSwift | submodules/AppCenter-sdk/Vendor/OCMock/Examples/SwiftExamples/SwiftExamples/MasterViewController.swift | 9 | 2999 | //
// MasterViewController.swift
// SwiftExamples
//
// Created by Erik Doernenburg on 11/06/2014.
// Copyright (c) 2014 Mulle Kybernetik. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var objects = NSMutableArray()
override func awakeFromNib() {
super.awakeFromNib()
}
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
}
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
(segue.destinationViewController as! DetailViewController).detailItem = object
}
}
}
// 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.
}
}
}
| gpl-2.0 | 0e9965344ec3205ebe5662b4cd58a1be | 33.471264 | 157 | 0.667222 | 5.605607 | false | false | false | false |
kevintavog/WatchThis | Source/WatchThis/AppDelegate.swift | 1 | 1623 | //
// WatchThis
//
import Cocoa
import RangicCore
import CocoaLumberjackSwift
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate
{
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var listController: ShowListController!
// MARK: Application hooks
func applicationDidFinishLaunching(_ aNotification: Notification)
{
#if DEBUG
dynamicLogLevel = DDLogLevel.verbose
#else
dynamicLogLevel = DDLogLevel.info
#endif
Logger.configure()
Preferences.setMissingDefaults()
ReverseNameLookupProvider.set(host: Preferences.baseLocationLookup)
Logger.info("Placename lookups via \(Preferences.baseLocationLookup)")
listController.addKeyboardShorcutToMenu()
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool
{
return true
}
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply
{
let close = listController != nil ? listController!.canClose() : true
return close ? NSApplication.TerminateReply.terminateNow : NSApplication.TerminateReply.terminateCancel
}
@IBAction func preferences(_ sender: AnyObject)
{
let preferencesController = PreferencesWindowController(windowNibName: "Preferences")
NSApplication.shared.runModal(for: preferencesController.window!)
}
func application(_ application: NSApplication, willPresentError error: Error) -> Error
{
Logger.error("willPresentError: \(error)")
return error
}
}
| mit | 9f9ce4bf0ca31e95443e9fc0cf78ad40 | 28.509091 | 111 | 0.703635 | 5.539249 | false | false | false | false |
tomasharkema/HoelangTotTrein.iOS | HoelangTotTrein/Station.swift | 1 | 4992 | //
// Station.swift
// HoelangTotTrein
//
// Created by Tomas Harkema on 13-02-15.
// Copyright (c) 2015 Tomas Harkema. All rights reserved.
//
import Foundation
import CoreLocation
struct Namen {
let kort:String
let middel:String
let lang:String
func string() -> String {
return lang
}
}
let RADIUS:CLLocationDistance = 150
class Station: NSObject, NSCoding {
let code:String!
let type:String!
let name:Namen!
let land:String!
let lat:Double!
let long:Double!
let UICCode:Int
//let synoniemen:[String]
override var hashValue: Int {
return self.code.toInt()!
}
override var hash:Int {
return self.code.toInt()!
}
let stationData:AEXMLElement
required init(coder aDecoder: NSCoder) {
self.code = aDecoder.decodeObjectForKey("code") as? String
self.type = aDecoder.decodeObjectForKey("type") as? String
self.land = aDecoder.decodeObjectForKey("land") as? String
self.lat = aDecoder.decodeDoubleForKey("lat")
self.long = aDecoder.decodeDoubleForKey("long")
self.UICCode = aDecoder.decodeIntegerForKey("UICCode")
self.name = Namen(kort: aDecoder.decodeObjectForKey("name.kort") as! String, middel: aDecoder.decodeObjectForKey("name.middel") as! String, lang: aDecoder.decodeObjectForKey("name.lang") as! String)
self.stationData = AEXMLDocument()
super.init()
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.code, forKey: "code")
aCoder.encodeObject(self.type, forKey: "type")
aCoder.encodeObject(self.land, forKey: "land")
aCoder.encodeDouble(self.lat, forKey: "lat")
aCoder.encodeDouble(self.long, forKey: "long")
aCoder.encodeInteger(self.UICCode, forKey: "UICCode")
aCoder.encodeObject(self.name.kort, forKey: "name.kort")
aCoder.encodeObject(self.name.middel, forKey: "name.middel")
aCoder.encodeObject(self.name.lang, forKey: "name.lang")
}
init (obj:AEXMLElement) {
stationData = obj
code = obj["Code"]?.stringValue
type = obj["Type"]?.stringValue
land = obj["Land"]?.stringValue
lat = obj["Lat"]?.doubleValue
long = obj["Lon"]?.doubleValue
UICCode = obj["UICCode"]?.intValue ?? 0;
let namen: AEXMLElement = obj["Namen"]!
let kort = namen["Kort"];
let middel = namen["Middel"];
let lang = namen["Lang"];
name = Namen(kort: kort?.stringValue ?? "", middel: middel?.stringValue ?? "", lang: lang?.stringValue ?? "")
}
func getLocation() -> CLLocation {
return CLLocation(latitude: lat!, longitude: long!)
}
func getRegion(i:Int) -> CLRegion {
let center = getLocation().coordinate
return CLCircularRegion(center: center, radius: RADIUS, identifier: CodeContainer(namespace: .Station, code: code, deelIndex: i).string())
}
class func sortStation(stations:Array<Station>, sortableRepresentation:(a:Station) -> Double, number:Int = -1, sorter:(a:Double, b:Double) -> Bool) -> Array<Station> {
var dict = Dictionary<NSString, Double>()
for station in stations {
dict[station.code] = sortableRepresentation(a: station)
}
var stationsK:Array<NSString> = Array(dict.keys)
sort(&stationsK) { a, b -> Bool in
return sorter(a:dict[a]!, b:dict[b]!)
}
return stationsK.slice(number).map { find(stations, $0 as! String)! }
}
class func getClosestStation(stations: Array<Station>,loc:CLLocation) -> Station? {
var currentStation:Station
var closestDistance:CLLocationDistance = DBL_MAX
var closestStation:Station?
for station in stations {
let dist = station.getLocation().distanceFromLocation(loc)
if (dist < closestDistance) {
closestStation = station;
closestDistance = dist;
}
}
return closestStation
}
class func sortStationsOnLocation(stations: Array<Station>, loc:CLLocation, number:Int = -1, sorter:(a:Double, b:Double) -> Bool) -> Array<Station> {
return sortStation(stations, sortableRepresentation: {
return $0.getLocation().distanceFromLocation(loc)
}, number:number, sorter: sorter)
}
}
func ==(lhs: Station, rhs: Station) -> Bool {
return lhs.code == rhs.code
}
func find(stations:Array<Station>, code:String) -> Station? {
return stations.filter{ $0.code == code }.first
}
func find(stations:Array<Station>, station:Station) -> Station? {
return find(stations, station.code)
}
func findIndex(stations:Array<Station>, station:Station) -> Int? {
var i = 0
var index:Int?
for s in stations {
if s == station {
index = i
}
i++
}
return index
} | apache-2.0 | 4bba4b8c0169ce17b77fab5f272963aa | 30.402516 | 206 | 0.61859 | 4.078431 | false | false | false | false |
abertelrud/swift-package-manager | Tests/PackageLoadingTests/TargetSourcesBuilderTests.swift | 2 | 41780 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
import Foundation
import PackageModel
import PackageLoading
import SPMTestSupport
import TSCBasic
import XCTest
class TargetSourcesBuilderTests: XCTestCase {
func testBasicFileContentsComputation() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: ["some2"],
sources: nil,
resources: [
.init(rule: .copy, path: "some/path/toBeCopied")
],
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
"/Foo.swift",
"/Bar.swift",
"/some/path.swift",
"/some2/path2.swift",
"/.some2/hello.swift",
"/Hello.something/hello.txt",
"/file",
"/path/to/file.xcodeproj/pbxproj",
"/path/to/somefile.txt",
"/some/path/toBeCopied/cool/hello.swift",
])
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageKind: .root(.root),
packagePath: .root,
target: target,
path: .root,
toolsVersion: .v5,
fileSystem: fs,
observabilityScope: observability.topScope
)
let contents = builder.computeContents().sorted()
XCTAssertEqual(contents, [
AbsolutePath(path: "/Bar.swift"),
AbsolutePath(path: "/Foo.swift"),
AbsolutePath(path: "/Hello.something/hello.txt"),
AbsolutePath(path: "/file"),
AbsolutePath(path: "/path/to/somefile.txt"),
AbsolutePath(path: "/some/path.swift"),
AbsolutePath(path: "/some/path/toBeCopied"),
])
XCTAssertNoDiagnostics(observability.diagnostics)
}
func testDirectoryWithExt_5_3() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: [],
sources: nil,
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
"/some/hello.swift",
"/some.thing/hello.txt",
])
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageKind: .root(.root),
packagePath: .root,
target: target,
path: .root,
toolsVersion: .v5_3,
fileSystem: fs,
observabilityScope: observability.topScope
)
let contents = builder.computeContents().sorted()
XCTAssertEqual(contents, [
AbsolutePath(path: "/some.thing"),
AbsolutePath(path: "/some/hello.swift"),
])
XCTAssertNoDiagnostics(observability.diagnostics)
}
func testDirectoryWithExt_5_6() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: [],
sources: nil,
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
"/some/hello.swift",
"/some.thing/hello.txt",
])
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageKind: .root(.root),
packagePath: .root,
target: target,
path: .root,
toolsVersion: .v5_6,
fileSystem: fs,
observabilityScope: observability.topScope
)
let contents = builder.computeContents().sorted()
XCTAssertEqual(contents, [
AbsolutePath(path: "/some.thing/hello.txt"),
AbsolutePath(path: "/some/hello.swift"),
])
XCTAssertNoDiagnostics(observability.diagnostics)
}
func testSpecialDirectoryWithExt_5_6() throws {
let root = AbsolutePath.root
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: [],
sources: nil,
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
root.appending(components: "some.xcassets", "hello.txt").pathString,
root.appending(components: "some", "hello.swift").pathString
])
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageKind: .root(.root),
packagePath: .root,
target: target,
path: .root,
toolsVersion: .v5_6,
fileSystem: fs,
observabilityScope: observability.topScope
)
let contents = builder.computeContents().sorted()
XCTAssertEqual(contents, [
root.appending(components: "some.xcassets"),
root.appending(components: "some", "hello.swift"),
])
XCTAssertNoDiagnostics(observability.diagnostics)
}
func testBasicRuleApplication() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: ["some2"],
sources: nil,
resources: [
.init(rule: .process(localization: .none), path: "path"),
.init(rule: .copy, path: "some/path/toBeCopied"),
],
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
"/Foo.swift",
"/Bar.swift",
"/some/path.swift",
"/some2/path2.swift",
"/.some2/hello.swift",
"/Hello.something/hello.txt",
"/file",
"/path/to/file.xcodeproj/pbxproj",
"/path/to/somefile.txt",
"/path/to/somefile2.txt",
"/some/path/toBeCopied/cool/hello.swift",
])
let somethingRule = FileRuleDescription(
rule: .processResource(localization: .none),
toolsVersion: .minimumRequired,
fileTypes: ["something"])
build(target: target, additionalFileRules: [somethingRule], toolsVersion: .v5, fs: fs) { _, _, _, _, _, _, _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
}
func testDoesNotErrorWithAdditionalFileRules() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: [],
sources: nil,
resources: [],
publicHeadersPath: nil,
type: .regular
)
let files = [
AbsolutePath(path: "/Foo.swift").pathString,
AbsolutePath(path: "/Bar.swift").pathString,
AbsolutePath(path: "/Baz.something").pathString,
]
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: files)
let somethingRule = FileRuleDescription(
rule: .compile,
toolsVersion: .v5_5,
fileTypes: ["something"]
)
build(target: target, additionalFileRules: [somethingRule], toolsVersion: .v5_5, fs: fs) { sources, _, _, _, _, _, _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
XCTAssertEqual(
sources.paths.map(\.pathString).sorted(),
files.sorted()
)
}
}
func testResourceConflicts() throws {
// Conflict between processed resources.
do {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process(localization: .none), path: "Resources")
])
let fs = InMemoryFileSystem(emptyFiles:
"/Resources/foo.txt",
"/Resources/Sub/foo.txt"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in
testDiagnostics(diagnostics, problemsOnly: false) { result in
var diagnosticsFound = [Basics.Diagnostic?]()
diagnosticsFound.append(result.check(diagnostic: "multiple resources named 'foo.txt' in target 'Foo'", severity: .error))
diagnosticsFound.append(result.checkUnordered(diagnostic: "found '\(RelativePath("Resources").appending(components: "foo.txt"))'", severity: .info))
diagnosticsFound.append(result.checkUnordered(diagnostic: "found '\(RelativePath("Resources").appending(components: "Sub", "foo.txt"))'", severity: .info))
for diagnostic in diagnosticsFound {
XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)
XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)
XCTAssertEqual(diagnostic?.metadata?.targetName, target.name)
}
}
}
}
// Conflict between processed and copied resources.
do {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process(localization: .none), path: "Processed"),
.init(rule: .copy, path: "Copied/foo.txt"),
])
let fs = InMemoryFileSystem(emptyFiles:
"/Processed/foo.txt",
"/Copied/foo.txt"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in
testDiagnostics(diagnostics, problemsOnly: false) { result in
var diagnosticsFound = [Basics.Diagnostic?]()
diagnosticsFound.append(result.check(diagnostic: "multiple resources named 'foo.txt' in target 'Foo'", severity: .error))
diagnosticsFound.append(result.checkUnordered(diagnostic: "found '\(RelativePath("Processed").appending(components: "foo.txt"))'", severity: .info))
diagnosticsFound.append(result.checkUnordered(diagnostic: "found '\(RelativePath("Copied").appending(components: "foo.txt"))'", severity: .info))
for diagnostic in diagnosticsFound {
XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)
XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)
XCTAssertEqual(diagnostic?.metadata?.targetName, target.name)
}
}
}
}
// No conflict between processed and copied in sub-path resources.
do {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process(localization: .none), path: "Processed"),
.init(rule: .copy, path: "Copied"),
])
let fs = InMemoryFileSystem(emptyFiles:
"/Processed/foo.txt",
"/Copied/foo.txt"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, _, _, _, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
}
// Conflict between copied directory resources.
do {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .copy, path: "A/Copy"),
.init(rule: .copy, path: "B/Copy"),
])
let fs = InMemoryFileSystem(emptyFiles:
"/A/Copy/foo.txt",
"/B/Copy/foo.txt"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in
testDiagnostics(diagnostics, problemsOnly: false) { result in
var diagnosticsFound = [Basics.Diagnostic?]()
diagnosticsFound.append(result.check(diagnostic: "multiple resources named 'Copy' in target 'Foo'", severity: .error))
diagnosticsFound.append(result.checkUnordered(diagnostic: "found '\(RelativePath("A").appending(components: "Copy"))'", severity: .info))
diagnosticsFound.append(result.checkUnordered(diagnostic: "found '\(RelativePath("B").appending(components: "Copy"))'", severity: .info))
for diagnostic in diagnosticsFound {
XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)
XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)
XCTAssertEqual(diagnostic?.metadata?.targetName, target.name)
}
}
}
}
// Conflict between processed localizations.
do {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process(localization: .none), path: "A"),
.init(rule: .process(localization: .none), path: "B"),
])
let fs = InMemoryFileSystem(emptyFiles:
"/A/en.lproj/foo.txt",
"/B/EN.lproj/foo.txt"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in
testDiagnostics(diagnostics, problemsOnly: false) { result in
var diagnosticsFound = [Basics.Diagnostic?]()
diagnosticsFound.append(result.check(diagnostic: "multiple resources named '\(RelativePath("en.lproj").appending(components: "foo.txt"))' in target 'Foo'", severity: .error))
diagnosticsFound.append(result.checkUnordered(diagnostic: "found '\(RelativePath("A").appending(components: "en.lproj", "foo.txt"))'", severity: .info))
diagnosticsFound.append(result.checkUnordered(diagnostic: "found '\(RelativePath("B").appending(components: "EN.lproj", "foo.txt"))'", severity: .info))
for diagnostic in diagnosticsFound {
XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)
XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)
XCTAssertEqual(diagnostic?.metadata?.targetName, target.name)
}
}
}
}
// Conflict between processed localizations and copied resources.
do {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process(localization: .none), path: "A"),
.init(rule: .copy, path: "B/en.lproj"),
])
let fs = InMemoryFileSystem(emptyFiles:
"/A/EN.lproj/foo.txt",
"/B/en.lproj/foo.txt"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in
testDiagnostics(diagnostics) { result in
let diagnostic = result.check(
diagnostic: "resource '\(RelativePath("B").appending(components: "en.lproj"))' in target 'Foo' conflicts with other localization directories",
severity: .error
)
XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)
XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)
XCTAssertEqual(diagnostic?.metadata?.targetName, target.name)
}
}
}
}
func testLocalizationDirectoryIgnoredOn5_2() throws {
let target = try TargetDescription(name: "Foo")
let fs = InMemoryFileSystem(emptyFiles:
"/en.lproj/Localizable.strings"
)
build(target: target, toolsVersion: .v5_2, fs: fs) { _, resources, _, _, _, _, _, diagnostics in
XCTAssert(resources.isEmpty)
XCTAssertNoDiagnostics(diagnostics)
}
}
func testLocalizationDirectorySubDirectory() throws {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process(localization: .none), path: "Processed"),
.init(rule: .copy, path: "Copied")
])
let fs = InMemoryFileSystem(emptyFiles:
"/Processed/en.lproj/sub/Localizable.strings",
"/Copied/en.lproj/sub/Localizable.strings"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in
testDiagnostics(diagnostics) { result in
let diagnostic = result.check(
diagnostic: "localization directory '\(RelativePath("Processed").appending(components: "en.lproj"))' in target 'Foo' contains sub-directories, which is forbidden",
severity: .error
)
XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)
XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)
XCTAssertEqual(diagnostic?.metadata?.targetName, target.name)
}
}
}
func testExplicitLocalizationInLocalizationDirectory() throws {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process(localization: .base), path: "Resources"),
])
let fs = InMemoryFileSystem(emptyFiles:
"/Resources/en.lproj/Localizable.strings"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in
testDiagnostics(diagnostics) { result in
let diagnostic = result.check(
diagnostic: .contains("""
resource '\(RelativePath("Resources").appending(components: "en.lproj", "Localizable.strings"))' in target 'Foo' is in a localization directory \
and has an explicit localization declaration
"""),
severity: .error
)
XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)
XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)
XCTAssertEqual(diagnostic?.metadata?.targetName, target.name)
}
}
}
// rdar://86297221
// There is no need to validate localization exists for default localization
func testMissingDefaultLocalization() throws {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process(localization: .none), path: "Resources"),
.init(rule: .process(localization: .default), path: "Image.png"),
.init(rule: .process(localization: .base), path: "Icon.png"),
])
let fs = InMemoryFileSystem(emptyFiles:
"/Resources/en.lproj/Localizable.strings",
"/Resources/en.lproj/Icon.png",
"/Resources/fr.lproj/Localizable.strings",
"/Resources/fr.lproj/Sign.png",
"/Resources/Base.lproj/Storyboard.storyboard",
"/Image.png",
"/Icon.png"
)
do {
build(target: target, defaultLocalization: "fr", toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
}
do {
build(target: target, defaultLocalization: "en", toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in
XCTAssertNoDiagnostics(diagnostics)
}
}
}
func testLocalizedAndUnlocalizedResources() throws {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process(localization: .none), path: "Resources"),
.init(rule: .process(localization: .default), path: "Image.png"),
.init(rule: .process(localization: .base), path: "Icon.png"),
])
let fs = InMemoryFileSystem(emptyFiles:
"/Resources/en.lproj/Localizable.strings",
"/Resources/Localizable.strings",
"/Resources/Base.lproj/Storyboard.storyboard",
"/Resources/Storyboard.storyboard",
"/Resources/Image.png",
"/Resources/Icon.png",
"/Image.png",
"/Icon.png"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in
testDiagnostics(diagnostics) { result in
var diagnosticsFound = [Basics.Diagnostic?]()
diagnosticsFound.append(result.checkUnordered(
diagnostic: .contains("resource 'Localizable.strings' in target 'Foo' has both localized and un-localized variants"),
severity: .warning
))
diagnosticsFound.append(result.checkUnordered(
diagnostic: .contains("resource 'Storyboard.storyboard' in target 'Foo' has both localized and un-localized variants"),
severity: .warning
))
diagnosticsFound.append(result.checkUnordered(
diagnostic: .contains("resource 'Image.png' in target 'Foo' has both localized and un-localized variants"),
severity: .warning
))
diagnosticsFound.append(result.checkUnordered(
diagnostic: .contains("resource 'Icon.png' in target 'Foo' has both localized and un-localized variants"),
severity: .warning
))
for diagnostic in diagnosticsFound {
XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)
XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)
XCTAssertEqual(diagnostic?.metadata?.targetName, target.name)
}
}
}
}
func testLocalizedResources() throws {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process(localization: .none), path: "Processed"),
.init(rule: .copy, path: "Copied"),
.init(rule: .process(localization: .base), path: "Other/Launch.storyboard"),
.init(rule: .process(localization: .default), path: "Other/Image.png"),
])
let fs = InMemoryFileSystem(emptyFiles:
"/Processed/foo.txt",
"/Processed/En-uS.lproj/Localizable.stringsdict",
"/Processed/en-US.lproj/Localizable.strings",
"/Processed/fr.lproj/Localizable.strings",
"/Processed/fr.lproj/Localizable.stringsdict",
"/Processed/Base.lproj/Storyboard.storyboard",
"/Copied/en.lproj/Localizable.strings",
"/Other/Launch.storyboard",
"/Other/Image.png"
)
build(target: target, defaultLocalization: "fr", toolsVersion: .v5_3, fs: fs) { _, resources, _, _, _, _, _, diagnostics in
XCTAssertEqual(resources.sorted(by: { $0.path < $1.path }), [
Resource(rule: .process(localization: .none), path: AbsolutePath(path: "/Processed/foo.txt")),
Resource(rule: .process(localization: "en-us"), path: AbsolutePath(path: "/Processed/En-uS.lproj/Localizable.stringsdict")),
Resource(rule: .process(localization: "en-us"), path: AbsolutePath(path: "/Processed/en-US.lproj/Localizable.strings")),
Resource(rule: .process(localization: "fr"), path: AbsolutePath(path: "/Processed/fr.lproj/Localizable.strings")),
Resource(rule: .process(localization: "fr"), path: AbsolutePath(path: "/Processed/fr.lproj/Localizable.stringsdict")),
Resource(rule: .process(localization: "Base"), path: AbsolutePath(path: "/Processed/Base.lproj/Storyboard.storyboard")),
Resource(rule: .copy, path: AbsolutePath(path: "/Copied")),
Resource(rule: .process(localization: "Base"), path: AbsolutePath(path: "/Other/Launch.storyboard")),
Resource(rule: .process(localization: "fr"), path: AbsolutePath(path: "/Other/Image.png")),
].sorted(by: { $0.path < $1.path }))
}
}
func testLocalizedImage() throws {
let fs = InMemoryFileSystem(emptyFiles:
"/Foo/fr.lproj/Image.png",
"/Foo/es.lproj/Image.png"
)
build(target: try TargetDescription(name: "Foo"), defaultLocalization: "fr", toolsVersion: .v5_3, fs: fs) { _, resources, _, _, _, _, _, diagnostics in
XCTAssertEqual(resources.sorted(by: { $0.path < $1.path }), [
Resource(rule: .process(localization: "fr"), path: AbsolutePath(path: "/Foo/fr.lproj/Image.png")),
Resource(rule: .process(localization: "es"), path: AbsolutePath(path: "/Foo/es.lproj/Image.png")),
].sorted(by: { $0.path < $1.path }))
}
}
func testInfoPlistResource() throws {
do {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .process(localization: .none), path: "Resources"),
])
let fs = InMemoryFileSystem(emptyFiles:
"/Resources/Processed/Info.plist"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in
testDiagnostics(diagnostics) { result in
let diagnostic = result.check(
diagnostic: .contains("resource '\(RelativePath("Resources").appending(components: "Processed", "Info.plist"))' in target 'Foo' is forbidden"),
severity: .error
)
XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)
XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)
XCTAssertEqual(diagnostic?.metadata?.targetName, target.name)
}
}
}
do {
let target = try TargetDescription(name: "Foo", resources: [
.init(rule: .copy, path: "Resources/Copied/Info.plist"),
])
let fs = InMemoryFileSystem(emptyFiles:
"/Resources/Copied/Info.plist"
)
build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in
testDiagnostics(diagnostics) { result in
let diagnostic = result.check(
diagnostic: .contains("resource '\(RelativePath("Resources").appending(components: "Copied", "Info.plist"))' in target 'Foo' is forbidden"),
severity: .error
)
XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)
XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)
XCTAssertEqual(diagnostic?.metadata?.targetName, target.name)
}
}
}
}
func testMissingExclude() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: ["fakeDir", "../../fileOutsideRoot.py"],
sources: nil,
resources: [],
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
"/Foo.swift",
"/Bar.swift"
])
do {
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageKind: .root(.init(path: "/test")),
packagePath: .init(path: "/test"),
target: target,
path: .root,
toolsVersion: .v5,
fileSystem: fs,
observabilityScope: observability.topScope
)
_ = try builder.run()
testDiagnostics(observability.diagnostics) { result in
var diagnosticsFound = [Basics.Diagnostic?]()
diagnosticsFound.append(result.checkUnordered(diagnostic: "Invalid Exclude '\(AbsolutePath(path: "/fileOutsideRoot.py"))': File not found.", severity: .warning))
diagnosticsFound.append(result.checkUnordered(diagnostic: "Invalid Exclude '\(AbsolutePath(path: "/fakeDir"))': File not found.", severity: .warning))
for diagnostic in diagnosticsFound {
XCTAssertEqual(diagnostic?.metadata?.packageIdentity, builder.packageIdentity)
XCTAssertEqual(diagnostic?.metadata?.packageKind, builder.packageKind)
XCTAssertEqual(diagnostic?.metadata?.targetName, target.name)
}
}
}
// should not emit for "remote" packages
do {
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageKind: .remoteSourceControl(URL(string: "https://some.where/foo/bar")!),
packagePath: .init(path: "/test"),
target: target,
path: .root,
toolsVersion: .v5,
fileSystem: fs,
observabilityScope: observability.topScope
)
_ = try builder.run()
XCTAssertNoDiagnostics(observability.diagnostics)
}
}
func testMissingResource() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: [],
sources: nil,
resources: [.init(rule: .copy, path: "../../../Fake.txt"),
.init(rule: .process(localization: .none), path: "NotReal")],
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
"/Foo.swift",
"/Bar.swift"
])
do {
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageKind: .root(.root),
packagePath: .root,
target: target,
path: .root,
toolsVersion: .v5,
fileSystem: fs,
observabilityScope: observability.topScope
)
_ = try builder.run()
testDiagnostics(observability.diagnostics) { result in
var diagnosticsFound = [Basics.Diagnostic?]()
diagnosticsFound.append(result.checkUnordered(diagnostic: "Invalid Resource '../../../Fake.txt': File not found.", severity: .warning))
diagnosticsFound.append(result.checkUnordered(diagnostic: "Invalid Resource 'NotReal': File not found.", severity: .warning))
for diagnostic in diagnosticsFound {
XCTAssertEqual(diagnostic?.metadata?.packageIdentity, builder.packageIdentity)
XCTAssertEqual(diagnostic?.metadata?.packageKind, builder.packageKind)
XCTAssertEqual(diagnostic?.metadata?.targetName, target.name)
}
}
}
// should not emit for "remote" packages
do {
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageKind: .remoteSourceControl(URL(string: "https://some.where/foo/bar")!),
packagePath: .root,
target: target,
path: .root,
toolsVersion: .v5,
fileSystem: fs,
observabilityScope: observability.topScope
)
_ = try builder.run()
XCTAssertNoDiagnostics(observability.diagnostics)
}
}
func testMissingSource() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: [],
sources: ["InvalidPackage.swift",
"DoesNotExist.swift",
"../../Tests/InvalidPackageTests/InvalidPackageTests.swift"],
resources: [],
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
"/Foo.swift",
"/Bar.swift"
])
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageKind: .root(.init(path: "/test")),
packagePath: .root,
target: target,
path: .root,
toolsVersion: .v5,
fileSystem: fs,
observabilityScope: observability.topScope
)
testDiagnostics(observability.diagnostics) { result in
var diagnosticsFound = [Basics.Diagnostic?]()
diagnosticsFound.append(result.checkUnordered(diagnostic: "Invalid Source '\(AbsolutePath(path: "/InvalidPackage.swift"))': File not found.", severity: .warning))
diagnosticsFound.append(result.checkUnordered(diagnostic: "Invalid Source '\(AbsolutePath(path: "/DoesNotExist.swift"))': File not found.", severity: .warning))
diagnosticsFound.append(result.checkUnordered(diagnostic: "Invalid Source '\(AbsolutePath(path: "/Tests/InvalidPackageTests/InvalidPackageTests.swift"))': File not found.", severity: .warning))
for diagnostic in diagnosticsFound {
XCTAssertEqual(diagnostic?.metadata?.packageIdentity, builder.packageIdentity)
XCTAssertEqual(diagnostic?.metadata?.packageKind, builder.packageKind)
XCTAssertEqual(diagnostic?.metadata?.targetName, target.name)
}
}
}
func testXcodeSpecificResourcesAreNotIncludedByDefault() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: [],
sources: ["File.swift"],
resources: [],
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
"/File.swift",
"/Foo.xcdatamodel"
])
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageKind: .root(.init(path: "/test")),
packagePath: .root,
target: target,
path: .root,
toolsVersion: .v5_5,
fileSystem: fs,
observabilityScope: observability.topScope
)
let outputs = try builder.run()
XCTAssertEqual(outputs.sources.paths, [AbsolutePath(path: "/File.swift")])
XCTAssertEqual(outputs.resources, [])
XCTAssertEqual(outputs.ignored, [])
XCTAssertEqual(outputs.others, [AbsolutePath(path: "/Foo.xcdatamodel")])
XCTAssertFalse(observability.hasWarningDiagnostics)
XCTAssertFalse(observability.hasErrorDiagnostics)
}
func testUnhandledResources() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: [],
sources: ["File.swift"],
resources: [],
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
"/File.swift",
"/foo.bar"
])
do {
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageKind: .root(.init(path: "/test")),
packagePath: .root,
target: target,
path: .root,
toolsVersion: .v5_5,
fileSystem: fs,
observabilityScope: observability.topScope
)
let outputs = try builder.run()
XCTAssertEqual(outputs.sources.paths, [AbsolutePath(path: "/File.swift")])
XCTAssertEqual(outputs.resources, [])
XCTAssertEqual(outputs.ignored, [])
XCTAssertEqual(outputs.others, [AbsolutePath(path: "/foo.bar")])
XCTAssertFalse(observability.hasWarningDiagnostics)
XCTAssertFalse(observability.hasErrorDiagnostics)
}
// should not emit for "remote" packages
do {
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageKind: .remoteSourceControl(URL(string: "https://some.where/foo/bar")!),
packagePath: .root,
target: target,
path: .root,
toolsVersion: .v5_5,
fileSystem: fs,
observabilityScope: observability.topScope
)
_ = try builder.run()
XCTAssertNoDiagnostics(observability.diagnostics)
}
}
func testDocCFilesDoNotCauseWarningOutsideXCBuild() throws {
let target = try TargetDescription(
name: "Foo",
path: nil,
exclude: [],
sources: ["File.swift"],
resources: [],
publicHeadersPath: nil,
type: .regular
)
let fs = InMemoryFileSystem()
fs.createEmptyFiles(at: .root, files: [
"/File.swift",
"/Foo.docc"
])
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageKind: .root(.root),
packagePath: .root,
target: target,
path: .root,
defaultLocalization: nil,
additionalFileRules: FileRuleDescription.swiftpmFileTypes,
toolsVersion: .v5_5,
fileSystem: fs,
observabilityScope: observability.topScope
)
let outputs = try builder.run()
XCTAssertEqual(outputs.sources.paths, [AbsolutePath(path: "/File.swift")])
XCTAssertEqual(outputs.resources, [])
XCTAssertEqual(outputs.ignored, [AbsolutePath(path: "/Foo.docc")])
XCTAssertEqual(outputs.others, [])
XCTAssertNoDiagnostics(observability.diagnostics)
}
// MARK: - Utilities
private func build(
target: TargetDescription,
defaultLocalization: String? = nil,
additionalFileRules: [FileRuleDescription] = [],
toolsVersion: ToolsVersion,
fs: FileSystem,
file: StaticString = #file,
line: UInt = #line,
checker: (Sources, [Resource], [AbsolutePath], [AbsolutePath], PackageIdentity, PackageReference.Kind, AbsolutePath, [Basics.Diagnostic]) throws -> Void
) {
let observability = ObservabilitySystem.makeForTesting()
let builder = TargetSourcesBuilder(
packageIdentity: .plain("test"),
packageKind: .root(.root),
packagePath: .root,
target: target,
path: .root,
defaultLocalization: defaultLocalization,
additionalFileRules: additionalFileRules,
toolsVersion: toolsVersion,
fileSystem: fs,
observabilityScope: observability.topScope
)
do {
let (sources, resources, headers, _, others) = try builder.run()
try checker(sources, resources, headers, others, builder.packageIdentity, builder.packageKind, builder.packagePath, observability.diagnostics)
} catch {
XCTFail(error.localizedDescription, file: file, line: line)
}
}
}
extension TargetSourcesBuilder {
public init(
packageIdentity: PackageIdentity,
packageKind: PackageReference.Kind,
packagePath: AbsolutePath,
target: TargetDescription,
path: AbsolutePath,
toolsVersion: ToolsVersion,
fileSystem: FileSystem,
observabilityScope: ObservabilityScope
) {
self.init(
packageIdentity: packageIdentity,
packageKind: packageKind,
packagePath: packagePath,
target: target,
path: path,
defaultLocalization: .none,
additionalFileRules: [],
toolsVersion: toolsVersion,
fileSystem: fileSystem,
observabilityScope: observabilityScope
)
}
}
| apache-2.0 | c32ab546a838e6b425d23bb2304404cc | 38.904489 | 205 | 0.558114 | 5.056275 | false | true | false | false |
AliSoftware/SwiftGen | Sources/SwiftGenKit/Parsers/CoreData/Model.swift | 1 | 1174 | //
// SwiftGenKit
// Copyright ยฉ 2020 SwiftGen
// MIT Licence
//
import Foundation
import Kanna
extension CoreData {
public struct Model {
public let entities: [String: Entity]
public let configurations: [String: [String]]
public let fetchRequests: [FetchRequest]
public let fetchRequestsByEntityName: [String: [FetchRequest]]
}
}
private enum XML {
static let entitiesPath = "/model/entity"
static let configurationsPath = "/model/configuration"
static let fetchRequestsPath = "/model/fetchRequest"
}
extension CoreData.Model {
init(with document: Kanna.XMLDocument) throws {
let allEntities = try document.xpath(XML.entitiesPath).map(CoreData.Entity.init(with:))
let entitiesByName = Dictionary(allEntities.map { ($0.name, $0) }) { first, _ in first }
entities = entitiesByName
configurations = try CoreData.Configuration.parse(
from: document.xpath(XML.configurationsPath),
entityNames: Array(entitiesByName.keys)
)
fetchRequests = try document.xpath(XML.fetchRequestsPath).map(CoreData.FetchRequest.init(with:))
fetchRequestsByEntityName = Dictionary(grouping: fetchRequests) { $0.entity }
}
}
| mit | 2172e9a40c3adf49c6b8775b5fa14379 | 29.868421 | 100 | 0.729753 | 4.159574 | false | true | false | false |
otto-de/OTTOPhotoBrowser | OTTOPhotoBrowser/Classes/OTTOZoomingScrollView.swift | 1 | 7222 | //
// OttoZoomingScrollView.swift
// OTTOPhotoBrowser
//
// Created by Lukas Zielinski on 22/12/2016.
// Copyright ยฉ 2016 CocoaPods. All rights reserved.
//
import UIKit
class OTTOZoomingScrollView: UIScrollView, UIScrollViewDelegate {
var photo: OTTOPhoto? {
didSet {
displayImage()
}
}
var padding: CGFloat = 0
weak var photoBrowserView: OTTOPhotoBrowserView?
private let activityIndicatorView: UIActivityIndicatorView
private let tapView: UIView
private let photoImageView: UIImageView
private var isPinchoutDetected = false
func prepareForReuse() {
photo = nil
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(photoBrowserView: OTTOPhotoBrowserView) {
self.photoBrowserView = photoBrowserView
activityIndicatorView = UIActivityIndicatorView()
tapView = UIView(frame: CGRect.zero)
photoImageView = UIImageView(frame: CGRect.zero)
super.init(frame: CGRect.zero)
activityIndicatorView.style = .gray
activityIndicatorView.hidesWhenStopped = true
addSubview(activityIndicatorView)
tapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tapView.backgroundColor = UIColor.clear
let tapViewSingleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap(gestureRecognizer:)))
let tapViewDoubleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(gestureRecognizer:)))
tapViewDoubleTapRecognizer.numberOfTapsRequired = 2
tapViewSingleTapRecognizer.require(toFail: tapViewDoubleTapRecognizer)
tapView.addGestureRecognizer(tapViewSingleTapRecognizer)
tapView.addGestureRecognizer(tapViewDoubleTapRecognizer)
photoImageView.backgroundColor = UIColor.clear
let imageViewSingleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap(gestureRecognizer:)))
let imageViewDoubleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(gestureRecognizer:)))
imageViewDoubleTapRecognizer.numberOfTapsRequired = 2
imageViewSingleTapRecognizer.require(toFail: imageViewDoubleTapRecognizer)
photoImageView.contentMode = .scaleAspectFit
photoImageView.isUserInteractionEnabled = true
photoImageView.addGestureRecognizer(imageViewSingleTapRecognizer)
photoImageView.addGestureRecognizer(imageViewDoubleTapRecognizer)
addSubview(tapView)
addSubview(photoImageView)
backgroundColor = UIColor.clear
delegate = self
showsVerticalScrollIndicator = false
showsHorizontalScrollIndicator = false
decelerationRate = UIScrollView.DecelerationRate.fast
autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
func displayImage() {
guard let photo = photo else {
return
}
if let image = photoBrowserView?.imageForPhoto(photo: photo), image.size.width > 0, image.size.height > 0 {
minimumZoomScale = 1
maximumZoomScale = 1
zoomScale = 1
photoImageView.image = image
photoImageView.isHidden = false
photoImageView.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
contentSize = photoImageView.frame.size
setMaxMinZoomScalesForCurrentBounds()
activityIndicatorView.stopAnimating()
} else {
photoImageView.isHidden = true
activityIndicatorView.startAnimating()
}
setNeedsLayout()
}
private func setMaxMinZoomScalesForCurrentBounds() {
if photoImageView.image == nil {
return
}
var boundsSize = bounds.size
boundsSize.width -= 0.1
boundsSize.height -= 0.1
let imageSize = photoImageView.frame.size
let xScale = boundsSize.width / imageSize.width; // the scale needed to perfectly fit the image width-wise
let yScale = boundsSize.height / imageSize.height; // the scale needed to perfectly fit the image height-wise
let minScale = min(xScale, yScale); // use minimum of these to allow the image to become fully visible
let maxScale = minScale * 2.5
maximumZoomScale = maxScale;
minimumZoomScale = minScale;
zoomScale = minScale;
let paddingX = photoImageView.frame.size.width > padding * 4 ? padding : 0
let paddingY = photoImageView.frame.size.height > padding * 4 ? padding : 0
photoImageView.frame = CGRect(x: 0, y: 0, width: photoImageView.frame.size.width, height: photoImageView.frame.size.height).insetBy(dx: paddingX, dy: paddingY)
setNeedsLayout()
}
override func layoutSubviews() {
tapView.frame = bounds
super.layoutSubviews()
let boundsSize = bounds.size
var frameToCenter = photoImageView.frame
if frameToCenter.size.width < boundsSize.width {
frameToCenter.origin.x = floor((boundsSize.width - frameToCenter.size.width) / CGFloat(2))
} else {
frameToCenter.origin.x = 0;
}
if frameToCenter.size.height < boundsSize.height {
frameToCenter.origin.y = floor((boundsSize.height - frameToCenter.size.height) / CGFloat(2));
} else {
frameToCenter.origin.y = 0;
}
photoImageView.frame = frameToCenter
activityIndicatorView.center = CGPoint(x: bounds.midX, y: bounds.midY)
}
// MARK: UIScrollViewDelegate
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return photoImageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
setNeedsLayout()
layoutIfNeeded()
if zoomScale < (minimumZoomScale - minimumZoomScale * 0.4) {
isPinchoutDetected = true
}
}
func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
photoBrowserView?.scrollViewDidEndZooming(scrollView, with: view, atScale: scale)
if isPinchoutDetected {
isPinchoutDetected = false
photoBrowserView?.onPinchout()
}
}
// MARK: Tap Detection
@objc func handleSingleTap(gestureRecognizer: UITapGestureRecognizer) {
photoBrowserView?.onTap()
}
@objc func handleDoubleTap(gestureRecognizer: UITapGestureRecognizer) {
let touchPoint = gestureRecognizer.location(in: photoImageView)
if zoomScale == maximumZoomScale {
setZoomScale(minimumZoomScale, animated: true)
} else {
zoom(to: CGRect(x: touchPoint.x, y: touchPoint.y, width: 1, height: 1), animated: true)
}
photoBrowserView?.onZoomedWithDoubleTap()
}
}
| mit | 85243012d261a677b2c332208a5604a6 | 36.609375 | 167 | 0.652264 | 5.685827 | false | false | false | false |
exoduz/GSMessages | GSMessages/GSMessage.swift | 1 | 9346 | //
// GSMessage.swift
// GSMessagesExample
//
// Created by Gesen on 15/7/10.
// Copyright (c) 2015ๅนด Gesen. All rights reserved.
//
import UIKit
public enum GSMessageType {
case Success
case Error
case Warning
case Info
}
public enum GSMessagePosition {
case Top
case Bottom
}
public enum GSMessageAnimation {
case Slide
case Fade
}
public enum GSMessageOption {
case Animation(GSMessageAnimation)
case AnimationDuration(NSTimeInterval)
case AutoHide(Bool)
case AutoHideDelay(Double) // Second
case Height(CGFloat)
case HideOnTap(Bool)
case Position(GSMessagePosition)
case TextColor(UIColor)
case TextPadding(CGFloat)
}
extension UIViewController {
public func showMessage(text: String, type: GSMessageType, options: [GSMessageOption]?) {
GSMessage.showMessageAddedTo(view, text: text, type: type, options: options, inViewController: self)
}
public func hideMessage() {
view.hideMessage()
}
}
extension UIView {
public func showMessage(text: String, type: GSMessageType, options: [GSMessageOption]?) {
GSMessage.showMessageAddedTo(self, text: text, type: type, options: options, inViewController: nil)
}
public func hideMessage() {
installedMessage?.hide()
}
}
public class GSMessage {
public static var font: UIFont = UIFont.systemFontOfSize(14)
public static var textAlignment: NSTextAlignment = NSTextAlignment.Center
public static var successBackgroundColor: UIColor = UIColor(red: 142.0/255, green: 183.0/255, blue: 64.0/255, alpha: 0.95)
public static var warningBackgroundColor: UIColor = UIColor(red: 230.0/255, green: 189.0/255, blue: 1.0/255, alpha: 0.95)
public static var errorBackgroundColor: UIColor = UIColor(red: 219.0/255, green: 36.0/255, blue: 27.0/255, alpha: 0.70)
public static var infoBackgroundColor: UIColor = UIColor(red: 44.0/255, green: 187.0/255, blue: 255.0/255, alpha: 0.90)
class func showMessageAddedTo(view: UIView, text: String, type: GSMessageType, options: [GSMessageOption]?, inViewController: UIViewController?) {
if view.installedMessage != nil && view.uninstallMessage == nil { view.hideMessage() }
if view.installedMessage == nil {
GSMessage(view: view, text: text, type: type, options: options, inViewController: inViewController).show()
}
}
func show() {
if view?.installedMessage != nil { return }
view?.installedMessage = self
view?.addSubview(message)
if animation == .Fade {
message.alpha = 0
UIView.animateWithDuration(animationDuration) { self.message.alpha = 1 }
}
else if animation == .Slide && position == .Top {
message.transform = CGAffineTransformMakeTranslation(0, -messageHeight)
UIView.animateWithDuration(animationDuration) { self.message.transform = CGAffineTransformMakeTranslation(0, 0) }
}
else if animation == .Slide && position == .Bottom {
message.transform = CGAffineTransformMakeTranslation(0, height)
UIView.animateWithDuration(animationDuration) { self.message.transform = CGAffineTransformMakeTranslation(0, 0) }
}
if autoHide { GCDAfter(autoHideDelay) { self.hide() } }
}
func hide() {
if view?.installedMessage !== self || view?.uninstallMessage != nil { return }
view?.uninstallMessage = self
view?.installedMessage = nil
if animation == .Fade {
UIView.animateWithDuration(self.animationDuration,
animations: { [weak self] in if let this = self { this.message.alpha = 0 } },
completion: { [weak self] finished in self?.removeFromSuperview() }
)
}
else if animation == .Slide && position == .Top {
UIView.animateWithDuration(self.animationDuration,
animations: { [weak self] in if let this = self { this.message.transform = CGAffineTransformMakeTranslation(0, -this.messageHeight) } },
completion: { [weak self] finished in self?.removeFromSuperview() }
)
}
else if animation == .Slide && position == .Bottom {
UIView.animateWithDuration(self.animationDuration,
animations: { [weak self] in if let this = self { this.message.transform = CGAffineTransformMakeTranslation(0, this.height) } },
completion: { [weak self] finished in self?.removeFromSuperview() }
)
}
}
private weak var view: UIView?
private var message: UIView!
private var messageText: UILabel!
private var animation: GSMessageAnimation = .Slide
private var animationDuration: NSTimeInterval = 0.3
private var autoHide: Bool = true
private var autoHideDelay: Double = 3
private var backgroundColor: UIColor!
private var height: CGFloat = 44
private var hideOnTap: Bool = true
private var offsetY: CGFloat = 0
private var position: GSMessagePosition = .Top
private var textColor: UIColor = UIColor.whiteColor()
private var textPadding: CGFloat = 30
private var y: CGFloat = 0
private var messageHeight: CGFloat { return offsetY + height }
private init(view: UIView, text: String, type: GSMessageType, options: [GSMessageOption]?, inViewController: UIViewController?) {
switch type {
case .Success: backgroundColor = GSMessage.successBackgroundColor
case .Warning: backgroundColor = GSMessage.warningBackgroundColor
case .Error: backgroundColor = GSMessage.errorBackgroundColor
case .Info: backgroundColor = GSMessage.infoBackgroundColor
}
if let options = options {
for option in options {
switch (option) {
case let .Animation(value): animation = value
case let .AnimationDuration(value): animationDuration = value
case let .AutoHide(value): autoHide = value
case let .AutoHideDelay(value): autoHideDelay = value
case let .Height(value): height = value
case let .HideOnTap(value): hideOnTap = value
case let .Position(value): position = value
case let .TextColor(value): textColor = value
case let .TextPadding(value): textPadding = value
}
}
}
switch position {
case .Top:
if let inViewController = inViewController {
let navigation = inViewController.navigationController ?? (inViewController as? UINavigationController)
let navigationBarHidden = (navigation?.navigationBarHidden ?? true)
let navigationBarTranslucent = (navigation?.navigationBar.translucent ?? false)
let statusBarHidden = UIApplication.sharedApplication().statusBarHidden
if !navigationBarHidden && navigationBarTranslucent && !statusBarHidden { offsetY+=20 }
if !navigationBarHidden && navigationBarTranslucent { offsetY+=44; }
if (navigationBarHidden && !statusBarHidden) { offsetY+=20 }
}
case .Bottom:
y = view.bounds.size.height - height
}
message = UIView(frame: CGRect(x: 0, y: y, width: view.bounds.size.width, height: messageHeight))
message.backgroundColor = backgroundColor
messageText = UILabel(frame: CGRect(x: textPadding, y: offsetY, width: message.bounds.size.width - textPadding * 2, height: height))
messageText.text = text
messageText.font = GSMessage.font
messageText.textColor = textColor
messageText.textAlignment = GSMessage.textAlignment
message.addSubview(messageText)
if hideOnTap { message.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "handleTap:")) }
self.view = view
}
@objc private func handleTap(tapGesture: UITapGestureRecognizer) {
hide()
}
private func removeFromSuperview() {
message.removeFromSuperview()
view?.uninstallMessage = nil
}
}
extension UIView {
private var installedMessage: GSMessage? {
get { return objc_getAssociatedObject(self, &installedMessageKey) as? GSMessage }
set { objc_setAssociatedObject(self, &installedMessageKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
private var uninstallMessage: GSMessage? {
get { return objc_getAssociatedObject(self, &uninstallMessageKey) as? GSMessage }
set { objc_setAssociatedObject(self, &uninstallMessageKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
}
private var installedMessageKey = ""
private var uninstallMessageKey = ""
private func GCDAfter(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
| mit | e91b4043b9bf7d497dc33461c3152a52 | 37.295082 | 152 | 0.638913 | 4.912723 | false | false | false | false |
richardPFisk/Alamofire | Source/AFError.swift | 1 | 21030 | //
// AFError.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with
/// their own associated reasons.
///
/// - invalidURL: Returned when a `URLConvertible` type fails to create a valid `URL`.
/// - parameterEncodingFailed: Returned when a parameter encoding object throws an error during the encoding process.
/// - multipartEncodingFailed: Returned when some step in the multipart encoding process fails.
/// - responseValidationFailed: Returned when a `validate()` call fails.
/// - responseSerializationFailed: Returned when a response serializer encounters an error in the serialization process.
public enum AFError: Error {
/// The underlying reason the parameter encoding error occurred.
///
/// - missingURL: The URL request did not have a URL to encode.
/// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the
/// encoding process.
/// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during
/// encoding process.
public enum ParameterEncodingFailureReason {
case missingURL
case jsonEncodingFailed(error: Error)
case propertyListEncodingFailed(error: Error)
}
/// The underlying reason the multipart encoding error occurred.
///
/// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a
/// file URL.
/// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty
/// `lastPathComponent` or `pathExtension.
/// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable.
/// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw
/// an error.
/// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory.
/// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by
/// the system.
/// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided
/// threw an error.
/// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`.
/// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the
/// encoded data to disk.
/// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file
/// already exists at the provided `fileURL`.
/// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is
/// not a file URL.
/// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an
/// underlying error.
/// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with
/// underlying system error.
public enum MultipartEncodingFailureReason {
case bodyPartURLInvalid(url: URL)
case bodyPartFilenameInvalid(in: URL)
case bodyPartFileNotReachable(at: URL)
case bodyPartFileNotReachableWithError(atURL: URL, error: Error)
case bodyPartFileIsDirectory(at: URL)
case bodyPartFileSizeNotAvailable(at: URL)
case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error)
case bodyPartInputStreamCreationFailed(for: URL)
case outputStreamCreationFailed(for: URL)
case outputStreamFileAlreadyExists(at: URL)
case outputStreamURLInvalid(url: URL)
case outputStreamWriteFailed(error: Error)
case inputStreamReadFailed(error: Error)
}
/// The underlying reason the response validation error occurred.
///
/// - dataFileNil: The data file containing the server response did not exist.
/// - dataFileReadFailed: The data file containing the server response could not be read.
/// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes`
/// provided did not contain wildcard type.
/// - unacceptableContentType: The response `Content-Type` did not match any type in the provided
/// `acceptableContentTypes`.
/// - unacceptableStatusCode: The response status code was not acceptable.
/// - serviceUnavailable: The response status code was HTTP 503 Service Unavailable, with a Retry-After header field set
public enum ResponseValidationFailureReason {
case dataFileNil
case dataFileReadFailed(at: URL)
case missingContentType(acceptableContentTypes: [String])
case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String)
case unacceptableStatusCode(code: Int)
case serviceUnavailable(retryAfter: RetryAfter)
}
/// The underlying reason the response serialization error occurred.
///
/// - inputDataNil: The server response contained no data.
/// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length.
/// - inputFileNil: The file containing the server response did not exist.
/// - inputFileReadFailed: The file containing the server response could not be read.
/// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`.
/// - jsonSerializationFailed: JSON serialization failed with an underlying system error.
/// - propertyListSerializationFailed: Property list serialization failed with an underlying system error.
public enum ResponseSerializationFailureReason {
case inputDataNil
case inputDataNilOrZeroLength
case inputFileNil
case inputFileReadFailed(at: URL)
case stringSerializationFailed(encoding: String.Encoding)
case jsonSerializationFailed(error: Error)
case propertyListSerializationFailed(error: Error)
}
case invalidURL(url: URLConvertible)
case parameterEncodingFailed(reason: ParameterEncodingFailureReason)
case multipartEncodingFailed(reason: MultipartEncodingFailureReason)
case responseValidationFailed(reason: ResponseValidationFailureReason)
case responseSerializationFailed(reason: ResponseSerializationFailureReason)
}
// MARK: - Adapt Error
struct AdaptError: Error {
let error: Error
}
extension Error {
var underlyingAdaptError: Error? { return (self as? AdaptError)?.error }
}
// MARK: - Error Booleans
extension AFError {
/// Returns whether the AFError is an invalid URL error.
public var isInvalidURLError: Bool {
if case .invalidURL = self { return true }
return false
}
/// Returns whether the AFError is a parameter encoding error. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isParameterEncodingError: Bool {
if case .parameterEncodingFailed = self { return true }
return false
}
/// Returns whether the AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties
/// will contain the associated values.
public var isMultipartEncodingError: Bool {
if case .multipartEncodingFailed = self { return true }
return false
}
/// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`,
/// `responseContentType`, and `responseCode` properties will contain the associated values.
public var isResponseValidationError: Bool {
if case .responseValidationFailed = self { return true }
return false
}
/// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and
/// `underlyingError` properties will contain the associated values.
public var isResponseSerializationError: Bool {
if case .responseSerializationFailed = self { return true }
return false
}
/// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`,
/// `responseContentType`, and `responseCode` properties will contain the associated values.
public var isServiceUnavailableError: Bool {
switch self {
case .responseValidationFailed(let reason):
return reason.retyAfter != nil && reason.responseCode == 503
default:
return false
}
}
}
// MARK: - Convenience Properties
extension AFError {
/// The `URLConvertible` associated with the error.
public var urlConvertible: URLConvertible? {
switch self {
case .invalidURL(let url):
return url
default:
return nil
}
}
/// The `URL` associated with the error.
public var url: URL? {
switch self {
case .multipartEncodingFailed(let reason):
return reason.url
default:
return nil
}
}
/// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`,
/// `.multipartEncodingFailed` or `.responseSerializationFailed` error.
public var underlyingError: Error? {
switch self {
case .parameterEncodingFailed(let reason):
return reason.underlyingError
case .multipartEncodingFailed(let reason):
return reason.underlyingError
case .responseSerializationFailed(let reason):
return reason.underlyingError
default:
return nil
}
}
/// The acceptable `Content-Type`s of a `.responseValidationFailed` error.
public var acceptableContentTypes: [String]? {
switch self {
case .responseValidationFailed(let reason):
return reason.acceptableContentTypes
default:
return nil
}
}
/// The response `Content-Type` of a `.responseValidationFailed` error.
public var responseContentType: String? {
switch self {
case .responseValidationFailed(let reason):
return reason.responseContentType
default:
return nil
}
}
/// The response code of a `.responseValidationFailed` error.
public var responseCode: Int? {
switch self {
case .responseValidationFailed(let reason):
return reason.responseCode
default:
return nil
}
}
public var retryAfter: RetryAfter? {
switch self {
case .responseValidationFailed(let reason):
return reason.retyAfter
default:
return nil
}
}
/// The `String.Encoding` associated with a failed `.stringResponse()` call.
public var failedStringEncoding: String.Encoding? {
switch self {
case .responseSerializationFailed(let reason):
return reason.failedStringEncoding
default:
return nil
}
}
}
extension AFError.ParameterEncodingFailureReason {
var underlyingError: Error? {
switch self {
case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error):
return error
default:
return nil
}
}
}
extension AFError.MultipartEncodingFailureReason {
var url: URL? {
switch self {
case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url),
.bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url),
.bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url),
.outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url),
.bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _):
return url
default:
return nil
}
}
var underlyingError: Error? {
switch self {
case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error),
.outputStreamWriteFailed(let error), .inputStreamReadFailed(let error):
return error
default:
return nil
}
}
}
extension AFError.ResponseValidationFailureReason {
var acceptableContentTypes: [String]? {
switch self {
case .missingContentType(let types), .unacceptableContentType(let types, _):
return types
default:
return nil
}
}
var responseContentType: String? {
switch self {
case .unacceptableContentType(_, let responseType):
return responseType
default:
return nil
}
}
var responseCode: Int? {
switch self {
case .unacceptableStatusCode(let code):
return code
case .serviceUnavailable:
return 503
default:
return nil
}
}
var retyAfter: RetryAfter? {
switch self {
case .serviceUnavailable(let retryAfter):
return retryAfter
default:
return nil
}
}
}
extension AFError.ResponseSerializationFailureReason {
var failedStringEncoding: String.Encoding? {
switch self {
case .stringSerializationFailed(let encoding):
return encoding
default:
return nil
}
}
var underlyingError: Error? {
switch self {
case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error):
return error
default:
return nil
}
}
}
// MARK: - Error Descriptions
extension AFError: LocalizedError {
public var errorDescription: String? {
switch self {
case .invalidURL(let url):
return "URL is not valid: \(url)"
case .parameterEncodingFailed(let reason):
return reason.localizedDescription
case .multipartEncodingFailed(let reason):
return reason.localizedDescription
case .responseValidationFailed(let reason):
return reason.localizedDescription
case .responseSerializationFailed(let reason):
return reason.localizedDescription
}
}
}
extension AFError.ParameterEncodingFailureReason {
var localizedDescription: String {
switch self {
case .missingURL:
return "URL request to encode was missing a URL"
case .jsonEncodingFailed(let error):
return "JSON could not be encoded because of error:\n\(error.localizedDescription)"
case .propertyListEncodingFailed(let error):
return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)"
}
}
}
extension AFError.MultipartEncodingFailureReason {
var localizedDescription: String {
switch self {
case .bodyPartURLInvalid(let url):
return "The URL provided is not a file URL: \(url)"
case .bodyPartFilenameInvalid(let url):
return "The URL provided does not have a valid filename: \(url)"
case .bodyPartFileNotReachable(let url):
return "The URL provided is not reachable: \(url)"
case .bodyPartFileNotReachableWithError(let url, let error):
return (
"The system returned an error while checking the provided URL for " +
"reachability.\nURL: \(url)\nError: \(error)"
)
case .bodyPartFileIsDirectory(let url):
return "The URL provided is a directory: \(url)"
case .bodyPartFileSizeNotAvailable(let url):
return "Could not fetch the file size from the provided URL: \(url)"
case .bodyPartFileSizeQueryFailedWithError(let url, let error):
return (
"The system returned an error while attempting to fetch the file size from the " +
"provided URL.\nURL: \(url)\nError: \(error)"
)
case .bodyPartInputStreamCreationFailed(let url):
return "Failed to create an InputStream for the provided URL: \(url)"
case .outputStreamCreationFailed(let url):
return "Failed to create an OutputStream for URL: \(url)"
case .outputStreamFileAlreadyExists(let url):
return "A file already exists at the provided URL: \(url)"
case .outputStreamURLInvalid(let url):
return "The provided OutputStream URL is invalid: \(url)"
case .outputStreamWriteFailed(let error):
return "OutputStream write failed with error: \(error)"
case .inputStreamReadFailed(let error):
return "InputStream read failed with error: \(error)"
}
}
}
extension AFError.ResponseSerializationFailureReason {
var localizedDescription: String {
switch self {
case .inputDataNil:
return "Response could not be serialized, input data was nil."
case .inputDataNilOrZeroLength:
return "Response could not be serialized, input data was nil or zero length."
case .inputFileNil:
return "Response could not be serialized, input file was nil."
case .inputFileReadFailed(let url):
return "Response could not be serialized, input file could not be read: \(url)."
case .stringSerializationFailed(let encoding):
return "String could not be serialized with encoding: \(encoding)."
case .jsonSerializationFailed(let error):
return "JSON could not be serialized because of error:\n\(error.localizedDescription)"
case .propertyListSerializationFailed(let error):
return "PropertyList could not be serialized because of error:\n\(error.localizedDescription)"
}
}
}
extension AFError.ResponseValidationFailureReason {
var localizedDescription: String {
switch self {
case .dataFileNil:
return "Response could not be validated, data file was nil."
case .dataFileReadFailed(let url):
return "Response could not be validated, data file could not be read: \(url)."
case .missingContentType(let types):
return (
"Response Content-Type was missing and acceptable content types " +
"(\(types.joined(separator: ","))) do not match \"*/*\"."
)
case .unacceptableContentType(let acceptableTypes, let responseType):
return (
"Response Content-Type \"\(responseType)\" does not match any acceptable types: " +
"\(acceptableTypes.joined(separator: ","))."
)
case .unacceptableStatusCode(let code):
return "Response status code was unacceptable: \(code)."
case .serviceUnavailable(let retryAfter):
return "Response status code was unacceptable due to Service Unavailable. Retry after: \(retryAfter)"
}
}
}
| mit | 9449f199fdd9d3b99001211979ed53bb | 41.57085 | 125 | 0.646743 | 5.526938 | false | false | false | false |
chronodm/apsu-core-swift | ApsuCore/ComponentTypeKey.swift | 1 | 549 | //
// Created by David Moles on 2/24/15.
// Copyright (c) 2015 David Moles. All rights reserved.
//
import Foundation
public class ComponentTypeKey: Hashable {
private let type: AnyClass
public let hashValue: Int
public let description: String
init<T: AnyObject>(_ type: T.Type) {
self.type = type
self.hashValue = Int(CFHash(type))
self.description = NSStringFromClass(type)
}
}
public func == (lhs: ComponentTypeKey, rhs: ComponentTypeKey) -> Bool {
return CFEqual(lhs.type, rhs.type) != 0
}
| mit | 5365dd441a65ae35eccf5139cfc0f6e9 | 20.96 | 71 | 0.663024 | 3.839161 | false | false | false | false |
crazypoo/PTools | Pods/NotificationBannerSwift/NotificationBanner/Classes/BannerPositionFrame.swift | 2 | 4892 | /*
The MIT License (MIT)
Copyright (c) 2017-2018 Dalton Hinterscher
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
public enum BannerPosition: Int {
case bottom
case top
}
class BannerPositionFrame {
private(set) var startFrame: CGRect = .zero
private(set) var endFrame: CGRect = .zero
init(
bannerPosition: BannerPosition,
bannerWidth: CGFloat,
bannerHeight: CGFloat,
maxY: CGFloat,
finishYOffset: CGFloat = 0,
edgeInsets: UIEdgeInsets?
) {
self.startFrame = startFrame(
for: bannerPosition,
bannerWidth: bannerWidth,
bannerHeight: bannerHeight,
maxY: maxY,
edgeInsets: edgeInsets
)
self.endFrame = endFrame(
for: bannerPosition,
bannerWidth: bannerWidth,
bannerHeight: bannerHeight,
maxY: maxY,
finishYOffset: finishYOffset,
edgeInsets: edgeInsets
)
}
/**
Returns the start frame for the notification banner based on the given banner position
- parameter bannerPosition: The position the notification banners should slide in from
- parameter bannerWidth: The width of the notification banner
- parameter bannerHeight: The height of the notification banner
- parameter maxY: The maximum `y` position the banner can slide in from. This value is only used
if the bannerPosition is .bottom
- parameter edgeInsets: The sides edges insets from superview
*/
private func startFrame(
for bannerPosition: BannerPosition,
bannerWidth: CGFloat,
bannerHeight: CGFloat,
maxY: CGFloat,
edgeInsets: UIEdgeInsets?
) -> CGRect {
let edgeInsets = edgeInsets ?? .zero
switch bannerPosition {
case .bottom:
return CGRect(
x: edgeInsets.left,
y: maxY,
width: bannerWidth - edgeInsets.left - edgeInsets.right,
height: bannerHeight
)
case .top:
return CGRect(
x: edgeInsets.left,
y: -bannerHeight,
width: bannerWidth - edgeInsets.left - edgeInsets.right,
height: bannerHeight
)
}
}
/**
Returns the end frame for the notification banner based on the given banner position
- parameter bannerPosition: The position the notification banners should slide in from
- parameter bannerWidth: The width of the notification banner
- parameter bannerHeight: The height of the notification banner
- parameter maxY: The maximum `y` position the banner can slide in from. This value is only used if the bannerPosition is .bottom
- parameter finishYOffset: The `y` position offset the banner can slide in. Used for displaying several banenrs simaltaneously
- parameter edgeInsets: The sides edges insets from superview
*/
private func endFrame(
for bannerPosition: BannerPosition,
bannerWidth: CGFloat,
bannerHeight: CGFloat,
maxY: CGFloat,
finishYOffset: CGFloat = 0,
edgeInsets: UIEdgeInsets?
) -> CGRect {
let edgeInsets = edgeInsets ?? .zero
switch bannerPosition {
case .bottom:
return CGRect(
x: edgeInsets.left,
y: maxY - bannerHeight - edgeInsets.bottom - finishYOffset,
width: startFrame.width,
height: startFrame.height)
case .top:
return CGRect(
x: edgeInsets.left,
y: edgeInsets.top + finishYOffset,
width: startFrame.width,
height: startFrame.height
)
}
}
}
| mit | 6e194fca35410974f38e28abbb3b4f1e | 35.507463 | 147 | 0.637163 | 5.243301 | false | false | false | false |
xumx/ditto | Ditto/ListViewController.swift | 2 | 10517 | import UIKit
class ListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var objectType: DittoObjectType
let dittoStore: DittoStore
let segmentedControl: UISegmentedControl
var tableView: UITableView!
var editButton: UIBarButtonItem!
var newButton: UIBarButtonItem!
var doneButton: UIBarButtonItem!
let defaults = NSUserDefaults(suiteName: "group.io.kern.ditto")!
init() {
objectType = .Ditto
dittoStore = DittoStore()
segmentedControl = UISegmentedControl(items: ["Categories", "Dittos"])
super.init(nibName: nil, bundle: nil)
navigationItem.titleView = segmentedControl
segmentedControl.selectedSegmentIndex = 1
segmentedControl.addTarget(self, action: Selector("segmentedControlChanged:"), forControlEvents: .ValueChanged)
editButton = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: "editButtonClicked")
newButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "newButtonClicked")
doneButton = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "doneButtonClicked")
navigationItem.leftBarButtonItem = editButton
navigationItem.rightBarButtonItem = newButton
}
override func loadView() {
tableView = UITableView(frame: CGRectZero, style: .Plain)
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(ObjectTableViewCell.classForCoder(), forCellReuseIdentifier: "ObjectTableViewCell")
view = tableView
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector:"handleAppInForeground", name:
UIApplicationWillEnterForegroundNotification, object: nil)
loadPendingDittos()
tableView.reloadData()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
var segmentedFrame = segmentedControl.frame
segmentedFrame.size.width = UIScreen.mainScreen().bounds.width * 0.5
segmentedControl.frame = segmentedFrame
}
func segmentedControlChanged(sender: AnyObject) {
switch segmentedControl.selectedSegmentIndex {
case 0:
objectType = .Category
case 1:
objectType = .Ditto
default:
fatalError("Unknown index")
}
tableView.reloadData()
}
func textForCellAtIndexPath(indexPath: NSIndexPath) -> String {
switch objectType {
case .Category:
return "\(dittoStore.getCategory(indexPath.row)) (\(dittoStore.countInCategory(indexPath.row)))"
case .Ditto:
return dittoStore.getDittoPreviewInCategory(indexPath.section, index: indexPath.row)
}
}
//==============================
// MARK: - Table View Callbacks
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
switch objectType {
case .Category: return 1
case .Ditto: return dittoStore.countCategories()
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch objectType {
case .Category: return dittoStore.countCategories()
case .Ditto: return dittoStore.countInCategory(section)
}
}
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch objectType {
case .Category: return 0
case .Ditto: return 33
}
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
switch objectType {
case .Category:
return nil
case .Ditto:
let v = CategoryHeaderView(frame: CGRectZero)
v.text = dittoStore.getCategory(section)
return v
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let text = textForCellAtIndexPath(indexPath)
return ObjectTableViewCell.heightForText(text, truncated: true, disclosure: true)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ObjectTableViewCell", forIndexPath: indexPath) as! ObjectTableViewCell
let text = textForCellAtIndexPath(indexPath)
cell.setText(text, disclosure: true)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
presentEditViewController(indexPath)
}
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
switch objectType {
case .Category: dittoStore.moveCategoryFromIndex(sourceIndexPath.row, toIndex: destinationIndexPath.row)
case .Ditto: dittoStore.moveDittoFromCategory(sourceIndexPath.section, index: sourceIndexPath.row, toCategory: destinationIndexPath.section, index: destinationIndexPath.row)
}
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
switch objectType {
case .Category:
presentRemoveCategoryWarning({ action in
self.dittoStore.removeCategoryAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Left)
})
case .Ditto:
dittoStore.removeDittoFromCategory(indexPath.section, index: indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Left)
}
}
}
//==========================
// MARK: - Button Callbacks
func newButtonClicked() {
if objectType == .Category && !dittoStore.canCreateNewCategory() {
presentMaxCategoryWarning()
} else {
presentNewViewController()
}
}
func editButtonClicked() {
segmentedControl.enabled = false
segmentedControl.userInteractionEnabled = false
navigationItem.setLeftBarButtonItem(doneButton, animated: true)
navigationItem.setRightBarButtonItem(nil, animated: true)
tableView.setEditing(true, animated: true)
}
func doneButtonClicked() {
segmentedControl.enabled = true
segmentedControl.userInteractionEnabled = true
navigationItem.setLeftBarButtonItem(editButton, animated: true)
navigationItem.setRightBarButtonItem(newButton, animated: true)
tableView.setEditing(false, animated: true)
}
//=====================================
// MARK: - Presenting View Controllers
func presentNewViewController() {
let newViewController = NewViewController(objectType: objectType)
let subnavController = NavigationController(rootViewController: newViewController)
presentViewController(subnavController, animated: true, completion: nil)
}
func presentEditViewController(indexPath: NSIndexPath) {
var editViewController: EditViewController
switch objectType {
case .Category:
editViewController = EditViewController(categoryIndex: indexPath.row)
case .Ditto:
editViewController = EditViewController(categoryIndex: indexPath.section, dittoIndex: indexPath.row)
}
let subnavController = NavigationController(rootViewController: editViewController)
presentViewController(subnavController, animated: true, completion: nil)
}
func presentMaxCategoryWarning() {
let alert = UIAlertController(title: "Warning",
message: "You can only create up to 8 categories. Delete a category before creating a new one.",
preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Okay", style: .Cancel, handler: nil))
presentViewController(alert, animated: true, completion: nil)
}
func presentRemoveCategoryWarning(handler: ((UIAlertAction!) -> Void)) {
let alert = UIAlertController(title: "Warning",
message: "Deleting a category removes all of its Dittos. Are you sure you wish to continue?",
preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Delete", style: .Destructive, handler: handler))
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
presentViewController(alert, animated: true, completion: nil)
}
//========
// Helpers
func loadPendingDittos() {
defaults.synchronize()
if let pendingDittos = defaults.dictionaryForKey("pendingDittos") as? [String:[String]] {
if let pendingCategories = defaults.arrayForKey("pendingCategories") as? [String] {
let categories = dittoStore.getCategories()
for (index, category) in categories.enumerate() {
if let dittos = pendingDittos[category] {
for ditto in dittos {
dittoStore.addDittoToCategory(index, text: ditto)
}
}
}
defaults.removeObjectForKey("pendingDittos")
defaults.removeObjectForKey("pendingCategories")
defaults.synchronize()
}
}
}
func handleAppInForeground() {
loadPendingDittos()
tableView.reloadData()
}
} | bsd-3-clause | f16a8289f002d16c8382e36c7cbb2c5b | 35.648084 | 181 | 0.634497 | 5.769062 | false | false | false | false |
kstaring/swift | stdlib/public/core/LifetimeManager.swift | 1 | 6252 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Evaluate `f()` and return its result, ensuring that `x` is not
/// destroyed before f returns.
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: () throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try body()
}
/// Evaluate `f(x)` and return its result, ensuring that `x` is not
/// destroyed before f returns.
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: (T) throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try body(x)
}
extension String {
/// Invokes the given closure on the contents of the string, represented as a
/// pointer to a null-terminated sequence of UTF-8 code units.
///
/// The `withCString(_:)` method ensures that the sequence's lifetime extends
/// through the execution of `body`. The pointer argument to `body` is only
/// valid for the lifetime of the closure. Do not escape it from the closure
/// for later use.
///
/// - Parameter body: A closure that takes a pointer to the string's UTF-8
/// code unit sequence as its sole argument. If the closure has a return
/// value, it is used as the return value of the `withCString(_:)` method.
/// The pointer argument is valid only for the duration of the closure's
/// execution.
/// - Returns: The return value of the `body` closure, if any.
public func withCString<Result>(
_ body: (UnsafePointer<Int8>) throws -> Result
) rethrows -> Result {
return try self.utf8CString.withUnsafeBufferPointer {
try body($0.baseAddress!)
}
}
}
// Fix the lifetime of the given instruction so that the ARC optimizer does not
// shorten the lifetime of x to be before this point.
@_transparent
public func _fixLifetime<T>(_ x: T) {
Builtin.fixLifetime(x)
}
/// Invokes the given closure with a mutable pointer to the given argument.
///
/// The `withUnsafeMutablePointer(to:_:)` function is useful for calling
/// Objective-C APIs that take in/out parameters (and default-constructible
/// out parameters) by pointer.
///
/// The pointer argument to `body` is valid only for the lifetime of the
/// closure. Do not escape it from the closure for later use.
///
/// - Parameters:
/// - arg: An instance to temporarily use via pointer.
/// - body: A closure that takes a mutable pointer to `arg` as its sole
/// argument. If the closure has a return value, it is used as the return
/// value of the `withUnsafeMutablePointer(to:_:)` function. The pointer
/// argument is valid only for the duration of the closure's execution.
/// - Returns: The return value of the `body` closure, if any.
///
/// - SeeAlso: `withUnsafePointer(to:_:)`
public func withUnsafeMutablePointer<T, Result>(
to arg: inout T,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafeMutablePointer<T>(Builtin.addressof(&arg)))
}
/// Invokes the given closure with a pointer to the given argument.
///
/// The `withUnsafePointer(to:_:)` function is useful for calling Objective-C
/// APIs that take in/out parameters (and default-constructible out
/// parameters) by pointer.
///
/// The pointer argument to `body` is valid only for the lifetime of the
/// closure. Do not escape it from the closure for later use.
///
/// - Parameters:
/// - arg: An instance to temporarily use via pointer.
/// - body: A closure that takes a pointer to `arg` as its sole argument. If
/// the closure has a return value, it is used as the return value of the
/// `withUnsafePointer(to:_:)` function. The pointer argument is valid
/// only for the duration of the closure's execution.
/// - Returns: The return value of the `body` closure, if any.
///
/// - SeeAlso: `withUnsafeMutablePointer(to:_:)`
public func withUnsafePointer<T, Result>(
to arg: inout T,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafePointer<T>(Builtin.addressof(&arg)))
}
@available(*, unavailable, renamed: "withUnsafeMutablePointer(to:_:)")
public func withUnsafeMutablePointer<T, Result>(
_ arg: inout T,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result
{
Builtin.unreachable()
}
@available(*, unavailable, renamed: "withUnsafePointer(to:_:)")
public func withUnsafePointer<T, Result>(
_ arg: inout T,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafeMutablePointer(to:_:) instead")
public func withUnsafeMutablePointers<A0, A1, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ body: (
UnsafeMutablePointer<A0>, UnsafeMutablePointer<A1>) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafeMutablePointer(to:_:) instead")
public func withUnsafeMutablePointers<A0, A1, A2, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ arg2: inout A2,
_ body: (
UnsafeMutablePointer<A0>,
UnsafeMutablePointer<A1>,
UnsafeMutablePointer<A2>
) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafePointer(to:_:) instead")
public func withUnsafePointers<A0, A1, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ body: (UnsafePointer<A0>, UnsafePointer<A1>) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafePointer(to:_:) instead")
public func withUnsafePointers<A0, A1, A2, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ arg2: inout A2,
_ body: (
UnsafePointer<A0>,
UnsafePointer<A1>,
UnsafePointer<A2>
) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
| apache-2.0 | 3ac8c53e3ba66bf0086e3b987b482233 | 34.123596 | 88 | 0.676743 | 4.078278 | false | false | false | false |
alfishe/mooshimeter-osx | mooshimeter-osx/Measurements/MeterReading.swift | 1 | 3099 | //
// Created by Dev on 8/27/16.
// Copyright (c) 2016 alfishe. All rights reserved.
//
import Foundation
class MeterReading
{
var value: Float
var digits: UInt16
var maxValue: Float
var prefix: MetricPrefix
var prefixMultiplier: Float
var prefixScale: Int
var uom: UnitsOfMeasure
var formattedValue: Float
init(value: Float, uom: UnitsOfMeasure)
{
self.value = value
self.digits = 100
self.maxValue = 0
self.uom = uom
self.prefix = .noPrefix
self.prefixMultiplier = Float(UOMHelper.sharedInstance.prefixMultipliers[self.prefix]!)
self.prefixScale = UOMHelper.sharedInstance.prefixScale[self.prefix]!
self.formattedValue = 0
self.determineValueRange(value)
}
init(value: Float, digits: UInt16, maxValue: Float, uom: UnitsOfMeasure)
{
self.value = value
self.digits = digits
self.maxValue = maxValue
self.uom = uom
self.prefix = .noPrefix
self.prefixMultiplier = Float(UOMHelper.sharedInstance.prefixMultipliers[self.prefix]!)
self.prefixScale = UOMHelper.sharedInstance.prefixScale[self.prefix]!
self.formattedValue = 0
self.determineValueRange(value)
}
func toString() -> String
{
let result = String.init(format: "%f %@%@", self.formattedValue, UOMHelper.sharedInstance.prefixShortName[self.prefix]!, self.uom.description)
return result
}
func toStringUOM() -> String
{
let result = self.uom.description
return result
}
func isInRange() -> Bool
{
var result = false
if self.value < self.maxValue
{
result = false
}
return result
}
func multiplyReadings(_ reading1: MeterReading, reading2: MeterReading) -> MeterReading
{
let resultValue = reading1.value * reading2.value
let resultDigits = (reading1.digits + reading2.digits) / 2
let resultMaxValue = reading1.maxValue * reading2.maxValue
var resultUOM: UnitsOfMeasure = .undefined
if (reading1.uom == .ampers && reading2.uom == .volts) || (reading1.uom == .volts && reading2.uom == .ampers)
{
resultUOM = .watts
}
let result = MeterReading(
value: resultValue,
digits: resultDigits,
maxValue: resultMaxValue,
uom: resultUOM
)
return result
}
//MARK: -
//MARK: Helper methods
func determineValueRange(_ value: Float)
{
let absValue = Double(abs(value))
let sign: Double = value > 0 ? 1 : -1
for prefix in UOMHelper.sharedInstance.prefixMultipliers
{
let multiplier = prefix.value
let prefixedValue = absValue / multiplier
if prefixedValue > 0 && prefixedValue < 1000
{
let prefixScale = UOMHelper.sharedInstance.prefixScale[self.prefix]!
let formattedValue = Float(sign * prefixedValue.round(to: prefixScale))
self.formattedValue = formattedValue
self.prefix = prefix.key;
self.prefixMultiplier = Float(UOMHelper.sharedInstance.prefixMultipliers[self.prefix]!)
self.prefixScale = prefixScale
break
}
}
}
}
| mit | 32fd5d0298fd7f8ebad2c5d36fbb408d | 24.825 | 146 | 0.660536 | 3.962916 | false | false | false | false |
le-lerot/altim | Altim/CameraViewController.swift | 1 | 2605 | //
// CameraViewController.swift
// Altim
//
// Created by Martin Delille on 23/12/2016.
// Copyright ยฉ 2016 Phonations. All rights reserved.
//
import UIKit
import AVFoundation
import CoreMotion
class CameraViewController: UIViewController {
var cameraPreviewLayer: AVCaptureVideoPreviewLayer?
var hudLayer = CAShapeLayer()
var motionManager = CMMotionManager()
@IBOutlet weak var cameraView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let session = AVCaptureSession()
session.sessionPreset = AVCaptureSessionPresetHigh
let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
do {
let input = try AVCaptureDeviceInput(device: device)
session.addInput(input)
// Create video preview layer and add it to the UI
if let newCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: session) {
let viewLayer = self.cameraView.layer
let size = self.cameraView.bounds
newCaptureVideoPreviewLayer.frame = size;
viewLayer.addSublayer(newCaptureVideoPreviewLayer)
self.cameraPreviewLayer = newCaptureVideoPreviewLayer;
session.startRunning()
let textLayer = CATextLayer()
textLayer.string = "coucou"
textLayer.frame = CGRect(x: 0, y: 20, width: size.width, height: 40)
viewLayer.addSublayer(textLayer)
hudLayer.backgroundColor = UIColor.red.cgColor
hudLayer.frame = CGRect(x: size.width / 2 - 20, y: 0, width: 40, height: size.height)
viewLayer.addSublayer(hudLayer)
}
} catch {
print(error)
}
motionManager.deviceMotionUpdateInterval = 0.1
motionManager.startDeviceMotionUpdates(to: OperationQueue.main) { (deviceMotion, error) in
if let yaw = deviceMotion?.attitude.yaw {
let size = self.cameraView.bounds
let x = CGFloat(yaw) * size.width
self.hudLayer.frame = CGRect(x: x, y: 0, width: 10, height: size.height)
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-3.0 | 12a03623b30528831346da16e54061e3 | 31.55 | 107 | 0.63172 | 5.197605 | false | false | false | false |
WaterReporter/WaterReporter-iOS | WaterReporter/Pods/ActiveLabel/ActiveLabel/RegexParser.swift | 1 | 831 | //
// RegexParser.swift
// ActiveLabel
//
// Created by Pol Quintana on 06/01/16.
// Copyright ยฉ 2016 Optonaut. All rights reserved.
//
import Foundation
struct RegexParser {
static let hashtagPattern = "(?:^|\\s|$)#[\\p{L}0-9_]*"
static let mentionPattern = "(?:^|\\s|$|[.])@[\\p{L}0-9_]*"
static let urlPattern = "(^|[\\s.:;?\\-\\]<\\(])" +
"((https?://|www\\.|pic\\.)[-\\w;/?:@&=+$\\|\\_.!~*\\|'()\\[\\]%#,โบ]+[\\w/#](\\(\\))?)" +
"(?=$|[\\s',\\|\\(\\).:;?\\-\\[\\]>\\)])"
static func getElements(from text: String, with pattern: String, range: NSRange) -> [NSTextCheckingResult]{
guard let elementRegex = try? NSRegularExpression(pattern: pattern, options: [.CaseInsensitive]) else { return [] }
return elementRegex.matchesInString(text, options: [], range: range)
}
} | agpl-3.0 | b38322e69c516c7a7e9769f8ec9f2344 | 33.541667 | 123 | 0.533816 | 3.352227 | false | false | false | false |
ITzTravelInTime/TINU | TINU/SettingsSectionItem.swift | 1 | 6860 | /*
TINU, the open tool to create bootable macOS installers.
Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import Cocoa
public class SettingsSectionItem: NSView{
static var surface: NSView!
var image = NSImageView()
var name = NSTextField()
var isSelected = false
var id = OtherOptionsViewController.SectionsID(rawValue: 0)!
var itemsScrollView: NSScrollView?
let normalColor = NSColor.transparent.cgColor
var selectedColor = NSColor.selectedControlColor.cgColor
var imageColor = NSColor.systemGray
override public func draw(_ dirtyRect: NSRect) {
/*
if isSelected{
self.backgroundColor = NSColor.selectedControlColor
}else{
self.backgroundColor = NSColor.transparent
}
*/
image.frame.size = NSSize(width: (self.frame.size.width / 5) - 10, height: self.frame.height - 10)
image.frame.origin = NSPoint(x: 5, y: 5)
image.imageAlignment = .alignCenter
image.imageScaling = .scaleProportionallyUpOrDown
image.isEditable = false
self.addSubview(image)
var h: CGFloat = 18
var n: CGFloat = 1
for c in name.stringValue{
if c == "\n"{
n += 1
}
}
h *= n
name.frame.size = NSSize(width: (self.frame.size.width / 5) * 4 - 5, height: h)
name.frame.origin = NSPoint(x: image.frame.origin.x + image.frame.size.width + 5, y: self.frame.height / 2 - name.frame.height / 2)
name.isEditable = false
name.isSelectable = false
name.drawsBackground = false
name.isBordered = false
name.isBezeled = false
name.alignment = .left
name.font = NSFont.systemFont(ofSize: 13)
self.addSubview(name)
}
override public func updateLayer() {
super.updateLayer()
if #available(macOS 10.14, *), look.usesSFSymbols() {
selectedColor = NSColor.controlAccentColor.cgColor
} else {
selectedColor = NSColor.selectedControlColor.cgColor
}
if isSelected{
if look.usesSFSymbols(){
self.layer?.cornerRadius = 3
}
self.layer?.backgroundColor = selectedColor
}else{
self.layer?.backgroundColor = normalColor
}
if #available(macOS 10.14, *), look.usesSFSymbols() && isSelected {
self.name.textColor = NSColor.selectedMenuItemTextColor
}else{
self.name.textColor = NSColor.textColor
}
if #available(macOS 11.0, *), look.usesSFSymbols(){
self.image.contentTintColor = isSelected ? self.name.textColor : self.imageColor
}
}
override public func mouseDown(with event: NSEvent) {
select()
}
func select(){
makeSelected()
addSettingsToScrollView()
}
public func makeSelected(){
for vv in self.superview?.subviews ?? []{
if let v = vv as? SettingsSectionItem, v != self{
v.makeNormal()
}
}
isSelected = true
updateLayer()
}
public func makeNormal(){
isSelected = false
updateLayer()
}
public func addSettingsToScrollView(){
guard let scrollView = itemsScrollView else { return }
scrollView.documentView = NSView()
scrollView.verticalScroller?.isHidden = false
SettingsSectionItem.surface = NSView()
switch id{
case OtherOptionsViewController.SectionsID.generalOptions, OtherOptionsViewController.SectionsID.advancedOptions:
let isAdvanced = (id == OtherOptionsViewController.SectionsID.advancedOptions)
let itemHeigth: CGFloat = 30
var isGray = true
SettingsSectionItem.surface.frame.origin = CGPoint.zero
SettingsSectionItem.surface.frame.size = NSSize.init(width: scrollView.frame.size.width - 20, height: itemHeigth * (CGFloat(cvm.shared.options.list.count)))
var count: CGFloat = 0
for i in cvm.shared.options.list.sorted(by: { $0.0.rawValue > $1.0.rawValue }){
if !(i.value.isVisible && (i.value.isAdvanced == isAdvanced)){
SettingsSectionItem.surface.frame.size.height -= itemHeigth
continue
}
let item = OtherOptionsCheckBox(frame: NSRect(x: 0, y: count, width: SettingsSectionItem.surface.frame.size.width, height: itemHeigth))
item.optionID = i.value.id
isGray.toggle()
count += itemHeigth
SettingsSectionItem.surface.addSubview(item)
//surface.frame.size = CGSize(width: surface.frame.size.width, height: surface.frame.size.height + itemHeigth)
}
if SettingsSectionItem.surface.frame.height < scrollView.frame.height{
let h = scrollView.frame.height - 2
let w = scrollView.frame.width - 2
let delta = (h - SettingsSectionItem.surface.frame.height)
SettingsSectionItem.surface.frame.size.height = h
SettingsSectionItem.surface.frame.size.width = w
scrollView.hasVerticalScroller = false
//scrollView.verticalScrollElasticity = .none
scrollView.verticalScrollElasticity = .automatic
for item in SettingsSectionItem.surface.subviews{
item.frame.size.width = w
item.frame.origin.y += delta
}
}else{
scrollView.hasVerticalScroller = true
scrollView.verticalScrollElasticity = .automatic
}
scrollView.documentView = SettingsSectionItem.surface
case OtherOptionsViewController.SectionsID.eFIFolderReplacementClover, OtherOptionsViewController.SectionsID.eFIFolderReplacementOpenCore:
//efi replacement menu
#if useEFIReplacement && !macOnlyMode
SettingsSectionItem.surface = EFIReplacementView.init(frame: NSRect(origin: CGPoint.zero, size: NSSize(width: scrollView.frame.size.width - 17, height: scrollView.frame.size.height - 2))) as NSView
scrollView.documentView = SettingsSectionItem.surface
switch id{
case OtherOptionsViewController.SectionsID.eFIFolderReplacementClover:
(SettingsSectionItem.surface as? EFIReplacementView)!.bootloader = .clover
break
case OtherOptionsViewController.SectionsID.eFIFolderReplacementOpenCore:
(SettingsSectionItem.surface as? EFIReplacementView)!.bootloader = .openCore
break
default:
break
}
scrollView.verticalScrollElasticity = .none
#else
break
#endif
default:
break
}
SettingsSectionItem.surface.draw(SettingsSectionItem.surface.frame)
if let documentView = scrollView.documentView{
documentView.scroll(NSPoint.init(x: 0, y: documentView.bounds.size.height))
}
}
}
| gpl-2.0 | 552abfc4c0e0fc32b974e22456c37aa6 | 27.347107 | 200 | 0.721137 | 3.819599 | false | false | false | false |
playbasis/native-sdk-ios | PlaybasisSDK/Classes/PBModel/PBAuthenticationToken.swift | 1 | 1792 | //
// AuthenticationToken.swift
// Idea
//
// Created by Mรฉdรฉric Petit on 4/20/2559 BE.
// Copyright ยฉ 2559 playbasis. All rights reserved.
//
import UIKit
import SAMKeychain
import ObjectMapper
let expirationDateKey:String = "expirationDateKey"
class PBAuthenticationToken: Mappable {
var token:String? = nil
var expirationDate:NSDate? = nil
init(apiResponse:PBApiResponse) {
Mapper<PBAuthenticationToken>().map(apiResponse.parsedJson, toObject: self)
}
init() {
self.getFromKeychain()
}
required init?(_ map: Map){
}
func mapping(map: Map) {
token <- map["token"]
expirationDate <- (map["date_expire"], ISO8601DateTransform())
self.saveInKeychain()
}
func isExpiredOrInvalid() -> Bool {
return expirationDate == nil || self.token == nil || (expirationDate!.compare(NSDate()) == .OrderedAscending || expirationDate!.compare(NSDate()) == .OrderedSame)
}
private func saveInKeychain() {
if let token = self.token {
PBDataManager.sharedInstance.saveToken(token, withType: .AuthenticationToken)
PBDataManager.sharedInstance.saveValue(expirationDate, forKey: expirationDateKey)
}
}
private func clearKeyChain() {
PBDataManager.sharedInstance.clearToken()
PBDataManager.sharedInstance.unsetValueFromKey(expirationDateKey)
}
func getFromKeychain() {
self.token = PBDataManager.sharedInstance.getTokenWithType(.AuthenticationToken)
self.expirationDate = PBDataManager.sharedInstance.valueForKey(expirationDateKey) as? NSDate
}
func invalidate() {
self.token = nil
self.expirationDate = nil
self.clearKeyChain()
}
}
| mit | 68a7242ff45c686a1dcad74673c531c5 | 27.396825 | 170 | 0.65735 | 4.732804 | false | false | false | false |
benlangmuir/swift | test/stdlib/subString.swift | 9 | 9167 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// UNSUPPORTED: freestanding
import StdlibUnittest
var SubstringTests = TestSuite("SubstringTests")
func checkMatch<S: Collection, T: Collection>(_ x: S, _ y: T, _ i: S.Index)
where S.Index == T.Index, S.Iterator.Element == T.Iterator.Element,
S.Iterator.Element: Equatable
{
expectEqual(x[i], y[i])
}
func checkMatchContiguousStorage<S: Collection, T: Collection>(_ x: S, _ y: T)
where S.Element == T.Element, S.Element: Equatable
{
let xElement = x.withContiguousStorageIfAvailable { $0.first }
let yElement = y.withContiguousStorageIfAvailable { $0.first }
expectEqual(xElement, yElement)
}
func checkHasContiguousStorage<S: Collection>(_ x: S) {
expectTrue(x.withContiguousStorageIfAvailable { _ in true } ?? false)
}
func checkHasContiguousStorageSubstring(_ x: Substring.UTF8View) {
let hasStorage = x.withContiguousStorageIfAvailable { _ in true } ?? false
expectTrue(hasStorage)
}
SubstringTests.test("Equality") {
let s = "abcdefg"
let s1 = s[s.index(s.startIndex, offsetBy: 2) ..<
s.index(s.startIndex, offsetBy: 4)]
let s2 = s1[s1.startIndex..<s1.endIndex]
let s3 = s2[s1.startIndex..<s1.endIndex]
expectEqual(s1, "cd")
expectEqual(s2, "cd")
expectEqual(s3, "cd")
expectTrue("" == s.dropFirst(s.count))
expectTrue(s.dropFirst().dropFirst(s.count) == s.dropFirst(s.count))
expectEqual("ab" as String, s.prefix(2))
expectEqual("fg" as String, s.suffix(2))
#if _runtime(_ObjC)
expectTrue(s == s[...])
expectTrue(s[...] == s)
expectTrue(s.dropFirst(2) != s)
expectTrue(s == s.dropFirst(0))
expectTrue(s != s.dropFirst(1))
expectTrue(s != s.dropLast(1))
expectEqual(s[...], s[...])
expectEqual(s.dropFirst(0), s.dropFirst(0))
expectTrue(s == s.dropFirst(0))
expectTrue(s.dropFirst(2) != s.dropFirst(1))
expectNotEqual(s.dropLast(2), s.dropLast(1))
expectEqual(s.dropFirst(1), s.dropFirst(1))
expectTrue(s != s[...].dropFirst(1))
#endif
// equatable conformance
expectTrue("one,two,three".split(separator: ",").contains("two"))
expectTrue("one,two,three".split(separator: ",") == ["one","two","three"])
}
#if _runtime(_ObjC)
SubstringTests.test("Equality/Emoji")
.xfail(.osxMinor(10, 9, reason: "Mac OS X 10.9 has an old ICU"))
.xfail(.iOSMajor(7, reason: "iOS 7 has an old ICU"))
.code {
let s = "abcdefg"
let emoji: String = s + "๐๐๐ฝ๐ซ๐ท๐ฉโ๐ฉโ๐งโ๐ฆ๐" + "๐ก๐ง๐ช๐จ๐ฆ๐ฎ๐ณ"
let i = emoji.firstIndex(of: "๐")!
expectEqual("๐๐๐ฝ" as String, emoji[i...].prefix(2))
expectTrue("๐๐๐ฝ๐ซ๐ท๐ฉโ๐ฉโ๐งโ๐ฆ๐๐ก๐ง๐ช" as String == emoji[i...].dropLast(2))
expectTrue("๐ซ๐ท๐ฉโ๐ฉโ๐งโ๐ฆ๐๐ก๐ง๐ช" as String == emoji[i...].dropLast(2).dropFirst(2))
expectTrue(s as String != emoji[i...].dropLast(2).dropFirst(2))
expectEqualSequence("๐๐๐ฝ๐ซ๐ท๐ฉโ๐ฉโ๐งโ๐ฆ๐๐ก๐ง๐ช" as String, emoji[i...].dropLast(2))
expectEqualSequence("๐ซ๐ท๐ฉโ๐ฉโ๐งโ๐ฆ๐๐ก๐ง๐ช" as String, emoji[i...].dropLast(2).dropFirst(2))
}
#endif
SubstringTests.test("Comparison") {
var s = "abc"
s += "defg"
expectFalse(s < s[...])
expectTrue(s <= s[...])
expectTrue(s >= s[...])
expectFalse(s > s[...])
expectFalse(s[...] < s)
expectTrue(s[...] <= s)
expectTrue(s[...] >= s)
expectFalse(s[...] > s)
expectFalse(s[...] < s[...])
expectTrue(s[...] <= s[...])
expectTrue(s[...] >= s[...])
expectFalse(s[...] > s[...])
expectTrue(s < s.dropFirst())
expectFalse(s > s.dropFirst())
expectFalse(s < s.dropLast())
expectTrue(s > s.dropLast())
expectTrue(s.dropFirst() < s.dropFirst(2))
expectFalse(s.dropFirst() > s.dropFirst(2))
expectFalse(s.dropLast() < s.dropLast(2))
expectTrue(s.dropLast() > s.dropLast(2))
expectFalse(s.dropFirst() < s.dropFirst().dropLast())
expectTrue(s.dropFirst() > s.dropFirst().dropLast())
expectTrue(s.dropFirst() > s)
expectTrue(s.dropFirst() > s[...])
expectTrue(s >= s[...])
expectTrue(s.dropFirst() >= s.dropFirst())
// comparable conformance
expectEqualSequence("pen,pineapple,apple,pen".split(separator: ",").sorted(),
["apple", "pen", "pen", "pineapple"])
}
SubstringTests.test("Filter") {
var name = "๐Edward Woodward".dropFirst()
var filtered = name.filter { $0 != "d" }
expectType(Substring.self, &name)
expectType(String.self, &filtered)
expectEqual("Ewar Woowar", filtered)
}
SubstringTests.test("CharacterView") {
let s = "abcdefg"
var t = s.dropFirst(2)
var u = t.dropFirst(2)
checkMatch(s, t, t.startIndex)
checkMatch(s, t, t.index(after: t.startIndex))
checkMatch(s, t, t.index(before: t.endIndex))
checkMatch(s, t, u.startIndex)
checkMatch(t, u, u.startIndex)
checkMatch(t, u, u.index(after: u.startIndex))
checkMatch(t, u, u.index(before: u.endIndex))
expectEqual("", String(t.dropFirst(10)))
expectEqual("", String(t.dropLast(10)))
expectEqual("", String(u.dropFirst(10)))
expectEqual("", String(u.dropLast(10)))
t.replaceSubrange(t.startIndex...t.startIndex, with: ["C"])
u.replaceSubrange(u.startIndex...u.startIndex, with: ["E"])
expectEqual(String(u), "Efg")
expectEqual(String(t), "Cdefg")
expectEqual(s, "abcdefg")
}
SubstringTests.test("UnicodeScalars") {
let s = "abcdefg"
var t = s.unicodeScalars.dropFirst(2)
var u = t.dropFirst(2)
checkMatch(s.unicodeScalars, t, t.startIndex)
checkMatch(s.unicodeScalars, t, t.index(after: t.startIndex))
checkMatch(s.unicodeScalars, t, t.index(before: t.endIndex))
checkMatch(s.unicodeScalars, t, u.startIndex)
checkMatch(t, u, u.startIndex)
checkMatch(t, u, u.index(after: u.startIndex))
checkMatch(t, u, u.index(before: u.endIndex))
expectEqual("", String(t.dropFirst(10)))
expectEqual("", String(t.dropLast(10)))
expectEqual("", String(u.dropFirst(10)))
expectEqual("", String(u.dropLast(10)))
t.replaceSubrange(t.startIndex...t.startIndex, with: ["C"])
u.replaceSubrange(u.startIndex...u.startIndex, with: ["E"])
expectEqual(String(u), "Efg")
expectEqual(String(t), "Cdefg")
expectEqual(s, "abcdefg")
}
SubstringTests.test("UTF16View") {
let s = "abcdefg"
let t = s.utf16.dropFirst(2)
let u = t.dropFirst(2)
checkMatch(s.utf16, t, t.startIndex)
checkMatch(s.utf16, t, t.index(after: t.startIndex))
checkMatch(s.utf16, t, t.index(before: t.endIndex))
checkMatch(s.utf16, t, u.startIndex)
checkMatch(t, u, u.startIndex)
checkMatch(t, u, u.index(after: u.startIndex))
checkMatch(t, u, u.index(before: u.endIndex))
expectEqual("", String(t.dropFirst(10))!)
expectEqual("", String(t.dropLast(10))!)
expectEqual("", String(u.dropFirst(10))!)
expectEqual("", String(u.dropLast(10))!)
}
SubstringTests.test("Mutate Substring through utf16 view") {
let s = "abcdefg"
var ss = s[...]
expectEqual(s.startIndex, ss.startIndex)
expectEqual(s.count, ss.count)
let first = ss.utf16.removeFirst()
expectEqual(s.index(after: s.startIndex), ss.startIndex)
expectEqual(s.count - 1, ss.count)
}
SubstringTests.test("Mutate Substring through unicodeScalars view") {
let s = "abcdefg"
var ss = s[...]
expectEqual(s.startIndex, ss.startIndex)
expectEqual(s.count, ss.count)
ss.unicodeScalars.append("h")
expectEqual(s.startIndex, ss.startIndex)
expectEqual(s.count + 1, ss.count)
expectEqual(ss.last, "h")
expectEqual(s.last, "g")
}
SubstringTests.test("UTF8View") {
let strs = [
"abcdefg", // Small ASCII
"abรฉร", // Small Unicode
"012345678901234567890", // Large ASCII
"abรฉร012345678901234567890", // Large Unicode
]
for s in strs {
let count = s.count
let t = s.utf8.dropFirst(2)
let u = t.dropFirst(2)
checkMatch(s.utf8, t, t.startIndex)
checkMatch(s.utf8, t, t.index(after: t.startIndex))
checkMatch(s.utf8, t, u.startIndex)
checkMatch(t, u, u.startIndex)
checkMatch(t, u, u.index(after: u.startIndex))
expectEqual("", String(t.dropFirst(100))!)
expectEqual("", String(t.dropLast(100))!)
expectEqual("", String(u.dropFirst(100))!)
expectEqual("", String(u.dropLast(100))!)
checkHasContiguousStorage(s.utf8) // Strings always do
checkHasContiguousStorageSubstring(t)
checkHasContiguousStorageSubstring(u)
checkMatchContiguousStorage(Array(s.utf8), s.utf8)
// The specialization for Substring.withContiguousStorageIfAvailable was
// added in https://github.com/apple/swift/pull/29146.
guard #available(SwiftStdlib 5.3, *) else {
return
}
checkHasContiguousStorage(t)
checkHasContiguousStorage(u)
checkMatchContiguousStorage(Array(t), t)
checkMatchContiguousStorage(Array(u), u)
}
}
SubstringTests.test("Persistent Content") {
var str = "abc"
str += "def"
expectEqual("bcdefg", str.dropFirst(1) + "g")
expectEqual("bcdefg", (str.dropFirst(1) + "g") as String)
}
SubstringTests.test("Substring.base") {
let str = "abรฉร01๐๐๐จโ๐จโ๐งโ๐ฆ"
expectEqual(str, str.dropLast().base)
for idx in str.indices {
expectEqual(str, str[idx...].base)
expectEqual(str, str[...idx].base)
}
}
runAllTests()
| apache-2.0 | 0ae2a8f7e5e9ce816706194d50806064 | 30.238596 | 86 | 0.661799 | 3.312128 | false | true | false | false |
mozilla-mobile/firefox-ios | Tests/SyncTests/MockSyncServerTests.swift | 2 | 9151 | // 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 Shared
import Account
import Storage
@testable import Sync
import UIKit
import XCTest
class MockSyncServerTests: XCTestCase {
var server: MockSyncServer!
var client: Sync15StorageClient!
override func setUp() {
server = MockSyncServer(username: "1234567")
server.start()
client = getClient(server: server)
}
private func getClient(server: MockSyncServer) -> Sync15StorageClient? {
guard let url = server.baseURL.asURL else {
XCTFail("Couldn't get URL.")
return nil
}
let authorizer: Authorizer = identity
let queue = DispatchQueue.global(qos: DispatchQoS.background.qosClass)
return Sync15StorageClient(serverURI: url, authorizer: authorizer, workQueue: queue, resultQueue: queue, backoff: MockBackoffStorage())
}
func testDeleteSpec() {
// Deletion of a collection path itself, versus trailing slash, sets the right flags.
let all = SyncDeleteRequestSpec.fromPath(path: "/1.5/123456/storage/bookmarks", withQuery: [:])!
XCTAssertTrue(all.wholeCollection)
XCTAssertNil(all.ids)
let some = SyncDeleteRequestSpec.fromPath(path: "/1.5/123456/storage/bookmarks", withQuery: ["ids": "123456,abcdef" as AnyObject])!
XCTAssertFalse(some.wholeCollection)
XCTAssertEqual(["123456", "abcdef"], some.ids!)
let one = SyncDeleteRequestSpec.fromPath(path: "/1.5/123456/storage/bookmarks/123456", withQuery: [:])!
XCTAssertFalse(one.wholeCollection)
XCTAssertNil(one.ids)
}
func testInfoCollections() {
server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: Bytes.generateGUID(), modified: 0)], inCollection: "bookmarks", now: 1326251111000)
server.storeRecords(records: [], inCollection: "tabs", now: 1326252222500)
server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: Bytes.generateGUID(), modified: 0)], inCollection: "bookmarks", now: 1326252222000)
server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: Bytes.generateGUID(), modified: 0)], inCollection: "clients", now: 1326253333000)
let expectation = self.expectation(description: "Waiting for result.")
let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))!
client.getInfoCollections().upon { result in
XCTAssertNotNil(result.successValue)
guard let response = result.successValue else {
expectation.fulfill()
return
}
let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))!
// JSON contents.
XCTAssertEqual(response.value.collectionNames().sorted(), ["bookmarks", "clients", "tabs"])
XCTAssertEqual(response.value.modified("bookmarks"), 1326252222000)
XCTAssertEqual(response.value.modified("clients"), 1326253333000)
// X-Weave-Timestamp.
XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds)
XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after)
// X-Weave-Records.
XCTAssertEqual(response.metadata.records, 3) // bookmarks, clients, tabs.
// X-Last-Modified, max of all collection modified timestamps.
XCTAssertEqual(response.metadata.lastModifiedMilliseconds, 1326253333000)
expectation.fulfill()
}
waitForExpectations(timeout: 10, handler: nil)
}
func testGet() {
server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: "guid", modified: 0)], inCollection: "bookmarks", now: 1326251111000)
let collectionClient = client.clientForCollection("bookmarks", encrypter: getEncrypter())
let expectation = self.expectation(description: "Waiting for result.")
let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))!
collectionClient.get("guid").upon { result in
XCTAssertNotNil(result.successValue)
guard let response = result.successValue else {
expectation.fulfill()
return
}
let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))!
// JSON contents.
XCTAssertEqual(response.value.id, "guid")
XCTAssertEqual(response.value.modified, 1326251111000)
// X-Weave-Timestamp.
XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds)
XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after)
// X-Weave-Records.
XCTAssertNil(response.metadata.records)
// X-Last-Modified.
XCTAssertEqual(response.metadata.lastModifiedMilliseconds, 1326251111000)
expectation.fulfill()
}
waitForExpectations(timeout: 10, handler: nil)
// And now a missing record, which should produce a 404.
collectionClient.get("missing").upon { result in
XCTAssertNotNil(result.failureValue)
guard let response = result.failureValue else {
expectation.fulfill()
return
}
XCTAssertNotNil(response as? NotFound<HTTPURLResponse>)
}
}
func testWipeStorage() {
server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: "a", modified: 0)], inCollection: "bookmarks", now: 1326251111000)
server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: "b", modified: 0)], inCollection: "bookmarks", now: 1326252222000)
server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: "c", modified: 0)], inCollection: "clients", now: 1326253333000)
server.storeRecords(records: [], inCollection: "tabs")
// For now, only testing wiping the storage root, which is the only thing we use in practice.
let expectation = self.expectation(description: "Waiting for result.")
let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))!
client.wipeStorage().upon { result in
XCTAssertNotNil(result.successValue)
guard let response = result.successValue else {
expectation.fulfill()
return
}
let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))!
// JSON contents: should be the empty object.
let jsonData = try! response.value.rawData()
let jsonString = String(data: jsonData, encoding: .utf8)!
XCTAssertEqual(jsonString, "{}")
// X-Weave-Timestamp.
XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds)
XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after)
// X-Weave-Records.
XCTAssertNil(response.metadata.records)
// X-Last-Modified.
XCTAssertNil(response.metadata.lastModifiedMilliseconds)
// And we really wiped the data.
XCTAssertTrue(self.server.collections.isEmpty)
expectation.fulfill()
}
waitForExpectations(timeout: 10, handler: nil)
}
func testPut() {
// For now, only test uploading crypto/keys. There's nothing special about this PUT, however.
let expectation = self.expectation(description: "Waiting for result.")
let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))!
client.uploadCryptoKeys(Keys.random(), withSyncKeyBundle: KeyBundle.random(), ifUnmodifiedSince: nil).upon { result in
XCTAssertNotNil(result.successValue)
guard let response = result.successValue else {
expectation.fulfill()
return
}
let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))!
// Contents: should be just the record timestamp.
XCTAssertLessThanOrEqual(before, response.value)
XCTAssertLessThanOrEqual(response.value, after)
// X-Weave-Timestamp.
XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds)
XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after)
// X-Weave-Records.
XCTAssertNil(response.metadata.records)
// X-Last-Modified.
XCTAssertNil(response.metadata.lastModifiedMilliseconds)
// And we really uploaded the record.
XCTAssertNotNil(self.server.collections["crypto"])
XCTAssertNotNil(self.server.collections["crypto"]?.records["keys"])
expectation.fulfill()
}
waitForExpectations(timeout: 10, handler: nil)
}
}
| mpl-2.0 | 7d8ab583e3122bbd71e3c386081cd7b6 | 45.928205 | 160 | 0.666812 | 5.440547 | false | true | false | false |
malaonline/iOS | mala-ios/Controller/Profile/CommentViewController.swift | 1 | 2929 | //
// CommentViewController.swift
// mala-ios
//
// Created by ็ๆฐๅฎ on 16/6/7.
// Copyright ยฉ 2016ๅนด Mala Online. All rights reserved.
//
import UIKit
import ESPullToRefresh
private let CommentViewCellReuseId = "CommentViewCellReuseId"
class CommentViewController: BaseTableViewController {
// MARK: - Property
/// ไผๆ ๅธๆจกๅๆฐ็ป
var models: [StudentCourseModel] = [] {
didSet {
handleModels(models, tableView: tableView)
}
}
/// ๆฏๅฆๆญฃๅจๆๅๆฐๆฎ
var isFetching: Bool = false
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupUserInterface()
configure()
loadCourse()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
sendScreenTrack(SAMyCommentsViewName)
// ๅผๅฏไธๆๅทๆฐ
tableView.es_startPullToRefresh()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Private Method
private func configure() {
tableView.es_addPullToRefresh(animator: ThemeRefreshHeaderAnimator(), handler: {
self.loadCourse(finish: {
self.tableView.es_stopPullToRefresh()
})
})
tableView.separatorStyle = .none
tableView.estimatedRowHeight = 208
tableView.backgroundColor = UIColor(named: .RegularBackground)
tableView.contentInset = UIEdgeInsets(top: 6, left: 0, bottom: 6, right: 0)
tableView.register(CommentViewCell.self, forCellReuseIdentifier: CommentViewCellReuseId)
}
private func setupUserInterface() {
// Style
defaultView.imageName = "comment_noData"
defaultView.text = L10n.noComment
defaultView.descText = L10n.commentLater
}
/// ่ทๅๅญฆ็่ฏพ็จไฟกๆฏ
@objc private func loadCourse(finish: (()->())? = nil) {
/// ่ทๅๅญฆ็่ฏพ็จไฟกๆฏ
MAProvider.getStudentSchedule(onlyPassed: true, failureHandler: { error in
defer { DispatchQueue.main.async { finish?() } }
self.models = []
self.isFetching = false
}) { schedule in
defer { DispatchQueue.main.async { finish?() } }
self.isFetching = false
self.models = schedule
}
}
// MARK: - DataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CommentViewCellReuseId, for: indexPath) as! CommentViewCell
cell.selectionStyle = .none
cell.model = self.models[indexPath.row]
return cell
}
}
| mit | d0aeba5201189ef2409d6bbd48dc34c7 | 28.645833 | 124 | 0.622628 | 4.915371 | false | false | false | false |
firebase/firebase-ios-sdk | Firestore/Swift/Source/Codable/DocumentID.swift | 1 | 6893 | /*
* Copyright 2019 Google
*
* 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 FirebaseFirestore
import FirebaseSharedSwift
@_implementationOnly import FirebaseCoreExtension
extension CodingUserInfoKey {
static let documentRefUserInfoKey =
CodingUserInfoKey(rawValue: "DocumentRefUserInfoKey")!
}
/// A type that can initialize itself from a Firestore `DocumentReference`,
/// which makes it suitable for use with the `@DocumentID` property wrapper.
///
/// Firestore includes extensions that make `String` and `DocumentReference`
/// conform to `DocumentIDWrappable`.
///
/// Note that Firestore ignores fields annotated with `@DocumentID` when writing
/// so there is no requirement to convert from the wrapped type back to a
/// `DocumentReference`.
public protocol DocumentIDWrappable {
/// Creates a new instance by converting from the given `DocumentReference`.
static func wrap(_ documentReference: DocumentReference) throws -> Self
}
extension String: DocumentIDWrappable {
public static func wrap(_ documentReference: DocumentReference) throws -> Self {
return documentReference.documentID
}
}
extension DocumentReference: DocumentIDWrappable {
public static func wrap(_ documentReference: DocumentReference) throws -> Self {
// Swift complains that values of type DocumentReference cannot be returned
// as Self which is nonsensical. The cast forces this to work.
return documentReference as! Self
}
}
/// An internal protocol that allows Firestore.Decoder to test if a type is a
/// DocumentID of some kind without knowing the specific generic parameter that
/// the user actually used.
///
/// This is required because Swift does not define an existential type for all
/// instances of a generic class--that is, it has no wildcard or raw type that
/// matches a generic without any specific parameter. Swift does define an
/// existential type for protocols though, so this protocol (to which DocumentID
/// conforms) indirectly makes it possible to test for and act on any
/// `DocumentID<Value>`.
internal protocol DocumentIDProtocol {
/// Initializes the DocumentID from a DocumentReference.
init(from documentReference: DocumentReference?) throws
}
/// A property wrapper type that marks a `DocumentReference?` or `String?` field to
/// be populated with a document identifier when it is read.
///
/// Apply the `@DocumentID` annotation to a `DocumentReference?` or `String?`
/// property in a `Codable` object to have it populated with the document
/// identifier when it is read and decoded from Firestore.
///
/// - Important: The name of the property annotated with `@DocumentID` must not
/// match the name of any fields in the Firestore document being read or else
/// an error will be thrown. For example, if the `Codable` object has a
/// property named `firstName` annotated with `@DocumentID`, and the Firestore
/// document contains a field named `firstName`, an error will be thrown when
/// attempting to decode the document.
///
/// - Example Read:
/// ````
/// struct Player: Codable {
/// @DocumentID var playerID: String?
/// var health: Int64
/// }
///
/// let p = try! await Firestore.firestore()
/// .collection("players")
/// .document("player-1")
/// .getDocument(as: Player.self)
/// print("\(p.playerID!) Health: \(p.health)")
///
/// // Prints: "Player: player-1, Health: 95"
/// ````
///
/// - Important: Trying to encode/decode this type using encoders/decoders other than
/// Firestore.Encoder throws an error.
///
/// - Important: When writing a Codable object containing an `@DocumentID` annotated field,
/// its value is ignored. This allows you to read a document from one path and
/// write it into another without adjusting the value here.
@propertyWrapper
public struct DocumentID<Value: DocumentIDWrappable & Codable>:
StructureCodingUncodedUnkeyed {
private var value: Value? = nil
public init(wrappedValue value: Value?) {
if let value = value {
logIgnoredValueWarning(value: value)
}
self.value = value
}
public var wrappedValue: Value? {
get { value }
set {
if let someNewValue = newValue {
logIgnoredValueWarning(value: someNewValue)
}
value = newValue
}
}
private func logIgnoredValueWarning(value: Value) {
FirebaseLogger.log(
level: .warning,
service: "[FirebaseFirestoreSwift]",
code: "I-FST000002",
message: """
Attempting to initialize or set a @DocumentID property with a non-nil \
value: "\(value)". The document ID is managed by Firestore and any \
initialized or set value will be ignored. The ID is automatically set \
when reading from Firestore.
"""
)
}
}
extension DocumentID: DocumentIDProtocol {
internal init(from documentReference: DocumentReference?) throws {
if let documentReference = documentReference {
value = try Value.wrap(documentReference)
} else {
value = nil
}
}
}
extension DocumentID: Codable {
/// A `Codable` object containing an `@DocumentID` annotated field should
/// only be decoded with `Firestore.Decoder`; this initializer throws if an
/// unsupported decoder is used.
///
/// - Parameter decoder: A decoder.
/// - Throws: ``FirestoreDecodingError``
public init(from decoder: Decoder) throws {
guard let reference = decoder
.userInfo[CodingUserInfoKey.documentRefUserInfoKey] as? DocumentReference else {
throw FirestoreDecodingError.decodingIsNotSupported(
"""
Could not find DocumentReference for user info key: \(CodingUserInfoKey
.documentRefUserInfoKey).
DocumentID values can only be decoded with Firestore.Decoder
"""
)
}
try self.init(from: reference)
}
/// A `Codable` object containing an `@DocumentID` annotated field can only
/// be encoded with `Firestore.Encoder`; this initializer always throws.
///
/// - Parameter encoder: An invalid encoder.
/// - Throws: ``FirestoreEncodingError``
public func encode(to encoder: Encoder) throws {
throw FirestoreEncodingError.encodingIsNotSupported(
"DocumentID values can only be encoded with Firestore.Encoder"
)
}
}
extension DocumentID: Equatable where Value: Equatable {}
extension DocumentID: Hashable where Value: Hashable {}
| apache-2.0 | 521994292b0f73271633049d203d768f | 35.860963 | 91 | 0.713913 | 4.505229 | false | false | false | false |
tqtifnypmb/armature | Sources/Armature/Protocol/Record.swift | 1 | 4269 | //
// Record.swift
// Armature
//
// The MIT License (MIT)
//
// Copyright (c) 2016 tqtifnypmb
//
// 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
final class Record {
var type: RecordType = .UNKNOWN_TYPE
var requestId: UInt16 = 0
var contentLength: UInt16 = 0
var contentData: [UInt8]?
class func readFrom(conn: Connection) throws -> Record? {
var buffer = [UInt8].init(count: FCGI_HEADER_LEN, repeatedValue: 0)
try conn.readInto(&buffer)
let record = Record()
record.requestId = (UInt16(buffer[2]) << 8) + UInt16(buffer[3])
record.contentLength = (UInt16(buffer[4]) << 8) + UInt16(buffer[5])
let paddingLength = UInt32(buffer[6])
if let type = RecordType(rawValue: buffer[1]) {
record.type = type
} else {
// Ignore unsupport request type
try skip(conn, len: UInt32(record.contentLength) + paddingLength)
return nil
}
if record.contentLength > 0 {
var data = [UInt8].init(count: Int(record.contentLength), repeatedValue: 0)
try conn.readInto(&data)
record.contentData = data
}
if paddingLength > 0 {
try skip(conn, len: paddingLength)
}
return record
}
class func createEOFRecord(reqId: UInt16, type: RecordType) -> Record {
let r = Record()
r.type = type
r.requestId = reqId
r.contentLength = 0
r.contentData = nil
return r
}
private class func skip(conn: Connection, len: UInt32) throws {
var ignore = [UInt8].init(count: Int(len), repeatedValue: 0)
try conn.readInto(&ignore)
}
func writeTo(conn: Connection) throws {
var paddingLength: UInt8 = 0
if self.contentLength != 0 {
paddingLength = UInt8(self.calPadding(self.contentLength, boundary: 8))
}
var heads = [UInt8].init(count: FCGI_HEADER_LEN, repeatedValue: 0)
heads[0] = 1 // Version
heads[1] = self.type.rawValue // Type
heads[2] = UInt8(self.requestId >> 8) // Request ID
heads[3] = UInt8(self.requestId & 0xFF) // Request ID
heads[4] = UInt8(self.contentLength >> 8) // Content Length
heads[5] = UInt8(self.contentLength & 0xFF) // Content Length
heads[6] = paddingLength // Paddign Length
heads[7] = 0 // Reserve
// FIXME: Is byte order important??
try conn.write(&heads)
if self.contentLength != 0 {
try conn.write(&self.contentData!)
}
if paddingLength > 0 {
var padding = [UInt8].init(count: Int(paddingLength), repeatedValue: 0)
try conn.write(&padding)
}
}
private func calPadding(n: UInt16, boundary: UInt16) -> UInt16 {
guard n != 0 else {
return boundary
}
return (~n + 1) & (boundary - 1)
}
}
| mit | f6b5a67f317d86daa7113e51989cde2c | 36.778761 | 87 | 0.58468 | 4.338415 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.