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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dricard/OnTheMap | OnTheMap/LoginViewController.swift | 1 | 13250 | //
// LoginViewController.swift
// OnTheMap
//
// Created by Denis Ricard on 2016-03-10.
// Copyright © 2016 Denis Ricard. All rights reserved.
//
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
/// This is the first View that appears when the app is launched. It
/// lets the user enter his/her credentials and then attempt to
/// authenticate with Udacity's API.
///
/// The user has the option to:
/// - login: with credentials,
/// - signup: to Udacity (this presents a web view), or
/// - login using Facebook (this presents a web view)
class LoginViewController: UIViewController, UITextFieldDelegate, FBSDKLoginButtonDelegate {
/// MARK: properties
var userLastName: String = ""
var userFirstName: String = ""
var userImageUrl: String = ""
// MARK: outlets
@IBOutlet weak var userEmail: UITextField!
@IBOutlet weak var userPassword: UITextField!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var loginFBButton: FBSDKLoginButton!
@IBOutlet weak var blurView: UIVisualEffectView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
// MARK: life cycle
override func viewDidLoad() {
super.viewDidLoad()
// setting the text fields attributes
userEmail.defaultTextAttributes = myTextAttributes
userPassword.defaultTextAttributes = myTextAttributes
// setting the text fields delegates
userEmail.delegate = self
userPassword.delegate = self
// setting the login with Facebook button delegate
loginFBButton.delegate = self
// configure the activity indicator we'll use while geocoding
configureActivityIndicatorView()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
subscribeToKeyboardShowNotifications()
blurView.alpha = 0
activityIndicator.stopAnimating()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeToKeyboardShowNotifications()
}
// MARK: user actions (and related methods)
/// This is called when the user presses the *login* button. If both credentials are valid
/// this calls the `authenticateWithUdacity` method on the *API* class which stores the result
/// in the *Model* class. The completion handler then performs a segue to the TabBarController
/// which displays the map with the pins if the login was successful or an error message if
/// unsuccessful.
@IBAction func loginPressed(sender: AnyObject) {
// first resign first responder if a text field was active
resignIfFirstResponder(userEmail)
resignIfFirstResponder(userPassword)
// GUARD: first check if the user entered an email and a password
guard !userEmail.text!.isEmpty && !userPassword.text!.isEmpty else {
presentAlertMessage("Missing credential", message: "Please enter both an email address and a password")
return
}
// GUARD: check if the user entered a valid email address
guard isEmailValid(userEmail.text!) else {
presentAlertMessage("Invalid email address", message: "Please enter a valid email address")
return
}
// unwrap the parameters (even if they should not be nil at this point, but to be extra sure
// and we need non-optionals for the method call anyways)
if let userEmailString = userEmail.text, userPasswordString = userPassword.text {
// visual feedback for activity
blurView.alpha = 0.5
activityIndicator.startAnimating()
// call the authenticate method
API.sharedInstance().authenticateWithUdacity(userEmailString, userPassword: userPasswordString) { (success, error) in
performUIUpdatesOnMain {
if success {
self.completeLogin()
} else {
// reset interface
self.blurView.alpha = 0
self.activityIndicator.stopAnimating()
print("Error returned by authenticateWithUdacity: \(error)")
if let error = error {
if error.code == Constants.UDACITY.networkError {
self.presentAlertMessage("Network error", message: "There was a problem with the network connection, please make sure that you have a connection to the internet.")
} else {
self.presentAlertMessage("Authentication error", message: "Your credentials were refused, please check your email and password and try again or signup.")
}
}
}
}
}
} else {
// this should never happen since we checked for empty credentials but extra safety never hurts
print("failed to unwrap optionals (userEmail or userPassword)")
presentAlertMessage("Missing credential", message: "Please enter both an email address and a password")
}
}
/// This completes the login process once the asynchronous authenticate methods terminates successfuly.
/// It performs a segue to the TabBarController. Students location data was stored in the *Model* class
/// if successful as well as an array of map annotations.
func completeLogin() {
// reset interface
blurView.alpha = 0
activityIndicator.stopAnimating()
performUIUpdatesOnMain {
let controller = self.storyboard!.instantiateViewControllerWithIdentifier("LocationTabBarController") as! UITabBarController
self.presentViewController(controller, animated: true, completion: nil)
}
}
@IBAction func signUpPressed(sender: AnyObject) {
let signupURL = NSURL(string: "https://www.udacity.com/account/auth#!/signup")
if let signupURL = signupURL {
UIApplication.sharedApplication().openURL(signupURL)
} else {
print("unable to unwrap NSURL for Udacity signup url")
}
}
// MARK: appearance and enabling/disabling of UI elements
/// Sets the text attributes for the text fields.
let myTextAttributes : [ String : AnyObject ] = [
NSForegroundColorAttributeName: UIColor.whiteColor()
]
/// Configures the activity indicator that is used when the geocode request is sent
func configureActivityIndicatorView() {
activityIndicator.activityIndicatorViewStyle = .WhiteLarge
activityIndicator.hidesWhenStopped = true
activityIndicator.color = UIColor.blueColor()
}
/// Sets a blur on/off over the View to indicate that we're geocoding the location
func setBlur(turnBlurOn: Bool) {
if turnBlurOn {
// here we set the blur over the view
UIView.animateWithDuration(0.5, animations: {
self.blurView.alpha = 0.5
})
} else {
// here we remove the blur
UIView.animateWithDuration(0.5, animations: {
self.blurView.alpha = 0
})
}
}
// MARK: textfield delegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// MARK: Facebook delegate
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
// visual feedback for activity
blurView.alpha = 0.5
activityIndicator.startAnimating()
guard error == nil else {
print("FB returned an error: \(error.localizedDescription)")
return
}
if let userToken = result.token {
// Do something with the data
Model.sharedInstance().loggedInWithFacebook = true
API.sharedInstance().authenticateWithUdacityFB(userToken.tokenString) { (success, error) in
performUIUpdatesOnMain {
if success {
self.completeLogin()
} else {
// reset interface
self.blurView.alpha = 0
self.activityIndicator.stopAnimating()
print("Error returned by authenticateWithUdacityFB: \(error)")
if let error = error {
if error.code == Constants.UDACITY.networkError {
self.presentAlertMessage("Network error", message: "There was a problem with the network connection, please make sure that you have a connection to the internet.")
} else {
self.presentAlertMessage("Authentication error", message: "Your credentials were refused, please check your email and password and try again or signup.")
}
}
}
}
}
}
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
// reset boolean
Model.sharedInstance().loggedInWithFacebook = false
}
func loginButtonWillLogin(loginButton: FBSDKLoginButton!) -> Bool {
// visual feedback for activity
blurView.alpha = 0.5
activityIndicator.startAnimating()
return true
}
// MARK: utilities functions
/// Tests if the provided textField is the first responder and, if so,
/// resign it as first responder. You should call this with both textFields
/// to make sure you resigned before processing the login.
func resignIfFirstResponder(textField: UITextField) {
if textField.isFirstResponder() {
textField.resignFirstResponder()
}
}
/// Display a one button alert message to communicate errors to the user. Display a title, a messge, and
/// an 'OK' button.
func presentAlertMessage(title: String, message: String) {
let controller = UIAlertController()
controller.title = title
controller.message = message
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { action in self.dismissViewControllerAnimated(true, completion: nil ) })
controller.addAction(okAction)
self.presentViewController(controller, animated: true, completion: nil)
}
/// Provides basic validation of email string to make sure it conforms to
/// _@_._ pattern. **This was adapted from something found on stack overflow**
func isEmailValid(email: String) -> Bool {
let filterString = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let emailTest = NSPredicate(format: "SELF MATCHES %@", filterString)
return emailTest.evaluateWithObject(email)
}
// MARK: keyboard functions
func keyboardWillShow(notification: NSNotification) {
//get screen height
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenHeight = screenSize.height
// get Keyboard height
let keyboardHeight = getKeyboardHeight(notification)
// check to see if bottom of password text field will be hidden by the keyboard and move view if so
if (screenHeight-keyboardHeight) < userPassword.frame.maxY {
view.frame.origin.y = -(userPassword.frame.maxY - (screenHeight-keyboardHeight) + 5)
}
subscribeToKeyboardHideNotification()
}
func keyboardWillHide(notification: NSNotification) {
view.frame.origin.y = 0
unsubscribeToKeyboardHideNotification()
}
func getKeyboardHeight(notification: NSNotification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.CGRectValue().height
}
func subscribeToKeyboardShowNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
}
func unsubscribeToKeyboardShowNotifications() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
}
func subscribeToKeyboardHideNotification() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
func unsubscribeToKeyboardHideNotification() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
}
| mit | 5cf227be263f21ff02553f5108a9aada | 40.145963 | 199 | 0.627595 | 5.798249 | false | false | false | false |
adozenlines/xmpp-messenger-ios | Example/Pods/xmpp-messenger-ios/Pod/Classes/OneRoster.swift | 4 | 4206 | //
// OneRoster.swift
// OneChat
//
// Created by Paul on 26/02/2015.
// Copyright (c) 2015 ProcessOne. All rights reserved.
//
import Foundation
import XMPPFramework
public protocol OneRosterDelegate {
func oneRosterContentChanged(controller: NSFetchedResultsController)
}
public class OneRoster: NSObject, NSFetchedResultsControllerDelegate {
public var delegate: OneRosterDelegate?
public var fetchedResultsControllerVar: NSFetchedResultsController?
// MARK: Singleton
public class var sharedInstance : OneRoster {
struct OneRosterSingleton {
static let instance = OneRoster()
}
return OneRosterSingleton.instance
}
public class var buddyList: NSFetchedResultsController {
get {
if sharedInstance.fetchedResultsControllerVar != nil {
return sharedInstance.fetchedResultsControllerVar!
}
return sharedInstance.fetchedResultsController()!
}
}
// MARK: Core Data
func managedObjectContext_roster() -> NSManagedObjectContext {
return OneChat.sharedInstance.xmppRosterStorage.mainThreadManagedObjectContext
}
private func managedObjectContext_capabilities() -> NSManagedObjectContext {
return OneChat.sharedInstance.xmppRosterStorage.mainThreadManagedObjectContext
}
public func fetchedResultsController() -> NSFetchedResultsController? {
if fetchedResultsControllerVar == nil {
let moc = OneRoster.sharedInstance.managedObjectContext_roster() as NSManagedObjectContext?
let entity = NSEntityDescription.entityForName("XMPPUserCoreDataStorageObject", inManagedObjectContext: moc!)
let sd1 = NSSortDescriptor(key: "sectionNum", ascending: true)
let sd2 = NSSortDescriptor(key: "displayName", ascending: true)
let sortDescriptors = [sd1, sd2]
let fetchRequest = NSFetchRequest()
fetchRequest.entity = entity
fetchRequest.sortDescriptors = sortDescriptors
fetchRequest.fetchBatchSize = 10
fetchedResultsControllerVar = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc!, sectionNameKeyPath: "sectionNum", cacheName: nil)
fetchedResultsControllerVar?.delegate = self
do {
try fetchedResultsControllerVar!.performFetch()
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
abort()
}
// if fetchedResultsControllerVar?.performFetch() == nil {
//Handle fetch error
//}
}
return fetchedResultsControllerVar!
}
public class func userFromRosterAtIndexPath(indexPath indexPath: NSIndexPath) -> XMPPUserCoreDataStorageObject {
return sharedInstance.fetchedResultsController()!.objectAtIndexPath(indexPath) as! XMPPUserCoreDataStorageObject
}
public class func userFromRosterForJID(jid jid: String) -> XMPPUserCoreDataStorageObject? {
let userJID = XMPPJID.jidWithString(jid)
if let user = OneChat.sharedInstance.xmppRosterStorage.userForJID(userJID, xmppStream: OneChat.sharedInstance.xmppStream, managedObjectContext: sharedInstance.managedObjectContext_roster()) {
return user
} else {
return nil
}
}
public class func removeUserFromRosterAtIndexPath(indexPath indexPath: NSIndexPath) {
let user = userFromRosterAtIndexPath(indexPath: indexPath)
sharedInstance.fetchedResultsControllerVar?.managedObjectContext.deleteObject(user)
}
public func controllerDidChangeContent(controller: NSFetchedResultsController) {
delegate?.oneRosterContentChanged(controller)
}
}
extension OneRoster: XMPPRosterDelegate {
public func xmppRoster(sender: XMPPRoster, didReceiveBuddyRequest presence:XMPPPresence) {
//was let user
_ = OneChat.sharedInstance.xmppRosterStorage.userForJID(presence.from(), xmppStream: OneChat.sharedInstance.xmppStream, managedObjectContext: managedObjectContext_roster())
}
public func xmppRosterDidEndPopulating(sender: XMPPRoster?) {
let jidList = OneChat.sharedInstance.xmppRosterStorage.jidsForXMPPStream(OneChat.sharedInstance.xmppStream)
print("List=\(jidList)")
}
}
extension OneRoster: XMPPStreamDelegate {
public func xmppStream(sender: XMPPStream, didReceiveIQ ip: XMPPIQ) -> Bool {
if let msg = ip.attributeForName("from") {
if msg.stringValue() == "conference.process-one.net" {
}
}
return false
}
} | mit | 0dca8ef3d82187ac64394d68047e1799 | 32.125984 | 193 | 0.779838 | 4.673333 | false | false | false | false |
trill-lang/LLVMSwift | Sources/LLVM/IRValue.swift | 1 | 7771 | #if SWIFT_PACKAGE
import cllvm
#endif
/// An `IRValue` is a type that is capable of lowering itself to an
/// `LLVMValueRef` object for use with LLVM's C API.
public protocol IRValue {
/// Retrieves the underlying LLVM value object.
func asLLVM() -> LLVMValueRef
}
public extension IRValue {
/// Retrieves the type of this value.
var type: IRType {
return convertType(LLVMTypeOf(asLLVM()))
}
/// Returns whether this value is a constant.
var isConstant: Bool {
return LLVMIsConstant(asLLVM()) != 0
}
/// Returns whether this value is an instruction.
var isInstruction: Bool {
return LLVMIsAInstruction(asLLVM()) != nil
}
/// Returns whether this value has been initialized with the special `undef`
/// value.
///
/// The `undef` value can be used anywhere a constant is expected, and
/// indicates that the user of the value may receive an unspecified
/// bit-pattern.
var isUndef: Bool {
return LLVMIsUndef(asLLVM()) != 0
}
/// Gets and sets the name for this value.
var name: String {
get {
let ptr = LLVMGetValueName(asLLVM())!
return String(cString: ptr)
}
set {
LLVMSetValueName(asLLVM(), newValue)
}
}
/// Replaces all uses of this value with the specified value.
///
/// - parameter value: The new value to swap in.
func replaceAllUses(with value: IRValue) {
LLVMReplaceAllUsesWith(asLLVM(), value.asLLVM())
}
/// Dumps a representation of this value to stderr.
func dump() {
LLVMDumpValue(asLLVM())
}
/// The kind of this value.
var kind: IRValueKind {
return IRValueKind(llvm: LLVMGetValueKind(asLLVM()))
}
}
/// Enumerates the kinds of values present in LLVM IR.
public enum IRValueKind {
/// The value is an argument.
case argument
/// The value is a basic block.
case basicBlock
/// The value is a memory use.
case memoryUse
/// The value is a memory definition.
case memoryDef
/// The value is a memory phi node.
case memoryPhi
/// The value is a function.
case function
/// The value is a global alias.
case globalAlias
/// The value is an ifunc.
case globalIFunc
/// The value is a variable.
case globalVariable
/// The value is a block address.
case blockAddress
/// The value is a constant expression.
case constantExpression
/// The value is a constant array.
case constantArray
/// The value is a constant struct.
case constantStruct
/// The value is a constant vector.
case constantVector
/// The value is undef.
case undef
/// The value is a constant aggregate zero.
case constantAggregateZero
/// The value is a constant data array.
case constantDataArray
/// The value is a constant data vector.
case constantDataVector
/// The value is a constant int value.
case constantInt
/// The value is a constant floating pointer value.
case constantFloat
/// The value is a constant pointer to null.
///
/// Note that this pointer is a zero bit-value pointer. Its semantics are dependent upon the address space.
case constantPointerNull
/// The value is a constant none-token value.
case constantTokenNone
/// The value is a metadata-as-value node.
case metadataAsValue
/// The value is inline assembly.
case inlineASM
/// The value is an instruction.
case instruction
init(llvm: LLVMValueKind) {
switch llvm {
case LLVMArgumentValueKind: self = .argument
case LLVMBasicBlockValueKind: self = .basicBlock
case LLVMMemoryUseValueKind: self = .memoryUse
case LLVMMemoryDefValueKind: self = .memoryDef
case LLVMMemoryPhiValueKind: self = .memoryPhi
case LLVMFunctionValueKind: self = .function
case LLVMGlobalAliasValueKind: self = .globalAlias
case LLVMGlobalIFuncValueKind: self = .globalIFunc
case LLVMGlobalVariableValueKind: self = .globalVariable
case LLVMBlockAddressValueKind: self = .blockAddress
case LLVMConstantExprValueKind: self = .constantExpression
case LLVMConstantArrayValueKind: self = .constantArray
case LLVMConstantStructValueKind: self = .constantStruct
case LLVMConstantVectorValueKind: self = .constantVector
case LLVMUndefValueValueKind: self = .undef
case LLVMConstantAggregateZeroValueKind: self = .constantAggregateZero
case LLVMConstantDataArrayValueKind: self = .constantDataArray
case LLVMConstantDataVectorValueKind: self = .constantDataVector
case LLVMConstantIntValueKind: self = .constantInt
case LLVMConstantFPValueKind: self = .constantFloat
case LLVMConstantPointerNullValueKind: self = .constantPointerNull
case LLVMConstantTokenNoneValueKind: self = .constantTokenNone
case LLVMMetadataAsValueValueKind: self = .metadataAsValue
case LLVMInlineAsmValueKind: self = .inlineASM
case LLVMInstructionValueKind: self = .instruction
default: fatalError("unknown IRValue kind \(llvm)")
}
}
}
extension LLVMValueRef: IRValue {
/// Retrieves the underlying LLVM value object.
public func asLLVM() -> LLVMValueRef {
return self
}
}
// N.B. This conformance is strictly not correct, but LLVM-C chooses to muddy
// the difference between LLVMValueRef and a number of what should be refined
// types. What matters is that we verify any returned `IRInstruction` values
// are actually instructions.
extension LLVMValueRef: IRInstruction {}
extension Int: IRValue {
/// Retrieves the underlying LLVM value object.
public func asLLVM() -> LLVMValueRef {
return IntType(width: MemoryLayout<Int>.size * 8).constant(self).asLLVM()
}
}
extension Int8: IRValue {
/// Retrieves the underlying LLVM value object.
public func asLLVM() -> LLVMValueRef {
return IntType(width: MemoryLayout<Int8>.size * 8).constant(self).asLLVM()
}
}
extension Int16: IRValue {
/// Retrieves the underlying LLVM value object.
public func asLLVM() -> LLVMValueRef {
return IntType(width: MemoryLayout<Int16>.size * 8).constant(self).asLLVM()
}
}
extension Int32: IRValue {
/// Retrieves the underlying LLVM value object.
public func asLLVM() -> LLVMValueRef {
return IntType(width: MemoryLayout<Int32>.size * 8).constant(self).asLLVM()
}
}
extension Int64: IRValue {
/// Retrieves the underlying LLVM value object.
public func asLLVM() -> LLVMValueRef {
return IntType(width: MemoryLayout<Int64>.size * 8).constant(self).asLLVM()
}
}
extension UInt: IRValue {
/// Retrieves the underlying LLVM value object.
public func asLLVM() -> LLVMValueRef {
return IntType(width: MemoryLayout<UInt>.size * 8).constant(self).asLLVM()
}
}
extension UInt8: IRValue {
/// Retrieves the underlying LLVM value object.
public func asLLVM() -> LLVMValueRef {
return IntType(width: MemoryLayout<UInt8>.size * 8).constant(self).asLLVM()
}
}
extension UInt16: IRValue {
/// Retrieves the underlying LLVM value object.
public func asLLVM() -> LLVMValueRef {
return IntType(width: MemoryLayout<UInt16>.size * 8).constant(self).asLLVM()
}
}
extension UInt32: IRValue {
/// Retrieves the underlying LLVM value object.
public func asLLVM() -> LLVMValueRef {
return IntType(width: MemoryLayout<UInt32>.size * 8).constant(self).asLLVM()
}
}
extension UInt64: IRValue {
/// Retrieves the underlying LLVM value object.
public func asLLVM() -> LLVMValueRef {
return IntType(width: MemoryLayout<UInt64>.size * 8).constant(self).asLLVM()
}
}
extension Bool: IRValue {
/// Retrieves the underlying LLVM value object.
public func asLLVM() -> LLVMValueRef {
return IntType(width: 1).constant(self ? 1 : 0).asLLVM()
}
}
extension String: IRValue {
/// Retrieves the underlying LLVM value object.
public func asLLVM() -> LLVMValueRef {
return LLVMConstString(self, UInt32(self.utf8.count), 0)
}
}
| mit | a3e92c5ef29b7350005e0ef075726336 | 30.208835 | 110 | 0.71458 | 4.074987 | false | false | false | false |
l4u/ZLSwipeableViewSwift | ZLSwipeableViewSwiftDemo/ZLSwipeableViewSwiftDemo/ZLSwipeableViewController.swift | 12 | 6785 | //
// ViewController.swift
// ZLSwipeableViewSwiftDemo
//
// Created by Zhixuan Lai on 4/27/15.
// Copyright (c) 2015 Zhixuan Lai. All rights reserved.
//
import UIKit
import performSelector_swift
import UIColor_FlatColors
import Cartography
import ReactiveUI
class ZLSwipeableViewController: UIViewController {
var swipeableView: ZLSwipeableView!
var colors = ["Turquoise", "Green Sea", "Emerald", "Nephritis", "Peter River", "Belize Hole", "Amethyst", "Wisteria", "Wet Asphalt", "Midnight Blue", "Sun Flower", "Orange", "Carrot", "Pumpkin", "Alizarin", "Pomegranate", "Clouds", "Silver", "Concrete", "Asbestos"]
var colorIndex = 0
var loadCardsFromXib = false
var reloadBarButtonItem = UIBarButtonItem(title: "Reload", style: .Plain) { item in }
var leftBarButtonItem = UIBarButtonItem(title: "←", style: .Plain) { item in }
var upBarButtonItem = UIBarButtonItem(title: "↑", style: .Plain) { item in }
var rightBarButtonItem = UIBarButtonItem(title: "→", style: .Plain) { item in }
var downBarButtonItem = UIBarButtonItem(title: "↓", style: .Plain) { item in }
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
swipeableView.loadViews()
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.setToolbarHidden(false, animated: false)
view.backgroundColor = UIColor.whiteColor()
view.clipsToBounds = true
reloadBarButtonItem.addAction() { item in
let alertController = UIAlertController(title: nil, message: "Load Cards:", preferredStyle: .ActionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ...
}
alertController.addAction(cancelAction)
let ProgrammaticallyAction = UIAlertAction(title: "Programmatically", style: .Default) { (action) in
self.loadCardsFromXib = false
self.colorIndex = 0
self.swipeableView.discardViews()
self.swipeableView.loadViews()
}
alertController.addAction(ProgrammaticallyAction)
let XibAction = UIAlertAction(title: "From Xib", style: .Default) { (action) in
self.loadCardsFromXib = true
self.colorIndex = 0
self.swipeableView.discardViews()
self.swipeableView.loadViews()
}
alertController.addAction(XibAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
leftBarButtonItem.addAction() { item in
self.swipeableView.swipeTopView(inDirection: .Left)
}
upBarButtonItem.addAction() { item in
self.swipeableView.swipeTopView(inDirection: .Up)
}
rightBarButtonItem.addAction() { item in
self.swipeableView.swipeTopView(inDirection: .Right)
}
downBarButtonItem.addAction() { item in
self.swipeableView.swipeTopView(inDirection: .Down)
}
var fixedSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, action: {item in})
var flexibleSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, action: {item in})
var items = [fixedSpace, reloadBarButtonItem, flexibleSpace, leftBarButtonItem, flexibleSpace, upBarButtonItem, flexibleSpace, rightBarButtonItem, flexibleSpace, downBarButtonItem, fixedSpace]
toolbarItems = items
swipeableView = ZLSwipeableView()
view.addSubview(swipeableView)
swipeableView.didStart = {view, location in
println("Did start swiping view at location: \(location)")
}
swipeableView.swiping = {view, location, translation in
println("Swiping at view location: \(location) translation: \(translation)")
}
swipeableView.didEnd = {view, location in
println("Did end swiping view at location: \(location)")
}
swipeableView.didSwipe = {view, direction, vector in
println("Did swipe view in direction: \(direction), vector: \(vector)")
}
swipeableView.didCancel = {view in
println("Did cancel swiping view")
}
swipeableView.nextView = {
if self.colorIndex < self.colors.count {
var cardView = CardView(frame: self.swipeableView.bounds)
cardView.backgroundColor = self.colorForName(self.colors[self.colorIndex])
self.colorIndex++
if self.loadCardsFromXib {
var contentView = NSBundle.mainBundle().loadNibNamed("CardContentView", owner: self, options: nil).first! as! UIView
contentView.setTranslatesAutoresizingMaskIntoConstraints(false)
contentView.backgroundColor = cardView.backgroundColor
cardView.addSubview(contentView)
// This is important:
// https://github.com/zhxnlai/ZLSwipeableView/issues/9
/*// Alternative:
let metrics = ["width":cardView.bounds.width, "height": cardView.bounds.height]
let views = ["contentView": contentView, "cardView": cardView]
cardView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[contentView(width)]", options: .AlignAllLeft, metrics: metrics, views: views))
cardView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[contentView(height)]", options: .AlignAllLeft, metrics: metrics, views: views))
*/
layout(contentView, cardView) { view1, view2 in
view1.left == view2.left
view1.top == view2.top
view1.width == cardView.bounds.width
view1.height == cardView.bounds.height
}
}
return cardView
}
return nil
}
layout(swipeableView, view) { view1, view2 in
view1.left == view2.left+50
view1.right == view2.right-50
view1.top == view2.top + 120
view1.bottom == view2.bottom - 100
}
}
// MARK: ()
func colorForName(name: String) -> UIColor {
let sanitizedName = name.stringByReplacingOccurrencesOfString(" ", withString: "")
let selector = "flat\(sanitizedName)Color"
return UIColor.swift_performSelector(Selector(selector), withObject: nil) as! UIColor
}
}
| mit | 2150738a522aeb8fca28f3867c593be8 | 43.880795 | 269 | 0.607939 | 5.245356 | false | false | false | false |
Palleas/Rewatch | Rewatch/AppDelegate.swift | 1 | 2893 | //
// AppDelegate.swift
// Rewatch
//
// Created by Romain Pouclet on 2015-10-15.
// Copyright © 2015 Perfectly-Cooked. All rights reserved.
//
import UIKit
import KeychainSwift
import CoreData
import Mixpanel
import BetaSeriesKit
import ReactiveCocoa
import Result
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var client: Client!
var persistence: PersistenceController!
var analyticsController: AnalyticsController!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
BuddyBuildSDK.setup()
application.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
// Setup stylesheet
let stylesheet = Stylesheet()
stylesheet.apply()
// Retrieve API Keys
let keys = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("Keys", ofType: "plist")!) as! [String: String]
analyticsController = MixpanelAnalyticsController(mixpanel: Mixpanel.sharedInstanceWithToken(keys["MixpanelAPIKey"]!))
// Setup Window
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window = window
persistence = try! PersistenceController(initCallback: { () -> Void in
if let rootViewController = window.rootViewController as? RootViewController {
rootViewController.boot()
}
})
window.rootViewController = RootViewController(persistenceController: self.persistence, analyticsController: analyticsController)
window.makeKeyAndVisible()
return true
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
guard let host = url.host else { return false }
if host == "oauth" {
BetaSeriesKit.Client.completeSignIn(url)
} else if host == "episode" {
if let episode = url.pathComponents?.filter({ $0 != "/" }).first, let episodeId = Int(episode) {
guard let presentedEpisode = episodeWithId(episodeId, inContext: persistence.managedObjectContext) else {
return true
}
let episodeViewController = (window?.rootViewController as? RootViewController)?.episodeViewController
episodeViewController?.presentEpisode(presentedEpisode)
}
}
return true
}
func applicationWillResignActive(application: UIApplication) {
persistence.save()
}
func applicationDidEnterBackground(application: UIApplication) {
persistence.save()
}
func applicationWillTerminate(application: UIApplication) {
persistence.save()
}
}
| mit | 8f5d93c9dbf879c383e69694eba9a7f6 | 33.428571 | 137 | 0.670124 | 5.795591 | false | false | false | false |
SwiftOnEdge/Edge | Tests/HTTPTests/PerformanceTests.swift | 1 | 5680 | //
// ServerTests.swift
// Edge
//
// Created by Tyler Fleming Cloutier on 10/30/16.
//
//
import Foundation
import XCTest
import PromiseKit
@testable import HTTP
func generateRandomBytes(_ num: Int) -> Data? {
var data = Data(count: num)
let result = data.withUnsafeMutableBytes {
SecRandomCopyBytes(kSecRandomDefault, data.count, $0)
}
if result == errSecSuccess {
return data
} else {
print("Problem generating random bytes")
return nil
}
}
let dataSize = 10_000_000
let oneMBData = generateRandomBytes(dataSize)!
let rootUrl = "http://localhost:3000"
class PerformanceTests: XCTestCase {
struct TestError: Error {
}
private func postData(path: String) -> Promise<()> {
let session = URLSession(configuration: .default)
let urlString = rootUrl + path
let url = URL(string: urlString)!
var req = URLRequest(url: url)
req.httpMethod = "POST"
req.httpBody = oneMBData
return Promise { resolve, reject in
session.dataTask(with: req) { (data, urlResp, err) in
if let err = err {
reject(err)
}
resolve(())
}.resume()
}
}
private func getData(path: String) -> Promise<Data> {
let session = URLSession(configuration: .default)
let urlString = rootUrl + path
let url = URL(string: urlString)!
var req = URLRequest(url: url)
req.httpMethod = "GET"
return Promise { resolve, reject in
session.dataTask(with: req) { (data, urlResp, err) in
if let err = err {
XCTFail("Error on response: \(err)")
reject(err)
}
guard let data = data else {
XCTFail("No data returned")
reject(TestError())
return
}
resolve(data)
}.resume()
}
}
private func emptyGet(path: String) -> Promise<()> {
let session = URLSession(configuration: .default)
let urlString = rootUrl + path
let url = URL(string: urlString)!
var req = URLRequest(url: url)
req.httpMethod = "GET"
return Promise { resolve, reject in
session.dataTask(with: req) { (data, urlResp, err) in
if let err = err {
XCTFail("Error on response: \(err)")
reject(err)
}
resolve(())
}.resume()
}
}
func testPerformanceReceivingData() {
self.measureMetrics(XCTestCase.defaultPerformanceMetrics, automaticallyStartMeasuring: false) {
let app = Router()
app.post("/post") { request -> Response in
let count = request.body.count
XCTAssertEqual(count, dataSize)
return Response()
}
let server = HTTP.Server(delegate: app, reusePort: true)
server.listen(host: "0.0.0.0", port: 3000)
let expectSuccess = expectation(description: "Request was not successful.")
self.startMeasuring()
postData(path: "/post").then {
expectSuccess.fulfill()
}.catch { error in
XCTFail(error.localizedDescription)
}
waitForExpectations(timeout: 5) { error in
self.stopMeasuring()
server.stop()
}
}
}
func testPerformanceSendingData() {
self.measureMetrics(XCTestCase.defaultPerformanceMetrics, automaticallyStartMeasuring: false) {
let app = Router()
app.get("/get") { request -> Response in
return Response(body: oneMBData)
}
let server = HTTP.Server(delegate: app, reusePort: true)
server.listen(host: "0.0.0.0", port: 3000)
let expectSuccess = expectation(description: "Request was not successful.")
self.startMeasuring()
getData(path: "/get").then { data in
expectSuccess.fulfill()
XCTAssertEqual(dataSize, data.count)
}.catch { error in
XCTFail(error.localizedDescription)
}
waitForExpectations(timeout: 5) { error in
self.stopMeasuring()
server.stop()
}
}
}
func testPerformanceConcurrentRequests() {
self.measureMetrics(XCTestCase.defaultPerformanceMetrics, automaticallyStartMeasuring: false) {
let app = Router()
app.get("/get") { request -> Response in
return Response()
}
let server = HTTP.Server(delegate: app, reusePort: true)
server.listen(host: "0.0.0.0", port: 3000)
self.startMeasuring()
for _ in 0..<150 {
let expectSuccess = self.expectation(description: "Request was not successful.")
DispatchQueue.global().async {
self.emptyGet(path: "/get").then {
expectSuccess.fulfill()
}.catch { error in
XCTFail(error.localizedDescription)
}
}
}
waitForExpectations(timeout: 5) { error in
self.stopMeasuring()
server.stop()
}
}
}
}
extension PerformanceTests {
static var allTests = [
("testPerformanceSendingData", testPerformanceSendingData),
]
}
| mit | 003b6b16f2193e8983cc801a880b9a42 | 27.686869 | 103 | 0.530634 | 5.103324 | false | true | false | false |
Drakken-Engine/GameEngine | DrakkenEngine_Editor/NewScriptViewController.swift | 1 | 2556 | //
// NewScriptViewController.swift
// DrakkenEngine
//
// Created by Allison Lindner on 26/11/16.
// Copyright © 2016 Drakken Studio. All rights reserved.
//
import Cocoa
class NewScriptViewController: NSViewController {
let appDelegate = NSApplication.shared().delegate as! AppDelegate
@IBOutlet weak var scriptNameTF: NSTextField!
@IBOutlet weak var startCB: NSButton!
@IBOutlet weak var updateCB: NSButton!
@IBOutlet weak var rightClickCB: NSButton!
@IBOutlet weak var leftClickCB: NSButton!
@IBOutlet weak var touchCB: NSButton!
@IBOutlet weak var keyDownCB: NSButton!
@IBOutlet weak var keyUpCB: NSButton!
@IBOutlet weak var receiveMessageCB: NSButton!
@IBAction func newScript(_ sender: Any) {
if !scriptNameTF.stringValue.isEmpty {
var content = ""
if startCB.state == NSOnState {
content += "function Start() {\n //Call once on start game\n}\n"
}
if updateCB.state == NSOnState {
content += "\nfunction Update() {\n //Call every frame\n}\n"
}
if rightClickCB.state == NSOnState {
content += "\nfunction RightClick(x, y) {\n \n}\n"
}
if leftClickCB.state == NSOnState {
content += "\nfunction LeftClick(x, y) {\n \n}\n"
}
if touchCB.state == NSOnState {
content += "\nfunction Touch(x, y) {\n \n}\n"
}
if keyDownCB.state == NSOnState {
content += "\nfunction KeyDown(keycode, modifier) {\n \n}\n"
}
if keyUpCB.state == NSOnState {
content += "\nfunction KeyUp(keycode, modifier) {\n \n}\n"
}
if receiveMessageCB.state == NSOnState {
content += "\nfunction ReceiveMessage(message) {\n \n}\n"
}
let fileManager = FileManager()
if fileManager.createFile(atPath: dCore.instance.SCRIPTS_PATH!.appendingPathComponent("\(scriptNameTF.stringValue).js").path,
contents: content.data(using: .utf8),
attributes: nil) {
NSLog("New script created")
}
self.dismiss(self)
}
}
@IBAction func cancel(_ sender: Any) {
self.dismiss(self)
}
}
| gpl-3.0 | 0a19c6b2351e7f8067e74c6a845922c6 | 33.066667 | 137 | 0.522896 | 4.670932 | false | false | false | false |
RMizin/PigeonMessenger-project | FalconMessenger/Settings/Menu/Appearance/AppearanceTableViewController.swift | 1 | 5297 | //
// AppearanceTableViewController.swift
// FalconMessenger
//
// Created by Roman Mizin on 3/1/19.
// Copyright © 2019 Roman Mizin. All rights reserved.
//
import UIKit
enum DefaultMessageTextFontSize: Float {
case extraSmall = 14
case small = 15
case medium = 16
case regular = 17
case large = 19
case extraLarge = 23
case extraLargeX2 = 26
static func allFontSizes() -> [Float] {
return [DefaultMessageTextFontSize.extraSmall.rawValue,
DefaultMessageTextFontSize.small.rawValue,
DefaultMessageTextFontSize.medium.rawValue,
DefaultMessageTextFontSize.regular.rawValue,
DefaultMessageTextFontSize.large.rawValue,
DefaultMessageTextFontSize.extraLarge.rawValue,
DefaultMessageTextFontSize.extraLargeX2.rawValue]
}
}
class AppearanceTableViewController: MenuControlsTableViewController {
fileprivate let sectionTitles = ["Text size", "Preview", "Theme"]
fileprivate let themesTitles = ["Default", "Dark", "Living Coral"]
fileprivate let themes = [Theme.Default, Theme.Dark, Theme.LivingCoral]
fileprivate let userDefaultsManager = UserDefaultsManager()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Appearance"
NotificationCenter.default.addObserver(self, selector: #selector(changeTheme), name: .themeUpdated, object: nil)
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 10.0
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateAppearanceExampleTheme()
}
@objc fileprivate func changeTheme() {
view.backgroundColor = ThemeManager.currentTheme().generalBackgroundColor
tableView.backgroundColor = view.backgroundColor
navigationItem.hidesBackButton = true
navigationItem.hidesBackButton = false
updateAppearanceExampleTheme()
}
fileprivate func updateAppearanceExampleTheme() {
guard let cell = tableView.cellForRow(at: IndexPath(row: 0, section: 1)) as? AppearanceExampleTableViewCell else { return }
cell.appearanceExampleCollectionView.updateTheme()
DispatchQueue.main.async { [weak self] in self?.tableView.reloadData() }
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 0 ? 1 : section == 1 ? 1 : themes.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
return 32
} else if indexPath.section == 1 {
return UITableView.automaticDimension
} else {
return ControlButton.cellHeight
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitles[section]
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: appearanceTextSizeTableViewCellID,
for: indexPath) as? AppearanceTextSizeTableViewCell ?? AppearanceTextSizeTableViewCell()
cell.sliderView.delegate = self
return cell
} else if indexPath.section == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: appearanceExampleTableViewCellID,
for: indexPath) as? AppearanceExampleTableViewCell ?? AppearanceExampleTableViewCell()
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: controlButtonCellID,
for: indexPath) as? GroupAdminPanelTableViewCell ?? GroupAdminPanelTableViewCell()
cell.selectionStyle = .none
cell.backgroundColor = ThemeManager.currentTheme().generalBackgroundColor
cell.button.addTarget(self, action: #selector(controlButtonClicked(_:)), for: .touchUpInside)
cell.button.setTitle(themesTitles[indexPath.row], for: .normal)
cell.button.setTitleColor(ThemeManager.currentTheme().controlButtonTintColor, for: .normal)
cell.button.backgroundColor = ThemeManager.currentTheme().controlButtonColor
if themes[indexPath.row] == ThemeManager.currentTheme() {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
return cell
}
@objc fileprivate func controlButtonClicked(_ sender: UIButton) {
guard let superview = sender.superview else { return }
let point = tableView.convert(sender.center, from: superview)
guard let indexPath = tableView.indexPathForRow(at: point) else { return }
ThemeManager.applyTheme(theme: themes[indexPath.row])
if let navigationBar = navigationController?.navigationBar {
ThemeManager.setNavigationBarAppearance(navigationBar)
}
}
}
extension AppearanceTableViewController: UIIncrementSliderUpdateDelegate {
func incrementSliderDidUpdate(to value: CGFloat) {
autoreleasepool {
try! RealmKeychain.defaultRealm.safeWrite {
for object in RealmKeychain.defaultRealm.objects(Conversation.self) {
object.shouldUpdateRealmRemotelyBeforeDisplaying.value = true
}
}
}
userDefaultsManager.updateObject(for: userDefaultsManager.chatLogDefaultFontSizeID, with: Float(value))
updateAppearanceExampleTheme()
}
}
| gpl-3.0 | 0be1935bf95dbe34ee2e4dbb970a922a | 35.524138 | 125 | 0.757175 | 4.542024 | false | false | false | false |
emilstahl/swift | test/Interpreter/function_metatypes.swift | 12 | 1116 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
protocol ProtocolHasInOut {
typealias Input
typealias Mutator = (inout Input) -> ()
var f: Mutator { get }
}
// Emit type metadata for this struct's fields
struct HasInOut<T> {
var f: (inout T) -> ()
}
struct HasInOutProtocol : ProtocolHasInOut {
typealias Input = Int
let f: (inout Input) -> ()
}
func foo<T>(t: T.Type) -> Any {
return { (x: T) -> Int in return 6060 }
}
var i = 0
// Dynamic casting
var f = foo((Int, Int).self)
var g = f as! (Int, Int) -> Int
print(g(1010, 2020))
// CHECK: 6060
// Struct with InOut
let hio = HasInOut(f: { (inout x: Int) in x = 3030 })
i = 0
hio.f(&i)
print(i)
// CHECK: 3030
// Struct that conforms to Protocol with InOut
let hiop = HasInOutProtocol(f: { (inout x: Int) in x = 4040 })
i = 0
hiop.f(&i)
print(i)
// CHECK: 4040
func fooInOut<T>(t: T.Type) -> Any {
return { (inout x: T) -> () in x = unsafeBitCast((8080, 9090), T.self) }
}
var fio = fooInOut((Int, Int).self)
var gio = fio as! (inout (Int, Int)) -> ()
var xy = (0, 0)
gio(&xy)
print(xy)
// CHECK: (8080, 9090)
| apache-2.0 | d0a71f1f1f937ed1511a57153cb1f936 | 19.290909 | 74 | 0.616487 | 2.735294 | false | false | false | false |
cliqz-oss/browser-ios | Client/Frontend/Browser/ReaderModeBarView.swift | 2 | 6505 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import SnapKit
import Shared
import XCGLogger
private let log = Logger.browserLogger
enum ReaderModeBarButtonType {
case markAsRead, markAsUnread, settings, addToReadingList, removeFromReadingList
fileprivate var localizedDescription: String {
switch self {
case .markAsRead: return NSLocalizedString("Mark as Read", comment: "Name for Mark as read button in reader mode")
case .markAsUnread: return NSLocalizedString("Mark as Unread", comment: "Name for Mark as unread button in reader mode")
case .settings: return NSLocalizedString("Display Settings", comment: "Name for display settings button in reader mode. Display in the meaning of presentation, not monitor.")
case .addToReadingList: return NSLocalizedString("Add to Reading List", comment: "Name for button adding current article to reading list in reader mode")
case .removeFromReadingList: return NSLocalizedString("Remove from Reading List", comment: "Name for button removing current article from reading list in reader mode")
}
}
fileprivate var imageName: String {
switch self {
case .markAsRead: return "MarkAsRead"
case .markAsUnread: return "MarkAsUnread"
case .settings: return "SettingsSerif"
case .addToReadingList: return "addToReadingList"
case .removeFromReadingList: return "removeFromReadingList"
}
}
fileprivate var image: UIImage? {
let image = UIImage(named: imageName)
image?.accessibilityLabel = localizedDescription
return image
}
}
protocol ReaderModeBarViewDelegate {
func readerModeBar(_ readerModeBar: ReaderModeBarView, didSelectButton buttonType: ReaderModeBarButtonType)
}
struct ReaderModeBarViewUX {
static let Themes: [String: Theme] = {
var themes = [String: Theme]()
var theme = Theme()
theme.backgroundColor = UIConstants.PrivateModeReaderModeBackgroundColor
theme.buttonTintColor = UIColor.white
themes[Theme.PrivateMode] = theme
theme = Theme()
theme.backgroundColor = UIColor.white
theme.buttonTintColor = UIColor.darkGray
themes[Theme.NormalMode] = theme
// TODO: to be removed
// Cliqz: Temporary use same mode for both Normal and Private modes
themes[Theme.PrivateMode] = theme
return themes
}()
}
class ReaderModeBarView: UIView {
var delegate: ReaderModeBarViewDelegate?
var readStatusButton: UIButton!
var settingsButton: UIButton!
var listStatusButton: UIButton!
dynamic var buttonTintColor: UIColor = UIColor.clear {
didSet {
readStatusButton.tintColor = self.buttonTintColor
settingsButton.tintColor = self.buttonTintColor
listStatusButton.tintColor = self.buttonTintColor
}
}
override init(frame: CGRect) {
super.init(frame: frame)
readStatusButton = createButton(.markAsRead, action: #selector(ReaderModeBarView.SELtappedReadStatusButton(_:)))
readStatusButton.snp_makeConstraints { (make) -> () in
make.left.equalTo(self)
make.height.centerY.equalTo(self)
make.width.equalTo(80)
}
settingsButton = createButton(.settings, action: #selector(ReaderModeBarView.SELtappedSettingsButton(_:)))
settingsButton.snp_makeConstraints { (make) -> () in
make.height.centerX.centerY.equalTo(self)
make.width.equalTo(80)
}
listStatusButton = createButton(.addToReadingList, action: #selector(ReaderModeBarView.SELtappedListStatusButton(_:)))
listStatusButton.snp_makeConstraints { (make) -> () in
make.right.equalTo(self)
make.height.centerY.equalTo(self)
make.width.equalTo(80)
}
readStatusButton.isHidden = true
listStatusButton.isHidden = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let context = UIGraphicsGetCurrentContext()
context!.setLineWidth(0.5)
context!.setStrokeColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1.0)
context!.setStrokeColor(UIColor.gray.cgColor)
context!.beginPath()
context!.move(to: CGPoint(x: 0, y: frame.height))
context!.addLine(to: CGPoint(x: frame.width, y: frame.height))
context!.strokePath()
}
fileprivate func createButton(_ type: ReaderModeBarButtonType, action: Selector) -> UIButton {
let button = UIButton()
addSubview(button)
button.setImage(type.image, for: UIControlState())
button.addTarget(self, action: action, for: .touchUpInside)
return button
}
func SELtappedReadStatusButton(_ sender: UIButton!) {
delegate?.readerModeBar(self, didSelectButton: unread ? .markAsRead : .markAsUnread)
}
func SELtappedSettingsButton(_ sender: UIButton!) {
delegate?.readerModeBar(self, didSelectButton: .settings)
}
func SELtappedListStatusButton(_ sender: UIButton!) {
delegate?.readerModeBar(self, didSelectButton: added ? .removeFromReadingList : .addToReadingList)
}
var unread: Bool = true {
didSet {
let buttonType: ReaderModeBarButtonType = unread && added ? .markAsRead : .markAsUnread
readStatusButton.setImage(buttonType.image, for: UIControlState())
readStatusButton.isEnabled = added
readStatusButton.alpha = added ? 1.0 : 0.6
}
}
var added: Bool = false {
didSet {
let buttonType: ReaderModeBarButtonType = added ? .removeFromReadingList : .addToReadingList
listStatusButton.setImage(buttonType.image, for: UIControlState())
}
}
}
extension ReaderModeBarView: Themeable {
func applyTheme(_ themeName: String) {
guard let theme = ReaderModeBarViewUX.Themes[themeName] else {
log.error("Unable to apply unknown theme \(themeName)")
return
}
backgroundColor = theme.backgroundColor
buttonTintColor = theme.buttonTintColor!
}
}
| mpl-2.0 | cb9ee1d185521da97c94d0b288ee3acc | 36.171429 | 182 | 0.671176 | 5.09397 | false | false | false | false |
mcxiaoke/learning-ios | ios_programming_4th/Homepwner-ch17/Homepwner/ItemsViewController.swift | 1 | 5446 | //
// ViewController.swift
// Homepwner
//
// Created by Xiaoke Zhang on 2017/8/16.
// Copyright © 2017年 Xiaoke Zhang. All rights reserved.
//
import UIKit
class ItemsViewController: UITableViewController {
@IBOutlet var headerView:UIView!
@IBAction func addNewItem(_ sender: AnyObject) {
print("addNewItem")
let newItem = ItemStore.shared.createItem()
let lastRow = ItemStore.shared.allItems.index(of:newItem) ?? 0
let indexPath = IndexPath(row:lastRow, section:0)
tableView.insertRows(at: [indexPath], with: .none)
let detailVC = DetailViewController()
detailVC.item = newItem
detailVC.createMode = true
showModalViewController(vc: detailVC)
}
@IBAction func toggleEditMode(_ sender: AnyObject) {
print("toggleEditMode \(self.isEditing)")
guard let v = sender as? UIButton else { return }
if self.isEditing {
v.setTitle("Edit", for: .normal)
self.isEditing = false
} else {
v.setTitle("Done", for: .normal)
self.isEditing = true
}
}
init() {
super.init(style: .plain)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "UITableViewCell")
for _ in 0..<5 {
ItemStore.shared.allItems += Item.randomItem()
}
self.navigationItem.title = "Homepwner"
let newButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addNewItem(_:)))
self.navigationItem.leftBarButtonItem = self.editButtonItem
self.navigationItem.rightBarButtonItem = newButtonItem
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension
}
override func viewWillAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.tableView.reloadData()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ItemStore.shared.allItems.count + 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell")!
if indexPath.row == ItemStore.shared.allItems.count {
cell.textLabel?.textAlignment = .center
cell.textLabel?.text = "No more items!"
} else {
let item = ItemStore.shared.allItems[indexPath.row]
cell.textLabel?.textAlignment = .left
cell.textLabel?.text = item.description
}
return cell
}
// can not edit last row
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return indexPath.row < ItemStore.shared.allItems.count
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
print("commitEditingStyle \(editingStyle.rawValue) \(indexPath.row)")
if editingStyle == .delete {
let item = ItemStore.shared.allItems[indexPath.row]
ItemStore.shared.allItems -= item
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
// can not move last row
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return indexPath.row < ItemStore.shared.allItems.count
}
// can not move to last row
override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
if proposedDestinationIndexPath.row == ItemStore.shared.allItems.count {
return sourceIndexPath
} else {
return proposedDestinationIndexPath
}
}
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
print("moveRowAt from \(sourceIndexPath.row) to \(destinationIndexPath.row)")
ItemStore.shared.move(fromIndex: sourceIndexPath.row, toIndex: destinationIndexPath.row)
}
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if indexPath.row == ItemStore.shared.allItems.count {
return nil
} else {
return indexPath
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let detailVC = DetailViewController()
detailVC.item = ItemStore.shared.allItems[indexPath.row]
showModalViewController(vc: detailVC)
}
func showModalViewController(vc: DetailViewController) {
let nvc = UINavigationController(rootViewController: vc)
if UIDevice.current.userInterfaceIdiom == .pad {
vc.dismissBlock = { self.tableView.reloadData() }
nvc.modalPresentationStyle = .formSheet
}
self.present(nvc, animated: true, completion: nil)
}
}
| apache-2.0 | 459985fb1223e1b140d9982fc1160e66 | 36.537931 | 189 | 0.655705 | 5.208612 | false | false | false | false |
Pursuit92/antlr4 | runtime/Swift/Antlr4/org/antlr/v4/runtime/atn/LL1Analyzer.swift | 3 | 10474 | /* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
public class LL1Analyzer {
/** Special value added to the lookahead sets to indicate that we hit
* a predicate during analysis if {@code seeThruPreds==false}.
*/
public let HIT_PRED: Int = CommonToken.INVALID_TYPE
public let atn: ATN
public init(_ atn: ATN) {
self.atn = atn
}
/**
* Calculates the SLL(1) expected lookahead set for each outgoing transition
* of an {@link org.antlr.v4.runtime.atn.ATNState}. The returned array has one element for each
* outgoing transition in {@code s}. If the closure from transition
* <em>i</em> leads to a semantic predicate before matching a symbol, the
* element at index <em>i</em> of the result will be {@code null}.
*
* @param s the ATN state
* @return the expected symbols for each outgoing transition of {@code s}.
*/
public func getDecisionLookahead(_ s: ATNState?) throws -> [IntervalSet?]? {
// print("LOOK("+s.stateNumber+")");
guard let s = s else {
return nil
}
let length = s.getNumberOfTransitions()
var look: [IntervalSet?] = [IntervalSet?](repeating: nil, count: length)
//new IntervalSet[s.getNumberOfTransitions()];
for alt in 0..<length {
look[alt] = try IntervalSet()
var lookBusy: Set<ATNConfig> = Set<ATNConfig>()
let seeThruPreds: Bool = false // fail to get lookahead upon pred
try _LOOK(s.transition(alt).target, nil, PredictionContext.EMPTY,
look[alt]!, &lookBusy, BitSet(), seeThruPreds, false)
// Wipe out lookahead for this alternative if we found nothing
// or we had a predicate when we !seeThruPreds
if look[alt]!.size() == 0 || look[alt]!.contains(HIT_PRED) {
look[alt] = nil
}
}
return look
}
/**
* Compute set of tokens that can follow {@code s} in the ATN in the
* specified {@code ctx}.
*
* <p>If {@code ctx} is {@code null} and the end of the rule containing
* {@code s} is reached, {@link org.antlr.v4.runtime.Token#EPSILON} is added to the result set.
* If {@code ctx} is not {@code null} and the end of the outermost rule is
* reached, {@link org.antlr.v4.runtime.Token#EOF} is added to the result set.</p>
*
* @param s the ATN state
* @param ctx the complete parser context, or {@code null} if the context
* should be ignored
*
* @return The set of tokens that can follow {@code s} in the ATN in the
* specified {@code ctx}.
*/
public func LOOK(_ s: ATNState, _ ctx: RuleContext?) throws -> IntervalSet {
return try LOOK(s, nil, ctx)
}
/**
* Compute set of tokens that can follow {@code s} in the ATN in the
* specified {@code ctx}.
*
* <p>If {@code ctx} is {@code null} and the end of the rule containing
* {@code s} is reached, {@link org.antlr.v4.runtime.Token#EPSILON} is added to the result set.
* If {@code ctx} is not {@code null} and the end of the outermost rule is
* reached, {@link org.antlr.v4.runtime.Token#EOF} is added to the result set.</p>
*
* @param s the ATN state
* @param stopState the ATN state to stop at. This can be a
* {@link org.antlr.v4.runtime.atn.BlockEndState} to detect epsilon paths through a closure.
* @param ctx the complete parser context, or {@code null} if the context
* should be ignored
*
* @return The set of tokens that can follow {@code s} in the ATN in the
* specified {@code ctx}.
*/
public func LOOK(_ s: ATNState, _ stopState: ATNState?, _ ctx: RuleContext?) throws -> IntervalSet {
let r: IntervalSet = try IntervalSet()
let seeThruPreds: Bool = true // ignore preds; get all lookahead
let lookContext: PredictionContext? = ctx != nil ? PredictionContext.fromRuleContext(s.atn!, ctx) : nil
var config = Set<ATNConfig>()
try _LOOK(s, stopState, lookContext,
r, &config, BitSet(), seeThruPreds, true)
return r
}
/**
* Compute set of tokens that can follow {@code s} in the ATN in the
* specified {@code ctx}.
*
* <p>If {@code ctx} is {@code null} and {@code stopState} or the end of the
* rule containing {@code s} is reached, {@link org.antlr.v4.runtime.Token#EPSILON} is added to
* the result set. If {@code ctx} is not {@code null} and {@code addEOF} is
* {@code true} and {@code stopState} or the end of the outermost rule is
* reached, {@link org.antlr.v4.runtime.Token#EOF} is added to the result set.</p>
*
* @param s the ATN state.
* @param stopState the ATN state to stop at. This can be a
* {@link org.antlr.v4.runtime.atn.BlockEndState} to detect epsilon paths through a closure.
* @param ctx The outer context, or {@code null} if the outer context should
* not be used.
* @param look The result lookahead set.
* @param lookBusy A set used for preventing epsilon closures in the ATN
* from causing a stack overflow. Outside code should pass
* {@code new HashSet<ATNConfig>} for this argument.
* @param calledRuleStack A set used for preventing left recursion in the
* ATN from causing a stack overflow. Outside code should pass
* {@code new BitSet()} for this argument.
* @param seeThruPreds {@code true} to true semantic predicates as
* implicitly {@code true} and "see through them", otherwise {@code false}
* to treat semantic predicates as opaque and add {@link #HIT_PRED} to the
* result if one is encountered.
* @param addEOF Add {@link org.antlr.v4.runtime.Token#EOF} to the result if the end of the
* outermost context is reached. This parameter has no effect if {@code ctx}
* is {@code null}.
*/
internal func _LOOK(_ s: ATNState,
_ stopState: ATNState?,
_ ctx: PredictionContext?,
_ look: IntervalSet,
_ lookBusy: inout Set<ATNConfig>,
_ calledRuleStack: BitSet,
_ seeThruPreds: Bool, _ addEOF: Bool) throws {
// print ("_LOOK(\(s.stateNumber), ctx=\(ctx)");
//TODO var c : ATNConfig = ATNConfig(s, 0, ctx);
if s.description == "273" {
var s = 0
}
var c: ATNConfig = ATNConfig(s, 0, ctx)
if lookBusy.contains(c) {
return
} else {
lookBusy.insert(c)
}
// if ( !lookBusy.insert (c) ) {
// return;
// }
if s == stopState {
guard let ctx = ctx else {
try look.add(CommonToken.EPSILON)
return
}
if ctx.isEmpty() && addEOF {
try look.add(CommonToken.EOF)
return
}
}
if s is RuleStopState {
guard let ctx = ctx else {
try look.add(CommonToken.EPSILON)
return
}
if ctx.isEmpty() && addEOF {
try look.add(CommonToken.EOF)
return
}
if ctx != PredictionContext.EMPTY {
// run thru all possible stack tops in ctx
let length = ctx.size()
for i in 0..<length {
var returnState: ATNState = atn.states[(ctx.getReturnState(i))]!
var removed: Bool = try calledRuleStack.get(returnState.ruleIndex!)
//TODO try
//try {
try calledRuleStack.clear(returnState.ruleIndex!)
try self._LOOK(returnState, stopState, ctx.getParent(i), look, &lookBusy, calledRuleStack, seeThruPreds, addEOF)
//}
defer {
if removed {
try! calledRuleStack.set(returnState.ruleIndex!)
}
}
}
return
}
}
var n: Int = s.getNumberOfTransitions()
for i in 0..<n {
var t: Transition = s.transition(i)
if type(of: t) === RuleTransition.self {
if try calledRuleStack.get((t as! RuleTransition).target.ruleIndex!) {
continue
}
var newContext: PredictionContext =
SingletonPredictionContext.create(ctx, (t as! RuleTransition).followState.stateNumber)
//TODO try
//try {
try calledRuleStack.set((t as! RuleTransition).target.ruleIndex!)
try _LOOK(t.target, stopState, newContext, look, &lookBusy, calledRuleStack, seeThruPreds, addEOF)
//}
defer {
try! calledRuleStack.clear((t as! RuleTransition).target.ruleIndex!)
}
} else {
if t is AbstractPredicateTransition {
if seeThruPreds {
try _LOOK(t.target, stopState, ctx, look, &lookBusy, calledRuleStack, seeThruPreds, addEOF)
} else {
try look.add(HIT_PRED)
}
} else {
if t.isEpsilon() {
try _LOOK(t.target, stopState, ctx, look, &lookBusy, calledRuleStack, seeThruPreds, addEOF)
} else {
if type(of: t) === WildcardTransition.self {
try look.addAll(IntervalSet.of(CommonToken.MIN_USER_TOKEN_TYPE, atn.maxTokenType))
} else {
var set: IntervalSet? = try t.labelIntervalSet()
if set != nil {
if t is NotSetTransition {
set = try set!.complement(IntervalSet.of(CommonToken.MIN_USER_TOKEN_TYPE, atn.maxTokenType)) as? IntervalSet
}
try look.addAll(set)
}
}
}
}
}
}
}
}
| bsd-3-clause | 1cbac345b4eea54c85c2bc40b09da3b2 | 41.064257 | 144 | 0.548883 | 4.338857 | false | false | false | false |
breadwallet/breadwallet-core | Swift/BRCryptoDemo/TransferTableViewCell.swift | 1 | 2375 | //
// TransferTableViewCell.swift
// CoreDemo
//
// Created by Ed Gamble on 8/9/18.
// Copyright © 2018-2019 Breadwallet AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
// See the CONTRIBUTORS file at the project root for a list of contributors.
//
import UIKit
import BRCrypto
class TransferTableViewCell: UITableViewCell {
var transfer : Transfer? {
didSet {
updateView()
}
}
var dateFormatter : DateFormatter!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
if nil == dateFormatter {
dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func colorForState() -> UIColor {
guard let state = transfer?.state else { return UIColor.black }
switch state {
case .created: return UIColor.gray
case .submitted: return UIColor.yellow
case .included: return UIColor.green
// case .errored: return UIColor.red
// case .cancelled: return UIColor.blue
// case .replaced: return UIColor.blue
case .deleted: return UIColor.black
case .signed: return UIColor.yellow
case .pending: return UIColor.yellow
case .failed/* (let reason) */: return UIColor.red
}
}
func updateView () {
if let transfer = transfer {
let date: Date? = transfer.confirmation.map {
Date (timeIntervalSince1970: TimeInterval ($0.timestamp))
}
let hash = transfer.hash
dateLabel.text = date.map { dateFormatter.string(from: $0) } ?? "<pending>"
addrLabel.text = hash.map { $0.description } ?? "<pending>"
amountLabel.text = transfer.amountDirected.description
feeLabel.text = "Fee: \(transfer.fee)"
dotView.mainColor = colorForState()
dotView.setNeedsDisplay()
}
}
@IBOutlet var dateLabel: UILabel!
@IBOutlet var amountLabel: UILabel!
@IBOutlet var addrLabel: UILabel!
@IBOutlet var feeLabel: UILabel!
@IBOutlet var dotView: Dot!
}
| mit | 34301c1b205f3e651d85496cba6b4a3e | 29.435897 | 87 | 0.620051 | 4.636719 | false | false | false | false |
tid-kijyun/Kanna | Sources/Kanna/libxmlHTMLDocument.swift | 2 | 12104 | /**@file libxmlHTMLDocument.swift
Kanna
Copyright (c) 2015 Atsushi Kiwaki (@_tid_)
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 CoreFoundation
import libxml2
extension String.Encoding {
var IANACharSetName: String? {
#if os(Linux) && swift(>=4)
switch self {
case .ascii:
return "us-ascii"
case .iso2022JP:
return "iso-2022-jp"
case .isoLatin1:
return "iso-8859-1"
case .isoLatin2:
return "iso-8859-2"
case .japaneseEUC:
return "euc-jp"
case .macOSRoman:
return "macintosh"
case .nextstep:
return "x-nextstep"
case .nonLossyASCII:
return nil
case .shiftJIS:
return "cp932"
case .symbol:
return "x-mac-symbol"
case .unicode:
return "utf-16"
case .utf16:
return "utf-16"
case .utf16BigEndian:
return "utf-16be"
case .utf32:
return "utf-32"
case .utf32BigEndian:
return "utf-32be"
case .utf32LittleEndian:
return "utf-32le"
case .utf8:
return "utf-8"
case .windowsCP1250:
return "windows-1250"
case .windowsCP1251:
return "windows-1251"
case .windowsCP1252:
return "windows-1252"
case .windowsCP1253:
return "windows-1253"
case .windowsCP1254:
return "windows-1254"
default:
return nil
}
#elseif os(Linux) && swift(>=3)
switch self {
case String.Encoding.ascii:
return "us-ascii"
case String.Encoding.iso2022JP:
return "iso-2022-jp"
case String.Encoding.isoLatin1:
return "iso-8859-1"
case String.Encoding.isoLatin2:
return "iso-8859-2"
case String.Encoding.japaneseEUC:
return "euc-jp"
case String.Encoding.macOSRoman:
return "macintosh"
case String.Encoding.nextstep:
return "x-nextstep"
case String.Encoding.nonLossyASCII:
return nil
case String.Encoding.shiftJIS:
return "cp932"
case String.Encoding.symbol:
return "x-mac-symbol"
case String.Encoding.unicode:
return "utf-16"
case String.Encoding.utf16:
return "utf-16"
case String.Encoding.utf16BigEndian:
return "utf-16be"
case String.Encoding.utf32:
return "utf-32"
case String.Encoding.utf32BigEndian:
return "utf-32be"
case String.Encoding.utf32LittleEndian:
return "utf-32le"
case String.Encoding.utf8:
return "utf-8"
case String.Encoding.windowsCP1250:
return "windows-1250"
case String.Encoding.windowsCP1251:
return "windows-1251"
case String.Encoding.windowsCP1252:
return "windows-1252"
case String.Encoding.windowsCP1253:
return "windows-1253"
case String.Encoding.windowsCP1254:
return "windows-1254"
default:
return nil
}
#else
let cfenc = CFStringConvertNSStringEncodingToEncoding(rawValue)
guard let cfencstr = CFStringConvertEncodingToIANACharSetName(cfenc) else {
return nil
}
return cfencstr as String
#endif
}
}
/*
libxmlHTMLDocument
*/
final class libxmlHTMLDocument: HTMLDocument {
private var docPtr: htmlDocPtr?
private var rootNode: XMLElement?
private var html: String
private var url: String?
private var encoding: String.Encoding
var text: String? { rootNode?.text }
var toHTML: String? {
let buf = xmlBufferCreate()
let outputBuf = xmlOutputBufferCreateBuffer(buf, nil)
defer {
xmlOutputBufferClose(outputBuf)
xmlBufferFree(buf)
}
htmlDocContentDumpOutput(outputBuf, docPtr, nil)
let html = String(cString: UnsafePointer(xmlOutputBufferGetContent(outputBuf)))
return html
}
var toXML: String? {
var buf: UnsafeMutablePointer<xmlChar>?
let size: UnsafeMutablePointer<Int32>? = nil
defer {
xmlFree(buf)
}
xmlDocDumpMemory(docPtr, &buf, size)
let html = String(cString: UnsafePointer<UInt8>(buf!))
return html
}
var innerHTML: String? { rootNode?.innerHTML }
var className: String? { nil }
var tagName: String? {
get { nil }
set {}
}
var content: String? {
get { text }
set { rootNode?.content = newValue }
}
var namespaces: [Namespace] { getNamespaces(docPtr: docPtr) }
init(html: String, url: String?, encoding: String.Encoding, option: UInt) throws {
self.html = html
self.url = url
self.encoding = encoding
guard html.lengthOfBytes(using: encoding) > 0 else {
throw ParseError.Empty
}
guard let charsetName = encoding.IANACharSetName,
let cur = html.cString(using: encoding) else {
throw ParseError.EncodingMismatch
}
let url: String = ""
docPtr = cur.withUnsafeBytes { htmlReadDoc($0.bindMemory(to: xmlChar.self).baseAddress!, url, charsetName, CInt(option)) }
guard let docPtr = docPtr else {
throw ParseError.EncodingMismatch
}
rootNode = try libxmlHTMLNode(document: self, docPtr: docPtr)
}
deinit {
xmlFreeDoc(docPtr)
}
var title: String? { at_xpath("//title")?.text }
var head: XMLElement? { at_xpath("//head") }
var body: XMLElement? { at_xpath("//body") }
func xpath(_ xpath: String, namespaces: [String: String]? = nil) -> XPathObject {
guard let docPtr = docPtr else { return .none }
return XPath(doc: self, docPtr: docPtr).xpath(xpath, namespaces: namespaces)
}
func css(_ selector: String, namespaces: [String: String]? = nil) -> XPathObject {
guard let docPtr = docPtr else { return .none }
return XPath(doc: self, docPtr: docPtr).css(selector, namespaces: namespaces)
}
}
/*
libxmlXMLDocument
*/
final class libxmlXMLDocument: XMLDocument {
private var docPtr: xmlDocPtr?
private var rootNode: XMLElement?
private var xml: String
private var url: String?
private var encoding: String.Encoding
var text: String? { rootNode?.text }
var toHTML: String? {
let buf = xmlBufferCreate()
let outputBuf = xmlOutputBufferCreateBuffer(buf, nil)
defer {
xmlOutputBufferClose(outputBuf)
xmlBufferFree(buf)
}
htmlDocContentDumpOutput(outputBuf, docPtr, nil)
let html = String(cString: UnsafePointer(xmlOutputBufferGetContent(outputBuf)))
return html
}
var toXML: String? {
var buf: UnsafeMutablePointer<xmlChar>?
let size: UnsafeMutablePointer<Int32>? = nil
defer {
xmlFree(buf)
}
xmlDocDumpMemory(docPtr, &buf, size)
let html = String(cString: UnsafePointer<UInt8>(buf!))
return html
}
var innerHTML: String? { rootNode?.innerHTML }
var className: String? { nil }
var tagName: String? {
get { nil }
set {}
}
var content: String? {
get { text }
set { rootNode?.content = newValue }
}
var namespaces: [Namespace] { getNamespaces(docPtr: docPtr) }
init(xml: String, url: String?, encoding: String.Encoding, option: UInt) throws {
self.xml = xml
self.url = url
self.encoding = encoding
if xml.isEmpty {
throw ParseError.Empty
}
guard let charsetName = encoding.IANACharSetName,
let cur = xml.cString(using: encoding) else {
throw ParseError.EncodingMismatch
}
let url: String = ""
docPtr = cur.withUnsafeBytes { xmlReadDoc($0.bindMemory(to: xmlChar.self).baseAddress!, url, charsetName, CInt(option)) }
rootNode = try libxmlHTMLNode(document: self, docPtr: docPtr!)
}
deinit {
xmlFreeDoc(docPtr)
}
func xpath(_ xpath: String, namespaces: [String: String]? = nil) -> XPathObject {
guard let docPtr = docPtr else { return .none }
return XPath(doc: self, docPtr: docPtr).xpath(xpath, namespaces: namespaces)
}
func css(_ selector: String, namespaces: [String: String]? = nil) -> XPathObject {
guard let docPtr = docPtr else { return .none }
return XPath(doc: self, docPtr: docPtr).css(selector, namespaces: namespaces)
}
}
struct XPath {
private let doc: XMLDocument
private var docPtr: xmlDocPtr
private var nodePtr: xmlNodePtr?
private var isRoot: Bool {
guard let nodePtr = nodePtr else { return true }
return xmlDocGetRootElement(docPtr) == nodePtr
}
init(doc: XMLDocument, docPtr: xmlDocPtr, nodePtr: xmlNodePtr? = nil) {
self.doc = doc
self.docPtr = docPtr
self.nodePtr = nodePtr
}
func xpath(_ xpath: String, namespaces: [String: String]? = nil) -> XPathObject {
guard let ctxt = xmlXPathNewContext(docPtr) else { return .none }
defer { xmlXPathFreeContext(ctxt) }
if let nsDictionary = namespaces {
for (ns, name) in nsDictionary {
xmlXPathRegisterNs(ctxt, ns, name)
}
}
if let node = nodePtr {
ctxt.pointee.node = node
}
guard let result = xmlXPathEvalExpression(adoptXpath(xpath), ctxt) else { return .none }
defer { xmlXPathFreeObject(result) }
return XPathObject(document: doc, docPtr: docPtr, object: result.pointee)
}
func css(_ selector: String, namespaces: [String: String]? = nil) -> XPathObject {
if let xpath = try? CSS.toXPath(selector, isRoot: isRoot) {
return self.xpath(xpath, namespaces: namespaces)
}
return .none
}
private func adoptXpath(_ xpath: String) -> String {
guard !isRoot else { return xpath }
if xpath.hasPrefix("/") {
return "." + xpath
} else {
return xpath
}
}
}
private func getNamespaces(docPtr: xmlDocPtr?) -> [Namespace] {
let rootNode = xmlDocGetRootElement(docPtr)
guard let ns = xmlGetNsList(docPtr, rootNode) else {
return []
}
var result: [Namespace] = []
var next = ns.pointee
while next != nil {
if let namePtr = next?.pointee.href {
let prefixPtr = next?.pointee.prefix
let prefix = prefixPtr == nil ? "" : String(cString: UnsafePointer<UInt8>(prefixPtr!))
let name = String(cString: UnsafePointer<UInt8>(namePtr))
result.append(Namespace(prefix: prefix, name: name))
}
next = next?.pointee.next
}
return result
}
| mit | 1ed86fb1f303198ed0f9b1bde990f63e | 30.035897 | 131 | 0.605502 | 4.310541 | false | false | false | false |
cplaverty/KeitaiWaniKani | WaniKaniKit/Model/ReviewStatistics.swift | 1 | 2040 | //
// ReviewStatistics.swift
// WaniKaniKit
//
// Copyright © 2017 Chris Laverty. All rights reserved.
//
public struct ReviewStatistics: ResourceCollectionItemData, Equatable {
public let createdAt: Date
public let subjectID: Int
public let subjectType: SubjectType
public let meaningCorrect: Int
public let meaningIncorrect: Int
public let meaningMaxStreak: Int
public let meaningCurrentStreak: Int
public let readingCorrect: Int
public let readingIncorrect: Int
public let readingMaxStreak: Int
public let readingCurrentStreak: Int
public let percentageCorrect: Int
public let isHidden: Bool
private enum CodingKeys: String, CodingKey {
case createdAt = "created_at"
case subjectID = "subject_id"
case subjectType = "subject_type"
case meaningCorrect = "meaning_correct"
case meaningIncorrect = "meaning_incorrect"
case meaningMaxStreak = "meaning_max_streak"
case meaningCurrentStreak = "meaning_current_streak"
case readingCorrect = "reading_correct"
case readingIncorrect = "reading_incorrect"
case readingMaxStreak = "reading_max_streak"
case readingCurrentStreak = "reading_current_streak"
case percentageCorrect = "percentage_correct"
case isHidden = "hidden"
}
}
public extension ReviewStatistics {
var total: Int {
return meaningCorrect + readingCorrect + meaningIncorrect + readingIncorrect
}
var meaningTotal: Int {
return meaningCorrect + meaningIncorrect
}
var meaningPercentageCorrect: Int {
guard meaningTotal != 0 else {
return 100
}
return meaningCorrect * 100 / meaningTotal
}
var readingTotal: Int {
return readingCorrect + readingIncorrect
}
var readingPercentageCorrect: Int {
guard readingTotal != 0 else {
return 100
}
return readingCorrect * 100 / readingTotal
}
}
| mit | 1d01bd4bd2a8077da00a4d61fcfc0caa | 28.985294 | 84 | 0.664541 | 5.084788 | false | false | false | false |
tottakai/RxSwift | RxExample/RxExample/Examples/WikipediaImageSearch/WikipediaAPI/WikipediaSearchResult.swift | 8 | 1830 | //
// WikipediaSearchResult.swift
// RxExample
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
struct WikipediaSearchResult: CustomDebugStringConvertible {
let title: String
let description: String
let URL: Foundation.URL
init(title: String, description: String, URL: Foundation.URL) {
self.title = title
self.description = description
self.URL = URL
}
// tedious parsing part
static func parseJSON(_ json: [AnyObject]) throws -> [WikipediaSearchResult] {
let rootArrayTyped = json.map { $0 as? [AnyObject] }
.filter { $0 != nil }
.map { $0! }
if rootArrayTyped.count != 3 {
throw WikipediaParseError
}
let titleAndDescription = Array(zip(rootArrayTyped[0], rootArrayTyped[1]))
let titleDescriptionAndUrl: [((AnyObject, AnyObject), AnyObject)] = Array(zip(titleAndDescription, rootArrayTyped[2]))
let searchResults: [WikipediaSearchResult] = try titleDescriptionAndUrl.map ( { result -> WikipediaSearchResult in
let (first, url) = result
let (title, description) = first
guard let titleString = title as? String,
let descriptionString = description as? String,
let urlString = url as? String,
let URL = Foundation.URL(string: urlString) else {
throw WikipediaParseError
}
return WikipediaSearchResult(title: titleString, description: descriptionString, URL: URL)
})
return searchResults
}
}
extension WikipediaSearchResult {
var debugDescription: String {
return "[\(title)](\(URL))"
}
}
| mit | 21693b1ba2ef86c88787e2af897634e3 | 29.483333 | 126 | 0.625478 | 4.750649 | false | false | false | false |
KrishMunot/swift | test/1_stdlib/Interval.swift | 3 | 5586 | //===--- Interval.swift ---------------------------------------------------===//
//
// 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: %target-run-simple-swift
// REQUIRES: executable_test
//
import StdlibUnittest
// Check that the generic parameter is called 'Bound'.
protocol TestProtocol1 {}
extension HalfOpenInterval where Bound : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension ClosedInterval where Bound : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
var IntervalTestSuite = TestSuite("Interval")
IntervalTestSuite.test("Ambiguity") {
// Ensure type deduction still works as expected; these will fail to
// compile if it's broken
var pieToPie = -3.1415927..<3.1415927
expectType(HalfOpenInterval<Double>.self, &pieToPie)
var pieThruPie = -3.1415927...3.1415927
expectType(ClosedInterval<Double>.self, &pieThruPie)
var zeroToOne = 0..<1
expectType(Range<Int>.self, &zeroToOne)
var zeroThruOne = 0...1
// If/when we get a separate ClosedRange representation, this test
// will have to change.
expectType(Range<Int>.self, &zeroThruOne)
}
IntervalTestSuite.test("PatternMatching") {
let pie = 3.1415927
let expectations : [(Double, halfOpen: Bool, closed: Bool)] = [
(-2 * pie, false, false),
(-pie, true, true),
(0, true, true),
(pie, false, true),
(2 * pie, false, false)
]
for (x, halfOpenExpected, closedExpected) in expectations {
var halfOpen: Bool
switch x {
case -3.1415927..<3.1415927:
halfOpen = true
default:
halfOpen = false
}
var closed: Bool
switch x {
case -3.1415927...3.1415927:
closed = true
default:
closed = false
}
expectEqual(halfOpenExpected, halfOpen)
expectEqual(closedExpected, closed)
}
}
IntervalTestSuite.test("Overlaps") {
func expectOverlaps<
I0: Interval, I1: Interval where I0.Bound == I1.Bound
>(_ expectation: Bool, _ lhs: I0, _ rhs: I1) {
if expectation {
expectTrue(lhs.overlaps(rhs))
expectTrue(rhs.overlaps(lhs))
}
else {
expectFalse(lhs.overlaps(rhs))
expectFalse(rhs.overlaps(lhs))
}
}
// 0-4, 5-10
expectOverlaps(false, 0..<4, 5..<10)
expectOverlaps(false, 0..<4, 5...10)
expectOverlaps(false, 0...4, 5..<10)
expectOverlaps(false, 0...4, 5...10)
// 0-5, 5-10
expectOverlaps(false, 0..<5, 5..<10)
expectOverlaps(false, 0..<5, 5...10)
expectOverlaps(true, 0...5, 5..<10)
expectOverlaps(true, 0...5, 5...10)
// 0-6, 5-10
expectOverlaps(true, 0..<6, 5..<10)
expectOverlaps(true, 0..<6, 5...10)
expectOverlaps(true, 0...6, 5..<10)
expectOverlaps(true, 0...6, 5...10)
// 0-20, 5-10
expectOverlaps(true, 0..<20, 5..<10)
expectOverlaps(true, 0..<20, 5...10)
expectOverlaps(true, 0...20, 5..<10)
expectOverlaps(true, 0...20, 5...10)
// 0-0, 0-5
expectOverlaps(false, 0..<0, 0..<5)
expectOverlaps(false, 0..<0, 0...5)
}
IntervalTestSuite.test("Emptiness") {
expectTrue((0.0..<0.0).isEmpty)
expectFalse((0.0...0.0).isEmpty)
expectFalse((0.0..<0.1).isEmpty)
expectFalse((0.0..<0.1).isEmpty)
}
IntervalTestSuite.test("start/end") {
expectEqual(0.0, (0.0..<0.1).start)
expectEqual(0.0, (0.0...0.1).start)
expectEqual(0.1, (0.0..<0.1).end)
expectEqual(0.1, (0.0...0.1).end)
}
// Something to test with that distinguishes debugDescription from description
struct X<T : Comparable> : Comparable, CustomStringConvertible, CustomDebugStringConvertible {
init(_ a: T) {
self.a = a
}
var description: String {
return String(a)
}
var debugDescription: String {
return "X(\(String(reflecting: a)))"
}
var a: T
}
func < <T : Comparable>(lhs: X<T>, rhs: X<T>) -> Bool {
return lhs.a < rhs.a
}
func == <T : Comparable>(lhs: X<T>, rhs: X<T>) -> Bool {
return lhs.a == rhs.a
}
IntervalTestSuite.test("CustomStringConvertible/CustomDebugStringConvertible") {
expectEqual("0.0..<0.1", String(X(0.0)..<X(0.1)))
expectEqual("0.0...0.1", String(X(0.0)...X(0.1)))
expectEqual(
"HalfOpenInterval(X(0.0)..<X(0.5))",
String(reflecting: HalfOpenInterval(X(0.0)..<X(0.5))))
expectEqual(
"ClosedInterval(X(0.0)...X(0.5))",
String(reflecting: ClosedInterval(X(0.0)...X(0.5))))
}
IntervalTestSuite.test("rdar12016900") {
do {
let wc = 0
expectFalse((0x00D800 ..< 0x00E000).contains(wc))
}
do {
let wc = 0x00D800
expectTrue((0x00D800 ..< 0x00E000).contains(wc))
}
}
IntervalTestSuite.test("clamp") {
expectEqual(
(5..<10).clamp(0..<3), 5..<5)
expectEqual(
(5..<10).clamp(0..<9), 5..<9)
expectEqual(
(5..<10).clamp(0..<13), 5..<10)
expectEqual(
(5..<10).clamp(7..<9), 7..<9)
expectEqual(
(5..<10).clamp(7..<13), 7..<10)
expectEqual(
(5..<10).clamp(13..<15), 10..<10)
expectEqual(
(5...10).clamp(0...3), 5...5)
expectEqual(
(5...10).clamp(0...9), 5...9)
expectEqual(
(5...10).clamp(0...13), 5...10)
expectEqual(
(5...10).clamp(7...9), 7...9)
expectEqual(
(5...10).clamp(7...13), 7...10)
expectEqual(
(5...10).clamp(13...15), 10...10)
}
runAllTests()
| apache-2.0 | 02de156f07a439879a39711dc722cdf7 | 23.9375 | 94 | 0.611708 | 3.173864 | false | true | false | false |
srn214/Floral | Floral/Floral/Classes/Expand/Extensions/UIKit/UITableView+Extension.swift | 1 | 7165 | //
// UITableView+Extension.swift
// College
//
// Created by Liudongdong on 2019/4/4.
// Copyright © 2019 zeroLu. All rights reserved.
//
import UIKit
// MARK: - Properties
public extension UITableView {
/// Index path of last row in tableView.
var indexPathForLastRow: IndexPath? {
return indexPathForLastRow(inSection: lastSection)
}
/// Index of last section in tableView.
var lastSection: Int {
return numberOfSections > 0 ? numberOfSections - 1 : 0
}
}
// MARK: - Methods
public extension UITableView {
/// Number of all rows in all sections of tableView.
///
/// - Returns: The count of all rows in the tableView.
func numberOfRows() -> Int {
var section = 0
var rowCount = 0
while section < numberOfSections {
rowCount += numberOfRows(inSection: section)
section += 1
}
return rowCount
}
/// IndexPath for last row in section.
///
/// - Parameter section: section to get last row in.
/// - Returns: optional last indexPath for last row in section (if applicable).
func indexPathForLastRow(inSection section: Int) -> IndexPath? {
guard section >= 0 else { return nil }
guard numberOfRows(inSection: section) > 0 else {
return IndexPath(row: 0, section: section)
}
return IndexPath(row: numberOfRows(inSection: section) - 1, section: section)
}
/// 刷新数据
///
/// - Parameter completion: 刷新完成回调
func reloadData(_ completion: @escaping () -> Void) {
UIView.animate(withDuration: 0, animations: {
self.reloadData()
}, completion: { _ in
completion()
})
}
/// Remove TableFooterView.
func removeTableFooterView() {
tableFooterView = nil
}
/// Remove TableHeaderView.
func removeTableHeaderView() {
tableHeaderView = nil
}
/// SwifterSwift: Dequeue reusable UITableViewCell using class name
///
/// - Parameter name: UITableViewCell type
/// - Returns: UITableViewCell object with associated class name.
/// 获取 UITableViewCell
///
/// - Parameter name: 继承UITableViewCell类Class
/// - Returns: Cell
func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type) -> T {
guard let cell = dequeueReusableCell(withIdentifier: String(describing: name)) as? T else {
fatalError("Couldn't find UITableViewCell for \(String(describing: name)), make sure the cell is registered with table view")
}
return cell
}
/// SwifterSwift: Dequeue reusable UITableViewCell using class name for indexPath
///
/// - Parameters:
/// - name: UITableViewCell type.
/// - indexPath: location of cell in tableView.
/// - Returns: UITableViewCell object with associated class name.
/// 获取 UITableViewCell
///
/// - Parameters:
/// - name: 继承UITableViewCell类Class
/// - indexPath: indexPath
/// - Returns: Cell
func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type, for indexPath: IndexPath) -> T {
guard let cell = dequeueReusableCell(withIdentifier: String(describing: name), for: indexPath) as? T else {
fatalError("Couldn't find UITableViewCell for \(String(describing: name)), make sure the cell is registered with table view")
}
return cell
}
/// 获取 UITableViewSection头部和尾部
///
/// - Parameter name: 继承UITableViewHeaderFooterView类Class
/// - Returns: UITableViewSection头部和尾部
func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>(withClass name: T.Type) -> T {
guard let headerFooterView = dequeueReusableHeaderFooterView(withIdentifier: String(describing: name)) as? T else {
fatalError("Couldn't find UITableViewHeaderFooterView for \(String(describing: name)), make sure the view is registered with table view")
}
return headerFooterView
}
/// 获取 Nib UITableViewSection头部和尾部
///
/// - Parameters:
/// - nib: nib
/// - name: UITableViewSection头部和尾部
func register<T: UITableViewHeaderFooterView>(nib: UINib?, withHeaderFooterViewClass name: T.Type) {
register(nib, forHeaderFooterViewReuseIdentifier: String(describing: name))
}
/// 注册 UITableViewSection头部和尾部
///
/// - Parameter name: UITableViewSection头部和尾部
func register<T: UITableViewHeaderFooterView>(headerFooterViewClassWith name: T.Type) {
register(T.self, forHeaderFooterViewReuseIdentifier: String(describing: name))
}
/// 注册 UITableViewCell
///
/// - Parameter name: Cell
func register<T: UITableViewCell>(cellWithClass name: T.Type) {
register(T.self, forCellReuseIdentifier: String(describing: name))
}
/// 注册 Nib UITableViewCell
///
/// - Parameters:
/// - nib: nib
/// - name: Cell
func register<T: UITableViewCell>(nib: UINib?, withCellClass name: T.Type) {
register(nib, forCellReuseIdentifier: String(describing: name))
}
/// SwifterSwift: Register UITableViewCell with .xib file using only its corresponding class.
/// Assumes that the .xib filename and cell class has the same name.
///
/// - Parameters:
/// - name: UITableViewCell type.
/// - bundleClass: Class in which the Bundle instance will be based on.
/// 注册 Nib UITableViewCell
///
/// - Parameters:
/// - name: 继承UITableViewCell类Class
/// - bundleClass: bundleClass
func register<T: UITableViewCell>(nibWithCellClass name: T.Type, at bundleClass: AnyClass? = nil) {
let identifier = String(describing: name)
var bundle: Bundle?
if let bundleName = bundleClass {
bundle = Bundle(for: bundleName)
}
register(UINib(nibName: identifier, bundle: bundle), forCellReuseIdentifier: identifier)
}
/// Check whether IndexPath is valid within the tableView
///
/// - Parameter indexPath: An IndexPath to check
/// - Returns: Boolean value for valid or invalid IndexPath
func isValidIndexPath(_ indexPath: IndexPath) -> Bool {
return indexPath.section < numberOfSections && indexPath.row < numberOfRows(inSection: indexPath.section)
}
/// Safely scroll to possibly invalid IndexPath
///
/// - Parameters:
/// - indexPath: Target IndexPath to scroll to
/// - scrollPosition: Scroll position
/// - animated: Whether to animate or not
func safeScrollToRow(at indexPath: IndexPath, at scrollPosition: UITableView.ScrollPosition, animated: Bool) {
guard indexPath.section < numberOfSections else { return }
guard indexPath.row < numberOfRows(inSection: indexPath.section) else { return }
scrollToRow(at: indexPath, at: scrollPosition, animated: animated)
}
}
| mit | 56c7de5d09dad9861ae7c0b6a52adc04 | 33.965174 | 149 | 0.638019 | 4.991477 | false | false | false | false |
hetefe/HTF_sina_swift | sina_htf/sina_htf/Classes/Tools/NetworkTools.swift | 1 | 3496 | //
// NetworkTools.swift
// sina_htf
//
// Created by 赫腾飞 on 15/12/21.
// Copyright © 2015年 hetefe. All rights reserved.
//
import AFNetworking
let dataErrorDomain = "com.baidu.data.error"
enum HTTPMethod: String {
case GET = "GET"
case POST = "POST"
}
class NetworkTools: AFHTTPSessionManager {
//网络请求的处理层 以后的网络请求都是用此类进行数据的获取
//声明单例对象
static let sharedTools: NetworkTools = {
//设置base URL
let urlString = "https://api.weibo.com/"
let url = NSURL(string: urlString)
let tools = NetworkTools(baseURL: url)
tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
return tools
}()
//网络请求的核心方法封装
func requestJSONDict(method: HTTPMethod , urlString:String, parameters:[String: String]?, finished: (dict: [String: AnyObject]?, error: NSError?) ->() ) {
if method == HTTPMethod.POST{
//发送POST请求
POST(urlString, parameters: parameters, progress: { (p) -> Void in
print(p)
}, success: { (_, result) -> Void in
// print(result)
guard let dict = result as? [String: AnyObject] else {
//不能够转换为字典
//执行失败的回调
//domain 反转的域名 com.baidu.error
//code : 错误状态码 自己定义的错误信息 一般使用负数
let myError = NSError(domain: dataErrorDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey:"数据不合法"])
print(myError)
finished(dict: nil, error: myError)
return
}
//执行成功的回调
finished(dict: dict, error: nil)
}) { (_, error) -> Void in
//请求失败的回调 请求失败的回调
finished(dict: nil, error: error)
print(error)
}
}else{
GET(urlString, parameters: parameters, progress: { (p) -> Void in
print(p)
}, success: { (_, result) -> Void in
// print(result)
guard let dict = result as? [String: AnyObject] else {
//不能够转换为字典
//执行失败的回调
//domain 反转的域名 com.baidu.error
//code : 错误状态码 自己定义的错误信息 一般使用负数
let myError = NSError(domain: dataErrorDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey:"数据不合法"])
print(myError)
finished(dict: nil, error: myError)
return
}
//执行成功的回调
finished(dict: dict, error: nil)
}) { (_, error) -> Void in
print(error)
}
}
}
}
| mit | 4c37f573b1d0228b4d337682bd2f57cf | 30.158416 | 158 | 0.435971 | 4.971564 | false | false | false | false |
wenghengcong/Coderpursue | BeeFun/BeeFun/SystemManager/Storage/BFDocument.swift | 1 | 740 | //
// BFDocument.swift
// BeeFun
//
// Created by WengHengcong on 2017/12/5.
// Copyright © 2017年 JungleSong. All rights reserved.
//
import UIKit
class BFDocument: UIDocument {
var data: NSData?
override func load(fromContents contents: Any, ofType typeName: String?) throws {
// Load your document from contents
if let validData: NSData = contents as? NSData {
self.data = validData.copy() as? NSData
}
}
override func contents(forType typeName: String) throws -> Any {
// Encode your document with an instance of NSData or NSFileWrapper
if self.data == nil {
self.data = NSData()
}
return self.data ?? NSData()
}
}
| mit | 3b1ebcf5ea294ff40670d49249eb675b | 23.566667 | 85 | 0.61194 | 4.360947 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Features/DebugPushNotifications/Controller/DebugPushNotificationsViewController.swift | 1 | 8884 | import Library
import Prelude
import UIKit
import UserNotifications
internal final class DebugPushNotificationsViewController: UIViewController {
@IBOutlet fileprivate var rootStackView: UIStackView!
@IBOutlet fileprivate var scrollView: UIScrollView!
@IBOutlet fileprivate var separatorViews: [UIView]!
override func viewDidLoad() {
super.viewDidLoad()
_ = self
|> \.title .~ "Push notifications"
}
internal override func bindStyles() {
super.bindStyles()
_ = self
|> baseControllerStyle()
let rowsStackViews = self.rootStackView.arrangedSubviews.compactMap { $0 as? UIStackView }
let rowStackViews = rowsStackViews.flatMap { rows in
rows.arrangedSubviews.compactMap { $0 as? UIStackView }
}
let buttonStackViews = rowStackViews.compactMap { $0.arrangedSubviews.last as? UIStackView }
let titleLabels = self.rootStackView.arrangedSubviews.compactMap { $0 as? UILabel }
let buttons = buttonStackViews
.flatMap { stackView in stackView.arrangedSubviews.compactMap { $0 as? UIButton } }
let inAppButtons = buttons.enumerated().filter { idx, _ in idx % 2 == 0 }.map(second)
let delayedButtons = buttons.enumerated().filter { idx, _ in idx % 2 == 1 }.map(second)
_ = self.rootStackView
|> UIStackView.lens.spacing .~ Styles.grid(3)
_ = self.scrollView
|> UIScrollView.lens.delaysContentTouches .~ false
_ = rowsStackViews
||> UIStackView.lens.spacing .~ Styles.grid(2)
_ = rowStackViews
||> UIStackView.lens.distribution .~ .equalSpacing
||> UIStackView.lens.alignment .~ .center
_ = buttonStackViews
||> UIStackView.lens.spacing .~ Styles.grid(1)
_ = titleLabels
||> UILabel.lens.textColor .~ .ksr_support_400
||> UILabel.lens.font .~ .ksr_title1(size: 22)
_ = rowStackViews.compactMap { $0.arrangedSubviews.first as? UILabel }
||> UILabel.lens.textColor .~ .ksr_support_700
||> UILabel.lens.font .~ .ksr_body()
_ = buttons
||> greenButtonStyle
||> UIButton.lens.contentEdgeInsets %~ {
.init(top: $0.top / 2, left: $0.left / 2, bottom: $0.bottom / 2, right: $0.right / 2)
}
inAppButtons.enumerated().forEach { idx, button in
_ = button
|> UIButton.lens.tag .~ idx
|> UIButton.lens.title(for: .normal) .~ "In-app"
|> UIButton.lens.targets .~ [(self, #selector(inAppButtonTapped(_:)), .touchUpInside)]
}
delayedButtons.enumerated().forEach { idx, button in
_ = button
|> UIButton.lens.tag .~ idx
|> UIButton.lens.title(for: .normal) .~ "Delayed"
|> UIButton.lens.targets .~ [(self, #selector(delayedButtonTapped(_:)), .touchUpInside)]
}
_ = self.separatorViews
||> separatorStyle
}
@objc fileprivate func inAppButtonTapped(_ button: UIButton) {
self.scheduleNotification(forIndex: button.tag, delay: false)
}
@objc fileprivate func delayedButtonTapped(_ button: UIButton) {
self.scheduleNotification(forIndex: button.tag, delay: true)
}
fileprivate func scheduleNotification(forIndex index: Int, delay: Bool) {
guard index >= 0, index < allPushData.count else { return }
let pushData = allPushData[index]
self.addNotificationRequest(delay: delay, pushData: pushData)
}
private func addNotificationRequest(delay: Bool, pushData: [String: Any]) {
let identifier = "notify-test"
let content = UNMutableNotificationContent()
content.body = self.body(from: pushData)
content.userInfo = pushData
content.categoryIdentifier = identifier
// timeInterval must be greater than 0.
let trigger = UNTimeIntervalNotificationTrigger(
timeInterval: delay ? 5 : 0.5,
repeats: false
)
let request = UNNotificationRequest(
identifier: identifier,
content: content,
trigger: trigger
)
UNUserNotificationCenter.current().add(request)
}
private func body(from pushData: [String: Any]) -> String {
return (pushData["aps"] as? [String: AnyObject])?["alert"] as? String ?? ""
}
}
private let backingPushData: [String: Any] = [
"aps": [
"alert": "Blob McBlobby backed Double Fine Adventure."
],
"activity": [
"category": "backing",
"id": 1,
"project_id": 1_929_840_910
]
]
private let updatePushData: [String: Any] = [
"aps": [
"alert": "Update #6 posted by Double Fine Adventure."
],
"activity": [
"category": "update",
"id": 1,
"project_id": 1_929_840_910,
"update_id": 190_349
]
]
private let successPushData: [String: Any] = [
"aps": [
"alert": "Double Fine Adventure has been successfully funded!"
],
"activity": [
"category": "success",
"id": 1,
"project_id": 1_929_840_910
]
]
private let failurePushData: [String: Any] = [
"aps": [
"alert": "Double Fine Adventure was not successfully funded."
],
"activity": [
"category": "failure",
"id": 1,
"project_id": 1_929_840_910
]
]
private let cancellationPushData: [String: Any] = [
"aps": [
"alert": "Double Fine Adventure has been canceled."
],
"activity": [
"category": "cancellation",
"id": 1,
"project_id": 1_929_840_910
]
]
private let followPushData: [String: Any] = [
"aps": [
"alert": "Blob McBlobby is following you on Kickstarter!"
],
"activity": [
"category": "follow",
"id": 1
]
]
private let messagePushData: [String: Any] = [
"aps": [
"alert": "Chinati Foundation sent you a message about Robert Irwin Project."
],
"message": [
"message_thread_id": 17_848_074,
"project_id": 820_501_933
]
]
private let surveyPushData: [String: Any] = [
"aps": [
"alert": "Response needed! Get your reward for backing Help Me Transform This Pile of Wood."
],
"survey": [
"id": 15_182_605,
"project_id": 820_501_933
]
]
private let reminderPushData: [String: Any] = [
"aps": [
"alert": "Reminder! This Pile of Wood is ending soon."
],
"project": [
"photo": "https://ksr-ugc.imgix.net/assets/012/224/660/847bc4da31e6863e9351bee4e55b8005_original.jpg?w=160&h=90&fit=fill&bg=FBFAF8&v=1464773625&auto=format&q=92&s=fc738d87d861a96333e9f93bee680c27",
"id": 820_501_933
]
]
private let backingForCreatorPushData: [String: Any] = [
"aps": [
"alert": "New backer! Blob has pledged $50 to Help Me Transform This Pile Of Wood."
],
"activity": [
"category": "backing",
"id": 1,
"project_id": 820_501_933
],
"for_creator": true
]
private let messageForCreatorPushData: [String: Any] = [
"aps": [
"alert": "Blob McBlobby sent you a message about Help Me Transform This Pile Of Wood."
],
"message": [
"message_thread_id": 17_848_074,
"project_id": 820_501_933
],
"for_creator": true
]
private let failureForCreatorPushData: [String: Any] = [
"aps": [
"alert": "Help Me Transform This Pile Of Wood was not successfully funded."
],
"activity": [
"category": "failure",
"id": 1,
"project_id": 820_501_933
],
"for_creator": true
]
private let successForCreatorPushData: [String: Any] = [
"aps": [
"alert": "Help Me Transform This Pile Of Wood has been successfully funded!"
],
"activity": [
"category": "success",
"id": 1,
"project_id": 820_501_933
],
"for_creator": true
]
private let cancellationForCreatorPushData: [String: Any] = [
"aps": [
"alert": "Help Me Transform This Pile Of Wood has been canceled."
],
"activity": [
"category": "cancellation",
"id": 1,
"project_id": 820_501_933
],
"for_creator": true
]
private let projectCommentForCreatorPushData: [String: Any] = [
"aps": [
"alert": "New comment! Blob has commented on Help Me Transform This Pile Of Wood."
],
"activity": [
"category": "comment-project",
"id": 1,
"project_id": 820_501_933
],
"for_creator": true
]
private let updateCommentForCreatorPushData: [String: Any] = [
"aps": [
"alert": "New comment! Blob has commented on update #11."
],
"activity": [
"category": "comment-post",
"id": 1,
"project_id": 820_501_933,
"update_id": 1_731_094
],
"for_creator": true
]
private let postLikeForCreatorPushData: [String: Any] = [
"aps": [
"alert": "Blob liked your update: Important message from Tim..."
],
"post": [
"id": 175_622,
"project_id": 1_929_840_910
],
"for_creator": true
]
private let allPushData: [[String: Any]] = [
backingPushData,
updatePushData,
successPushData,
failurePushData,
cancellationPushData,
followPushData,
messagePushData,
surveyPushData,
reminderPushData,
backingForCreatorPushData,
messageForCreatorPushData,
failureForCreatorPushData,
successForCreatorPushData,
cancellationForCreatorPushData,
projectCommentForCreatorPushData,
updateCommentForCreatorPushData,
postLikeForCreatorPushData
]
| apache-2.0 | 5684089a41825a58edee8ab040aef150 | 25.519403 | 201 | 0.645543 | 3.583703 | false | false | false | false |
dvor/Antidote | Antidote/QRScannerController.swift | 1 | 5261 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import UIKit
import AVFoundation
class QRScannerController: UIViewController {
var didScanStringsBlock: (([String]) -> Void)?
var cancelBlock: ((Void) -> Void)?
fileprivate let theme: Theme
fileprivate var previewLayer: AVCaptureVideoPreviewLayer!
fileprivate var captureSession: AVCaptureSession!
fileprivate var aimView: QRScannerAimView!
var pauseScanning: Bool = false {
didSet {
pauseScanning ? captureSession.stopRunning() : captureSession.startRunning()
if !pauseScanning {
aimView.frame = CGRect.zero
}
}
}
init(theme: Theme) {
self.theme = theme
super.init(nibName: nil, bundle: nil)
createCaptureSession()
createBarButtonItems()
NotificationCenter.default.addObserver(
self,
selector: #selector(QRScannerController.applicationDidEnterBackground),
name: NSNotification.Name.UIApplicationDidEnterBackground,
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(QRScannerController.applicationWillEnterForeground),
name: NSNotification.Name.UIApplicationWillEnterForeground,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
required convenience init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
loadViewWithBackgroundColor(theme.colorForType(.NormalBackground))
createViewsAndLayers()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
captureSession.startRunning()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
captureSession.stopRunning()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
previewLayer.frame = view.bounds
}
}
// MARK: Actions
extension QRScannerController {
func cancelButtonPressed() {
cancelBlock?()
}
}
// MARK: Notifications
extension QRScannerController {
func applicationDidEnterBackground() {
captureSession.stopRunning()
}
func applicationWillEnterForeground() {
if !pauseScanning {
captureSession.startRunning()
}
}
}
extension QRScannerController: AVCaptureMetadataOutputObjectsDelegate {
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
let readableObjects = metadataObjects.filter {
$0 is AVMetadataMachineReadableCodeObject
}.map {
previewLayer.transformedMetadataObject(for: $0 as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject
}
guard !readableObjects.isEmpty else {
return
}
aimView.frame = readableObjects[0].bounds
let strings = readableObjects.map {
$0.stringValue!
}
didScanStringsBlock?(strings)
}
}
private extension QRScannerController {
func createCaptureSession() {
captureSession = AVCaptureSession()
let input = captureSessionInput()
let output = AVCaptureMetadataOutput()
if (input != nil) && captureSession.canAddInput(input) {
captureSession.addInput(input)
}
if captureSession.canAddOutput(output) {
captureSession.addOutput(output)
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
if output.availableMetadataObjectTypes.contains(where: { $0 as! String == AVMetadataObjectTypeQRCode }) {
output.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
}
}
}
func captureSessionInput() -> AVCaptureDeviceInput? {
guard let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) else {
return nil
}
if device.isAutoFocusRangeRestrictionSupported {
do {
try device.lockForConfiguration()
device.autoFocusRangeRestriction = .near
device.unlockForConfiguration()
}
catch {
// nop
}
}
return try? AVCaptureDeviceInput(device: device)
}
func createBarButtonItems() {
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(QRScannerController.cancelButtonPressed))
}
func createViewsAndLayers() {
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
view.layer.addSublayer(previewLayer)
aimView = QRScannerAimView(theme: theme)
view.addSubview(aimView)
view.bringSubview(toFront: aimView)
}
}
| mit | 227bb630be258db25c8b66316f13c2e8 | 28.391061 | 162 | 0.654248 | 5.832594 | false | false | false | false |
wireapp/wire-ios-data-model | Source/Model/Message/ConversationMessage.swift | 1 | 11581 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// 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 3 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, see http://www.gnu.org/licenses/.
//
import Foundation
import WireLinkPreview
private var zmLog = ZMSLog(tag: "Message")
@objc
public enum ZMDeliveryState: UInt {
case invalid = 0
case pending = 1
case sent = 2
case delivered = 3
case read = 4
case failedToSend = 5
}
@objc
public protocol ReadReceipt {
@available(*, deprecated, message: "Use `userType` instead")
var user: ZMUser { get }
var userType: UserType { get }
var serverTimestamp: Date? { get }
}
@objc
public protocol ZMConversationMessage: NSObjectProtocol {
/// Unique identifier for the message
var nonce: UUID? { get }
/// The user who sent the message (internal)
@available(*, deprecated, message: "Use `senderUser` instead")
var sender: ZMUser? { get }
/// The user who sent the message
var senderUser: UserType? { get }
/// The timestamp as received by the server
var serverTimestamp: Date? { get }
@available(*, deprecated, message: "Use `conversationLike` instead")
var conversation: ZMConversation? { get }
/// The conversation this message belongs to
var conversationLike: ConversationLike? { get }
/// The current delivery state of this message. It makes sense only for
/// messages sent from this device. In any other case, it will be
/// ZMDeliveryStateDelivered
var deliveryState: ZMDeliveryState { get }
/// True if the message has been successfully sent to the server
var isSent: Bool { get }
/// List of recipients who have read the message.
var readReceipts: [ReadReceipt] { get }
/// Whether the message expects read confirmations.
var needsReadConfirmation: Bool { get }
/// The textMessageData of the message which also contains potential link previews. If the message has no text, it will be nil
var textMessageData: ZMTextMessageData? { get }
/// The image data associated with the message. If the message has no image, it will be nil
var imageMessageData: ZMImageMessageData? { get }
/// The system message data associated with the message. If the message is not a system message data associated, it will be nil
var systemMessageData: ZMSystemMessageData? { get }
/// The knock message data associated with the message. If the message is not a knock, it will be nil
var knockMessageData: ZMKnockMessageData? { get }
/// The file transfer data associated with the message. If the message is not the file transfer, it will be nil
var fileMessageData: ZMFileMessageData? { get }
/// The location message data associated with the message. If the message is not a location message, it will be nil
var locationMessageData: LocationMessageData? { get }
var usersReaction: [String: [UserType]] { get }
/// In case this message failed to deliver, this will resend it
func resend()
/// tell whether or not the message can be deleted
var canBeDeleted: Bool { get }
/// True if the message has been deleted
var hasBeenDeleted: Bool { get }
var updatedAt: Date? { get }
/// Starts the "self destruction" timer if all conditions are met
/// It checks internally if the message is ephemeral, if sender is the other user and if there is already an existing timer
/// Returns YES if a timer was started by the message call
func startSelfDestructionIfNeeded() -> Bool
/// Returns true if the message is ephemeral
var isEphemeral: Bool { get }
/// If the message is ephemeral, it returns a fixed timeout
/// Otherwise it returns -1
/// Override this method in subclasses if needed
var deletionTimeout: TimeInterval { get }
/// Returns true if the message is an ephemeral message that was sent by the selfUser and the obfuscation timer already fired
/// At this point the genericMessage content is already cleared. You should receive a notification that the content was cleared
var isObfuscated: Bool { get }
/// Returns the date when a ephemeral message will be destructed or `nil` if th message is not ephemeral
var destructionDate: Date? { get }
/// Returns whether this is a message that caused the security level of the conversation to degrade in this session (since the
/// app was restarted)
var causedSecurityLevelDegradation: Bool { get }
/// Marks the message as the last unread message in the conversation, moving the unread mark exactly before this
/// message.
func markAsUnread()
/// Checks if the message can be marked unread
var canBeMarkedUnread: Bool { get }
/// The replies quoting this message.
var replies: Set<ZMMessage> { get }
/// An in-memory identifier for tracking the message during its life cycle.
var objectIdentifier: String { get }
/// The links attached to the message.
var linkAttachments: [LinkAttachment]? { get set }
/// Used to trigger link attachments update for this message.
var needsLinkAttachmentsUpdate: Bool { get set }
var isSilenced: Bool { get }
/// Whether the asset message can not be received or shared.
var isRestricted: Bool { get }
}
public protocol ConversationCompositeMessage {
/// The composite message associated with the message. If the message is not a composite message, it will be nil
var compositeMessageData: CompositeMessageData? { get }
}
public extension ZMConversationMessage {
/// Whether the given user is the sender of the message.
func isUserSender(_ user: UserType) -> Bool {
guard let zmUser = user as? ZMUser else { return false }
return zmUser == senderUser as? ZMUser
}
}
public extension Equatable where Self: ZMConversationMessage { }
public func == (lhs: ZMConversationMessage, rhs: ZMConversationMessage) -> Bool {
return lhs.isEqual(rhs)
}
public func == (lhs: ZMConversationMessage?, rhs: ZMConversationMessage?) -> Bool {
switch (lhs, rhs) {
case (nil, nil):
return true
case (_, nil):
return false
case (nil, _):
return false
case (_, _):
return lhs!.isEqual(rhs!)
}
}
// MARK: - Conversation managed properties
extension ZMMessage {
@NSManaged public var visibleInConversation: ZMConversation?
@NSManaged public var hiddenInConversation: ZMConversation?
public var conversation: ZMConversation? {
return self.visibleInConversation ?? self.hiddenInConversation
}
}
// MARK: - Conversation Message protocol implementation
extension ZMMessage: ZMConversationMessage {
public var conversationLike: ConversationLike? {
return conversation
}
public var senderUser: UserType? {
return sender
}
@NSManaged public var linkAttachments: [LinkAttachment]?
@NSManaged public var needsLinkAttachmentsUpdate: Bool
@NSManaged public var replies: Set<ZMMessage>
public var readReceipts: [ReadReceipt] {
return confirmations.filter({ $0.type == .read }).sorted(by: { a, b in a.serverTimestamp < b.serverTimestamp })
}
public var objectIdentifier: String {
return nonpersistedObjectIdentifer
}
public var causedSecurityLevelDegradation: Bool {
return false
}
public var canBeMarkedUnread: Bool {
guard self.isNormal,
self.serverTimestamp != nil,
self.conversation != nil,
let sender = self.sender,
!sender.isSelfUser else {
return false
}
return true
}
public func markAsUnread() {
guard canBeMarkedUnread,
let serverTimestamp = self.serverTimestamp,
let conversation = self.conversation,
let managedObjectContext = self.managedObjectContext,
let syncContext = managedObjectContext.zm_sync else {
zmLog.error("Cannot mark as unread message outside of the conversation.")
return
}
let conversationID = conversation.objectID
conversation.lastReadServerTimeStamp = Date(timeInterval: -0.01, since: serverTimestamp)
managedObjectContext.saveOrRollback()
syncContext.performGroupedBlock {
guard let syncObject = try? syncContext.existingObject(with: conversationID), let syncConversation = syncObject as? ZMConversation else {
zmLog.error("Cannot mark as unread message outside of the conversation: sync conversation cannot be fetched.")
return
}
syncConversation.calculateLastUnreadMessages()
syncContext.saveOrRollback()
}
}
public var isSilenced: Bool {
return conversation?.isMessageSilenced(nil, senderID: sender?.remoteIdentifier) ?? true
}
public var isRestricted: Bool {
guard
(self.isFile || self.isImage),
let managedObjectContext = self.managedObjectContext
else { return false }
let featureService = FeatureService(context: managedObjectContext)
let fileSharingFeature = featureService.fetchFileSharing()
return fileSharingFeature.status == .disabled
}
}
extension ZMMessage {
@NSManaged public var sender: ZMUser?
@NSManaged public var serverTimestamp: Date?
@objc public var textMessageData: ZMTextMessageData? {
return nil
}
@objc public var imageMessageData: ZMImageMessageData? {
return nil
}
@objc public var knockMessageData: ZMKnockMessageData? {
return nil
}
@objc public var systemMessageData: ZMSystemMessageData? {
return nil
}
@objc public var fileMessageData: ZMFileMessageData? {
return nil
}
@objc public var locationMessageData: LocationMessageData? {
return nil
}
@objc public var isSent: Bool {
return true
}
@objc public var deliveryState: ZMDeliveryState {
return .delivered
}
@objc public var usersReaction: [String: [UserType]] {
var result = [String: [ZMUser]]()
for reaction in reactions where reaction.users.count > 0 {
result[reaction.unicodeValue!] = [ZMUser](reaction.users)
}
return result
}
@objc public var canBeDeleted: Bool {
return deliveryState != .pending
}
@objc public var hasBeenDeleted: Bool {
return isZombieObject || (visibleInConversation == nil && hiddenInConversation != nil)
}
@objc public var updatedAt: Date? {
return nil
}
@objc public func startSelfDestructionIfNeeded() -> Bool {
if !isZombieObject && isEphemeral, let sender = sender, !sender.isSelfUser {
return startDestructionIfNeeded()
}
return false
}
@objc public var isEphemeral: Bool {
return false
}
@objc public var deletionTimeout: TimeInterval {
return -1
}
}
| gpl-3.0 | dacf0509d5d7c297ffb956c0bd1682ea | 31.169444 | 149 | 0.677921 | 4.882378 | false | false | false | false |
Sadmansamee/quran-ios | Quran/JuzsMultipleSectionDataSource.swift | 1 | 1782 | //
// JuzsMultipleSectionDataSource.swift
// Quran
//
// Created by Mohamed Afifi on 4/29/16.
// Copyright © 2016 Quran.com. All rights reserved.
//
import Foundation
import GenericDataSources
class JuzsMultipleSectionDataSource: CompositeDataSource {
let numberFormatter = NumberFormatter()
let headerReuseIdentifier: String
var juzs: [Juz] = []
var onJuzHeaderSelected: ((Juz) -> Void)? = nil
init(type: SectionType, headerReuseIdentifier: String) {
self.headerReuseIdentifier = headerReuseIdentifier
super.init(sectionType: type)
}
func setSections<ItemType, CellType: ReusableCell>(_ sections: [(Juz, [ItemType])],
dataSourceCreator: () -> BasicDataSource<ItemType, CellType>) {
for dataSource in dataSources {
removeDataSource(dataSource)
}
for section in sections {
let ds = dataSourceCreator()
ds.items = section.1
addDataSource(ds)
}
juzs = sections.map { $0.0 }
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header: JuzTableViewHeaderFooterView = cast(tableView.dequeueReusableHeaderFooterView(withIdentifier: headerReuseIdentifier))
let juz = juzs[section]
header.titleLabel.text = String(format: NSLocalizedString("juz2_description", tableName: "Android", comment: ""), juz.juzNumber)
header.subtitleLabel.text = numberFormatter.string(from: NSNumber(value: juz.startPageNumber))
header.object = juz
header.onTapped = { [weak self] in
guard let object = header.object as? Juz else { return }
self?.onJuzHeaderSelected?(object)
}
return header
}
}
| mit | bda018243d98e38cdf21e070b45131ed | 29.706897 | 137 | 0.658619 | 4.638021 | false | false | false | false |
yourtion/RestfulClient | RestClient/ResultViewController.swift | 1 | 1520 | //
// ResultViewController.swift
// RestClient
//
// Created by YourtionGuo on 7/22/14.
// Copyright (c) 2014 yourtion. All rights reserved.
//
import UIKit
class ResultViewController: UIViewController {
@IBOutlet weak var resultText: UITextView!
var requestParams = Array<Array<String>>()
var requestUrl = String()
var requestMethod = String()
var paramDic = [String:String]()
var data: NSMutableData = NSMutableData()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Result"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func startRequest() {
let url = NSURL(string: requestUrl)
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "GET"
let queue = NSOperationQueue()
let completion = { (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
if ((error) != nil) {
print(error)
return
}
var respon: AnyObject!
if ((data) != nil) {
respon = NSString(data: data!, encoding: UInt())
}
dispatch_async(dispatch_get_main_queue(), {
self.resultText.text = respon as! String
})
}
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler: completion)
}
}
| mit | 632ffe3e5aa4f1760efc92ca72e5138f | 28.230769 | 101 | 0.592763 | 4.919094 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGPU/CoreImage/SVGComponentTransferKernel.swift | 1 | 13200 | //
// SVGComponentTransferKernel.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. 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.
//
#if canImport(CoreImage)
extension CIImage {
private class SVGComponentTransferKernel: CIImageProcessorKernel {
enum TransferFunctionType: String, CaseIterable {
case identity
case table
case discrete
case gamma
}
static let function_constants: [String: MTLFunctionConstantValues] = {
var function_constants: [String: MTLFunctionConstantValues] = [:]
for alpha in TransferFunctionType.allCases {
for blue in TransferFunctionType.allCases {
for green in TransferFunctionType.allCases {
for red in TransferFunctionType.allCases {
let constants = MTLFunctionConstantValues()
withUnsafeBytes(of: red == .table || red == .discrete) { constants.setConstantValue($0.baseAddress!, type: .bool, withName: "has_red_channel_table") }
withUnsafeBytes(of: red == .discrete) { constants.setConstantValue($0.baseAddress!, type: .bool, withName: "is_red_channel_discrete") }
withUnsafeBytes(of: red == .gamma) { constants.setConstantValue($0.baseAddress!, type: .bool, withName: "has_red_channel_gamma") }
withUnsafeBytes(of: green == .table || green == .discrete) { constants.setConstantValue($0.baseAddress!, type: .bool, withName: "has_green_channel_table") }
withUnsafeBytes(of: green == .discrete) { constants.setConstantValue($0.baseAddress!, type: .bool, withName: "is_green_channel_discrete") }
withUnsafeBytes(of: green == .gamma) { constants.setConstantValue($0.baseAddress!, type: .bool, withName: "has_green_channel_gamma") }
withUnsafeBytes(of: blue == .table || blue == .discrete) { constants.setConstantValue($0.baseAddress!, type: .bool, withName: "has_blue_channel_table") }
withUnsafeBytes(of: blue == .discrete) { constants.setConstantValue($0.baseAddress!, type: .bool, withName: "is_blue_channel_discrete") }
withUnsafeBytes(of: blue == .gamma) { constants.setConstantValue($0.baseAddress!, type: .bool, withName: "has_blue_channel_gamma") }
withUnsafeBytes(of: alpha == .table || alpha == .discrete) { constants.setConstantValue($0.baseAddress!, type: .bool, withName: "has_alpha_channel_table") }
withUnsafeBytes(of: alpha == .discrete) { constants.setConstantValue($0.baseAddress!, type: .bool, withName: "is_alpha_channel_discrete") }
withUnsafeBytes(of: alpha == .gamma) { constants.setConstantValue($0.baseAddress!, type: .bool, withName: "has_alpha_channel_gamma") }
function_constants["_\(red.rawValue)_\(green.rawValue)_\(blue.rawValue)_\(alpha.rawValue)"] = constants
}
}
}
}
return function_constants
}()
override class var synchronizeInputs: Bool {
return false
}
override class func process(with inputs: [CIImageProcessorInput]?, arguments: [String: Any]?, output: CIImageProcessorOutput) throws {
guard let commandBuffer = output.metalCommandBuffer else { return }
guard let source = inputs?[0].metalTexture else { return }
guard let output_texture = output.metalTexture else { return }
guard let red = arguments?["red"] as? SVGComponentTransferEffect.TransferFunction else { return }
guard let green = arguments?["green"] as? SVGComponentTransferEffect.TransferFunction else { return }
guard let blue = arguments?["blue"] as? SVGComponentTransferEffect.TransferFunction else { return }
guard let alpha = arguments?["alpha"] as? SVGComponentTransferEffect.TransferFunction else { return }
let _red: String
switch red {
case .identity: _red = "_identity"
case .table: _red = "_table"
case .discrete: _red = "_discrete"
case .gamma: _red = "_gamma"
}
let _green: String
switch green {
case .identity: _green = "_identity"
case .table: _green = "_table"
case .discrete: _green = "_discrete"
case .gamma: _green = "_gamma"
}
let _blue: String
switch blue {
case .identity: _blue = "_identity"
case .table: _blue = "_table"
case .discrete: _blue = "_discrete"
case .gamma: _blue = "_gamma"
}
let _alpha: String
switch alpha {
case .identity: _alpha = "_identity"
case .table: _alpha = "_table"
case .discrete: _alpha = "_discrete"
case .gamma: _alpha = "_gamma"
}
guard let function_constant = function_constants["\(_red)\(_green)\(_blue)\(_alpha)"] else { return }
guard let pipeline = self.make_pipeline(commandBuffer.device, "svg_component_transfer", function_constant) else { return }
guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }
encoder.setComputePipelineState(pipeline)
encoder.setTexture(source, index: 0)
encoder.setTexture(output_texture , index: 1)
switch red {
case .identity: break
case let .table(table):
withUnsafeBytes(of: Int32(table.count)) { encoder.setBytes($0.baseAddress!, length: $0.count, index: 2) }
table.map { Float($0) }.withUnsafeBytes { encoder.setBytes($0.baseAddress!, length: $0.count, index: 6) }
case let .discrete(table):
withUnsafeBytes(of: Int32(table.count)) { encoder.setBytes($0.baseAddress!, length: $0.count, index: 2) }
table.map { Float($0) }.withUnsafeBytes { encoder.setBytes($0.baseAddress!, length: $0.count, index: 6) }
case let .gamma(amplitude, exponent, offset):
withUnsafeBytes(of: (Float(amplitude), Float(exponent), Float(offset))) { encoder.setBytes($0.baseAddress!, length: $0.count, index: 2) }
}
switch green {
case .identity: break
case let .table(table):
withUnsafeBytes(of: Int32(table.count)) { encoder.setBytes($0.baseAddress!, length: $0.count, index: 3) }
table.map { Float($0) }.withUnsafeBytes { encoder.setBytes($0.baseAddress!, length: $0.count, index: 7) }
case let .discrete(table):
withUnsafeBytes(of: Int32(table.count)) { encoder.setBytes($0.baseAddress!, length: $0.count, index: 3) }
table.map { Float($0) }.withUnsafeBytes { encoder.setBytes($0.baseAddress!, length: $0.count, index: 7) }
case let .gamma(amplitude, exponent, offset):
withUnsafeBytes(of: (Float(amplitude), Float(exponent), Float(offset))) { encoder.setBytes($0.baseAddress!, length: $0.count, index: 3) }
}
switch blue {
case .identity: break
case let .table(table):
withUnsafeBytes(of: Int32(table.count)) { encoder.setBytes($0.baseAddress!, length: $0.count, index: 4) }
table.map { Float($0) }.withUnsafeBytes { encoder.setBytes($0.baseAddress!, length: $0.count, index: 8) }
case let .discrete(table):
withUnsafeBytes(of: Int32(table.count)) { encoder.setBytes($0.baseAddress!, length: $0.count, index: 4) }
table.map { Float($0) }.withUnsafeBytes { encoder.setBytes($0.baseAddress!, length: $0.count, index: 8) }
case let .gamma(amplitude, exponent, offset):
withUnsafeBytes(of: (Float(amplitude), Float(exponent), Float(offset))) { encoder.setBytes($0.baseAddress!, length: $0.count, index: 4) }
}
switch alpha {
case .identity: break
case let .table(table):
withUnsafeBytes(of: Int32(table.count)) { encoder.setBytes($0.baseAddress!, length: $0.count, index: 5) }
table.map { Float($0) }.withUnsafeBytes { encoder.setBytes($0.baseAddress!, length: $0.count, index: 9) }
case let .discrete(table):
withUnsafeBytes(of: Int32(table.count)) { encoder.setBytes($0.baseAddress!, length: $0.count, index: 5) }
table.map { Float($0) }.withUnsafeBytes { encoder.setBytes($0.baseAddress!, length: $0.count, index: 9) }
case let .gamma(amplitude, exponent, offset):
withUnsafeBytes(of: (Float(amplitude), Float(exponent), Float(offset))) { encoder.setBytes($0.baseAddress!, length: $0.count, index: 5) }
}
let group_width = max(1, pipeline.threadExecutionWidth)
let group_height = max(1, pipeline.maxTotalThreadsPerThreadgroup / group_width)
let threadsPerThreadgroup = MTLSize(width: group_width, height: group_height, depth: 1)
let threadgroupsPerGrid = MTLSize(width: (output_texture.width + group_width - 1) / group_width, height: (output_texture.height + group_height - 1) / group_height, depth: 1)
encoder.dispatchThreadgroups(threadgroupsPerGrid, threadsPerThreadgroup: threadsPerThreadgroup)
encoder.endEncoding()
}
}
public func componentTransfer(red: SVGComponentTransferEffect.TransferFunction,
green: SVGComponentTransferEffect.TransferFunction,
blue: SVGComponentTransferEffect.TransferFunction,
alpha: SVGComponentTransferEffect.TransferFunction) -> CIImage {
if extent.isEmpty { return .empty() }
if red == .identity && green == .identity && blue == .identity && alpha == .identity {
return self
}
switch red {
case let .table(table): guard !table.isEmpty else { return .empty() }
case let .discrete(table): guard !table.isEmpty else { return .empty() }
default: break
}
switch green {
case let .table(table): guard !table.isEmpty else { return .empty() }
case let .discrete(table): guard !table.isEmpty else { return .empty() }
default: break
}
switch blue {
case let .table(table): guard !table.isEmpty else { return .empty() }
case let .discrete(table): guard !table.isEmpty else { return .empty() }
default: break
}
switch alpha {
case let .table(table): guard !table.isEmpty else { return .empty() }
case let .discrete(table): guard !table.isEmpty else { return .empty() }
default: break
}
let _extent = extent.isInfinite ? extent : extent.insetBy(dx: .random(in: -1..<0), dy: .random(in: -1..<0))
var rendered = try? SVGComponentTransferKernel.apply(withExtent: _extent, inputs: [self.unpremultiplyingAlpha()], arguments: ["red": red, "green": green, "blue": blue, "alpha": alpha]).premultiplyingAlpha()
if !extent.isInfinite {
rendered = rendered?.cropped(to: extent)
}
return rendered ?? .empty()
}
}
#endif
| mit | ec4fa40afbe7783041d507544a6511b8 | 53.771784 | 214 | 0.578333 | 4.71597 | false | false | false | false |
andreamazz/AMScrollingNavbar | Demo/Pods/AMScrollingNavbar/Source/ScrollingNavbar+Sizes.swift | 2 | 2090 | import UIKit
import WebKit
/**
Implements the main functions providing constants values and computed ones
*/
extension ScrollingNavigationController {
// MARK: - View sizing
var fullNavbarHeight: CGFloat {
return navbarHeight + statusBarHeight
}
var navbarHeight: CGFloat {
return navigationBar.frame.size.height
}
var statusBarHeight: CGFloat {
var statusBarHeight = UIApplication.shared.statusBarFrame.size.height
if #available(iOS 11.0, *) {
// Account for the notch when the status bar is hidden
statusBarHeight = max(UIApplication.shared.statusBarFrame.size.height, UIApplication.shared.delegate?.window??.safeAreaInsets.top ?? 0)
}
return statusBarHeight - extendedStatusBarDifference
}
// Extended status call changes the bounds of the presented view
var extendedStatusBarDifference: CGFloat {
return abs(view.bounds.height - (UIApplication.shared.delegate?.window??.frame.size.height ?? UIScreen.main.bounds.height))
}
var tabBarOffset: CGFloat {
// Only account for the tab bar if a tab bar controller is present and the bar is not translucent
if let tabBarController = tabBarController {
return tabBarController.tabBar.isTranslucent ? 0 : tabBarController.tabBar.frame.height
}
return 0
}
func scrollView() -> UIScrollView? {
if let webView = self.scrollableView as? UIWebView {
return webView.scrollView
} else if let wkWebView = self.scrollableView as? WKWebView {
return wkWebView.scrollView
} else {
return scrollableView as? UIScrollView
}
}
var contentOffset: CGPoint {
return scrollView()?.contentOffset ?? CGPoint.zero
}
var contentSize: CGSize {
guard let scrollView = scrollView() else {
return CGSize.zero
}
let verticalInset = scrollView.contentInset.top + scrollView.contentInset.bottom
return CGSize(width: scrollView.contentSize.width, height: scrollView.contentSize.height + verticalInset)
}
var deltaLimit: CGFloat {
return navbarHeight - statusBarHeight
}
}
| mit | abd80a782d2575cd6227b68ba8388431 | 30.19403 | 141 | 0.720096 | 4.97619 | false | false | false | false |
Karumi/Alamofire-Result | Tests/ResultTests.swift | 1 | 5081 | // ResultTests.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.
@testable import Alamofire
import Foundation
import XCTest
import Result
class ResultTestCase: BaseTestCase {
let error = Error.errorWithCode(.StatusCodeValidationFailed, failureReason: "Status code validation failed")
// MARK: - Is Success Tests
func testThatIsSuccessPropertyReturnsTrueForSuccessCase() {
// Given, When
let result = Result<String, NSError>.Success("success")
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true for success case")
}
func testThatIsSuccessPropertyReturnsFalseForFailureCase() {
// Given, When
let result = Result<String, NSError>.Failure(error)
// Then
XCTAssertFalse(result.isSuccess, "result is success should be true for failure case")
}
// MARK: - Is Failure Tests
func testThatIsFailurePropertyReturnsFalseForSuccessCase() {
// Given, When
let result = Result<String, NSError>.Success("success")
// Then
XCTAssertFalse(result.isFailure, "result is failure should be false for success case")
}
func testThatIsFailurePropertyReturnsTrueForFailureCase() {
// Given, When
let result = Result<String, NSError>.Failure(error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true for failure case")
}
// MARK: - Value Tests
func testThatValuePropertyReturnsValueForSuccessCase() {
// Given, When
let result = Result<String, NSError>.Success("success")
// Then
XCTAssertEqual(result.value ?? "", "success", "result value should match expected value")
}
func testThatValuePropertyReturnsNilForFailureCase() {
// Given, When
let result = Result<String, NSError>.Failure(error)
// Then
XCTAssertNil(result.value, "result value should be nil for failure case")
}
// MARK: - Error Tests
func testThatErrorPropertyReturnsNilForSuccessCase() {
// Given, When
let result = Result<String, NSError>.Success("success")
// Then
XCTAssertTrue(result.error == nil, "result error should be nil for success case")
}
func testThatErrorPropertyReturnsErrorForFailureCase() {
// Given, When
let result = Result<String, NSError>.Failure(error)
// Then
XCTAssertTrue(result.error != nil, "result error should not be nil for failure case")
}
// MARK: - Description Tests
func testThatDescriptionStringMatchesExpectedValueForSuccessCase() {
// Given, When
let result = Result<String, NSError>.Success("success")
// Then
XCTAssertEqual(result.description, "SUCCESS", "result description should match expected value for success case")
}
func testThatDescriptionStringMatchesExpectedValueForFailureCase() {
// Given, When
let result = Result<String, NSError>.Failure(error)
// Then
XCTAssertEqual(result.description, "FAILURE", "result description should match expected value for failure case")
}
// MARK: - Debug Description Tests
func testThatDebugDescriptionStringMatchesExpectedValueForSuccessCase() {
// Given, When
let result = Result<String, NSError>.Success("success value")
// Then
XCTAssertEqual(
result.debugDescription,
"SUCCESS: success value",
"result debug description should match expected value for success case"
)
}
func testThatDebugDescriptionStringMatchesExpectedValueForFailureCase() {
// Given, When
let result = Result<String, NSError>.Failure(error)
// Then
XCTAssertEqual(
result.debugDescription,
"FAILURE: \(error)",
"result debug description should match expected value for failure case"
)
}
}
| mit | 94a6e5e54104d465db1d3df4afbbce63 | 33.787671 | 120 | 0.683796 | 5.043694 | false | true | false | false |
faisalmemon/swift | projectEuler.playground/section-1.swift | 1 | 3997 | // Faisal Memon
// Project Euler problems
// The purpose of this program is to practice using the swift language
// We aim for program clarity and high performance.
/** Return the sum of all multiples less that the supplied limit.
This algorithm uses an arithmetic progression algorithm.
N*(N+1)/2 = 1 + 2 + 3 + ... + N (arithmetic progression)
therefore
m * N*(N+1)/2 = m + 2m + 3m + ... + mN
Given some "limit" and some multiple "m",
(limit - 1) / m gives the upper value we should count to
assuming integer (rounding down) division
Combining these two ideas is the algorithm we use.
@param limit The limit we are count up to, but less than
@param multiple The multiple we are summing up
*/
func sumOfMultiples(limit:Int, multiple:Int) ->Int
{
let arithmetic_N:Int = (limit - 1)/multiple
let result = multiple * arithmetic_N * (arithmetic_N + 1) / 2
return result
}
func eulerProblem_01()
{
println("Problem 1\n\nIf we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.\n")
// We count multiples for 3 and 5, but exclude 3*5 multiples as they are already counted
// in the multiples of 3
let result =
sumOfMultiples(1000, 3) +
sumOfMultiples(1000, 5) -
sumOfMultiples(1000, 15)
println("The answer is \(result).\n")
}
eulerProblem_01()
/** Calculate the next even fibonacci number within a limit.
Methodology:
1) Fibonacci numbers are either odd (o) or even (e) as follows:
o, e, o, o, e, o, o, e, o, o, e, ... because of the arithmetic
rule:
Odd + Odd = Even
Even + Even = Even
Odd + Even = Odd
2) By do two rounds of fibonacci, we can get from one "e" to the
next "e". We don't need to bother checking its even.
3) To avoid re-computing past results, we ask for the past
running total to be supplied, and the past pair of fibonacci
numbers before doing our two rounds of fibonacci
4) We assume the passed in pair of fibonacci numbers don't exceed
are supplied limit, and on the next even fibonacci we can just test
for exceeding the limit there only.
5) Fibonacci numbers grow very fast (nearly doubling each time). Since
the next even is found after two iterations, it means we have exponential
growth for the next fibonacci number. For limit L, we'll find the sum
after O(log(L)) time.
@param runningTotal Total of even fibonacci numbers seen so far
@param upperLimit Limit number not to exceed the next even fibonacci
@param n0 First of an adjacent pair of fibonacci numbers with
n0 < upperLimit
@param n1 Next fibonacci number after n1 with n1 < upperLimit
@returns (updatedTotal,n3,n4) where updatedTotal is the supplied runningTotal
plus the next even fibonacci number not exceeding the supplied
upperLimit, n3 and n4 are the next pair of fibonacci numbers to be
supplied for the next call to this method
*/
func sumNextEvenFibonacci(runningTotal:Int, upperLimit:Int, n0:Int, n1:Int) -> (Int, Int, Int)
{
let n2 = n0 + n1
let n3 = n2 + n1
let n4 = n3 + n2
if (n4 < upperLimit)
{
return (runningTotal + n4, n3, n4)
}
else
{
return (runningTotal, n3, n4)
}
}
func eulerProblem_02()
{
println("Problem 2\n\nEach new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:\n 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... \n\nBy considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.\n")
var n0 = 1, n1 = 2, n2 = 0, runningTotal = 2
do
{
(runningTotal, n0, n1) = sumNextEvenFibonacci(runningTotal, 4_000_000, n0, n1)
} while (n1 < 4_000_000)
println("The answer is \(runningTotal).\n")
}
eulerProblem_02()
| mit | bc0fceafd5eb28e35aaa07986d057554 | 33.756522 | 346 | 0.677008 | 3.59766 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKit/categories/NSNumber+Formatter.swift | 1 | 2290 | //
// NSNumber+Formatter.swift
// TripKit
//
// Created by Adrian Schönig on 10.04.20.
// Copyright © 2020 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
extension NSNumber {
private static let formatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.locale = .autoupdatingCurrent
formatter.maximumSignificantDigits = 2
formatter.usesSignificantDigits = true
formatter.roundingMode = .up
return formatter
}()
public func toMoneyString(currencyCode: String, decimalPlaces: Int = 0) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencyCode = currencyCode
formatter.currencySymbol = nil
formatter.zeroSymbol = NSLocalizedString("Free", tableName: "Shared", bundle: .tripKit, comment: "Free as in beer")
if decimalPlaces == 0 {
formatter.roundingIncrement = NSNumber(value: 1)
}
formatter.maximumFractionDigits = decimalPlaces
formatter.minimumFractionDigits = decimalPlaces
formatter.usesGroupingSeparator = true
return formatter.string(from: self)!
}
public func toCarbonString() -> String {
guard floatValue > 0 else {
// Should really be as below, but it breaks Xcode export
// See https://developer.apple.com/forums/thread/696752?login=true
//
// Should be: "No\u{00a0}CO₂" (i.e., non-breaking unicode)
return NSLocalizedString("No CO₂", tableName: "Shared", bundle: .tripKit, comment: "Indicator for no carbon emissions. Note the space is non-breaking white space!")
}
let formatter = Self.formatter
formatter.numberStyle = .decimal
formatter.currencyCode = nil
formatter.currencySymbol = nil
formatter.roundingIncrement = NSNumber(value: 0.1)
formatter.zeroSymbol = nil
// Should be "%@kg\u{00a0}CO₂" (i.e., non-breaking unicode)
return NSString(format: "%@kg CO₂", formatter.string(from: self)!) as String
}
func toScoreString() -> String {
let formatter = Self.formatter
formatter.numberStyle = .currency
formatter.currencyCode = nil
formatter.currencySymbol = "❦"
formatter.roundingIncrement = NSNumber(value: 0.1)
formatter.zeroSymbol = nil
return formatter.string(from: self)!
}
}
| apache-2.0 | 9e06d5e44cbde01d145a1428c32877d1 | 33.515152 | 170 | 0.700176 | 4.40619 | false | false | false | false |
noppoMan/Prorsum | Sources/Prorsum/WebSocket/EventEmitter.swift | 1 | 1691 | //The MIT License (MIT)
//
//Copyright (c) 2015 Zewo
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
public final class EventEmitter<T> {
fileprivate var listeners: [EventListener<T>] = []
public init() {}
public func addListener(_ times: Int = -1, listen: @escaping EventListener<T>.Listen) -> EventListener<T> {
let listener = EventListener<T>(calls: times, listen: listen)
listeners.append(listener)
return listener
}
public func emit(_ event: T) throws {
listeners = listeners.filter({ $0.active })
for listener in listeners {
let _ = try listener.call(event)
}
}
}
| mit | ebf6f5a4edd7407a2455057b01ca4c32 | 40.243902 | 111 | 0.709639 | 4.461741 | false | false | false | false |
alexanderedge/European-Sports | EurosportPlayerTV/Controllers/CatchupsCollectionViewController.swift | 1 | 3368 | //
// CatchupsCollectionViewController.swift
// EurosportPlayer
//
// Created by Alexander Edge on 25/05/2016.
import UIKit
import CoreData
import EurosportKit
import AVKit
private let reuseIdentifier = "Cell"
class CatchupsCollectionViewController: FetchedResultsCollectionViewController, FetchedResultsControllerBackedType {
typealias FetchedType = Catchup
var sport: Sport!
var fetchRequest: NSFetchRequest<FetchedType> {
let predicate = NSPredicate(format: "sport == %@ AND expirationDate > %@", sport, Date() as NSDate)
let fetchRequest = Catchup.fetchRequest(predicate, sortedBy: "startDate", ascending: false)
return fetchRequest
}
lazy var fetchedResultsController: NSFetchedResultsController<FetchedType> = {
let frc = NSFetchedResultsController(fetchRequest: self.fetchRequest, managedObjectContext: self.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil)
frc.delegate = self
do {
try frc.performFetch()
} catch {
fatalError("unable to perform fetch: \(error)")
}
return frc
}()
override func viewDidLoad() {
super.viewDidLoad()
title = sport.name
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
guard let sections = fetchedResultsController.sections else {
return 0
}
return sections.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let sections = fetchedResultsController.sections, sections.count > section else {
return 0
}
return sections[section].numberOfObjects
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as DoubleLabelCollectionViewCell
let catchup = objectAt(indexPath)
cell.titleLabel.text = catchup.title
cell.detailLabel.text = "\(catchup.catchupDescription) (\(DateComponentsFormatter().string(from: catchup.duration)!))"
cell.imageView.setImage(catchup.imageURL, placeholder: UIImage(named: "catchup_placeholder"), darken: true)
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let catchup = objectAt(indexPath)
print("selected catchup \(catchup.identifier)")
if let stream = catchup.streams.firstObject as? CatchupStream {
guard let user = User.currentUser(persistentContainer.viewContext) else {
return
}
stream.generateAuthenticatedURL(user) { result in
switch result {
case .success(let url):
self.showVideoForURL(url)
break
case .failure(let error):
self.showAlert(NSLocalizedString("catchup-failed", comment: "error starting catcup"), error: error as NSError)
print("error generating authenticated URL: \(error)")
break
}
}
}
}
}
| mit | 94ee00506bb0edac699c1a98af8074ed | 33.367347 | 178 | 0.664192 | 5.539474 | false | false | false | false |
RevenueCat/purchases-ios | Tests/APITesters/SwiftAPITester/SwiftAPITester/PackageAPI.swift | 1 | 1067 | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// PackageAPI.swift
//
// Created by Madeline Beyl on 8/26/21.
import Foundation
import RevenueCat
import StoreKit
var pack: Package!
func checkPackageAPI() {
let ident: String = pack.identifier
let pType: PackageType = pack.packageType
let prod: StoreProduct = pack.storeProduct
let lps: String = pack.localizedPriceString
let lips: String? = pack.localizedIntroductoryPriceString
print(pack!, ident, pType, prod, lps, lips!)
}
var packageType: PackageType!
func checkPackageEnums() {
switch packageType! {
case .custom,
.lifetime,
.annual,
.sixMonth,
.threeMonth,
.twoMonth,
.monthly,
.weekly,
.unknown:
print(packageType!)
@unknown default:
fatalError()
}
}
| mit | 5565cd9a037545148c16ceef6ca0582a | 22.711111 | 68 | 0.650422 | 3.851986 | false | false | false | false |
sajeel/AutoScout | AutoScout/Models & View Models/CarInfo.swift | 1 | 1941 | //
// CarInfos.swift
// AutoScout
//
// Created by Sajjeel Khilji on 5/20/17.
// Copyright © 2017 Saj. All rights reserved.
//
import Foundation
import RealmSwift
public class CarInfo: Object // , CarInfoViewModelData
{
dynamic var price = 0
dynamic var milage = 0
dynamic var make = ""
dynamic var fuelType = ""
dynamic var imageUrl = ""
dynamic var carID = 0
dynamic var firstRegistration = ""
dynamic var accidentFree = true
dynamic var isFav = false
convenience init(id: Int, make: String, milage: Int, price:Int, fuelType: String, imageUrl: String, firsRegistration:String, accidentFree: Bool, isFav: Bool) {
self.init()
self.carID = id
self.make = make
self.milage = milage
self.price = price
self.imageUrl = imageUrl
self.firstRegistration = firsRegistration
self.accidentFree = accidentFree
self.fuelType = fuelType
self.isFav = isFav
//super.init();
}
override public static func primaryKey() -> String {
return "carID"
}
// dynamic var price: UInt = 0
// dynamic var milage: UInt = 0
// dynamic var make: String?
// dynamic var fuelType: String?
//
// dynamic var imageUrl: String?
//
// dynamic var carID: UInt = 0
// dynamic var firstRegistration: String?
// dynamic var accidentFree: Bool
//
//
//
// convenience init(id: UInt, make: String, milage: UInt, price:UInt, fuelType: String, imageUrl: String, firsRegistration:String, accidentFree: Bool) {
// self.init()
// self.carID = id
// self.make = make
// self.milage = milage
// self.price = price
// self.imageUrl = imageUrl
// self.firstRegistration = firsRegistration
// self.accidentFree = accidentFree
// //super.init();
//
// }
}
| gpl-3.0 | 7d6f7d813bf7ddd4c5fe82caeaba5dfc | 24.194805 | 163 | 0.59433 | 3.872255 | false | false | false | false |
AlesTsurko/DNMKit | DNMModel/IntervalRelationship.swift | 1 | 916 | //
// IntervalRelationship.swift
// DNMModel
//
// Created by James Bean on 11/27/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import Foundation
// Implementation of Allen's interval algebra calculus
public struct IntervalRelationship: OptionSetType {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
public static var Equal = IntervalRelationship(rawValue: 1)
public static var TakesPlaceBefore = IntervalRelationship(rawValue: 2)
public static var TakesPlaceAfter = IntervalRelationship(rawValue: 4)
public static var Meets = IntervalRelationship(rawValue: 8)
public static var Overlaps = IntervalRelationship(rawValue: 16)
public static var During = IntervalRelationship(rawValue: 32)
public static var Starts = IntervalRelationship(rawValue: 64)
public static var Finishes = IntervalRelationship(rawValue: 128)
} | gpl-2.0 | bf1f0b55393940e6ec669246ef174de1 | 35.64 | 74 | 0.755191 | 4.59799 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/Cocoa/Components/UIImage/ImageFetcher/RemoteImageFetcher.swift | 1 | 1614 | //
// Xcore
// Copyright © 2018 Xcore
// MIT license, see LICENSE file for details
//
import UIKit
final class RemoteImageFetcher: ImageFetcher {
func canHandle(_ image: ImageRepresentable) -> Bool {
image.imageSource.isRemoteUrl
}
/// Loads remote image either via from cache or web.
///
/// - Parameters:
/// - image: The image requested to be fetched.
/// - imageView: An optional property if this image will be set on the image
/// view.
/// - callback: A closure with the `UIImage` object and cache type if image
/// successfully fetched; otherwise, `nil`.
func fetch(
_ image: ImageRepresentable,
in imageView: UIImageView?,
_ callback: @escaping ResultBlock
) {
guard
case let .url(value) = image.imageSource,
let url = URL(string: value),
url.host != nil
else {
callback(.failure(ImageFetcherError.notFound))
return
}
let cancelToken = ImageDownloader.load(url: url) { image, _, error, finished, cacheType in
guard finished else {
return
}
guard let image = image else {
callback(.failure(error ?? ImageFetcherError.notFound))
return
}
callback(.success((image, cacheType)))
}
// Store the token cancel block so the request can be cancelled if needed.
imageView?._imageFetcherCancelBlock = cancelToken
}
func removeCache() {
ImageDownloader.removeCache()
}
}
| mit | a650d726cd85d9515f2340605629b21c | 27.803571 | 98 | 0.580285 | 4.887879 | false | false | false | false |
chrisjmendez/swift-exercises | Concurrency/Operational Queues/Concurrency/ViewController.swift | 1 | 5645 | //
// ViewController.swift
// Concurrency
//
// Created by tommy trojan on 4/11/15.
// Copyright (c) 2015 Skyground Media Inc. All rights reserved.
//
import UIKit
typealias KVOContext = UInt8
class ViewController: UIViewController {
@IBOutlet weak var currentBuyerLabel: UILabel!
@IBOutlet weak var nextBuyerLabel: UILabel!
@IBOutlet weak var userBoughtTapeRoll: UITextView!
@IBOutlet weak var userPaidTapeRoll: UITextView!
@IBOutlet weak var onAlphaSlider: UISlider!
@IBOutlet weak var buyBtn: UIButton!
@IBOutlet weak var cancelBtn: UIButton!
@IBOutlet weak var resetBtn: UIButton!
@IBAction func onAlphaChanged(sender: AnyObject) {
}
@IBAction func onBuyClicked(sender: AnyObject) {
buyNow()
}
@IBAction func onCancelClicked(sender: AnyObject) {
operationQueue.cancelAllOperations()
}
@IBAction func onResetClicked(sender: AnyObject) {
currentIdx = 0
}
let customers:Array<String> = ["A", "B", "C", "D", "E", "F", "G"]
var currentIdx:Int = 0
var operationQueue:NSOperationQueue = NSOperationQueue()
override func viewDidLoad() {
super.viewDidLoad()
clearLabels()
buyNow()
}
/** ** ** ** ** ** ** ** ** ** ** ** ** **
UI Methods
** ** ** ** ** ** ** ** ** ** ** ** ** **/
func buyNow(){
updateLabels( "currentBuyerLabel", message: "\(customers[currentIdx])")
var remainingCustomers:Int = (customers.count - 1) - currentIdx
updateLabels( "nextBuyerLabel", message: "\(remainingCustomers)" )
if(currentIdx < customers.count - 1){
currentIdx++
} else {
currentIdx = 0
}
buyAndPay()
}
func buyAndPay(){
//Switch to new customer
let customerName:String = customers[currentIdx]
//1. Create an Operation from NSOperation
var buyTicket:NSBlockOperation = NSBlockOperation.init(block: {
//Run simulator to resemble an HTTP request
let num:Double = Simulator.sharedInstance.runSimulatorWithMinTime(2, maxTime: 5)
//You cannot update the UIX from a background thread so you call this data back up the main UIX.
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//Update the text label with the new async data
self.updateLabels("currentBuyerLabel", message: self.customers[self.currentIdx])
self.updateLabels("userBoughtTapeRoll", message: "\(customerName) bought tickets in \(num).")
var nextIdx:Int = self.currentIdx + 1
self.updateLabels( "nextBuyerLabel", message: self.customers[nextIdx])
})
})
//2. Trigger a completion event
buyTicket.completionBlock = {
print("nsBlockOperation.completionBlock completed for \(customerName)")
}
var payTicket:NSBlockOperation = NSBlockOperation.init(block: {
//Run simulator to resemble an HTTP request
let num:Double = Simulator.sharedInstance.runSimulatorWithMinTime(2, maxTime: 5)
//You cannot update the UIX from a background thread so you call this data back up the main UIX.
dispatch_async(dispatch_get_main_queue(), { () -> Void in
print("payTicket in \(num) time")
self.updateLabels( "userPaidTapeRoll", message: "\(customerName) paid in \(num) time")
})
})
payTicket.addDependency( buyTicket )
var MyObservationContext = KVOContext()
let options = NSKeyValueObservingOptions.New //NSKeyValueObservingOptions.Old
payTicket.addObserver(self,
forKeyPath: "isCancelled",
options: options,
context: &MyObservationContext )
//3. Add the operations to a queue
operationQueue.addOperation( buyTicket )
operationQueue.addOperation( payTicket )
}
func clearLabels(){
updateLabels( "currentBuyerLabel", message: "")
updateLabels( "nextBuyerLabel", message: "")
updateLabels( "userBoughtTapeRoll", message: "")
updateLabels( "userPaidTapeRoll", message: "")
}
//Serial task
func buyTicket(){
//Increment the index
currentIdx++
if(currentIdx == customers.count ){
//Turn off the BUY button
buyBtn.enabled = false
clearLabels()
updateLabels( "currentBuyerLabel", message: "No more customers.")
}else{
}
}
func updateLabels(label:String, message:String){
switch(label){
case "currentBuyerLabel":
currentBuyerLabel.text = message
break
case "nextBuyerLabel":
nextBuyerLabel.text = message
break
case "userBoughtTapeRoll":
var oldMessage:String = userBoughtTapeRoll.text
var newMessage:String = "\(message) \n"
userBoughtTapeRoll.text = oldMessage + newMessage
break
case "userPaidTapeRoll":
var oldMessage:String = userPaidTapeRoll.text
var newMessage:String = "\(message) \n"
userPaidTapeRoll.text = oldMessage + newMessage
default :
break
}
}
}
| mit | 9007b1fdb8a305ba5e6e474eb6ceb3d7 | 31.257143 | 109 | 0.573251 | 4.820666 | false | false | false | false |
skeeet/HackerNews | HackerNews/Model/HTMLParser/HTMLNode.swift | 5 | 9300 | /**@file
* @brief Swift-HTML-Parser
* @author _tid_
*/
import Foundation
/**
* HTMLNode
*/
public class HTMLNode {
public enum HTMLNodeType : String {
case HTMLUnkownNode = ""
case HTMLHrefNode = "href"
case HTMLTextNode = "text"
case HTMLCodeNode = "code"
case HTMLSpanNode = "span"
case HTMLPNode = "p"
case HTMLLiNode = "li"
case HTMLUiNode = "ui"
case HTMLImageNode = "image"
case HTMLOlNode = "ol"
case HTMLStrongNode = "strong"
case HTMLPreNode = "pre"
case HTMLBlockQuoteNode = "blockquote"
}
private var doc : htmlDocPtr
private var node : xmlNode?
private var pointer : xmlNodePtr
private let nodeType : HTMLNodeType
/**
* 親ノード
*/
private var parent : HTMLNode? {
if let p = self.node?.parent {
return HTMLNode(doc: self.doc, node: p)
}
return nil
}
/**
* 次ノード
*/
public var next : HTMLNode? {
if let n : UnsafeMutablePointer<xmlNode> = node?.next {
if n != nil {
return HTMLNode(doc: doc, node: n)
}
}
return nil
}
/**
* 子ノード
*/
public var child : HTMLNode? {
if let c = node?.children {
if c != nil {
return HTMLNode(doc: doc, node: c)
}
}
return nil
}
/**
* クラス名
*/
public var className : String {
return getAttributeNamed("class")
}
/**
* タグ名
*/
public var tagName : String {
return HTMLNode.GetTagName(self.node)
}
private static func GetTagName(node: xmlNode?) -> String {
if let n = node {
return ConvXmlCharToString(n.name)
}
return ""
}
/**
* コンテンツ
*/
public var contents : String {
if node != nil {
var n = self.node!.children
if n != nil {
return ConvXmlCharToString(n.memory.content)
}
}
return ""
}
public var recursiveContent : String {
if node != nil {
return ConvXmlCharToString(xmlNodeGetContent(pointer))
}
return ""
}
public var rawContents : String {
if node != nil {
return rawContentsOfNode(self.node!, self.pointer)
}
return ""
}
/**
* Initializer
* @param[in] doc xmlDoc
*/
public init(doc: htmlDocPtr = nil) {
self.doc = doc
var node = xmlDocGetRootElement(doc)
self.pointer = node
self.nodeType = .HTMLUnkownNode
if node != nil {
self.node = node.memory
}
}
private init(doc: htmlDocPtr, node: UnsafePointer<xmlNode>) {
self.doc = doc
self.node = node.memory
self.pointer = xmlNodePtr(node)
if let type = HTMLNodeType(rawValue: HTMLNode.GetTagName(self.node)) {
self.nodeType = type
} else {
self.nodeType = .HTMLUnkownNode
}
}
/**
* 属性名を取得する
* @param[in] name 属性
* @return 属性名
*/
public func getAttributeNamed(name: String) -> String {
for var attr : xmlAttrPtr = node!.properties; attr != nil; attr = attr.memory.next {
var mem = attr.memory
if name == ConvXmlCharToString(mem.name) {
return ConvXmlCharToString(mem.children.memory.content)
}
}
return ""
}
/**
* タグ名に一致する全ての子ノードを探す
* @param[in] tagName タグ名
* @return 子ノードの配列
*/
public func findChildTags(tagName: String) -> [HTMLNode] {
var nodes : [HTMLNode] = []
return findChildTags(tagName, node: self.child, retAry: &nodes)
}
private func findChildTags(tagName: String, node: HTMLNode?, inout retAry: [HTMLNode] ) -> [HTMLNode] {
if let n = node {
for curNode in n {
if curNode.tagName == tagName {
retAry.append(curNode)
}
findChildTags(tagName, node: curNode.child, retAry: &retAry)
}
}
return retAry
}
/**
* タグ名で子ノードを探す
* @param[in] tagName タグ名
* @return 子ノード。見つからなければnil
*/
public func findChildTag(tagName: String) -> HTMLNode? {
return findChildTag(tagName, node: self)
}
private func findChildTag(tagName: String, node: HTMLNode?) -> HTMLNode? {
if let nd = node {
for curNode in nd {
if tagName == curNode.tagName {
return curNode
}
if let c = curNode.child {
if let n = findChildTag(tagName, node: c) {
return n
}
}
}
}
return nil
}
//------------------------------------------------------
public func findChildTagsAttr(tagName: String, attrName : String, attrValue : String) -> [HTMLNode] {
var nodes : [HTMLNode] = []
return findChildTagsAttr(tagName, attrName : attrName, attrValue : attrValue, node: self.child, retAry: &nodes)
}
private func findChildTagsAttr(tagName: String, attrName : String, attrValue : String, node: HTMLNode?, inout retAry: [HTMLNode] ) -> [HTMLNode] {
if let n = node {
for curNode in n {
if curNode.tagName == tagName && curNode.getAttributeNamed(attrName) == attrValue {
retAry.append(curNode)
}
findChildTagsAttr(tagName, attrName : attrName, attrValue : attrValue, node: curNode.child, retAry: &retAry)
}
}
return retAry
}
public func findChildTagAttr(tagName : String, attrName : String, attrValue : String) -> HTMLNode?
{
return findChildTagAttr(tagName, attrName : attrName, attrValue : attrValue, node: self)
}
private func findChildTagAttr(tagName : String, attrName : String, attrValue : String, node: HTMLNode?) -> HTMLNode?
{
if let nd = node {
for curNode in nd {
if tagName == curNode.tagName && curNode.getAttributeNamed(attrName) == attrValue {
return curNode
}
if let c = curNode.child {
if let n = findChildTagAttr(tagName,attrName: attrName,attrValue: attrValue, node: c) {
return n
}
}
}
}
return nil
}
/**
* Find node by id (id has to be used properly it is a uniq attribute)
* @param[in] id String
* @return HTMLNode
*/
public func findNodeById(id: String) -> HTMLNode? {
return findNodeById(id, node: self)
}
private func findNodeById(id: String, node: HTMLNode?) -> HTMLNode? {
if let nd = node {
for curNode in nd {
if id == curNode.getAttributeNamed("id") {
return curNode
}
if let c = curNode.child {
if let n = findNodeById(id, node: c) {
return n
}
}
}
}
return nil
}
/**
* xpathで子ノードを探す
* @param[in] xpath xpath
* @return 子ノード。見つからなければnil
*/
public func xpath(xpath: String) -> [HTMLNode]? {
let ctxt = xmlXPathNewContext(self.doc)
if ctxt == nil {
return nil
}
xmlXPathSetContextNode(pointer, ctxt)
let result = xmlXPathEvalExpression(xpath, ctxt)
xmlXPathFreeContext(ctxt)
if result == nil {
return nil
}
let nodeSet = result.memory.nodesetval
if nodeSet == nil || nodeSet.memory.nodeNr == 0 || nodeSet.memory.nodeTab == nil {
return nil
}
var nodes : [HTMLNode] = []
let size = Int(nodeSet.memory.nodeNr)
for var i = 0; i < size; ++i {
let n = nodeSet.memory
let node = nodeSet.memory.nodeTab[i]
let htmlNode = HTMLNode(doc: self.doc, node: node)
nodes.append(htmlNode)
}
return nodes
}
}
extension HTMLNode : SequenceType {
public func generate() -> HTMLNodeGenerator {
return HTMLNodeGenerator(node: self)
}
}
/**
* HTMLNodeGenerator
*/
public class HTMLNodeGenerator : GeneratorType {
private var node : HTMLNode?
public init(node: HTMLNode?) {
self.node = node
}
public func next() -> HTMLNode? {
var temp = node
node = node?.next
return temp
}
}
| mit | 280a4cd2ceed09158d6e731eb4435d1e | 26.005952 | 150 | 0.499118 | 4.587462 | false | false | false | false |
cabarique/TheProposalGame | MyProposalGame/Scenes/GameBuildMode.swift | 1 | 15343 | /*
* Copyright (c) 2015 Neil North.
*
* 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 SpriteKit
import GameplayKit
enum toolSelection {
case toolMove
case toolAdd
case toolRemove
}
class GameBuildMode: SGScene {
//Layers
var worldLayer:TileLayer!
var overlayLayer = SKNode()
//Tiles
let tileImages = [
"0","1","2","3","4","5","6","7","8","9",
"10","11","12","13","14","15","16","17","18"
]
let tileObjects = [
"B3","Sign_1","Sign_2",
"Crate","Mushroom_1","Mushroom_2", "diamondBlue", "Coin", "Zombie1", "Zombie2", "Mage1", "Mage2", "Boss", "Princess"
]
//Tools
var currentTool = toolSelection.toolMove
var tilePanel: builderPanel?
override func didMoveToView(view: SKView) {
GameSettings.Builder.ALL_Black_Background = true
//Setup camera
let myCamera = SKCameraNode()
camera = myCamera
addChild(myCamera)
//Setup Layers
switch GameSettings.Builder.BUILDER_LEVEL {
case 0:
worldLayer = TileLayer1(levelIndex: GameSettings.Builder.BUILDER_LEVEL, typeIndex: .setBuilder)
tilePanel = builderPanel(objectImages: tileObjects, objectTexture: "TileObjects", tileImages: tileImages, imagetexture: "Tiles")
case 1:
worldLayer = TileLayer2(levelIndex: GameSettings.Builder.BUILDER_LEVEL, typeIndex: .setBuilder)
tilePanel = builderPanel(objectImages: tileObjects, objectTexture: "TileObjects", tileImages: tileImages, imagetexture: "Tiles2")
case 2:
worldLayer = TileLayer3(levelIndex: GameSettings.Builder.BUILDER_LEVEL, typeIndex: .setBuilder)
tilePanel = builderPanel(objectImages: tileObjects, objectTexture: "TileObjects", tileImages: tileImages, imagetexture: "Tiles3")
case 3:
worldLayer = TileLayer4(levelIndex: GameSettings.Builder.BUILDER_LEVEL, typeIndex: .setBuilder)
tilePanel = builderPanel(objectImages: tileObjects, objectTexture: "TileObjects", tileImages: tileImages, imagetexture: "Tiles4")
default:
worldLayer = TileLayer1(levelIndex: 0, typeIndex: .setBuilder)
tilePanel = builderPanel(objectImages: tileObjects, objectTexture: "TileObjects", tileImages: tileImages, imagetexture: "Tiles")
}
addChild(worldLayer)
myCamera.addChild(overlayLayer)
updateTileMap()
//UI Elements
let modeButton = SKLabelNode(fontNamed: "MarkerFelt-Wide")
modeButton.posByScreen(-0.4, y: 0.4)
modeButton.fontSize = 40
modeButton.text = lt("Move")
modeButton.fontColor = SKColor.whiteColor()
modeButton.zPosition = 150
modeButton.name = "modeSelect"
overlayLayer.addChild(modeButton)
let zoButton = SKLabelNode(fontNamed: "MarkerFelt-Wide")
zoButton.posByScreen(-0.4, y: -0.45)
zoButton.fontSize = 30
zoButton.text = lt("Zoom Out")
zoButton.fontColor = SKColor.whiteColor()
zoButton.zPosition = 150
zoButton.name = "zoomOut"
overlayLayer.addChild(zoButton)
let ziButton = SKLabelNode(fontNamed: "MarkerFelt-Wide")
ziButton.posByScreen(-0.2, y: -0.45)
ziButton.fontSize = 30
ziButton.text = lt("Zoom In")
ziButton.fontColor = SKColor.whiteColor()
ziButton.zPosition = 150
ziButton.name = "zoomIn"
overlayLayer.addChild(ziButton)
let upButton = SKLabelNode(fontNamed: "MarkerFelt-Wide")
upButton.posByScreen(0.35, y: 0.45)
upButton.fontSize = 30
upButton.text = lt("Up")
upButton.fontColor = SKColor.whiteColor()
upButton.zPosition = 150
upButton.name = "Up"
overlayLayer.addChild(upButton)
let downButton = SKLabelNode(fontNamed: "MarkerFelt-Wide")
downButton.posByScreen(0.35, y: -0.45)
downButton.fontSize = 30
downButton.text = lt("Down")
downButton.fontColor = SKColor.whiteColor()
downButton.zPosition = 150
downButton.name = "Down"
overlayLayer.addChild(downButton)
let printButton = SKLabelNode(fontNamed: "MarkerFelt-Wide")
printButton.posByScreen(0.0, y: -0.45)
printButton.fontSize = 30
printButton.text = lt("Print")
printButton.fontColor = SKColor.whiteColor()
printButton.zPosition = 150
printButton.name = "Print"
overlayLayer.addChild(printButton)
let background = SKSpriteNode(imageNamed: "BG")
background.position = CGPointZero
background.xScale = 1.2
background.yScale = 1.2
background.alpha = 0.2
background.zPosition = -1
overlayLayer.addChild(background)
tilePanel!.posByScreen(0.45, y: 0.45)
tilePanel!.selectIndex(0)
overlayLayer.addChild(tilePanel!)
}
//MARK: Responders
override func screenInteractionStarted(location: CGPoint) {
if let node = nodeAtPoint(location) as? SKLabelNode {
if node.name == "modeSelect" {
switch currentTool {
case .toolMove:
node.text = lt("Add")
currentTool = .toolAdd
break
case .toolAdd:
node.text = lt("Remove")
currentTool = .toolRemove
break
case .toolRemove:
node.text = lt("Move")
currentTool = .toolMove
break
}
return
}
if node.name == "zoomOut" {
if let camera = camera {
camera.xScale = camera.xScale + 0.2
camera.yScale = camera.yScale + 0.2
}
return
}
if node.name == "zoomIn" {
if let camera = camera {
camera.xScale = camera.xScale - 0.2
camera.yScale = camera.yScale - 0.2
}
return
}
if node.name == "Up" {
tilePanel!.position = CGPoint(x: tilePanel!.position.x, y: tilePanel!.position.y - 34)
return
}
if node.name == "Down" {
tilePanel!.position = CGPoint(x: tilePanel!.position.x, y: tilePanel!.position.y + 34)
return
}
if node.name == "Print" {
worldLayer.levelGenerator.printLayer()
return
}
}
if let node = nodeAtPoint(location) as? SKSpriteNode {
if ((node.name?.hasPrefix("T_")) != nil) {
tilePanel!.selectIndex((node.userData!["index"] as? Int)!)
return
}
}
switch currentTool {
case .toolMove:
if let camera = camera {
camera.runAction(SKAction.moveTo(location, duration: 0.2))
//print("x: \(floor(abs(location.x/32.0))) y: \(floor(abs(location.y/32.0)))")
}
break
case .toolAdd:
let locationInfo = locationToTileIndex(CGPoint(x: location.x + 16, y: location.y - 16))
if locationInfo.valid == true {
changeTile(tilePanel!.selectedIndex, location: locationInfo.tileIndex)
updateTileMap()
}
break
case .toolRemove:
let locationInfo = locationToTileIndex(CGPoint(x: location.x + 16, y: location.y - 16))
if locationInfo.valid == true {
changeTile(0, location: locationInfo.tileIndex)
updateTileMap()
}
break
}
}
//MARK: functions
func changeTile(tileCode:Int,location:CGPoint) {
worldLayer.levelGenerator.setTile(position: location, toValue: tileCode)
}
func updateTileMap() {
for child in worldLayer.children {
child.removeFromParent()
}
worldLayer.levelGenerator.presentLayerViaDelegate(GameSettings.Builder.BUILDER_LEVEL)
for child in worldLayer.children {
if let name = child.name {
switch name {
case "placeholder_Diamond":
let label = SKLabelNode(text: "D")
label.zPosition = GameSettings.GameParams.zValues.zWorld + 1
label.position = child.position
worldLayer.addChild(label)
break
case "placeholder_Coin":
let label = SKLabelNode(text: "C")
label.zPosition = GameSettings.GameParams.zValues.zWorld + 1
label.position = child.position
worldLayer.addChild(label)
break
case "placeholder_StartPoint":
let label = SKLabelNode(text: "S")
label.zPosition = GameSettings.GameParams.zValues.zWorld + 1
label.position = child.position
worldLayer.addChild(label)
break
case "placeholder_FinishPoint":
let label = SKLabelNode(text: "F")
label.zPosition = GameSettings.GameParams.zValues.zWorld + 1
label.position = child.position
worldLayer.addChild(label)
break
case "placeholder_Zombie1":
let label = SKLabelNode(text: "Z1")
label.zPosition = GameSettings.GameParams.zValues.zWorld + 1
label.position = child.position
worldLayer.addChild(label)
break
case "placeholder_Zombie2":
let label = SKLabelNode(text: "Z2")
label.zPosition = GameSettings.GameParams.zValues.zWorld + 1
label.position = child.position
worldLayer.addChild(label)
break
case "placeholder_Mage1":
let label = SKLabelNode(text: "M1")
label.zPosition = GameSettings.GameParams.zValues.zWorld + 1
label.position = child.position
worldLayer.addChild(label)
break
case "placeholder_Mage2":
let label = SKLabelNode(text: "M2")
label.zPosition = GameSettings.GameParams.zValues.zWorld + 1
label.position = child.position
worldLayer.addChild(label)
break
case "placeholder_Boss":
let label = SKLabelNode(text: "B")
label.zPosition = GameSettings.GameParams.zValues.zWorld + 1
label.position = child.position
worldLayer.addChild(label)
break
case "placeholder_Princess":
let label = SKLabelNode(text: "P")
label.zPosition = GameSettings.GameParams.zValues.zWorld + 1
label.position = child.position
worldLayer.addChild(label)
break
case "placeholder_EndDialog":
let label = SKLabelNode(text: "ED")
label.zPosition = GameSettings.GameParams.zValues.zWorld + 1
label.position = child.position
worldLayer.addChild(label)
break
default:
break
}
}
}
}
func locationToTileIndex(location:CGPoint) -> (valid:Bool, tileIndex:CGPoint) {
let newIndex = CGPoint(x: floor(abs(location.x/32.0)), y: floor(abs(location.y/32.0)))
if (newIndex.x >= 0 && newIndex.x < worldLayer.levelGenerator.mapSize.x) &&
(newIndex.y >= 0 && newIndex.y < worldLayer.levelGenerator.mapSize.y) {
return (true, newIndex)
} else {
return (false, newIndex)
}
}
}
//Tile Panel
class builderPanel: SKNode {
var atlasTiles: SKTextureAtlas!
var atlasObjects: SKTextureAtlas!
var selectedIndex = 0
init(objectImages: [String], objectTexture: String, tileImages:[String], imagetexture: String) {
super.init()
atlasTiles = SKTextureAtlas(named: imagetexture)
for (index, imageString) in tileImages.enumerate() {
let node = SKSpriteNode(texture: atlasTiles.textureNamed(imageString))
node.size = CGSize(width: 32, height: 32)
node.position = CGPoint(x: 0, y: index * -34)
node.alpha = 0.5
node.zPosition = 150
node.name = "T_\(index)"
node.userData = ["index":index]
addChild(node)
}
atlasObjects = SKTextureAtlas(named: objectTexture)
for (i, imageString) in objectImages.enumerate() {
let index = i + tileImages.count
let node = SKSpriteNode(texture: atlasObjects.textureNamed(imageString))
node.size = CGSize(width: 32, height: 32)
node.position = CGPoint(x: 0, y: index * -34)
node.alpha = 0.5
node.zPosition = 150
node.name = "T_\(index)"
node.userData = ["index":index]
addChild(node)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func selectIndex(indexSelected:Int) {
selectedIndex = indexSelected
for child in children {
if selectedIndex == (child.userData!["index"] as? Int)! {
child.alpha = 1.0
child.setScale(1.1)
} else {
child.alpha = 0.5
child.setScale(1.0)
}
}
}
}
| mit | ba6280aafadb13f9d8fb912274f620a1 | 37.843038 | 141 | 0.554976 | 4.667782 | false | false | false | false |
Vostro162/VaporTelegram | Sources/App/MaskPosition.swift | 1 | 781 | //
// MaskPosition.swift
// VaporTelegram
//
// Created by Marius Hartig on 25.08.17.
//
//
import Foundation
struct MaskPosition {
// One of “forehead”, “eyes”, “mouth”, or “chin”.
public enum Position: String {
case forehead = "forehead"
case eyes = "eyes"
case mouth = "mouth"
case chin = "chin"
}
// The part of the face relative to which the mask should be placed
let position: Position
// point
let point: MaskPoint
// Mask scaling coefficient. For example, 2.0 means double size.
let scale: Float
init(position: Position, point: MaskPoint, scale: Float) {
self.position = position
self.point = point
self.scale = scale
}
}
| mit | a755156f5ebc56f8a7b22e932829e18e | 20.25 | 71 | 0.588235 | 3.943299 | false | false | false | false |
Sage-Bionetworks/MoleMapper | MoleMapper/Charts/Classes/Data/CandleChartDataSet.swift | 1 | 3016 | //
// CandleChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class CandleChartDataSet: LineScatterCandleChartDataSet
{
/// the width of the candle-shadow-line in pixels.
///
/// **default**: 3.0
public var shadowWidth = CGFloat(1.5)
/// the space between the candle entries
///
/// **default**: 0.1 (10%)
private var _bodySpace = CGFloat(0.1)
/// the color of the shadow line
public var shadowColor: UIColor?
/// use candle color for the shadow
public var shadowColorSameAsCandle = false
/// color for open <= close
public var decreasingColor: UIColor?
/// color for open > close
public var increasingColor: UIColor?
/// Are decreasing values drawn as filled?
public var decreasingFilled = false
/// Are increasing values drawn as filled?
public var increasingFilled = true
public override init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(yVals: yVals, label: label)
}
internal override func calcMinMax(start start: Int, end: Int)
{
if (yVals.count == 0)
{
return
}
var entries = yVals as! [CandleChartDataEntry]
var endValue : Int
if end == 0
{
endValue = entries.count - 1
}
else
{
endValue = end
}
_lastStart = start
_lastEnd = end
_yMin = entries[start].low
_yMax = entries[start].high
for (var i = start + 1; i <= endValue; i++)
{
let e = entries[i]
if (e.low < _yMin)
{
_yMin = e.low
}
if (e.high > _yMax)
{
_yMax = e.high
}
}
}
/// the space that is left out on the left and right side of each candle,
/// **default**: 0.1 (10%), max 0.45, min 0.0
public var bodySpace: CGFloat
{
set
{
if (newValue < 0.0){
_bodySpace = 0.0
}else if (newValue > 0.45){
_bodySpace = 0.45
}else{
_bodySpace = newValue
}
}
get
{
return _bodySpace
}
}
/// Is the shadow color same as the candle color?
public var isShadowColorSameAsCandle: Bool { return shadowColorSameAsCandle }
/// Are increasing values drawn as filled?
public var isIncreasingFilled: Bool { return increasingFilled; }
/// Are decreasing values drawn as filled?
public var isDecreasingFilled: Bool { return decreasingFilled; }
} | bsd-3-clause | 91692cc6e51cbcecf784b5619fe85ec7 | 23.729508 | 81 | 0.534814 | 4.597561 | false | false | false | false |
mleiv/MEGameTracker | MEGameTracker/Models/Item/ItemDisplayType.swift | 1 | 1549 | //
// ItemDisplayType.swift
// MEGameTracker
//
// Created by Emily Ivie on 6/17/16.
// Copyright © 2016 Emily Ivie. All rights reserved.
//
import UIKit
/// Distinguishes item variants so they can be displayed with UI differences.
/// Consider this a subset of ItemType.
public enum ItemDisplayType: String, Codable, CaseIterable {
case goal = "Goal"
case loot = "Loot"
case medkit = "MedKit"
case novelty = "Novelty"
case other = "Other" // other experience or information
/// Returns the string values of all the enum variations.
private static let stringValues: [ItemDisplayType: String] = {
return Dictionary(uniqueKeysWithValues: allCases.map { ($0, $0.stringValue) })
}()
/// Creates an enum from a string value, if possible.
public init?(stringValue: String?) {
self.init(rawValue: stringValue ?? "")
}
/// Returns the string value of an enum.
public var stringValue: String {
return ItemDisplayType.stringValues[self] ?? "Unknown"
}
/// Returns a UI color appropriate to differentiate this item on a map.
public var color: UIColor {
switch self {
case .goal: return UIColor(red: 0.8, green: 0.0, blue: 0.0, alpha: 1.0)
case .loot: return UIColor(red: 0.9, green: 0.6, blue: 0.2, alpha: 1.0)
case .medkit: return UIColor(red: 0.3, green: 0.5, blue: 1.0, alpha: 1.0)
case .novelty: return UIColor(red: 1.0, green: 0.6, blue: 0.7, alpha: 1.0)
case .other: return UIColor(red: 0.6, green: 0.6, blue: 0.9, alpha: 1.0)
}
}
}
| mit | 0b9fb7d4c7983f06e4c98dafdcf50bdb | 32.652174 | 86 | 0.656331 | 3.350649 | false | false | false | false |
piersadrian/switch | Flow/Sources/Buffer.swift | 1 | 1083 | //
// Buffer.swift
// Switch
//
// Created by Piers Mainwaring on 12/26/15.
// Copyright © 2016 Playfair, LLC. All rights reserved.
//
import Foundation
class Buffer {
// MARK: - Internal Properties
var data: NSMutableData
var length: Int {
didSet {
data.length = length
}
}
var remainingLength: Int {
return data.length - currentPosition
}
var currentPosition: Int = 0 {
willSet {
if newValue + currentPosition > data.length {
fatalError("can't set position beyond buffer's length")
}
}
}
var cursor: UnsafeMutablePointer<Void> {
return data.mutableBytes.advancedBy(currentPosition)
}
var completed: Bool {
return currentPosition == data.length
}
// MARK: - Lifecycle
init(expectedLength length: Int) {
self.data = NSMutableData(length: length)!
self.length = length
}
init(data: NSData) {
self.data = NSMutableData(data: data)
self.length = data.length
}
}
| mit | fc2918238f09f6741e58154ddaad595c | 19.415094 | 71 | 0.584104 | 4.416327 | false | false | false | false |
nfls/nflsers | app/v2/Essential/AbstractProvider.swift | 1 | 3402 | //
// Provider.swift
// NFLSers-iOS
//
// Created by Qingyang Hu on 21/01/2018.
// Copyright © 2018 胡清阳. All rights reserved.
//
import Foundation
import Moya
import SwiftyJSON
import Cache
import Result
import ObjectMapper
class AbstractProvider<T:TargetType> {
let provider:MoyaProvider<T>
public let notifier:MessageNotifier
init() {
provider = MainOAuth2().getRequestClosure(type: T.self)
notifier = MessageNotifier()
}
internal func request<R:BaseMappable>(
target: T,
type: R.Type,
success successCallback: @escaping (AbstractResponse<R>) -> Void,
error errorCallback: ((_ error: Error) -> Void)? = nil,
failure failureCallback: (() -> Void)? = nil
) {
provider.request(target) { (result) in
switch result {
case let .success(response):
if response.statusCode == 400 {
if target.baseURL.absoluteString.hasPrefix("https://nfls.io") {
NotificationCenter.default.post(name: NSNotification.Name(NotificationType.logout.rawValue), object: nil)
self.notifier.showInfo("请重新登录。")
}
} else {
if let json = JSON(response.data).dictionaryObject {
do {
let value = try AbstractResponse<R>(JSON: json)
successCallback(value)
} catch let error {
debugPrint(error)
do {
let detail = try AbstractMessage(JSON: json)
if let errorCallback = errorCallback {
errorCallback(detail)
} else {
self.notifier.showNetworkError(detail)
}
} catch let errorWithError {
debugPrint(errorWithError)
if let errorCallback = errorCallback {
errorCallback(AbstractError(status: 1001,message: errorWithError.localizedDescription))
} else {
self.notifier.showNetworkError(AbstractError(status: 1001,message: errorWithError.localizedDescription))
}
}
}
} else {
debugPrint(String(data: response.data, encoding: .utf8) ?? "")
if let failureCallback = failureCallback {
failureCallback()
} else {
self.notifier.showNetworkError(AbstractError(status: 1002, message: "JSON解析失败,请检查网络及当前用户权限。"))
}
}
}
case .failure(let error):
debugPrint(error)
if let failureCallback = failureCallback {
failureCallback()
} else {
self.notifier.showNetworkError(AbstractError(status: 0, message: "请求失败"))
}
}
}
}
}
| apache-2.0 | c7ed9e890f25659a58316f39fd79c509 | 39.228916 | 140 | 0.471099 | 5.909735 | false | false | false | false |
vakoc/logging | Sources/Logging.swift | 1 | 7398 | // This source file is part of the vakoc.com open source project(s)
//
// Copyright © 2016 Mark Vakoc. All rights reserved.
// Licensed under Apache License v2.0
//
// See http://www.vakoc.com/LICENSE.txt for license information
import Foundation
public var globalLogLevel: LogLevel = .trace
public enum LogLevel: Int {
case trace,
debug,
info,
warning,
error,
off
}
extension String {
func indentedLines(_ indent: String = " ", separatedBy: String = "\n") -> String {
return self.components(separatedBy: separatedBy)
.map { return "\(indent)\($0)" }
.joined(separator: separatedBy)
}
}
extension Thread {
class func indentedCallStackSymbols() -> String {
return self.callStackSymbols.map { return " " + $0 }.joined(separator: "\n")
}
}
extension LogLevel : CustomStringConvertible {
public var description: String {
get {
switch(self) {
case .trace:
return "TRACE"
case .debug:
return "DEBUG"
case .info:
return "INFO"
case .warning:
return "WARN"
case .error:
return "ERROR"
case .off:
return ""
}
}
}
public var paddedDescription: String {
get {
switch(self) {
case .trace:
return " TRACE"
case .debug:
return " DEBUG"
case .info:
return " INFO"
case .warning:
return "⚠ WARN"
case .error:
return "☣ ERROR"
case .off:
return ""
}
}
}
}
/**
logs a message using the specified level
:param: message the message to log, must return a string
:param: level the log level of the message
:param: function the calling function name
:param: file the calling file
:param: line the calling line
:returns: the log message used without any adornment such as function name, file, line
*/
@inline(__always)
public func log( _ message: @autoclosure() -> String, level: LogLevel = .debug, function: String = #function, file: String = #file, line: Int = #line, callstack: Bool = false) -> Void {
if level.rawValue >= globalLogLevel.rawValue {
let message = message()
let f = URL(fileURLWithPath: file).lastPathComponent ?? "unknown"
if callstack {
print("[\(level.paddedDescription)] \(f):\(line) • \(function) - \(message)\nCallstack:\n\(Thread.indentedCallStackSymbols())")
} else {
print("[\(level.paddedDescription)] \(f):\(line) • \(function) - \(message)")
}
}
}
/**
logs a error message
:param: message the message to log, must return a string
:param: function the calling function name
:param: file the calling file
:param: line the calling line
:returns: the log message used without any adornment such as function name, file, line
*/
@inline(__always)
public func error( _ message: @autoclosure() -> String, function: String = #function, file: String = #file, line: Int = #line, callstack: Bool = false) -> Void {
return log(message, level: .error, function: function, file: file, line: line, callstack: callstack)
}
/**
logs a warning message
:param: message the message to log, must return a string
:param: function the calling function name
:param: file the calling file
:param: line the calling line
:returns: the log message used without any adornment such as function name, file, line
*/
@inline(__always)
public func warn( _ message: @autoclosure() -> String, function: String = #function, file: String = #file, line: Int = #line, callstack: Bool = false) -> Void {
return log(message, level: .warning, function: function, file: file, line: line, callstack: callstack)
}
/**
logs a debug (trace) message
:param: message the message to log, must return a string
:param: function the calling function name
:param: file the calling file
:param: line the calling line
:returns: the log message used without any adornment such as function name, file, line
*/
@inline(__always)
public func debug( _ message: @autoclosure() -> String, function: String = #function, file: String = #file, line: Int = #line, callstack: Bool = false) -> Void {
return log(message, level: .debug, function: function, file: file, line: line, callstack: callstack)
}
/**
logs an informative message
:param: message the message to log, must return a string
:param: function the calling function name
:param: file the calling file
:param: line the calling line
:returns: the log message used without any adornment such as function name, file, line
*/
@inline(__always)
public func info( _ message: @autoclosure() -> String, function: String = #function, file: String = #file, line: Int = #line, callstack: Bool = false) -> Void {
return log(message, level: .info, function: function, file: file, line: line, callstack: callstack)
}
/**
logs a trace (finer than debug) message
:param: message the message to log, must return a string
:param: function the calling function name
:param: file the calling file
:param: line the calling line
:returns: the log message used without any adornment such as function name, file, line
*/
@inline(__always)
public func trace( _ message: @autoclosure() -> String, function: String = #function, file: String = #file, line: Int = #line, callstack: Bool = false) -> Void {
return log(message, level: .trace, function: function, file: file, line: line, callstack: callstack)
}
/**
logs a http request and reponse
*/
@inline(__always)
public func trace(_ description: String, request: URLRequest, data: Data?, response: URLResponse?, error: NSError?, function: String = #function, file: String = #file, line: Int = #line) -> Void {
guard globalLogLevel.rawValue <= LogLevel.trace.rawValue else {
return
}
var components = [description, "with \(request.httpMethod ?? "GET") request"]
components.append("\(request)")
if let headers = request.allHTTPHeaderFields {
components.append("headers")
components.append("\(headers)")
}
if let body = request.httpBody, let bodyString = String(data: body, encoding: String.Encoding.utf8) {
components.append("request body")
components.append(bodyString)
}
if let response = response {
components.append("returned")
components.append("\(response)")
}
if let response = response as? HTTPURLResponse, let contentType = response.allHeaderFields["Content-Type"] as? String , contentType.contains("application/json"), let data = data, let json = try? JSONSerialization.jsonObject(with: data as Data, options: []) {
components.append("with response")
components.append("\(json)")
} else if let data = data, let body = String(data: data as Data, encoding: String.Encoding.utf8) {
components.append("with response")
components.append(body)
}
if let error = error {
components.append("error:")
components.append("\(error)")
}
trace(components.joined(separator: "\n"), function: function, file: file, line: line)
}
| apache-2.0 | 6eebef800840467fd259a20bde1a0a0c | 32.283784 | 263 | 0.632291 | 4.155793 | false | false | false | false |
JHStone/DYZB | DYZB/DYZB/Classes/Main/View/PageTitleView.swift | 1 | 5330 | //
// PageTitleView.swift
// DYZB
//
// Created by 谷建华 on 17/2/14.
// Copyright © 2017年 谷建华. All rights reserved.
//
import UIKit
protocol PageTitleViewDelegate : class{
func pageTitleView(titleView : PageTitleView, selectedIndex: Int)
}
fileprivate let scrollViewLineH : CGFloat = 2
//定义长量
private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0)
class PageTitleView: UIView {
lazy var titleArray : [String] = [String]()
weak var delegate : PageTitleViewDelegate?
fileprivate lazy var titlesLabels : [UILabel] = [UILabel]()
fileprivate var lastIndex : Int = 0
fileprivate lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.scrollsToTop = false
scrollView.showsHorizontalScrollIndicator = false
return scrollView
}()
fileprivate lazy var scrollViewLine : UIView = {
let scrollViewLine = UIView()
scrollViewLine.backgroundColor = UIColor.orange
return scrollViewLine
}()
//定义元组
fileprivate var kNormalColor: (CGFloat,CGFloat, CGFloat) = (85, 85, 85)
init(frame: CGRect, titles: [String]) {
super.init(frame: frame)
titleArray = titles
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK:- UI
extension PageTitleView{
fileprivate func setupUI(){
scrollView.frame = self.bounds
addSubview(scrollView)
setupLabelTitle()
setupBottomLineAndScrollViewLine()
}
private func setupLabelTitle(){
//这里是创建label
let labelW = screenW / CGFloat(titleArray.count)
let labelH = self.bounds.size.height
for (index, content) in titleArray.enumerated(){
let label = UILabel()
label.textAlignment = .center
label.text = content
label.tag = index
label.font = UIFont.systemFont(ofSize: 16.0)
label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
label.frame = CGRect(x: CGFloat(index) * labelW , y: 0, width: labelW, height: labelH)
label.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(tap:)))
label.addGestureRecognizer(tapGes)
scrollView.addSubview(label)
titlesLabels.append(label)
}
}
//设置底部线条
private func setupBottomLineAndScrollViewLine(){
let lineH : CGFloat = 0.5
let bottomLine = UIView(frame: CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH))
bottomLine.backgroundColor = UIColor.lightGray
addSubview(bottomLine)
//底部的orangeView
scrollViewLine.frame = CGRect(x: 0, y: frame.height - lineH - scrollViewLineH, width: screenW / CGFloat(titleArray.count), height: scrollViewLineH)
addSubview(scrollViewLine)
}
}
//MARK:- 监听label的点击
extension PageTitleView{
@objc fileprivate func titleLabelClick(tap : UITapGestureRecognizer){
//获取当前的label
let currentLabel = tap.view as! UILabel
//拿到tag
let currentTage = currentLabel.tag
if currentTage == lastIndex {return}
//获取之前的label
let lastLabel = titlesLabels[lastIndex]
currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
lastLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
currentLabel.textColor = UIColor.orange
UIView.animate(withDuration: 0.25) {
self.scrollViewLine.frame.origin.x = CGFloat(currentTage) * (self.scrollViewLine.frame.size.width)
}
lastIndex = currentTage;
delegate?.pageTitleView(titleView: self, selectedIndex: currentTage)
}
}
//MARK:- collectionView的滚动
extension PageTitleView{
func setupTitleViewContentOffset(pageView: PageContentView, sourceIndex: Int, target: Int, progress: CGFloat) {
// 1.取出sourceLabel/targetLabel
let sourceLabel = titlesLabels[sourceIndex]
let targetLabel = titlesLabels[target]
// 2.处理滑块的逻辑
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = moveTotalX * progress
scrollViewLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
//颜色的变化
let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2)
// 3.2.变化sourceLabel
sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress)
// 3.2.变化targetLabel
targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress)
lastIndex = target
}
}
| mit | cdc1be6d4118a303e3f79dc7326d3077 | 32.733766 | 174 | 0.637536 | 4.655018 | false | false | false | false |
MisterZhouZhou/swift-demo | swift-demo/swift-demo/classes/DemoListViewController.swift | 1 | 2461 | //
// DemoListViewController.swift
// swift-demo
//
// Created by rayootech on 16/4/12.
// Copyright © 2016年 rayootech. All rights reserved.
//
import UIKit
class DemoListViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var listArray :NSArray = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "demo列表"
let tableView = UITableView(frame: UIScreen.mainScreen().applicationFrame)
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
self.view.addSubview(tableView)
listArray = ["实现轮播图","动画效果"]
}
/**
UITableViewDelegate
*/
func numberOfSectionsInTableView(tableView: UITableView) -> Int{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return listArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let ID = "cell"
var cell = tableView.dequeueReusableCellWithIdentifier(ID)
if cell == nil{
cell = UITableViewCell(style: .Default, reuseIdentifier: ID)
}
cell?.accessoryType = .DisclosureIndicator
cell?.textLabel?.text = "\(listArray[indexPath.row])"
cell?.selectionStyle = .None
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch indexPath.row{
case 0:
self.navigationController?.pushViewController(EasyScrollViewController(), animated: true)
break
case 1:
self.navigationController?.pushViewController(AnimationListViewController(), animated: true)
break
default:
break
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | e303eecdf529400583d48cf4d9382e4c | 29.835443 | 108 | 0.650246 | 5.413333 | false | false | false | false |
APUtils/APExtensions | APExtensions/Classes/Core/_Extensions/_Foundation/String+Utils.swift | 1 | 3996 | //
// String+Utils.swift
// APExtensions
//
// Created by Anton Plebanovich on 16/04/16.
// Copyright © 2019 Anton Plebanovich. All rights reserved.
//
import Foundation
import RoutableLogger
// ******************************* MARK: - Appending
public extension String {
mutating func appendNewLine() {
append("\n")
}
mutating func append(valueName: String?, value: Any?, separator: String = ", ") {
var stringRepresentation: String
if let value = g.unwrap(value) {
if let value = value as? String {
stringRepresentation = value
} else if let bool = value as? Bool {
stringRepresentation = bool ? "true" : "false"
} else {
stringRepresentation = "\(value)"
}
} else {
stringRepresentation = "nil"
}
if let valueName = valueName {
append("\(valueName):", separator: separator)
appendWithSpace(stringRepresentation)
} else {
append(stringRepresentation, separator: separator)
}
}
mutating func appendWithNewLine(_ string: String?) {
append(string, separator: "\n")
}
mutating func appendWithSpace(_ string: String?) {
append(string, separator: " ")
}
mutating func appendWithComma(_ string: String?) {
append(string, separator: ", ")
}
mutating func append(_ string: String?, separator: String) {
guard let string = string, !string.isEmpty else { return }
if isEmpty {
self.append(string)
} else {
self.append("\(separator)\(string)")
}
}
mutating func wrap(`class`: Any.Type) {
self = String(format: "%@(%@)", String(describing: `class`), self)
}
}
// ******************************* MARK: - Capitalization
public extension String {
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}
// ******************************* MARK: - Random
public extension String {
/// Generates random string with spaces.
static func random(length: Int, averageWordLength: Int? = nil) -> String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let spacesCount = averageWordLength == nil ? 0 : letters.count / averageWordLength!
let lettersWithSpace = letters.appending(String(repeating: " ", count: spacesCount))
return String((0..<length).map{ _ in lettersWithSpace.randomElement()! })
}
}
// ******************************* MARK: - Safe
public extension String {
/// Safely initializes string with contents of a file or returns `nil` and reports an error if unable.
init?(safeContentsOf url: URL, encoding: Encoding, file: String = #file, function: String = #function, line: UInt = #line) {
guard FileManager.default.fileExists(atPath: url.path) else {
RoutableLogger.logError("Unable to get contents of non-existing file", data: ["url": url], file: file, function: function, line: line)
return nil
}
do {
try self.init(contentsOf: url, encoding: encoding)
} catch {
RoutableLogger.logError("Can not get contents of a file", error: error, data: ["url": url], file: file, function: function, line: line)
return nil
}
}
}
// ******************************* MARK: - Other
public extension String {
/// Returns fileName without extension
var fileName: String {
guard let lastPathComponent = components(separatedBy: "/").last else { return "" }
var components = lastPathComponent.components(separatedBy: ".")
if components.count == 1 {
return lastPathComponent
} else {
components.removeLast()
return components.joined(separator: ".")
}
}
}
| mit | e921c0ac3644bd3a8a58f4bdd32452a6 | 30.96 | 147 | 0.570213 | 4.932099 | false | false | false | false |
boyXiong/XWSwiftRefreshT | XWSwiftRefreshT/Footer/XWRefreshAutoStateFooter.swift | 2 | 2049 | //
// XWRefreshAutoStateFooter.swift
// XWSwiftRefresh
//
// Created by Xiong Wei on 15/10/6.
// Copyright © 2015年 Xiong Wei. All rights reserved.
// 新浪微博: @爱吃香干炒肉
import UIKit
/** footerView 只有状态文字 */
public class XWRefreshAutoStateFooter: XWRefreshAutoFooter {
//MARK: 外部
/** 显示刷新状态的label */
lazy var stateLabel:UILabel = {
[unowned self] in
let lable = UILabel().Lable()
self.addSubview(lable)
return lable
}()
/** 隐藏刷新状态的文字 */
public var refreshingTitleHidden:Bool = false
/** 设置状态的显示文字 */
public func setTitle(title:String, state:XWRefreshState){
self.stateLabel.text = self.stateTitles[self.state];
}
//MARK: 私有的
/** 每个状态对应的文字 */
private var stateTitles:Dictionary<XWRefreshState, String> = [
XWRefreshState.Idle : XWRefreshFooterStateIdleText,
XWRefreshState.Refreshing : XWRefreshFooterStateRefreshingText,
XWRefreshState.NoMoreData : XWRefreshFooterStateNoMoreDataText
]
override func prepare() {
super.prepare()
self.stateLabel.userInteractionEnabled = true
self.stateLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "stateLabelClick"))
self.stateLabel.text = self.stateTitles[state]
}
func stateLabelClick(){
if self.state == XWRefreshState.Idle {
self.beginRefreshing()
}
}
override func placeSubvies() {
super.placeSubvies()
self.stateLabel.frame = self.bounds
}
override var state:XWRefreshState {
didSet{
if oldValue == state { return }
if self.refreshingTitleHidden && state == XWRefreshState.Refreshing {
self.stateLabel.text = nil
}else {
self.stateLabel.text = self.stateTitles[state]
}
}
}
}
| mit | 9b0e1ff5b62a72ea9c93dede0eeb69d7 | 25.162162 | 109 | 0.61312 | 4.620525 | false | false | false | false |
mthud/MorphingLabel | MorphingLabel+Sparkle.swift | 1 | 4272 | /
// MorphingLabel+Sparkle.swift
// https://github.com/mthud/MorphingLabel
//
import UIKit
extension MorphingLabel {
fileprivate func maskedImageForCharLimbo(_ charLimbo: CharacterLimbo, withProgress progress: CGFloat) -> (UIImage, CGRect)
{
let maskedHeight = charLimbo.rect.size.height * max(0.01, progress)
let maskedSize = CGSize(width: charLimbo.rect.size.width, height: maskedHeight)
UIGraphicsBeginImageContextWithOptions(maskedSize, false, UIScreen.main.scale)
let rect = CGRect(x: 0, y: 0, width: charLimbo.rect.size.width, height: maskedHeight)
String(charLimbo.char).draw(in: rect, withAttributes: [
NSFontAttributeName: self.font,
NSForegroundColorAttributeName: self.textColor
])
guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else {
return (UIImage(), CGRect.zero)
}
UIGraphicsEndImageContext()
let newRect = CGRect (
x: charLimbo.rect.origin.x,
y: charLimbo.rect.origin.y,
width: charLimbo.rect.size.width,
height: maskedHeight
)
return (newImage, newRect)
}
func SparkleLoad() {
startClosures["Sparkle\(MorphingPhases.start)"] = {
self.emitterView.removeAllEmitters()
}
progressClosures["Sparkle\(MorphingPhases.progress)"] = {
(index: Int, progress: Float, isNewChar: Bool) in
if (!isNewChar) {
return min(1.0, max(0.0, progress))
}
let j = Float(sin(Float(index))) * 1.5
return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * j))
}
effectClosures["Sparkle\(MorphingPhases.disappear)"] = {
char, index, progress in
return CharacterLimbo (
char: char,
rect: self.previousRects[index],
alpha: CGFloat(1.0 - progress),
size: self.font.pointSize,
drawingProgress: 0.0
)
}
effectClosures["Sparkle\(MorphingPhases.appear)"] = {
char, index, progress in
if (char != " ")
{
let rect = self.newRects[index]
let emitterPosition = CGPoint(
x: rect.origin.x + rect.size.width / 2.0,
y: CGFloat(progress) * rect.size.height * 0.9 + rect.origin.y
)
self.emitterView.createEmitter("c\(index)", particleName: "Sparkle", duration: self.morphingDuration)
{ (layer, cell) in
layer.emitterSize = CGSize(width: rect.size.width, height: 1)
layer.renderMode = kCAEmitterLayerOutline
cell.emissionLongitude = CGFloat(Double.pi / 2.0)
cell.scale = self.font.pointSize / 300.0
cell.scaleSpeed = self.font.pointSize / 300.0 * -1.5
cell.color = self.textColor.cgColor
cell.birthRate = Float(self.font.pointSize) * Float(arc4random_uniform(7) + 3)
}.update { (layer, _) in
layer.emitterPosition = emitterPosition
}.play()
}
return CharacterLimbo (
char: char,
rect: self.newRects[index],
alpha: CGFloat(self.morphingProgress),
size: self.font.pointSize,
drawingProgress: CGFloat(progress)
)
}
drawingClosures["Sparkle\(MorphingPhases.draw)"] = {
(charLimbo: CharacterLimbo) in
if (charLimbo.drawingProgress > 0.0)
{
let (charImage, rect) = self.maskedImageForCharLimbo(charLimbo, withProgress: charLimbo.drawingProgress)
charImage.draw(in: rect)
return true
}
return false
}
skipFramesClosures["Sparkle\(MorphingPhases.skipFrames)"] = {
return 1
}
}
}
| mit | e0b5f3c5f3795dc2f03023933c632bbc | 35.20339 | 127 | 0.528324 | 4.950174 | false | false | false | false |
sora0077/APIKit | Sources/BodyParametersType/MultipartFormDataBodyParameters.swift | 1 | 12234 | import Foundation
#if os(iOS) || os(watchOS) || os(tvOS)
import MobileCoreServices
#elseif os(OSX)
import CoreServices
#endif
/// `FormURLEncodedBodyParameters` serializes array of `Part` for HTTP body and states its content type is multipart/form-data.
public struct MultipartFormDataBodyParameters: BodyParametersType {
/// `EntityType` represents wheather the entity is expressed as `Data` or `InputStream`.
public enum EntityType {
/// Expresses the entity as `Data`, which has faster upload speed and lager memory usage.
case data
/// Expresses the entity as `InputStream`, which has smaller memory usage and slower upload speed.
case inputStream
}
public let parts: [Part]
public let boundary: String
public let entityType: EntityType
public init(parts: [Part], boundary: String = String(format: "%08x%08x", arc4random(), arc4random()), entityType: EntityType = .data) {
self.parts = parts
self.boundary = boundary
self.entityType = entityType
}
// MARK: BodyParametersType
/// `Content-Type` to send. The value for this property will be set to `Accept` HTTP header field.
public var contentType: String {
return "multipart/form-data; boundary=\(boundary)"
}
/// Builds `RequestBodyEntity.Data` that represents `form`.
public func buildEntity() throws -> RequestBodyEntity {
let inputStream = MultipartInputStream(parts: parts, boundary: boundary)
switch entityType {
case .inputStream:
return .inputStream(inputStream)
case .data:
return .data(try Data(inputStream: inputStream))
}
}
}
public extension MultipartFormDataBodyParameters {
/// Part represents single part of multipart/form-data.
public struct Part {
public enum Error: ErrorProtocol {
case illegalValue(Any)
case illegalFileURL(URL)
case cannotGetFileSize(URL)
}
public let inputStream: InputStream
public let name: String
public let mimeType: String?
public let fileName: String?
public let length: Int
/// Returns Part instance that has data presentation of passed value.
/// `value` will be converted via `String(_:)` and serialized via `String.dataUsingEncoding(_:)`.
/// If `mimeType` or `fileName` are `nil`, the fields will be omitted.
public init(value: Any, name: String, mimeType: String? = nil, fileName: String? = nil, encoding: String.Encoding = String.Encoding.utf8) throws {
guard let data = String(value).data(using: encoding) else {
throw Error.illegalValue(value)
}
self.inputStream = InputStream(data: data)
self.name = name
self.mimeType = mimeType
self.fileName = fileName
self.length = data.count
}
/// Returns Part instance that has input stream of specifed data.
/// If `mimeType` or `fileName` are `nil`, the fields will be omitted.
public init(data: Data, name: String, mimeType: String? = nil, fileName: String? = nil) {
self.inputStream = InputStream(data: data)
self.name = name
self.mimeType = mimeType
self.fileName = fileName
self.length = data.count
}
/// Returns Part instance that has input stream of specifed file URL.
/// If `mimeType` or `fileName` are `nil`, values for the fields will be detected from URL.
public init(fileURL: URL, name: String, mimeType: String? = nil, fileName: String? = nil) throws {
guard let inputStream = InputStream(url: fileURL) else {
throw Error.illegalFileURL(fileURL)
}
let fileSize = fileURL.path
.flatMap { try? FileManager.default.attributesOfItem(atPath: $0) }
.flatMap { $0[FileAttributeKey.size] as? NSNumber }
.map { $0.intValue }
guard let bodyLength = fileSize else {
throw Error.cannotGetFileSize(fileURL)
}
let detectedMimeType = fileURL.pathExtension
.flatMap { UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, $0, nil)?.takeRetainedValue() }
.flatMap { UTTypeCopyPreferredTagWithClass($0, kUTTagClassMIMEType)?.takeRetainedValue() }
.map { $0 as String }
self.inputStream = inputStream
self.name = name
self.mimeType = mimeType ?? detectedMimeType ?? "application/octet-stream"
self.fileName = fileName ?? fileURL.lastPathComponent
self.length = bodyLength
}
}
internal class PartInputStream: AbstractInputStream {
let headerData: Data
let footerData: Data
let bodyPart: Part
let totalLength: Int
var totalSentLength: Int
init(part: Part, boundary: String) {
let header: String
switch (part.mimeType, part.fileName) {
case (let mimeType?, let fileName?):
header = "--\(boundary)\r\nContent-Disposition: form-data; name=\"\(part.name)\"; filename=\"\(fileName)\"\r\nContent-Type: \(mimeType)\r\n\r\n"
case (let mimeType?, _):
header = "--\(boundary)\r\nContent-Disposition: form-data; name=\"\(part.name)\"; \r\nContent-Type: \(mimeType)\r\n\r\n"
default:
header = "--\(boundary)\r\nContent-Disposition: form-data; name=\"\(part.name)\"\r\n\r\n"
}
headerData = header.data(using: String.Encoding.utf8)!
footerData = "\r\n".data(using: String.Encoding.utf8)!
bodyPart = part
totalLength = headerData.count + bodyPart.length + footerData.count
totalSentLength = 0
super.init()
}
var headerRange: CountableRange<Int> {
return 0..<headerData.count
}
var bodyRange: CountableRange<Int> {
return headerRange.endIndex..<(headerRange.endIndex + bodyPart.length)
}
var footerRange: CountableRange<Int> {
return bodyRange.endIndex..<(bodyRange.endIndex + footerData.count)
}
// MARK: InputStream
override var hasBytesAvailable: Bool {
return totalSentLength < totalLength
}
override func read(_ buffer: UnsafeMutablePointer<UInt8>, maxLength: Int) -> Int {
var sentLength = 0
while sentLength < maxLength && totalSentLength < totalLength {
let offsetBuffer = buffer + sentLength
let availableLength = maxLength - sentLength
switch totalSentLength {
case headerRange:
let readLength = min(headerRange.endIndex - totalSentLength, availableLength)
let readRange = NSRange(location: totalSentLength - headerRange.startIndex, length: readLength)
(headerData as NSData).getBytes(offsetBuffer, range: readRange)
sentLength += readLength
totalSentLength += sentLength
case bodyRange:
if bodyPart.inputStream.streamStatus == .notOpen {
bodyPart.inputStream.open()
}
let readLength = bodyPart.inputStream.read(offsetBuffer, maxLength: availableLength)
sentLength += readLength
totalSentLength += readLength
case footerRange:
let readLength = min(footerRange.endIndex - totalSentLength, availableLength)
let range = NSRange(location: totalSentLength - footerRange.startIndex, length: readLength)
(footerData as NSData).getBytes(offsetBuffer, range: range)
sentLength += readLength
totalSentLength += readLength
default:
print("Illegal range access: \(totalSentLength) is out of \(headerRange.startIndex)..<\(footerRange.endIndex)")
return -1
}
}
return sentLength;
}
}
internal class MultipartInputStream: AbstractInputStream {
let boundary: String
let partStreams: [PartInputStream]
let footerData: Data
let totalLength: Int
var totalSentLength: Int
private var privateStreamStatus = Stream.Status.notOpen
init(parts: [Part], boundary: String) {
self.boundary = boundary
self.partStreams = parts.map { PartInputStream(part: $0, boundary: boundary) }
self.footerData = "--\(boundary)--\r\n".data(using: String.Encoding.utf8)!
self.totalLength = partStreams.reduce(footerData.count) { $0 + $1.totalLength }
self.totalSentLength = 0
super.init()
}
var partsRange: CountableRange<Int> {
return 0..<partStreams.reduce(0) { $0 + $1.totalLength }
}
var footerRange: CountableRange<Int> {
return partsRange.endIndex..<(partsRange.endIndex + footerData.count)
}
var currentPartInputStream: PartInputStream? {
var currentOffset = 0
for partStream in partStreams {
let partStreamRange = currentOffset..<(currentOffset + partStream.totalLength)
if partStreamRange.contains(totalSentLength) {
return partStream
}
currentOffset += partStream.totalLength
}
return nil
}
// MARK: InputStream
// NOTE: InputStream does not have its own implementation because it is a class cluster.
override var streamStatus: Stream.Status {
return privateStreamStatus
}
override var hasBytesAvailable: Bool {
return totalSentLength < totalLength
}
override func open() {
privateStreamStatus = .open
}
override func close() {
privateStreamStatus = .closed
}
override func read(_ buffer: UnsafeMutablePointer<UInt8>, maxLength: Int) -> Int {
privateStreamStatus = .reading
var sentLength = 0
while sentLength < maxLength && totalSentLength < totalLength {
let offsetBuffer = buffer + sentLength
let availableLength = maxLength - sentLength
switch totalSentLength {
case partsRange:
guard let partStream = currentPartInputStream else {
print("Illegal offset \(totalLength) for part streams \(partsRange)")
return -1
}
let readLength = partStream.read(offsetBuffer, maxLength: availableLength)
sentLength += readLength
totalSentLength += readLength
case footerRange:
let readLength = min(footerRange.endIndex - totalSentLength, availableLength)
let range = NSRange(location: totalSentLength - footerRange.startIndex, length: readLength)
(footerData as NSData).getBytes(offsetBuffer, range: range)
sentLength += readLength
totalSentLength += readLength
default:
print("Illegal range access: \(totalSentLength) is out of \(partsRange.startIndex)..<\(footerRange.endIndex)")
return -1
}
if privateStreamStatus != .closed && !hasBytesAvailable {
privateStreamStatus = .atEnd
}
}
return sentLength
}
override var delegate: StreamDelegate? {
get { return nil }
set { }
}
override func schedule(in runLoop: RunLoop, forMode mode: RunLoopMode) {
}
override func remove(from runLoop: RunLoop, forMode mode: RunLoopMode) {
}
}
}
| mit | dfa94772164d9dc3a8755d4acb4837a2 | 37.11215 | 160 | 0.588932 | 5.225972 | false | false | false | false |
PTomas/NowYou-reTalking | Discussion/Discussion/DiscussionVC.swift | 1 | 6658 | //
// DiscussionVC.swift
// Discussion
//
// Created by Patrick Tomas on 5/21/17.
// Copyright © 2017 Patrick Tomas. All rights reserved.
//
import UIKit
class DiscussionVC: UIViewController, UITextViewDelegate {
var activeField: UITextField?
var UserBias = 3
var myString = NSString()
var myTextField = UITextField.self
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
let image = UIImage(named: "BackButton.png") as UIImage?
let button = UIButton(frame: CGRect(x: 20, y: 30, width: 14, height: 24))
button.backgroundColor = UIColor.white
button.setImage(image, for: .normal)
button.addTarget(self, action: #selector(ratingButtonTapped), for: .touchUpInside)
self.view.addSubview(button)
let WSJimage = UIImage(named: "WSJButton.jpg") as UIImage?
let WSJbutton = UIButton(frame: CGRect(x: 120, y: 180, width: 75, height: 75))
WSJbutton.layer.cornerRadius = 5
WSJbutton.backgroundColor = UIColor.white
WSJbutton.setImage(WSJimage, for: .normal)
WSJbutton.addTarget(self, action: #selector(WSJButtonTapped), for: .touchUpInside)
self.view.addSubview(WSJbutton)
let Gimage = UIImage(named: "GButton.jpg") as UIImage?
let Gbutton = UIButton(frame: CGRect(x: 220, y: 180, width: 75, height: 75))
Gbutton.layer.cornerRadius = 5
Gbutton.backgroundColor = UIColor.white
Gbutton.setImage(Gimage, for: .normal)
Gbutton.addTarget(self, action: #selector(GButtonTapped), for: .touchUpInside)
self.view.addSubview(Gbutton)
let yimage = UIImage(named: "yButton.png") as UIImage?
let ybutton = UIButton(frame: CGRect(x: 50, y: 180, width: 50, height: 50))
ybutton.backgroundColor = UIColor.white
ybutton.setImage(yimage, for: .normal)
ybutton.addTarget(self, action: #selector(yButtonTapped), for: .touchUpInside)
self.view.addSubview(ybutton)
let nimage = UIImage(named: "nButton.png") as UIImage?
let nbutton = UIButton(frame: CGRect(x: 300, y: 180, width: 50, height: 50))
nbutton.backgroundColor = UIColor.white
nbutton.setImage(nimage, for: .normal)
nbutton.addTarget(self, action: #selector(nButtonTapped), for: .touchUpInside)
self.view.addSubview(nbutton)
let sendimage = UIImage(named: "sendButton.png") as UIImage?
let sendButton = UIButton(frame: CGRect(x: 335, y: 625, width: 30, height: 30))
sendButton.backgroundColor = UIColor.white
sendButton.setImage(sendimage, for: .normal)
sendButton.addTarget(self, action: #selector(sendTapped), for: .touchUpInside)
self.view.addSubview(sendButton)
var myTextField: UITextField = UITextField(frame: CGRect(x: 50, y: 620, width: 280, height: 40))
myTextField.text = "What do you think"
myTextField.borderStyle = UITextBorderStyle.line
myTextField.layer.cornerRadius = 5
self.view.addSubview(myTextField)
let myTextView: UITextView = UITextView(frame: CGRect(x: 15, y: 250, width: 350.00, height: 360.00))
myTextView.text = " \(myString)"
myTextView.isUserInteractionEnabled = false
myTextView.layer.borderColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0).cgColor
myTextView.layer.borderWidth = 1.0
myTextView.layer.cornerRadius = 5
self.view.addSubview(myTextView)
var label = UILabel()
label = UILabel(frame: CGRect(x:0, y:30, width:350, height:40))
label.frame.origin = CGPoint(x: self.view.frame.width / 2 - 30, y: 30)
label.text="Topic"
label.font = UIFont(name:"HelveticaNeue-Bold", size: 30.0)
label.font = UIFont.boldSystemFont(ofSize: 30.0)
label.layer.shadowOffset = CGSize(width: 0, height: 5)
label.layer.shadowOpacity = 30
self.view.addSubview(label)
self.view.addSubview(button)
self.view.addSubview(ybutton)
self.view.addSubview(nbutton)
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown), name:NSNotification.Name.UIKeyboardWillShow, object: nil);
// Do any additional setup after loading the view.
}
func sendTapped() {
print("user input")
let replaced = (myString as NSString).replacingOccurrences(of: " ", with: "\(myTextField)")
}
func ratingButtonTapped() {
print("Back")
let viewController:ViewController = ViewController()
self.present(viewController, animated: true, completion: nil)
}
func yButtonTapped() {
print("User would agree with this")
UserBias = 1
}
func nButtonTapped() {
print("User would not agree with this")
UserBias = 2
}
func WSJButtonTapped() {
print("looking at info")
UIApplication.shared.openURL(NSURL(string: "https://www.wsj.com/")! as URL)
}
func GButtonTapped() {
print("looking at info")
UIApplication.shared.openURL(NSURL(string: "https://news.google.com/")! as URL)
}
deinit {
NotificationCenter.default.removeObserver(self);
}
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.view.frame.origin.y = 0
})
view.endEditing(true)
}
func keyboardWasShown(notification: NSNotification) {
let info = notification.userInfo!
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.view.frame.origin.y = -210
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 655b46c0898b79374873100050ee6675 | 36.823864 | 150 | 0.637675 | 4.311528 | false | false | false | false |
dreamsxin/swift | test/expr/cast/nil_value_to_optional.swift | 2 | 649 | // RUN: %target-parse-verify-swift
var t = true
var f = false
func markUsed<T>(_ t: T) {}
markUsed(t != nil) // expected-error {{type 'Bool' is not optional, value can never be nil}}
markUsed(f != nil) // expected-error {{type 'Bool' is not optional, value can never be nil}}
class C : Equatable {}
func == (lhs: C, rhs: C) -> Bool {
return true
}
func test(_ c: C) {
if c == nil {} // expected-error {{type 'C' is not optional, value can never be nil}}
}
class D {}
var d = D()
var dopt: D? = nil
var diuopt: D! = nil
_ = d == nil // expected-error{{type 'D' is not optional, value can never be nil}}
_ = dopt == nil
_ = diuopt == nil
| apache-2.0 | 8bbe226307b1f8b7be2227a9862ed362 | 21.37931 | 92 | 0.608629 | 2.884444 | false | false | false | false |
mshhmzh/firefox-ios | Client/Frontend/Browser/FindInPageHelper.swift | 4 | 1743 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import WebKit
protocol FindInPageHelperDelegate: class {
func findInPageHelper(findInPageHelper: FindInPageHelper, didUpdateCurrentResult currentResult: Int)
func findInPageHelper(findInPageHelper: FindInPageHelper, didUpdateTotalResults totalResults: Int)
}
class FindInPageHelper: TabHelper {
weak var delegate: FindInPageHelperDelegate?
private weak var tab: Tab?
class func name() -> String {
return "FindInPage"
}
required init(tab: Tab) {
self.tab = tab
if let path = NSBundle.mainBundle().pathForResource("FindInPage", ofType: "js"), source = try? NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String {
let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
tab.webView!.configuration.userContentController.addUserScript(userScript)
}
}
func scriptMessageHandlerName() -> String? {
return "findInPageHandler"
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
let data = message.body as! [String: Int]
if let currentResult = data["currentResult"] {
delegate?.findInPageHelper(self, didUpdateCurrentResult: currentResult)
}
if let totalResults = data["totalResults"] {
delegate?.findInPageHelper(self, didUpdateTotalResults: totalResults)
}
}
}
| mpl-2.0 | bd61be407774f3d4d2c0e4a3f6a46497 | 36.891304 | 177 | 0.717154 | 5.156805 | false | false | false | false |
mshhmzh/firefox-ios | ThirdParty/SQLite.swift/Tests/TestHelpers.swift | 9 | 3749 | import XCTest
import SQLite
class SQLiteTestCase : XCTestCase {
var trace = [String: Int]()
let db = try! Connection()
let users = Table("users")
override func setUp() {
super.setUp()
db.trace { SQL in
print(SQL)
self.trace[SQL] = (self.trace[SQL] ?? 0) + 1
}
}
func CreateUsersTable() {
try! db.execute(
"CREATE TABLE \"users\" (" +
"id INTEGER PRIMARY KEY, " +
"email TEXT NOT NULL UNIQUE, " +
"age INTEGER, " +
"salary REAL, " +
"admin BOOLEAN NOT NULL DEFAULT 0 CHECK (admin IN (0, 1)), " +
"manager_id INTEGER, " +
"FOREIGN KEY(manager_id) REFERENCES users(id)" +
")"
)
}
func InsertUsers(names: String...) throws {
try InsertUsers(names)
}
func InsertUsers(names: [String]) throws {
for name in names { try InsertUser(name) }
}
func InsertUser(name: String, age: Int? = nil, admin: Bool = false) throws -> Statement {
return try db.run(
"INSERT INTO \"users\" (email, age, admin) values (?, ?, ?)",
"\(name)@example.com", age?.datatypeValue, admin.datatypeValue
)
}
func AssertSQL(SQL: String, _ executions: Int = 1, _ message: String? = nil, file: String = __FILE__, line: UInt = __LINE__) {
XCTAssertEqual(
executions, trace[SQL] ?? 0,
message ?? SQL,
file: file, line: line
)
}
func AssertSQL(SQL: String, _ statement: Statement, _ message: String? = nil, file: String = __FILE__, line: UInt = __LINE__) {
try! statement.run()
AssertSQL(SQL, 1, message, file: file, line: line)
if let count = trace[SQL] { trace[SQL] = count - 1 }
}
// func AssertSQL(SQL: String, _ query: Query, _ message: String? = nil, file: String = __FILE__, line: UInt = __LINE__) {
// for _ in query {}
// AssertSQL(SQL, 1, message, file: file, line: line)
// if let count = trace[SQL] { trace[SQL] = count - 1 }
// }
func async(expect description: String = "async", timeout: Double = 5, @noescape block: (() -> Void) -> Void) {
let expectation = expectationWithDescription(description)
block(expectation.fulfill)
waitForExpectationsWithTimeout(timeout, handler: nil)
}
}
let bool = Expression<Bool>("bool")
let boolOptional = Expression<Bool?>("boolOptional")
let data = Expression<Blob>("blob")
let dataOptional = Expression<Blob?>("blobOptional")
let date = Expression<NSDate>("date")
let dateOptional = Expression<NSDate?>("dateOptional")
let double = Expression<Double>("double")
let doubleOptional = Expression<Double?>("doubleOptional")
let int = Expression<Int>("int")
let intOptional = Expression<Int?>("intOptional")
let int64 = Expression<Int64>("int64")
let int64Optional = Expression<Int64?>("int64Optional")
let string = Expression<String>("string")
let stringOptional = Expression<String?>("stringOptional")
func AssertSQL(@autoclosure expression1: () -> String, @autoclosure _ expression2: () -> Expressible, file: String = __FILE__, line: UInt = __LINE__) {
XCTAssertEqual(expression1(), expression2().asSQL(), file: file, line: line)
}
func AssertThrows<T>(@autoclosure expression: () throws -> T, file: String = __FILE__, line: UInt = __LINE__) {
do {
try expression()
XCTFail("expression expected to throw", file: file, line: line)
} catch {
XCTAssert(true, file: file, line: line)
}
}
let table = Table("table")
let virtualTable = VirtualTable("virtual_table")
let _view = View("view") // avoid Mac XCTestCase collision
| mpl-2.0 | 952b6826bce9c21c439efc8b7e942e7a | 31.6 | 151 | 0.590557 | 3.992545 | false | false | false | false |
syoung-smallwisdom/ResearchUXFactory-iOS | ResearchUXFactory/SBATrackedSelectionStep.swift | 1 | 18147 | //
// SBATrackedSelectionStep.swift
// ResearchUXFactory
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
open class SBATrackedSelectionStep: ORKPageStep, SBATrackedStep, SBATrackedDataSelectedItemsProtocol {
open var trackingType: SBATrackingStepType? {
return .selection
}
open var trackedItems: [SBATrackedDataObject] {
return _trackedItems
}
fileprivate var _trackedItems: [SBATrackedDataObject]
/**
Define a non-generic factory-style initializer to hide the implementation details of creating the
default selection/frequency steps in the owning class.
*/
init(inputItem: SBAFormStepSurveyItem, trackedItems: [SBATrackedDataObject], factory: SBABaseSurveyFactory) {
// Set the tracked items pointer
_trackedItems = trackedItems
// Create the steps with the *first* step as the selection step created from the inputItem
let firstStep = SBATrackedSelectionFormStep(surveyItem: inputItem, items: trackedItems)
let additionalSteps:[ORKStep] = inputItem.items?.mapAndFilter({ (element) -> ORKStep? in
// If the item does not conform to survey item then return nil
guard let surveyItem = element as? SBASurveyItem else { return nil }
// If the item is not a frequency item then no special handling required
// so fall back to the base level factory for creating the step
guard let trackedSurveyItem = element as? SBATrackedStep,
let type = trackedSurveyItem.trackingType , type == .frequency,
let formSurveyItem = element as? SBAFormStepSurveyItem
else {
return factory.createSurveyStep(surveyItem)
}
// Otherwise for the case where this is a frequency step, special-case the return to
// use the frequency subclass
return SBATrackedFrequencyFormStep(surveyItem: formSurveyItem)
}) ?? []
let steps = [firstStep] + additionalSteps
super.init(identifier: inputItem.identifier, steps: steps)
}
/**
Generic default initializer defined so that this class can include steps that are not the
frequency and selection steps.
*/
public init(identifier: String, trackedItems: [SBATrackedDataObject], steps:[ORKStep]) {
_trackedItems = trackedItems
super.init(identifier: identifier, steps: steps)
}
override open func stepViewControllerClass() -> AnyClass {
return SBATrackedSelectionStepViewController.classForCoder()
}
// MARK: SBATrackedDataSelectedItemsProtocol
@objc(stepResultWithSelectedItems:)
public func stepResult(selectedItems:[SBATrackedDataObject]?) -> ORKStepResult? {
guard let items = selectedItems else { return nil }
// Map the steps
var results:[ORKResult] = self.steps.map { (step) -> [ORKResult] in
var substepResults: [ORKResult] = {
if let trackingStep = step as? SBATrackedDataSelectedItemsProtocol {
// If the substeps implement the selected item result protocol then use that
return trackingStep.stepResult(selectedItems: items)?.results ?? []
}
else {
// TODO: syoung 09/27/2016 Support mapping the results from steps that are not the
// selection and frequency steps
return step.defaultStepResult().results ?? []
}
}()
for result in substepResults {
result.identifier = "\(step.identifier).\(result.identifier)"
}
substepResults.insert(ORKResult(identifier: "step.\(step.identifier)"), at: 0)
return substepResults
}.flatMap({$0})
// Add the tracked result last
let trackedResult = SBATrackedDataSelectionResult(identifier: self.identifier)
trackedResult.selectedItems = items
results.append(trackedResult)
return ORKStepResult(stepIdentifier: self.identifier, results: results)
}
// MARK: Selection filtering
var trackedResultIdentifier: String? {
return self.steps.find({ (step) -> Bool in
if let trackedStep = step as? SBATrackedStep , trackedStep.trackingType == .selection {
return true
}
return false
})?.identifier
}
func filterItems(resultSource:ORKTaskResultSource) -> [SBATrackedDataObject]? {
var items: [SBATrackedDataObject]? = trackedItems
for step in self.steps {
if let filterItems = items,
let filterStep = step as? SBATrackedSelectionFilter,
let stepResult = resultSource.stepResult(forStepIdentifier: step.identifier) {
items = filterStep.filter(selectedItems: filterItems, stepResult: stepResult)
}
}
return items
}
// MARK: Navigation override
override open func stepAfterStep(withIdentifier identifier: String?, with result: ORKTaskResult) -> ORKStep? {
// If the identifier is nil, then this is the first step and there isn't any
// filtering of the selection that needs to occur
guard identifier != nil else {
return super.stepAfterStep(withIdentifier: nil, with: result)
}
// Check if the current state means that nothing was selected. In this case
// there is no follow-up steps to further mutate the selection set.
guard let selectedItems = filterItems(resultSource: result) else { return nil }
// Loop through the next steps to look for the next valid step
var shouldSkip = false
var nextStep: ORKStep?
var previousIdentifier = identifier
repeat {
nextStep = super.stepAfterStep(withIdentifier: previousIdentifier, with: result)
shouldSkip = {
guard let navStep = nextStep as? SBATrackedNavigationStep else { return false }
navStep.update(selectedItems: selectedItems)
return navStep.shouldSkipStep
}()
previousIdentifier = nextStep?.identifier
} while shouldSkip && (nextStep != nil )
return nextStep
}
override open func stepBeforeStep(withIdentifier identifier: String, with result: ORKTaskResult) -> ORKStep? {
// Check if the current state means that nothing was selected. In this case
// return to the first step
guard let _ = filterItems(resultSource: result) else {
return self.steps.first
}
// Loop backward through the steps until one is found that is the first
var shouldSkip = false
var previousStep: ORKStep?
var previousIdentifier: String? = identifier
repeat {
previousStep = super.stepBeforeStep(withIdentifier: previousIdentifier!, with: result)
shouldSkip = {
guard let navStep = previousStep as? SBATrackedNavigationStep else { return false }
return navStep.shouldSkipStep
}()
previousIdentifier = previousStep?.identifier
} while shouldSkip && (previousIdentifier != nil )
return previousStep
}
// MARK: NSCoding
required public init(coder aDecoder: NSCoder) {
_trackedItems = aDecoder.decodeObject(forKey: "trackedItems") as? [SBATrackedDataObject] ?? []
super.init(coder: aDecoder)
}
override open func encode(with aCoder: NSCoder){
super.encode(with: aCoder)
aCoder.encode(self.trackedItems, forKey: "trackedItems")
}
// MARK: NSCopying
convenience init(identifier: String) {
// Copying requires defining the base class ORKStep init
self.init(identifier: identifier, trackedItems: [], steps:[])
}
override open func copy(with zone: NSZone? = nil) -> Any {
let copy = super.copy(with: zone) as! SBATrackedSelectionStep
copy._trackedItems = self._trackedItems
return copy
}
// MARK: Equality
override open func isEqual(_ object: Any?) -> Bool {
guard let object = object as? SBATrackedSelectionStep else { return false }
return super.isEqual(object) &&
SBAObjectEquality(object.trackedItems, self.trackedItems)
}
override open var hash: Int {
return super.hash ^
SBAObjectHash(self.trackedItems)
}
}
class SBATrackedSelectionStepViewController: ORKPageStepViewController {
override var result: ORKStepResult? {
guard let stepResult = super.result else { return nil }
guard let selectionStep = self.pageStep as? SBATrackedSelectionStep,
let trackedResultIdentifier = selectionStep.trackedResultIdentifier
else {
return nil
}
let trackingResult = SBATrackedDataSelectionResult(identifier: trackedResultIdentifier)
trackingResult.startDate = stepResult.startDate
trackingResult.endDate = stepResult.endDate
trackingResult.selectedItems = selectionStep.filterItems(resultSource: self.resultSource())
stepResult.addResult(trackingResult)
return stepResult
}
}
class SBATrackedSelectionFormStep: ORKFormStep, SBATrackedSelectionFilter, SBATrackedDataSelectedItemsProtocol {
let skipChoiceValue = "Skipped"
let noneChoiceValue = "None"
let choicesFormItemIdentifier = "choices"
// If this is an optional step, then building the form items will add a skip option
override var isOptional: Bool {
get {
return false
}
set (newValue) {
super.isOptional = newValue
}
}
init(surveyItem: SBAFormStepSurveyItem, items:[SBATrackedDataObject]) {
super.init(identifier: surveyItem.identifier)
surveyItem.mapStepValues(with: self)
// choices
var choices = items.map { (item) -> ORKTextChoice in
return item.createORKTextChoice()
}
// Add a choice for none of the above
let noneChoice = ORKTextChoice(text: Localization.localizedString("SBA_NONE_OF_THE_ABOVE"),
detailText: nil,
value: noneChoiceValue as NSString,
exclusive: true)
choices.append(noneChoice)
// If this is an optional step, then include a choice for skipping
if (super.isOptional) {
let skipChoice = ORKTextChoice(text: Localization.localizedString("SBA_SKIP_CHOICE"),
detailText: nil,
value: skipChoiceValue as NSString,
exclusive: true)
choices.append(skipChoice)
}
// setup the form items
let answerFormat = ORKTextChoiceAnswerFormat(style: .multipleChoice, textChoices: choices)
let formItem = ORKFormItem(identifier: choicesFormItemIdentifier, text: nil, answerFormat: answerFormat)
self.formItems = [formItem]
}
override init(identifier: String) {
super.init(identifier: identifier)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: SBATrackedDataSelectedItemsProtocol
@objc(stepResultWithSelectedItems:)
public func stepResult(selectedItems:[SBATrackedDataObject]?) -> ORKStepResult? {
guard let formItem = self.formItems?.first,
let choices = selectedItems?.map({$0.identifier})
else {
return self.defaultStepResult()
}
let answer: Any = (choices.count > 0) ? choices : noneChoiceValue
return stepResult(with: [formItem.identifier : answer] )
}
// MARK: SBATrackedSelectionFilter
var trackingType: SBATrackingStepType? {
return .selection
}
func filter(selectedItems items: [SBATrackedDataObject], stepResult: ORKStepResult) -> [SBATrackedDataObject]? {
// If the step result does not yet include the result of the step then just return all items
guard let choiceResult = stepResult.result(forIdentifier: choicesFormItemIdentifier) as? ORKChoiceQuestionResult else {
return items.map({ $0.copy() as! SBATrackedDataObject })
}
// If the selection was skipped then return nil
guard let choices = choiceResult.choiceAnswers as? [String] , choices != [skipChoiceValue] else {
return nil
}
// filter and map the results
return items.filter({ choices.contains($0.identifier) }).map({ $0.copy() as! SBATrackedDataObject })
}
}
class SBATrackedFrequencyFormStep: ORKFormStep, SBATrackedNavigationStep, SBATrackedSelectionFilter, SBATrackedDataSelectedItemsProtocol {
var frequencyAnswerFormat: ORKAnswerFormat?
init(surveyItem: SBAFormStepSurveyItem) {
super.init(identifier: surveyItem.identifier)
surveyItem.mapStepValues(with: self)
if let range = surveyItem as? SBANumberRange {
self.frequencyAnswerFormat = range.createAnswerFormat(with: .scale)
}
}
// MARK: SBATrackedNavigationStep
var trackingType: SBATrackingStepType? {
return .frequency
}
var shouldSkipStep: Bool {
return (self.formItems == nil) || (self.formItems!.count == 0)
}
func update(selectedItems:[SBATrackedDataObject]) {
self.formItems = selectedItems.filter({ $0.usesFrequencyRange }).map { (item) -> ORKFormItem in
return ORKFormItem(identifier: item.identifier, text: item.text, answerFormat: self.frequencyAnswerFormat)
}
}
func filter(selectedItems items: [SBATrackedDataObject], stepResult: ORKStepResult) -> [SBATrackedDataObject]? {
return items.map({ (item) -> SBATrackedDataObject in
let copy = item.copy() as! SBATrackedDataObject
if let scaleResult = stepResult.result(forIdentifier: item.identifier) as? ORKScaleQuestionResult,
let answer = scaleResult.scaleAnswer {
copy.frequency = answer.uintValue
}
return copy
})
}
// MARK: SBATrackedDataSelectedItemsProtocol
@objc(stepResultWithSelectedItems:)
public func stepResult(selectedItems:[SBATrackedDataObject]?) -> ORKStepResult? {
let results = selectedItems?.mapAndFilter({ (item) -> ORKScaleQuestionResult? in
guard item.usesFrequencyRange else { return nil }
let scaleResult = ORKScaleQuestionResult(identifier: item.identifier)
scaleResult.scaleAnswer = NSNumber(value: item.frequency)
return scaleResult
})
return ORKStepResult(stepIdentifier: self.identifier, results: results)
}
// MARK: NSCoding
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.frequencyAnswerFormat = aDecoder.decodeObject(forKey: #keyPath(frequencyAnswerFormat)) as? ORKAnswerFormat
}
override func encode(with aCoder: NSCoder){
super.encode(with: aCoder)
aCoder.encode(self.frequencyAnswerFormat, forKey: #keyPath(frequencyAnswerFormat))
}
// MARK: NSCopying
override init(identifier: String) {
super.init(identifier: identifier)
}
override func copy(with zone: NSZone? = nil) -> Any {
let copy = super.copy(with: zone) as! SBATrackedFrequencyFormStep
copy.frequencyAnswerFormat = self.frequencyAnswerFormat
return copy
}
// MARK: Equality
override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? SBATrackedFrequencyFormStep else { return false }
return super.isEqual(object) &&
SBAObjectEquality(object.frequencyAnswerFormat, self.frequencyAnswerFormat)
}
override var hash: Int {
return super.hash ^
SBAObjectHash(self.frequencyAnswerFormat)
}
}
| bsd-3-clause | 9f8529a6cf0e793f5e8b3290eaaedcac | 39.595078 | 138 | 0.645046 | 5.25514 | false | false | false | false |
huyouare/Emoji-Search-Keyboard | Keyboard/StringBuilder.swift | 1 | 2895 | //
// StringBuilder.swift
// EmojiSearchKeyboard
//
// Created by Oladimeji Abidoye on 1/19/15.
// Copyright (c) 2015 Apple. All rights reserved.
//
import Foundation
/**
Supports creation of a String from pieces
*/
public class StringBuilder {
private var stringValue: String
/**
Construct with initial String contents
:param: string Initial value; defaults to empty string
*/
public init(string: String = "") {
self.stringValue = string
}
/**
Return the String object
:return: String
*/
public func toString() -> String {
return stringValue
}
/**
Return the current length of the String object
*/
public var length: Int {
return countElements(stringValue)
}
/**
Append a String to the object
:param: string String
:return: reference to this StringBuilder instance
*/
public func append(string: String) -> StringBuilder {
stringValue += string
return self
}
/**
Append a Printable to the object
:param: value a value supporting the Printable protocol
:return: reference to this StringBuilder instance
*/
public func append<T: Printable>(value: T) -> StringBuilder {
stringValue += value.description
return self
}
/**
Append a String and a newline to the object
:param: string String
:return: reference to this StringBuilder instance
*/
public func appendLine(string: String) -> StringBuilder {
stringValue += string + "\n"
return self
}
/**
Append a Printable and a newline to the object
:param: value a value supporting the Printable protocol
:return: reference to this StringBuilder instance
*/
public func appendLine<T: Printable>(value: T) -> StringBuilder {
stringValue += value.description + "\n"
return self
}
/**
Reset the object to an empty string
:return: reference to this StringBuilder instance
*/
public func clear() -> StringBuilder {
stringValue = ""
return self
}
}
/**
Append a String to a StringBuilder using operator syntax
:param: lhs StringBuilder
:param: rhs String
*/
public func += (lhs: StringBuilder, rhs: String) {
lhs.append(rhs)
}
/**
Append a Printable to a StringBuilder using operator syntax
:param: lhs Printable
:param: rhs String
*/
public func += <T: Printable>(lhs: StringBuilder, rhs: T) {
lhs.append(rhs.description)
}
/**
Create a StringBuilder by concatenating the values of two StringBuilders
:param: lhs first StringBuilder
:param: rhs second StringBuilder
:result StringBuilder
*/
public func +(lhs: StringBuilder, rhs: StringBuilder) -> StringBuilder {
return StringBuilder(string: lhs.toString() + rhs.toString())
} | bsd-3-clause | 128b9bd9655aaf8be297deff78f72d2e | 20.939394 | 72 | 0.638687 | 4.699675 | false | false | false | false |
mrdepth/Neocom | Legacy/Neocom/Neocom/NCBugreportViewController.swift | 2 | 12869 | //
// NCBugreportViewController.swift
// Neocom
//
// Created by Artem Shimanski on 01.02.2018.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import EVEAPI
import Futures
class NCBugreportViewController: NCTreeViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.register([Prototype.NCDefaultTableViewCell.compact,
Prototype.NCHeaderTableViewCell.static])
}
override func content() -> Future<TreeNode?> {
let rows = [
DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.compact,
nodeIdentifier: "CharacterSheet",
image: #imageLiteral(resourceName: "charactersheet"),
title: NSLocalizedString("Character Sheet", comment: ""),
accessoryType: .disclosureIndicator,
route: Router.Custom { [weak self] _,_ in self?.reportCharacterSheet()}),
DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.compact,
nodeIdentifier: "Skills",
image: #imageLiteral(resourceName: "skills"),
title: NSLocalizedString("Skills", comment: ""),
accessoryType: .disclosureIndicator,
route: Router.Custom { [weak self] _,_ in self?.reportSkills()}),
DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.compact,
nodeIdentifier: "Assets",
image: #imageLiteral(resourceName: "assets"),
title: NSLocalizedString("Assets", comment: ""),
accessoryType: .disclosureIndicator,
route: Router.Custom { [weak self] _,_ in self?.reportAssets()}),
DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.compact,
nodeIdentifier: "MarketOrders",
image: #imageLiteral(resourceName: "marketdeliveries"),
title: NSLocalizedString("Market Orders", comment: ""),
accessoryType: .disclosureIndicator,
route: Router.Custom { [weak self] _,_ in self?.reportMarketOrders()}),
DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.compact,
nodeIdentifier: "IndustryJobs",
image: #imageLiteral(resourceName: "industry"),
title: NSLocalizedString("Industry Jobs", comment: ""),
accessoryType: .disclosureIndicator,
route: Router.Custom { [weak self] _,_ in self?.reportIndustryJobs()}),
DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.compact,
nodeIdentifier: "Planetaries",
image: #imageLiteral(resourceName: "planets"),
title: NSLocalizedString("Planetaries", comment: ""),
accessoryType: .disclosureIndicator,
route: Router.Custom { [weak self] _,_ in self?.reportPlanetaries()}),
DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.compact,
nodeIdentifier: "Fitting",
image: #imageLiteral(resourceName: "fitting"),
title: NSLocalizedString("Fitting", comment: ""),
accessoryType: .disclosureIndicator,
route: Router.Custom { [weak self] _,_ in self?.reportFitting()}),
// DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.compact,
// nodeIdentifier: "Database",
// image: #imageLiteral(resourceName: "items"),
// title: NSLocalizedString("Database", comment: ""),
// accessoryType: .disclosureIndicator,
// route: Router.Custom { [weak self] _,_ in self?.reportDatabase()}),
DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.compact,
nodeIdentifier: "Spelling",
image: #imageLiteral(resourceName: "notepad"),
title: NSLocalizedString("Spelling Error", comment: ""),
accessoryType: .disclosureIndicator,
route: Router.Custom { [weak self] _,_ in self?.reportSpelling()}),
DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.compact,
nodeIdentifier: "Ads",
image: #imageLiteral(resourceName: "votes"),
title: NSLocalizedString("Ads/Subscription", comment: ""),
accessoryType: .disclosureIndicator,
route: Router.Custom { [weak self] _,_ in self?.reportAds()}),
DefaultTreeRow(prototype: Prototype.NCDefaultTableViewCell.compact,
nodeIdentifier: "Other",
image: #imageLiteral(resourceName: "other"),
title: NSLocalizedString("Other", comment: ""),
accessoryType: .disclosureIndicator,
route: Router.Custom { [weak self] _,_ in self?.reportOther()}),
]
let root = DefaultTreeSection(prototype: Prototype.NCHeaderTableViewCell.static, nodeIdentifier: "Root", title: NSLocalizedString("What kind of problem is this?", comment: "").uppercased(), isExpandable: false, children: rows)
return .init(RootNode([root]))
}
lazy var encoder: JSONEncoder = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .formatted(dateFormatter)
return encoder
}()
func process<T: Codable> (result: NCCachedResult<T>) -> Data {
do {
switch result {
case let .success(value, _):
return try encoder.encode(value)
case let .failure(error):
throw error
}
}
catch {
guard let data = (error as CustomDebugStringConvertible).debugDescription.data(using: .utf8) ?? error.localizedDescription.data(using: .utf8) else {return "Unknown Error".data(using: .utf8)!}
return data
}
}
func process<T: Codable> (_ result: Future<CachedValue<T>>) -> Data {
do {
guard let value = try result.get().value else {throw NCDataManagerError.noCacheData}
return try encoder.encode(value)
}
catch {
guard let data = (error as CustomDebugStringConvertible).debugDescription.data(using: .utf8) ?? error.localizedDescription.data(using: .utf8) else {return "Unknown Error".data(using: .utf8)!}
return data
}
}
private func reportCharacterSheet() {
if let account = NCAccount.current {
let progress = NCProgressHandler(viewController: self, totalUnitCount: 3)
let dataManager = NCDataManager(account: account)
DispatchQueue.global(qos: .utility).async { () -> [String: Data] in
var attachments = [String: Data]()
attachments["character.json"] = self.process(progress.progress.perform { dataManager.character() })
attachments["clones.json"] = self.process(progress.progress.perform { dataManager.clones() })
attachments["characterLocation.json"] = self.process(progress.progress.perform { dataManager.characterLocation() })
return attachments
}.then(on: .main) { (attachments) in
progress.finish()
Router.MainMenu.BugReport.Finish(attachments: attachments, subject: "Character Sheet").perform(source: self, sender: nil)
}
}
else {
Router.MainMenu.BugReport.Finish(attachments: [:], subject: "Character Sheet").perform(source: self, sender: nil)
}
}
private func reportSkills() {
if let account = NCAccount.current {
let progress = NCProgressHandler(viewController: self, totalUnitCount: 2)
let dataManager = NCDataManager(account: account)
DispatchQueue.global(qos: .utility).async { () -> [String: Data] in
var attachments = [String: Data]()
attachments["skills.json"] = self.process(progress.progress.perform { dataManager.skills() })
attachments["skillQueue.json"] = self.process(progress.progress.perform { dataManager.skillQueue() })
return attachments
}.then(on: .main) { (attachments) in
progress.finish()
Router.MainMenu.BugReport.Finish(attachments: attachments, subject: "Skills").perform(source: self, sender: nil)
}
}
else {
Router.MainMenu.BugReport.Finish(attachments: [:], subject: "Skills").perform(source: self, sender: nil)
}
}
private func reportAssets() {
if let account = NCAccount.current {
let progress = NCProgressHandler(viewController: self, totalUnitCount: 1)
let dataManager = NCDataManager(account: account)
DispatchQueue.global(qos: .utility).async { () -> [String: Data] in
var attachments = [String: Data]()
for i in 1...20 {
let assets = progress.progress.perform { dataManager.assets(page: i) }
guard (try? assets.get())?.value?.isEmpty == false else {break}
attachments["assetsPage\(i).json"] = self.process(assets)
}
return attachments
}.then(on: .main) { (attachments) in
progress.finish()
Router.MainMenu.BugReport.Finish(attachments: attachments, subject: "Assets").perform(source: self, sender: nil)
}
}
else {
Router.MainMenu.BugReport.Finish(attachments: [:], subject: "Assets").perform(source: self, sender: nil)
}
}
private func reportMarketOrders() {
if let account = NCAccount.current {
let progress = NCProgressHandler(viewController: self, totalUnitCount: 1)
let dataManager = NCDataManager(account: account)
DispatchQueue.global(qos: .utility).async { () -> [String: Data] in
var attachments = [String: Data]()
attachments["marketOrders.json"] = self.process(progress.progress.perform { dataManager.marketOrders() })
return attachments
}.then(on: .main) { (attachments) in
progress.finish()
Router.MainMenu.BugReport.Finish(attachments: attachments, subject: "Market Orders").perform(source: self, sender: nil)
}
}
else {
Router.MainMenu.BugReport.Finish(attachments: [:], subject: "Market Orders").perform(source: self, sender: nil)
}
}
private func reportIndustryJobs() {
if let account = NCAccount.current {
let progress = NCProgressHandler(viewController: self, totalUnitCount: 1)
let dataManager = NCDataManager(account: account)
DispatchQueue.global(qos: .utility).async { () -> [String: Data] in
var attachments = [String: Data]()
attachments["industryJobs.json"] = self.process(progress.progress.perform { dataManager.industryJobs() })
return attachments
}.then(on: .main) { (attachments) in
progress.finish()
Router.MainMenu.BugReport.Finish(attachments: attachments, subject: "Industry Jobs").perform(source: self, sender: nil)
}
}
else {
Router.MainMenu.BugReport.Finish(attachments: [:], subject: "Industry Jobs").perform(source: self, sender: nil)
}
}
private func reportPlanetaries() {
if let account = NCAccount.current {
let progress = NCProgressHandler(viewController: self, totalUnitCount: 2)
let dataManager = NCDataManager(account: account)
DispatchQueue.global(qos: .utility).async { () -> [String: Data] in
var attachments = [String: Data]()
let colonies = progress.progress.perform { dataManager.colonies() }
attachments["colonies.json"] = self.process(colonies)
if let value = (try? colonies.get())?.value {
progress.progress.perform {
let progress = Progress(totalUnitCount: Int64(value.count))
for colony in value {
attachments["colony\(colony.planetID).json"] = self.process(progress.perform { dataManager.colonyLayout(planetID: colony.planetID) })
}
}
}
return attachments
}.then(on: .main) { (attachments) in
progress.finish()
Router.MainMenu.BugReport.Finish(attachments: attachments, subject: "Planetaries").perform(source: self, sender: nil)
}
}
else {
Router.MainMenu.BugReport.Finish(attachments: [:], subject: "Planetaries").perform(source: self, sender: nil)
}
}
private func reportFitting() {
Router.Mail.Attachments { [weak self] (controller, loadout) in
controller.dismiss(animated: true, completion: nil)
guard let strongSelf = self else {return}
guard let loadout = loadout as? NCLoadout else {return}
guard let data = loadout.data?.data else {return}
guard let typeName = NCDatabase.sharedDatabase?.invTypes[Int(loadout.typeID)]?.typeName else {return}
guard let eft = (NCLoadoutRepresentation.eft([(typeID: Int(loadout.typeID), data: data, name: typeName)]).value as? [String])?.first else {return}
guard let eftData = eft.data(using: .utf8) else {return}
Router.MainMenu.BugReport.Finish(attachments: ["\(typeName).cfg": eftData], subject: "Fitting").perform(source: strongSelf, sender: nil)
}.perform(source: self, sender: nil)
}
private func reportSpelling() {
Router.MainMenu.BugReport.Finish(attachments: [:], subject: "Spelling Error").perform(source: self, sender: nil)
}
private func reportAds() {
if let url = Bundle.main.appStoreReceiptURL, let data = try? Data(contentsOf: url) {
Router.MainMenu.BugReport.Finish(attachments: [url.lastPathComponent: data], subject: "Ads/Subscription").perform(source: self, sender: nil)
}
else {
Router.MainMenu.BugReport.Finish(attachments: [:], subject: "Ads/Subscription").perform(source: self, sender: nil)
}
}
private func reportOther() {
Router.MainMenu.BugReport.Finish(attachments: [:], subject: "Other").perform(source: self, sender: nil)
}
}
| lgpl-2.1 | 4db46cf8d4a5ef4ffe3dc4ee88e1a31d | 40.779221 | 228 | 0.69428 | 4.127004 | false | false | false | false |
adrfer/swift | test/1_stdlib/Inputs/PrintTestTypes.swift | 10 | 2751 | public protocol ProtocolUnrelatedToPrinting {}
public struct StructPrintable : CustomStringConvertible,
ProtocolUnrelatedToPrinting {
let x: Int
public init(_ x: Int) {
self.x = x
}
public var description: String {
return "►\(x)◀︎"
}
}
public struct LargeStructPrintable : CustomStringConvertible,
ProtocolUnrelatedToPrinting {
let a: Int
let b: Int
let c: Int
let d: Int
public init(_ a: Int, _ b: Int, _ c: Int, _ d: Int) {
self.a = a
self.b = b
self.c = c
self.d = d
}
public var description: String {
return "<\(a) \(b) \(c) \(d)>"
}
}
public struct StructDebugPrintable : CustomDebugStringConvertible {
let x: Int
public init(_ x: Int) {
self.x = x
}
public var debugDescription: String {
return "►\(x)◀︎"
}
}
public struct StructVeryPrintable : CustomStringConvertible,
CustomDebugStringConvertible, ProtocolUnrelatedToPrinting {
let x: Int
public init(_ x: Int) {
self.x = x
}
public var description: String {
return "<description: \(x)>"
}
public var debugDescription: String {
return "<debugDescription: \(x)>"
}
}
public struct EmptyStructWithoutDescription {
public init() {}
}
public struct WithoutDescription {
let x: Int
public init(_ x: Int) {
self.x = x
}
}
public struct ValuesWithoutDescription<T, U, V> {
let t: T
let u: U
let v: V
public init(_ t: T, _ u: U, _ v: V) {
self.t = t
self.u = u
self.v = v
}
}
public class ClassPrintable : CustomStringConvertible,
ProtocolUnrelatedToPrinting {
let x: Int
public init(_ x: Int) {
self.x = x
}
public var description: String {
return "►\(x)◀︎"
}
}
public class ClassVeryPrintable : CustomStringConvertible,
CustomDebugStringConvertible, ProtocolUnrelatedToPrinting {
let x: Int
public init(_ x: Int) {
self.x = x
}
public var description: String {
return "<description: \(x)>"
}
public var debugDescription: String {
return "<debugDescription: \(x)>"
}
}
public struct MyString : StringLiteralConvertible,
StringInterpolationConvertible {
public init(str: String) {
value = str
}
public var value: String
public init(unicodeScalarLiteral value: String) {
self.init(str: value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(str: value)
}
public init(stringLiteral value: String) {
self.init(str: value)
}
public init(stringInterpolation strings: MyString...) {
var result = ""
for s in strings {
result += s.value
}
self.init(str: result)
}
public init<T>(stringInterpolationSegment expr: T) {
self.init(str: "<segment " + String(expr) + ">")
}
}
| apache-2.0 | 60ecc8a2bd28a113762aa53ae160b3d8 | 16.407643 | 67 | 0.642517 | 3.806407 | false | false | false | false |
yichizhang/YZBasicCells | BasicCells-Source/YZCollectionCollectionViewCell.swift | 1 | 4277 | /*
Copyright (c) 2015 Yichi Zhang
https://github.com/yichizhang
[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
/// This class is meant to be an 'abstract class'
class YZCollectionCollectionViewCell: UICollectionViewCell, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var registerClasses:((UICollectionView) -> Void)?
var numberOfSections:((Void) -> Int)?
var numberOfItemsInSection:((Int) -> Int)!
var cellForItemAtIndexPath:((UICollectionView, NSIndexPath) -> UICollectionViewCell)!
var sizeForItemAtIndexPath:((UICollectionView, NSIndexPath) -> CGSize)?
var didSelectItemAtIndexPath:((NSIndexPath) -> Void)?
var insetForSectionAtIndex:((Int) -> UIEdgeInsets)?
var minimumInteritemSpacingForSectionAtIndex:((Int) -> CGFloat)?
var minimumLineSpacingForSectionAtIndex:((Int) -> CGFloat)?
override func awakeFromNib() {
super.awakeFromNib()
}
func cellCollectionView() -> UICollectionView{
return UICollectionView()
}
func reloadData(){
self.registerClasses?(self.cellCollectionView())
self.cellCollectionView().delegate = self
self.cellCollectionView().dataSource = self
self.cellCollectionView().reloadData()
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
if (self.numberOfSections == nil){
return 0
}else{
return self.numberOfSections!()
}
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.numberOfItemsInSection(section)
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
return self.cellForItemAtIndexPath(self.cellCollectionView(), indexPath)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
if (self.sizeForItemAtIndexPath == nil){
let h = self.cellCollectionView().bounds.height;
return CGSizeMake(h, h)
}else{
return self.sizeForItemAtIndexPath!(self.cellCollectionView(), indexPath)
}
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.didSelectItemAtIndexPath?(indexPath)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
if (self.insetForSectionAtIndex == nil){
return UIEdgeInsetsZero
}else{
return self.insetForSectionAtIndex!(section)
}
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
if (self.minimumInteritemSpacingForSectionAtIndex == nil){
return 0
}else{
return self.minimumInteritemSpacingForSectionAtIndex!(section)
}
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
if (self.minimumLineSpacingForSectionAtIndex == nil){
return 0
}else{
return self.minimumLineSpacingForSectionAtIndex!(section)
}
}
}
| mit | f6de1ddfb53b74534d20a9106e6a3d3d | 40.125 | 461 | 0.785364 | 5.165459 | false | false | false | false |
pushian/YFCalendar | YFCalendar/Classes/YFCalendarDataType.swift | 1 | 880 |
import UIKit
public enum ShapeType {
case CircleWithFill
case UnselectedDotMarks
case SelectedDotMarks
case TopLine
}
@objc public enum DateType: Int {
case InsideCurrentMonth = 1
case OutsideCurrentMonth = 2
case Today = 3
}
@objc public enum DateState: Int {
case Selected = 0
case Noselected = 1
}
@objc public enum SelectionMode: Int {
case Single = 1
case Multiple = 2
}
@objc public enum CalendarScrollDirection: Int {
case Vertical = 1
case Horizontal = 2
}
public struct DotedDate {
var date: NSDate?
var dotColors: [UIColor]?
func equalsTo(object: DotedDate) -> Bool {
return self.date == object.date
}
}
public enum DayName: Int {
case Sunday = 0
case Monday = 1
case Tuesday = 2
case Wednesday = 3
case Thursday = 4
case Friday = 5
case Saturday = 6
}
| mit | 0a520f7bf6c9da568d92576141ac53ab | 16.959184 | 48 | 0.65 | 3.826087 | false | false | false | false |
xixijiushui/douyu | douyu/douyu/Classes/Home/Controller/RecommendViewController.swift | 1 | 5827 | //
// RecommendViewController.swift
// douyu
//
// Created by 赵伟 on 2016/11/8.
// Copyright © 2016年 赵伟. All rights reserved.
//
import UIKit
private let kItemMargin : CGFloat = 10
private let kHeaderViewH : CGFloat = 50
private let kItemW : CGFloat = (kScreenW - 3 * kItemMargin) / 2
private let kNormalItemH : CGFloat = kItemW * 3 / 4
private let kPrettyItemH : CGFloat = kItemW * 4 / 3
private let kCycleViewH = kScreenW * 3 / 8
private let kGameViewH : CGFloat = 90
private let kNormalCellID : String = "kNormalCellID"
private let kPrettyCellID : String = "kPrettyCellID"
private let kHeadViewID : String = "kHeadViewID"
class RecommendViewController: UIViewController {
private lazy var recommendVM : RecommendViewModel = RecommendViewModel()
private lazy var collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSizeMake(kItemW, kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSizeMake(kScreenW, kHeaderViewH)
layout.sectionInset = UIEdgeInsetsMake(0, kItemMargin, 0, kItemMargin)
let collectionView : UICollectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.whiteColor()
collectionView.dataSource = self
collectionView.delegate = self
collectionView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
collectionView.registerNib(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.registerNib(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
collectionView.registerNib(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeadViewID)
return collectionView
}()
private lazy var cycleView : RecommendCycleView = {
let cycleView = RecommendCycleView.recommendCycleView()
cycleView.frame = CGRectMake(0, -kCycleViewH - kGameViewH, kScreenW, kCycleViewH)
return cycleView
}()
private lazy var gameView : RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH)
return gameView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
extension RecommendViewController {
private func setupUI() {
view.addSubview(collectionView)
collectionView.addSubview(cycleView)
collectionView.addSubview(gameView)
//设置内边距
collectionView.contentInset = UIEdgeInsetsMake(kCycleViewH + kGameViewH, 0, 0, 0)
}
private func loadData() {
recommendVM.requestData {
self.collectionView.reloadData()
// 2.将数据传递给GameView
var groups = self.recommendVM.anchorGroups
// 2.1.移除前两组数据
groups.removeFirst()
groups.removeFirst()
// 2.2.添加更多组
let moreGroup = AnchorGroup()
moreGroup.tag_name = "更多"
groups.append(moreGroup)
self.gameView.groups = groups
}
// 2.请求轮播数据
recommendVM.requestCycleData {
self.cycleView.cycleModels = self.recommendVM.cycleModels
}
}
}
extension RecommendViewController : UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return recommendVM.anchorGroups.count
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let group = recommendVM.anchorGroups[section]
return group.anchors.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let group = recommendVM.anchorGroups[indexPath.section]
let anchor = group.anchors[indexPath.item]
var cell : CollectionBaseCell!
if indexPath.section == 1 {
cell = collectionView.dequeueReusableCellWithReuseIdentifier(kPrettyCellID, forIndexPath: indexPath) as! CollectionPrettyCell
} else {
cell = collectionView.dequeueReusableCellWithReuseIdentifier(kNormalCellID, forIndexPath: indexPath) as! CollectionNormalCell
}
cell.anchor = anchor
return cell
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
// 1.取出HeaderView
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: kHeadViewID, forIndexPath: indexPath) as! CollectionHeaderView
// 取出模型
headerView.group = recommendVM.anchorGroups[indexPath.section]
return headerView
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kItemW, height: kPrettyItemH)
}
return CGSize(width: kItemW, height: kNormalItemH)
}
}
| mit | fdf013791d49ed85f4b8d08448a78277 | 34.226994 | 187 | 0.680773 | 6.037855 | false | false | false | false |
insidegui/WWDC | WWDC/EventHeroViewController.swift | 1 | 6763 | //
// ScheduleUnavailableViewController.swift
// WWDC
//
// Created by Guilherme Rambo on 28/05/20.
// Copyright © 2020 Guilherme Rambo. All rights reserved.
//
import Cocoa
import ConfCore
import RxSwift
import RxCocoa
public final class EventHeroViewController: NSViewController {
private(set) var hero = BehaviorRelay<EventHero?>(value: nil)
private lazy var backgroundImageView: FullBleedImageView = {
let v = FullBleedImageView()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
private lazy var placeholderImageView: FullBleedImageView = {
let v = FullBleedImageView()
v.translatesAutoresizingMaskIntoConstraints = false
v.image = NSImage(named: .init("schedule-placeholder"))
return v
}()
private func makeShadow() -> NSShadow {
let shadow = NSShadow()
shadow.shadowBlurRadius = 1
shadow.shadowColor = NSColor.black.withAlphaComponent(0.7)
shadow.shadowOffset = NSSize(width: 1, height: 1)
return shadow
}
private lazy var titleLabel: NSTextField = {
let l = NSTextField(wrappingLabelWithString: "")
l.font = .boldTitleFont
l.textColor = .primaryText
l.alignment = .center
l.shadow = makeShadow()
return l
}()
private lazy var bodyLabel: NSTextField = {
let l = NSTextField(wrappingLabelWithString: "")
l.font = NSFont.systemFont(ofSize: 14)
l.textColor = .secondaryText
l.alignment = .center
l.shadow = makeShadow()
return l
}()
private lazy var scrollView: NSScrollView = {
let v = NSScrollView()
v.contentView = FlippedClipView()
v.drawsBackground = false
v.backgroundColor = .clear
v.borderType = .noBorder
v.documentView = self.textStack
v.autohidesScrollers = true
v.translatesAutoresizingMaskIntoConstraints = false
v.automaticallyAdjustsContentInsets = false
v.contentInsets = NSEdgeInsets(top: 120, left: 0, bottom: 0, right: 0)
return v
}()
private lazy var textStack: NSStackView = {
let v = NSStackView(views: [titleLabel, bodyLabel])
v.translatesAutoresizingMaskIntoConstraints = false
v.orientation = .vertical
v.spacing = 12
return v
}()
public override func loadView() {
view = NSView()
view.wantsLayer = true
view.addSubview(placeholderImageView)
NSLayoutConstraint.activate([
placeholderImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
placeholderImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
placeholderImageView.topAnchor.constraint(equalTo: view.topAnchor),
placeholderImageView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
view.addSubview(backgroundImageView)
NSLayoutConstraint.activate([
backgroundImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
backgroundImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
backgroundImageView.topAnchor.constraint(equalTo: view.topAnchor),
backgroundImageView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
view.addSubview(scrollView)
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: view.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
scrollView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
scrollView.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: 220),
scrollView.trailingAnchor.constraint(greaterThanOrEqualTo: view.trailingAnchor, constant: -220)
])
NSLayoutConstraint.activate([
textStack.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
textStack.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
textStack.topAnchor.constraint(equalTo: scrollView.topAnchor),
textStack.widthAnchor.constraint(equalTo: scrollView.widthAnchor),
textStack.heightAnchor.constraint(equalTo: scrollView.heightAnchor)
])
}
public override func viewDidLoad() {
super.viewDidLoad()
bindViews()
}
private var imageDownloadOperation: Operation?
private let disposeBag = DisposeBag()
private func bindViews() {
let image = hero.compactMap({ $0?.backgroundImage }).compactMap(URL.init)
image.distinctUntilChanged().subscribe(onNext: { [weak self] imageUrl in
guard let self = self else { return }
self.imageDownloadOperation?.cancel()
self.imageDownloadOperation = ImageDownloadCenter.shared.downloadImage(from: imageUrl, thumbnailHeight: Constants.thumbnailHeight) { url, result in
guard url == imageUrl, result.original != nil else { return }
self.backgroundImageView.image = result.original
}
}).disposed(by: disposeBag)
let heroUnavailable = hero.map({ $0 == nil })
heroUnavailable.bind(to: backgroundImageView.rx.isHidden).disposed(by: disposeBag)
heroUnavailable.map({ !$0 }).bind(to: placeholderImageView.rx.isHidden).disposed(by: disposeBag)
hero.map({ $0?.title ?? "Schedule not available" }).bind(to: titleLabel.rx.text).disposed(by: disposeBag)
hero.map({ hero in
let unavailable = "The schedule is not currently available. Check back later."
guard let hero = hero else { return unavailable }
if hero.textComponents.isEmpty {
return hero.body
} else {
return hero.textComponents.joined(separator: "\n\n")
}
}).bind(to: bodyLabel.rx.text).disposed(by: disposeBag)
hero.compactMap({ $0?.titleColor }).subscribe(onNext: { [weak self] colorHex in
guard let self = self else { return }
self.titleLabel.textColor = NSColor.fromHexString(hexString: colorHex)
}).disposed(by: disposeBag)
// Dim background when there's a lot of text to show
hero.compactMap({ $0 }).map({ $0.textComponents.count > 2 }).subscribe(onNext: { [weak self] largeText in
self?.backgroundImageView.alphaValue = 0.5
}).disposed(by: disposeBag)
hero.compactMap({ $0?.bodyColor }).subscribe(onNext: { [weak self] colorHex in
guard let self = self else { return }
self.bodyLabel.textColor = NSColor.fromHexString(hexString: colorHex)
}).disposed(by: disposeBag)
}
}
| bsd-2-clause | c6f222f1d9b1de10b979a3991cd4267f | 34.589474 | 159 | 0.658681 | 5.122727 | false | false | false | false |
arvedviehweger/swift | test/Migrator/Inputs/minimal_objc_inference.swift | 1 | 615 | import Foundation
class MyClass : NSObject {
var propertyUsedInKeyPath : NSObject? = nil
dynamic var dynamicVarUsedInSelector : Int { return 2 }
func overridden() {}
func usedViaAnyObject() {}
func unused() {}
}
extension MyClass {
func inExtensionAndOverridden() {}
}
class MySubClass : MyClass {
override func overridden() {}
override func inExtensionAndOverridden() {}
}
func test(object: AnyObject, mine: MyClass) {
_ = #selector(MyClass.overridden)
_ = #selector(getter: MyClass.dynamicVarUsedInSelector)
_ = #keyPath(MyClass.propertyUsedInKeyPath)
_ = object.usedViaAnyObject?()
}
| apache-2.0 | 8319720a87de5a866e8e8e6e89fdb297 | 23.6 | 57 | 0.721951 | 3.993506 | false | false | false | false |
corderoi/Microblast | Microblast/GameViewController.swift | 1 | 12695 | //
// GameViewController.swift
// Microblast
//
// Created by Ian Cordero on 11/12/14.
// Copyright (c) 2014 Ian Cordero. All rights reserved.
//
import UIKit
import SpriteKit
import AVFoundation
import CoreMotion
class GameViewController: UIViewController, GameDelegate
{
var scene: GameScene!
var game: Game!
var acceptUserInput = false
var touchDown: NSDate? = nil
var touchDuration = 0
var previewViewLabelText = ["", "", "", ""]
let motionManager: CMMotionManager = CMMotionManager()
var previewTicks = 0
var time = 0.0
@IBOutlet weak var previewView: UIView! // does the job
@IBOutlet weak var previewViewLabel1: UILabel!
@IBOutlet weak var previewViewLabel2: UILabel!
@IBOutlet weak var previewViewLabel3: UILabel!
@IBOutlet weak var previewViewLabel4: UILabel!
@IBOutlet weak var statusBarView: UIView!
@IBOutlet weak var levelNumberDisplay: UILabel!
@IBOutlet weak var scoreNumberDisplay: UILabel!
@IBOutlet weak var specialNameDisplay: UILabel!
var backgroundMusicPlayer: AVAudioPlayer!
override func viewDidLoad()
{
super.viewDidLoad()
createGame()
startTitleScreen()
startPreviewScreen()
}
func createGame()
{
game = Game()
game.delegate = self
}
func startTitleScreen()
{
let skView = view as SKView
// DEBUG
//skView.showsFPS = true
//skView.showsDrawCount = true
//skView.showsNodeCount = true
}
func startPreviewScreen()
{
let skView = view as SKView
// DEBUG
//skView.showsFPS = false
//skView.showsDrawCount = false
//skView.showsNodeCount = false
skView.ignoresSiblingOrder = true
skView.multipleTouchEnabled = false
let previewScene = PreviewScene(size: skView.bounds.size, labels: [previewViewLabel1, previewViewLabel2, previewViewLabel3, previewViewLabel4], callback: startGameScreen)
previewScene.scaleMode = .ResizeFill
previewView.hidden = false
playBackgroundMusic()
skView.presentScene(previewScene)
}
func startGameScreen()
{
// Start game scene
let skView = view as SKView
// DEBUG
//skView.showsFPS = false
//skView.showsDrawCount = false
//skView.showsNodeCount = false
//skView.ignoresSiblingOrder = true
skView.multipleTouchEnabled = false
scene = GameScene(size: skView.bounds.size)
scene.scaleMode = .ResizeFill
scene.tick = didTick
scene.frameTick = didFrameTick
scene.startMusic = playBackgroundMusic
scene.stopMusic = stopBackgroundMusic
scene.startTicking()
scene.collisionHappened = game.field.resultOfCollision
startNewCampaign()
motionManager.startAccelerometerUpdates()
skView.presentScene(scene, transition: SKTransition.crossFadeWithDuration(0.5))
}
func startNewCampaign()
{
scene.setUpCampaign()
startGame()
}
func startGame()
{
acceptUserInput = true
statusBarView.hidden = false
previewView.hidden = true
previewTicks = 0
previewIsDone(game)
game.start()
}
func gameDidEnd()
{
statusBarView.hidden = true
acceptUserInput = false
game.hasStarted = false
game.score = 0
game.level = 0
scoreDidUpdate(game)
levelDidUpdate(game)
game.energy = [Energy]()
previewViewLabel1.text = ""
previewViewLabel2.text = ""
previewViewLabel3.text = ""
previewViewLabel4.text = ""
createGame()
startPreviewScreen()
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent)
{
if !acceptUserInput
{
return
}
if !game.hasStarted
{
return
}
else
{
touchDown = NSDate()
let touch = touches.anyObject() as UITouch
let touchLocation = touch.locationInNode(scene)
if touchLocation.x > view.bounds.size.width - PauseButtonSize.width && touchLocation.y > view.bounds.size.height - PauseButtonSize.height
{
touchDown = nil
if !scene.paused {
statusBarView.alpha = 0.3
scene.pauseScene()
scene.stopTicking()
backgroundMusicPlayer.volume = 0.25
}
else
{
backgroundMusicPlayer.volume = 1.0
scene.unpauseScene()
statusBarView.alpha = 0.75
scene.startTicking()
}
}
}
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent)
{
if !acceptUserInput || !game.hasStarted
{
return
}
if touchDown == nil
{
return
}
touchDown = nil
let myTouchDuration = touchDuration
touchDuration = 0
game.charge = 0
chargeDidUpdate(game)
if myTouchDuration >= PowerThreshold
{
if let player = game.field.player
{
if player.hasSpecial()
{
player.trySpecial()
game.energy = [Energy]()
energyDidUpdate(game)
return
}
}
}
if let player = game.field.player
{
player.tryShoot()
}
}
override func prefersStatusBarHidden() -> Bool
{
return true
}
func didFrameTick()
{
if !acceptUserInput || !game.hasStarted
{
return
}
game.field.moveProjectiles()
// Move player
if let player = game.field.player {
if let data = motionManager.accelerometerData
{
player.move(data.acceleration.x)
}
else
{
// Uncomment for sample sinusoidal movement when no accelerometer
// data is available
//let sampleData = sin(time++ / 10.0) / 2.0
//player.move(sampleData)
}
}
// Charge power
if touchDown != nil
{
touchDuration++
game.charge++
chargeDidUpdate(game)
}
}
func didTick()
{
if !game.hasStarted
{
return
}
else
{
game.field.moveViruses()
game.field.tryVirusAttack()
game.checkIfLevelIsOver()
}
}
func previewIsDone(game: Game)
{
scene.dissolvePreview(game)
}
func playerDidAppear(game: Game, player: WhiteBloodCell)
{
scene.addPlayer(game, player: player)
}
func playerDidMove(game: Game, player: WhiteBloodCell)
{
scene.redrawPlayer(game, player: player)
}
func playerDidShoot(type: AntibodyType)
{
switch type
{
case AntibodyType.Special1:
scene.playSound("special.wav")
default:
scene.playSound("laser.wav")
}
}
func playerDidDie(game: Game)
{
var offset = 0
for i in 0 ..< game.field.player!.antibodies.count {
scene.removeAntibody(i - offset++)
}
scene.removePlayer(game.continueLevel)
game.field.removePlayer()
}
func antibodyDidAppear(game: Game, antibody: Antibody)
{
scene.addAntibody(antibody)
}
func antibodiesDidMove(game: Game)
{
scene.redrawAntibodies(game)
}
func antibodyDidDie(whichAntibody: Int)
{
scene.removeAntibody(whichAntibody)
}
func virusDidAppear(game: Game, virus: Virus, afterTransition: (() -> ()))
{
scene.addVirus(game, virus: virus, completion: afterTransition)
}
func virusesDidMove(game: Game)
{
scene.redrawViruses(game)
}
func virusesDidDescend(game: Game)
{
scene.redrawViruses(game, descended: true)
}
func virusReachedBottomOfField(game: Game)
{
// DEBUG
println("Game over!")
scene.stopTicking()
}
func virusReachedEdgeOfField(game: Game)
{
}
func virusDidDie(game: Game, whichVirus: Int)
{
scene.removeVirus(game, whichVirus: whichVirus)
// (Number of viruses left, index to access in [SpeedConfig])
let stageProgression = [
(1, 4), (2, 3), (game.field.startingCount / 4, 2), (game.field.startingCount / 2, 1)
]
if game.field.viruses.count == 0
{
playerDidKillAllViruses(game)
game.stage = 0
}
else
{
for (limit, stage) in stageProgression
{
if game.field.viruses.count == limit
{
scene.tickLengthMillis = SpeedConfig[stage].tickLength
scene.virusMoveDuration = SpeedConfig[stage].moveDuration
game.field.step = SpeedConfig[stage].step
game.field.virusAnimationSpeed = SpeedConfig[stage].virusAnimationSpeed
break
}
}
}
}
func antigenDidAppear(virus: Virus, antigen: Antigen)
{
scene.addAntigen(virus, antigen: antigen)
}
func antigensDidMove(game: Game)
{
scene.redrawAntigens(game)
}
func antigenDidDie(whichVirus: Int, whichAntigen: Int)
{
scene.removeAntigens(whichVirus, whichAntigen: whichAntigen)
}
func antigenDidExplode()
{
scene.playSound("boom.wav")
}
func playerDidKillAllViruses(game: Game)
{
scene.endOfLevel(game)
}
func levelDidEnd(game: Game, transition: (() -> ()))
{
scene.stopSpacedTicks()
scene.tickLengthMillis = SpeedConfig[0].tickLength
scene.virusMoveDuration = SpeedConfig[0].moveDuration
game.field.step = SpeedConfig[0].step
game.field.virusAnimationSpeed = SpeedConfig[0].virusAnimationSpeed
scene.levelTransition(game, transition)
}
func levelDidBegin(game: Game)
{
scene.startSpacedTicks()
}
func levelDidUpdate(game: Game)
{
levelNumberDisplay.text = "\(game.level+1)"
}
func scoreDidUpdate(game: Game)
{
scoreNumberDisplay.text = "\(game.score)"
}
func energyDidUpdate(game: Game)
{
if game.energy.count == 4
{
switch game.energy[0]
{
case .RedEnergy:
specialNameDisplay.text = "Piercing Shot"
case Energy.BlueEnergy:
specialNameDisplay.text = "Left Hook Shot"
case .GreenEnergy:
specialNameDisplay.text = "Right Hook Shot"
case .GoldEnergy:
specialNameDisplay.text = "Diagonal Burst"
default:
break
}
}
else
{
specialNameDisplay.text = ""
}
scene.redrawEnergy(game)
}
func chargeDidUpdate(game: Game)
{
scene.redrawCharge(game)
}
func playBackgroundMusic()
{
let filename = "theme.mp3"
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
if (url == nil)
{
println("Could not find file: \(filename)")
return
}
var error: NSError? = nil
backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
if backgroundMusicPlayer == nil
{
println("Could not create audio player: \(error!)")
return
}
backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
}
func stopBackgroundMusic()
{
backgroundMusicPlayer = nil
}
} | mit | d6e4c33e50a26ad5dc1f807040bc9f5a | 24.341317 | 178 | 0.539346 | 4.935848 | false | false | false | false |
kallahir/AlbumTrackr-iOS | AlbumTracker/FeedCell.swift | 1 | 1520 | //
// FeedCell.swift
// AlbumTracker
//
// Created by Itallo Rossi Lucas on 4/17/16.
// Copyright © 2016 AlbumTrackr. All rights reserved.
//
import UIKit
class FeedCell: UITableViewCell {
@IBOutlet weak var feedView: UIView!
@IBOutlet weak var feedImage: UIImageView!
@IBOutlet weak var artistName: UILabel!
@IBOutlet weak var releaseInfo: UILabel!
@IBOutlet weak var feedHeaderView: UIView!
@IBOutlet weak var releaseTypeImage: UIImageView!
@IBOutlet weak var releaseDate: UILabel!
@IBOutlet weak var releaseType: UILabel!
override func layoutSubviews() {
self.setupFeedArea()
self.setupImage()
self.setupFeedHeader()
}
func setupFeedArea(){
self.feedView.alpha = 1.0
self.feedView.layer.masksToBounds = false
self.feedView.layer.cornerRadius = 3.0
self.feedView.layer.shadowOffset = CGSizeMake(-0.1, 0.1)
self.feedView.layer.shadowRadius = 0.5
self.feedView.layer.borderWidth = 0.5
self.feedView.layer.borderColor = UIColor.lightGrayColor().CGColor
}
func setupImage(){
self.feedImage.layer.cornerRadius = 2.0;
self.feedImage.clipsToBounds = true;
}
func setupFeedHeader(){
self.feedHeaderView.layer.masksToBounds = false
self.feedHeaderView.layer.borderWidth = 0.5
self.feedHeaderView.layer.cornerRadius = 3.0
self.feedHeaderView.layer.borderColor = UIColor.lightGrayColor().CGColor
}
}
| agpl-3.0 | dace98e54f57834a11bbe2c81592c796 | 29.38 | 80 | 0.670178 | 4.173077 | false | false | false | false |
bluesnap/bluesnap-ios | BluesnapSDK/BluesnapSDK/BSCcInputLine.swift | 1 | 38137 | //
// BSCcInputLine.swift
// BluesnapSDK
//
// Created by Shevie Chen on 22/05/2017.
// Copyright © 2017 Bluesnap. All rights reserved.
//
import UIKit
/**
This protocol should be implemented by the view which owns the BSCcInputLine control; Although the component's functionality is sort-of self-sufficient, we still have some calls to the parent
*/
public protocol BSCcInputLineDelegate: class {
/**
startEditCreditCard is called when we switch to the 'open' state of the component
*/
func startEditCreditCard()
/**
startEditCreditCard is called when we switch to the 'closed' state of the component
*/
func endEditCreditCard()
/**
willCheckCreditCard is called just before calling the BlueSnap server to validate the CCN; since this is a longish asynchronous action, you may want to disable some functionality
*/
func willCheckCreditCard()
/**
didCheckCreditCard is called just after getting the BlueSnap server result; this is where you hide the activity indicator.
The card type, issuing country etc will be filled in the creditCard if the error is nil, so check the error first.
*/
func didCheckCreditCard(creditCard: BSCreditCard, error: BSErrors?)
/**
didSubmitCreditCard is called at the end of submitPaymentFields() to let the owner know of the submit result; The card type, issuing country etc will be filled in the creditCard if the error is nil, so check the error first.
*/
func didSubmitCreditCard(creditCard: BSCreditCard, error: BSErrors?)
/**
showAlert is called in case of unexpected errors from the BlueSnap server.
*/
func showAlert(_ message: String)
}
/**
BSCcInputLine is a Custom control for CC details input (Credit Card number, expiration date and CVV).
It inherits configurable properties from BSBaseTextInput that let you adjust the look&feel and adds some.
[We use BSBaseTextInput for the CCN field and image,and add fields for EXP and CVV.]
The control has 2 states:
* Open: when we edit the CC number, the field gets longer, EXP and CVV fields are hidden; a 'next' button is shown if the field already has a value
* Closed: after CCN is entered and validated, the field gets shorter and displays only the last 4 digits; EXP and CVV fields are shown and ediatble; 'next' button is hidden.
*/
@IBDesignable
public class BSCcInputLine: BSBaseTextInput {
// MARK: Configurable properties
/**
showOpenInDesign (default = false) helps you to see the component on the storyboard in both states, open (when you edit the CCN field) or closed (CCn shows only last 4 digits and is not editable, you can edit EXP and CVV fields).
*/
@IBInspectable var showOpenInDesign: Bool = false {
didSet {
if designMode {
ccnIsOpen = showOpenInDesign
if ccnIsOpen {
setOpenState(before: true, during: true, after: true)
} else {
setClosedState(before: true, during: true, after: true)
}
}
}
}
/**
expPlaceholder (default = "MM/YY") determines the placeholder text for the EXP field
*/
@IBInspectable var expPlaceholder: String = "MM/YY" {
didSet {
self.expTextField.placeholder = expPlaceholder
}
}
/**
cvvPlaceholder (default = "CVV") determines the placeholder text for the CVV field
*/
@IBInspectable var cvvPlaceholder: String = "CVV" {
didSet {
self.cvvTextField.placeholder = cvvPlaceholder
}
}
/**
ccnWidth (default = 220) determines the CCN text field width in the 'open' state (value will change at runtime according to the device)
*/
@IBInspectable var ccnWidth: CGFloat = 220 {
didSet {
if designMode {
resizeElements()
}
}
}
/**
last4Width (default = 70) determines the CCN text field width in the 'closed' state, when we show only last 4 digits of the CCN (value will change at runtime according to the device)
*/
@IBInspectable var last4Width: CGFloat = 70 {
didSet {
if designMode {
resizeElements()
}
}
}
/**
expWidth (default = 70) determines the EXP field width (value will change at runtime according to the device)
*/
@IBInspectable var expWidth: CGFloat = 70 {
didSet {
self.actualExpWidth = expWidth
if designMode {
resizeElements()
}
}
}
/**
cvvWidth (default = 70) determines the CVV field width (value will change at runtime according to the device)
*/
@IBInspectable var cvvWidth: CGFloat = 70 {
didSet {
if designMode {
resizeElements()
}
}
}
/**
nextBtnWidth (default = 20) determines the width of the next button, which shows in the open state when we already have a value in the CCN field (value will change at runtime according to the device)
*/
@IBInspectable var nextBtnWidth: CGFloat = 22 {
didSet {
if designMode {
resizeElements()
}
}
}
/**
nextBtnHeight (default = 22) determines the height of the next button, which shows in the open state when we already have a value in the CCN field (value will change at runtime according to the device)
*/
@IBInspectable var nextBtnHeight: CGFloat = 22 {
didSet {
if designMode {
resizeElements()
}
}
}
/**
nextBtnHeight (default = internal image, looks like >) determines the image for the next button, which shows in the open state when we already have a value in the CCN field (value will change at runtime according to the device)
*/
@IBInspectable var nextBtnImage: UIImage?
// MARK: public properties
/**
When using this control, you need to implement the BSCcInputLineDelegate protocol, and set the control's delegate to be that class
*/
public var delegate: BSCcInputLineDelegate?
var cardType: String = "" {
didSet {
updateCcIcon(ccType: cardType)
}
}
/**
ccnIsOpen indicated the state of the control (open or closed)
*/
var ccnIsOpen: Bool = true {
didSet {
if designMode {
self.isEditable = ccnIsOpen ? true : false
if ccnIsOpen {
self.textField.text = ccn
} else {
self.textField.text = BSStringUtils.last4(ccn)
}
}
}
}
// MARK: private properties
internal var expTextField: UITextField = UITextField()
internal var cvvTextField: UITextField = UITextField()
private var ccnAnimationLabel: UILabel = UILabel()
internal var expErrorLabel: UILabel?
internal var cvvErrorLabel: UILabel?
private var nextButton: UIButton = UIButton()
private var showNextButton = false
private var ccn: String = ""
private var lastValidateCcn: String = ""
private var closing = false
var actualCcnWidth: CGFloat = 220
var actualLast4Width: CGFloat = 70
var actualExpWidth: CGFloat = 70
var actualCvvWidth: CGFloat = 70
var actualErrorWidth: CGFloat = 150
var actualNextBtnWidth: CGFloat = 22
var actualNextBtnHeight: CGFloat = 22
// MARK: Constants
fileprivate let animationDuration = TimeInterval(0.4)
// MARK: UIView override functions
// called at design time (StoryBoard) to init the component
override init(frame: CGRect) {
super.init(frame: frame)
updateCcIcon(ccType: "")
}
// called at runtime to init the component
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: Public functions
/**
reset sets the component to its initial state, where the fields are emnpty and we are in the 'open' state
*/
public func reset() {
closing = false
showNextButton = false
hideError()
textField.text = ""
expTextField.text = ""
cvvTextField.text = ""
updateCcIcon(ccType: "")
ccn = ""
openCcn(animated: false)
}
/**
This should be called when you try to navigate away from the current view; it bypasses validations so that the fields will resign first responder
*/
public func closeOnLeave() {
closing = true
}
/**
The EXP field contains the expiration date in format MM/YY. This function returns the expiration date in format MMYYYY
*/
public func getExpDateAsMMYYYY() -> String! {
let newValue = self.expTextField.text ?? ""
if let p = newValue.firstIndex(of: "/") {
let mm = newValue[..<p]
let yy = BSStringUtils.removeNoneDigits(String(newValue[p..<newValue.endIndex]))
let currentYearStr = String(BSValidator.getCurrentYear())
let p1 = currentYearStr.index(currentYearStr.startIndex, offsetBy: 2)
let first2Digits = currentYearStr[..<p1]
return "\(mm)/\(first2Digits)\(yy)"
}
return ""
}
/**
Returns the CCN value
*/
override public func getValue() -> String! {
if self.ccnIsOpen {
return self.textField.text
} else {
return ccn
}
}
/**
Sets the CCN value
*/
override public func setValue(_ newValue: String!) {
ccn = newValue
if self.ccnIsOpen {
self.textField.text = ccn
}
}
/**
Returns the CVV value
*/
public func getCvv() -> String! {
return self.cvvTextField.text ?? ""
}
/**
Returns the CC Type
*/
public func getCardType() -> String! {
return cardType
}
/**
Validated the 3 fields; returns true if all are OK; displays errors under the fields if not.
*/
public func validate() -> Bool {
let ok1 = validateCCN()
let ok2 = validateExp(ignoreIfEmpty: false)
let ok3 = validateCvv(ignoreIfEmpty: false)
let result = ok1 && ok2 && ok3
return result
}
/**
Submits the CCN to BlueSnap server; This lets us get the CC issuing country and card type from server, while validating the CCN
*/
public func checkCreditCard(ccn: String) {
if validateCCN() {
self.closeCcn(animated: true)
self.delegate?.willCheckCreditCard()
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
BSApiManager.submitCcn(ccNumber: ccn, completion: { (creditCard, error) in
// Check for error
if let error = error {
if (error == .invalidCcNumber) {
DispatchQueue.main.async {
self.showError(BSValidator.ccnInvalidMessage)
}
} else {
var message = BSLocalizedStrings.getString(BSLocalizedString.Error_General_CC_Validation_Error)
if (error == .cardTypeNotSupported) {
message = BSLocalizedStrings.getString(BSLocalizedString.Error_Card_Type_Not_Supported_1) + BSLocalizedStrings.getString(BSLocalizedString.Error_Card_Type_Not_Supported_2)
DispatchQueue.main.async {
self.showError(BSValidator.ccnInvalidMessage)
}
}
DispatchQueue.main.async {
self.delegate?.showAlert(message)
}
}
} else {
self.cardType = creditCard.ccType ?? ""
}
DispatchQueue.main.async {
self.delegate?.didCheckCreditCard(creditCard: creditCard, error: error)
}
})
})
}
}
/**
This should be called by the 'Pay' button - it submits all the CC details to BlueSnap server, so that later purchase requests to BlueSnap will not need gto contain these values (they will be automatically identified by the token).
In case of errors from the server (there may be validations we did not catch before), we show the errors under the matching fields.
After getting the result, we call the delegate's didSubmitCreditCard function.
- parameters:
- purchaseDetails: optional purchase details to be tokenized as well as the CC details
*/
public func submitPaymentFields(purchaseDetails: BSCcSdkResult?) {
let ccn = self.getValue() ?? ""
let cvv = self.getCvv() ?? ""
let exp = self.getExpDateAsMMYYYY() ?? ""
BSApiManager.submitPurchaseDetails(ccNumber: ccn, expDate: exp, cvv: cvv, last4Digits: nil, cardType: nil, billingDetails: purchaseDetails?.billingDetails, shippingDetails: purchaseDetails?.shippingDetails, storeCard: purchaseDetails?.storeCard, fraudSessionId: BlueSnapSDK.fraudSessionId, completion: {
creditCard, error in
if let error = error {
if (error == .invalidCcNumber) {
self.showError(BSValidator.ccnInvalidMessage)
} else if (error == .invalidExpDate) {
self.showExpError(BSValidator.expInvalidMessage)
} else if (error == .invalidCvv) {
self.showCvvError(BSValidator.cvvInvalidMessage)
} else if (error == .expiredToken) {
let message = BSLocalizedStrings.getString(BSLocalizedString.Error_Cc_Submit_Token_expired)
DispatchQueue.main.async {
self.delegate?.showAlert(message)
}
} else if (error == .tokenNotFound) {
let message = BSLocalizedStrings.getString(BSLocalizedString.Error_Cc_Submit_Token_not_found)
DispatchQueue.main.async {
self.delegate?.showAlert(message)
}
} else {
NSLog("Unexpected error submitting Payment Fields to BS")
let message = BSLocalizedStrings.getString(BSLocalizedString.Error_General_CC_Submit_Error)
DispatchQueue.main.async {
self.delegate?.showAlert(message)
}
}
}
defer {
if (purchaseDetails!.isShopperRequirements()) {
BSApiManager.shopper?.chosenPaymentMethod = BSChosenPaymentMethod(chosenPaymentMethodType: BSPaymentType.CreditCard.rawValue)
BSApiManager.shopper?.chosenPaymentMethod?.creditCard = creditCard
BSApiManager.updateShopper(completion: {
result, error in
if let error = error {
if (error == .expiredToken) {
let message = BSLocalizedStrings.getString(BSLocalizedString.Error_Cc_Submit_Token_expired)
DispatchQueue.main.async {
self.delegate?.showAlert(message)
}
} else if (error == .tokenNotFound) {
let message = BSLocalizedStrings.getString(BSLocalizedString.Error_Cc_Submit_Token_not_found)
DispatchQueue.main.async {
self.delegate?.showAlert(message)
}
} else {
NSLog("Unexpected error submitting Payment Fields to BS")
let message = BSLocalizedStrings.getString(BSLocalizedString.Error_General_CC_Submit_Error)
DispatchQueue.main.async {
self.delegate?.showAlert(message)
}
}
}
DispatchQueue.main.async {
self.delegate?.didSubmitCreditCard(creditCard: creditCard, error: error)
}
})
} else {
DispatchQueue.main.async {
self.delegate?.didSubmitCreditCard(creditCard: creditCard, error: error)
}
}
}
})
}
override public func dismissKeyboard() {
if self.textField.isFirstResponder {
self.textField.resignFirstResponder()
} else if self.expTextField.isFirstResponder {
self.expTextField.resignFirstResponder()
} else if self.cvvTextField.isFirstResponder {
self.cvvTextField.resignFirstResponder()
}
}
// MARK: BSBaseTextInput Override functions
override func initRatios() -> (hRatio: CGFloat, vRatio: CGFloat) {
let ratios = super.initRatios()
// keep proportion of image
let imageRatio = min(ratios.hRatio, ratios.vRatio)
actualNextBtnWidth = (nextBtnWidth * imageRatio).rounded()
actualNextBtnHeight = (nextBtnHeight * imageRatio).rounded()
actualCcnWidth = (ccnWidth * ratios.hRatio).rounded()
actualLast4Width = (last4Width * ratios.hRatio).rounded()
actualExpWidth = (expWidth * ratios.hRatio).rounded()
actualCvvWidth = (cvvWidth * ratios.hRatio).rounded()
actualErrorWidth = self.frame.width / 3
return ratios
}
override func buildElements() {
super.buildElements()
self.textField.accessibilityIdentifier = "CcTextField"
self.expTextField.accessibilityIdentifier = "ExpTextField"
self.cvvTextField.accessibilityIdentifier = "CvvTextField"
ccnAnimationLabel.accessibilityIdentifier = "last4digitsLabel"
nextButton.accessibilityIdentifier = "NextButton"
self.textField.delegate = self
self.addSubview(expTextField)
self.expTextField.delegate = self
self.addSubview(cvvTextField)
self.cvvTextField.delegate = self
if let fieldCoverButton = fieldCoverButton {
self.insertSubview(ccnAnimationLabel, belowSubview: fieldCoverButton)
} else {
self.addSubview(ccnAnimationLabel)
}
fieldKeyboardType = .numberPad
expTextField.addTarget(self, action: #selector(BSCcInputLine.expFieldDidBeginEditing(_:)), for: .editingDidBegin)
expTextField.addTarget(self, action: #selector(BSCcInputLine.expFieldEditingChanged(_:)), for: .editingChanged)
cvvTextField.addTarget(self, action: #selector(BSCcInputLine.cvvFieldDidBeginEditing(_:)), for: .editingDidBegin)
cvvTextField.addTarget(self, action: #selector(BSCcInputLine.cvvFieldEditingChanged(_:)), for: .editingChanged)
expTextField.textAlignment = .center
cvvTextField.textAlignment = .center
setNumericKeyboard()
setButtonImage()
}
override func setElementAttributes() {
super.setElementAttributes()
expTextField.keyboardType = .numberPad
expTextField.backgroundColor = self.fieldBkdColor
expTextField.textColor = self.textColor
expTextField.returnKeyType = UIReturnKeyType.done
expTextField.borderStyle = .none
expTextField.placeholder = expPlaceholder
cvvTextField.keyboardType = .numberPad
cvvTextField.backgroundColor = self.fieldBkdColor
cvvTextField.textColor = self.textColor
cvvTextField.returnKeyType = UIReturnKeyType.done
cvvTextField.borderStyle = .none
cvvTextField.placeholder = cvvPlaceholder
cvvTextField.borderStyle = textField.borderStyle
expTextField.borderStyle = textField.borderStyle
cvvTextField.layer.borderWidth = fieldBorderWidth
expTextField.layer.borderWidth = fieldBorderWidth
if let fieldBorderColor = self.fieldBorderColor {
cvvTextField.layer.borderColor = fieldBorderColor.cgColor
expTextField.layer.borderColor = fieldBorderColor.cgColor
}
}
override func resizeElements() {
super.resizeElements()
expTextField.font = textField.font
cvvTextField.font = textField.font
if ccnIsOpen == true {
expTextField.alpha = 0
cvvTextField.alpha = 0
} else {
expTextField.alpha = 1
cvvTextField.alpha = 1
}
let fieldEndX = getFieldX() + self.actualLast4Width
let cvvFieldX = self.frame.width - actualCvvWidth - self.actualRightMargin
let expFieldX = (fieldEndX + cvvFieldX - actualExpWidth) / 2.0
let fieldY = (self.frame.height - actualFieldHeight) / 2
expTextField.frame = CGRect(x: expFieldX, y: fieldY, width: actualExpWidth, height: actualFieldHeight)
cvvTextField.frame = CGRect(x: cvvFieldX, y: fieldY, width: actualCvvWidth, height: actualFieldHeight)
adjustNextButton()
if fieldCornerRadius != 0 {
cvvTextField.layer.cornerRadius = fieldCornerRadius
expTextField.layer.cornerRadius = fieldCornerRadius
}
self.ccnAnimationLabel.font = self.textField.font
let labelWidth = self.ccnIsOpen ? actualCcnWidth : actualLast4Width
self.ccnAnimationLabel.frame = CGRect(x: self.textField.frame.minX, y: self.textField.frame.minY, width: labelWidth, height: self.textField.frame.height)
self.ccnAnimationLabel.alpha = self.ccnIsOpen ? 0 : 1
}
override func getImageRect() -> CGRect {
return CGRect(x: actualRightMargin, y: (self.frame.height - actualImageHeight) / 2, width: actualImageWidth, height: actualImageHeight)
}
override func getFieldWidth() -> CGFloat {
return actualCcnWidth
}
override func getFieldX() -> CGFloat {
let fieldX = actualLeftMargin + actualImageWidth + actualMiddleMargin
return fieldX
}
override func resizeError() {
let labelFont = UIFont(name: self.fontName, size: actualErrorFontSize)
if let errorLabel = errorLabel {
if labelFont != nil {
errorLabel.font = labelFont
}
errorLabel.textAlignment = .left
let x: CGFloat = actualLeftMargin
errorLabel.frame = CGRect(x: x, y: self.frame.height - actualErrorHeight, width: actualErrorWidth, height: actualErrorHeight)
}
if let expErrorLabel = expErrorLabel {
if labelFont != nil {
expErrorLabel.font = labelFont
}
expErrorLabel.textAlignment = .center
let fieldCenter: CGFloat! = expTextField.frame.minX + expTextField.frame.width / 2.0
let x = fieldCenter - actualErrorWidth / 2.0
expErrorLabel.textAlignment = .center
expErrorLabel.frame = CGRect(x: x, y: self.frame.height - actualErrorHeight, width: actualErrorWidth, height: actualErrorHeight)
}
if let cvvErrorLabel = cvvErrorLabel {
if labelFont != nil {
cvvErrorLabel.font = labelFont
}
cvvErrorLabel.textAlignment = .right
let x = self.frame.width - rightMargin - actualErrorWidth
cvvErrorLabel.textAlignment = .right
cvvErrorLabel.frame = CGRect(x: x, y: self.frame.height - actualErrorHeight, width: actualErrorWidth, height: actualErrorHeight)
}
}
// MARK: TextFieldDelegate functions
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return true
}
/**
This handler is called when one of the text fields is about to end editing; we perform validation,
ignoring empty values, but allow exiting the field even if there is an error.
*/
func textFieldShouldEndEditing(_ sender: UITextField) -> Bool {
if closing {
closing = false
return true
}
if sender == self.textField {
if ccnIsOpen {
ccn = self.textField.text!
if lastValidateCcn == self.textField.text {
self.closeCcn(animated: true)
} else {
self.lastValidateCcn = self.ccn
self.checkCreditCard(ccn: ccn)
}
}
} else if sender == self.expTextField {
_ = validateExp(ignoreIfEmpty: true)
} else if sender == self.cvvTextField {
_ = validateCvv(ignoreIfEmpty: true)
}
return true
}
// MARK: Numeric Keyboard 'done' button enhancement
override internal func setNumericKeyboard() {
let viewForDoneButtonOnKeyboard = createDoneButtonForKeyboard()
self.textField.inputAccessoryView = viewForDoneButtonOnKeyboard
self.expTextField.inputAccessoryView = viewForDoneButtonOnKeyboard
self.cvvTextField.inputAccessoryView = viewForDoneButtonOnKeyboard
}
// MARK: extra error handling
/*
Shows the given text as an error below the exp text field
*/
public func showExpError(_ errorText: String?) {
if expErrorLabel == nil {
expErrorLabel = UILabel()
expErrorLabel!.accessibilityIdentifier = "ExpErrorLabel"
initErrorLabel(errorLabel: expErrorLabel)
}
showErrorByField(field: self.expTextField, errorLabel: expErrorLabel, errorText: errorText)
}
/*
Shows the given text as an error below the exp text field
*/
public func showCvvError(_ errorText: String?) {
if cvvErrorLabel == nil {
cvvErrorLabel = UILabel()
cvvErrorLabel!.accessibilityIdentifier = "CvvErrorLabel"
initErrorLabel(errorLabel: cvvErrorLabel)
}
showErrorByField(field: self.cvvTextField, errorLabel: cvvErrorLabel, errorText: errorText)
}
func hideExpError() {
hideErrorByField(field: expTextField, errorLabel: expErrorLabel)
}
func hideCvvError() {
hideErrorByField(field: cvvTextField, errorLabel: cvvErrorLabel)
}
// MARK: focus on fields
func focusOnCcnField() {
DispatchQueue.global(qos: .userInteractive).async {
DispatchQueue.main.async {
if self.ccnIsOpen == true {
self.textField.becomeFirstResponder()
}
}
}
}
func focusOnExpField() {
DispatchQueue.global(qos: .userInteractive).async {
DispatchQueue.main.async {
if self.ccnIsOpen == false {
self.expTextField.becomeFirstResponder()
}
}
}
}
func focusOnCvvField() {
DispatchQueue.global(qos: .userInteractive).async {
DispatchQueue.main.async {
if self.ccnIsOpen == false {
self.cvvTextField.becomeFirstResponder()
}
}
}
}
func focusOnNextField() {
DispatchQueue.global(qos: .userInteractive).async {
DispatchQueue.main.async {
let nextTage = self.tag + 1;
let nextResponder = self.superview?.viewWithTag(nextTage) as? BSInputLine
if nextResponder != nil {
nextResponder?.textField.becomeFirstResponder()
}
}
}
}
// MARK: event handlers
override func fieldCoverButtonTouchUpInside(_ sender: Any) {
openCcn(animated: true)
}
override public func textFieldDidBeginEditing(_ sender: UITextField) {
//hideError(textField)
}
override public func textFieldDidEndEditing(_ sender: UITextField) {
delegate?.endEditCreditCard()
}
override func textFieldEditingChanged(_ sender: UITextField) {
self.ccn = self.textField.text!
BSValidator.ccnEditingChanged(textField)
let ccn = BSStringUtils.removeNoneDigits(textField.text ?? "")
let ccnLength = ccn.count
if ccnLength >= 6 {
cardType = BSValidator.getCCTypeByRegex(textField.text ?? "")?.lowercased() ?? ""
} else {
cardType = ""
}
let maxLength: Int = BSValidator.getCcLengthByCardType(cardType)
if checkMaxLength(textField: sender, maxLength: maxLength) == true {
if ccnLength == maxLength {
if self.textField.canResignFirstResponder {
focusOnExpField()
}
}
}
}
@objc func expFieldDidBeginEditing(_ sender: UITextField) {
//hideError(expTextField)
}
@objc func expFieldEditingChanged(_ sender: UITextField) {
BSValidator.expEditingChanged(sender)
if checkMaxLength(textField: sender, maxLength: 5) == true {
if sender.text?.count == 5 {
if expTextField.canResignFirstResponder {
focusOnCvvField()
}
}
}
}
@objc func cvvFieldDidBeginEditing(_ sender: UITextField) {
//hideError(cvvTextField)
}
@objc func cvvFieldEditingChanged(_ sender: UITextField) {
BSValidator.cvvEditingChanged(sender)
let cvvLength = BSValidator.getCvvLength(cardType: self.cardType)
if checkMaxLength(textField: sender, maxLength: cvvLength) == true {
if sender.text?.count == cvvLength {
if cvvTextField.canResignFirstResponder == true {
focusOnNextField()
}
}
}
}
@objc func nextArrowClick() {
if textField.canResignFirstResponder {
focusOnExpField()
}
}
// MARK: Validation methods
func validateCCN() -> Bool {
let result = BSValidator.validateCCN(input: self)
return result
}
func validateExp(ignoreIfEmpty: Bool) -> Bool {
if ccnIsOpen {
return true
}
var result = true
if !ignoreIfEmpty || (expTextField.text?.count)! > 0 {
result = BSValidator.validateExp(input: self)
}
return result
}
func validateCvv(ignoreIfEmpty: Bool) -> Bool {
if ccnIsOpen {
return true
}
var result = true
if !ignoreIfEmpty || (cvvTextField.text?.count)! > 0 {
result = BSValidator.validateCvv(input: self, cardType: cardType)
}
return result
}
// private/internal functions
private func closeCcn(animated: Bool) {
self.ccnIsOpen = false
if animated {
DispatchQueue.main.async {
self.setClosedState(before: true, during: false, after: false)
//self.layoutIfNeeded()
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
UIView.animate(withDuration: self.animationDuration, animations: {
self.setClosedState(before: false, during: true, after: false)
}, completion: { animate in
self.setClosedState(before: false, during: false, after: true)
})
}
} else {
self.setClosedState(before: true, during: true, after: true)
}
self.showNextButton = true // after first close, this will always be true
}
private func openCcn(animated: Bool) {
var canOpen = true
if cvvTextField.isFirstResponder {
if !cvvTextField.canResignFirstResponder {
canOpen = false
} else {
//cvvTextField.resignFirstResponder()
}
} else if expTextField.isFirstResponder {
if !expTextField.canResignFirstResponder {
canOpen = false
} else {
//expTextField.resignFirstResponder()
}
}
if canOpen {
self.hideExpError()
self.hideCvvError()
self.ccnIsOpen = true
if animated {
DispatchQueue.main.async {
self.setOpenState(before: true, during: false, after: false)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
UIView.animate(withDuration: self.animationDuration, animations: {
self.setOpenState(before: false, during: true, after: false)
}, completion: { animate in
self.setOpenState(before: false, during: false, after: true)
})
}
} else {
self.setOpenState(before: true, during: true, after: true)
}
}
}
func adjustNextButton() {
let x: CGFloat = self.frame.width - actualRightMargin - actualNextBtnWidth
let y: CGFloat = (self.frame.height - actualNextBtnHeight) / 2.0
nextButton.frame = CGRect(x: x, y: y, width: actualNextBtnWidth, height: actualNextBtnHeight)
if self.ccnIsOpen && (showNextButton || designMode) {
nextButton.alpha = 1
} else {
nextButton.alpha = 0
}
}
private func setButtonImage() {
var btnImage: UIImage?
if let img = self.nextBtnImage {
btnImage = img
} else {
btnImage = BSViewsManager.getImage(imageName: "forward_arrow")
}
if let img = btnImage {
nextButton.setImage(img, for: .normal)
nextButton.contentVerticalAlignment = .fill
nextButton.contentHorizontalAlignment = .fill
nextButton.addTarget(self, action: #selector(self.nextArrowClick), for: .touchUpInside)
self.addSubview(nextButton)
}
}
func updateCcIcon(ccType: String?) {
// change the image in ccIconImage
if let image = BSImageLibrary.getCcIconByCardType(ccType: ccType) {
DispatchQueue.main.async {
self.image = image
}
}
}
private func checkMaxLength(textField: UITextField!, maxLength: Int) -> Bool {
if (BSStringUtils.removeNoneDigits(textField.text!).count > maxLength) {
textField.deleteBackward()
return false
} else {
return true
}
}
private func closeExpCvv() {
self.expTextField.frame = CGRect(x: self.expTextField.frame.maxX, y: self.expTextField.frame.minY, width: 0, height: self.expTextField.frame.height)
self.cvvTextField.frame = CGRect(x: self.cvvTextField.frame.maxX, y: self.cvvTextField.frame.minY, width: 0, height: self.cvvTextField.frame.height)
}
private func openExpCvv() {
self.expTextField.frame = CGRect(x: self.expTextField.frame.maxX - actualExpWidth, y: self.expTextField.frame.minY, width: actualExpWidth, height: self.expTextField.frame.height)
self.cvvTextField.frame = CGRect(x: self.cvvTextField.frame.maxX - actualCvvWidth, y: self.cvvTextField.frame.minY, width: actualCvvWidth, height: self.cvvTextField.frame.height)
}
private func setClosedState(before: Bool, during: Bool, after: Bool) {
if before {
closeExpCvv()
self.ccnAnimationLabel.text = self.ccn
self.textField.alpha = 0
self.ccnAnimationLabel.alpha = 1
//self.layoutIfNeeded()
}
if during {
self.expTextField.alpha = 1
self.cvvTextField.alpha = 1
self.ccnAnimationLabel.frame = CGRect(x: self.textField.frame.minX, y: self.textField.frame.minY, width: self.actualLast4Width, height: self.textField.frame.height)
openExpCvv()
adjustNextButton()
}
if (after) {
self.ccnAnimationLabel.text = BSStringUtils.last4(ccn)
self.isEditable = false
self.adjustCoverButton()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
//self.layoutIfNeeded()
if !self.expTextField.isFirstResponder {
_ = self.validateExp(ignoreIfEmpty: true)
}
if !self.cvvTextField.isFirstResponder {
_ = self.validateCvv(ignoreIfEmpty: true)
}
}
}
}
override func getCoverButtonWidth() -> CGFloat {
return actualLast4Width
}
private func setOpenState(before: Bool, during: Bool, after: Bool) {
if before {
self.ccnAnimationLabel.frame = CGRect(x: self.textField.frame.minX, y: self.textField.frame.minY, width: self.actualLast4Width, height: self.textField.frame.height)
self.ccnAnimationLabel.alpha = 1
self.ccnAnimationLabel.text = BSStringUtils.last4(ccn)
self.textField.alpha = 0
}
if during {
self.expTextField.alpha = 0
self.cvvTextField.alpha = 0
self.ccnAnimationLabel.alpha = 1
self.ccnAnimationLabel.frame = CGRect(x: self.textField.frame.minX, y: self.textField.frame.minY, width: self.actualCcnWidth, height: self.textField.frame.height)
self.ccnAnimationLabel.text = ccn
closeExpCvv()
adjustNextButton()
}
if (after) {
self.ccnAnimationLabel.alpha = 0
self.textField.alpha = 1
self.isEditable = true
self.adjustCoverButton()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
//self.layoutIfNeeded()
self.delegate?.startEditCreditCard()
self.focusOnCcnField()
}
}
}
}
| mit | 9379552e6475821c9054ff6eed2b484e | 35.32 | 311 | 0.597782 | 4.9157 | false | false | false | false |
microeditionbiz/reddit-client | reddit-client/reddit-client/Feed/LinkCell.swift | 1 | 3737 | //
// LinkCell.swift
// reddit-client
//
// Created by Pablo Romero on 1/19/17.
// Copyright © 2017 Pablo Romero. All rights reserved.
//
import UIKit
class LinkCell: UITableViewCell {
@IBOutlet weak var thumbnailImageView: UIRemoteImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var detailsLabel: UILabel!
@IBOutlet weak var commentsLabel: UILabel!
@IBOutlet weak var titleLabelLeadingConstraint: NSLayoutConstraint!
// Important: these values have to be in sync with IB
static let padding: CGFloat = 8.0
static let veritcalSpace: CGFloat = 4.0
static let minHeight: CGFloat = 80.0
static let titleFont = UIFont.systemFont(ofSize: 19.0, weight: UIFontWeightSemibold)
static let thumbnailWidth: CGFloat = 63.0
static let detailsHeight: CGFloat = 16.0
static let commentsCountHeight: CGFloat = 16.0
static let contentViewPadding: CGFloat = 1.0
// --------------------------------------------------
override func awakeFromNib() {
super.awakeFromNib()
self.thumbnailImageView.layer.cornerRadius = 5.0
self.thumbnailImageView.clipsToBounds = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func update(withLink link: Link) {
self.titleLabel.text = LinkCell.titleText(forLink: link)
self.detailsLabel.text = LinkCell.detailsText(forLink: link)
self.commentsLabel.text = LinkCell.commentsCountText(forLink: link)
if link.hasThumbnail() {
self.thumbnailImageView.isHidden = false
self.titleLabelLeadingConstraint.constant = LinkCell.thumbnailWidth + 2 * LinkCell.padding
let url = URL(string: link.thumbnail!)!
self.thumbnailImageView.setContent(url: url)
} else {
self.thumbnailImageView.isHidden = true
self.titleLabelLeadingConstraint.constant = LinkCell.padding
self.thumbnailImageView.setContent(url: nil)
}
}
static func titleText(forLink link: Link) -> String {
return link.title ?? ""
}
static func detailsText(forLink link: Link) -> String {
if let author = link.author {
return "\(link.createdAt!.friendlyDescription()) by \(author)"
} else {
return "\(link.createdAt!.friendlyDescription())"
}
}
static func commentsCountText(forLink link: Link) -> String {
return (link.commentsCount == 1 ?
"\(link.commentsCount) comment" :
"\(link.commentsCount) comments")
}
static func neededHeight(forLink link: Link) -> CGFloat {
var maxSize = CGSize(width: UIScreen.main.bounds.width - 2 * padding,
height: .greatestFiniteMagnitude)
if link.hasThumbnail() {
maxSize.width -= (thumbnailWidth + padding)
}
let options: NSStringDrawingOptions = [.usesFontLeading, .usesLineFragmentOrigin]
let attributedTitle = NSAttributedString(string: LinkCell.titleText(forLink: link),
attributes: [NSFontAttributeName: titleFont])
let titleRect = attributedTitle.boundingRect(with: maxSize,
options: options,
context: nil)
let height = ceil(titleRect.height) + detailsHeight + commentsCountHeight + padding + 3 * veritcalSpace + contentViewPadding
return (height < minHeight ? minHeight : height)
}
}
| mit | ee806ef1e3c3234beed87c5cef55e681 | 35.271845 | 132 | 0.609475 | 5.124829 | false | false | false | false |
atrick/swift | test/Concurrency/concurrent_value_checking.swift | 2 | 14495 | // RUN: %target-typecheck-verify-swift -disable-availability-checking -warn-concurrency -parse-as-library
// REQUIRES: concurrency
class NotConcurrent { } // expected-note 27{{class 'NotConcurrent' does not conform to the 'Sendable' protocol}}
// ----------------------------------------------------------------------
// Sendable restriction on actor operations
// ----------------------------------------------------------------------
actor A1 {
let localLet: NotConcurrent = NotConcurrent()
func synchronous() -> NotConcurrent? { nil }
func asynchronous(_: NotConcurrent?) async { }
}
// Actor initializers and Sendable
actor A2 {
var localVar: NotConcurrent
init(value: NotConcurrent) {
self.localVar = value
}
convenience init(forwardSync value: NotConcurrent) {
self.init(value: value)
}
convenience init(delegatingSync value: NotConcurrent) {
self.init(forwardSync: value)
}
init(valueAsync value: NotConcurrent) async {
self.localVar = value
}
convenience init(forwardAsync value: NotConcurrent) async {
await self.init(valueAsync: value)
}
nonisolated convenience init(nonisoAsync value: NotConcurrent, _ c: Int) async {
if c == 0 {
await self.init(valueAsync: value)
} else {
self.init(value: value)
}
}
convenience init(delegatingAsync value: NotConcurrent, _ c: Int) async {
if c == 0 {
await self.init(valueAsync: value)
} else if c == 1 {
self.init(value: value)
} else if c == 2 {
await self.init(forwardAsync: value)
} else {
self.init(delegatingSync: value)
}
}
}
func testActorCreation(value: NotConcurrent) async {
_ = A2(value: value) // expected-warning{{non-sendable type 'NotConcurrent' passed in call to nonisolated initializer 'init(value:)' cannot cross actor boundary}}
_ = await A2(valueAsync: value) // expected-warning{{non-sendable type 'NotConcurrent' passed in call to actor-isolated initializer 'init(valueAsync:)' cannot cross actor boundary}}
_ = A2(delegatingSync: value) // expected-warning{{non-sendable type 'NotConcurrent' passed in call to nonisolated initializer 'init(delegatingSync:)' cannot cross actor boundary}}
_ = await A2(delegatingAsync: value, 9) // expected-warning{{non-sendable type 'NotConcurrent' passed in call to actor-isolated initializer 'init(delegatingAsync:_:)' cannot cross actor boundary}}
_ = await A2(nonisoAsync: value, 3) // expected-warning{{non-sendable type 'NotConcurrent' passed in call to nonisolated initializer 'init(nonisoAsync:_:)' cannot cross actor boundary}}
}
extension A1 {
func testIsolation(other: A1) async {
// All within the same actor domain, so the Sendable restriction
// does not apply.
_ = localLet
_ = synchronous()
_ = await asynchronous(nil)
_ = self.localLet
_ = self.synchronous()
_ = await self.asynchronous(nil)
// Across to a different actor, so Sendable restriction is enforced.
_ = other.localLet // expected-warning{{non-sendable type 'NotConcurrent' in asynchronous access to actor-isolated property 'localLet' cannot cross actor boundary}}
_ = await other.synchronous() // expected-warning{{non-sendable type 'NotConcurrent?' returned by implicitly asynchronous call to actor-isolated instance method 'synchronous()' cannot cross actor boundary}}
_ = await other.asynchronous(nil) // expected-warning{{non-sendable type 'NotConcurrent?' passed in call to actor-isolated instance method 'asynchronous' cannot cross actor boundary}}
}
}
// ----------------------------------------------------------------------
// Sendable restriction on global actor operations
// ----------------------------------------------------------------------
actor TestActor {}
@globalActor
struct SomeGlobalActor {
static var shared: TestActor { TestActor() }
}
@SomeGlobalActor
let globalValue: NotConcurrent? = nil
@SomeGlobalActor
func globalSync(_: NotConcurrent?) {
}
@SomeGlobalActor
func globalAsync(_: NotConcurrent?) async {
await globalAsync(globalValue) // both okay because we're in the actor
globalSync(nil)
}
func globalTest() async {
let a = globalValue // expected-warning{{non-sendable type 'NotConcurrent?' in asynchronous access to global actor 'SomeGlobalActor'-isolated let 'globalValue' cannot cross actor boundary}}
await globalAsync(a) // expected-warning{{non-sendable type 'NotConcurrent?' passed in implicitly asynchronous call to global actor 'SomeGlobalActor'-isolated function cannot cross actor boundary}}
await globalSync(a) // expected-warning{{non-sendable type 'NotConcurrent?' passed in call to global actor 'SomeGlobalActor'-isolated function cannot cross actor boundary}}
}
struct HasSubscript {
@SomeGlobalActor
subscript (i: Int) -> NotConcurrent? { nil }
}
class ClassWithGlobalActorInits { // expected-note 2{{class 'ClassWithGlobalActorInits' does not conform to the 'Sendable' protocol}}
@SomeGlobalActor
init(_: NotConcurrent) { }
@SomeGlobalActor
init() { }
}
@MainActor
func globalTestMain(nc: NotConcurrent) async {
let a = globalValue // expected-warning{{non-sendable type 'NotConcurrent?' in asynchronous access to global actor 'SomeGlobalActor'-isolated let 'globalValue' cannot cross actor boundary}}
await globalAsync(a) // expected-warning{{non-sendable type 'NotConcurrent?' passed in implicitly asynchronous call to global actor 'SomeGlobalActor'-isolated function cannot cross actor boundary}}
await globalSync(a) // expected-warning{{non-sendable type 'NotConcurrent?' passed in call to global actor 'SomeGlobalActor'-isolated function cannot cross actor boundary}}
_ = await ClassWithGlobalActorInits(nc) // expected-warning{{non-sendable type 'NotConcurrent' passed in call to global actor 'SomeGlobalActor'-isolated function cannot cross actor boundary}}
// expected-warning@-1{{non-sendable type 'ClassWithGlobalActorInits' returned by call to global actor 'SomeGlobalActor'-isolated function cannot cross actor boundary}}
_ = await ClassWithGlobalActorInits() // expected-warning{{non-sendable type 'ClassWithGlobalActorInits' returned by call to global actor 'SomeGlobalActor'-isolated function cannot cross actor boundary}}
}
@SomeGlobalActor
func someGlobalTest(nc: NotConcurrent) {
let hs = HasSubscript()
let _ = hs[0] // okay
_ = ClassWithGlobalActorInits(nc)
}
// ----------------------------------------------------------------------
// Sendable restriction on captures.
// ----------------------------------------------------------------------
func acceptNonConcurrent(_: () -> Void) { }
func acceptConcurrent(_: @Sendable () -> Void) { }
func testConcurrency() {
let x = NotConcurrent()
var y = NotConcurrent()
y = NotConcurrent()
acceptNonConcurrent {
print(x) // okay
print(y) // okay
}
acceptConcurrent {
print(x) // expected-warning{{capture of 'x' with non-sendable type 'NotConcurrent' in a `@Sendable` closure}}
print(y) // expected-warning{{capture of 'y' with non-sendable type 'NotConcurrent' in a `@Sendable` closure}}
// expected-error@-1{{reference to captured var 'y' in concurrently-executing code}}
}
}
@preconcurrency func acceptUnsafeSendable(_ fn: @Sendable () -> Void) { }
func testUnsafeSendableNothing() {
var x = 5
acceptUnsafeSendable {
x = 17 // expected-error{{mutation of captured var 'x' in concurrently-executing code}}
}
print(x)
}
func testUnsafeSendableInAsync() async {
var x = 5
acceptUnsafeSendable {
x = 17 // expected-error{{mutation of captured var 'x' in concurrently-executing code}}
}
print(x)
}
// ----------------------------------------------------------------------
// Sendable restriction on key paths.
// ----------------------------------------------------------------------
class NC: Hashable { // expected-note 2{{class 'NC' does not conform to the 'Sendable' protocol}}
func hash(into: inout Hasher) { }
static func==(_: NC, _: NC) -> Bool { true }
}
class HasNC {
var dict: [NC: Int] = [:]
}
func testKeyPaths(dict: [NC: Int], nc: NC) {
_ = \HasNC.dict[nc] // expected-warning{{cannot form key path that captures non-sendable type 'NC'}}
}
// ----------------------------------------------------------------------
// Sendable restriction on nonisolated declarations.
// ----------------------------------------------------------------------
actor ANI {
nonisolated let nc = NC()
nonisolated func f() -> NC? { nil }
}
func testANI(ani: ANI) async {
_ = ani.nc // expected-warning{{non-sendable type 'NC' in asynchronous access to nonisolated property 'nc' cannot cross actor boundary}}
}
// ----------------------------------------------------------------------
// Sendable restriction on conformances.
// ----------------------------------------------------------------------
protocol AsyncProto {
func asyncMethod(_: NotConcurrent) async
}
extension A1: AsyncProto {
func asyncMethod(_: NotConcurrent) async { } // expected-warning{{non-sendable type 'NotConcurrent' in parameter of actor-isolated instance method 'asyncMethod' satisfying non-isolated protocol requirement cannot cross actor boundary}}
}
protocol MainActorProto {
func asyncMainMethod(_: NotConcurrent) async
}
class SomeClass: MainActorProto {
@SomeGlobalActor
func asyncMainMethod(_: NotConcurrent) async { } // expected-warning{{non-sendable type 'NotConcurrent' in parameter of global actor 'SomeGlobalActor'-isolated instance method 'asyncMainMethod' satisfying non-isolated protocol requirement cannot cross actor boundary}}
}
// ----------------------------------------------------------------------
// Sendable restriction on concurrent functions.
// ----------------------------------------------------------------------
@Sendable func concurrentFunc() -> NotConcurrent? { nil }
// ----------------------------------------------------------------------
// No Sendable restriction on @Sendable function types.
// ----------------------------------------------------------------------
typealias CF = @Sendable () -> NotConcurrent?
typealias BadGenericCF<T> = @Sendable () -> T?
typealias GoodGenericCF<T: Sendable> = @Sendable () -> T? // okay
var concurrentFuncVar: (@Sendable (NotConcurrent) -> Void)? = nil
// ----------------------------------------------------------------------
// Sendable restriction on @Sendable closures.
// ----------------------------------------------------------------------
func acceptConcurrentUnary<T>(_: @Sendable (T) -> T) { }
func concurrentClosures<T>(_: T) {
acceptConcurrentUnary { (x: T) in
_ = x // ok
acceptConcurrentUnary { _ in x } // expected-warning{{capture of 'x' with non-sendable type 'T' in a `@Sendable` closure}}
}
}
// ----------------------------------------------------------------------
// Sendable checking
// ----------------------------------------------------------------------
struct S1: Sendable {
var nc: NotConcurrent // expected-warning{{stored property 'nc' of 'Sendable'-conforming struct 'S1' has non-sendable type 'NotConcurrent'}}
}
struct S2<T>: Sendable {
var nc: T // expected-warning{{stored property 'nc' of 'Sendable'-conforming generic struct 'S2' has non-sendable type 'T'}}
}
struct S3<T> {
var c: T
var array: [T]
}
extension S3: Sendable where T: Sendable { }
enum E1: Sendable {
case payload(NotConcurrent) // expected-warning{{associated value 'payload' of 'Sendable'-conforming enum 'E1' has non-sendable type 'NotConcurrent'}}
}
enum E2<T> {
case payload(T)
}
extension E2: Sendable where T: Sendable { }
final class C1: Sendable {
let nc: NotConcurrent? = nil // expected-warning{{stored property 'nc' of 'Sendable'-conforming class 'C1' has non-sendable type 'NotConcurrent?'}}
var x: Int = 0 // expected-warning{{stored property 'x' of 'Sendable'-conforming class 'C1' is mutable}}
let i: Int = 0
}
final class C2: Sendable {
let x: Int = 0
}
class C3 { }
class C4: C3, @unchecked Sendable {
var y: Int = 0 // okay
}
class C5: @unchecked Sendable {
var x: Int = 0 // okay
}
class C6: C5 {
var y: Int = 0 // still okay, it's unsafe
}
final class C7<T>: Sendable { }
class C9: Sendable { } // expected-warning{{non-final class 'C9' cannot conform to 'Sendable'; use '@unchecked Sendable'}}
extension NotConcurrent {
func f() { }
func test() {
Task {
f() // expected-warning{{capture of 'self' with non-sendable type 'NotConcurrent' in a `@Sendable` closure}}
}
Task {
self.f() // expected-warning{{capture of 'self' with non-sendable type 'NotConcurrent' in a `@Sendable` closure}}
}
Task { [self] in
f() // expected-warning{{capture of 'self' with non-sendable type 'NotConcurrent' in a `@Sendable` closure}}
}
Task { [self] in
self.f() // expected-warning{{capture of 'self' with non-sendable type 'NotConcurrent' in a `@Sendable` closure}}
}
}
}
// ----------------------------------------------------------------------
// @unchecked Sendable disabling checking
// ----------------------------------------------------------------------
struct S11: @unchecked Sendable {
var nc: NotConcurrent // okay
}
struct S12<T>: @unchecked Sendable {
var nc: T // okay
}
enum E11<T>: @unchecked Sendable {
case payload(NotConcurrent) // okay
case other(T) // okay
}
class C11 { }
class C12: @unchecked C11 { } // expected-error{{'unchecked' attribute cannot apply to non-protocol type 'C11'}}
protocol P { }
protocol Q: @unchecked Sendable { } // expected-error{{'unchecked' attribute only applies in inheritance clauses}}
typealias TypeAlias1 = @unchecked P // expected-error{{'unchecked' attribute only applies in inheritance clauses}}
// ----------------------------------------------------------------------
// UnsafeSendable historical name
// ----------------------------------------------------------------------
enum E12<T>: UnsafeSendable { // expected-warning{{'UnsafeSendable' is deprecated: Use @unchecked Sendable instead}}
case payload(NotConcurrent) // okay
case other(T) // okay
}
// ----------------------------------------------------------------------
// @Sendable inference through optionals
// ----------------------------------------------------------------------
func testSendableOptionalInference(nc: NotConcurrent) {
var fn: (@Sendable () -> Void)? = nil
fn = {
print(nc) // expected-warning{{capture of 'nc' with non-sendable type 'NotConcurrent' in a `@Sendable` closure}}
}
_ = fn
}
| apache-2.0 | d4cf2ff15cb5bbf78c0022a078639bef | 36.45478 | 270 | 0.620973 | 4.451781 | false | false | false | false |
FranDepascuali/ProyectoAlimentar | ProyectoAlimentar/UIComponents/Authentication/Login/LoginViewController.swift | 1 | 1885 | //
// LoginViewController.swift
// ProyectoAlimentar
//
// Created by Francisco Depascuali on 10/20/16.
// Copyright © 2016 Alimentar. All rights reserved.
//
import UIKit
//import FacebookLogin
//import FacebookCore
import Core
public final class LoginViewController: UIViewController {
fileprivate let _viewModel: LoginViewModel
//
// fileprivate lazy var _loginView: LoginView = LoginView.loadFromNib()!
//
public init(viewModel: LoginViewModel) {
_viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// override public func loadView() {
// view = _loginView
//
// loadFacebookButton()
// }
//
// override public func viewDidLoad() {
// super.viewDidLoad()
//
// bindViewModel()
// }
}
//
//private extension LoginViewController {
//
// func bindViewModel() {
//
// }
//
// func loadFacebookButton() {
// let loginButton = LoginButton(readPermissions: [.publicProfile, .userFriends, .email])
// loginButton.add(into:_loginView.facebookButtonContainerView)
// loginButton.delegate = self
// }
//}
//
//extension LoginViewController: LoginButtonDelegate {
//
// public func loginButtonDidCompleteLogin(_ loginButton: LoginButton, result: LoginResult) {
//
// switch result {
// case .cancelled:
// print("Login cancelled")
// case .failed(let error):
// print("Login failed with error \(error)")
// case .success(_, _, let token):
// _viewModel
// .login(token.authenticationToken)
// .start()
// }
// }
//
// public func loginButtonDidLogOut(_ loginButton: LoginButton) {
// // Do nothing
// }
//}
| apache-2.0 | d34dff69f98d97b2ead3ff064068a0cd | 24.12 | 96 | 0.609342 | 4.233708 | false | false | false | false |
conrrado/treinamento | TreinamentoDeSwift3/TreinamentoDeSwift3/Controllers/PhotoCollectionViewController.swift | 1 | 5340 | //
// PhotoCollectionViewController.swift
// TreinamentoDeSwift3
//
// Created by Conrrado Camacho (6018) on 04/07/17.
// Copyright © 2017 Conrrado Camacho (6018). All rights reserved.
//
import UIKit
class PhotoCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
// MARK: - Properties
fileprivate let reuseIdentifier = "Cell"
fileprivate let reuseIdentifierHeader = "CellHeader"
fileprivate var photos: NSArray = []
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
// self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
self.collectionView!.register(UINib(nibName: "PhotoCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
self.collectionView!.register(PhotoCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: reuseIdentifierHeader)
let top3 = ["Banana", "Maçã", "Uva"]
let others = ["Goiaba", "Jabuticaba", "Amora", "Melão", "Laranja"]
photos = NSArray(objects: top3, others)
let flow = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
flow.sectionInset = UIEdgeInsetsMake(20, 0, 20, 0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let kHeight = 100
let width = (collectionView.bounds.size.width / 10) * 3
return CGSize.init(width: CGFloat(width), height: CGFloat(kHeight))
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return photos.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
let ar = photos.object(at: section) as! Array<Any>
return ar.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PhotoCollectionViewCell
let ar = photos.object(at: indexPath.section) as! Array<Any>
// Configure the cell
cell.imageView.image = UIImage(named: "image1")
cell.label.text = ar[indexPath.row] as? String
return cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
var reusableView: PhotoCollectionReusableView? = nil
if kind == UICollectionElementKindSectionHeader {
reusableView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: reuseIdentifierHeader, for: indexPath) as? PhotoCollectionReusableView
reusableView?.label.text = "bla-bla-bla"
}
return reusableView!
}
// MARK: UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
return false
}
override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return false
}
override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
}
*/
}
| mit | 48ebf4e845aee1e9f7c74eb06f59edea | 39.120301 | 212 | 0.708208 | 5.774892 | false | false | false | false |
aptyr/-github-iOS | #github-ios/presenter/LoginPresenter.swift | 1 | 1455 | //
// LoginPresentable.swift
// #github-ios
//
// Created by Artur on 05/04/2017.
// Copyright © 2017 Artur Matusiak. All rights reserved.
//
import Foundation
class LoginPresenter: LoginPresentable {
private let view: LoginView
private var interactor: LoginInteractable?
private var state: LoginState? {
return LoginStateFactory.getLoginState(hasAccessTokenKey: Secure.token(forUser: "aptyr") != nil)
}
required init(view: LoginView) {
self.view = view
NotificationCenterController.observeAuthURLSchema(notificationHandler: self.authURLSchemaObserver)
self.interactor = LoginInteractor(presenter: self)
}
private func authURLSchemaObserver(notification: Notification) {
let url = notification.object as? URL
let queryItems = URLComponents(string: (url?.absoluteString)!)?.queryItems
let codeParam = queryItems?.filter {$0.name == "code"}.first?.value
if let _ = codeParam {
self.interactor?.getAccessToken(code: codeParam!)
}
}
func updateView() {
guard let state = self.state else { return }
self.view.webView(asHidden: state.shouldWebViewBeHidden())
}
func obtain(accessToken: AccessToken) {
try? Secure.store(accessToken: accessToken, forUser: "aptyr")
self.view.close()
}
}
| apache-2.0 | a81ecece54d46c1543a66153f602322b | 25.436364 | 106 | 0.630674 | 4.720779 | false | false | false | false |
tardieu/swift | test/attr/attr_specialize.swift | 1 | 13287 | // RUN: %target-typecheck-verify-swift
// RUN: %target-swift-ide-test -print-ast-typechecked -source-filename=%s -disable-objc-attr-requires-foundation-module | %FileCheck %s
struct S<T> {}
public protocol P {
}
extension Int: P {
}
public protocol ProtocolWithDep {
associatedtype Element
}
public class C1 {
}
class Base {}
class Sub : Base {}
class NonSub {}
// Specialize freestanding functions with the correct number of concrete types.
// ----------------------------------------------------------------------------
// CHECK: @_specialize(exported: false, kind: full, where T == Int)
@_specialize(where T == Int)
// CHECK: @_specialize(exported: false, kind: full, where T == S<Int>)
@_specialize(where T == S<Int>)
@_specialize(where T == Int, U == Int) // expected-error{{use of undeclared type 'U'}},
@_specialize(where T == T1) // expected-error{{use of undeclared type 'T1'}}
public func oneGenericParam<T>(_ t: T) -> T {
return t
}
// CHECK: @_specialize(exported: false, kind: full, where T == Int, U == Int)
@_specialize(where T == Int, U == Int)
@_specialize(where T == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'U' in '_specialize' attribute}}
public func twoGenericParams<T, U>(_ t: T, u: U) -> (T, U) {
return (t, u)
}
@_specialize(where T == Int) // expected-error{{trailing 'where' clause in '_specialize' attribute of non-generic function 'nonGenericParam'}}
func nonGenericParam(x: Int) {}
// Specialize contextual types.
// ----------------------------
class G<T> {
// CHECK: @_specialize(exported: false, kind: full, where T == Int)
@_specialize(where T == Int)
@_specialize(where T == T) // expected-error{{Only concrete type same-type requirements are supported by '_specialize' attribute}}
@_specialize(where T == S<T>) // expected-error{{Only concrete type same-type requirements are supported by '_specialize' attribute}}
@_specialize(where T == Int, U == Int) // expected-error{{use of undeclared type 'U'}}
func noGenericParams() {}
// CHECK: @_specialize(exported: false, kind: full, where T == Int, U == Float)
@_specialize(where T == Int, U == Float)
// CHECK: @_specialize(exported: false, kind: full, where T == Int, U == S<Int>)
@_specialize(where T == Int, U == S<Int>)
@_specialize(where T == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error {{Missing constraint for 'U' in '_specialize' attribute}}
func oneGenericParam<U>(_ t: T, u: U) -> (U, T) {
return (u, t)
}
}
// Specialize with requirements.
// -----------------------------
protocol Thing {}
struct AThing : Thing {}
// CHECK: @_specialize(exported: false, kind: full, where T == AThing)
@_specialize(where T == AThing)
@_specialize(where T == Int) // expected-error{{same-type constraint type 'Int' does not conform to required protocol 'Thing'}}
func oneRequirement<T : Thing>(_ t: T) {}
protocol HasElt {
associatedtype Element
}
struct IntElement : HasElt {
typealias Element = Int
}
struct FloatElement : HasElt {
typealias Element = Float
}
@_specialize(where T == FloatElement)
@_specialize(where T == IntElement) // expected-error{{generic parameter 'T.Element' cannot be equal to both 'Float' and 'Int'}}
func sameTypeRequirement<T : HasElt>(_ t: T) where T.Element == Float {}
@_specialize(where T == Sub)
@_specialize(where T == NonSub) // expected-error{{'T' requires that 'NonSub' inherit from 'Base'}}
func superTypeRequirement<T : Base>(_ t: T) {}
@_specialize(where X:_Trivial(8), Y == Int) // expected-error{{trailing 'where' clause in '_specialize' attribute of non-generic function 'requirementOnNonGenericFunction'}}
public func requirementOnNonGenericFunction(x: Int, y: Int) {
}
@_specialize(where Y == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}}
public func missingRequirement<X:P, Y>(x: X, y: Y) {
}
@_specialize(where) // expected-error{{expected identifier for type name}}
@_specialize() // expected-error{{expected a parameter label or a where clause in '_specialize' attribute}} expected-error{{expected declaration}}
public func funcWithEmptySpecializeAttr<X: P, Y>(x: X, y: Y) {
}
@_specialize(where X:_Trivial(8), Y:_Trivial(32), Z == Int) // expected-error{{use of undeclared type 'Z'}}
@_specialize(where X:_Trivial(8), Y:_Trivial(32, 4))
@_specialize(where X == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'Y' in '_specialize' attribute}}
@_specialize(where Y:_Trivial(32)) // expected-error {{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}}
@_specialize(where Y: P) // expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}}
@_specialize(where Y: MyClass) // expected-error{{use of undeclared type 'MyClass'}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}}
@_specialize(where X:_Trivial(8), Y == Int)
@_specialize(where X == Int, Y == Int)
@_specialize(where X == Int, X == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'Y' in '_specialize' attribute}}
@_specialize(where Y:_Trivial(32), X == Float)
@_specialize(where X1 == Int, Y1 == Int) // expected-error{{use of undeclared type 'X1'}} expected-error{{use of undeclared type 'Y1'}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 0, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}} expected-error{{Missing constraint for 'Y' in '_specialize' attribute}}
public func funcWithTwoGenericParameters<X, Y>(x: X, y: Y) {
}
@_specialize(where X == Int, Y == Int)
@_specialize(exported: true, where X == Int, Y == Int)
@_specialize(exported: false, where X == Int, Y == Int)
@_specialize(exported: false where X == Int, Y == Int) // expected-error{{missing ',' in '_specialize' attribute}}
@_specialize(exported: yes, where X == Int, Y == Int) // expected-error{{expected a boolean true or false value in '_specialize' attribute}}
@_specialize(exported: , where X == Int, Y == Int) // expected-error{{expected a boolean true or false value in '_specialize' attribute}}
@_specialize(kind: partial, where X == Int, Y == Int)
@_specialize(kind: partial, where X == Int)
@_specialize(kind: full, where X == Int, Y == Int)
@_specialize(kind: any, where X == Int, Y == Int) // expected-error{{expected 'partial' or 'full' as values of the 'kind' parameter in '_specialize' attribute}}
@_specialize(kind: false, where X == Int, Y == Int) // expected-error{{expected 'partial' or 'full' as values of the 'kind' parameter in '_specialize' attribute}}
@_specialize(kind: partial where X == Int, Y == Int) // expected-error{{missing ',' in '_specialize' attribute}}
@_specialize(kind: partial, where X == Int, Y == Int)
@_specialize(kind: , where X == Int, Y == Int)
@_specialize(exported: true, kind: partial, where X == Int, Y == Int)
@_specialize(exported: true, exported: true, where X == Int, Y == Int) // expected-error{{parameter 'exported' was already defined in '_specialize' attribute}}
@_specialize(kind: partial, exported: true, where X == Int, Y == Int)
@_specialize(kind: partial, kind: partial, where X == Int, Y == Int) // expected-error{{parameter 'kind' was already defined in '_specialize' attribute}}
@_specialize(where X == Int, Y == Int, exported: true, kind: partial) // expected-error{{use of undeclared type 'exported'}} expected-error{{use of undeclared type 'kind'}} expected-error{{use of undeclared type 'partial'}} expected-error{{expected identifier for type name}}
public func anotherFuncWithTwoGenericParameters<X: P, Y>(x: X, y: Y) {
}
@_specialize(where T: P) // expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}}
@_specialize(where T: Int) // expected-error{{Only conformances to protocol types are supported by '_specialize' attribute}} expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}}
@_specialize(where T: S1) // expected-error{{Only conformances to protocol types are supported by '_specialize' attribute}} expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}}
@_specialize(where T: C1) // expected-error{{Only conformances to protocol types are supported by '_specialize' attribute}} expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}}
@_specialize(where Int: P) // expected-error{{type 'Int' in conformance requirement does not refer to a generic parameter or associated type}} expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 0, but expected 1)}} expected-error{{Missing constraint for 'T' in '_specialize' attribute}}
func funcWithForbiddenSpecializeRequirement<T>(_ t: T) {
}
@_specialize(where T: _Trivial(32), T: _Trivial(64), T: _Trivial, T: _RefCountedObject) // expected-error{{multiple layout constraints cannot be used at the same time: '_Trivial(64)' and '_Trivial(32)'}} expected-note{{previous layout constraint declaration '_Trivial(32)' was here}} expected-error{{multiple layout constraints cannot be used at the same time: '_Trivial' and '_Trivial(32)'}} expected-note{{previous layout constraint declaration '_Trivial(32)' was here}} expected-error{{multiple layout constraints cannot be used at the same time: '_RefCountedObject' and '_Trivial(32)'}} expected-note{{previous layout constraint declaration '_Trivial(32)' was here}}
@_specialize(where Array<T> == Int) // expected-error{{Only requirements on generic parameters are supported by '_specialize' attribute}}
// expected-error@-1{{generic signature requires types 'Array<T>' and 'Int' to be the same}}
@_specialize(where T.Element == Int) // expected-error{{Only requirements on generic parameters are supported by '_specialize' attribute}}
public func funcWithComplexSpecializeRequirements<T: ProtocolWithDep>(t: T) -> Int {
return 55555
}
public struct S1 {
}
@_specialize(exported: false, where T == Int64)
public func simpleGeneric<T>(t: T) -> T {
return t
}
@_specialize(exported: true, where S: _Trivial(64))
// Check that any bitsize size is OK, not only powers of 8.
@_specialize(where S: _Trivial(60))
@_specialize(exported: true, where S: _RefCountedObject)
@inline(never)
public func copyValue<S>(_ t: S, s: inout S) -> Int64 where S: P{
return 1
}
@_specialize(exported: true, where S: _Trivial)
@_specialize(exported: true, where S: _Trivial(64))
@_specialize(exported: true, where S: _Trivial(32))
@_specialize(exported: true, where S: _RefCountedObject)
@inline(never)
public func copyValueAndReturn<S>(_ t: S, s: inout S) -> S where S: P{
return s
}
struct OuterStruct<S> {
struct MyStruct<T> {
@_specialize(where T == Int, U == Float) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 2, but expected 3)}} expected-error{{Missing constraint for 'S' in '_specialize' attribute}}
public func foo<U>(u : U) {
}
@_specialize(where T == Int, U == Float, S == Int)
public func bar<U>(u : U) {
}
}
}
// Check _TrivialAtMostN constraints.
@_specialize(exported: true, where S: _TrivialAtMost(64))
@inline(never)
public func copy2<S>(_ t: S, s: inout S) -> S where S: P{
return s
}
// Check missing alignment.
@_specialize(where S: _Trivial(64, )) // expected-error{{expected non-negative alignment to be specified in layout constraint}}
// Check non-numeric size.
@_specialize(where S: _Trivial(Int)) // expected-error{{expected non-negative size to be specified in layout constraint}}
// Check non-numeric alignment.
@_specialize(where S: _Trivial(64, X)) // expected-error{{expected non-negative alignment to be specified in layout constraint}}
@inline(never)
public func copy3<S>(_ s: S) -> S {
return s
}
public func funcWithWhereClause<T>(t: T) where T:P, T: _Trivial(64) { // expected-error{{layout constraints are only allowed inside '_specialize' attributes}}
}
// rdar://problem/29333056
public protocol P1 {
associatedtype DP1
associatedtype DP11
}
public protocol P2 {
associatedtype DP2 : P1
}
public struct H<T> {
}
public struct MyStruct3 : P1 {
public typealias DP1 = Int
public typealias DP11 = H<Int>
}
public struct MyStruct4 : P2 {
public typealias DP2 = MyStruct3
}
@_specialize(where T==MyStruct4)
public func foo<T: P2>(_ t: T) where T.DP2.DP11 == H<T.DP2.DP1> {
}
| apache-2.0 | e40fd7b011065a507a51cafb634e6e27 | 52.361446 | 670 | 0.701889 | 3.757636 | false | false | false | false |
wang-chuanhui/CHSDK | Source/Application/Application.swift | 1 | 706 | //
// Application.swift
// CHSDK
//
// Created by 王传辉 on 2017/8/18.
// Copyright © 2017年 王传辉. All rights reserved.
//
import Foundation
public class Application {
public static let shared: Application = Application()
private init() {
}
public private(set) lazy var images: [Image] = {
var images: [Image] = []
var count: UInt32 = 0
let imageNames = objc_copyImageNames(&count)
(0..<count).forEach({ (i) in
let advanced = imageNames.advanced(by: Int(i))
let pointee = advanced.pointee
images.append(Image(imageName: pointee))
})
return images
}()
}
| mit | 40f429808158d3dbf96c841bf42f7e0e | 18.742857 | 58 | 0.561505 | 3.971264 | false | false | false | false |
Snowy1803/BreakBaloon-mobile | BreakBaloon/Settings/SettingScene.swift | 1 | 5801 | //
// SettingScene.swift
// BreakBaloon
//
// Created by Emil on 21/06/2016.
// Copyright © 2016 Snowy_1803. All rights reserved.
//
import AVFoundation
import SpriteKit
class SettingScene: SKScene, ECLoginDelegate {
var previous: StartScene
var ok: Button!
var reset: Button!
var extensions: Button!
var login: Button!
var audioSetting: AudioSlider
var musicSetting: AudioSlider
var musicIndexSetting: MusicSelector
var themeIndexSetting: ThemeSelector
convenience init(previous: StartScene) {
self.init(previous, previous.view!.gvc)
}
init(_ previous: StartScene, _ gvc: GameViewController) {
self.previous = previous
audioSetting = AudioSlider(name: NSLocalizedString("settings.audio", comment: "Sound effects"), music: false, gvc: gvc)
musicSetting = AudioSlider(name: NSLocalizedString("settings.music", comment: "Music"), music: true, gvc: gvc)
musicIndexSetting = MusicSelector(gvc: gvc)
themeIndexSetting = ThemeSelector(gvc: gvc)
super.init(size: previous.frame.size)
backgroundColor = SKColor.brown
let top = frame.height - (gvc.skView?.safeAreaInsets.top ?? 0)
let name = SKLabelNode(text: NSLocalizedString("settings.title", comment: "Settings"))
name.fontName = Button.fontName
name.fontColor = SKColor.black
name.position = CGPoint(x: frame.midX, y: top - 50)
addChild(name)
audioSetting.volume = gvc.audioVolume
audioSetting.position = CGPoint(x: frame.width / 2, y: top - 150)
addChild(audioSetting)
musicSetting.volume = gvc.backgroundMusicPlayer.volume
musicSetting.position = CGPoint(x: frame.width / 2, y: top - 250)
addChild(musicSetting)
musicIndexSetting.position = CGPoint(x: frame.width / 2, y: top - 300)
addChild(musicIndexSetting)
themeIndexSetting.position = CGPoint(x: frame.width / 2, y: top - 400)
addChild(themeIndexSetting)
extensions = Button(size: .mini, text: NSLocalizedString("settings.extensions", comment: "Extensions"))
extensions.position = CGPoint(x: frame.width / 3, y: top - 500)
addChild(extensions)
login = Button(size: .mini, text: NSLocalizedString("settings.log\(ECLoginManager.shared.loggedIn ? "out" : "in")", comment: "login/out"))
login.position = CGPoint(x: frame.width / 3 * 2, y: top - 500)
addChild(login)
let bottom = gvc.skView?.safeAreaInsets.bottom ?? 0
ok = Button(size: .mini, text: NSLocalizedString("ok", comment: "Ok"))
ok.position = CGPoint(x: frame.width / 3, y: 50 + bottom)
addChild(ok)
reset = Button(size: .mini, text: NSLocalizedString("reset", comment: "Reset settings"))
reset.position = CGPoint(x: frame.width / 3 * 2, y: 50 + bottom)
addChild(reset)
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesEnded(_ touches: Set<UITouch>, with _: UIEvent?) {
if touches.count == 1 {
let touch = touches.first!
let point = touch.location(in: self)
if onNode(ok, point: point) {
close()
} else if onNode(reset, point: point) {
resetSettings()
} else if onNode(extensions, point: point) {
showExtConfig()
} else if onNode(login, point: point) {
DispatchQueue.main.async { [self] in
if ECLoginManager.shared.loggedIn {
ECLoginManager.shared.logOut()
loginDidComplete()
} else {
ECLoginManager.shared.logInDialog(delegate: self)
}
}
} else if onNode(audioSetting, point: point) {
audioSetting.calculateVolume(touch)
} else if onNode(musicSetting, point: point) {
musicSetting.calculateVolume(touch)
} else if onNode(musicIndexSetting, point: point) {
musicIndexSetting.click(touch)
} else if onNode(themeIndexSetting, point: point) {
themeIndexSetting.click(touch)
}
}
}
func present(alert: UIAlertController) {
view?.gvc.present(alert, animated: true, completion: nil)
}
func loginDidComplete() {
login.label.text = NSLocalizedString("settings.log\(ECLoginManager.shared.loggedIn ? "out" : "in")", comment: "login/out")
}
override func touchesMoved(_ touches: Set<UITouch>, with _: UIEvent?) {
if touches.count == 1 {
let touch = touches.first!
let point = touch.location(in: self)
if onNode(audioSetting, point: point) {
audioSetting.calculateVolume(touch)
} else if onNode(musicSetting, point: point) {
musicSetting.calculateVolume(touch)
}
}
}
func resetSettings() {
audioSetting.volume = GameViewController.defaultAudioVolume
musicSetting.volume = GameViewController.defaultMusicVolume
musicIndexSetting.reset()
}
func close() {
view?.presentScene(previous, transition: SKTransition.doorsCloseHorizontal(withDuration: 1))
}
func showExtConfig() {
let scene = ExtensionSettingScene(self)
view?.presentScene(scene, transition: SKTransition.push(with: .left, duration: 1))
scene.initialize()
}
func onNode(_ node: SKNode, point: CGPoint) -> Bool {
node.frame.contains(point)
}
}
| mit | fe57f212425a9a4b13b94ace27982f8c | 38.189189 | 146 | 0.605172 | 4.403948 | false | false | false | false |
neilsardesai/chrono-swift | Sample Apps/ChronoSample/Chrono/Chrono.swift | 2 | 9284 | //
// Chrono.swift
// chrono-swift
//
// Created by Neil Sardesai on 2016-11-16.
// Copyright © 2016 Neil Sardesai. All rights reserved.
//
import Foundation
import JavaScriptCore
/// A singleton that contains methods for extracting date information from natural language phrases. Subclassing is not allowed.
final class Chrono {
/// Use this property to get the shared singleton instance of `Chrono`
static let shared = Chrono()
private var context: JSContext
private init() {
// Create JavaScript environment
context = JSContext()
// Load chrono.min.js
let path = Bundle.main.path(forResource: "chrono.min", ofType: "js")
let url = URL(fileURLWithPath: path!)
var chronoJSSource = try! String(contentsOf: url, encoding: .utf8)
// Won’t work without this
chronoJSSource = "var window = this;\n \(chronoJSSource)"
// Evaluate chrono.min.js
context.evaluateScript(chronoJSSource)
}
// MARK: Convenience Methods
/**
Attempts to extract a date from a given natural language phrase. The reference date is assumed to be the current system date.
Example: If the current system date is November 20th, 2016 9:41 AM CST, and the natural language phrase is “2 days ago”, the return `Date` will be November 18th, 2016 9:41 AM CST
- Parameter naturalLanguageString: The input natural language phrase
- Returns: A `Date` extracted from the input `naturalLanguageString`. If a `Date` could not be found, returns `nil`.
*/
func dateFrom(naturalLanguageString: String) -> Date? {
let results = parsedResultsFrom(naturalLanguageString: naturalLanguageString, referenceDate: nil)
guard let date = results.startDate else { return nil }
return date
}
/**
Attempts to extract a date interval from a given natural language phrase. The reference date is assumed to be the current system date.
Example: If the current system date is November 20th, 2016 9:41 AM CST, and the natural language phrase is “tomorrow from 3-4 PM”, the return `DateInterval` will be November 21th, 2016 3:00 PM CST - November 21th, 2016 4:00 PM CST
- Parameter naturalLanguageString: The input natural language phrase
- Returns: A `DateInterval` extracted from the input `naturalLanguageString`. If a `DateInterval` could not be found, returns `nil`.
*/
func dateIntervalFrom(naturalLanguageString: String) -> DateInterval? {
let results = parsedResultsFrom(naturalLanguageString: naturalLanguageString, referenceDate: nil)
guard let startDate = results.startDate, let endDate = results.endDate else { return nil }
return DateInterval(start: startDate, end: endDate)
}
/**
Attempts to extract a date from a given natural language phrase. A reference date is required. If you want to use the current system date as the reference date, use `dateFrom(naturalLanguageString:)` instead.
Example: If the reference date is October 18th, 2016 9:41 AM CST, and the natural language phrase is “2 days ago”, the return `Date` will be October 16th, 2016 9:41 AM CST
- Parameter naturalLanguageString: The input natural language phrase
- Parameter referenceDate: The reference date used to calculate the return `Date`
- Returns: A `Date` extracted from the input `naturalLanguageString` and calculated based on the `referenceDate`. If a `Date` could not be found, returns `nil`.
*/
func dateFrom(naturalLanguageString: String, referenceDate: Date) -> Date? {
let results = parsedResultsFrom(naturalLanguageString: naturalLanguageString, referenceDate: referenceDate)
guard let date = results.startDate else { return nil }
return date
}
/**
Attempts to extract a date interval from a given natural language phrase. A reference date is required. If you want to use the current system date as the reference date, use `dateIntervalFrom(naturalLanguageString:)` instead.
Example: If the reference date is October 18th, 2016 9:41 AM CST, and the natural language phrase is “tomorrow from 3-4 PM”, the return `DateInterval` will be October 19th, 2016 3:00 PM - October 19th, 2016 4:00 PM.
- Parameter naturalLanguageString: The input natural language phrase
- Parameter referenceDate: The reference date used to calculate the return `DateInterval`
- Returns: A `DateInterval` extracted from the input `naturalLanguageString` and calculated based on the `referenceDate`. If a `DateInterval` could not be found, returns `nil`.
*/
func dateIntervalFrom(naturalLanguageString: String, referenceDate: Date) -> DateInterval? {
let results = parsedResultsFrom(naturalLanguageString: naturalLanguageString, referenceDate: referenceDate)
guard let startDate = results.startDate, let endDate = results.endDate else { return nil }
return DateInterval(start: startDate, end: endDate)
}
// MARK: Detailed Parsed Results
/**
Attempts to extract date information from a given natural language phrase and returns a `ChronoParsedResult` with detailed results about the extracted date information. You can optionally pass in a reference date for date calculations. If no reference date is passed in, the reference date is assumed to be the current system date.
- Parameter naturalLanguageString: The input natural language phrase
- Parameter referenceDate: The reference date used to calculate date information. If you specify `nil` for this parameter, `referenceDate` is assumed to be the current system date.
- Returns: A `ChronoParsedResult` with details about extracted date information
*/
func parsedResultsFrom(naturalLanguageString: String, referenceDate: Date?) -> ChronoParsedResult {
context.setObject(naturalLanguageString, forKeyedSubscript: "naturalLanguageString" as NSString)
if let referenceDate = referenceDate {
// Get year, month, day from referenceDate
context.setObject(referenceDate, forKeyedSubscript: "referenceDate" as NSString)
context.evaluateScript("var results = chrono.parse(naturalLanguageString, referenceDate);")
}
else {
// Reference date is automatically current date if referenceDate is nil
context.evaluateScript("var results = chrono.parse(naturalLanguageString);")
}
// Position in natural language string where time phrase starts
let index = context.evaluateScript("results[0].index;")
var indexOfStartingCharacterOfTimePhrase: Int?
if index!.description != "undefined" {
indexOfStartingCharacterOfTimePhrase = Int(index!.toInt32())
}
// Separate time phrase from rest of input string
let text = context.evaluateScript("results[0].text;")
var timePhrase: String?
var ignoredText: String?
if text!.description != "undefined" {
timePhrase = text!.toString()
// Filter out (on/in) + (the) + timePhrase
let timePhrasePattern = "(?>\\s*)*(\\bon|\\bin)*(?>\\s*)*(\\bthe)*(?>\\s*)*\(timePhrase!)(?>\\s*[[:punct:]]*\\s*)*"
let timePhraseRegex = try! NSRegularExpression(pattern: timePhrasePattern, options: .caseInsensitive)
ignoredText = timePhraseRegex.stringByReplacingMatches(in: naturalLanguageString, options: [], range: NSRange(0..<naturalLanguageString.utf16.count), withTemplate: " ")
ignoredText = ignoredText?.trimmingCharacters(in: .whitespacesAndNewlines)
}
// Reference date used by Chrono
let ref = context.evaluateScript("results[0].ref;")
var referenceDateFromContext: Date?
if ref!.description != "undefined" {
referenceDateFromContext = ref!.toDate()
}
// Date discovered in time phrase. In the case of a date range, this is the start date.
let start = context.evaluateScript("results[0].start.date();")
var startDate: Date?
if start!.description != "undefined" {
startDate = start!.toDate()
}
// In the case of a date range, this is the end date.
let end = context.evaluateScript("results[0].end.date();")
var endDate: Date?
if end!.description != "undefined" {
endDate = end!.toDate()
}
// Create date interval in the case of a date range
var dateInterval: DateInterval?
if let startDate = startDate, let endDate = endDate {
dateInterval = DateInterval(start: startDate, end: endDate)
}
return ChronoParsedResult(inputString: naturalLanguageString, indexOfStartingCharacterOfTimePhrase: indexOfStartingCharacterOfTimePhrase, timePhrase: timePhrase, ignoredText: ignoredText, referenceDate: referenceDateFromContext, startDate: startDate, endDate: endDate, dateInterval: dateInterval)
}
}
| mit | 0ddff8080423d1b29f3e4ca104881e07 | 51.942857 | 336 | 0.679007 | 4.90991 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/PushToTalk.swift | 1 | 18120 | //
// PushToTalk.swift
// Telegram
//
// Created by Mikhail Filimonov on 02/12/2020.
// Copyright © 2020 Telegram. All rights reserved.
//
import Foundation
import HotKey
import SwiftSignalKit
import TGUIKit
import InAppSettings
import KeyboardKey
extension PushToTalkValue {
func isEqual(_ value: KeyboardGlobalHandler.Result) -> Bool {
return value.keyCodes == self.keyCodes && self.modifierFlags == value.modifierFlags && value.otherMouse == self.otherMouse
}
}
final class KeyboardGlobalHandler {
static func hasPermission(askPermission: Bool = true) -> Bool {
let result: Bool
if #available(macOS 10.15, *) {
result = PermissionsManager.checkInputMonitoring(withPrompt: false)
} else if #available(macOS 10.14, *) {
result = PermissionsManager.checkAccessibility(withPrompt: false)
} else {
result = true
}
if !result && askPermission {
self.requestPermission()
}
return result
}
static func requestPermission() -> Void {
if #available(macOS 10.15, *) {
_ = PermissionsManager.checkInputMonitoring(withPrompt: true)
} else if #available(macOS 10.14, *) {
_ = PermissionsManager.checkAccessibility(withPrompt: true)
} else {
}
}
private struct Handler {
let pushToTalkValue: PushToTalkValue?
let success:(Result)->Void
let eventType: NSEvent.EventTypeMask
init(PushToTalkValue: PushToTalkValue?, success:@escaping(Result)->Void, eventType: NSEvent.EventTypeMask) {
self.pushToTalkValue = PushToTalkValue
self.success = success
self.eventType = eventType
}
}
struct Result {
let keyCodes: [UInt16]
let otherMouse:[Int]
let modifierFlags: [PushToTalkValue.ModifierFlag]
let string: String
let eventType: NSEvent.EventTypeMask
}
private var monitors: [Any?] = []
private var keyDownHandler: Handler?
private var keyUpHandler: Handler?
private var eventTap: CFMachPort?
private var runLoopSource:CFRunLoopSource?
static func getPermission()->Signal<Bool, NoError> {
return Signal { subscriber in
subscriber.putNext(KeyboardGlobalHandler.hasPermission(askPermission: false))
subscriber.putCompletion()
return EmptyDisposable
} |> runOn(.concurrentDefaultQueue()) |> deliverOnMainQueue
}
private let disposable = MetaDisposable()
enum Mode {
case local(WeakReference<Window>)
case global
}
private let mode: Mode
init(mode: Mode) {
self.mode = mode
switch mode {
case .global:
self.disposable.set(KeyboardGlobalHandler.getPermission().start(next: { [weak self] value in
self?.runListener(hasPermission: value)
}))
case .local:
self.runListener(hasPermission: false)
}
}
private func runListener(hasPermission: Bool) {
final class ProcessEvent {
var process:(NSEvent)->Void = { _ in }
}
let processEvent = ProcessEvent()
processEvent.process = { [weak self] event in
self?.process(event)
}
if hasPermission {
func callback(proxy: CGEventTapProxy, type: CGEventType, event: CGEvent, refcon: UnsafeMutableRawPointer?) -> Unmanaged<CGEvent>? {
if let event = NSEvent(cgEvent: event) {
let processor = Unmanaged<ProcessEvent>.fromOpaque(refcon!).takeUnretainedValue()
processor.process(event)
}
return Unmanaged.passRetained(event)
}
let eventMask:Int32 = (1 << CGEventType.keyDown.rawValue) |
(1 << CGEventType.otherMouseDown.rawValue) |
(1 << CGEventType.otherMouseUp.rawValue) |
(1 << CGEventType.keyUp.rawValue) |
(1 << CGEventType.flagsChanged.rawValue)
self.eventTap = CGEvent.tapCreate(tap: .cghidEventTap,
place: .headInsertEventTap,
options: .listenOnly,
eventsOfInterest: CGEventMask(eventMask),
callback: callback,
userInfo: UnsafeMutableRawPointer(Unmanaged.passRetained(processEvent).toOpaque()))
if let eventTap = self.eventTap {
let runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0)
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, .commonModes)
CGEvent.tapEnable(tap: eventTap, enable: true)
self.runLoopSource = runLoopSource
}
} else {
monitors.append(NSEvent.addLocalMonitorForEvents(matching: [.keyUp, .keyDown, .flagsChanged, .otherMouseUp, .otherMouseDown], handler: { [weak self] event in
guard let `self` = self else {
return event
}
self.process(event)
return event
}))
}
}
deinit {
for monitor in monitors {
if let monitor = monitor {
NSEvent.removeMonitor(monitor)
}
}
if let eventTap = eventTap {
CGEvent.tapEnable(tap: eventTap, enable: false)
}
if let source = self.runLoopSource {
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), source, .commonModes)
}
disposable.dispose()
}
private var downStake:[NSEvent] = []
private var otherMouseDownStake:[NSEvent] = []
private var flagsStake:[NSEvent] = []
private var currentDownStake:[NSEvent] = []
private var currentOtherMouseDownStake:[NSEvent] = []
private var currentFlagsStake:[NSEvent] = []
var activeCount: Int {
var total:Int = 0
if currentDownStake.count > 0 {
total += currentDownStake.count
}
if currentFlagsStake.count > 0 {
total += currentFlagsStake.count
}
if currentOtherMouseDownStake.count > 0 {
total += currentOtherMouseDownStake.count
}
return total
}
@discardableResult private func process(_ event: NSEvent) -> Bool {
switch mode {
case .global:
break
case let .local(window):
if window.value?.windowNumber != event.windowNumber {
return false
}
}
let oldActiveCount = self.activeCount
switch event.type {
case .keyUp:
currentDownStake.removeAll(where: { $0.keyCode == event.keyCode })
case .keyDown:
if !downStake.contains(where: { $0.keyCode == event.keyCode }) {
downStake.append(event)
}
if !currentDownStake.contains(where: { $0.keyCode == event.keyCode }) {
currentDownStake.append(event)
}
case .otherMouseDown:
if !otherMouseDownStake.contains(where: { $0.buttonNumber == event.buttonNumber }) {
otherMouseDownStake.append(event)
}
if !currentOtherMouseDownStake.contains(where: { $0.buttonNumber == event.buttonNumber }) {
currentOtherMouseDownStake.append(event)
}
case .otherMouseUp:
currentOtherMouseDownStake.removeAll(where: { $0.buttonNumber == event.buttonNumber })
case .flagsChanged:
if !flagsStake.contains(where: { $0.keyCode == event.keyCode }) {
flagsStake.append(event)
}
if !currentFlagsStake.contains(where: { $0.keyCode == event.keyCode }) {
currentFlagsStake.append(event)
} else {
currentFlagsStake.removeAll(where: { $0.keyCode == event.keyCode })
}
default:
break
}
let newActiveCount = self.activeCount
if oldActiveCount != newActiveCount {
applyStake(oldActiveCount < newActiveCount)
}
if self.activeCount == 0 {
self.downStake.removeAll()
self.flagsStake.removeAll()
self.otherMouseDownStake.removeAll()
}
return false
}
private var isDownSent: Bool = false
private var isUpSent: Bool = false
@discardableResult private func applyStake(_ isDown: Bool) -> Bool {
var string = ""
var _flags: [PushToTalkValue.ModifierFlag] = []
let finalFlag = self.flagsStake.max(by: { lhs, rhs in
return lhs.modifierFlags.rawValue < rhs.modifierFlags.rawValue
})
if let finalFlag = finalFlag {
string += StringFromKeyCode(finalFlag.keyCode, finalFlag.modifierFlags.rawValue)!
}
for flag in flagsStake {
_flags.append(PushToTalkValue.ModifierFlag(keyCode: flag.keyCode, flag: flag.modifierFlags.rawValue))
}
var _keyCodes:[UInt16] = []
for key in downStake {
string += StringFromKeyCode(key.keyCode, 0)!.uppercased()
if key != downStake.last {
string += " + "
}
_keyCodes.append(key.keyCode)
}
var _otherMouse:[Int] = []
for key in otherMouseDownStake {
if !string.isEmpty {
string += " + "
}
string += "MOUSE\(key.buttonNumber)"
if key != otherMouseDownStake.last {
string += " + "
}
_otherMouse.append(key.buttonNumber)
}
let result = Result(keyCodes: _keyCodes, otherMouse: _otherMouse, modifierFlags: _flags, string: string, eventType: isDown ? .keyDown : .keyUp)
string = ""
var flags: [PushToTalkValue.ModifierFlag] = []
for flag in currentFlagsStake {
flags.append(PushToTalkValue.ModifierFlag(keyCode: flag.keyCode, flag: flag.modifierFlags.rawValue))
}
var keyCodes:[UInt16] = []
for key in currentDownStake {
keyCodes.append(key.keyCode)
}
var otherMouses:[Int] = []
for key in currentOtherMouseDownStake {
otherMouses.append(key.buttonNumber)
}
let invokeUp:(PushToTalkValue)->Bool = { ptt in
var invoke: Bool = false
for keyCode in ptt.keyCodes {
if !keyCodes.contains(keyCode) {
invoke = true
}
}
for mouse in ptt.otherMouse {
if !otherMouses.contains(mouse) {
invoke = true
}
}
for flag in ptt.modifierFlags {
if !flags.contains(flag) {
invoke = true
}
}
return invoke
}
let invokeDown:(PushToTalkValue)->Bool = { ptt in
var invoke: Bool = true
for keyCode in ptt.keyCodes {
if !keyCodes.contains(keyCode) {
invoke = false
}
}
for buttonNumber in ptt.otherMouse {
if !otherMouses.contains(buttonNumber) {
invoke = false
}
}
for flag in ptt.modifierFlags {
if !flags.contains(flag) {
invoke = false
}
}
return invoke
}
var isHandled: Bool = false
if isDown {
isUpSent = false
if let keyDown = self.keyDownHandler {
if let ptt = keyDown.pushToTalkValue {
if invokeDown(ptt) {
keyDown.success(result)
isDownSent = true
isHandled = true
}
} else {
keyDown.success(result)
isDownSent = true
isHandled = true
}
}
} else {
if let keyUp = self.keyUpHandler {
if let ptt = keyUp.pushToTalkValue {
if invokeUp(ptt), (isDownSent || keyDownHandler == nil), !isUpSent {
keyUp.success(result)
isHandled = true
isUpSent = true
}
} else if (isDownSent || keyDownHandler == nil), !isUpSent {
keyUp.success(result)
isHandled = true
isUpSent = true
}
}
}
if activeCount == 0 {
isDownSent = false
}
return isHandled
}
func setKeyDownHandler(_ pushToTalkValue: PushToTalkValue?, success: @escaping(Result)->Void) {
self.keyDownHandler = .init(PushToTalkValue: pushToTalkValue, success: success, eventType: .keyDown)
}
func setKeyUpHandler(_ pushToTalkValue: PushToTalkValue?, success: @escaping(Result)->Void) {
self.keyUpHandler = .init(PushToTalkValue: pushToTalkValue, success: success, eventType: .keyUp)
}
func removeHandlers() {
self.keyDownHandler = nil
self.keyUpHandler = nil
}
}
final class PushToTalk {
enum Mode {
case speaking(sound: String?)
case waiting(sound: String?)
case toggle(activate: String?, deactivate: String?)
}
var update: (Mode)->Void = { _ in }
private let disposable = MetaDisposable()
private let actionDisposable = MetaDisposable()
private let monitor: KeyboardGlobalHandler
private let spaceMonitor: KeyboardGlobalHandler
private let spaceEvent = PushToTalkValue(keyCodes: [KeyboardKey.Space.rawValue], otherMouse: [], modifierFlags: [], string: "⎵")
init(sharedContext: SharedAccountContext, window: Window) {
self.monitor = KeyboardGlobalHandler(mode: .global)
self.spaceMonitor = KeyboardGlobalHandler(mode: .local(WeakReference(value: window)))
let settings = voiceCallSettings(sharedContext.accountManager) |> deliverOnMainQueue
disposable.set(settings.start(next: { [weak self] settings in
self?.updateSettings(settings)
}))
}
private func installSpaceMonitor(settings: VoiceCallSettings) {
switch settings.mode {
case .pushToTalk:
self.spaceMonitor.setKeyDownHandler(spaceEvent, success: { [weak self] result in
self?.proccess(result.eventType, false)
})
self.spaceMonitor.setKeyUpHandler(spaceEvent, success: { [weak self] result in
self?.proccess(result.eventType, false)
})
case .always:
self.spaceMonitor.setKeyDownHandler(spaceEvent, success: { _ in
})
self.spaceMonitor.setKeyUpHandler(spaceEvent, success: { [weak self] result in
self?.update(.toggle(activate: nil, deactivate: nil))
})
case .none:
self.spaceMonitor.removeHandlers()
}
}
private func deinstallSpaceMonitor() {
self.spaceMonitor.removeHandlers()
}
private func updateSettings(_ settings: VoiceCallSettings) {
let performSound: Bool = settings.pushToTalkSoundEffects
switch settings.mode {
case .always:
if let event = settings.pushToTalk {
self.monitor.setKeyUpHandler(event, success: { [weak self] result in
self?.update(.toggle(activate: nil, deactivate: nil))
})
self.monitor.setKeyDownHandler(event, success: {_ in
})
if event == spaceEvent {
deinstallSpaceMonitor()
} else {
installSpaceMonitor(settings: settings)
}
} else {
self.monitor.removeHandlers()
installSpaceMonitor(settings: settings)
}
case .pushToTalk:
if let event = settings.pushToTalk {
self.monitor.setKeyUpHandler(event, success: { [weak self] result in
self?.proccess(result.eventType, performSound)
})
self.monitor.setKeyDownHandler(event, success: { [weak self] result in
self?.proccess(result.eventType, performSound)
})
if event == spaceEvent {
deinstallSpaceMonitor()
} else {
installSpaceMonitor(settings: settings)
}
} else {
self.monitor.removeHandlers()
installSpaceMonitor(settings: settings)
}
case .none:
self.monitor.removeHandlers()
deinstallSpaceMonitor()
}
}
private func proccess(_ eventType: NSEvent.EventTypeMask, _ performSound: Bool) {
if eventType == .keyUp {
let signal = Signal<NoValue, NoError>.complete() |> delay(0.15, queue: .mainQueue())
actionDisposable.set(signal.start(completed: { [weak self] in
self?.update(.waiting(sound: performSound ? "Pop" : nil))
}))
} else if eventType == .keyDown {
actionDisposable.set(nil)
self.update(.speaking(sound: performSound ? "Purr" : nil))
}
}
deinit {
actionDisposable.dispose()
disposable.dispose()
}
}
| gpl-2.0 | 8616027df7f5cd17a498fd127847ad38 | 34.042553 | 169 | 0.544627 | 4.901786 | false | false | false | false |
qiuncheng/study-for-swift | TestPromiseKit/Pods/PromiseKit/Sources/when.swift | 17 | 8771 | #if os(Linux)
import Foundation
import Dispatch
#else
import Foundation.NSProgress
#endif
private func _when<T>(_ promises: [Promise<T>]) -> Promise<Void> {
let root = Promise<Void>.pending()
var countdown = promises.count
guard countdown > 0 else {
root.fulfill()
return root.promise
}
#if !PMKDisableProgress
#if os(Linux)
let progress = NSProgress(totalUnitCount: Int64(promises.count))
progress.cancellable = false
progress.pausable = false
#else
let progress = Progress(totalUnitCount: Int64(promises.count))
progress.isCancellable = false
progress.isPausable = false
#endif //Linux
#else
var progress: (completedUnitCount: Int, totalUnitCount: Int) = (0, 0)
#endif
let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: .concurrent)
for promise in promises {
promise.state.pipe { resolution in
barrier.sync(flags: .barrier) {
switch resolution {
case .rejected(let error, let token):
token.consumed = true
if root.promise.isPending {
progress.completedUnitCount = progress.totalUnitCount
root.reject(error)
}
case .fulfilled:
guard root.promise.isPending else { return }
progress.completedUnitCount += 1
countdown -= 1
if countdown == 0 {
root.fulfill()
}
}
}
}
}
return root.promise
}
/**
Wait for all promises in a set to fulfill.
For example:
when(fulfilled: promise1, promise2).then { results in
//…
}.catch { error in
switch error {
case NSURLError.NoConnection:
//…
case CLError.NotAuthorized:
//…
}
}
- Note: If *any* of the provided promises reject, the returned promise is immediately rejected with that error.
- Warning: In the event of rejection the other promises will continue to resolve and, as per any other promise, will either fulfill or reject. This is the right pattern for `getter` style asynchronous tasks, but often for `setter` tasks (eg. storing data on a server), you most likely will need to wait on all tasks and then act based on which have succeeded and which have failed, in such situations use `when(resolved:)`.
- Parameter promises: The promises upon which to wait before the returned promise resolves.
- Returns: A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects.
- Note: `when` provides `NSProgress`.
- SeeAlso: `when(resolved:)`
*/
public func when<T>(fulfilled promises: [Promise<T>]) -> Promise<[T]> {
return _when(promises).then(on: zalgo) { promises.map{ $0.value! } }
}
/// Wait for all promises in a set to fulfill.
public func when(fulfilled promises: Promise<Void>...) -> Promise<Void> {
return _when(promises)
}
/// Wait for all promises in a set to fulfill.
public func when(fulfilled promises: [Promise<Void>]) -> Promise<Void> {
return _when(promises)
}
/// Wait for all promises in a set to fulfill.
public func when<U, V>(fulfilled pu: Promise<U>, _ pv: Promise<V>) -> Promise<(U, V)> {
return _when([pu.asVoid(), pv.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!) }
}
/// Wait for all promises in a set to fulfill.
public func when<U, V, W>(fulfilled pu: Promise<U>, _ pv: Promise<V>, _ pw: Promise<W>) -> Promise<(U, V, W)> {
return _when([pu.asVoid(), pv.asVoid(), pw.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!, pw.value!) }
}
/// Wait for all promises in a set to fulfill.
public func when<U, V, W, X>(fulfilled pu: Promise<U>, _ pv: Promise<V>, _ pw: Promise<W>, _ px: Promise<X>) -> Promise<(U, V, W, X)> {
return _when([pu.asVoid(), pv.asVoid(), pw.asVoid(), px.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!, pw.value!, px.value!) }
}
/// Wait for all promises in a set to fulfill.
public func when<U, V, W, X, Y>(fulfilled pu: Promise<U>, _ pv: Promise<V>, _ pw: Promise<W>, _ px: Promise<X>, _ py: Promise<Y>) -> Promise<(U, V, W, X, Y)> {
return _when([pu.asVoid(), pv.asVoid(), pw.asVoid(), px.asVoid(), py.asVoid()]).then(on: zalgo) { (pu.value!, pv.value!, pw.value!, px.value!, py.value!) }
}
/**
Generate promises at a limited rate and wait for all to fulfill.
For example:
func downloadFile(url: URL) -> Promise<Data> {
// ...
}
let urls: [URL] = /*…*/
let urlGenerator = urls.makeIterator()
let generator = AnyIterator<Promise<Data>> {
guard url = urlGenerator.next() else {
return nil
}
return downloadFile(url)
}
when(generator, concurrently: 3).then { datum: [Data] -> Void in
// ...
}
- Warning: Refer to the warnings on `when(fulfilled:)`
- Parameter promiseGenerator: Generator of promises.
- Returns: A new promise that resolves when all the provided promises fulfill or one of the provided promises rejects.
- SeeAlso: `when(resolved:)`
*/
public func when<T, PromiseIterator: IteratorProtocol>(fulfilled promiseIterator: PromiseIterator, concurrently: Int) -> Promise<[T]> where PromiseIterator.Element == Promise<T> {
guard concurrently > 0 else {
return Promise(error: PMKError.whenConcurrentlyZero)
}
var generator = promiseIterator
var root = Promise<[T]>.pending()
var pendingPromises = 0
var promises: [Promise<T>] = []
let barrier = DispatchQueue(label: "org.promisekit.barrier.when", attributes: [.concurrent])
func dequeue() {
guard root.promise.isPending else { return } // don’t continue dequeueing if root has been rejected
var shouldDequeue = false
barrier.sync {
shouldDequeue = pendingPromises < concurrently
}
guard shouldDequeue else { return }
var index: Int!
var promise: Promise<T>!
barrier.sync(flags: .barrier) {
guard let next = generator.next() else { return }
promise = next
index = promises.count
pendingPromises += 1
promises.append(next)
}
func testDone() {
barrier.sync {
if pendingPromises == 0 {
root.fulfill(promises.flatMap{ $0.value })
}
}
}
guard promise != nil else {
return testDone()
}
promise.state.pipe { resolution in
barrier.sync(flags: .barrier) {
pendingPromises -= 1
}
switch resolution {
case .fulfilled:
dequeue()
testDone()
case .rejected(let error, let token):
token.consumed = true
root.reject(error)
}
}
dequeue()
}
dequeue()
return root.promise
}
/**
Waits on all provided promises.
`when(fulfilled:)` rejects as soon as one of the provided promises rejects. `when(resolved:)` waits on all provided promises and **never** rejects.
when(resolved: promise1, promise2, promise3).then { results in
for result in results where case .fulfilled(let value) {
//…
}
}.catch { error in
// invalid! Never rejects
}
- Returns: A new promise that resolves once all the provided promises resolve.
- Warning: The returned promise can *not* be rejected.
- Note: Any promises that error are implicitly consumed, your UnhandledErrorHandler will not be called.
*/
public func when<T>(resolved promises: Promise<T>...) -> Promise<[Result<T>]> {
return when(resolved: promises)
}
/// Waits on all provided promises.
public func when<T>(resolved promises: [Promise<T>]) -> Promise<[Result<T>]> {
guard !promises.isEmpty else { return Promise(value: []) }
var countdown = promises.count
let barrier = DispatchQueue(label: "org.promisekit.barrier.join", attributes: .concurrent)
return Promise { fulfill, reject in
for promise in promises {
promise.state.pipe { resolution in
if case .rejected(_, let token) = resolution {
token.consumed = true // all errors are implicitly consumed
}
var done = false
barrier.sync(flags: .barrier) {
countdown -= 1
done = countdown == 0
}
if done {
fulfill(promises.map { Result($0.state.get()!) })
}
}
}
}
}
| mit | 923babe39c8647bac88c467da611be76 | 32.818533 | 424 | 0.596758 | 4.274768 | false | false | false | false |
PomTTcat/SourceCodeGuideRead_JEFF | RxSwiftGuideRead/RxSwift-master/Tests/RxCocoaTests/DelegateProxyTest+UIKit.swift | 2 | 19601 | //
// DelegateProxyTest+UIKit.swift
// Tests
//
// Created by Krunoslav Zaher on 12/5/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import UIKit
@testable import RxCocoa
@testable import RxSwift
import XCTest
// MARK: Tests
extension DelegateProxyTest {
func test_UITableViewDelegateExtension() {
performDelegateTest(UITableViewSubclass1(frame: CGRect.zero)) { ExtendTableViewDelegateProxy(tableViewSubclass: $0) }
}
func test_UITableViewDataSourceExtension() {
performDelegateTest(UITableViewSubclass2(frame: CGRect.zero)) { ExtendTableViewDataSourceProxy(tableViewSubclass: $0) }
}
@available(iOS 10.0, tvOS 10.0, *)
func test_UITableViewDataSourcePrefetchingExtension() {
performDelegateTest(UITableViewSubclass3(frame: CGRect.zero)) { ExtendTableViewDataSourcePrefetchingProxy(parentObject: $0) }
}
}
extension DelegateProxyTest {
func test_UICollectionViewDelegateExtension() {
let layout = UICollectionViewFlowLayout()
performDelegateTest(UICollectionViewSubclass1(frame: CGRect.zero, collectionViewLayout: layout)) { ExtendCollectionViewDelegateProxy(parentObject: $0) }
}
func test_UICollectionViewDataSourceExtension() {
let layout = UICollectionViewFlowLayout()
performDelegateTest(UICollectionViewSubclass2(frame: CGRect.zero, collectionViewLayout: layout)) { ExtendCollectionViewDataSourceProxy(parentObject: $0) }
}
@available(iOS 10.0, tvOS 10.0, *)
func test_UICollectionViewDataSourcePrefetchingExtension() {
let layout = UICollectionViewFlowLayout()
performDelegateTest(UICollectionViewSubclass3(frame: CGRect.zero, collectionViewLayout: layout)) { ExtendCollectionViewDataSourcePrefetchingProxy(parentObject: $0) }
}
}
extension DelegateProxyTest {
func test_UINavigationControllerDelegateExtension() {
performDelegateTest(UINavigationControllerSubclass()) { ExtendNavigationControllerDelegateProxy(navigationControllerSubclass: $0) }
}
}
extension DelegateProxyTest {
func test_UIScrollViewDelegateExtension() {
performDelegateTest(UIScrollViewSubclass(frame: CGRect.zero)) { ExtendScrollViewDelegateProxy(scrollViewSubclass: $0) }
}
}
#if os(iOS)
extension DelegateProxyTest {
func test_UISearchBarDelegateExtension() {
performDelegateTest(UISearchBarSubclass(frame: CGRect.zero)) { ExtendSearchBarDelegateProxy(searchBarSubclass: $0) }
}
}
#endif
extension DelegateProxyTest {
func test_UITextViewDelegateExtension() {
performDelegateTest(UITextViewSubclass(frame: CGRect.zero)) { ExtendTextViewDelegateProxy(textViewSubclass: $0) }
}
}
#if os(iOS)
extension DelegateProxyTest {
func test_UISearchController() {
performDelegateTest(UISearchControllerSubclass()) { ExtendSearchControllerDelegateProxy(searchControllerSubclass: $0) }
}
}
extension DelegateProxyTest {
func test_UIPickerViewExtension() {
performDelegateTest(UIPickerViewSubclass(frame: CGRect.zero)) { ExtendPickerViewDelegateProxy(pickerViewSubclass: $0) }
}
func test_UIPickerViewDataSourceExtension() {
performDelegateTest(UIPickerViewSubclass2(frame: CGRect.zero)) { ExtendPickerViewDataSourceProxy(pickerViewSubclass: $0) }
}
}
#endif
#if os(iOS)
extension DelegateProxyTest {
func test_UIWebViewDelegateExtension() {
performDelegateTest(UIWebViewSubclass(frame: CGRect.zero)) { ExtendWebViewDelegateProxy(webViewSubclass: $0) }
}
}
#endif
extension DelegateProxyTest {
func test_UITabBarControllerDelegateExtension() {
performDelegateTest(UITabBarControllerSubclass()) { ExtendTabBarControllerDelegateProxy(tabBarControllerSubclass: $0) }
}
}
extension DelegateProxyTest {
func test_UITabBarDelegateExtension() {
performDelegateTest(UITabBarSubclass()) { ExtendTabBarDelegateProxy(tabBarSubclass: $0) }
}
}
extension DelegateProxyTest {
/* something is wrong with subclassing mechanism.
func test_NSTextStorageDelegateExtension() {
performDelegateTest(NSTextStorageSubclass(attributedString: NSAttributedString()))
}*/
}
// MARK: Mocks
final class ExtendTableViewDelegateProxy
: RxTableViewDelegateProxy
, TestDelegateProtocol {
weak fileprivate(set) var control: UITableViewSubclass1?
init(tableViewSubclass: UITableViewSubclass1) {
self.control = tableViewSubclass
super.init(tableView: tableViewSubclass)
}
}
final class UITableViewSubclass1
: UITableView
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UIScrollView, UIScrollViewDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UIScrollViewDelegate) -> Disposable {
return RxScrollViewDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendTableViewDataSourceProxy
: RxTableViewDataSourceProxy
, TestDelegateProtocol {
weak fileprivate(set) var control: UITableViewSubclass2?
init(tableViewSubclass: UITableViewSubclass2) {
self.control = tableViewSubclass
super.init(tableView: tableViewSubclass)
}
}
final class UITableViewSubclass2
: UITableView
, TestDelegateControl {
func doThatTest(_ value: Int) {
if dataSource != nil {
(dataSource as! TestDelegateProtocol).testEventHappened?(value)
}
}
var delegateProxy: DelegateProxy<UITableView, UITableViewDataSource> {
return self.rx.dataSource
}
func setMineForwardDelegate(_ testDelegate: UITableViewDataSource) -> Disposable {
return RxTableViewDataSourceProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
@available(iOS 10.0, tvOS 10.0, *)
final class ExtendTableViewDataSourcePrefetchingProxy
: RxTableViewDataSourcePrefetchingProxy
, TestDelegateProtocol {
weak fileprivate(set) var control: UITableViewSubclass3?
init(parentObject: UITableViewSubclass3) {
self.control = parentObject
super.init(tableView: parentObject)
}
}
@available(iOS 10.0, tvOS 10.0, *)
final class UITableViewSubclass3
: UITableView
, TestDelegateControl {
func doThatTest(_ value: Int) {
if prefetchDataSource != nil {
(prefetchDataSource as! TestDelegateProtocol).testEventHappened?(value)
}
}
var delegateProxy: DelegateProxy<UITableView, UITableViewDataSourcePrefetching> {
return self.rx.prefetchDataSource
}
func setMineForwardDelegate(_ testDelegate: UITableViewDataSourcePrefetching) -> Disposable {
return RxTableViewDataSourcePrefetchingProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendCollectionViewDelegateProxy
: RxCollectionViewDelegateProxy
, TestDelegateProtocol {
weak fileprivate(set) var control: UICollectionViewSubclass1?
init(parentObject: UICollectionViewSubclass1) {
self.control = parentObject
super.init(collectionView: parentObject)
}
}
final class UICollectionViewSubclass1
: UICollectionView
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UIScrollView, UIScrollViewDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UIScrollViewDelegate) -> Disposable {
return RxScrollViewDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendCollectionViewDataSourceProxy
: RxCollectionViewDataSourceProxy
, TestDelegateProtocol {
weak fileprivate(set) var control: UICollectionViewSubclass2?
init(parentObject: UICollectionViewSubclass2) {
self.control = parentObject
super.init(collectionView: parentObject)
}
}
final class UICollectionViewSubclass2
: UICollectionView
, TestDelegateControl {
func doThatTest(_ value: Int) {
if dataSource != nil {
(dataSource as! TestDelegateProtocol).testEventHappened?(value)
}
}
var delegateProxy: DelegateProxy<UICollectionView, UICollectionViewDataSource> {
return self.rx.dataSource
}
func setMineForwardDelegate(_ testDelegate: UICollectionViewDataSource) -> Disposable {
return RxCollectionViewDataSourceProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
@available(iOS 10.0, tvOS 10.0, *)
final class ExtendCollectionViewDataSourcePrefetchingProxy
: RxCollectionViewDataSourcePrefetchingProxy
, TestDelegateProtocol {
weak fileprivate(set) var control: UICollectionViewSubclass3?
init(parentObject: UICollectionViewSubclass3) {
self.control = parentObject
super.init(collectionView: parentObject)
}
}
@available(iOS 10.0, tvOS 10.0, *)
final class UICollectionViewSubclass3
: UICollectionView
, TestDelegateControl {
func doThatTest(_ value: Int) {
if prefetchDataSource != nil {
(prefetchDataSource as! TestDelegateProtocol).testEventHappened?(value)
}
}
var delegateProxy: DelegateProxy<UICollectionView, UICollectionViewDataSourcePrefetching> {
return self.rx.prefetchDataSource
}
func setMineForwardDelegate(_ testDelegate: UICollectionViewDataSourcePrefetching) -> Disposable {
return RxCollectionViewDataSourcePrefetchingProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendScrollViewDelegateProxy
: RxScrollViewDelegateProxy
, TestDelegateProtocol {
weak fileprivate(set) var control: UIScrollViewSubclass?
init(scrollViewSubclass: UIScrollViewSubclass) {
self.control = scrollViewSubclass
super.init(scrollView: scrollViewSubclass)
}
}
final class UIScrollViewSubclass
: UIScrollView
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UIScrollView, UIScrollViewDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UIScrollViewDelegate) -> Disposable {
return RxScrollViewDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
#if os(iOS)
final class ExtendSearchBarDelegateProxy
: RxSearchBarDelegateProxy
, TestDelegateProtocol {
weak fileprivate(set) var control: UISearchBarSubclass?
init(searchBarSubclass: UISearchBarSubclass) {
self.control = searchBarSubclass
super.init(searchBar: searchBarSubclass)
}
}
final class UISearchBarSubclass
: UISearchBar
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UISearchBar, UISearchBarDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UISearchBarDelegate) -> Disposable {
return RxSearchBarDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
#endif
final class ExtendTextViewDelegateProxy
: RxTextViewDelegateProxy
, TestDelegateProtocol {
weak fileprivate(set) var control: UITextViewSubclass?
init(textViewSubclass: UITextViewSubclass) {
self.control = textViewSubclass
super.init(textView: textViewSubclass)
}
}
final class UITextViewSubclass
: UITextView
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UIScrollView, UIScrollViewDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UIScrollViewDelegate) -> Disposable {
return RxScrollViewDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
#if os(iOS)
final class ExtendSearchControllerDelegateProxy
: RxSearchControllerDelegateProxy
, TestDelegateProtocol {
init(searchControllerSubclass: UISearchControllerSubclass) {
super.init(searchController: searchControllerSubclass)
}
}
final class UISearchControllerSubclass
: UISearchController
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UISearchController, UISearchControllerDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UISearchControllerDelegate) -> Disposable {
return RxSearchControllerDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendPickerViewDelegateProxy
: RxPickerViewDelegateProxy
, TestDelegateProtocol {
init(pickerViewSubclass: UIPickerViewSubclass) {
super.init(pickerView: pickerViewSubclass)
}
}
final class UIPickerViewSubclass
: UIPickerView
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UIPickerView, UIPickerViewDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UIPickerViewDelegate) -> Disposable {
return RxPickerViewDelegateProxy.installForwardDelegate(testDelegate,
retainDelegate: false,
onProxyForObject: self)
}
}
final class ExtendPickerViewDataSourceProxy
: RxPickerViewDataSourceProxy
, TestDelegateProtocol {
weak fileprivate(set) var control: UIPickerViewSubclass2?
init(pickerViewSubclass: UIPickerViewSubclass2) {
self.control = pickerViewSubclass
super.init(pickerView: pickerViewSubclass)
}
}
final class UIPickerViewSubclass2: UIPickerView, TestDelegateControl {
func doThatTest(_ value: Int) {
if dataSource != nil {
(dataSource as! TestDelegateProtocol).testEventHappened?(value)
}
}
var delegateProxy: DelegateProxy<UIPickerView, UIPickerViewDataSource> {
return self.rx.dataSource
}
func setMineForwardDelegate(_ testDelegate: UIPickerViewDataSource) -> Disposable {
return RxPickerViewDataSourceProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendWebViewDelegateProxy
: RxWebViewDelegateProxy
, TestDelegateProtocol {
init(webViewSubclass: UIWebViewSubclass) {
super.init(webView: webViewSubclass)
}
}
final class UIWebViewSubclass: UIWebView, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UIWebView, UIWebViewDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UIWebViewDelegate) -> Disposable {
return RxWebViewDelegateProxy.installForwardDelegate(testDelegate,
retainDelegate: false,
onProxyForObject: self)
}
}
#endif
final class ExtendTextStorageDelegateProxy
: RxTextStorageDelegateProxy
, TestDelegateProtocol {
init(textStorageSubclass: NSTextStorageSubclass) {
super.init(textStorage: textStorageSubclass)
}
}
final class NSTextStorageSubclass
: NSTextStorage
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<NSTextStorage, NSTextStorageDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: NSTextStorageDelegate) -> Disposable {
return RxTextStorageDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendNavigationControllerDelegateProxy
: RxNavigationControllerDelegateProxy
, TestDelegateProtocol {
weak fileprivate(set) var control: UINavigationControllerSubclass?
init(navigationControllerSubclass: UINavigationControllerSubclass) {
self.control = navigationControllerSubclass
super.init(navigationController: navigationControllerSubclass)
}
}
final class ExtendTabBarControllerDelegateProxy
: RxTabBarControllerDelegateProxy
, TestDelegateProtocol {
weak fileprivate(set) var tabBarControllerSubclass: UITabBarControllerSubclass?
init(tabBarControllerSubclass: UITabBarControllerSubclass) {
self.tabBarControllerSubclass = tabBarControllerSubclass
super.init(tabBar: tabBarControllerSubclass)
}
}
final class ExtendTabBarDelegateProxy
: RxTabBarDelegateProxy
, TestDelegateProtocol {
weak fileprivate(set) var control: UITabBarSubclass?
init(tabBarSubclass: UITabBarSubclass) {
self.control = tabBarSubclass
super.init(tabBar: tabBarSubclass)
}
}
final class UINavigationControllerSubclass: UINavigationController, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UINavigationController, UINavigationControllerDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UINavigationControllerDelegate) -> Disposable {
return RxNavigationControllerDelegateProxy.installForwardDelegate(testDelegate,
retainDelegate: false,
onProxyForObject: self)
}
}
final class UITabBarControllerSubclass
: UITabBarController
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UITabBarController, UITabBarControllerDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UITabBarControllerDelegate) -> Disposable {
return RxTabBarControllerDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class UITabBarSubclass: UITabBar, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UITabBar, UITabBarDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UITabBarDelegate) -> Disposable {
return RxTabBarDelegateProxy.installForwardDelegate(testDelegate,
retainDelegate: false,
onProxyForObject: self)
}
}
| mit | 6df331d78eaa9b56b5df4a0ccce026a2 | 31.941176 | 173 | 0.724184 | 5.488659 | false | true | false | false |
qiuncheng/study-for-swift | learn-rx-swift/Pods/RxSwift/RxSwift/Observables/Implementations/Do.swift | 32 | 1999 | //
// Do.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
final class DoSink<O: ObserverType> : Sink<O>, ObserverType {
typealias Element = O.E
typealias Parent = Do<Element>
private let _parent: Parent
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
do {
try _parent._eventHandler(event)
forwardOn(event)
if event.isStopEvent {
dispose()
}
}
catch let error {
forwardOn(.error(error))
dispose()
}
}
}
final class Do<Element> : Producer<Element> {
typealias EventHandler = (Event<Element>) throws -> Void
fileprivate let _source: Observable<Element>
fileprivate let _eventHandler: EventHandler
fileprivate let _onSubscribe: (() -> ())?
fileprivate let _onSubscribed: (() -> ())?
fileprivate let _onDispose: (() -> ())?
init(source: Observable<Element>, eventHandler: @escaping EventHandler, onSubscribe: (() -> ())?, onSubscribed: (() -> ())?, onDispose: (() -> ())?) {
_source = source
_eventHandler = eventHandler
_onSubscribe = onSubscribe
_onSubscribed = onSubscribed
_onDispose = onDispose
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
_onSubscribe?()
let sink = DoSink(parent: self, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
_onSubscribed?()
let onDispose = _onDispose
let allSubscriptions = Disposables.create {
subscription.dispose()
onDispose?()
}
return (sink: sink, subscription: allSubscriptions)
}
}
| mit | f5f3f0a36918fc24deedd7b8af211723 | 30.21875 | 154 | 0.586587 | 4.734597 | false | false | false | false |
VikingDen/actor-platform | actor-apps/app-ios/ActorApp/Controllers Support/Alerts.swift | 24 | 6551 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
private var pickDocumentClosure = "_pick_document_closure"
private var actionShitReference = "_action_shit"
extension UIViewController {
func alertUser(message: String) {
RMUniversalAlert.showAlertInViewController(self,
withTitle: nil,
message: NSLocalizedString(message, comment: "Message"),
cancelButtonTitle: NSLocalizedString("AlertOk", comment: "Ok"),
destructiveButtonTitle: nil,
otherButtonTitles: nil,
tapBlock: nil)
}
func confirmAlertUser(message: String, action: String, tapYes: ()->()) {
confirmAlertUser(message, action: action, tapYes: tapYes, tapNo: nil)
}
func confirmAlertUser(message: String, action: String, tapYes: ()->(), tapNo: (()->())?) {
RMUniversalAlert.showAlertInViewController(self,
withTitle: nil,
message: NSLocalizedString(message, comment: "Message"),
cancelButtonTitle: NSLocalizedString("AlertCancel", comment: "Cancel"),
destructiveButtonTitle: nil,
otherButtonTitles: [NSLocalizedString(action, comment: "Cancel")],
tapBlock: { (alert, buttonIndex) -> Void in
if (buttonIndex >= alert.firstOtherButtonIndex) {
tapYes()
} else {
tapNo?()
}
})
}
func textInputAlert(message: String, content: String?, action:String, tapYes: (nval: String)->()) {
var alertView = UIAlertView(
title: nil,
message: NSLocalizedString(message, comment: "Title"),
delegate: self,
cancelButtonTitle: NSLocalizedString("AlertCancel", comment: "Cancel Title"))
alertView.addButtonWithTitle(NSLocalizedString(action, comment: "Action Title"))
alertView.alertViewStyle = UIAlertViewStyle.PlainTextInput
alertView.textFieldAtIndex(0)!.autocapitalizationType = UITextAutocapitalizationType.Words
alertView.textFieldAtIndex(0)!.text = content
alertView.textFieldAtIndex(0)!.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light
alertView.tapBlock = { (alert: UIAlertView, buttonIndex) -> () in
if (buttonIndex != alert.cancelButtonIndex) {
tapYes(nval: alert.textFieldAtIndex(0)!.text)
}
}
alertView.show()
}
func confirmUser(message: String, action: String, cancel: String, sourceView: UIView, sourceRect: CGRect, tapYes: ()->()) {
RMUniversalAlert.showActionSheetInViewController(
self,
withTitle: nil,
message: NSLocalizedString(message, comment: "Message"),
cancelButtonTitle: NSLocalizedString(cancel, comment: "Cancel Title"),
destructiveButtonTitle: NSLocalizedString(action, comment: "Destruct Title"),
otherButtonTitles: nil,
popoverPresentationControllerBlock: { (popover: RMPopoverPresentationController) -> Void in
popover.sourceView = sourceView
popover.sourceRect = sourceRect
},
tapBlock: { (alert, buttonIndex) -> Void in
if (buttonIndex == alert.destructiveButtonIndex) {
tapYes()
}
})
}
func showActionSheet(title: String?, buttons: [String], cancelButton: String?, destructButton: String?, sourceView: UIView, sourceRect: CGRect, tapClosure: (index: Int) -> ()) {
var convertedButtons:[String] = [String]()
for b in buttons {
convertedButtons.append(NSLocalizedString(b, comment: "Button Title"))
}
RMUniversalAlert.showActionSheetInViewController(
self,
withTitle: nil,
message: title,
cancelButtonTitle: cancelButton != nil ? NSLocalizedString(cancelButton!, comment: "Cancel") : nil,
destructiveButtonTitle: destructButton != nil ? NSLocalizedString(destructButton!, comment: "Destruct") : nil,
otherButtonTitles: convertedButtons,
popoverPresentationControllerBlock: { (popover: RMPopoverPresentationController) -> Void in
popover.sourceView = sourceView
popover.sourceRect = sourceRect
},
tapBlock: { (alert, buttonIndex) -> Void in
if (buttonIndex == alert.cancelButtonIndex) {
tapClosure(index: -1)
} else if (buttonIndex == alert.destructiveButtonIndex) {
tapClosure(index: -2)
} else if (buttonIndex >= alert.firstOtherButtonIndex) {
tapClosure(index: buttonIndex - alert.firstOtherButtonIndex)
}
})
}
func showActionSheet(buttons: [String], cancelButton: String?, destructButton: String?, sourceView: UIView, sourceRect: CGRect, tapClosure: (index: Int) -> ()) {
showActionSheet(nil, buttons:buttons, cancelButton: cancelButton, destructButton: destructButton, sourceView: sourceView, sourceRect:sourceRect, tapClosure: tapClosure)
}
func showActionSheetFast(buttons: [String], cancelButton: String, tapClosure: (index: Int) -> ()) {
var actionShit = ABActionShit()
var convertedButtons:[String] = [String]()
for b in buttons {
convertedButtons.append(NSLocalizedString(b, comment: "Button Title"))
}
actionShit.buttonTitles = convertedButtons
actionShit.cancelButtonTitle = NSLocalizedString(cancelButton,comment: "Cancel")
var shitDelegate = ActionShitDelegate(tapClosure: tapClosure)
actionShit.delegate = shitDelegate
// Convert from weak to strong reference
setAssociatedObject(actionShit, shitDelegate, &actionShitReference, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
actionShit.showWithCompletion(nil)
}
}
class ActionShitDelegate: NSObject, ABActionShitDelegate {
let tapClosure: (index: Int) -> ()
init (tapClosure: (index: Int) -> ()) {
self.tapClosure = tapClosure
}
func actionShit(actionShit: ABActionShit!, clickedButtonAtIndex buttonIndex: Int) {
tapClosure(index: buttonIndex)
}
func actionShitClickedCancelButton(actionShit: ABActionShit!) {
tapClosure(index: -1)
}
}
| mit | 9895970d58b88174f431a99f6e827b8b | 42.673333 | 181 | 0.628454 | 5.308752 | false | false | false | false |
Coderian/SwiftedKML | SwiftedKML/Elements/MultiGeometry.swift | 1 | 2548 | //
// MultiGeometry.swift
// SwiftedKML
//
// Created by 佐々木 均 on 2016/02/02.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// KML MultiGeometry
///
/// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd)
///
/// <element name="MultiGeometry" type="kml:MultiGeometryType" substitutionGroup="kml:AbstractGeometryGroup"/>
public class MultiGeometry :SPXMLElement, AbstractGeometryGroup , HasXMLElementValue {
public static var elementName: String = "MultiGeometry"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch parent {
case let v as MultiGeometry:v.value.abstractGeometryGroup.append(self)
case let v as Placemark: v.value.abstractGeometryGroup = self
default: break
}
}
}
}
public var value : MultiGeometryType
public required init(attributes:[String:String]){
self.value = MultiGeometryType(attributes: attributes)
super.init(attributes: attributes)
}
public var abstractObject : AbstractObjectType { return self.value }
public var abstractGeometry : AbstractGeometryType { return self.value }
}
/// KML MultiGeometryType
///
/// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd)
///
/// <complexType name="MultiGeometryType" final="#all">
/// <complexContent>
/// <extension base="kml:AbstractGeometryType">
/// <sequence>
/// <element ref="kml:AbstractGeometryGroup" minOccurs="0" maxOccurs="unbounded"/>
/// <element ref="kml:MultiGeometrySimpleExtensionGroup" minOccurs="0" maxOccurs="unbounded"/>
/// <element ref="kml:MultiGeometryObjectExtensionGroup" minOccurs="0" maxOccurs="unbounded"/>
/// </sequence>
/// </extension>
/// </complexContent>
/// </complexType>
/// <element name="MultiGeometrySimpleExtensionGroup" abstract="true" type="anySimpleType"/>
/// <element name="MultiGeometryObjectExtensionGroup" abstract="true" substitutionGroup="kml:AbstractObjectGroup"/>
public class MultiGeometryType: AbstractGeometryType {
public var abstractGeometryGroup: [AbstractGeometryGroup] = []
public var multiGeometrySimpleExtensionGroup: [AnyObject] = []
public var multiGeometryObjectExtensionGroup: [AbstractObjectGroup] = []
}
| mit | e8090db86e8db52d33e97fa56d16e420 | 40.516667 | 119 | 0.681253 | 4.193603 | false | false | false | false |
lemberg/obd2-swift-lib | OBD2-Swift/Classes/Parser/SensorDescriptorTable.swift | 1 | 27067 | //
// SensorDescriptorTable.swift
// OBD2Swift
//
// Created by Max Vitruk on 27/04/2017.
// Copyright © 2017 Lemberg. All rights reserved.
//
import Foundation
//------------------------------------------------------------------------------
//MARK: -
//MARK: Global Sensor Table
let NULL = ""
let VOID : ((Data)->(Float))? = nil
let VOID_F : ((Float)->(Float))? = nil
let INT_MAX = Int.max
let SensorDescriptorTable : [SensorDescriptor] = [
//MARK:- PID 0x00
SensorDescriptor(0x00,
"Supported PIDs $00", // Description
"", // Short Description
NULL, // Units Metric
INT_MAX, // Min Metric
INT_MAX, // Max Metric
NULL, // Units Imperial
INT_MAX, // Min Imperial
INT_MAX, // Max Imperial
VOID, // Calc Function
VOID_F ), // Convert Function
//MARK:- PID 0x01
SensorDescriptor(0x01,
"Monitor status since DTCs cleared",
"Includes Malfunction Indicator Lamp (MIL) status and number of DTCs.",
NULL,
INT_MAX,
INT_MAX,
NULL,
INT_MAX,
INT_MAX,
VOID,
VOID_F),
//MARK:- PID 0x02
SensorDescriptor(0x02,
"Freeze Frame Status",
"",
NULL,
INT_MAX,
INT_MAX,
NULL,
INT_MAX,
INT_MAX,
VOID,
VOID_F ),
//MARK:- PID 0x03
/* PID $03 decodes to a string description, not a numeric value */
SensorDescriptor(0x03,
"Fuel System Status",
"Fuel Status",
NULL,
INT_MAX,
INT_MAX,
NULL,
INT_MAX,
INT_MAX,
VOID,
VOID_F ),
//MARK:- PID 0x03
SensorDescriptor(0x03,
"Calculated Engine Load Value",
"Eng. Load",
"%",
0,
100,
NULL,
INT_MAX,
INT_MAX,
calcPercentage,
VOID_F),
//MARK:- PID 0x05
SensorDescriptor(0x05,
"Engine Coolant Temperature",
"ECT",
"˚C",
-40,
215,
"˚F",
-40,
419,
calcTemp,
convertTemp),
//MARK:- PID 0x06
SensorDescriptor(0x06,
"Short term fuel trim: Bank 1",
"SHORTTF1",
"%",
-100,
100,
NULL,
INT_MAX,
INT_MAX,
calcFuelTrimPercentage,
VOID_F ),
//MARK:- PID 0x07
SensorDescriptor(0x07,
"Long term fuel trim: Bank 1",
"LONGTF1",
"%",
-100,
100,
NULL,
INT_MAX,
INT_MAX,
calcFuelTrimPercentage,
VOID_F ),
//MARK:- PID 0x08
SensorDescriptor(0x08,
"Short term fuel trim: Bank 2",
"SHORTTF2",
"%",
-100,
100,
NULL,
INT_MAX,
INT_MAX,
calcFuelTrimPercentage,
VOID_F ),
//MARK:- PID 0x09
SensorDescriptor(0x09,
"Long term fuel trim: Bank 2",
"LONGTF2",
"%",
-100,
100,
NULL,
INT_MAX,
INT_MAX,
calcFuelTrimPercentage,
VOID_F ),
//MARK:- PID 0x0A
SensorDescriptor(0x0A,
"Fuel Pressure",
"Fuel Pressure",
"kPa",
0,
765,
"inHg",
0,
222,
VOID,
convertPressure ),
//MARK:- PID 0x0B
SensorDescriptor(0x0B,
"Intake Manifold Pressure",
"IMP",
"kPa",
0, 255,
"inHg",
0,
74,
calcInt,
convertPressure ),
//MARK:- PID 0x0C
SensorDescriptor(0x0C,
"Engine RPM",
"RPM",
"RPM",
0,
16384,
NULL,
INT_MAX,
INT_MAX,
calcEngineRPM,
VOID_F ),
//MARK:- PID 0x0D
SensorDescriptor(0x0D,
"Vehicle Speed",
"Speed",
"km/h",
0,
255,
"MPH",
0,
159,
calcInt,
convertSpeed ),
//MARK:- PID 0x0E
SensorDescriptor(0x0E,
"Timing Advance",
"Time Adv.",
"i",
-64,
64,
NULL,
INT_MAX,
INT_MAX,
calcTimingAdvance,
VOID_F ),
//MARK:- PID 0x0F
SensorDescriptor(0x0F,
"Intake Air Temperature",
"IAT",
"C",
-40,
215,
"F",
-40,
419,
calcTemp,
convertTemp ),
//MARK:- PID 0x10
SensorDescriptor(0x10,
"Mass Air Flow",
"MAF",
"g/s",
0,
656,
"lbs/min",
0,
87,
calcMassAirFlow,
convertAir ),
//MARK:- PID 0x11
SensorDescriptor(0x11,
"Throttle Position",
"ATP",
"%",
0,
100,
NULL,
INT_MAX,
INT_MAX,
calcPercentage,
VOID_F ),
//MARK:- PID 0x12
/* PID $12 decodes to a string description, not a numeric value */
SensorDescriptor(0x12,
"Secondary Air Status",
"Sec Air",
NULL, INT_MAX, INT_MAX, NULL, INT_MAX, INT_MAX, VOID, VOID_F ),
//MARK:- PID 0x13
/* PID $13 decodes to a string description, not a numeric value */
SensorDescriptor(0x13,
"Oxygen Sensors Present",
"O2 Sensors",
NULL, INT_MAX, INT_MAX, NULL, INT_MAX, INT_MAX, VOID, VOID_F ),
//MARK:- PID 0x14
SensorDescriptor(0x14,
"Oxygen Voltage: Bank 1, Sensor 1",
"OVB1S1",
"V",
0,
2,
NULL,
INT_MAX,
INT_MAX,
calcOxygenSensorVoltage,
VOID_F),
//MARK:- PID 0x15
SensorDescriptor(0x15,
"Oxygen Voltage: Bank 1, Sensor 2",
"OVB1S2",
"V",
0,
2,
NULL,
INT_MAX,
INT_MAX,
calcOxygenSensorVoltage,
VOID_F ),
//MARK:- PID 0x16
SensorDescriptor(0x16,
"Oxygen Voltage: Bank 1, Sensor 3",
"OVB1S3",
"V",
0,
2,
NULL,
INT_MAX,
INT_MAX,
calcOxygenSensorVoltage,
VOID_F ),
//MARK:- PID 0x17
SensorDescriptor(0x17,
"Oxygen Voltage: Bank 1, Sensor 4",
"OVB1S4",
"V",
0,
2,
NULL,
INT_MAX,
INT_MAX,
calcOxygenSensorVoltage,
VOID_F ),
//MARK:- PID 0x18
SensorDescriptor(0x18,
"Oxygen Voltage: Bank 2, Sensor 1",
"OVB1S1",
"V",
0,
2,
NULL,
INT_MAX,
INT_MAX,
calcOxygenSensorVoltage,
VOID_F ),
//MARK:- PID 0x19
SensorDescriptor(0x19,
"Oxygen Voltage: Bank 2, Sensor 2",
"OVB1S2",
"V",
0,
2,
NULL,
INT_MAX,
INT_MAX,
calcOxygenSensorVoltage,
VOID_F ),
//MARK:- PID 0x1A
SensorDescriptor(0x1A,
"Oxygen Voltage: Bank 2, Sensor 3",
"OVB1S3",
"V",
0,
2,
NULL,
INT_MAX,
INT_MAX,
calcOxygenSensorVoltage,
VOID_F ),
//MARK:- PID 0x1B
SensorDescriptor(0x1B,
"Oxygen Voltage: Bank 2, Sensor 4",
"OVB1S4",
"V",
0,
2,
NULL,
INT_MAX,
INT_MAX,
calcOxygenSensorVoltage,
VOID_F ),
//MARK:- PID 0x1C
/* PID $1C decodes to a string description, not a numeric value */
SensorDescriptor(0x1C,
"OBD standards to which this vehicle conforms",
"OBD Standard",
NULL, INT_MAX, INT_MAX, NULL, INT_MAX, INT_MAX, VOID, VOID_F ),
//MARK:- PID 0x1D
/* PID $1D decodes to a string description, not a numeric value */
SensorDescriptor(0x1D,
"Oxygen Sensors Present",
"O2 Sensors",
NULL, INT_MAX, INT_MAX, NULL, INT_MAX, INT_MAX, VOID, VOID_F ),
//MARK:- PID 0x1E
/* PID $1E decodes to a string description, not a numeric value */
SensorDescriptor(0x1E,
"Auxiliary Input Status",
"Aux Input",
NULL, INT_MAX, INT_MAX, NULL, INT_MAX, INT_MAX, VOID, VOID_F ),
//MARK:- PID 0x1F
SensorDescriptor(0x1F,
"Run Time Since Engine Start",
"Run Time",
"sec",
0,
65535,
NULL,
INT_MAX,
INT_MAX,
calcTime,
VOID_F ),
//MARK:- PID 0x20
/* PID 0x20: List Supported PIDs 0x21-0x3F */
/* No calculation or conversion */
SensorDescriptor(0x20,
"List Supported PIDs", "Supported PIDs",
"",
0,
0,
NULL, INT_MAX, INT_MAX, VOID, VOID_F ),
//MARK:- PID 0x21
SensorDescriptor(0x21,
"Distance traveled with malfunction indicator lamp (MIL) on",
"MIL Traveled",
"Km",
0,
65535,
"miles",
0,
40717,
calcDistance,
convertDistance ),
//MARK:- PID 0x22
SensorDescriptor(0x22,
"Fuel Rail Pressure (Manifold Vacuum)",
"Fuel Rail V.",
"kPa",
0,
5178,
"inHg",
0,
1502,
calcPressure,
convertPressure),
//MARK:- PID 0x23
SensorDescriptor(0x23,
"Fuel Rail Pressure (Diesel)",
"Fuel Rail D.",
"kPa",
0,
655350,
"inHg",
0,
190052,
calcPressureDiesel,
convertPressure ),
//MARK:- PID 0x24
SensorDescriptor(0x24,
"Equivalence Ratio: O2S1",
"R O2S1",
"", 0, 2,
NULL, INT_MAX, INT_MAX, calcEquivalenceRatio, VOID_F ),
//MARK:- PID 0x25
SensorDescriptor(0x25,
"Equivalence Ratio: O2S2",
"R O2S2",
"", 0, 2,
NULL, INT_MAX, INT_MAX, calcEquivalenceRatio, VOID_F ),
//MARK:- PID 0x26
SensorDescriptor(0x26,
"Equivalence Ratio: O2S3",
"R O2S3",
"", 0, 2,
NULL, INT_MAX, INT_MAX, calcEquivalenceRatio, VOID_F ),
//MARK:- PID 0x27
SensorDescriptor(0x27,
"Equivalence Ratio: O2S4", "R O2S4",
"", 0, 2,
NULL, INT_MAX, INT_MAX, calcEquivalenceRatio, VOID_F ),
//MARK:- PID 0x28
SensorDescriptor(0x28,
"Equivalence Ratio: O2S5", "R O2S5",
"", 0, 2,
NULL, INT_MAX, INT_MAX, calcEquivalenceRatio, VOID_F ),
//MARK:- PID 0x29
SensorDescriptor(0x29,
"Equivalence Ratio: O2S6", "R O2S6",
"", 0, 2,
NULL, INT_MAX, INT_MAX, calcEquivalenceRatio, VOID_F ),
//MARK:- PID 0x2A
SensorDescriptor(0x2A,
"Equivalence Ratio: O2S7", "R O2S7",
"", 0, 2,
NULL, INT_MAX, INT_MAX, calcEquivalenceRatio, VOID_F ),
//MARK:- PID 0x2B
SensorDescriptor(0x2B,
"Equivalence Ratio: O2S8", "R O2S8",
"", 0, 2,
NULL, INT_MAX, INT_MAX, calcEquivalenceRatio, VOID_F ),
//MARK:- PID 0x2C
SensorDescriptor(0x2C,
"Commanded EGR",
"EGR",
"%",
0,
100,
NULL,
INT_MAX,
INT_MAX,
calcPercentage,
VOID_F ),
//MARK:- PID 0x2D
SensorDescriptor(0x2D,
"EGR Error", "EGR Error", "%",
-100,
100,
NULL,
INT_MAX,
INT_MAX,
calcEGRError,
VOID_F ),
//MARK:- PID 0x2E
SensorDescriptor(0x2E,
"Commanded Evaporative Purge",
"Cmd Purge",
"%",
0,
100,
NULL,
INT_MAX,
INT_MAX,
calcPercentage,
VOID_F ),
//MARK:- PID 0x2F
SensorDescriptor(0x2F,
"Fuel Level Input",
"Fuel Level",
"%",
0,
100,
NULL,
INT_MAX,
INT_MAX,
calcPercentage,
VOID_F ),
//MARK:- PID 0x30
SensorDescriptor(0x30,
"Number of Warm-Ups Since Codes Cleared",
"# Warm-Ups",
"",
0,
255,
NULL, INT_MAX, INT_MAX,
calcInt,
VOID_F ),
//MARK:- PID 0x31
SensorDescriptor(0x31,
"Distance Traveled Since Codes Cleared", "Cleared Traveled",
"Km",
0,
65535,
"miles",
0,
40717,
calcDistance,
convertDistance),
//MARK:- PID 0x32
SensorDescriptor(0x32,
"Evaporative System Vapor Pressure",
"Vapor Pressure",
"Pa",
-8192,
8192,
"inHg",
-3,
3,
calcVaporPressure,
convertPressure2 ),
//MARK:- PID 0x33
SensorDescriptor(0x33,
"Barometric Pressure",
"Bar. Pressure",
"kPa",
0,
255,
"inHg",
0,
76,
calcInt,
convertPressure ),
//MARK:- PID 0x34
SensorDescriptor(0x34,
"Equivalence Ratio: O2S1",
"R O2S1",
"", 0, 2,
NULL, INT_MAX, INT_MAX,
calcEquivalenceRatio,
VOID_F ),
//MARK:- PID 0x35
SensorDescriptor(0x35,
"Equivalence Ratio: O2S2",
"R O2S2",
"", 0, 2,
NULL, INT_MAX, INT_MAX,
calcEquivalenceRatio,
VOID_F ),
//MARK:- PID 0x36
SensorDescriptor(0x36,
"Equivalence Ratio: O2S3",
"R O2S3",
"", 0, 2,
NULL, INT_MAX, INT_MAX,
calcEquivalenceRatio,
VOID_F ),
//MARK:- PID 0x37
SensorDescriptor(0x37,
"Equivalence Ratio: O2S4",
"R O2S4",
"", 0, 2,
NULL, INT_MAX, INT_MAX,
calcEquivalenceRatio,
VOID_F ),
//MARK:- PID 0x38
SensorDescriptor(0x38,
"Equivalence Ratio: O2S5",
"R O2S5",
"", 0, 2,
NULL, INT_MAX, INT_MAX, calcEquivalenceRatio, VOID_F ),
//MARK:- PID 0x39
SensorDescriptor(0x39,
"Equivalence Ratio: O2S6",
"R O2S6",
"", 0, 2,
NULL, INT_MAX, INT_MAX, calcEquivalenceRatio, VOID_F ),
//MARK:- PID 0x3A
SensorDescriptor(0x3A,
"Equivalence Ratio: O2S7",
"R O2S7",
"", 0, 2,
NULL, INT_MAX, INT_MAX, calcEquivalenceRatio, VOID_F ),
//MARK:- PID 0x3B
SensorDescriptor(0x3B,
"Equivalence Ratio: O2S8",
"R O2S8",
"", 0, 2,
NULL, INT_MAX, INT_MAX, calcEquivalenceRatio, VOID_F ),
//MARK:- PID 0x3C
SensorDescriptor(0x3C,
"Catalyst Temperature: Bank 1, Sensor 1",
"CT B1S1",
"C",
-40,
6514,
"F",
-40,
11694,
calcCatalystTemp,
convertTemp ),
//MARK:- PID 0x3D
SensorDescriptor(0x3D,
"Catalyst Temperature: Bank 2, Sensor 1",
"CT B2S1",
"C",
-40,
6514,
"F",
-40,
11694,
calcCatalystTemp,
convertTemp ),
//MARK:- PID 0x3E
SensorDescriptor(0x3E,
"Catalyst Temperature: Bank 1, Sensor 2",
"CT B1S2",
"C",-40,
6514,
"F",
-40,
11694,
calcCatalystTemp,
convertTemp ),
//MARK:- PID 0x3F
SensorDescriptor(0x3F,
"Catalyst Temperature: Bank 2, Sensor 2",
"CT B2S2",
"C",
-40,
6514,
"F",
-40,
11694,
calcCatalystTemp,
convertTemp ),
//MARK:- PID 0x40
/* PID 0x40: List Supported PIDs 0x41-0x5F */
/* No calculation or conversion */
SensorDescriptor(0x40,
NULL, NULL, NULL, INT_MAX, INT_MAX, NULL, INT_MAX, INT_MAX, VOID, VOID_F ),
//MARK:- PID 0x41
//TODO: - Decode PID $41 correctly
SensorDescriptor(0x41,
"Monitor status this drive cycle",
"Monitor status",
NULL, INT_MAX, INT_MAX, NULL, INT_MAX, INT_MAX, VOID, VOID_F),
//MARK:- PID 0x42
SensorDescriptor(0x42,
"Control Module Voltage",
"Ctrl Voltage",
"V",
0,
66,
NULL, INT_MAX, INT_MAX,
calcControlModuleVoltage,
VOID_F ),
//MARK:- PID 0x43
SensorDescriptor(0x43,
"Absolute Load Value",
"Abs Load Val",
"%",
0,
25700,
NULL, INT_MAX, INT_MAX,
calcAbsoluteLoadValue,
VOID_F ),
//MARK:- PID 0x44
SensorDescriptor(0x44,
"Command Equivalence Ratio",
"Cmd Equiv Ratio",
"",
0,
2,
NULL,
INT_MAX,
INT_MAX,
calcEquivalenceRatio,
VOID_F),
//MARK:- PID 0x45
SensorDescriptor(0x45,
"Relative Throttle Position",
"Rel Throttle Pos",
"%",
0,
100,
NULL,
INT_MAX,
INT_MAX,
calcPercentage, VOID_F ),
//MARK:- PID 0x46
SensorDescriptor(0x46,
"Ambient Air Temperature",
"Amb Air Temp",
"C",
-40,
215,
"F",
-104,
355,
calcTemp,
convertTemp ),
//MARK:- PID 0x47
SensorDescriptor(0x47,
"Absolute Throttle Position B",
"Abs Throt Pos B",
"%",
0,
100,
NULL,
INT_MAX,
INT_MAX,
calcPercentage,
VOID_F ),
//MARK:- PID 0x48
SensorDescriptor(0x48,
"Absolute Throttle Position C",
"Abs Throt Pos C",
"%",
0,100,
NULL, INT_MAX, INT_MAX,
calcPercentage,
VOID_F ),
//MARK:- PID 0x49
SensorDescriptor(0x49,
"Accelerator Pedal Position D",
"Abs Throt Pos D",
"%",
0, 100,
NULL, INT_MAX, INT_MAX,
calcPercentage,
VOID_F ),
//MARK:- PID 0x4A
SensorDescriptor(0x4A,
"Accelerator Pedal Position E",
"Abs Throt Pos E",
"%",
0, 100,
NULL, INT_MAX, INT_MAX,
calcPercentage,
VOID_F ),
//MARK:- PID 0x4B
SensorDescriptor(0x4B,
"Accelerator Pedal Position F",
"Abs Throt Pos F",
"%",
0, 100,
NULL, INT_MAX, INT_MAX,
calcPercentage,
VOID_F ),
//MARK:- PID 0x4C
SensorDescriptor(0x4C,
"Commanded Throttle Actuator",
"Cmd Throttle Act", "%",
0, 100,
NULL, INT_MAX, INT_MAX,
calcPercentage,
VOID_F ),
//MARK:- PID 0x4D
SensorDescriptor(0x4D,
"Time Run With MIL On",
"MIL Time On",
"min",
0,
65535,
NULL,
INT_MAX,
INT_MAX,
calcTime,
VOID_F ),
//MARK:- PID 0x4E
SensorDescriptor(0x4E,
"Time Since Trouble Codes Cleared",
"DTC Cleared Time",
"min",
0,
65535,
NULL,
INT_MAX,
INT_MAX,
calcTime,
VOID_F )
]
| mit | 17f477439ed918b396ef19195a6d67b0 | 29.511838 | 96 | 0.328776 | 5.104489 | false | false | false | false |
thesecretlab/Swift-iOS-Workshops-2014 | Swift/2. Functions and Closures.playground/section-1.swift | 1 | 4986 | // Playground - noun: a place where people can play
import UIKit
// MARK: -
// MARK: Functions
// Defining a function with no parameters and no return
func firstFunction() {
println("Hello!")
}
firstFunction()
// MARK: Functions with returns
// Defining a function that returns a value
func secondFunction() -> Int {
return 123
}
secondFunction()
// MARK: Functions with parameters
// Defining a function that takes parameters
func thirdFunction(firstValue: Int, secondValue: Int) -> Int {
return firstValue + secondValue
}
thirdFunction(1, 2)
// MARK: Functions returning tuple
// Functions can return multiple values, using a tuple
func fourthFunction(firstValue: Int, secondValue: Int) -> (doubled: Int, quadrupled: Int) {
return (firstValue * 2, secondValue * 4)
}
fourthFunction(2, 4)
// If a returned tuple has named components (which is optional), you can refer
// to those components by name:
// Accessing by number:
fourthFunction(2, 4).1 // = 16
// Same thing but with names:
fourthFunction(2, 4).quadrupled // = 16
// MARK: External parameter names
// Function parameters can be given names
func addNumbers(firstNumber num1 : Int, toSecondNumber num2: Int) -> Int {
return num1 + num2
}
addNumbers(firstNumber: 2, toSecondNumber: 3) // = 5
// You can shorthand this by adding a #
func multiplyNumbers(#firstNumber: Int, #multiplier: Int) -> Int {
return firstNumber * multiplier
}
multiplyNumbers(firstNumber: 2, multiplier: 3) // = 6
// MARK: Default values
// Function parameters can have default values, as long as they're at the end
func multiplyNumbers2 (firstNumber: Int, multiplier: Int = 2) -> Int {
return firstNumber * multiplier;
}
// Parameters with default values can be omitted
multiplyNumbers2(2) // = 4
// MARK: Variable parameters
// Functions can receive a variable number of parameters
func sumNumbers(numbers: Int...) -> Int {
// in this function, 'numbers' is an array of Ints
var total = 0
for number in numbers {
total += number
}
return total
}
sumNumbers(2,3,4,5) // = 14
// MARK: inout parameters
// Functions can change the value of variables that get passed to them using 'inout'
func swapValues(inout firstValue: Int, inout secondValue: Int) {
let tempValue = firstValue
firstValue = secondValue
secondValue = tempValue
}
var swap1 = 2
var swap2 = 3
swapValues(&swap1, &swap2)
swap1 // = 3
swap2 // = 2
// MARK: Closures and Function Types
// Functions can be stored in variables
var numbersFunc: (Int, Int) -> Int;
// numbersFunc can now store any function that takes two ints and returns an int
numbersFunc = addNumbers
numbersFunc(2, 3) // = 5
// MARK: Functions as parameters
// Functions can receive other functions as parameters
func timesThree(number: Int) -> Int {
return number * 3
}
func doSomethingToNumber(aNumber: Int, thingToDo: (Int)->Int) -> Int {
// call the function 'thingToDo' using 'aNumber', and return the result
return thingToDo(aNumber);
}
doSomethingToNumber(4, timesThree) // = 12
// MARK: Returning functions from functions
// Functions can return other functions
func createAdder(numberToAdd: Int) -> (Int) -> Int {
func adder(number: Int) -> Int {
return number + numberToAdd
}
return adder
}
var addTwo = createAdder(2)
addTwo(2) // = 4
// MARK: Capturing values in internal functions
// Functions can 'capture' values
func createIncrementor(incrementAmount: Int) -> () -> Int { // <1>
var amount = 0 // <2>
func incrementor() -> Int { // <3>
amount += incrementAmount // <4>
return amount
}
return incrementor // <5>
}
var incrementByTen = createIncrementor(10) // <6>
incrementByTen() // = 10 <7>
incrementByTen() // = 20
var incrementByFifteen = createIncrementor(15) // <8>
incrementByFifteen() // = 15 <9>
// MARK: Closures
// You can write short, anonymous functions called 'closures'
var numbers = [2,1,56,32,120,13]
var numbersSorted = sorted(numbers, { (n1: Int, n2: Int) -> Bool in
// Sort so that small numbers go before large numbers
return n2 > n1
}) // = [1, 2, 13, 32, 56, 120]
// The types of parameters and the return type can be inferred
var numbersSortedReverse = sorted(numbers, {n1, n2 in
return n1 > n2
}) // = [120, 56, 32, 13, 2, 1]
// If you don't care about the names of the parameters, use $0, $1, etc
// Also, if there's only a single line of code in the closure you can omit the 'return'
var numbersSortedAgain = sorted(numbers, {
$1 > $0
}) // = [1, 2, 13, 32, 56, 120]
// If the last parameter of a function is a closure, you can put the braces outside the parentheses
var numbersSortedReversedAgain = sorted(numbers) {
$0 > $1
} // = [120, 56, 32, 13, 2, 1]
// Closures can be stored in variables and used like functions
var comparator = {(a: Int, b:Int) in a < b}
comparator(1,2) // = true
var sortingInline = [2, 5, 98, 2, 13]
sort(&sortingInline)
sortingInline // = [2, 2, 5, 13, 98]
| mit | b76cc104593b6f72e3ba704a078cdc22 | 25.951351 | 99 | 0.686723 | 3.584472 | false | false | false | false |
5lucky2xiaobin0/PandaTV | PandaTV/PandaTV/Classes/Game/Controller/GameListVC.swift | 1 | 3104 | //
// GameCategoryVC.swift
// PandaTV
//
// Created by 钟斌 on 2017/4/2.
// Copyright © 2017年 xiaobin. All rights reserved.
//
import UIKit
import MJRefresh
private let itemSizeW = screenW / 4
private let itemSizeH = itemSizeW
class GameListVC: ShowBasicVC {
var gamelistvm : GameListVM = GameListVM()
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let layout = self.showCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsets.zero
}
}
extension GameListVC {
override func setUI(){
view.addSubview(showCollectionView)
}
}
// MARK: - 数据请求
extension GameListVC {
override func loadData() {
gamelistvm.requestListData {
self.showCollectionView.reloadData()
self.removeLoadImage()
}
}
}
extension GameListVC {
//控制组header的size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: screenW, height: HeaderFooterViewH)
}
//控制组footer的size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return CGSize.zero
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: itemSizeW, height: itemSizeH)
}
//返回组数
func numberOfSections(in collectionView: UICollectionView) -> Int {
return gamelistvm.listItems.count
}
//返回每组的行数
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let listItem = gamelistvm.listItems[section]
return listItem.thundImageItems.count
}
//设置头尾控件
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let item = gamelistvm.listItems[indexPath.section]
let cell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerCell, for: indexPath) as! HeaderCell
cell.gameName.text = item.cname
return cell
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let itemGroup = gamelistvm.listItems[indexPath.section]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: thundimageCell, for: indexPath) as! GameThumbImageCell
cell.item = itemGroup.thundImageItems[indexPath.item]
return cell
}
}
| mit | 738441d079f528d8485af7dbded9d524 | 30.010204 | 170 | 0.696611 | 5.312937 | false | false | false | false |
hooman/swift | libswift/Sources/SIL/Value.swift | 3 | 1648 | //===--- Value.swift - the Value protocol ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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
//
//===----------------------------------------------------------------------===//
import SILBridging
public protocol Value : AnyObject, CustomStringConvertible {
var uses: UseList { get }
var type: Type { get }
var definingInstruction: Instruction? { get }
}
extension Value {
public var description: String {
SILNode_debugDescription(bridgedNode).takeString()
}
public var uses: UseList {
return UseList(SILValue_firstUse(bridged))
}
public var type: Type {
return Type(bridged: SILValue_getType(bridged))
}
public var hashable: HashableValue { ObjectIdentifier(self) }
public var bridged: BridgedValue {
BridgedValue(obj: SwiftObject(self as AnyObject))
}
var bridgedNode: BridgedNode {
BridgedNode(obj: SwiftObject(self as AnyObject))
}
}
public typealias HashableValue = ObjectIdentifier
public func ==(_ lhs: Value, _ rhs: Value) -> Bool {
return lhs === rhs
}
extension BridgedValue {
func getAs<T: AnyObject>(_ valueType: T.Type) -> T { obj.getAs(T.self) }
}
final class Undef : Value {
public var definingInstruction: Instruction? { nil }
}
final class PlaceholderValue : Value {
public var definingInstruction: Instruction? { nil }
}
| apache-2.0 | 59102ccc71fcc872e44c089473eb74bb | 26.466667 | 80 | 0.665049 | 4.302872 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/DataExchange/DataExchange_Shapes.swift | 1 | 64219 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import Foundation
import SotoCore
extension DataExchange {
// MARK: Enums
public enum AssetType: String, CustomStringConvertible, Codable {
case s3Snapshot = "S3_SNAPSHOT"
public var description: String { return self.rawValue }
}
public enum Code: String, CustomStringConvertible, Codable {
case accessDeniedException = "ACCESS_DENIED_EXCEPTION"
case internalServerException = "INTERNAL_SERVER_EXCEPTION"
case malwareDetected = "MALWARE_DETECTED"
case malwareScanEncryptedFile = "MALWARE_SCAN_ENCRYPTED_FILE"
case resourceNotFoundException = "RESOURCE_NOT_FOUND_EXCEPTION"
case serviceQuotaExceededException = "SERVICE_QUOTA_EXCEEDED_EXCEPTION"
case validationException = "VALIDATION_EXCEPTION"
public var description: String { return self.rawValue }
}
public enum JobErrorLimitName: String, CustomStringConvertible, Codable {
case assetSizeInGb = "Asset size in GB"
case assetsPerRevision = "Assets per revision"
public var description: String { return self.rawValue }
}
public enum JobErrorResourceTypes: String, CustomStringConvertible, Codable {
case asset = "ASSET"
case revision = "REVISION"
public var description: String { return self.rawValue }
}
public enum Origin: String, CustomStringConvertible, Codable {
case entitled = "ENTITLED"
case owned = "OWNED"
public var description: String { return self.rawValue }
}
public enum ServerSideEncryptionTypes: String, CustomStringConvertible, Codable {
case aes256 = "AES256"
case awsKms = "aws:kms"
public var description: String { return self.rawValue }
}
public enum State: String, CustomStringConvertible, Codable {
case cancelled = "CANCELLED"
case completed = "COMPLETED"
case error = "ERROR"
case inProgress = "IN_PROGRESS"
case timedOut = "TIMED_OUT"
case waiting = "WAITING"
public var description: String { return self.rawValue }
}
public enum `Type`: String, CustomStringConvertible, Codable {
case exportAssetToSignedUrl = "EXPORT_ASSET_TO_SIGNED_URL"
case exportAssetsToS3 = "EXPORT_ASSETS_TO_S3"
case importAssetFromSignedUrl = "IMPORT_ASSET_FROM_SIGNED_URL"
case importAssetsFromS3 = "IMPORT_ASSETS_FROM_S3"
public var description: String { return self.rawValue }
}
// MARK: Shapes
public struct AssetDestinationEntry: AWSEncodableShape & AWSDecodableShape {
/// The unique identifier for the asset.
public let assetId: String
/// The S3 bucket that is the destination for the asset.
public let bucket: String
/// The name of the object in Amazon S3 for the asset.
public let key: String?
public init(assetId: String, bucket: String, key: String? = nil) {
self.assetId = assetId
self.bucket = bucket
self.key = key
}
private enum CodingKeys: String, CodingKey {
case assetId = "AssetId"
case bucket = "Bucket"
case key = "Key"
}
}
public struct AssetDetails: AWSDecodableShape {
public let s3SnapshotAsset: S3SnapshotAsset?
public init(s3SnapshotAsset: S3SnapshotAsset? = nil) {
self.s3SnapshotAsset = s3SnapshotAsset
}
private enum CodingKeys: String, CodingKey {
case s3SnapshotAsset = "S3SnapshotAsset"
}
}
public struct AssetEntry: AWSDecodableShape {
/// The ARN for the asset.
public let arn: String
/// Information about the asset, including its size.
public let assetDetails: AssetDetails
/// The type of file your data is stored in. Currently, the supported asset type is S3_SNAPSHOT.
public let assetType: AssetType
/// The date and time that the asset was created, in ISO 8601 format.
@CustomCoding<ISO8601DateCoder>
public var createdAt: Date
/// The unique identifier for the data set associated with this asset.
public let dataSetId: String
/// The unique identifier for the asset.
public let id: String
/// The name of the asset. When importing from Amazon S3, the S3 object key is used as the asset name. When exporting to Amazon S3, the asset name is used as default target S3 object key.
public let name: String
/// The unique identifier for the revision associated with this asset.
public let revisionId: String
/// The asset ID of the owned asset corresponding to the entitled asset being viewed. This parameter is returned when an asset owner is viewing the entitled copy of its owned asset.
public let sourceId: String?
/// The date and time that the asset was last updated, in ISO 8601 format.
@CustomCoding<ISO8601DateCoder>
public var updatedAt: Date
public init(arn: String, assetDetails: AssetDetails, assetType: AssetType, createdAt: Date, dataSetId: String, id: String, name: String, revisionId: String, sourceId: String? = nil, updatedAt: Date) {
self.arn = arn
self.assetDetails = assetDetails
self.assetType = assetType
self.createdAt = createdAt
self.dataSetId = dataSetId
self.id = id
self.name = name
self.revisionId = revisionId
self.sourceId = sourceId
self.updatedAt = updatedAt
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case assetDetails = "AssetDetails"
case assetType = "AssetType"
case createdAt = "CreatedAt"
case dataSetId = "DataSetId"
case id = "Id"
case name = "Name"
case revisionId = "RevisionId"
case sourceId = "SourceId"
case updatedAt = "UpdatedAt"
}
}
public struct AssetSourceEntry: AWSEncodableShape & AWSDecodableShape {
/// The S3 bucket that's part of the source of the asset.
public let bucket: String
/// The name of the object in Amazon S3 for the asset.
public let key: String
public init(bucket: String, key: String) {
self.bucket = bucket
self.key = key
}
private enum CodingKeys: String, CodingKey {
case bucket = "Bucket"
case key = "Key"
}
}
public struct CancelJobRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "jobId", location: .uri(locationName: "JobId"))
]
public let jobId: String
public init(jobId: String) {
self.jobId = jobId
}
private enum CodingKeys: CodingKey {}
}
public struct CreateDataSetRequest: AWSEncodableShape {
/// The type of file your data is stored in. Currently, the supported asset type is S3_SNAPSHOT.
public let assetType: AssetType
/// A description for the data set. This value can be up to 16,348 characters long.
public let description: String
/// The name of the data set.
public let name: String
/// A data set tag is an optional label that you can assign to a data set when you create it. Each tag consists of a key and an optional value, both of which you define. When you use tagging, you can also use tag-based access control in IAM policies to control access to these data sets and revisions.
public let tags: [String: String]?
public init(assetType: AssetType, description: String, name: String, tags: [String: String]? = nil) {
self.assetType = assetType
self.description = description
self.name = name
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case assetType = "AssetType"
case description = "Description"
case name = "Name"
case tags = "Tags"
}
}
public struct CreateDataSetResponse: AWSDecodableShape {
public let arn: String?
public let assetType: AssetType?
@OptionalCustomCoding<ISO8601DateCoder>
public var createdAt: Date?
public let description: String?
public let id: String?
public let name: String?
public let origin: Origin?
public let originDetails: OriginDetails?
public let sourceId: String?
public let tags: [String: String]?
@OptionalCustomCoding<ISO8601DateCoder>
public var updatedAt: Date?
public init(arn: String? = nil, assetType: AssetType? = nil, createdAt: Date? = nil, description: String? = nil, id: String? = nil, name: String? = nil, origin: Origin? = nil, originDetails: OriginDetails? = nil, sourceId: String? = nil, tags: [String: String]? = nil, updatedAt: Date? = nil) {
self.arn = arn
self.assetType = assetType
self.createdAt = createdAt
self.description = description
self.id = id
self.name = name
self.origin = origin
self.originDetails = originDetails
self.sourceId = sourceId
self.tags = tags
self.updatedAt = updatedAt
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case assetType = "AssetType"
case createdAt = "CreatedAt"
case description = "Description"
case id = "Id"
case name = "Name"
case origin = "Origin"
case originDetails = "OriginDetails"
case sourceId = "SourceId"
case tags = "Tags"
case updatedAt = "UpdatedAt"
}
}
public struct CreateJobRequest: AWSEncodableShape {
/// The details for the CreateJob request.
public let details: RequestDetails
/// The type of job to be created.
public let type: `Type`
public init(details: RequestDetails, type: `Type`) {
self.details = details
self.type = type
}
public func validate(name: String) throws {
try self.details.validate(name: "\(name).details")
}
private enum CodingKeys: String, CodingKey {
case details = "Details"
case type = "Type"
}
}
public struct CreateJobResponse: AWSDecodableShape {
public let arn: String?
@OptionalCustomCoding<ISO8601DateCoder>
public var createdAt: Date?
public let details: ResponseDetails?
public let errors: [JobError]?
public let id: String?
public let state: State?
public let type: `Type`?
@OptionalCustomCoding<ISO8601DateCoder>
public var updatedAt: Date?
public init(arn: String? = nil, createdAt: Date? = nil, details: ResponseDetails? = nil, errors: [JobError]? = nil, id: String? = nil, state: State? = nil, type: `Type`? = nil, updatedAt: Date? = nil) {
self.arn = arn
self.createdAt = createdAt
self.details = details
self.errors = errors
self.id = id
self.state = state
self.type = type
self.updatedAt = updatedAt
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case createdAt = "CreatedAt"
case details = "Details"
case errors = "Errors"
case id = "Id"
case state = "State"
case type = "Type"
case updatedAt = "UpdatedAt"
}
}
public struct CreateRevisionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "dataSetId", location: .uri(locationName: "DataSetId"))
]
/// An optional comment about the revision.
public let comment: String?
public let dataSetId: String
/// A revision tag is an optional label that you can assign to a revision when you create it. Each tag consists of a key and an optional value, both of which you define. When you use tagging, you can also use tag-based access control in IAM policies to control access to these data sets and revisions.
public let tags: [String: String]?
public init(comment: String? = nil, dataSetId: String, tags: [String: String]? = nil) {
self.comment = comment
self.dataSetId = dataSetId
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.comment, name: "comment", parent: name, max: 16384)
try self.validate(self.comment, name: "comment", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case comment = "Comment"
case tags = "Tags"
}
}
public struct CreateRevisionResponse: AWSDecodableShape {
public let arn: String?
public let comment: String?
@OptionalCustomCoding<ISO8601DateCoder>
public var createdAt: Date?
public let dataSetId: String?
public let finalized: Bool?
public let id: String?
public let sourceId: String?
public let tags: [String: String]?
@OptionalCustomCoding<ISO8601DateCoder>
public var updatedAt: Date?
public init(arn: String? = nil, comment: String? = nil, createdAt: Date? = nil, dataSetId: String? = nil, finalized: Bool? = nil, id: String? = nil, sourceId: String? = nil, tags: [String: String]? = nil, updatedAt: Date? = nil) {
self.arn = arn
self.comment = comment
self.createdAt = createdAt
self.dataSetId = dataSetId
self.finalized = finalized
self.id = id
self.sourceId = sourceId
self.tags = tags
self.updatedAt = updatedAt
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case comment = "Comment"
case createdAt = "CreatedAt"
case dataSetId = "DataSetId"
case finalized = "Finalized"
case id = "Id"
case sourceId = "SourceId"
case tags = "Tags"
case updatedAt = "UpdatedAt"
}
}
public struct DataSetEntry: AWSDecodableShape {
/// The ARN for the data set.
public let arn: String
/// The type of file your data is stored in. Currently, the supported asset type is S3_SNAPSHOT.
public let assetType: AssetType
/// The date and time that the data set was created, in ISO 8601 format.
@CustomCoding<ISO8601DateCoder>
public var createdAt: Date
/// The description for the data set.
public let description: String
/// The unique identifier for the data set.
public let id: String
/// The name of the data set.
public let name: String
/// A property that defines the data set as OWNED by the account (for providers) or ENTITLED to the account (for subscribers).
public let origin: Origin
/// If the origin of this data set is ENTITLED, includes the details for the product on AWS Marketplace.
public let originDetails: OriginDetails?
/// The data set ID of the owned data set corresponding to the entitled data set being viewed. This parameter is returned when a data set owner is viewing the entitled copy of its owned data set.
public let sourceId: String?
/// The date and time that the data set was last updated, in ISO 8601 format.
@CustomCoding<ISO8601DateCoder>
public var updatedAt: Date
public init(arn: String, assetType: AssetType, createdAt: Date, description: String, id: String, name: String, origin: Origin, originDetails: OriginDetails? = nil, sourceId: String? = nil, updatedAt: Date) {
self.arn = arn
self.assetType = assetType
self.createdAt = createdAt
self.description = description
self.id = id
self.name = name
self.origin = origin
self.originDetails = originDetails
self.sourceId = sourceId
self.updatedAt = updatedAt
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case assetType = "AssetType"
case createdAt = "CreatedAt"
case description = "Description"
case id = "Id"
case name = "Name"
case origin = "Origin"
case originDetails = "OriginDetails"
case sourceId = "SourceId"
case updatedAt = "UpdatedAt"
}
}
public struct DeleteAssetRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "assetId", location: .uri(locationName: "AssetId")),
AWSMemberEncoding(label: "dataSetId", location: .uri(locationName: "DataSetId")),
AWSMemberEncoding(label: "revisionId", location: .uri(locationName: "RevisionId"))
]
public let assetId: String
public let dataSetId: String
public let revisionId: String
public init(assetId: String, dataSetId: String, revisionId: String) {
self.assetId = assetId
self.dataSetId = dataSetId
self.revisionId = revisionId
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteDataSetRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "dataSetId", location: .uri(locationName: "DataSetId"))
]
public let dataSetId: String
public init(dataSetId: String) {
self.dataSetId = dataSetId
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteRevisionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "dataSetId", location: .uri(locationName: "DataSetId")),
AWSMemberEncoding(label: "revisionId", location: .uri(locationName: "RevisionId"))
]
public let dataSetId: String
public let revisionId: String
public init(dataSetId: String, revisionId: String) {
self.dataSetId = dataSetId
self.revisionId = revisionId
}
private enum CodingKeys: CodingKey {}
}
public struct Details: AWSDecodableShape {
public let importAssetFromSignedUrlJobErrorDetails: ImportAssetFromSignedUrlJobErrorDetails?
public let importAssetsFromS3JobErrorDetails: [AssetSourceEntry]?
public init(importAssetFromSignedUrlJobErrorDetails: ImportAssetFromSignedUrlJobErrorDetails? = nil, importAssetsFromS3JobErrorDetails: [AssetSourceEntry]? = nil) {
self.importAssetFromSignedUrlJobErrorDetails = importAssetFromSignedUrlJobErrorDetails
self.importAssetsFromS3JobErrorDetails = importAssetsFromS3JobErrorDetails
}
private enum CodingKeys: String, CodingKey {
case importAssetFromSignedUrlJobErrorDetails = "ImportAssetFromSignedUrlJobErrorDetails"
case importAssetsFromS3JobErrorDetails = "ImportAssetsFromS3JobErrorDetails"
}
}
public struct ExportAssetToSignedUrlRequestDetails: AWSEncodableShape {
/// The unique identifier for the asset that is exported to a signed URL.
public let assetId: String
/// The unique identifier for the data set associated with this export job.
public let dataSetId: String
/// The unique identifier for the revision associated with this export request.
public let revisionId: String
public init(assetId: String, dataSetId: String, revisionId: String) {
self.assetId = assetId
self.dataSetId = dataSetId
self.revisionId = revisionId
}
private enum CodingKeys: String, CodingKey {
case assetId = "AssetId"
case dataSetId = "DataSetId"
case revisionId = "RevisionId"
}
}
public struct ExportAssetToSignedUrlResponseDetails: AWSDecodableShape {
/// The unique identifier for the asset associated with this export job.
public let assetId: String
/// The unique identifier for the data set associated with this export job.
public let dataSetId: String
/// The unique identifier for the revision associated with this export response.
public let revisionId: String
/// The signed URL for the export request.
public let signedUrl: String?
/// The date and time that the signed URL expires, in ISO 8601 format.
@OptionalCustomCoding<ISO8601DateCoder>
public var signedUrlExpiresAt: Date?
public init(assetId: String, dataSetId: String, revisionId: String, signedUrl: String? = nil, signedUrlExpiresAt: Date? = nil) {
self.assetId = assetId
self.dataSetId = dataSetId
self.revisionId = revisionId
self.signedUrl = signedUrl
self.signedUrlExpiresAt = signedUrlExpiresAt
}
private enum CodingKeys: String, CodingKey {
case assetId = "AssetId"
case dataSetId = "DataSetId"
case revisionId = "RevisionId"
case signedUrl = "SignedUrl"
case signedUrlExpiresAt = "SignedUrlExpiresAt"
}
}
public struct ExportAssetsToS3RequestDetails: AWSEncodableShape {
/// The destination for the asset.
public let assetDestinations: [AssetDestinationEntry]
/// The unique identifier for the data set associated with this export job.
public let dataSetId: String
/// Encryption configuration for the export job.
public let encryption: ExportServerSideEncryption?
/// The unique identifier for the revision associated with this export request.
public let revisionId: String
public init(assetDestinations: [AssetDestinationEntry], dataSetId: String, encryption: ExportServerSideEncryption? = nil, revisionId: String) {
self.assetDestinations = assetDestinations
self.dataSetId = dataSetId
self.encryption = encryption
self.revisionId = revisionId
}
private enum CodingKeys: String, CodingKey {
case assetDestinations = "AssetDestinations"
case dataSetId = "DataSetId"
case encryption = "Encryption"
case revisionId = "RevisionId"
}
}
public struct ExportAssetsToS3ResponseDetails: AWSDecodableShape {
/// The destination in Amazon S3 where the asset is exported.
public let assetDestinations: [AssetDestinationEntry]
/// The unique identifier for the data set associated with this export job.
public let dataSetId: String
/// Encryption configuration of the export job.
public let encryption: ExportServerSideEncryption?
/// The unique identifier for the revision associated with this export response.
public let revisionId: String
public init(assetDestinations: [AssetDestinationEntry], dataSetId: String, encryption: ExportServerSideEncryption? = nil, revisionId: String) {
self.assetDestinations = assetDestinations
self.dataSetId = dataSetId
self.encryption = encryption
self.revisionId = revisionId
}
private enum CodingKeys: String, CodingKey {
case assetDestinations = "AssetDestinations"
case dataSetId = "DataSetId"
case encryption = "Encryption"
case revisionId = "RevisionId"
}
}
public struct ExportServerSideEncryption: AWSEncodableShape & AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the the AWS KMS key you want to use to encrypt the Amazon S3 objects. This parameter is required if you choose aws:kms as an encryption type.
public let kmsKeyArn: String?
/// The type of server side encryption used for encrypting the objects in Amazon S3.
public let type: ServerSideEncryptionTypes
public init(kmsKeyArn: String? = nil, type: ServerSideEncryptionTypes) {
self.kmsKeyArn = kmsKeyArn
self.type = type
}
private enum CodingKeys: String, CodingKey {
case kmsKeyArn = "KmsKeyArn"
case type = "Type"
}
}
public struct GetAssetRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "assetId", location: .uri(locationName: "AssetId")),
AWSMemberEncoding(label: "dataSetId", location: .uri(locationName: "DataSetId")),
AWSMemberEncoding(label: "revisionId", location: .uri(locationName: "RevisionId"))
]
public let assetId: String
public let dataSetId: String
public let revisionId: String
public init(assetId: String, dataSetId: String, revisionId: String) {
self.assetId = assetId
self.dataSetId = dataSetId
self.revisionId = revisionId
}
private enum CodingKeys: CodingKey {}
}
public struct GetAssetResponse: AWSDecodableShape {
public let arn: String?
public let assetDetails: AssetDetails?
public let assetType: AssetType?
@OptionalCustomCoding<ISO8601DateCoder>
public var createdAt: Date?
public let dataSetId: String?
public let id: String?
public let name: String?
public let revisionId: String?
public let sourceId: String?
@OptionalCustomCoding<ISO8601DateCoder>
public var updatedAt: Date?
public init(arn: String? = nil, assetDetails: AssetDetails? = nil, assetType: AssetType? = nil, createdAt: Date? = nil, dataSetId: String? = nil, id: String? = nil, name: String? = nil, revisionId: String? = nil, sourceId: String? = nil, updatedAt: Date? = nil) {
self.arn = arn
self.assetDetails = assetDetails
self.assetType = assetType
self.createdAt = createdAt
self.dataSetId = dataSetId
self.id = id
self.name = name
self.revisionId = revisionId
self.sourceId = sourceId
self.updatedAt = updatedAt
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case assetDetails = "AssetDetails"
case assetType = "AssetType"
case createdAt = "CreatedAt"
case dataSetId = "DataSetId"
case id = "Id"
case name = "Name"
case revisionId = "RevisionId"
case sourceId = "SourceId"
case updatedAt = "UpdatedAt"
}
}
public struct GetDataSetRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "dataSetId", location: .uri(locationName: "DataSetId"))
]
public let dataSetId: String
public init(dataSetId: String) {
self.dataSetId = dataSetId
}
private enum CodingKeys: CodingKey {}
}
public struct GetDataSetResponse: AWSDecodableShape {
public let arn: String?
public let assetType: AssetType?
@OptionalCustomCoding<ISO8601DateCoder>
public var createdAt: Date?
public let description: String?
public let id: String?
public let name: String?
public let origin: Origin?
public let originDetails: OriginDetails?
public let sourceId: String?
public let tags: [String: String]?
@OptionalCustomCoding<ISO8601DateCoder>
public var updatedAt: Date?
public init(arn: String? = nil, assetType: AssetType? = nil, createdAt: Date? = nil, description: String? = nil, id: String? = nil, name: String? = nil, origin: Origin? = nil, originDetails: OriginDetails? = nil, sourceId: String? = nil, tags: [String: String]? = nil, updatedAt: Date? = nil) {
self.arn = arn
self.assetType = assetType
self.createdAt = createdAt
self.description = description
self.id = id
self.name = name
self.origin = origin
self.originDetails = originDetails
self.sourceId = sourceId
self.tags = tags
self.updatedAt = updatedAt
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case assetType = "AssetType"
case createdAt = "CreatedAt"
case description = "Description"
case id = "Id"
case name = "Name"
case origin = "Origin"
case originDetails = "OriginDetails"
case sourceId = "SourceId"
case tags = "Tags"
case updatedAt = "UpdatedAt"
}
}
public struct GetJobRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "jobId", location: .uri(locationName: "JobId"))
]
public let jobId: String
public init(jobId: String) {
self.jobId = jobId
}
private enum CodingKeys: CodingKey {}
}
public struct GetJobResponse: AWSDecodableShape {
public let arn: String?
@OptionalCustomCoding<ISO8601DateCoder>
public var createdAt: Date?
public let details: ResponseDetails?
public let errors: [JobError]?
public let id: String?
public let state: State?
public let type: `Type`?
@OptionalCustomCoding<ISO8601DateCoder>
public var updatedAt: Date?
public init(arn: String? = nil, createdAt: Date? = nil, details: ResponseDetails? = nil, errors: [JobError]? = nil, id: String? = nil, state: State? = nil, type: `Type`? = nil, updatedAt: Date? = nil) {
self.arn = arn
self.createdAt = createdAt
self.details = details
self.errors = errors
self.id = id
self.state = state
self.type = type
self.updatedAt = updatedAt
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case createdAt = "CreatedAt"
case details = "Details"
case errors = "Errors"
case id = "Id"
case state = "State"
case type = "Type"
case updatedAt = "UpdatedAt"
}
}
public struct GetRevisionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "dataSetId", location: .uri(locationName: "DataSetId")),
AWSMemberEncoding(label: "revisionId", location: .uri(locationName: "RevisionId"))
]
public let dataSetId: String
public let revisionId: String
public init(dataSetId: String, revisionId: String) {
self.dataSetId = dataSetId
self.revisionId = revisionId
}
private enum CodingKeys: CodingKey {}
}
public struct GetRevisionResponse: AWSDecodableShape {
public let arn: String?
public let comment: String?
@OptionalCustomCoding<ISO8601DateCoder>
public var createdAt: Date?
public let dataSetId: String?
public let finalized: Bool?
public let id: String?
public let sourceId: String?
public let tags: [String: String]?
@OptionalCustomCoding<ISO8601DateCoder>
public var updatedAt: Date?
public init(arn: String? = nil, comment: String? = nil, createdAt: Date? = nil, dataSetId: String? = nil, finalized: Bool? = nil, id: String? = nil, sourceId: String? = nil, tags: [String: String]? = nil, updatedAt: Date? = nil) {
self.arn = arn
self.comment = comment
self.createdAt = createdAt
self.dataSetId = dataSetId
self.finalized = finalized
self.id = id
self.sourceId = sourceId
self.tags = tags
self.updatedAt = updatedAt
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case comment = "Comment"
case createdAt = "CreatedAt"
case dataSetId = "DataSetId"
case finalized = "Finalized"
case id = "Id"
case sourceId = "SourceId"
case tags = "Tags"
case updatedAt = "UpdatedAt"
}
}
public struct ImportAssetFromSignedUrlJobErrorDetails: AWSDecodableShape {
public let assetName: String
public init(assetName: String) {
self.assetName = assetName
}
private enum CodingKeys: String, CodingKey {
case assetName = "AssetName"
}
}
public struct ImportAssetFromSignedUrlRequestDetails: AWSEncodableShape {
/// The name of the asset. When importing from Amazon S3, the S3 object key is used as the asset name.
public let assetName: String
/// The unique identifier for the data set associated with this import job.
public let dataSetId: String
/// The Base64-encoded Md5 hash for the asset, used to ensure the integrity of the file at that location.
public let md5Hash: String
/// The unique identifier for the revision associated with this import request.
public let revisionId: String
public init(assetName: String, dataSetId: String, md5Hash: String, revisionId: String) {
self.assetName = assetName
self.dataSetId = dataSetId
self.md5Hash = md5Hash
self.revisionId = revisionId
}
public func validate(name: String) throws {
try self.validate(self.md5Hash, name: "md5Hash", parent: name, max: 24)
try self.validate(self.md5Hash, name: "md5Hash", parent: name, min: 24)
try self.validate(self.md5Hash, name: "md5Hash", parent: name, pattern: "/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/")
}
private enum CodingKeys: String, CodingKey {
case assetName = "AssetName"
case dataSetId = "DataSetId"
case md5Hash = "Md5Hash"
case revisionId = "RevisionId"
}
}
public struct ImportAssetFromSignedUrlResponseDetails: AWSDecodableShape {
/// The name for the asset associated with this import response.
public let assetName: String
/// The unique identifier for the data set associated with this import job.
public let dataSetId: String
/// The Base64-encoded Md5 hash for the asset, used to ensure the integrity of the file at that location.
public let md5Hash: String?
/// The unique identifier for the revision associated with this import response.
public let revisionId: String
/// The signed URL.
public let signedUrl: String?
/// The time and date at which the signed URL expires, in ISO 8601 format.
@OptionalCustomCoding<ISO8601DateCoder>
public var signedUrlExpiresAt: Date?
public init(assetName: String, dataSetId: String, md5Hash: String? = nil, revisionId: String, signedUrl: String? = nil, signedUrlExpiresAt: Date? = nil) {
self.assetName = assetName
self.dataSetId = dataSetId
self.md5Hash = md5Hash
self.revisionId = revisionId
self.signedUrl = signedUrl
self.signedUrlExpiresAt = signedUrlExpiresAt
}
private enum CodingKeys: String, CodingKey {
case assetName = "AssetName"
case dataSetId = "DataSetId"
case md5Hash = "Md5Hash"
case revisionId = "RevisionId"
case signedUrl = "SignedUrl"
case signedUrlExpiresAt = "SignedUrlExpiresAt"
}
}
public struct ImportAssetsFromS3RequestDetails: AWSEncodableShape {
/// Is a list of S3 bucket and object key pairs.
public let assetSources: [AssetSourceEntry]
/// The unique identifier for the data set associated with this import job.
public let dataSetId: String
/// The unique identifier for the revision associated with this import request.
public let revisionId: String
public init(assetSources: [AssetSourceEntry], dataSetId: String, revisionId: String) {
self.assetSources = assetSources
self.dataSetId = dataSetId
self.revisionId = revisionId
}
private enum CodingKeys: String, CodingKey {
case assetSources = "AssetSources"
case dataSetId = "DataSetId"
case revisionId = "RevisionId"
}
}
public struct ImportAssetsFromS3ResponseDetails: AWSDecodableShape {
/// Is a list of Amazon S3 bucket and object key pairs.
public let assetSources: [AssetSourceEntry]
/// The unique identifier for the data set associated with this import job.
public let dataSetId: String
/// The unique identifier for the revision associated with this import response.
public let revisionId: String
public init(assetSources: [AssetSourceEntry], dataSetId: String, revisionId: String) {
self.assetSources = assetSources
self.dataSetId = dataSetId
self.revisionId = revisionId
}
private enum CodingKeys: String, CodingKey {
case assetSources = "AssetSources"
case dataSetId = "DataSetId"
case revisionId = "RevisionId"
}
}
public struct JobEntry: AWSDecodableShape {
/// The ARN for the job.
public let arn: String
/// The date and time that the job was created, in ISO 8601 format.
@CustomCoding<ISO8601DateCoder>
public var createdAt: Date
/// Details of the operation to be performed by the job, such as export destination details or import source details.
public let details: ResponseDetails
/// Errors for jobs.
public let errors: [JobError]?
/// The unique identifier for the job.
public let id: String
/// The state of the job.
public let state: State
/// The job type.
public let type: `Type`
/// The date and time that the job was last updated, in ISO 8601 format.
@CustomCoding<ISO8601DateCoder>
public var updatedAt: Date
public init(arn: String, createdAt: Date, details: ResponseDetails, errors: [JobError]? = nil, id: String, state: State, type: `Type`, updatedAt: Date) {
self.arn = arn
self.createdAt = createdAt
self.details = details
self.errors = errors
self.id = id
self.state = state
self.type = type
self.updatedAt = updatedAt
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case createdAt = "CreatedAt"
case details = "Details"
case errors = "Errors"
case id = "Id"
case state = "State"
case type = "Type"
case updatedAt = "UpdatedAt"
}
}
public struct JobError: AWSDecodableShape {
/// The code for the job error.
public let code: Code
public let details: Details?
/// The name of the limit that was reached.
public let limitName: JobErrorLimitName?
/// The value of the exceeded limit.
public let limitValue: Double?
/// The message related to the job error.
public let message: String
/// The unique identifier for the resource related to the error.
public let resourceId: String?
/// The type of resource related to the error.
public let resourceType: JobErrorResourceTypes?
public init(code: Code, details: Details? = nil, limitName: JobErrorLimitName? = nil, limitValue: Double? = nil, message: String, resourceId: String? = nil, resourceType: JobErrorResourceTypes? = nil) {
self.code = code
self.details = details
self.limitName = limitName
self.limitValue = limitValue
self.message = message
self.resourceId = resourceId
self.resourceType = resourceType
}
private enum CodingKeys: String, CodingKey {
case code = "Code"
case details = "Details"
case limitName = "LimitName"
case limitValue = "LimitValue"
case message = "Message"
case resourceId = "ResourceId"
case resourceType = "ResourceType"
}
}
public struct ListDataSetRevisionsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "dataSetId", location: .uri(locationName: "DataSetId")),
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken"))
]
public let dataSetId: String
public let maxResults: Int?
public let nextToken: String?
public init(dataSetId: String, maxResults: Int? = nil, nextToken: String? = nil) {
self.dataSetId = dataSetId
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 25)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListDataSetRevisionsResponse: AWSDecodableShape {
public let nextToken: String?
public let revisions: [RevisionEntry]?
public init(nextToken: String? = nil, revisions: [RevisionEntry]? = nil) {
self.nextToken = nextToken
self.revisions = revisions
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case revisions = "Revisions"
}
}
public struct ListDataSetsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")),
AWSMemberEncoding(label: "origin", location: .querystring(locationName: "origin"))
]
public let maxResults: Int?
public let nextToken: String?
public let origin: String?
public init(maxResults: Int? = nil, nextToken: String? = nil, origin: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
self.origin = origin
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 25)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListDataSetsResponse: AWSDecodableShape {
public let dataSets: [DataSetEntry]?
public let nextToken: String?
public init(dataSets: [DataSetEntry]? = nil, nextToken: String? = nil) {
self.dataSets = dataSets
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case dataSets = "DataSets"
case nextToken = "NextToken"
}
}
public struct ListJobsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "dataSetId", location: .querystring(locationName: "dataSetId")),
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")),
AWSMemberEncoding(label: "revisionId", location: .querystring(locationName: "revisionId"))
]
public let dataSetId: String?
public let maxResults: Int?
public let nextToken: String?
public let revisionId: String?
public init(dataSetId: String? = nil, maxResults: Int? = nil, nextToken: String? = nil, revisionId: String? = nil) {
self.dataSetId = dataSetId
self.maxResults = maxResults
self.nextToken = nextToken
self.revisionId = revisionId
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 25)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListJobsResponse: AWSDecodableShape {
public let jobs: [JobEntry]?
public let nextToken: String?
public init(jobs: [JobEntry]? = nil, nextToken: String? = nil) {
self.jobs = jobs
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case jobs = "Jobs"
case nextToken = "NextToken"
}
}
public struct ListRevisionAssetsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "dataSetId", location: .uri(locationName: "DataSetId")),
AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")),
AWSMemberEncoding(label: "revisionId", location: .uri(locationName: "RevisionId"))
]
public let dataSetId: String
public let maxResults: Int?
public let nextToken: String?
public let revisionId: String
public init(dataSetId: String, maxResults: Int? = nil, nextToken: String? = nil, revisionId: String) {
self.dataSetId = dataSetId
self.maxResults = maxResults
self.nextToken = nextToken
self.revisionId = revisionId
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 25)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListRevisionAssetsResponse: AWSDecodableShape {
public let assets: [AssetEntry]?
public let nextToken: String?
public init(assets: [AssetEntry]? = nil, nextToken: String? = nil) {
self.assets = assets
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case assets = "Assets"
case nextToken = "NextToken"
}
}
public struct ListTagsForResourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resource-arn"))
]
public let resourceArn: String
public init(resourceArn: String) {
self.resourceArn = resourceArn
}
private enum CodingKeys: CodingKey {}
}
public struct ListTagsForResourceResponse: AWSDecodableShape {
public let tags: [String: String]?
public init(tags: [String: String]? = nil) {
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case tags
}
}
public struct OriginDetails: AWSDecodableShape {
public let productId: String
public init(productId: String) {
self.productId = productId
}
private enum CodingKeys: String, CodingKey {
case productId = "ProductId"
}
}
public struct RequestDetails: AWSEncodableShape {
/// Details about the export to Amazon S3 request.
public let exportAssetsToS3: ExportAssetsToS3RequestDetails?
/// Details about the export to signed URL request.
public let exportAssetToSignedUrl: ExportAssetToSignedUrlRequestDetails?
/// Details about the import from signed URL request.
public let importAssetFromSignedUrl: ImportAssetFromSignedUrlRequestDetails?
/// Details about the import from Amazon S3 request.
public let importAssetsFromS3: ImportAssetsFromS3RequestDetails?
public init(exportAssetsToS3: ExportAssetsToS3RequestDetails? = nil, exportAssetToSignedUrl: ExportAssetToSignedUrlRequestDetails? = nil, importAssetFromSignedUrl: ImportAssetFromSignedUrlRequestDetails? = nil, importAssetsFromS3: ImportAssetsFromS3RequestDetails? = nil) {
self.exportAssetsToS3 = exportAssetsToS3
self.exportAssetToSignedUrl = exportAssetToSignedUrl
self.importAssetFromSignedUrl = importAssetFromSignedUrl
self.importAssetsFromS3 = importAssetsFromS3
}
public func validate(name: String) throws {
try self.importAssetFromSignedUrl?.validate(name: "\(name).importAssetFromSignedUrl")
}
private enum CodingKeys: String, CodingKey {
case exportAssetsToS3 = "ExportAssetsToS3"
case exportAssetToSignedUrl = "ExportAssetToSignedUrl"
case importAssetFromSignedUrl = "ImportAssetFromSignedUrl"
case importAssetsFromS3 = "ImportAssetsFromS3"
}
}
public struct ResponseDetails: AWSDecodableShape {
/// Details for the export to Amazon S3 response.
public let exportAssetsToS3: ExportAssetsToS3ResponseDetails?
/// Details for the export to signed URL response.
public let exportAssetToSignedUrl: ExportAssetToSignedUrlResponseDetails?
/// Details for the import from signed URL response.
public let importAssetFromSignedUrl: ImportAssetFromSignedUrlResponseDetails?
/// Details for the import from Amazon S3 response.
public let importAssetsFromS3: ImportAssetsFromS3ResponseDetails?
public init(exportAssetsToS3: ExportAssetsToS3ResponseDetails? = nil, exportAssetToSignedUrl: ExportAssetToSignedUrlResponseDetails? = nil, importAssetFromSignedUrl: ImportAssetFromSignedUrlResponseDetails? = nil, importAssetsFromS3: ImportAssetsFromS3ResponseDetails? = nil) {
self.exportAssetsToS3 = exportAssetsToS3
self.exportAssetToSignedUrl = exportAssetToSignedUrl
self.importAssetFromSignedUrl = importAssetFromSignedUrl
self.importAssetsFromS3 = importAssetsFromS3
}
private enum CodingKeys: String, CodingKey {
case exportAssetsToS3 = "ExportAssetsToS3"
case exportAssetToSignedUrl = "ExportAssetToSignedUrl"
case importAssetFromSignedUrl = "ImportAssetFromSignedUrl"
case importAssetsFromS3 = "ImportAssetsFromS3"
}
}
public struct RevisionEntry: AWSDecodableShape {
/// The ARN for the revision.
public let arn: String
/// An optional comment about the revision.
public let comment: String?
/// The date and time that the revision was created, in ISO 8601 format.
@CustomCoding<ISO8601DateCoder>
public var createdAt: Date
/// The unique identifier for the data set associated with this revision.
public let dataSetId: String
/// To publish a revision to a data set in a product, the revision must first be finalized. Finalizing a revision tells AWS Data Exchange that your changes to the assets in the revision are complete. After it's in this read-only state, you can publish the revision to your products. Finalized revisions can be published through the AWS Data Exchange console or the AWS Marketplace Catalog API, using the StartChangeSet AWS Marketplace Catalog API action. When using the API, revisions are uniquely identified by their ARN.
public let finalized: Bool?
/// The unique identifier for the revision.
public let id: String
/// The revision ID of the owned revision corresponding to the entitled revision being viewed. This parameter is returned when a revision owner is viewing the entitled copy of its owned revision.
public let sourceId: String?
/// The date and time that the revision was last updated, in ISO 8601 format.
@CustomCoding<ISO8601DateCoder>
public var updatedAt: Date
public init(arn: String, comment: String? = nil, createdAt: Date, dataSetId: String, finalized: Bool? = nil, id: String, sourceId: String? = nil, updatedAt: Date) {
self.arn = arn
self.comment = comment
self.createdAt = createdAt
self.dataSetId = dataSetId
self.finalized = finalized
self.id = id
self.sourceId = sourceId
self.updatedAt = updatedAt
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case comment = "Comment"
case createdAt = "CreatedAt"
case dataSetId = "DataSetId"
case finalized = "Finalized"
case id = "Id"
case sourceId = "SourceId"
case updatedAt = "UpdatedAt"
}
}
public struct S3SnapshotAsset: AWSDecodableShape {
/// The size of the S3 object that is the object.
public let size: Double
public init(size: Double) {
self.size = size
}
private enum CodingKeys: String, CodingKey {
case size = "Size"
}
}
public struct StartJobRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "jobId", location: .uri(locationName: "JobId"))
]
public let jobId: String
public init(jobId: String) {
self.jobId = jobId
}
private enum CodingKeys: CodingKey {}
}
public struct StartJobResponse: AWSDecodableShape {
public init() {}
}
public struct TagResourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resource-arn"))
]
public let resourceArn: String
public let tags: [String: String]
public init(resourceArn: String, tags: [String: String]) {
self.resourceArn = resourceArn
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case tags
}
}
public struct UntagResourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "resourceArn", location: .uri(locationName: "resource-arn")),
AWSMemberEncoding(label: "tagKeys", location: .querystring(locationName: "tagKeys"))
]
public let resourceArn: String
public let tagKeys: [String]
public init(resourceArn: String, tagKeys: [String]) {
self.resourceArn = resourceArn
self.tagKeys = tagKeys
}
private enum CodingKeys: CodingKey {}
}
public struct UpdateAssetRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "assetId", location: .uri(locationName: "AssetId")),
AWSMemberEncoding(label: "dataSetId", location: .uri(locationName: "DataSetId")),
AWSMemberEncoding(label: "revisionId", location: .uri(locationName: "RevisionId"))
]
public let assetId: String
public let dataSetId: String
/// The name of the asset. When importing from Amazon S3, the S3 object key is used as the asset name. When exporting to Amazon S3, the asset name is used as default target S3 object key.
public let name: String
public let revisionId: String
public init(assetId: String, dataSetId: String, name: String, revisionId: String) {
self.assetId = assetId
self.dataSetId = dataSetId
self.name = name
self.revisionId = revisionId
}
private enum CodingKeys: String, CodingKey {
case name = "Name"
}
}
public struct UpdateAssetResponse: AWSDecodableShape {
public let arn: String?
public let assetDetails: AssetDetails?
public let assetType: AssetType?
@OptionalCustomCoding<ISO8601DateCoder>
public var createdAt: Date?
public let dataSetId: String?
public let id: String?
public let name: String?
public let revisionId: String?
public let sourceId: String?
@OptionalCustomCoding<ISO8601DateCoder>
public var updatedAt: Date?
public init(arn: String? = nil, assetDetails: AssetDetails? = nil, assetType: AssetType? = nil, createdAt: Date? = nil, dataSetId: String? = nil, id: String? = nil, name: String? = nil, revisionId: String? = nil, sourceId: String? = nil, updatedAt: Date? = nil) {
self.arn = arn
self.assetDetails = assetDetails
self.assetType = assetType
self.createdAt = createdAt
self.dataSetId = dataSetId
self.id = id
self.name = name
self.revisionId = revisionId
self.sourceId = sourceId
self.updatedAt = updatedAt
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case assetDetails = "AssetDetails"
case assetType = "AssetType"
case createdAt = "CreatedAt"
case dataSetId = "DataSetId"
case id = "Id"
case name = "Name"
case revisionId = "RevisionId"
case sourceId = "SourceId"
case updatedAt = "UpdatedAt"
}
}
public struct UpdateDataSetRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "dataSetId", location: .uri(locationName: "DataSetId"))
]
public let dataSetId: String
/// The description for the data set.
public let description: String?
/// The name of the data set.
public let name: String?
public init(dataSetId: String, description: String? = nil, name: String? = nil) {
self.dataSetId = dataSetId
self.description = description
self.name = name
}
private enum CodingKeys: String, CodingKey {
case description = "Description"
case name = "Name"
}
}
public struct UpdateDataSetResponse: AWSDecodableShape {
public let arn: String?
public let assetType: AssetType?
@OptionalCustomCoding<ISO8601DateCoder>
public var createdAt: Date?
public let description: String?
public let id: String?
public let name: String?
public let origin: Origin?
public let originDetails: OriginDetails?
public let sourceId: String?
@OptionalCustomCoding<ISO8601DateCoder>
public var updatedAt: Date?
public init(arn: String? = nil, assetType: AssetType? = nil, createdAt: Date? = nil, description: String? = nil, id: String? = nil, name: String? = nil, origin: Origin? = nil, originDetails: OriginDetails? = nil, sourceId: String? = nil, updatedAt: Date? = nil) {
self.arn = arn
self.assetType = assetType
self.createdAt = createdAt
self.description = description
self.id = id
self.name = name
self.origin = origin
self.originDetails = originDetails
self.sourceId = sourceId
self.updatedAt = updatedAt
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case assetType = "AssetType"
case createdAt = "CreatedAt"
case description = "Description"
case id = "Id"
case name = "Name"
case origin = "Origin"
case originDetails = "OriginDetails"
case sourceId = "SourceId"
case updatedAt = "UpdatedAt"
}
}
public struct UpdateRevisionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "dataSetId", location: .uri(locationName: "DataSetId")),
AWSMemberEncoding(label: "revisionId", location: .uri(locationName: "RevisionId"))
]
/// An optional comment about the revision.
public let comment: String?
public let dataSetId: String
/// Finalizing a revision tells AWS Data Exchange that your changes to the assets in the revision are complete. After it's in this read-only state, you can publish the revision to your products.
public let finalized: Bool?
public let revisionId: String
public init(comment: String? = nil, dataSetId: String, finalized: Bool? = nil, revisionId: String) {
self.comment = comment
self.dataSetId = dataSetId
self.finalized = finalized
self.revisionId = revisionId
}
public func validate(name: String) throws {
try self.validate(self.comment, name: "comment", parent: name, max: 16384)
try self.validate(self.comment, name: "comment", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case comment = "Comment"
case finalized = "Finalized"
}
}
public struct UpdateRevisionResponse: AWSDecodableShape {
public let arn: String?
public let comment: String?
@OptionalCustomCoding<ISO8601DateCoder>
public var createdAt: Date?
public let dataSetId: String?
public let finalized: Bool?
public let id: String?
public let sourceId: String?
@OptionalCustomCoding<ISO8601DateCoder>
public var updatedAt: Date?
public init(arn: String? = nil, comment: String? = nil, createdAt: Date? = nil, dataSetId: String? = nil, finalized: Bool? = nil, id: String? = nil, sourceId: String? = nil, updatedAt: Date? = nil) {
self.arn = arn
self.comment = comment
self.createdAt = createdAt
self.dataSetId = dataSetId
self.finalized = finalized
self.id = id
self.sourceId = sourceId
self.updatedAt = updatedAt
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case comment = "Comment"
case createdAt = "CreatedAt"
case dataSetId = "DataSetId"
case finalized = "Finalized"
case id = "Id"
case sourceId = "SourceId"
case updatedAt = "UpdatedAt"
}
}
}
| apache-2.0 | 70d73d6a1d17f14b8a0aa4c05f775582 | 38.962041 | 530 | 0.620284 | 4.94563 | false | false | false | false |
urbanthings/urbanthings-sdk-apple | UrbanThingsAPI/Internal/JSON/UTColor+JSON.swift | 1 | 1457 | //
// UTColor+JSON.swift
// UrbanThingsAPI
//
// Created by Mark Woollard on 01/05/2016.
// Copyright © 2016 UrbanThings. All rights reserved.
//
#if os(OSX)
import AppKit
public typealias UTColor = NSColor
#else
import UIKit
public typealias UTColor = UIColor
#endif
extension UTColor {
public class func fromJSON(required: Any?) throws -> UTColor {
guard let string = required as? String else {
throw UTAPIError(expected:String.self, not:required, file:#file, function:#function, line:#line)
}
guard let value = string.hexValue else {
throw UTAPIError(jsonParseError:"Invalid hex string \(string)", file:#file, function:#function, line:#line)
}
#if os(OSX)
return UTColor(deviceRed:CGFloat((value & 0xff0000) >> 16)/255.0,
green:CGFloat((value & 0xff00) >> 8)/255.0,
blue:CGFloat(value & 0xff)/255.0,
alpha:1.0)
#else
return UTColor(red:CGFloat((value & 0xff0000) >> 16)/255.0,
green:CGFloat((value & 0xff00) >> 8)/255.0,
blue:CGFloat(value & 0xff)/255.0,
alpha:1.0)
#endif
}
public class func fromJSON(optional: Any?) throws -> UTColor? {
guard let required = optional else {
return nil
}
return try UTColor.fromJSON(required:required)
}
}
| apache-2.0 | 943307ef795f772266a29c452ec7051b | 30.652174 | 119 | 0.572802 | 4.044444 | false | false | false | false |
allbto/WayThere | ios/WayThere/WayThere/Classes/Models/CoreData/Weather.swift | 2 | 2322 | //
// CD_Weather.swift
//
//
// Created by Allan BARBATO on 5/18/15.
//
//
import Foundation
import SwiftyJSON
import CoreData
@objc(Weather)
public class Weather: AModel {
@NSManaged public var title: String?
@NSManaged public var descriptionText: String?
@NSManaged public var humidity: NSNumber?
@NSManaged public var pressure: NSNumber?
@NSManaged public var rainAmount: NSNumber?
@NSManaged public var tempCelcius: NSNumber?
@NSManaged public var tempFahrenheit: NSNumber?
@NSManaged public var creationDate: NSDate
@NSManaged public var cityId: String?
@NSManaged public var day: String?
public var temp : Float {
get { return tempCelcius?.floatValue ?? 0 }
set {
tempCelcius = newValue
tempFahrenheit = newValue * (9 / 5) + 32 // °C x 9/5 + 32 = °F
}
}
public override func awakeFromInsert() {
super.awakeFromInsert()
creationDate = NSDate()
}
public override func fromJson(json: JSON)
{
self.temp = json["main"]["temp"].float ?? 0
self.pressure = json["main"]["pressure"].float
self.humidity = json["main"]["humidity"].float
self.rainAmount = json["rain"]["3h"].float
self.title = json["weather"][0]["main"].string
self.descriptionText = json["weather"][0]["description"].string
}
public func weatherImage() -> UIImage?
{
return Weather.weatherImage(self.title)
}
public static func weatherImage(title: String?) -> UIImage?
{
var image : UIImage? = nil
if let sTitle = title {
let formatedTitle : String
switch sTitle {
case "Clouds":
formatedTitle = "Cloudy"
case "Clear":
formatedTitle = "Sunny"
case "Rain", "Drizzle":
formatedTitle = "Rainy"
case "Extreme":
formatedTitle = "Thunderstorm"
case "Atmosphere":
formatedTitle = "Windy"
default:
formatedTitle = sTitle
}
image = UIImage(named: formatedTitle)
}
if image == nil {
image = UIImage(named: "Unknown")
}
return image
}
}
| mit | c11075c1e70ffeffec58f780af7b6c45 | 25.976744 | 76 | 0.564224 | 4.522417 | false | false | false | false |
WalletOne/P2P | P2PCore/Library/NetworkManager/Mapper.swift | 1 | 2069 | //
// Mapper.swift
// P2P_iOS
//
// Created by Vitaliy Kuzmenko on 20/07/2017.
// Copyright © 2017 Wallet One. All rights reserved.
//
import Foundation
@objc public protocol Mappable: NSObjectProtocol {
init(json: [String: Any])
}
func map(_ object: Any?, _ def: String) -> String {
return (object as? String) ?? def
}
func map(_ object: Any?, _ def: Int) -> Int {
return (object as? NSNumber)?.intValue ?? def
}
func map(_ object: Any?, _ def: Float) -> Float {
return (object as? NSNumber)?.floatValue ?? def
}
func map(_ object: Any?, _ def: Double) -> Double {
return (object as? NSNumber)?.doubleValue ?? def
}
func map(_ object: Any?, _ def: NSDecimalNumber) -> NSDecimalNumber {
guard let number = object as? NSNumber else { return def }
return NSDecimalNumber(decimal: number.decimalValue)
}
func map<T: Mappable>(_ object: Any?, _ def: T) -> T {
guard let json = object as? [String: Any] else { return def }
return T(json: json)
}
func map<T: Mappable>(_ object: Any?, _ def: [T]) -> [T] {
guard let jsonArray = object as? [[String: Any]] else { return def }
return jsonArray.map({ (json) -> T in
return map(json, T(json: [:]))
})
}
func map<T: RawRepresentable>(_ object: Any?, _ def: T) -> T {
if let raw = object as? T.RawValue {
return T(rawValue: raw) ?? def
} else {
return def
}
}
func map(_ object: Any?) -> Date? {
guard let string = object as? String else { return nil }
let formats = [
"yyyy-MM-dd'T'HH:mm:ss",
"yyyy-MM-dd'T'HH:mm:ss'.'SSZ",
"yyyy-MM-dd'T'HH:mm:ss'.'SS",
"yyyy-MM-dd'T'HH:mm:ssZZZZZ",
"yyyy-MM-dd'T'HH:mm:ss'.'SSSZ"
]
let formatter = DateFormatter()
formatter.timeZone = TimeZone(identifier: "UTC")
formatter.locale = Locale(identifier: "en_US_POSIX")
for format in formats {
formatter.dateFormat = format
if let date = formatter.date(from: string) {
return date
}
}
return nil
}
| mit | 4a0b1634117c9f3a5fbe44a41deb4bca | 24.219512 | 72 | 0.583656 | 3.429519 | false | false | false | false |
algolia/algoliasearch-client-swift | Sources/AlgoliaSearchClient/Models/APIKey/APIKeyParameters.swift | 1 | 4671 | //
// APIKeyParams.swift
//
//
// Created by Vladislav Fitc on 08/04/2020.
//
import Foundation
public struct APIKeyParameters {
/// Set of permissions ACL associated to an APIKey.
public var ACLs: [ACL]
/// A Unix timestamp used to define the expiration date of an APIKey.
public var validity: TimeInterval?
/**
Specify the maximum number of hits an [APIKey] can retrieve in one call.
This parameter can be used to protect you from attempts at retrieving your entire index contents by massively
querying the index.
*/
public var maxHitsPerQuery: Int?
/**
Specify the maximum number of API calls allowed from an IP address per hour.
Each time an API call is performed with an APIKey, a check is performed.
If the IP at the source of the call did more than this number of calls in the last hour, a 429 code is returned.
This parameter can be used to protect you from attempts at retrieving your entire index contents by massively
querying the index.
*/
public var maxQueriesPerIPPerHour: Int?
/**
Specify the list of targeted indices. You can target all indices starting with a prefix or ending with a
suffix using the ‘*’ character.
For example, “dev_*” matches all indices starting with “dev_” and “*_dev” matches all indices ending with “_dev”.
*/
public var indices: [IndexName]?
/**
Specify the list of referers. You can target all referers starting with a prefix, ending with a suffix using
the character `*`. For example, "https://algolia.com/`*`" matches all referers starting with
"https://algolia.com/" and "`*`.algolia.com" matches all referers ending with ".algolia.com".
If you want to allow the domain algolia.com you can use "`*`algolia.com/`*`".
*/
public var referers: [String]?
/**
Specify the Query parameters. You can force the Query parameters for a Query using the url string format.
Example: “typoTolerance=strict&ignorePlurals=false”.
*/
public var query: Query?
/**
Specify a description of the APIKey. Used for informative purposes only.
It has impact on the functionality of the APIKey.
*/
public var description: String?
/**
IPv4 network allowed to use the generated key. This is used for more protection against API key leaking and reuse.
- Note: Уou can only provide a single source, but you can specify a range of IPs (e.g., 192.168.1.0/24).
*/
public var restrictSources: String?
public init(ACLs: [ACL]) {
self.ACLs = ACLs
}
}
extension APIKeyParameters: Builder {}
extension APIKeyParameters {
private var queryWithAppliedRestrictSources: Query? {
guard let restrictSources = restrictSources else { return query }
var query = self.query ?? .init()
var customParameters = query.customParameters ?? [:]
customParameters[CodingKeys.restrictSources.rawValue] = .init(restrictSources)
query.customParameters = customParameters
return query
}
}
extension APIKeyParameters: Codable {
enum CodingKeys: String, CodingKey {
case ACLs = "acl"
case validity
case maxHitsPerQuery
case maxQueriesPerIPPerHour
case indices = "indexes"
case referers
case query = "queryParameters"
case description
case restrictSources
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.ACLs = try container.decode(forKey: .ACLs)
self.validity = try container.decodeIfPresent(forKey: .validity)
self.maxHitsPerQuery = try container.decodeIfPresent(forKey: .maxHitsPerQuery)
self.maxQueriesPerIPPerHour = try container.decodeIfPresent(forKey: .maxQueriesPerIPPerHour)
self.indices = try container.decodeIfPresent(forKey: .indices)
self.referers = try container.decodeIfPresent(forKey: .referers)
self.query = try container.decodeIfPresent(forKey: .query)
self.description = try container.decodeIfPresent(forKey: .description)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(ACLs, forKey: .ACLs)
try container.encodeIfPresent(validity, forKey: .validity)
try container.encodeIfPresent(maxHitsPerQuery, forKey: .maxHitsPerQuery)
try container.encodeIfPresent(maxQueriesPerIPPerHour, forKey: .maxQueriesPerIPPerHour)
try container.encodeIfPresent(indices, forKey: .indices)
try container.encodeIfPresent(referers, forKey: .referers)
try container.encodeIfPresent(queryWithAppliedRestrictSources?.urlEncodedString, forKey: .query)
try container.encodeIfPresent(description, forKey: .description)
}
}
| mit | 4537d64adec31b1fcda02aad6270830f | 35.582677 | 117 | 0.733534 | 4.262385 | false | false | false | false |
between40and2/XALG | frameworks/Framework-XALG/Sort/XALG_Sort_ShellSort.swift | 1 | 1161 | //
// XALG_Sort_ShellSort.swift
// XALG
//
// Created by Juguang Xiao on 06/03/2017.
//
import Swift
//https://github.com/between40and2/swift-algorithm-club/tree/master/Shell%20Sort
class XALG_Sort_ShellSort<Element: Comparable> : XALG_Sort_base<Element> {
override func sort(_ array: inout [Element]) {
var subCount = array.count / 2
var k = 0
while subCount > 0 {
for i in 0..<array.count {
guard i + subCount < array.count else{
break
}
if array[i] > array[i+subCount] {
array.swapAt(i, i+subCount)
// swap(&array[i], &array[i+subCount] )
}
guard subCount == 1 && i > 0 else {
continue
}
if array[i-1] > array[i] {
array.swapAt(i-1, i)
// swap(&array[i-1], &array[i])
}
}
subCount = subCount / 2
block_endRound?(k, array)
k += 1
}
}
}
| mit | c2c1cdbed26cc9545edd9093b6d821f4 | 26 | 80 | 0.425495 | 4.017301 | false | false | false | false |
lukaskubanek/OrderedDictionary | Tests/OrderedDictionaryTests/DescriptionTests.swift | 1 | 1420 | import Foundation
import OrderedDictionary
import XCTest
struct DescribedValue: CustomStringConvertible, CustomDebugStringConvertible {
init(_ value: Int) { self.value = value }
let value: Int
var description: String { return "\(value)" }
var debugDescription: String { return "debug(\(value))" }
}
class DescriptionTests: XCTestCase {
func testEmptyDescription() {
let orderedDictionary = OrderedDictionary<String, DescribedValue>()
XCTAssertEqual(orderedDictionary.description, "[:]")
}
func testDescription() {
let orderedDictionary: OrderedDictionary = [
"a": DescribedValue(1),
"b": DescribedValue(2),
"c": DescribedValue(3)
]
XCTAssertEqual(orderedDictionary.description, "[a: 1, b: 2, c: 3]")
}
func testEmptyDebugDescription() {
let orderedDictionary = OrderedDictionary<String, DescribedValue>()
XCTAssertEqual(orderedDictionary.debugDescription, "[:]")
}
func testDebugDescription() {
let orderedDictionary: OrderedDictionary = [
"a": DescribedValue(1),
"b": DescribedValue(2),
"c": DescribedValue(3)
]
XCTAssertEqual(
orderedDictionary.debugDescription,
"[\"a\": debug(1), \"b\": debug(2), \"c\": debug(3)]"
)
}
}
| mit | 2a021e958087eaa32d8c73b60c777640 | 27.979592 | 78 | 0.596479 | 5.461538 | false | true | false | false |
viWiD/Persist | Pods/Evergreen/Sources/Evergreen/Logger.swift | 1 | 25620 | //
// Logger.swift
// Evergreen
//
// Created by Nils Fischer on 19.08.14.
// Copyright (c) 2014 viWiD Webdesign & iOS Development. All rights reserved.
//
import Foundation
// MARK: - Global Interface
/// The root of the logger hierarchy
public let defaultLogger: Logger = {
let logger = Logger(key: "Default", parent: nil)
logger.handlers.append(ConsoleHandler())
return logger
}()
/// The default logger's log level
public var logLevel: LogLevel? {
get {
return defaultLogger.logLevel
}
set {
defaultLogger.logLevel = newValue
}
}
/// Returns the logger for the specified key path.
/// - seealso: `Logger.loggerForKeyPath(_:)`
public func getLogger(keyPath: Logger.KeyPath) -> Logger {
return Logger.loggerForKeyPath(keyPath)
}
/// Returns an appropriate logger for the given file.
/// - seealso: `Logger.loggerForFile(_:)`
public func getLoggerForFile(file: String = #file) -> Logger {
return Logger.loggerForFile(file)
}
/// Logs the event using a logger that is appropriate for the caller.
/// - seealso: `Logger.log(_:, forLevel:)`
public func log<M>(@autoclosure(escaping) message: () -> M, error: ErrorType? = nil, forLevel logLevel: LogLevel? = nil, onceForKey key: String? = nil, function: String = #function, file: String = #file, line: Int = #line)
{
Logger.loggerForFile(file).log(message, error: error, forLevel: logLevel, onceForKey: key, function: function, file: file, line: line)
}
/// Logs the event with the Verbose log level using a logger that is appropriate for the caller.
/// - seealso: `Logger.log(_:, forLevel:)`
public func verbose<M>(@autoclosure(escaping) message: () -> M, error: ErrorType? = nil, onceForKey key: String? = nil, function: String = #function, file: String = #file, line: Int = #line) {
Evergreen.log(message, error: error, forLevel: .Verbose, onceForKey: key, function: function, file: file, line: line)
}
/// Logs the event with the Debug log level using a logger that is appropriate for the caller.
/// - seealso: `Logger.log(_:, forLevel:)`
public func debug<M>(@autoclosure(escaping) message: () -> M, error: ErrorType? = nil, onceForKey key: String? = nil, function: String = #function, file: String = #file, line: Int = #line) {
Evergreen.log(message, error: error, forLevel: .Debug, onceForKey: key, function: function, file: file, line: line)
}
/// Logs the event with the Info log level using a logger that is appropriate for the caller.
/// - seealso: `Logger.log(_:, forLevel:)`
public func info<M>(@autoclosure(escaping) message: () -> M, error: ErrorType? = nil, onceForKey key: String? = nil, function: String = #function, file: String = #file, line: Int = #line) {
Evergreen.log(message, error: error, forLevel: .Info, onceForKey: key, function: function, file: file, line: line)
}
/// Logs the event with the Warning log level using a logger that is appropriate for the caller.
/// - seealso: `Logger.log(_:, forLevel:)`
public func warning<M>(@autoclosure(escaping) message: () -> M, error: ErrorType? = nil, onceForKey key: String? = nil, function: String = #function, file: String = #file, line: Int = #line) {
Evergreen.log(message, error: error, forLevel: .Warning, onceForKey: key, function: function, file: file, line: line)
}
/// Logs the event with the Error log level using a logger that is appropriate for the caller.
/// - seealso: `Logger.log(_:, forLevel:)`
public func error<M>(@autoclosure(escaping) message: () -> M, error: ErrorType? = nil, onceForKey key: String? = nil, function: String = #function, file: String = #file, line: Int = #line) {
Evergreen.log(message, error: error, forLevel: .Error, onceForKey: key, function: function, file: file, line: line)
}
/// Logs the event with the Critical log level using a logger that is appropriate for the caller.
/// - seealso: `Logger.log(_:, forLevel:)`
public func critical<M>(@autoclosure(escaping) message: () -> M, error: ErrorType? = nil, onceForKey key: String? = nil, function: String = #function, file: String = #file, line: Int = #line) {
Evergreen.log(message, error: error, forLevel: .Critical, onceForKey: key, function: function, file: file, line: line)
}
/// Alias for `Logger.tic` for a logger that is appropriate for the caller.
/// - seealso: `Logger.tic`
public func tic<M>(@autoclosure(escaping) andLog message: () -> M, error: ErrorType? = nil, forLevel logLevel: LogLevel? = nil, timerKey: String? = nil, function: String = #function, file: String = #file, line: Int = #line)
{
Logger.loggerForFile(file).tic(andLog: message, error: error, forLevel: logLevel, timerKey: timerKey, function: function, file: file, line: line)
}
/// Alias for `Logger.toc` for a logger that is appropriate for the caller.
/// - seealso: `Logger.toc`
public func toc<M>(@autoclosure(escaping) andLog message: () -> M, error: ErrorType? = nil, forLevel logLevel: LogLevel? = nil, timerKey: String? = nil, function: String = #function, file: String = #file, line: Int = #line)
{
Logger.loggerForFile(file).toc(andLog: message, error: error, forLevel: logLevel, timerKey: timerKey, function: function, file: file, line: line)
}
/**
Reads the logging configuration from environment variables.
Every environment variable with prefix `Evergreen` is evaluated as a logger key path and assigned a log level corresponding to its value. Values should match the log level descriptions, e.g. `Debug`.
Valid environment variable declarations would be e.g. `Evergreen = Debug` or `Evergreen.MyLogger = Verbose`.
*/
public func configureFromEnvironment()
{
let prefix = "Evergreen"
let environmentVariables = NSProcessInfo.processInfo().environment
var configurations = [(Logger, LogLevel)]()
for (key, value) in environmentVariables where key.hasPrefix(prefix) {
let (_, keyPath) = Logger.KeyPath(string: key).popFirst()
let logger = Logger.loggerForKeyPath(keyPath)
if let logLevel = LogLevel(description: value) {
logger.logLevel = logLevel
configurations.append((logger, logLevel))
} else {
log("Invalid Evergreen log level '\(value)' for key path '\(keyPath)' in environment variable.", forLevel: .Warning)
}
}
if configurations.count > 0 {
log("Configured Evergreen logging from environment. Configurations: \(configurations)", forLevel: .Debug)
} else {
log("Tried to configure Evergreen logging from environment, but no valid configuration was found.", forLevel: .Warning)
}
}
// MARK: - Logger
public final class Logger {
// MARK: Public Properties
/**
The verbosity threshold for this logger.
A logger will only log events with equal or higher log levels. If no log level is specified, the `effectiveLogLevel` is used to determine the log level by reaching up the logger hierarchy until a logger specifies a log level.
*/
public var logLevel: LogLevel?
/**
The effective verbosity threshold for this logger in its hierarchy.
Determined by reaching up the logger hierarchy until a logger specifies a log level.
*/
public var effectiveLogLevel: LogLevel? {
if let logLevel = self.logLevel {
return logLevel
} else {
if let parent = self.parent {
return parent.effectiveLogLevel
} else {
return nil
}
}
}
/**
The handlers provided by this logger to process log events.
Assign handlers such as a `ConsoleHandler` or `FileHandler` to this array to make them emit events passed to the logger.
*/
public var handlers = [Handler]()
/**
Whether to pass events up the logger hierarchy.
If set to `true`, events this logger received from logging calls or from children in its hierarchy are passed on to its parent after they were handled.
Defaults to `true`.
*/
public var shouldPropagate = true
/// The parent in the logger hierarchy
public let parent: Logger?
/// The children in the logger hierarchy
public private(set) var children = [ String : Logger]()
/// The root of the logger hierarchy
public var root: Logger {
if let parent = parent {
return parent.root
} else {
return self
}
}
/// The key used to identify this logger in the logger hierarchy and in records emitted by a handler
public let key: String
/// The key path up to the root of the logger hierarchy
public var keyPath: KeyPath {
return self.keyPath()
}
/// The key path up to (excluding) any logger in the hierarchy or to the root, if none is specified
public func keyPath(upToParent excludedLogger: Logger? = nil) -> KeyPath {
if let parent = self.parent where !(excludedLogger != nil && parent === excludedLogger!) {
return parent.keyPath(upToParent: excludedLogger).keyPathByAppendingComponent(self.key)
} else {
return KeyPath(components: [ self.key ])
}
}
// MARK: Initialization
/**
Creates a new logger. For general purposes, use the global `getLogger` method or the various Logger class and instance methods instead to retrieve appropriate loggers in the logger hierarchy.
- warning: If you don't specify a parent, the logger is detached from the logger hierarchy and will not have any handlers.
*/
public init(key: String, parent: Logger?) {
self.key = key
self.parent = parent
parent?.children[key] = self
}
// MARK: Intial Info
// TODO: Decide, whether this is useful or not. Clients can just log information about the handlers they set up themselves, e.g. the log file name of a FileHandler.
// private var hasLoggedInitialInfo: Bool = false
// /// Logs appropriate information about the logging setup automatically when the first logging call occurs.
// private func logInitialInfo() {
// if !hasLoggedInitialInfo {
// if handlers.count > 0 {
// let event = Event(logger: self, message: { "Logging to \(self.handlers)..." }, error: nil, logLevel: .Info, date: NSDate(), elapsedTime: nil, function: #function, file: #file, line: #line)
// self.handleEvent(event)
// }
// hasLoggedInitialInfo = true
// }
// if shouldPropagate {
// if let parent = self.parent {
// parent.logInitialInfo()
// }
// }
// }
// MARK: Logging
/**
Logs the event given by its `message` and additional information that is gathered automatically. The `logLevel` parameter in conjunction with the logger's `effectiveLogLevel` determines, if the event will be handled or ignored.
- parameter message: The message to be logged, provided by an autoclosure. The closure will not be evaluated if the event is not going to be emitted, so it can contain expensive operations only needed for logging purposes.
- parameter error: An error that occured and should be logged alongside the event.
- parameter logLevel: If the event's log level is lower than the receiving logger's `effectiveLogLevel`, the event will not be logged. The event will always be logged, if no log level is provided for either the event or the logger's `effectiveLogLevel`.
- parameter key: Only logs the message if no logging calls with the same `key` have occured before.
*/
public func log<M>(@autoclosure(escaping) message: () -> M, error: ErrorType? = nil, forLevel logLevel: LogLevel? = nil, onceForKey key: String? = nil, function: String = #function, file: String = #file, line: Int = #line)
{
if let key = key {
if keysLoggedOnce.contains(key) {
return
} else {
keysLoggedOnce.insert(key)
}
}
let event = Event(logger: self, message: message, error: error, logLevel: logLevel, date: NSDate(), elapsedTime: nil, once: key != nil, function: function, file: file, line: line)
self.logEvent(event)
}
/// Logs the event with the Verbose log level.
/// - seealso: `log(_:, forLevel:)`
public func verbose<M>(@autoclosure(escaping) message: () -> M, error: ErrorType? = nil, onceForKey key: String? = nil, function: String = #function, file: String = #file, line: Int = #line) {
self.log(message, error: error, forLevel: .Verbose, onceForKey: key, function: function, file: file, line: line)
}
/// Logs the event with the Debug log level.
/// - seealso: `log(_:, forLevel:)`
public func debug<M>(@autoclosure(escaping) message: () -> M, error: ErrorType? = nil, onceForKey key: String? = nil, function: String = #function, file: String = #file, line: Int = #line) {
self.log(message, error: error, forLevel: .Debug, onceForKey: key, function: function, file: file, line: line)
}
/// Logs the event with the Info log level.
/// - seealso: `log(_:, forLevel:)`
public func info<M>(@autoclosure(escaping) message: () -> M, error: ErrorType? = nil, onceForKey key: String? = nil, function: String = #function, file: String = #file, line: Int = #line) {
self.log(message, error: error, forLevel: .Info, onceForKey: key, function: function, file: file, line: line)
}
/// Logs the event with the Warning log level.
/// - seealso: `log(_:, forLevel:)`
public func warning<M>(@autoclosure(escaping) message: () -> M, error: ErrorType? = nil, onceForKey key: String? = nil, function: String = #function, file: String = #file, line: Int = #line) {
self.log(message, error: error, forLevel: .Warning, onceForKey: key, function: function, file: file, line: line)
}
/// Logs the event with the Error log level.
/// - seealso: `log(_:, forLevel:)`
public func error<M>(@autoclosure(escaping) message: () -> M, error: ErrorType? = nil, onceForKey key: String? = nil, function: String = #function, file: String = #file, line: Int = #line) {
self.log(message, error: error, forLevel: .Error, onceForKey: key, function: function, file: file, line: line)
}
/// Logs the event with the Critical log level.
/// - seealso: `log(_:, forLevel:)`
public func critical<M>(@autoclosure(escaping) message: () -> M, error: ErrorType? = nil, onceForKey key: String? = nil, function: String = #function, file: String = #file, line: Int = #line) {
self.log(message, error: error, forLevel: .Critical, onceForKey: key, function: function, file: file, line: line)
}
var keysLoggedOnce = Set<String>()
/// Logs the given event. Use `log(_:, forLevel:)` instead for convenience.
public func logEvent<M>(event: Event<M>)
{
// self.logInitialInfo()
if let effectiveLogLevel = self.effectiveLogLevel, let eventLogLevel = event.logLevel where eventLogLevel < effectiveLogLevel {
return
} else {
self.handleEvent(event)
}
}
/// Passes the event to this logger's `handlers` and then up the logger hierarchy, given `shouldPropagate` is set to `true`.
private func handleEvent<M>(event: Event<M>, wasHandled: Bool = false)
{
var wasHandled = wasHandled
for handler in handlers {
handler.emitEvent(event)
wasHandled = true
}
if let parent = self.parent where shouldPropagate {
parent.handleEvent(event, wasHandled: wasHandled)
} else {
if !wasHandled {
// TODO: use println() directly? Using log() will cause an endless loop when defaultLogger does not have any handlers.
print("Tried to log an event for logger '\(event.logger)', but no handler was found in the logger hierarchy to emit the event: \(event.file):\(event.line) \(event.function)")
}
}
}
// MARK: Measuring Time
private var defaultStartDate: NSDate?
private lazy var startDates = [String : NSDate]()
// TODO: log "Tic..." message by default
/**
Logs the given event and starts tracking the time until the next call to `toc`.
- parameter timerKey: Provide as an identifier in nested calls to `tic` and `toc`.
- seealso: `log(_:, forLevel:)`
- seealso: `toc`
*/
public func tic<M>(@autoclosure(escaping) andLog message: () -> M, error: ErrorType? = nil, forLevel logLevel: LogLevel? = nil, timerKey: String? = nil, function: String = #function, file: String = #file, line: Int = #line)
{
if let timerKey = timerKey {
startDates[timerKey] = NSDate()
} else {
defaultStartDate = NSDate()
}
self.log(message, error: error, forLevel: logLevel, function: function, file: file, line: line)
}
// TODO: log "...Toc" message by default
/**
Call after a preceding `tic` to log the elapsed time between both calls alongside the event.
- seealso: `tic`
*/
public func toc<M>(@autoclosure(escaping) andLog message: () -> M, error: ErrorType? = nil, forLevel logLevel: LogLevel? = nil, timerKey: String? = nil, function: String = #function, file: String = #file, line: Int = #line)
{
var startDate: NSDate?
if let timerKey = timerKey {
startDate = startDates[timerKey]
} else {
startDate = defaultStartDate
}
if let startDate = startDate {
let elapsedTime = NSDate().timeIntervalSinceDate(startDate)
let event = Event(logger: self, message: message, error: error, logLevel: logLevel, date: NSDate(), elapsedTime: elapsedTime, once: false, function: function, file: file, line: line)
self.logEvent(event)
}
}
// MARK: Logger Hierarchy
/// The root of the logger hierarchy
public class func defaultLogger() -> Logger {
return Evergreen.defaultLogger
}
/**
Returns an appropriate logger for the given file.
Generally, the logger's key will be the file name and it will be a direct child of the default logger.
*/
public class func loggerForFile(file: String = #file) -> Logger {
guard let fileURL = NSURL(string: file), let key = fileURL.lastPathComponent else {
return Evergreen.defaultLogger
}
return self.loggerForKeyPath(KeyPath(components: [ key ]))
}
/**
Always returns the same logger object for a given key path.
A key path is a dot-separated string of keys like `"MyModule.MyClass"` describing the logger hierarchy relative to the default logger.
A parent-child relationship is established and can be used to set specific settings such as log levels and handlers for only parts of the logger hierarchy.
*/
public class func loggerForKeyPath(keyPath: Logger.KeyPath) -> Logger {
let (key, remainingKeyPath) = keyPath.popFirst()
if let key = key {
if key == self.defaultLogger().key {
return self.defaultLogger().childForKeyPath(remainingKeyPath)
} else {
return self.defaultLogger().childForKeyPath(keyPath)
}
} else {
return self.defaultLogger()
}
}
/// Returns a logger with a given key path relative to the receiver.
public func childForKeyPath(keyPath: KeyPath) -> Logger {
let (key, remainingKeyPath) = keyPath.popFirst()
if let key = key {
let child = children[key] ?? Logger(key: key, parent: self)
return child.childForKeyPath(remainingKeyPath)
} else {
return self
}
}
// MARK: Key Path Struct
/// Encapsulates a hierarchical structure of keys used to identify a logger's position in the logger hierarchy.
public struct KeyPath: StringLiteralConvertible, CustomStringConvertible {
public let components: [String]
public init(components: [String]) {
self.components = components
}
public init(string: String) {
self.components = string.componentsSeparatedByString(".").filter { !$0.isEmpty }
}
public func keyPathByPrependingComponent(component: String) -> KeyPath {
return KeyPath(components: [ component ] + components)
}
public func keyPathByAppendingComponent(component: String) -> KeyPath {
return KeyPath(components: components + [ component ])
}
public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
self.components = value.componentsSeparatedByString(".").filter { !$0.isEmpty }
}
public typealias UnicodeScalarLiteralType = StringLiteralType
public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
self.components = value.componentsSeparatedByString(".").filter { !$0.isEmpty }
}
public init(stringLiteral value: StringLiteralType) {
self.components = value.componentsSeparatedByString(".").filter { !$0.isEmpty }
}
public func popFirst() -> (key: String?, remainingKeyPath: KeyPath) {
let key = components.first
let remainingKeyPath: KeyPath = (components.count > 1) ? KeyPath(components: Array(components[1..<components.count])) : KeyPath(components: [String]())
return (key, remainingKeyPath)
}
public var description: String {
return description()
}
public func description(separator separator: String? = nil) -> String {
return components.joinWithSeparator(separator ?? ".")
}
}
}
// MARK: - Printable
extension Logger: CustomStringConvertible {
public var description: String {
return self.description()
}
public func description(keyPathSeparator: String? = nil) -> String {
var keyPath = self.keyPath(upToParent: defaultLogger)
if self.root !== defaultLogger {
keyPath = keyPath.keyPathByPrependingComponent("DETACHED")
}
return keyPath.description(separator: keyPathSeparator)
}
}
// MARK: - Log Levels
/**
You can assign an *importance* or *severity* to an event corresponding to one of the following *log levels*:
- **Critical:** Events that are unexpected and can cause serious problems. You would want to be called in the middle of the night to deal with these.
- **Error:** Events that are unexpected and not handled by your software. Someone should tell you about these ASAP.
- **Warning:** Events that are unexpected, but will probably not affect the runtime of your software. You would want to investigate these eventually.
- **Info:** General events that document the software's lifecycle.
- **Debug:** Events to give you an understanding about the flow through your software, mainly for debugging purposes.
- **Verbose:** Detailed information about the environment to provide additional context when needed.
The logger that handles the event has a log level as well. **If the event's log level is lower than the logger's, it will not be logged.**
In addition to the log levels above, a logger can have one of the following log levels. Assigning these to events only makes sense in specific use cases.
- **All:** All events will be logged.
- **Off:** No events will be logged.
*/
public enum LogLevel: Int, CustomStringConvertible, Comparable {
case All = 0, Verbose, Debug, Info, Warning, Error, Critical, Off
public var description: String {
switch self {
case .All: return "All"
case .Verbose: return "Verbose"
case .Debug: return "Debug"
case .Info: return "Info"
case .Warning: return "Warning"
case .Error: return "Error"
case .Critical: return "Critical"
case .Off: return "Off"
}
}
public init?(description: String) {
let description = description.lowercaseString
var i = 0
while let logLevel = LogLevel(rawValue: i) {
if logLevel.description.lowercaseString == description {
self = logLevel
return
}
i += 1
}
return nil
}
}
public func == (lhs: LogLevel, rhs: LogLevel) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public func < (lhs: LogLevel, rhs: LogLevel) -> Bool {
return lhs.rawValue < rhs.rawValue
}
// MARK: - Log Event Struct
/// Represents an event given by a descriptive message and additional information that occured during the software's runtime. A log level describing the event's severity is associated with the event.
public struct Event<M> {
/// The logger that originally logged the event
let logger: Logger
/// The log message
let message: () -> M
/// An error that occured alongside the event
let error: ErrorType?
/// The log level. A logger will only log events with equal or higher log levels than its own. Events that don't specify a log level will always be logged.
let logLevel: LogLevel?
let date: NSDate
let elapsedTime: NSTimeInterval?
let once: Bool
let function: String
let file: String
let line: Int
}
| mit | c5f1193ef879f04cd5371eb50f72ebaf | 43.712042 | 258 | 0.650937 | 4.412677 | false | false | false | false |
GitOyoung/LibraryManagement | LibraryManagement/DataTool.swift | 1 | 2211 | //
// DataTool.swift
// LibraryManagement
//
// Created by oyoung on 15/11/30.
// Copyright © 2015年 Oyoung. All rights reserved.
//
import UIKit
//书本信息
class Book: NSObject {
}
//记录信息
class Record: NSObject {
let db:FMDatabase?
override init() {
db = FMDatabase(path: LMConfig.defaultConfig().dataBasePath())
}
}
//书本数据
class BookData: NSObject {
private var typeDict:NSDictionary?
private var dataSource:NSMutableDictionary?
override init() {
typeDict = nil
dataSource = nil
}
func loadData()
{
}
func storeData(data: NSMutableDictionary)
{
}
func storeBook(book: Book)
{
}
func typeInfo() -> NSDictionary?
{
return typeDict
}
func data() -> NSMutableDictionary?
{
return dataSource
}
}
//记录数据
class RecordData: NSObject {
var records:NSMutableArray?
override init() {
records = nil
}
//取数据
func loadRecords()
{
}
//保存全纪录数据
func storeRecords(records: NSMutableArray)
{
for record in records
{
if record.isKindOfClass(Record.classForCoder())
{
storeRecord(record as! Record)
}
}
}
//保存单条记录
func storeRecord(record: Record)
{
}
}
class DataTool: NSObject {
static private var dataTool:DataTool? = nil
static func defaultTool() -> DataTool
{
if dataTool == nil
{
dataTool = DataTool()
}
return dataTool!
}
private var _bookData: BookData?
private var _recordData: RecordData?
private override init() {
super.init()
_bookData = nil
_recordData = nil
}
func bookData() ->BookData
{
if _bookData == nil
{
_bookData = BookData()
}
return _bookData!
}
func recordData() -> RecordData
{
if _recordData == nil
{
_recordData = RecordData()
}
return _recordData!
}
}
| gpl-3.0 | 463362eba630e6a5bcd50f9b5380736b | 16.290323 | 70 | 0.525187 | 4.279441 | false | false | false | false |
kazedayo/GaldenApp | GaldenApp/View Controllers/BlockedUserViewController.swift | 1 | 1983 | //
// BlockedUserViewController.swift
// GaldenApp
//
// Created by Kin Wa Lam on 28/10/2017.
// Copyright © 2017年 1080@galden. All rights reserved.
//
import UIKit
class BlockedUserViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
@IBOutlet weak var blockListTableView: UITableView!
var blockedUsers = [BlockedUsers]()
let api = HKGaldenAPI()
override func viewDidLoad() {
super.viewDidLoad()
blockListTableView.dataSource = self
blockListTableView.delegate = self
api.getBlockedUsers(completion: {
blocked in
self.blockedUsers = blocked
self.blockListTableView.reloadData()
})
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return blockedUsers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BlockedUserTableViewCell") as! BlockedUserTableViewCell
cell.userLabel.text = blockedUsers[indexPath.row].userName
cell.idLabel.text = "UID: " + blockedUsers[indexPath.row].id
return cell
}
@IBAction func closeButtonPressed(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | ddef3e60747feef945bbe47429233e6e | 30.428571 | 121 | 0.668182 | 5.142857 | false | false | false | false |
xtcan/playerStudy_swift | TCVideo_Study/TCVideo_Study/Classes/Home/Controller/HomeViewController.swift | 1 | 3722 | //
// HomeViewController.swift
// TCVideo_Study
//
// Created by tcan on 17/5/22.
// Copyright © 2017年 tcan. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
view.backgroundColor = UIColor(hex: "e0e0e0")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//MARK:- UI
extension HomeViewController{
fileprivate func setupUI(){
setupNavigationBar()
setupContentView()
}
private func setupNavigationBar(){
// 2.设置右侧收藏的item
let collectImage = UIImage(named: "search_btn_follow")
navigationItem.rightBarButtonItem = UIBarButtonItem(image: collectImage, style: .plain, target: self, action: #selector(followItemClick))
// 事件监听 --> 发送消息 --> 将方法包装SEL --> 类方法列表 --> IMP
// 3.搜索框
let searchFrame = CGRect(x: 0, y: 0, width: 200, height: 32)
let searchBar = UISearchBar(frame: searchFrame)
searchBar.placeholder = "昵称/房间号/链接"
navigationItem.titleView = searchBar
searchBar.searchBarStyle = .minimal
let searchFiled = searchBar.value(forKey: "_searchField") as? UITextField
searchFiled?.textColor = UIColor.white
}
fileprivate func setupContentView() {
automaticallyAdjustsScrollViewInsets = false
//frame
let pageViewFrame = CGRect(x: 0, y: 64, width: view.bounds.width, height: view.bounds.height - 64 - 44)
// //头部标题
// let titles = ["推荐","热点","搞笑哈哈频道","音乐","体育","娱乐抢先看","汽车"]
//获取头部标题数据
let homeCategoryTypes = loadCategoryTypeData()
//遍历数组,取出每个模型的title属性
let titles = homeCategoryTypes.map({ $0.title })
/*
let titles1 = homeCategoryTypes.map { (type : HomeCategoryType) -> String in
return type.title
}
*/
//样式
let style = TCPageStyle()
style.isScrollEnable = true
style.isTitleScale = true
style.isShowCoverView = false
//初始化所有控制器
var childVCs = [WaterfallViewController]()
for type in homeCategoryTypes {
let vc = WaterfallViewController()
vc.homeType = type
childVCs.append(vc)
}
//根据上面参数创建pageview
let pageView = TCPageView(frame: pageViewFrame, titles: titles, titleStyle: style, childVCs: childVCs, parentVC: self)
//将pageview添加到当前控制器
view.addSubview(pageView)
}
/// 读取文件中的主页title分类
///
/// - Returns: 主页title分类
fileprivate func loadCategoryTypeData() -> [HomeCategoryType]{
//文件路径
let path = Bundle.main.path(forResource: "types.plist", ofType: nil)!
//根据文件路径获取的字典数组
let dictArray = NSArray(contentsOfFile: path) as! [[String : Any]]
//字典数组转模型数组
var modelArray = [HomeCategoryType]()
for dict in dictArray {
modelArray .append(HomeCategoryType(dict: dict))
}
return modelArray
}
}
// MARK:- 事件监听函数
extension HomeViewController {
@objc fileprivate func followItemClick() {
print("------")
}
}
| apache-2.0 | 173584f58497e0943c321a239e49cdfe | 26.491935 | 145 | 0.587562 | 4.575839 | false | false | false | false |
davidjinhan/ButtonMenuPopup | ButtonMenuPopup/CellRegistration.swift | 1 | 2524 | //
// CellRegistration.swift
// ButtonMenuPopup
//
// Created by HanJin on 2017. 3. 27..
// Copyright © 2017년 DavidJinHan. All rights reserved.
//
import UIKit
protocol ReusableView: class {
static var defaultReuseIdentifier: String { get }
}
extension ReusableView where Self: UIView {
static var defaultReuseIdentifier: String {
return NSStringFromClass(self).components(separatedBy: ".").last!
}
}
extension UICollectionViewCell: ReusableView {
}
extension UITableViewCell: ReusableView {
}
protocol NibLoadableView: class {
static var nibName: String { get }
}
extension NibLoadableView where Self: UIView {
static var nibName: String {
return NSStringFromClass(self).components(separatedBy: ".").last!
}
}
extension UICollectionView {
func register<T: UICollectionViewCell>(_: T.Type) where T: ReusableView {
register(T.self, forCellWithReuseIdentifier: T.defaultReuseIdentifier)
}
func register<T: UICollectionViewCell>(_: T.Type) where T: ReusableView, T: NibLoadableView {
let bundle = Bundle(for: T.self)
let nib = UINib(nibName: T.nibName, bundle: bundle)
register(nib, forCellWithReuseIdentifier: T.defaultReuseIdentifier)
}
func dequeueReusableCell<T: UICollectionViewCell>(forIndexPath indexPath: IndexPath) -> T where T: ReusableView {
guard let cell = dequeueReusableCell(withReuseIdentifier: T.defaultReuseIdentifier, for: indexPath as IndexPath) as? T else {
fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)")
}
return cell
}
}
extension UITableView {
func register<T: UITableViewCell>(_: T.Type) where T: ReusableView {
register(T.self, forCellReuseIdentifier: T.defaultReuseIdentifier)
}
func register<T: UITableViewCell>(_: T.Type) where T: ReusableView, T: NibLoadableView {
let bundle = Bundle(for: T.self)
let nib = UINib(nibName: T.nibName, bundle: bundle)
register(nib, forCellReuseIdentifier: T.defaultReuseIdentifier)
}
func dequeueReusableCell<T: UITableViewCell>(forIndexPath indexPath: IndexPath) -> T where T: ReusableView {
guard let cell = dequeueReusableCell(withIdentifier: T.defaultReuseIdentifier, for: indexPath as IndexPath) as? T else {
fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)")
}
return cell
}
}
| mit | 2c5dc777ea922516d180a10a71e44f62 | 30.123457 | 133 | 0.685839 | 4.962598 | false | false | false | false |
yaslab/Harekaze-iOS | Harekaze/Views/VideoInformationView.swift | 1 | 2474 | /**
*
* VideoInformationView.swift
* Harekaze
* Created by Yuki MIZUNO on 2016/07/17.
*
* Copyright (c) 2016-2017, Yuki MIZUNO
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import Material
class VideoInformationView: UIView {
// MARK: - Interface Builder outlets
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subTitleLabel: UILabel!
@IBOutlet weak var titleView: UIView!
// MARK: - Content size information
var estimatedHeight: CGFloat {
titleView.setNeedsLayout()
titleView.layoutIfNeeded()
return titleView.bounds.height
}
// MARK: - Content setup
func setup(_ program: Program) {
titleView.backgroundColor = Material.Color.blue.darken2
var subTitleText = ""
// Add episode and subtitle
if program.episode > 0 {
subTitleText = "#\(program.episode) "
}
if program.subTitle != "" {
subTitleText += program.subTitle
}
titleLabel.text = program.title
subTitleLabel.text = subTitleText
}
}
| bsd-3-clause | d293118c07ec90596e6fffa645b48dfc | 33.361111 | 80 | 0.74616 | 4.325175 | false | false | false | false |
petester42/RxSwift | RxExample/RxExample/Services/UIImageView+DownloadableImage.swift | 6 | 1526 | //
// UIImageView+DownloadableImage.swift
// RxExample
//
// Created by Vodovozov Gleb on 01.11.2015.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
import UIKit
extension UIImageView{
var rxex_downloadableImage: AnyObserver<DownloadableImage>{
return self.rxex_downloadableImageAnimated(nil)
}
func rxex_downloadableImageAnimated(transitionType:String?) -> AnyObserver<DownloadableImage> {
return AnyObserver { [weak self] event in
guard let strongSelf = self else { return }
MainScheduler.ensureExecutingOnScheduler()
switch event{
case .Next(let value):
for subview in strongSelf.subviews {
subview.removeFromSuperview()
}
switch value{
case .Content(let image):
strongSelf.rx_image.onNext(image)
case .OfflinePlaceholder:
let label = UILabel(frame: strongSelf.bounds)
label.textAlignment = .Center
label.font = UIFont.systemFontOfSize(35)
label.text = "⚠️"
strongSelf.addSubview(label)
}
case .Error(let error):
bindingErrorToInterface(error)
break
case .Completed:
break
}
}
}
}
#endif
| mit | 689d741d38f6c401f17979bff6ce40f8 | 27.166667 | 99 | 0.566732 | 5.07 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.