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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ibm-cloud-security/appid-serversdk-swift | Sources/IBMCloudAppID/Utils.swift | 1 | 7180 | /*
Copyright 2017 IBM Corp.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import SwiftyJSON
import LoggerAPI
import CryptorRSA
@available(OSX 10.12, *)
class Utils {
static func getAuthorizedIdentities(from idToken: JSON) -> AuthorizationContext? {
Log.debug("APIStrategy getAuthorizedIdentities")
return AuthorizationContext(idTokenPayload: idToken["payload"])
}
static func getAuthorizedIdentities(from idToken: [String: Any]) -> AuthorizationContext? {
Log.debug("APIStrategy getAuthorizedIdentities")
guard let json = try? JSONSerialization.data(withJSONObject: idToken, options: .prettyPrinted) else {
return nil
}
return AuthorizationContext(idTokenPayload: JSON(data: json))
}
static func parseToken(from tokenString: String) throws -> JSON {
let tokenComponents = tokenString.components(separatedBy: ".")
guard tokenComponents.count == 3 else {
Log.error("Invalid access token format")
throw AppIDError.invalidTokenFormat
}
guard let jwtHeaderData = tokenComponents[0].base64decodedData(),
let jwtPayloadData = tokenComponents[1].base64decodedData()
else {
Log.error("Invalid access token format")
throw AppIDError.invalidTokenFormat
}
let jwtHeader = JSON(data: jwtHeaderData)
let jwtPayload = JSON(data: jwtPayloadData)
let jwtSignature = tokenComponents[2]
var json = JSON([:])
json["header"] = jwtHeader
json["payload"] = jwtPayload
json["signature"] = JSON(jwtSignature)
return json
}
private static func parseTokenObject(from tokenString: String) throws -> Token {
return try Token(with: tokenString)
}
@available(OSX 10.12, *)
private static func isSignatureValid(_ token: Token, with pk: String) throws -> Bool {
var isValid: Bool = false
guard let tokenPublicKey = try? CryptorRSA.createPublicKey(withPEM: pk) else {
throw AppIDError.publicKeyNotFound
}
// Signed message is the first two components of the token
let messageString = token.rawHeader + "." + token.rawPayload
let messageData = messageString.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
let message = CryptorRSA.createPlaintext(with: messageData)
// signature is 3rd component
// add padding, URL decode, base64 decode
guard let sigData = token.signature.base64decodedData() else {
throw AppIDError.invalidTokenSignature
}
let signature = CryptorRSA.createSigned(with: sigData)
isValid = try message.verify(with: tokenPublicKey, signature: signature, algorithm: .sha256)
if !isValid {
Log.error("invalid signature on token")
}
return isValid
}
static func isTokenValid(token: String) -> Bool {
Log.debug("isTokenValid")
if let jwt = try? parseToken(from: token) {
let jwtPayload = jwt["payload"].dictionary
guard let jwtExpirationTimestamp = jwtPayload?["exp"]?.double else {
return false
}
return Date(timeIntervalSince1970: jwtExpirationTimestamp) > Date()
} else {
return false
}
}
///
/// Decodes and Validates the provided token
///
/// - Parameter: tokenString - the jwt string to decode and validate validate
/// - Parameter: publicKeyUtil - the public key utility used to retrieve keys
/// - Parameter: options - the configuration options to use for token validation
/// - Returns: the decoded jwt payload
/// throws AppIDError on token validation failure
static func decodeAndValidate(tokenString: String,
publicKeyUtil: PublicKeyUtil,
options: AppIDPluginConfig,
completion: @escaping ([String: Any]?, AppIDError?) -> Void) {
func logAndReturn(_ error: AppIDError, completion: @escaping ([String: Any]?, AppIDError?) -> Void) {
Log.debug("Unable to validate token: " + error.description)
completion(nil, error)
}
guard let token = try? Utils.parseTokenObject(from: tokenString) else {
return logAndReturn(.invalidTokenFormat, completion: completion)
}
guard let payload = token.payloadDict else {
return logAndReturn(.invalidToken("Could not parse payload"), completion: completion)
}
guard token.alg == "RS256" else {
return logAndReturn(.invalidAlgorithm, completion: completion)
}
guard let kid = token.kid else {
return logAndReturn(.missingTokenKid, completion: completion)
}
publicKeyUtil.getPublicKey(kid: kid) { (key, error) in
if let error = error {
return logAndReturn(error, completion: completion)
}
guard let key = key else {
return logAndReturn(.missingPublicKey, completion: completion)
}
// Validate Signature
guard let isValid = try? isSignatureValid(token, with: key), isValid else {
return logAndReturn(.missingTokenKid, completion: completion)
}
guard token.isExpired == false else {
return logAndReturn(.expiredToken, completion: completion)
}
guard token.tenant == options.tenantId else {
return logAndReturn(.invalidTenant, completion: completion)
}
/// The WebAppStrategy requires full token validation
if options.shouldValidateAudAndIssuer {
guard let aud = token.aud, aud.contains(where: { $0 == options.clientId }) else {
return logAndReturn(.invalidAudience, completion: completion)
}
guard token.iss == options.tokenIssuer else {
return logAndReturn(.invalidIssuer, completion: completion)
}
}
completion(payload, nil)
}
}
static func parseJsonStringtoDictionary(_ jsonString: String) throws -> [String:Any] {
do {
guard let data = jsonString.data(using: String.Encoding.utf8),
let responseJson = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
throw AppIDError.jsonParsingError
}
return responseJson as [String:Any]
}
}
}
| apache-2.0 | 9d43d48821affd5929fb8e647997c6a0 | 36.591623 | 118 | 0.628969 | 5.117605 | false | false | false | false |
tjw/swift | test/DebugInfo/LoadableByAddress-allockstack.swift | 4 | 1022 | // Check we don't crash when verifying debug info.
// Ideally this should print the output after loadable by address runs
// but there's no way of doing this in SIL (for IRGen passes).
// RUN: %target-swift-frontend -emit-sil %s -Onone \
// RUN: -sil-verify-all -Xllvm -verify-di-holes -emit-ir \
// RUN: -Xllvm -sil-print-debuginfo -g -o - | %FileCheck %s
struct m {
let major: Int
let minor: Int
let n: Int
let o: [String]
let p: [String]
init(major: Int, minor: Int, n: Int, o: [String], p: [String]) {
self.major = major
self.minor = minor
self.n = n
self.o = o
self.p = p
}
}
enum a {
case any
case b(m)
}
struct c<e> {
enum f {
case g(a)
}
}
struct h<i>{
typealias j = i
typealias d = j
typealias f = c<d>.f
subscript(identifier: d) -> f {
return .g(.any)
}
func k(l: f, identifier: d) -> h {
switch (l, self[identifier]) {
default:
return self
}
}
}
// CHECK: define linkonce_odr hidden %swift.opaque* @"$S4main1mVwCP"
| apache-2.0 | 46567c2af2eb61892fb51dd76af0c7d8 | 19.857143 | 70 | 0.59589 | 2.945245 | false | false | false | false |
ggu/2D-RPG-Template | Borba/backend/model/PlayerModel.swift | 2 | 3697 | //
// PlayerModelExtension.swift
// Borba
//
// Created by Gabriel Uribe on 3/6/16.
// Copyright © 2016 Team Five Three. All rights reserved.
//
import SpriteKit
protocol PlayerModelDelegate {
func playerDeath()
func playerLeveledUp()
}
class PlayerModel {
private var spellManager = SpellManager.newGame()
private var stats = PlayerStats()
var activeSpell: Spell
var activeSpellOnCooldown = false
var delegate: PlayerModelDelegate?
var spellList: [String: Spell]
private init() {
(activeSpell, spellList) = spellManager.getInitialPlayerSpells()
}
class func newGame() -> PlayerModel {
return PlayerModel()
}
func getNewPlayerPosition(vX: CGFloat, vY: CGFloat, angle: CGFloat, pos: CGPoint) -> CGPoint {
var dx: CGFloat = 0
var dy: CGFloat = 0
if (vX > 0 && vY > 0) {
dx = CGFloat(stats.movementSpeed * sinf(fabs(Float(angle))));
dy = CGFloat(sqrtf(powf(stats.movementSpeed, 2) - powf(Float(dx), 2)));
} else if (vX > 0 && vY < 0) {
dy = -CGFloat(stats.movementSpeed * sinf(fabs(Float(angle) + Float(M_PI/2))));
dx = CGFloat(sqrtf(powf(stats.movementSpeed, 2) - powf(Float(dy), 2)));
} else if (vX < 0 && vY < 0) {
dy = -CGFloat(stats.movementSpeed * sinf(Float(angle) - Float(M_PI/2)));
dx = -CGFloat(sqrtf(powf(stats.movementSpeed, 2) - powf(Float(dy), 2)));
} else if (vX < 0 && vY > 0) {
dx = -CGFloat(stats.movementSpeed * sinf(Float(angle)));
dy = CGFloat(sqrtf(powf(stats.movementSpeed, 2) - powf(Float(dx), 2)));
} else if (vX < 0 && vY == 0) {
dx = -CGFloat(stats.movementSpeed)
} else if (vX > 0 && vY == 0) {
dx = CGFloat(stats.movementSpeed)
} else if (vX == 0 && vY < 0) {
dy = -CGFloat(stats.movementSpeed)
} else if (vX == 0 && vY > 0) {
dy = CGFloat(stats.movementSpeed)
}
return CGPoint(x: pos.x + dx, y: pos.y + dy);
}
func setActiveSkill(spellName: String) {
if let spell = spellList[spellName] {
activeSpell = spell
}
}
func takeDamage(damage: Double) {
stats.health -= damage
checkForDeath()
}
private func checkForDeath() {
if isDead() {
delegate?.playerDeath()
}
}
func checkIfLeveledUp() {
if didLevelUp() {
stats.levelUp()
delegate?.playerLeveledUp()
}
}
func getAttack() -> Double {
return stats.attack
}
func isDead() -> Bool {
return stats.health <= 0
}
func canUseSpell() -> Bool {
return !activeSpellOnCooldown && stats.mana > activeSpell.cost
}
// refactor this
func handleSpellCast(angle: CGFloat) -> (SKSpriteNode, SKAction) {
let spell = SpellNode(spell: activeSpell.spellName, angle: angle)
activeSpellOnCooldown = true
stats.mana -= activeSpell.cost
let action = SKAction.sequence([SKAction.waitForDuration(stats.cooldownModifier * activeSpell.cooldown), SKAction.runBlock({
self.activeSpellOnCooldown = false
})])
return (spell, action)
}
func regenHealth() {
stats.regenHealth()
}
func regenMana() {
stats.regenMana()
}
func getRemainingManaFraction() -> Double {
return stats.getRemainingManaFraction()
}
func getRemainingHealthFraction() -> Double {
return stats.getRemainingHealthFraction()
}
func getRemainingExpFraction() -> Double {
return stats.getRemainingExpFraction()
}
func getSpellDamageModifier() -> Double {
return stats.spellDamageModifier
}
func didLevelUp() -> Bool {
return stats.exp >= stats.expToLevel
}
func getLevel() -> Int {
return stats.level
}
func gainExp(exp: Double) {
stats.gainExp(exp)
}
}
| mit | 1a86d25262c8812e6df639dcf2188d9d | 24.846154 | 128 | 0.629058 | 3.54023 | false | false | false | false |
gurenupet/hah-auth-ios-swift | hah-auth-ios-swift/hah-auth-ios-swift/Constants.swift | 1 | 598 | //
// Constants.swift
// hah-auth-ios-swift
//
// Created by Anton Antonov on 06.07.17.
// Copyright © 2017 KRIT. All rights reserved.
//
import Foundation
enum Parameters: String {
case MixpanelToken = "407806200170018a45f587cac86ef5bb"
case WheatherAPIKey = "71581e5ec25e34803c8ee87ffe803867"
}
enum Fonts: String {
case Regular = "SFUIText-Regular"
case Medium = "SFUIText-Medium"
}
enum URLs {
static let base = "http://api.openweathermap.org/data/2.5"
struct Authorization {
static let weather = "/weather"
}
}
| mit | 1cf4cb50d2c7c37bbb69277c236319a9 | 18.258065 | 62 | 0.644891 | 3.28022 | false | false | false | false |
caronae/caronae-ios | Caronae/User/Login/LoginViewController.swift | 1 | 5184 | import SafariServices
import SVProgressHUD
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var welcomeLabel: UILabel!
@IBOutlet weak var loginButton: CaronaeGradientButton!
@IBOutlet weak var idTextField: UITextField!
@IBOutlet weak var tokenTextField: UITextField!
@IBOutlet weak var changeLoginMethodButton: UIButton!
var authController = AuthenticationController()
private var isAutoLoginMethod: Bool! {
didSet {
changeLoginMethod()
}
}
static func viewController() -> LoginViewController {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "InitialTokenScreen") as! LoginViewController
viewController.modalTransitionStyle = .flipHorizontal
return viewController
}
override func viewDidLoad() {
super.viewDidLoad()
isAutoLoginMethod = true
#if DEVELOPMENT
changeLoginMethodButton.isHidden = false
#endif
idTextField.delegate = self
tokenTextField.delegate = self
}
// MARK: IBActions
@IBAction func authenticate() {
if isAutoLoginMethod {
self.authController.openLogin()
} else {
view.endEditing(true)
let id = idTextField.text!
let token = tokenTextField.text!
self.authController.authenticate(withIDUFRJ: id, token: token, callback: { error in
guard error == nil else {
NSLog("There was an error authenticating the user. %@", error!.description)
var errorMessage: String!
switch error!.caronaeCode {
case .invalidCredentials:
errorMessage = "Chave não autorizada. Verifique se a mesma foi digitada corretamente e tente de novo."
case .invalidResponse:
errorMessage = "Ocorreu um erro carregando seu perfil."
default:
errorMessage = "Ocorreu um erro autenticando com o servidor do Caronaê. Por favor, tente novamente."
}
CaronaeAlertController.presentOkAlert(withTitle: "Não foi possível autenticar", message: errorMessage)
return
}
NSLog("User was authenticated. Switching main view controller...")
let rootViewController = TabBarController.instance()
UIApplication.shared.keyWindow?.replaceViewController(with: rootViewController)
})
}
}
@IBAction func didTapChangeLoginMethod() {
view.endEditing(true)
isAutoLoginMethod = !isAutoLoginMethod
}
func changeLoginMethod() {
view.isUserInteractionEnabled = false
if !isAutoLoginMethod {
idTextField.text = ""
tokenTextField.text = ""
}
let changeLoginMethodbuttonTitle = isAutoLoginMethod ? "Entrar manualmente" : "Entrar com universidade"
let loginButtonTitle = isAutoLoginMethod ? "Entrar com universidade" : "Entrar"
let loginButtonIcon = isAutoLoginMethod ? UIImage(named: "InstitutionIcon") : nil
UIView.animate(withDuration: 0.25, animations: {
if self.isAutoLoginMethod {
self.idTextField.alpha = 0.0
self.tokenTextField.alpha = 0.0
} else {
self.idTextField.isHidden = false
self.tokenTextField.isHidden = false
}
}, completion: { _ in
UIView.animate(withDuration: 0.25, animations: {
if self.isAutoLoginMethod {
self.idTextField.isHidden = true
self.tokenTextField.isHidden = true
} else {
self.idTextField.alpha = 1.0
self.tokenTextField.alpha = 1.0
}
}, completion: { _ in
self.view.isUserInteractionEnabled = true
})
UIView.performWithoutAnimation {
self.changeLoginMethodButton.setTitle(changeLoginMethodbuttonTitle, for: .normal)
self.changeLoginMethodButton.layoutIfNeeded()
self.loginButton.setTitle(loginButtonTitle, for: .normal)
self.loginButton.setImage(loginButtonIcon, for: .normal)
self.loginButton.layoutIfNeeded()
}
})
}
}
// MARK: UITextFieldDelegate Methods
extension LoginViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
switch textField {
case tokenTextField:
authenticate()
return false
case idTextField:
if idTextField.hasText {
tokenTextField.becomeFirstResponder()
}
default:
break
}
return true
}
}
| gpl-3.0 | 0937072004cbe28238b38f4c0f09b91a | 35.223776 | 127 | 0.580502 | 5.498938 | false | false | false | false |
NobodyNada/SwiftChatSE | Sources/SwiftChatSE/Row.swift | 1 | 3191 | //
// Row.swift
// SwiftChatSE
//
// Created by NobodyNada on 5/8/17.
//
//
import Foundation
#if os(Linux)
import CSQLite
#else
import SQLite3
#endif
open class Row {
///The columns of this row.
public let columns: [DatabaseNativeType?]
///A Dictionary mapping the names of this row's columns to their indices in `columns`.
public let columnNames: [String:Int]
///Initializes a Row with the results of a prepared statement.
public init(statement: OpaquePointer) {
var columns = [DatabaseNativeType?]()
var columnNames = [String:Int]()
for i in 0..<sqlite3_column_count(statement) {
let value: DatabaseNativeType?
let type = sqlite3_column_type(statement, i)
switch type {
case SQLITE_INTEGER:
value = sqlite3_column_int64(statement, i)
case SQLITE_FLOAT:
value = sqlite3_column_double(statement, i)
case SQLITE_TEXT:
value = String(cString: sqlite3_column_text(statement, i))
case SQLITE_BLOB:
let bytes = sqlite3_column_bytes(statement, i)
if bytes == 0 {
value = Data()
} else {
value = Data(bytes: sqlite3_column_blob(statement, i), count: Int(bytes))
}
case SQLITE_NULL:
value = nil
default:
fatalError("unrecognized SQLite type \(type)")
}
columns.append(value)
columnNames[String(cString: sqlite3_column_name(statement, i))] = Int(i)
}
self.columns = columns
self.columnNames = columnNames
}
///Initializes a Row with the specified columns.
public init(columns: [DatabaseNativeType?], columnNames: [String:Int]) {
self.columns = columns
self.columnNames = columnNames
}
//MARK: - Convenience functions for accessing columns
///Returns the contents of the column at the specified index.
///
///- parameter index: The index of the column to return.
///- parameter type: The type of the column to return. Will be inferred by the compiler
/// if not specified. Must conform to `DatabaseType`.
///
///- returns: The contents of the column, or `nil` if the contents are `NULL`.
///
///- warning: Will crash if the index is out of range or the column has an incompatible type.
open func column<T: DatabaseType>(at index: Int, type: T.Type = T.self) -> T? {
guard let value = columns[index] else { return nil }
guard let converted = T.from(native: value) else {
fatalError("column \(index) has an incompatible type ('\(Swift.type(of: value))' could not be converted to '\(type)')")
}
return converted
}
///Returns the contents of the column with the specified name.
///
///- parameter name: The name of the column to return.
///- parameter type: The type of the column to return. Will be inferred by the compiler
/// if not specified. Must conform to `DatabaseType`.
///
///- returns: The contents of the column.
///
///- warning: Will crash if the name does not exist or the column has an incompatible type.
open func column<T: DatabaseType>(named name: String, type: T.Type = T.self) -> T? {
guard let index = columnNames[name] else {
fatalError("column '\(name)' not found in \(Array(columnNames.keys))")
}
return column(at: index)
}
}
| mit | 11542f1d27176b1b96beea71da1f70c2 | 30.284314 | 122 | 0.669696 | 3.630262 | false | false | false | false |
lancy98/HamburgerMenu | HamburgerMenu/HamburgerMenu/SlideMenuViewController.swift | 1 | 10103 | //
// SlideMenuViewController.swift
// DynamicTrayDemo
//
// Created by Lancy on 27/05/15.
// Copyright (c) 2015 Lancy. All rights reserved.
//
import UIKit
protocol DynamicTrayMenuDataSource : class {
func trayViewController() -> UIViewController
func mainViewController() -> UIViewController
}
class SlideMenuViewController: UIViewController {
weak var dataSource: DynamicTrayMenuDataSource? {
didSet {
if let inDataSource = dataSource {
let mainVC = inDataSource.mainViewController()
mainViewController = mainVC
addViewController(mainVC, toView: view)
view.sendSubviewToBack(mainVC.view)
if let tView = trayView {
let trayVC = inDataSource.trayViewController()
trayViewController = trayVC
addViewController(trayVC, toView: trayView!)
}
}
}
}
private var trayViewController: UIViewController?
private var mainViewController: UIViewController?
private var trayView: UIVisualEffectView?
private var trayLeftEdgeConstraint: NSLayoutConstraint?
private var animator: UIDynamicAnimator?
private var gravity: UIGravityBehavior?
private var attachment: UIAttachmentBehavior?
private let widthFactor = CGFloat(0.4) // 40% width of the view
private let minThresholdFactor = CGFloat(0.2)
private var overlayView: UIView?
private var trayWidth: CGFloat {
return CGFloat(view.frame.width * widthFactor);
}
private var isGravityRight = false
// check if the hamburger menu is being showed
var isShowingTray: Bool {
return isGravityRight
}
func showTray() {
tray(true)
}
func hideTray() {
tray(false)
}
func updateMainViewController(viewController: UIViewController) {
if let mainVC = mainViewController {
mainVC.willMoveToParentViewController(nil)
mainVC.view.removeFromSuperview()
mainVC.removeFromParentViewController()
}
addViewController(viewController, toView: view)
}
private func tray(show: Bool) {
let pushBehavior = UIPushBehavior(items: [trayView!], mode: .Instantaneous)
pushBehavior.angle = show ? CGFloat(M_PI) : 0
pushBehavior.magnitude = UI_USER_INTERFACE_IDIOM() == .Pad ? 1500 : 200
isGravityRight = show
upadateGravity(isGravityRight)
animator!.addBehavior(pushBehavior);
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
setUpTrayView()
setUpGestureRecognizers()
animator = UIDynamicAnimator(referenceView: view)
setUpBehaviors()
if trayViewController == nil && dataSource != nil {
let trayVC = dataSource!.trayViewController()
trayViewController = trayVC
addViewController(trayVC, toView: trayView!)
}
}
private func addViewController(viewController: UIViewController, toView: UIView) {
addChildViewController(viewController)
viewController.view.setTranslatesAutoresizingMaskIntoConstraints(false)
toView.addSubview(viewController.view)
viewController.didMoveToParentViewController(self)
toView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options:
NSLayoutFormatOptions(0), metrics: nil, views: ["view": viewController.view]))
toView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options:
NSLayoutFormatOptions(0), metrics: nil, views: ["view": viewController.view]))
}
private func setUpBehaviors() {
// Collision behaviour
let collisionBehavior = UICollisionBehavior(items: [trayView!])
let rightInset = view.frame.width - trayWidth
let edgeInset = UIEdgeInsetsMake(0, -trayWidth, 0, rightInset)
collisionBehavior.setTranslatesReferenceBoundsIntoBoundaryWithInsets(edgeInset)
animator!.addBehavior(collisionBehavior)
// Gravity behaviour
gravity = UIGravityBehavior(items: [trayView!])
animator!.addBehavior(gravity)
upadateGravity(isGravityRight)
}
private func upadateGravity(isRight: Bool) {
let angle = isRight ? 0 : M_PI
gravity!.setAngle(CGFloat(angle), magnitude: 1.0)
// Add the overlay if gravity is right
if isRight {
addOverlayView()
} else {
removeOverlayView()
}
}
private func addOverlayView() {
if overlayView == nil {
// Create overlay view.
overlayView = UIView.new()
overlayView!.backgroundColor = UIColor.blackColor()
overlayView!.alpha = 0.0
overlayView!.setTranslatesAutoresizingMaskIntoConstraints(false)
mainViewController!.view.addSubview(overlayView!)
// Fill the parent.
mainViewController!.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options:
NSLayoutFormatOptions(0), metrics: nil, views: ["view": overlayView!]))
mainViewController!.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options:
NSLayoutFormatOptions(0), metrics: nil, views: ["view": overlayView!]))
// Add Tap Gesture
let tapGesture = UITapGestureRecognizer(target: self, action: Selector("overlayTapped:"))
overlayView!.addGestureRecognizer(tapGesture)
// animate with alpha
UIView.animateWithDuration(0.4) {
self.overlayView!.alpha = 0.4
}
}
}
private func removeOverlayView() {
if overlayView != nil {
UIView.animateWithDuration(0.4, animations: {
self.overlayView!.alpha = 0.0
}, completion: { completed in
self.overlayView!.removeFromSuperview()
self.overlayView = nil
})
}
}
func overlayTapped(tapGesture: UITapGestureRecognizer) {
tray(false) // hide the tray.
}
private func setUpTrayView() {
// Adding blur view
let blurEffect = UIBlurEffect(style: .ExtraLight)
trayView = UIVisualEffectView(effect: blurEffect)
trayView!.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(trayView!)
// Add constraints to blur view
view.addConstraint(NSLayoutConstraint(item: trayView!, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 0.4, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: trayView!, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: trayView!, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1.0, constant: 0.0))
trayLeftEdgeConstraint = NSLayoutConstraint(item: trayView!, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1.0, constant:-trayWidth)
view.addConstraint(trayLeftEdgeConstraint!)
view.layoutIfNeeded()
}
override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
private func setUpGestureRecognizers() {
// Edge pan.
let edgePan = UIScreenEdgePanGestureRecognizer(target: self, action: Selector("pan:"))
edgePan.edges = .Left
view.addGestureRecognizer(edgePan)
// Pan.
let pan = UIPanGestureRecognizer (target: self, action: Selector("pan:"))
trayView!.addGestureRecognizer(pan)
}
func pan(gesture: UIPanGestureRecognizer) {
let currentPoint = gesture.locationInView(view)
let xOnlyPoint = CGPointMake(currentPoint.x, view.center.y)
switch(gesture.state) {
case .Began:
attachment = UIAttachmentBehavior(item: trayView!, attachedToAnchor: xOnlyPoint)
animator!.addBehavior(attachment)
case .Changed:
attachment!.anchorPoint = xOnlyPoint
case .Cancelled, .Ended:
animator!.removeBehavior(attachment)
attachment = nil
let velocity = gesture.velocityInView(view)
let velocityThreshold = CGFloat(500)
if abs(velocity.x) > velocityThreshold {
isGravityRight = velocity.x > 0
upadateGravity(isGravityRight)
} else {
isGravityRight = (trayView!.frame.origin.x + trayView!.frame.width) > (view.frame.width * minThresholdFactor)
upadateGravity(isGravityRight)
}
default:
if attachment != nil {
animator!.removeBehavior(attachment)
attachment = nil
}
}
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
animator!.removeAllBehaviors()
if (trayView!.frame.origin.x + trayView!.frame.width) > (view.center.x * minThresholdFactor) {
trayLeftEdgeConstraint?.constant = 0
isGravityRight = true
} else {
trayLeftEdgeConstraint?.constant = -(size.width * widthFactor)
isGravityRight = false
}
coordinator.animateAlongsideTransition({ context in
self.view.layoutIfNeeded()
}, completion: { context in
self.setUpBehaviors()
})
}
} | mit | a792d8f919bec31174c01d99b257ab06 | 35.476534 | 175 | 0.619915 | 5.51775 | false | false | false | false |
davidkobilnyk/BNRGuideSolutionsInSwift | 06-ViewControllers/HypnoNerd/HypnoNerd/BNRHypnosisViewController.swift | 1 | 1326 | //
// BNRHypnosisViewController.swift
// HypnoNerd
//
// Created by David Kobilnyk on 7/7/14.
// Copyright (c) 2014 David Kobilnyk. All rights reserved.
//
import UIKit
class BNRHypnosisViewController: UIViewController {
override init() {
super.init(nibName: "BNRHypnosisViewController", bundle: nil)
// Set the tab bar item's title
self.tabBarItem.title = "Hypnotize"
// Create a UIImage from a file
// This will use Hypno@2x on retina display devices
let image = UIImage(named: "Hypno.png")
// "'imageNamed is unavailable: use object construction 'UIImage(named:)'"
// Put that image on the tab bar item
self.tabBarItem.image = image
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func loadView() {
// Create a view
let frame = UIScreen.mainScreen().bounds
let backgroundView = BNRHypnosisView(frame: frame)
// Set it as *the* view of this view controller
self.view = backgroundView
}
override func viewDidLoad() {
// Always call the super implementation of viewDidLoad
super.viewDidLoad()
println("BNRHypnosisViewController loaded its view")
}
} | mit | 7357cddd32e606414d2b0ecdc3b9a249 | 27.847826 | 82 | 0.61991 | 4.405316 | false | false | false | false |
mortenbekditlevsen/Future | Future/Future.swift | 2 | 7561 | //
// Future.swift
// Future
//
// Created by Le Van Nghia on 5/31/15.
// Copyright (c) 2015 Le Van Nghia. All rights reserved.
//
import Foundation
import Result
public class Future<T, Error: ErrorType> {
public typealias ResultType = Result<T, Error>
// MARK: Properties
internal var result: Optional<ResultType>
private let operation: (ResultType -> Void) -> Void
public var value: Optional<T> {
return result?.value
}
public var error: Optional<Error> {
return result?.error
}
public var isCompleted: Bool {
return result != nil
}
public var isSuccess: Bool {
return result?.value != nil
}
public var isFailure: Bool {
return result?.error != nil
}
// MAKR: Initilizers
// Init a future with the given asynchronous operation.
public init(operation: (ResultType -> Void) -> Void) {
self.operation = operation
}
// Init a future with the given result (Result<T, Errror>).
public convenience init(result: ResultType) {
self.init(operation: { completion in
completion(result)
})
}
// Init a future that succeeded with the given `value`.
public convenience init(value: T) {
self.init(result: Result(value: value))
}
// Init a future that failed with the given `error`.
public convenience init(error: Error) {
self.init(result: Result(error: error))
}
// MARK - Completing
// Completes the future with the given `completion` closure.
// If the future is already completed, this will be applied immediately.
public func onComplete(completion: ResultType -> Void) {
if result != nil {
completion(result!)
return
}
self.operation { [weak self] result in
self?.result = result
completion(result)
}
}
// Completes the future with `Success` completion.
// If the future is already completed, this will be applied immediately.
// And the `completion` closure is only executed if the future success.
public func onSuccess(completion: T -> Void) {
onComplete { result in
switch result {
case .Success(let bv): completion(bv)
default: break
}
}
}
// Compeltes the future with `Failure` completion.
// If the future is already completed, this will be applied immediately.
// And the `completion` colosure is only executed if the future fails.
public func onFailure(completion: Error -> Void) {
onComplete { result in
switch result {
case .Failure(let be): completion(be)
default: break
}
}
}
}
// MARK: Funtional composition
extension Future {
// map | you can also use `<^>` operator
// Creates a new future by applying a function to the successful result of this future.
// If this future is completed with an error then the new future will also contain this error.
public func map<U>(f: T -> U) -> Future<U, Error> {
return Future<U, Error>(operation: { completion in
self.onComplete { result in
switch result {
case .Success(let bv): completion(Result(value: f(bv)))
case .Failure(let be): completion(Result(error: be))
}
}
})
}
// flatMap | | you can also use `>>-` operator
// Creates a new future by applying a function to the successful result of this future,
// and returns the result of the function as the new future.
// If this future is completed with an error then the new future will also contain this error.
public func flatMap<U>(f: T -> Future<U, Error>) -> Future<U, Error> {
return flatten(map(f))
}
// filter
// Creates a new future by filtering the value of the current future with a predicate.
// If the current future contains a value which satisfies the predicate, the new future will also hold that value.
// Otherwise, the resulting future will fail with `noSuchElementError`.
public func filter(noSuchElementError: Error, p: T -> Bool) -> Future<T, Error> {
return Future<T, Error>(operation: { completion in
self.onComplete { result in
switch result {
case .Success(let bv):
let r = p(bv) ? Result(value: bv) : Result(error: noSuchElementError)
completion(r)
case .Failure: completion(result)
}
}
})
}
// zip
// Creates a new future that holds the tupple of results of `this` and `that`.
public func zip<U>(that: Future<U, Error>) -> Future<(T,U), Error> {
return self.flatMap { thisVal -> Future<(T,U), Error> in
return that.map { thatVal in
return (thisVal, thatVal)
}
}
}
// recover
// Returns a future that succeeded if this is a success.
// Returns a future that succeeded by applying function `f` to `error` value if this is a failure.
public func recover(f: Error -> T) -> Future<T, Error> {
return Future<T, Error>(operation: { completion in
self.onComplete { result in
switch result {
case .Success: completion(result)
case .Failure(let be): completion(Result(value: f(be)))
}
}
})
}
// andThen
// Applies the side-effect function to the result of this future.
// and returns a new future with the result of this future.
public func andThen(result: Result<T, Error> -> Void) -> Future<T, Error> {
return Future<T, Error>(operation: { completion in
self.onComplete { r in
result(r)
completion(r)
}
})
}
}
// MARK: Funtions
// flatten
public func flatten<T, Error>(future: Future<Future<T, Error>, Error>) -> Future<T, Error> {
return Future<T, Error>(operation: { completion in
future.onComplete { result in
switch result {
case .Success(let bf): bf.onComplete(completion)
case .Failure(let be): completion(Result(error: be))
}
}
})
}
// MARK: Printable
extension Future: CustomStringConvertible {
public var description: String {
return "result: \(result)\n"
+ "isCompleted: \(isCompleted)\n"
+ "isSuccess: \(isSuccess)\n"
+ "isFailure: \(isFailure)\n"
}
}
// MARK: DebugPrintable
extension Future: CustomDebugStringConvertible {
public var debugDescription: String {
return description
}
}
// MARK: Operators
infix operator <^> {
// Left associativity
associativity left
// precedence
precedence 150
}
/*
// Avoid conflict with the operator of Result
infix operator >>- {
// Left associativity
associativity left
// Using the same `precedence` value in antitypical/Result
precedence 100
}
*/
// Operator for `map`
public func <^> <T, U, Error> (future: Future<T, Error>, transform: T -> U) -> Future<U, Error> {
return future.map(transform)
}
// Operator for `flatMap`
public func >>- <T, U, Error> (future: Future<T, Error>, transform: T -> Future<U, Error>) -> Future<U, Error> {
return future.flatMap(transform)
}
| mit | c003a1c1cfce416059e456add4015f5f | 29.487903 | 118 | 0.588679 | 4.439812 | false | false | false | false |
FotiosTragopoulos/Core-Geometry | Core Geometry/Par1ViewLine.swift | 1 | 1694 | //
// Par1ViewLine.swift
// Core Geometry
//
// Created by Fotios Tragopoulos on 13/01/2017.
// Copyright © 2017 Fotios Tragopoulos. All rights reserved.
//
import UIKit
class Par1ViewLine: UIView {
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
let myShadowOffset = CGSize (width: 10, height: 10)
context?.setShadow (offset: myShadowOffset, blur: 8)
context?.saveGState()
context?.setLineWidth(3.0)
context?.setStrokeColor(UIColor.red.cgColor)
let xView = viewWithTag(2)?.alignmentRect(forFrame: rect).midX
let yView = viewWithTag(2)?.alignmentRect(forFrame: rect).midY
let width = self.viewWithTag(2)?.frame.size.width
let height = self.viewWithTag(2)?.frame.size.height
let size = CGSize(width: width! * 0.8, height: height! * 0.4)
let linePlacementX = CGFloat(size.width/2)
let linePlacementY = CGFloat(size.height/2)
context?.move(to: CGPoint(x: (xView! - linePlacementX), y: (yView! - linePlacementY)))
context?.addLine(to: CGPoint(x: (xView! + linePlacementX), y: (yView! + linePlacementY)))
let dashArray:[CGFloat] = [10, 4]
context?.setLineDash(phase: 3, lengths: dashArray)
context?.strokePath()
context?.restoreGState()
self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.15, initialSpringVelocity: 6.0, options: .allowUserInteraction, animations: { self.transform = CGAffineTransform.identity } ,completion: nil)
}
}
| apache-2.0 | a6b6a693985dd96db6beb110b2026681 | 37.477273 | 219 | 0.637921 | 3.955607 | false | false | false | false |
ashikahmad/SugarAnchor | Example/SugarAnchor/Example2VC.swift | 1 | 3627 | //
// Example2VC.swift
// SugarAnchor
//
// Created by Ashik uddin Ahmad on 5/13/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import SugarAnchor
/*
Portrait Mode Layout Lanscape Mode Layout
--------------------- --------------------------
+-----------------+ +---------------------------+
| +-----+ +-----+ | | +-----+ +--------------+ |
| | RED | |GREEN| | | | RED | | | |
| | | | | | | | | | | |
| +-----+ +-----+ | | +-----+ | BLUE | |
| +-------------+ | | +-----+ | | |
| | | | | |GREEN| | | |
| | | | | | | | | |
| | BLUE | | | +-----+ +--------------+ |
| | | | +---------------------------+
| | | |
| +-------------+ |
+-----------------+
*/
class Example2VC: UIViewController {
// Portrait-only constraints
private var poConstraints: [NSLayoutConstraint] = []
// Lanscape-only constraints
private var loConstraints: [NSLayoutConstraint] = []
override func viewDidLoad() {
super.viewDidLoad()
let redView = addedView(.red)
let greenView = addedView(.green)
let blueView = addedView(.blue)
let margins = view.layoutMarginsGuide
// Common
redView.leadingAnchor =*= margins.leadingAnchor
redView.topAnchor =*= topLayoutGuide.bottomAnchor + 8
redView.widthAnchor =*= redView.heightAnchor
greenView.widthAnchor =*= redView.widthAnchor
greenView.widthAnchor =*= greenView.heightAnchor
blueView.trailingAnchor =*= margins.trailingAnchor
blueView.bottomAnchor =*= bottomLayoutGuide.topAnchor - 8
// Portrait only
let pc1 = greenView.leadingAnchor =~= redView.trailingAnchor + 8
let pc2 = greenView.topAnchor =~= redView.topAnchor
let pc3 = greenView.trailingAnchor =~= margins.trailingAnchor
let pc4 = blueView.topAnchor =~= redView.bottomAnchor + 8
let pc5 = blueView.leadingAnchor =~= margins.leadingAnchor
poConstraints.append(contentsOf: [pc1, pc2, pc3, pc4, pc5])
// Landscape only
let lc1 = blueView.leadingAnchor =~= redView.trailingAnchor + 8
let lc2 = blueView.topAnchor =~= redView.topAnchor
let lc3 = greenView.topAnchor =~= redView.bottomAnchor + 8
let lc4 = greenView.leadingAnchor =~= margins.leadingAnchor
let lc5 = greenView.bottomAnchor =~= blueView.bottomAnchor
loConstraints.append(contentsOf: [lc1, lc2, lc3, lc4, lc5])
// To force current mode first time
traitCollectionDidChange(traitCollection)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
// FIXME: iPad landscape is not covered!
if traitCollection.verticalSizeClass == .regular {
// Portrait
loConstraints.forEach { $0.isActive = false }
poConstraints.forEach { $0.isActive = true }
} else {
// Landscape
poConstraints.forEach { $0.isActive = false }
loConstraints.forEach { $0.isActive = true }
}
}
func addedView(_ color: UIColor)-> UIView {
let newView = UIView()
newView.translatesAutoresizingMaskIntoConstraints = false
newView.backgroundColor = color
view.addSubview(newView)
return newView
}
}
| mit | fe6832ed620cf98d6d86fffb768be2ea | 34.203883 | 91 | 0.518478 | 4.946794 | false | false | false | false |
hunj/hCrypto | hCrypto/hCryptor.swift | 1 | 2962 | //
// hCryptor.swift
// hCrypto
//
// Created by Hun Jae Lee on 6/7/16.
// Copyright © 2016 Hun Jae Lee. All rights reserved.
//
import Foundation
class hCryptor {
var key = ""
var message = ""
init() {
key = generateKey()
}
init(key: String) {
self.key = key
}
init(message: String) {
key = generateKey()
self.message = message
}
// MARK: Public functions
/**
Encrypts the given text.
- Parameter text: the `String` to encrypt
- Returns: `(Ciphertext, Key)` tuple where `Ciphertext` is the encrypted text, and `Key` is the key to be used to decrypt later.
*/
func encrypt(text: String) -> (String, String) {
var encrypted = String()
let longKey = matchLengthOfKeyToText(text, key: self.key)
let keyAscii = asciiValueArrayOf(longKey)
let textAscii = asciiValueArrayOf(text)
for i in 0 ..< textAscii.count {
encrypted += String( UnicodeScalar(Int(textAscii[i]) + Int(keyAscii[i])) )
}
return (encrypted, self.key)
}
/**
Decrypts the given text with given key.
- Parameters:
- ciphertext: the text to decrypt
- key: the key to this decyphering
- Returns: the deciphered message.
*/
func decrypt(ciphertext: String, key: String) -> String {
var result = ""
let asciiText = asciiValueArrayOf(ciphertext)
let longKey = matchLengthOfKeyToText(ciphertext, key: key)
let keyAscii = asciiValueArrayOf(longKey)
for i in 0 ..< asciiText.count {
result += String( UnicodeScalar(Int(asciiText[i]) - Int(keyAscii[i])) )
}
return result
}
// MARK: Private functions
/**
returns a randomly generated key of 32 characters (String).
Resource: http://github.com/Flinesoft/HandySwift
*/
private func generateKey() -> String {
let allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let allowedCharsCount = UInt32(allowedChars.characters.count)
var randomString = ""
for _ in (0..<32) {
let randomNum = Int(arc4random_uniform(allowedCharsCount))
let newCharacter = allowedChars[allowedChars.startIndex.advancedBy(randomNum)]
randomString += String(newCharacter)
}
return randomString
}
/**
Returns an array of ascii values of each characters in the given String.
- Parameter text: the String to convert into ascii value array
- Returns: the array of ascii values of each characters in the given String.
*/
private func asciiValueArrayOf(text: String) -> [UInt32] {
var asciiText = [UInt32]()
for i in 0 ..< text.characters.count {
asciiText.append(text.asciiValueAt(pos: i))
}
return asciiText
}
/**
matches the length of given `key` to the length of `text` by reiterating.
- Parameters:
- text: the text to compare
- key: the key to resize up
- Returns: the resized `key`
*/
private func matchLengthOfKeyToText(text: String, key: String) -> String {
var encryptKey = key
while encryptKey.characters.count < text.characters.count {
encryptKey += key
}
return encryptKey
}
} | mit | dfe2be6a1c0f96bcc27a732d57170d1f | 24.534483 | 129 | 0.695035 | 3.391753 | false | false | false | false |
Daniel-Lopez/EZSwiftExtensions | EZSwiftExtensionsTests/EZSwiftExtensionsTestsDictionary.swift | 1 | 2900 | //
// EZSwiftExtensionsTestsDictionary.swift
// EZSwiftExtensions
//
// Created by Valentino Urbano on 28/01/16.
// Copyright © 2016 Goktug Yilmaz. All rights reserved.
//
import XCTest
import EZSwiftExtensions
class EZSwiftExtensionsTestsDictionary: XCTestCase {
var firstdic: [String:Int]!
var secondDic: [String:Int]!
var thirdDic: [String:Int]!
var fourthDic: [String:Int]!
override func setUp() {
super.setUp()
firstdic = ["one" : 1, "two" : 2, "three" : 3]
secondDic = ["four" : 4, "five" : 5]
thirdDic = ["six" : 6, "seven" : 7]
fourthDic = ["two" : 2, "three" : 3, "five" : 5, "six" : 6]
}
func testUnion() {
let union = firstdic.union(secondDic)
XCTAssertEqual(firstdic.keys.count + secondDic.keys.count, union.keys.count)
XCTAssertEqual(firstdic.values.count + secondDic.values.count, union.values.count)
let multiUnion = firstdic | secondDic | thirdDic
XCTAssertEqual(firstdic.keys.count + secondDic.keys.count + thirdDic.keys.count, multiUnion.keys.count)
XCTAssertEqual(firstdic.values.count + secondDic.values.count + thirdDic.values.count, multiUnion.values.count)
}
func testIntersection() {
let union = firstdic | secondDic
let intersection = union & fourthDic
XCTAssertTrue(intersection.has("two"))
XCTAssertTrue(intersection.has("three"))
XCTAssertTrue(intersection.has("five"))
XCTAssertEqual(intersection.count, 3)
}
func testDifference() {
let union = firstdic | secondDic
let difference = union - fourthDic
XCTAssertTrue(difference.has("one"))
XCTAssertTrue(difference.has("four"))
XCTAssertEqual(difference.count, 2)
}
func testTestAll() {
let allKeysHaveMoreThan3Chars = firstdic.testAll { key, _ in key.length >= 3 }
XCTAssertTrue(allKeysHaveMoreThan3Chars)
}
func testToArray() {
let array = fourthDic.toArray { key, value in
return key.uppercaseString + String(value)
}
XCTAssertNotNil(array.indexOf("TWO2"))
XCTAssertNotNil(array.indexOf("FIVE5"))
XCTAssertEqual(array.count, fourthDic.count)
}
func testMapFilterValues() {
let thirdMappedDic = thirdDic.mapFilterValues { (key, value) -> String? in
if value == 6 {
return nil
} else {
return "\(key) * 2 = \(value * 2)"
}
}
XCTAssertEqual(thirdMappedDic.count, 1)
XCTAssertTrue(thirdMappedDic.has("seven"))
XCTAssertEqual(thirdMappedDic["seven"], "seven * 2 = 14")
}
func testFilter() {
let secondFiltered = secondDic.filter { key, value in key != "five" }
XCTAssertTrue(secondFiltered.has("four"))
XCTAssertEqual(secondFiltered.count, 1)
}
}
| mit | 37d3e5d0934430d83901b824edd38159 | 30.857143 | 119 | 0.624698 | 4.094633 | false | true | false | false |
KBryan/SwiftFoundation | Source/POSIXRegularExpression.swift | 1 | 8116 | //
// POSIXRegularExpression.swift
// SwiftFoundation
//
// Created by Alsey Coleman Miller on 7/22/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
// MARK: - POSIX Regular Expression Functions
public func POSIXRegexCompile(pattern: String, options: [RegularExpressionCompileOption]) throws -> UnsafeMutablePointer<regex_t> {
let regexPointer = UnsafeMutablePointer<regex_t>.alloc(1)
defer { regexPointer.dealloc(1) }
let flags = RegularExpressionCompileOption.optionsBitmask(options)
let errorCode = regcomp(regexPointer, pattern, flags)
guard errorCode == 0 else {
throw RegularExpressionCompileError(rawValue: errorCode)!
}
return regexPointer
}
public func POSIXRegexMatch(regex: UnsafeMutablePointer<regex_t>, string: String, options: [RegularExpressionMatchOption]) -> Range<UInt>? {
//let flags = RegularExpressionMatchOption.flagValue(options)
// regexec(regex, string, 100, <#T##__pmatch: UnsafeMutablePointer<regmatch_t>##UnsafeMutablePointer<regmatch_t>#>, flags)
return nil;
}
// MARK: - Supporting Types
// MARK: Options
public typealias POSIXRegularExpressionCompileOptionFlag = Int32
/// POSIX Regular Expression Compilation Options
public enum RegularExpressionCompileOption: POSIXRegularExpressionCompileOptionFlag, BitMaskOption {
/** Do not differentiate case. */
case CaseInsensitive
/** Use POSIX Extended Regular Expression syntax when interpreting regular expression. If not set, POSIX Basic Regular Expression syntax is used. */
case ExtendedSyntax
/** Report only success/fail. */
case NoSub
/// Treat a newline in string as dividing string into multiple lines, so that ```$``` can match before the newline and ```^``` can match after. Also, don’t permit ```.``` to match a newline, and don’t permit ```[^…]``` to match a newline.
///
/// Otherwise, newline acts like any other ordinary character.
case NewLine
public init?(rawValue: POSIXRegularExpressionCompileOptionFlag) {
switch rawValue {
case REG_ICASE: self = CaseInsensitive
case REG_EXTENDED: self = ExtendedSyntax
case REG_NOSUB: self = NoSub
case REG_NEWLINE: self = NewLine
default: return nil
}
}
public var rawValue: POSIXRegularExpressionCompileOptionFlag {
switch self {
case .CaseInsensitive: return REG_ICASE
case .ExtendedSyntax: return REG_EXTENDED
case .NoSub: return REG_NOSUB
case .NewLine: return REG_NEWLINE
}
}
}
public typealias POSIXRegularExpressionMatchOptionFlag = Int32
/// POSIX Regular Expression Matching Options */
public enum RegularExpressionMatchOption: POSIXRegularExpressionMatchOptionFlag, BitMaskOption {
/** Do not regard the beginning of the specified string as the beginning of a line; more generally, don’t make any assumptions about what text might precede it. */
case NotBeginningOfLine
/** Do not regard the end of the specified string as the end of a line; more generally, don’t make any assumptions about what text might follow it. */
case NotEndOfLine
public init?(rawValue: POSIXRegularExpressionMatchOptionFlag) {
switch rawValue {
case REG_NOTBOL: self = NotBeginningOfLine
case REG_NOTEOL: self = NotEndOfLine
default: return nil
}
}
public var rawValue: POSIXRegularExpressionMatchOptionFlag {
switch self {
case .NotBeginningOfLine: return REG_NOTBOL
case .NotEndOfLine: return REG_NOTEOL
}
}
}
// MARK: Errors
public typealias POSIXRegularExpressionCompileErrorRawValue = Int32
public enum RegularExpressionCompileError: POSIXRegularExpressionCompileErrorRawValue, ErrorType {
/// Invalid use of repetition operators such as using '*' as the first character.
///
/// For example, the consecutive repetition operators ```**``` in ```a**``` are invalid. As another example, if the syntax is extended regular expression syntax, then the repetition operator ```*``` with nothing on which to operate in ```*``` is invalid.
case InvalidRepetition
/// Invalid use of back reference operator.
///
/// For example, the count '```-1```' in '```a\{-1```' is invalid.
case InvalidBackReference
/// The regex routines ran out of memory.
case OutOfMemory
/// Invalid use of pattern operators such as group or list.
case InvalidPatternOperator
/// Un-matched brace interval operators.
case UnMatchedBraceInterval
/// Un-matched bracket list operators.
case UnMatchedBracketList
/// Invalid collating element.
case InvalidCollating
/// Unknown character class name.
case UnknownCharacterClassName
/// Trailing backslash.
case TrailingBackslash
/// Un-matched parenthesis group operators.
case UnMatchedParenthesis
/// Invalid use of the range operator.
///
/// E.g. The ending point of the range occurs prior to the starting point.
case InvalidRange
/// Invalid back reference to a subexpression.
case InvalidBackReferenceToSubExpression
/* Linux
/// Non specific error. This is not defined by POSIX.2.
case GenericError
/// Compiled regular expression requires a pattern buffer larger than 64Kb. This is not defined by POSIX.2.
case GreaterThan64KB
*/
public init?(rawValue: POSIXRegularExpressionCompileErrorRawValue) {
switch rawValue {
case REG_BADRPT: self = InvalidRepetition
case REG_BADBR: self = InvalidBackReference
case REG_ESPACE: self = OutOfMemory
case REG_BADPAT: self = InvalidPatternOperator
case REG_EBRACE: self = UnMatchedBraceInterval
case REG_EBRACK: self = UnMatchedBracketList
case REG_ECOLLATE: self = InvalidCollating
case REG_ECTYPE: self = UnknownCharacterClassName
case REG_EESCAPE: self = TrailingBackslash
case REG_EPAREN: self = UnMatchedParenthesis
case REG_ERANGE: self = InvalidRange
case REG_ESUBREG: self = InvalidBackReferenceToSubExpression
/*
#if os(linux)
case REG_EEND: self = .GenericError // Linux
case REG_ESIZE: self = .GreaterThan64KB // Linux
#endif
*/
default: return nil
}
}
public var rawValue: POSIXRegularExpressionCompileErrorRawValue {
switch self {
case InvalidRepetition: return REG_BADRPT
case InvalidBackReference: return REG_BADBR
case OutOfMemory: return REG_ESPACE
case InvalidPatternOperator: return REG_BADPAT
case UnMatchedBraceInterval: return REG_EBRACE
case UnMatchedBracketList: return REG_EBRACK
case InvalidCollating: return REG_ECOLLATE
case UnknownCharacterClassName: return REG_ECTYPE
case TrailingBackslash: return REG_EESCAPE
case UnMatchedParenthesis: return REG_EPAREN
case InvalidRange: return REG_ERANGE
case InvalidBackReferenceToSubExpression: return REG_ESUBREG
}
}
}
| mit | 05ecfb8cb3c2abe9f23bcbaa3ea64d6f | 35.674208 | 258 | 0.613819 | 5.208869 | false | false | false | false |
EvsenevDev/SmartReceiptsiOS | SmartReceipts/Modules/Generate Report/GenerateReportDisplayData.swift | 2 | 569 | //
// GenerateReportDisplayData.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 07/06/2017.
// Copyright © 2017 Will Baumann. All rights reserved.
//
import Foundation
import Viperit
final class GenerateReportDisplayData: DisplayData {
}
struct GenerateReportSelection {
var fullPdfReport = false
var pdfReportWithoutTable = false
var csvFile = false
var zipFiles = false
var zipStampedJPGs = false
var isValid: Bool {
return fullPdfReport || pdfReportWithoutTable || csvFile || zipFiles || zipStampedJPGs
}
}
| agpl-3.0 | faa6c0b5fac832d3c974bac39a5c5899 | 21.72 | 94 | 0.714789 | 4 | false | false | false | false |
benlangmuir/swift | test/Generics/sr15790.swift | 2 | 824 | // RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s
// https://github.com/apple/swift/issues/58067
// CHECK-LABEL: sr15790.(file).P1@
// CHECK-NEXT: Requirement signature: <Self where Self.[P1]X : P1, Self.[P1]X == Self.[P1]X.[P1]X>
public protocol P1 {
associatedtype X: P1 where X.X == X
}
// CHECK-LABEL: sr15790.(file).P2@
// CHECK-NEXT: Requirement signature: <Self where Self : Collection, Self : P1, Self.[Sequence]Element : P1, Self.[P1]X == Self.[P2]Z.[P2]Y, Self.[P2]Y : P3, Self.[P2]Z : P2>
public protocol P2: Collection, P1 where Element: P1, X == Z.Y {
associatedtype Y: P3
associatedtype Z: P2
}
// CHECK-LABEL: sr15790.(file).P3@
// CHECK-NEXT: Requirement signature: <Self where Self : P2, Self.[P3]T : P2>
public protocol P3: P2 {
associatedtype T: P2
}
| apache-2.0 | c29b87909b9719c061d0ec47462dbbf8 | 36.454545 | 174 | 0.674757 | 2.719472 | false | false | false | false |
TeamYYZ/DineApp | Dine/RestaurantCell.swift | 1 | 1066 | //
// RestaurantCell.swift
// Dine
//
// Created by you wu on 3/24/16.
// Copyright © 2016 YYZ. All rights reserved.
//
import UIKit
class RestaurantCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var genreLabel: UILabel!
@IBOutlet weak var profileView: UIImageView!
@IBOutlet weak var ratingView: UIImageView!
var business: Business! {
didSet {
nameLabel.text = business.name
genreLabel.text = business.categories
if let image = business.imageURL {
profileView.setImageWithURL(image)
}
if let image = business.ratingImageURL {
ratingView.setImageWithURL(image)
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
selectionStyle = .None
// Configure the view for the selected state
}
}
| gpl-3.0 | 69d9a23577357b0940ad64975115cbf1 | 24.97561 | 63 | 0.61784 | 4.754464 | false | false | false | false |
malaonline/iOS | mala-ios/Model/Other/SMSResultModel.swift | 1 | 885 | //
// SMSResultModel.swift
// mala-ios
//
// Created by Elors on 1/4/16.
// Copyright © 2016 Mala Online. All rights reserved.
//
import UIKit
class SMSResultModel: NSObject {
// MARK: - Property
var sent: Bool = false
var verified: Bool = false
var first_login: Bool = false
var token: String = ""
var reason: String?
// MARK: - Constructed
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeys(dict)
}
// MARK: - Override
override func setValue(_ value: Any?, forUndefinedKey key: String) {
println("SMSResultModel - Set for UndefinedKey: \(key) -")
}
// MARK: - Description
override var description: String {
let keys = ["sent", "verified", "first_login", "token", "reason"]
return dictionaryWithValues(forKeys: keys).description
}
}
| mit | d6b75bd6b8063981b3c8b74d26488599 | 21.666667 | 73 | 0.596154 | 4.055046 | false | false | false | false |
Xiomara7/slackers | slackers/MembersViewCell.swift | 1 | 3454 | //
// MembersViewCell.swift
// slackers
//
// Created by Xiomara on 11/4/15.
// Copyright © 2015 Xiomara. All rights reserved.
//
import UIKit
class MembersViewCell: UITableViewCell {
var shouldUpdateConstraints = true
var view: UIView!
var username: UILabel!
var name: UILabel!
var profileImage: UIImageView!
var isAdminLabel: UILabel!
init(reuseIdentifier: String?) {
super.init(style: .Default, reuseIdentifier: reuseIdentifier)
self.backgroundColor = UIColor.clearColor()
self.translatesAutoresizingMaskIntoConstraints = true
view = UIView(frame: CGRectZero)
view.translatesAutoresizingMaskIntoConstraints = true
view.backgroundColor = UIColor.clearColor()
view.layer.borderWidth = defaultBorderWidth
view.layer.cornerRadius = defaultCornerRadius
self.contentView.addSubview(view)
username = UILabel(frame: CGRectZero)
username.translatesAutoresizingMaskIntoConstraints = true
username.font = UIFont(name: userFontName, size: 16.0)
view.addSubview(username)
name = UILabel(frame: CGRectZero)
name.translatesAutoresizingMaskIntoConstraints = true
name.font = UIFont(name: nameFontName, size: 22.0)
view.addSubview(name)
profileImage = UIImageView(frame: CGRectZero)
profileImage.translatesAutoresizingMaskIntoConstraints = true
profileImage.backgroundColor = UIColor.grayColor()
profileImage.contentMode = UIViewContentMode.ScaleAspectFill
profileImage.layer.cornerRadius = defaultCornerRadius
profileImage.layer.masksToBounds = true
profileImage.autoSetDimension(.Height, toSize: 48.0)
profileImage.autoSetDimension(.Width, toSize: 48.0)
view.addSubview(profileImage)
isAdminLabel = UILabel(frame: CGRectZero)
isAdminLabel.translatesAutoresizingMaskIntoConstraints = true
isAdminLabel.font = UIFont(name: userFontName, size: 14.0)
view.addSubview(isAdminLabel)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
class var defaultHeight: CGFloat {
return defaultCellHeight
}
override func updateConstraints() {
if shouldUpdateConstraints {
let inset: CGFloat = 10.0
view.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(inset, inset, inset, inset))
profileImage.autoPinEdgeToSuperviewEdge(.Top, withInset: inset)
profileImage.autoPinEdgeToSuperviewEdge(.Left, withInset: inset)
name.autoPinEdge(.Left, toEdge: .Right, ofView: profileImage, withOffset: inset)
name.autoPinEdgeToSuperviewEdge(.Top, withInset: inset)
username.autoPinEdge(.Top, toEdge: .Bottom, ofView: name, withOffset: inset)
username.autoPinEdge(.Left, toEdge: .Right, ofView: profileImage, withOffset: inset)
isAdminLabel.autoPinEdgeToSuperviewEdge(.Right, withInset: 10.0)
isAdminLabel.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 10.0)
shouldUpdateConstraints = false
}
super.updateConstraints()
}
}
| mit | 7dfe3bbd37dce97a4e8a6d1365979e93 | 32.852941 | 101 | 0.643498 | 5.716887 | false | false | false | false |
Constructor-io/constructorio-client-swift | AutocompleteClientTests/FW/Logic/Request/TrackSearchResultClickRequestBuilder.swift | 1 | 5191 | //
// TrackSearchResultClickRequestBuilderTests.swift
// Constructor.io
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import XCTest
@testable import ConstructorAutocomplete
class TrackSearchResultClickRequestBuilderTests: XCTestCase {
fileprivate let testACKey = "asdf1213123"
fileprivate let searchTerm = "test search term"
fileprivate let itemName = "some item name"
fileprivate let customerID = "custIDq3 qd"
fileprivate let variationID = "varID123"
fileprivate let sectionName = "some section name@"
fileprivate var encodedSearchTerm: String = ""
fileprivate var encodedItemName: String = ""
fileprivate var encodedCustomerID: String = ""
fileprivate var encodedVariationID: String = ""
fileprivate var encodedSectionName: String = ""
fileprivate var builder: RequestBuilder!
override func setUp() {
super.setUp()
self.encodedSearchTerm = searchTerm.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!
self.encodedItemName = itemName.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
self.encodedCustomerID = customerID.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
self.encodedVariationID = variationID.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
self.encodedSectionName = self.sectionName.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
self.builder = RequestBuilder(apiKey: testACKey, baseURL: Constants.Query.baseURLString)
}
func testTrackSearchResultClickBuilder() {
let tracker = CIOTrackSearchResultClickData(searchTerm: searchTerm, itemName: itemName, customerID: customerID)
builder.build(trackData: tracker)
let request = builder.getRequest()
let url = request.url!.absoluteString
XCTAssertEqual(request.httpMethod, "GET")
XCTAssertTrue(url.hasPrefix("https://ac.cnstrc.com/autocomplete/\(encodedSearchTerm)/click_through?"))
XCTAssertTrue(url.contains("name=\(encodedItemName)"), "URL should contain the item name.")
XCTAssertTrue(url.contains("customer_id=\(encodedCustomerID)"), "URL should contain the customer ID.")
XCTAssertTrue(url.contains("c=\(Constants.versionString())"), "URL should contain the version string")
XCTAssertTrue(url.contains("key=\(testACKey)"), "URL should contain the api key")
}
func testTrackSearchResultClickBuilder_WithCustomBaseURL() {
let tracker = CIOTrackSearchResultClickData(searchTerm: searchTerm, itemName: itemName, customerID: customerID)
let customBaseURL = "https://custom-base-url.com"
self.builder = RequestBuilder(apiKey: testACKey, baseURL: customBaseURL)
builder.build(trackData: tracker)
let request = builder.getRequest()
let url = request.url!.absoluteString
XCTAssertTrue(url.hasPrefix(customBaseURL))
}
func testTrackSearchResultClickBuilder_WithSectionName() {
let tracker = CIOTrackSearchResultClickData(searchTerm: searchTerm, itemName: itemName, customerID: customerID, sectionName: sectionName)
builder.build(trackData: tracker)
let request = builder.getRequest()
let url = request.url!.absoluteString
XCTAssertEqual(request.httpMethod, "GET")
XCTAssertTrue(url.hasPrefix("https://ac.cnstrc.com/autocomplete/\(encodedSearchTerm)/click_through?"))
XCTAssertTrue(url.contains("name=\(encodedItemName)"), "URL should contain the item name.")
XCTAssertTrue(url.contains("customer_id=\(encodedCustomerID)"), "URL should contain the customer ID.")
XCTAssertTrue(url.contains("section=\(encodedSectionName)"), "URL should contain the autocomplete section name.")
XCTAssertTrue(url.contains("c=\(Constants.versionString())"), "URL should contain the version string")
XCTAssertTrue(url.contains("key=\(testACKey)"), "URL should contain the api key")
}
func testTrackSearchResultClickBuilder_WithVariationID() {
let tracker = CIOTrackSearchResultClickData(searchTerm: searchTerm, itemName: itemName, customerID: customerID, sectionName: sectionName, variationID: variationID)
builder.build(trackData: tracker)
let request = builder.getRequest()
let url = request.url!.absoluteString
XCTAssertEqual(request.httpMethod, "GET")
XCTAssertTrue(url.hasPrefix("https://ac.cnstrc.com/autocomplete/\(encodedSearchTerm)/click_through?"))
XCTAssertTrue(url.contains("name=\(encodedItemName)"), "URL should contain the item name.")
XCTAssertTrue(url.contains("customer_id=\(encodedCustomerID)"), "URL should contain the customer ID.")
XCTAssertTrue(url.contains("variation_id=\(variationID)"), "URL should contain the variation ID.")
XCTAssertTrue(url.contains("section=\(encodedSectionName)"), "URL should contain the autocomplete section name.")
XCTAssertTrue(url.contains("c=\(Constants.versionString())"), "URL should contain the version string")
XCTAssertTrue(url.contains("key=\(testACKey)"), "URL should contain the api key")
}
}
| mit | 0c78bc148594eb3a49a75a73c899c8f8 | 53.0625 | 171 | 0.730058 | 5 | false | true | false | false |
BlenderSleuth/Unlokit | Unlokit/ViewControllers/LevelSelectViewController.swift | 1 | 4954 | //
// LevelSelectViewController.swift
// Unlokit
//
// Created by Ben Sutherland on 31/1/17.
// Copyright © 2017 blendersleuthdev. All rights reserved.
//
import UIKit
protocol LevelSelectDelegate: class {
func completeLevel()
func saveLevels()
func setNextLevelView(from levelView: LevelView)
var currentLevelView: LevelView? { get set }
var levelViews: [Int: [LevelView]] { get }
}
// This is so that you only do the tutorial once
var doneTutorial = false
class LevelSelectViewController: UIViewController, LevelViewDelegate, LevelSelectDelegate {
@IBOutlet weak var mainScrollView: UIScrollView!
// Dict of stage views
var stageViews = [Int: StageView]()
// Set this to true to run the tutorial
var doTutorial = false
// Level views based on stage
var levelViews = [Int: [LevelView]]()
var stages = [Int: Stage]()
var levels = [Level]()
// So that we can tell which level views to make available
var currentLevelView: LevelView?
var nextLevelView: LevelView?
// Whether to reset the scroll views or not
var notLoaded = true
override func viewDidLoad() {
super.viewDidLoad()
// Load stages
let _ = Stages.sharedInstance.stages
// Run the tutorial if it is the first time or specified
if (isFirstGameLaunch && !doneTutorial) || doTutorial {
// Hide navigation bar
navigationController?.navigationBar.isHidden = true
// Present the tutorial
present(level: Stages.sharedInstance.tutorial)
// First game launch is over.
setValueFor(key: .isFirstGameLaunch)
} else {
setupScroll(frame: view.frame)
reset()
notLoaded = false
}
}
override func viewDidDisappear(_ animated: Bool) {
if doTutorial || (isFirstGameLaunch && !doneTutorial) {
// Put the naviagtion bar back
navigationController?.navigationBar.isHidden = false
// Run this after the tutorial loaded
setupScroll(frame: view.frame)
reset(hideNavBar: true)
doTutorial = false
notLoaded = true
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if notLoaded {
reset()
} else {
navigationController?.isNavigationBarHidden = false
}
}
func reset(hideNavBar: Bool = false) {
navigationController?.isNavigationBarHidden = hideNavBar
// Iterate through stages
for (_, stageView) in stageViews {
// Save levels
stageView.stage.saveLevels()
// Check if there is a levelView
if let levelViews = levelViews[stageView.stage.number] {
// Update progress view with stage
stageView.progressView.update(levelViews: levelViews)
}
}
// Reset current level view
nextLevelView = nil
}
func saveLevels() {
for (_, stageView) in stageViews {
// Save levels
stageView.stage.saveLevels()
}
}
func setupScroll(frame: CGRect) {
// Each stage view is the width of the screen, and 1/4 of the width in height
let width = frame.width
let height = width / 4
let size = CGSize(width: width, height: height)
// Find out the full height of the scroll view
let fullHeight = height * CGFloat(Stages.sharedInstance.stages.count)
mainScrollView.contentSize.height = fullHeight
// To find the y position of each stage view
var yPos: CGFloat = 0
for stage in Stages.sharedInstance.stages {
let stageView = StageView(frame: CGRect(origin: CGPoint(x: 0, y: yPos), size: size), stage: stage, delegate: self)
mainScrollView.addSubview(stageView)
stageViews[stageView.stage.number] = stageView
yPos += height
}
}
func setNextLevelView(from levelView: LevelView) {
// Find next level view and make it avaible
let number = levelView.level.number - 1
// Check levels and stages
if levelViews[levelView.level.stageNumber]!.endIndex == number + 1 {
// Get max stage by key of dictionary
let maxStage = levelViews.max { a, b in a.key < b.key }?.key
// Last level of last stage, stay the same
if levelView.level.stageNumber == maxStage {
print("last level, setting next level to current")
nextLevelView = levelViews[levelView.level.stageNumber]?[number]
} else {
// First level of next stage
nextLevelView = levelViews[levelView.level.stageNumber + 1]?[0]
}
} else {
// Next level in current stage
nextLevelView = levelViews[levelView.level.stageNumber ]?[number + 1]
}
}
func present(level: Level) {
if let gameViewController = storyboard?.instantiateViewController(withIdentifier: "GameViewController") as? GameViewController {
// Animate with cross dissolve
let transition = CATransition()
transition.duration = 0.5
navigationController?.view.layer.add(transition, forKey: nil)
navigationController?.pushViewController(gameViewController, animated: false)
gameViewController.level = level
gameViewController.delegate = self
}
}
func completeLevel() {
nextLevelView?.makeAvailable()
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| gpl-3.0 | 339f7b9cac9f92c7a718d6d18ab6743d | 26.670391 | 130 | 0.709267 | 3.749432 | false | false | false | false |
toggl/superday | teferi/Services/Implementations/Persistency/Adapters/CoreDataModelAdapter.swift | 1 | 1147 | import Foundation
import CoreData
class CoreDataModelAdapter<T>
{
func getModel(fromManagedObject managedObject: NSManagedObject) -> T
{
fatalError("Not implemented")
}
func setManagedElementProperties(fromModel model: T, managedObject: NSManagedObject)
{
fatalError("Not implemented")
}
var sortDescriptorsForList : [NSSortDescriptor]!
var sortDescriptorsForLast : [NSSortDescriptor]!
func getLocation(_ managedObject: NSManagedObject, timeKey: String, latKey: String, lngKey: String) -> Location?
{
var location : Location? = nil
let possibleTime = managedObject.value(forKey: timeKey) as? Date
let possibleLatitude = managedObject.value(forKey: latKey) as? Double
let possibleLongitude = managedObject.value(forKey: lngKey) as? Double
if let time = possibleTime, let latitude = possibleLatitude, let longitude = possibleLongitude
{
location = Location(timestamp: time,
latitude: latitude, longitude: longitude)
}
return location
}
}
| bsd-3-clause | 0d1ba69c8c57f4a6f6cbb8049424e10e | 31.771429 | 116 | 0.653008 | 5.237443 | false | false | false | false |
sunshineclt/NKU-Helper | NKU Helper/功能/成绩查询/GPACell.swift | 1 | 1576 | //
// GPACell.swift
// NKU Helper
//
// Created by 陈乐天 on 16/7/18.
// Copyright © 2016年 陈乐天. All rights reserved.
//
import UIKit
class GPACell: UITableViewCell {
@IBOutlet var ClassNameLabel: UILabel!
@IBOutlet var GradeLabel: UILabel!
@IBOutlet var gradeImageView: UIImageView!
var GPAName: String! {
didSet {
ClassNameLabel.text = GPAName
}
}
var GPASum: Double!
var GPA: Double! {
didSet {
GradeLabel.text = NSString(format: "%.2lf", GPA) as String
gradeImageView.image = getGradeImageWithGrade(GPA)
}
}
fileprivate func getGradeImageWithGrade(_ grade: Double) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 40, height: 40), false, 0)
let context = UIGraphicsGetCurrentContext()!
let per = (grade - 1) / (GPASum - 1)
var red: Double = 0, green: Double = 0
if per < 0.5 {
red = 1
green = per / 0.5
}
else {
green = 1
red = ( 1 - per ) / 0.5
}
if per < 0 {
red = 0
green = 0
}
context.setFillColor(UIColor(red: CGFloat(red * 0.8 + 0.1), green: CGFloat(green * 0.8 + 0.1), blue: 0.1, alpha: 1).cgColor)
context.addEllipse(in: CGRect(x: 10, y: 10, width: 20, height: 20));
context.drawPath(using: .fill)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext();
return image
}
}
| gpl-3.0 | b372f4455c1ced2c6b1ce92a82546c74 | 26.875 | 132 | 0.556694 | 3.97201 | false | false | false | false |
CraigZheng/KomicaViewer | KomicaViewer/KomicaViewer/ViewController/ForumQRScannerViewController.swift | 1 | 8212 | //
// ForumQRScannerViewController.swift
// KomicaViewer
//
// Created by Craig Zheng on 11/09/2016.
// Copyright © 2016 Craig. All rights reserved.
//
import UIKit
import AVFoundation
import KomicaEngine
import Firebase
class ForumQRScannerViewController: UIViewController {
@IBOutlet var cameraPreviewView: UIView!
var capturedForum: KomicaForum?
fileprivate var captureSession: AVCaptureSession?
fileprivate var warningAlertController: UIAlertController?
fileprivate struct SegueIdentifier {
static let addForum = "addForum"
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Request camera permission.
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (granted) in
DispatchQueue.main.async(execute: {
if (granted) {
// Permission has been granted. Use dispatch_async for any UI updating
// code because this block may be executed in a thread.
self.setUpScanner()
} else {
// No permission, inform user about the permission issue, or quit.
let alertController = UIAlertController(title: "\(UIApplication.appName) Would Like To Use Your Camera", message: nil, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { [weak self] _ in
// Dismiss self.
_ = self?.navigationController?.popToRootViewController(animated: true)
}))
alertController.addAction(UIAlertAction(title: "Settings", style: .default, handler: { _ in
let settingsUrl = URL(string: UIApplicationOpenSettingsURLString)
if let url = settingsUrl {
UIApplication.shared.openURL(url)
}
}))
self.present(alertController, animated: true, completion: nil)
}
})
})
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
captureSession?.stopRunning()
}
fileprivate func setUpScanner() {
captureSession?.stopRunning()
captureSession = AVCaptureSession()
let videoCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
if let videoInput = try? AVCaptureDeviceInput(device:videoCaptureDevice),
let captureSession = captureSession
{
captureSession.addInput(videoInput)
let metadataOutput = AVCaptureMetadataOutput()
captureSession.addOutput(metadataOutput)
metadataOutput.setMetadataObjectsDelegate(self, queue:DispatchQueue.main)
metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code]
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer?.frame = self.cameraPreviewView.bounds; // Align to cameraPreviewView.
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill;
cameraPreviewView.layer.addSublayer(previewLayer!)
captureSession.startRunning()
}
}
}
// MARK: Navigation
extension ForumQRScannerViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == SegueIdentifier.addForum, let destinationViewController = segue.destination as? AddForumTableViewController {
// Passing nil to the destination would cause the app to crash, so if capturedForum is nil, pass a new komica forum object to it.
destinationViewController.newForum = capturedForum ?? KomicaForum()
}
}
}
// MARK: UI actions.
extension ForumQRScannerViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBAction func loadFromLibraryAction(_ sender: AnyObject) {
let picker = UIImagePickerController()
picker.allowsEditing = false
picker.sourceType = .photoLibrary
picker.delegate = self
present(picker, animated: true, completion: nil)
}
@IBAction func scanQRHelpBarButtonItemAction(_ sender: AnyObject) {
if let scanForumQRHelpURL = Configuration.singleton.scanForumQRHelpURL, UIApplication.shared.canOpenURL(scanForumQRHelpURL as URL)
{
UIApplication.shared.openURL(scanForumQRHelpURL)
Analytics.logEvent(AnalyticsEventSelectContent, parameters: [
AnalyticsParameterContentType: "SELECT REMOTE URL" as NSObject,
AnalyticsParameterItemID: "\(scanForumQRHelpURL.absoluteString)" as NSString,
AnalyticsParameterItemName: "\(scanForumQRHelpURL.absoluteString)" as NSString])
}
}
// MARK: UIImagePickerControllerDelegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage,
let ciImage = CIImage(image: pickedImage)
{
let parsedResult = performQRCodeDetection(ciImage)
if let last = parsedResult.last {
if !parseJsonString(last) {
ProgressHUD.showMessage("QR code cannot be parsed, please try again")
}
}
}
dismiss(animated: true, completion: nil)
}
}
// MARK: AVCaptureMetadataOutputObjectsDelegate
extension ForumQRScannerViewController: AVCaptureMetadataOutputObjectsDelegate {
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
if let lastMetadataObject = metadataObjects.last,
let readableObject = lastMetadataObject as? AVMetadataMachineReadableCodeObject
{
if (readableObject.type == AVMetadataObjectTypeQRCode) {
if parseJsonString(readableObject.stringValue) {
captureSession?.stopRunning()
return
}
}
}
if warningAlertController == nil {
// Cannot parse.
warningAlertController = UIAlertController(title: "QR code cannot be parsed, please try again", message: nil, preferredStyle: .alert)
warningAlertController?.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { (_) in
self.warningAlertController = nil
}))
present(warningAlertController!, animated: true, completion: nil)
}
}
func parseJsonString(_ jsonString: String) -> Bool {
// Construct a forum object with the scanned result.
if let jsonData = jsonString.data(using: String.Encoding.utf8),
let jsonDict = (try? JSONSerialization.jsonObject(with: jsonData,
options: .allowFragments)) as? [String: AnyObject], !jsonString.isEmpty
{
capturedForum = KomicaForum(jsonDict: jsonDict)
if ((capturedForum?.isReady()) != nil) {
performSegue(withIdentifier: SegueIdentifier.addForum, sender: nil)
return true
}
}
return false
}
}
// MARK: Read from library
extension ForumQRScannerViewController {
// Shamelessly copied from http://stackoverflow.com/questions/35956538/how-to-read-qr-code-from-static-image and modified to my need.
func performQRCodeDetection(_ image: CIImage) -> [String] {
let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh, CIDetectorAspectRatio: 1.0])
let features = detector?.features(in: image)
var strings = [String]()
features?.forEach { feature in
if let feature = feature as? CIQRCodeFeature {
strings.append(feature.messageString!)
}
}
return strings
}
}
| mit | d53ef5f97cbdcc478025e2572af085b6 | 42.909091 | 162 | 0.650956 | 5.686288 | false | false | false | false |
gribozavr/swift | test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1conformance-1distinct_use.swift | 1 | 3396 | // RUN: %swift -target %module-target-future -emit-ir -prespecialize-generic-metadata %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$sytN" = external{{( dllimport)?}} global %swift.full_type
// CHECK: @"$s4main5ValueVySiGMf" = internal constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i8**,
// CHECK-SAME: i32{{(, \[4 x i8\])?}},
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// i8** @"$sB[[INT]]_WV",
// i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVySiGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 512,
// CHECK-SAME: %swift.type_descriptor* bitcast (<{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8, i32, i32, i32 }>* @"$s4main5ValueVMn" to %swift.type_descriptor*),
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1PAAWP", i32 0, i32 0),
// CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}},
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
protocol P {}
extension Int : P {}
struct Value<First : P> {
let first: First
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i8**, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySiGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: }
func doit() {
consume( Value(first: 13) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]], %swift.type*, i8**) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: [[ERASED_TABLE:%[0-9]+]] = bitcast i8** %2 to i8*
// CHECK: br label %[[TYPE_COMPARISON_LABEL:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_LABEL]]:
// CHECK: [[EQUAL_TYPE:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE]]
// CHECK: [[EQUAL_TYPES:%[0-9]+]] = and i1 true, [[EQUAL_TYPE]]
// CHECK: br i1 [[EQUAL_TYPES]], label %[[EXIT_PRESPECIALIZED:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]]
// CHECK: [[EXIT_PRESPECIALIZED]]:
// CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i8**, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySiGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 }
// CHECK: [[EXIT_NORMAL]]:
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE]], i8* [[ERASED_TABLE]], i8* undef, %swift.type_descriptor* bitcast (<{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8, i32, i32, i32 }>* @"$s4main5ValueVMn" to %swift.type_descriptor*))
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | fcba5a6bf273833633f20106e54b453c | 52.904762 | 349 | 0.606596 | 2.885302 | false | false | false | false |
RMizin/PigeonMessenger-project | FalconMessenger/Authentication/PhoneAuthentication/VerificationControllers/VerificationContainerView.swift | 1 | 4950 | //
// VerificationContainerView.swift
// Pigeon-project
//
// Created by Roman Mizin on 8/3/17.
// Copyright © 2017 Roman Mizin. All rights reserved.
//
import UIKit
final class VerificationContainerView: UIView {
let titleNumber: UILabel = {
let titleNumber = UILabel()
titleNumber.translatesAutoresizingMaskIntoConstraints = false
titleNumber.textAlignment = .center
titleNumber.textColor = ThemeManager.currentTheme().generalTitleColor
titleNumber.font = UIFont.boldSystemFont(ofSize: 32)
return titleNumber
}()
let subtitleText: UILabel = {
let subtitleText = UILabel()
subtitleText.translatesAutoresizingMaskIntoConstraints = false
subtitleText.font = UIFont.boldSystemFont(ofSize: 15)//(ofSize: 15)
subtitleText.textAlignment = .center
subtitleText.textColor = ThemeManager.currentTheme().generalTitleColor
subtitleText.text = "We have sent you an SMS with the code"
return subtitleText
}()
let verificationCode: UITextField = {
let verificationCode = UITextField()
verificationCode.font = UIFont.boldSystemFont(ofSize: 20)
verificationCode.translatesAutoresizingMaskIntoConstraints = false
verificationCode.textAlignment = .center
verificationCode.keyboardType = .numberPad
if #available(iOS 12.0, *) {
verificationCode.textContentType = .oneTimeCode
}
verificationCode.textColor = ThemeManager.currentTheme().generalTitleColor
verificationCode.keyboardAppearance = ThemeManager.currentTheme().keyboardAppearance
verificationCode.backgroundColor = .clear
verificationCode.layer.cornerRadius = 25
verificationCode.layer.borderWidth = 1
verificationCode.attributedPlaceholder = NSAttributedString(string: "Code",
attributes: [NSAttributedString.Key.foregroundColor:
ThemeManager.currentTheme().generalSubtitleColor])
verificationCode.layer.borderColor = ThemeManager.currentTheme().inputTextViewColor.cgColor
if !DeviceType.isIPad {
verificationCode.addDoneButtonOnKeyboard()
}
return verificationCode
}()
let resend: UIButton = {
let resend = UIButton()
resend.translatesAutoresizingMaskIntoConstraints = false
resend.setTitle("Resend", for: .normal)
resend.contentVerticalAlignment = .center
resend.contentHorizontalAlignment = .center
resend.setTitleColor(ThemeManager.currentTheme().generalSubtitleColor, for: .highlighted)
resend.setTitleColor(ThemeManager.currentTheme().generalSubtitleColor, for: .disabled)
return resend
}()
weak var enterVerificationCodeController: VerificationCodeController?
var seconds = 120
var timer = Timer()
var timerLabel: UILabel = {
var timerLabel = UILabel()
timerLabel.textColor = ThemeManager.currentTheme().generalSubtitleColor
timerLabel.font = UIFont.systemFont(ofSize: 13)
timerLabel.translatesAutoresizingMaskIntoConstraints = false
timerLabel.textAlignment = .center
timerLabel.sizeToFit()
timerLabel.numberOfLines = 0
return timerLabel
}()
override init(frame: CGRect) {
super.init(frame: frame)
resend.setTitleColor(ThemeManager.currentTheme().tintColor, for: .normal)
addSubview(titleNumber)
addSubview(subtitleText)
addSubview(verificationCode)
addSubview(resend)
addSubview(timerLabel)
NSLayoutConstraint.activate([
titleNumber.topAnchor.constraint(equalTo: topAnchor),
titleNumber.leadingAnchor.constraint(equalTo: leadingAnchor),
titleNumber.trailingAnchor.constraint(equalTo: trailingAnchor),
titleNumber.heightAnchor.constraint(equalToConstant: 70),
subtitleText.topAnchor.constraint(equalTo: titleNumber.bottomAnchor),
subtitleText.leadingAnchor.constraint(equalTo: leadingAnchor),
subtitleText.trailingAnchor.constraint(equalTo: trailingAnchor),
subtitleText.heightAnchor.constraint(equalToConstant: 30),
verificationCode.topAnchor.constraint(equalTo: subtitleText.bottomAnchor, constant: 30),
verificationCode.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10),
verificationCode.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10),
verificationCode.heightAnchor.constraint(equalToConstant: 50),
resend.topAnchor.constraint(equalTo: verificationCode.bottomAnchor, constant: 5),
resend.leadingAnchor.constraint(equalTo: leadingAnchor),
resend.trailingAnchor.constraint(equalTo: trailingAnchor),
resend.heightAnchor.constraint(equalToConstant: 45),
timerLabel.topAnchor.constraint(equalTo: resend.bottomAnchor, constant: 0),
timerLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10),
timerLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10),
timerLabel.heightAnchor.constraint(equalToConstant: 35)
])
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
}
| gpl-3.0 | 03605cbceb2d99df5221e50fd1c5b579 | 36.778626 | 95 | 0.758133 | 5.304394 | false | false | false | false |
ontouchstart/swift3-playground | Graphing.playgroundbook/Contents/Sources/PlaygroundInternal/ChartValue.swift | 1 | 16451 | //
// ChartValueView.swift
// Charts
//
// Copyright © 2014-2016 Apple Inc. All rights reserved.
//
import UIKit
internal struct ChartValue {
let label: String?
let index: Int?
let value: (Double, Double)
let color: Color
let screenPoint: CGPoint
}
extension ChartValue {
var integralScreenPoint: CGPoint {
get {
return CGPoint(x: round(screenPoint.x), y: round(screenPoint.y))
}
}
}
internal class ChartValueView: UIView {
private let horizontalHighlightView: UIView
private var horizontalHighlightLocation: CGFloat? {
didSet {
updateHorizontalHighlight()
}
}
private var displayedValues = [ChartValue]()
private var calloutViews = [CalloutView]()
internal weak var chartView: ChartView?
// MARK: Initialization
init(chartView: ChartView) {
horizontalHighlightView = UIView(frame: CGRect.zero)
horizontalHighlightView.backgroundColor = chartView.style.highlightLineColor.uiColor
super.init(frame: CGRect.zero)
self.chartView = chartView
self.isOpaque = false
addSubview(horizontalHighlightView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Interface
internal func display(values: [ChartValue]) {
if (values.count > 0) {
displayedValues.removeAll()
}
displayedValues += values
updateCallouts()
}
internal func dismissDisplayedValues() {
displayedValues.removeAll()
updateCallouts()
}
internal func displayHighlightAt(horizontalLocation: CGFloat?) {
horizontalHighlightLocation = horizontalLocation
}
internal func dismissHighlight() {
horizontalHighlightLocation = nil
}
// MARK: Display
func updateHorizontalHighlight() {
guard let chartView = chartView else {
horizontalHighlightView.removeFromSuperview()
return
}
let style = chartView.style
let highlightWidth = CGFloat(style.highlightLineWidth)
if let horizontalHighlightLocation = horizontalHighlightLocation {
horizontalHighlightView.isHidden = false
horizontalHighlightView.frame = CGRect(x: horizontalHighlightLocation - (highlightWidth / 2), y: 0, width: highlightWidth, height: bounds.height)
}
else {
horizontalHighlightView.isHidden = true
}
}
func updateCallouts() {
for calloutView in calloutViews {
calloutView.removeFromSuperview()
}
guard let chartView = chartView else { return }
let style = chartView.style
for valuePoint in displayedValues {
var optCalloutView = calloutViews.first { calloutView in
return calloutView.superview == nil
}
if optCalloutView == nil {
let calloutView = CalloutView(style: style)
calloutViews.append(calloutView)
optCalloutView = calloutView
}
guard let calloutView = optCalloutView else {
fatalError("Couldn't create CalloutView to display value.")
}
calloutView.chartValue = valuePoint
let calloutViewSize = calloutView.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
let calloutFrame = calloutRectFor(calloutSize: calloutViewSize, anchorPoint: valuePoint.integralScreenPoint)
addSubview(calloutView)
calloutView.frame = calloutFrame
}
}
func calloutRectFor(calloutSize: CGSize, anchorPoint: CGPoint) -> CGRect {
guard let chartView = chartView else { return CGRect.zero }
let style = chartView.style
var calloutRect = CGRect.zero
let cornerRadius = CGFloat(style.calloutCornerRadius)
let arrowLength = CGFloat(style.calloutArrowLength)
let calloutOffset = CGFloat(style.calloutOffset)
let calloutUpOrigin = CGPoint(
x: anchorPoint.x - (calloutSize.width / 2),
y: anchorPoint.y - calloutSize.height - arrowLength - calloutOffset
)
let calloutRightOrigin = CGPoint(
x: anchorPoint.x + arrowLength + calloutOffset,
y: anchorPoint.y - (calloutSize.height / 2)
)
var prefersHorizontalCallout = false
// If the value falls far enough horizontally offscreen we should attempt to display the callouts on either horizontal side
if (anchorPoint.x - arrowLength - cornerRadius < bounds.minX || anchorPoint.x + arrowLength + cornerRadius > bounds.maxX) {
prefersHorizontalCallout = true
}
if prefersHorizontalCallout {
calloutRect = CGRect(origin: calloutRightOrigin, size: calloutSize)
}
else {
calloutRect = CGRect(origin: calloutUpOrigin, size: calloutSize)
}
var intersection = calloutRect.intersection(bounds)
// Work out whether the callout would be displayed vertically offscreen
if (intersection.height < calloutRect.height) {
if !prefersHorizontalCallout {
// Flip down to display down
calloutRect = calloutRect.offsetBy(dx: 0, dy: calloutRect.height + ((calloutOffset + arrowLength) * 2))
// Recalculate the intersection
intersection = calloutRect.intersection(bounds)
}
}
// Work out whether the callout would be displayed horizontally offscreen
if intersection.width < calloutRect.width {
if prefersHorizontalCallout {
// Flip over to display on the left
calloutRect = calloutRect.offsetBy(dx: -(calloutRect.width + ((calloutOffset + arrowLength) * 2)), dy: 0)
}
else {
// Adjust slightly left
let adjustment = calloutRect.minX < 0 ? calloutRect.width - intersection.width : -(calloutRect.width - intersection.width)
calloutRect = calloutRect.offsetBy(dx: adjustment, dy: 0)
}
}
return calloutRect.integral
}
}
private class CalloutView: UIView {
private class CalloutContentView: UIView {
let titleLabel = UILabel()
let xTitleLabel = UILabel()
let xValueLabel = UILabel()
let yTitleLabel = UILabel()
let yValueLabel = UILabel()
let indexTitleLabel = UILabel()
let indexValueLabel = UILabel()
var chartValue: ChartValue? {
didSet {
configureContent()
}
}
let style: ChartStyle
var fieldTitleRightConstraints = [NSLayoutConstraint]()
var fixedWidthConstraint: NSLayoutConstraint!
init(style: ChartStyle) {
self.style = style
super.init(frame: CGRect.zero)
addSubview(titleLabel)
titleLabel.textAlignment = .center
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
titleLabel.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
titleLabel.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
let spaceWidth = ceil((" " as NSString).size(attributes: style.calloutFieldTitleLabelAttributes).width)
let maxWidth = CGFloat(style.calloutMaxWidth)
let contentInset = CGFloat(style.calloutTitlePadding)
fixedWidthConstraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: 130)
addConstraint(fixedWidthConstraint)
func configure(titleLabel: UILabel, valueLabel: UILabel, topAnchor: NSLayoutYAxisAnchor, bottomAnchor: NSLayoutYAxisAnchor?) {
addSubview(titleLabel)
addSubview(valueLabel)
titleLabel.textAlignment = .right
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
let titleLabelRightConstraint = titleLabel.rightAnchor.constraint(equalTo: self.centerXAnchor, constant: spaceWidth.negated())
fieldTitleRightConstraints.append(titleLabelRightConstraint)
titleLabelRightConstraint.isActive = true
titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: contentInset).isActive = true
if let bottomAnchor = bottomAnchor {
titleLabel.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
valueLabel.textAlignment = .left
valueLabel.translatesAutoresizingMaskIntoConstraints = false
valueLabel.leftAnchor.constraint(equalTo: titleLabel.rightAnchor, constant: spaceWidth).isActive = true
valueLabel.rightAnchor.constraint(lessThanOrEqualTo: self.rightAnchor).isActive = true
valueLabel.topAnchor.constraint(equalTo: topAnchor, constant: contentInset).isActive = true
if let bottomAnchor = bottomAnchor {
valueLabel.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
}
configure(titleLabel: xTitleLabel, valueLabel: xValueLabel, topAnchor: titleLabel.bottomAnchor, bottomAnchor: nil)
configure(titleLabel: yTitleLabel, valueLabel: yValueLabel, topAnchor: xTitleLabel.bottomAnchor, bottomAnchor: nil)
configure(titleLabel: indexTitleLabel, valueLabel: indexValueLabel, topAnchor: yTitleLabel.bottomAnchor, bottomAnchor: self.bottomAnchor)
configureContent()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configureContent() {
guard let chartValue = chartValue else {
for label in [titleLabel, xValueLabel, xTitleLabel, yTitleLabel, yValueLabel, indexTitleLabel, indexValueLabel] {
label.attributedText = nil
}
return
}
if let title = chartValue.label {
let attributes = style.calloutTitleLabelAttributesWith(color: chartValue.color)
titleLabel.attributedText = NSAttributedString(string: title, attributes: attributes)
}
else {
titleLabel.attributedText = nil
}
let fieldTitleAttributes = style.calloutFieldTitleLabelAttributes
let fieldValueAttributes = style.calloutFieldValueLabelAttributes
let displayIndex = (chartValue.index != nil)
indexTitleLabel.attributedText = displayIndex ? NSAttributedString(string: "index:", attributes: fieldTitleAttributes) : nil
indexValueLabel.attributedText = displayIndex ? NSAttributedString(string: "\(chartValue.index!)", attributes: fieldValueAttributes) : nil
fieldTitleRightConstraints.forEach { constraint in
constraint.isActive = displayIndex
}
fixedWidthConstraint.isActive = !displayIndex
let xValue = displayIndex ? "\(chartValue.value.0)" : String(format: "%.10f", chartValue.value.0)
let yValue = displayIndex ? "\(chartValue.value.1)" : String(format: "%.10f", chartValue.value.1)
xTitleLabel.attributedText = NSAttributedString(string: "x:", attributes: fieldTitleAttributes)
xValueLabel.attributedText = NSAttributedString(string: xValue, attributes: fieldValueAttributes)
yTitleLabel.attributedText = NSAttributedString(string: "y:", attributes: fieldTitleAttributes)
yValueLabel.attributedText = NSAttributedString(string: yValue, attributes: fieldValueAttributes)
}
}
let style: ChartStyle
let backgroundLayer: CAShapeLayer
let contentView: CalloutContentView
var chartValue: ChartValue? {
didSet {
contentView.chartValue = chartValue
}
}
init(style: ChartStyle) {
self.style = style
backgroundLayer = CAShapeLayer()
contentView = CalloutContentView(style: style)
super.init(frame: CGRect.zero)
backgroundLayer.fillColor = style.calloutBackgroundColor.cgColor
backgroundLayer.frame = bounds
layer.addSublayer(backgroundLayer)
let contentInset = CGFloat(style.calloutLabelInset)
let maxWidth = CGFloat(style.calloutMaxWidth)
addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.topAnchor.constraint(equalTo: self.topAnchor, constant: contentInset).isActive = true
contentView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -contentInset).isActive = true
contentView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: contentInset).isActive = true
contentView.rightAnchor.constraint(equalTo: self.rightAnchor, constant:-contentInset).isActive = true
let maxWidthConstraint = NSLayoutConstraint(item: contentView, attribute: .width, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .width, multiplier: 1.0, constant: maxWidth)
contentView.addConstraint(maxWidthConstraint)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private override func layoutSubviews() {
super.layoutSubviews()
updateBackgroundLayer()
}
func updateBackgroundLayer() {
guard let chartValue = chartValue else { return }
let arrowPoint = convert(chartValue.screenPoint, from: superview)
let arrowLength = CGFloat(style.calloutArrowLength)
let cornerRadius = CGFloat(style.calloutCornerRadius)
let calloutOffset = CGFloat(style.calloutOffset)
let trianglePath = UIBezierPath()
if (bounds.contains(CGPoint(x: arrowPoint.x, y: bounds.midY))) {
// Callout displayed vertically
trianglePath.move(to: CGPoint(x: arrowPoint.x, y: arrowPoint.y < bounds.minY ? arrowPoint.y + calloutOffset : arrowPoint.y - calloutOffset))
let yPos = bounds.midY < arrowPoint.y ? bounds.maxY : bounds.minY
trianglePath.addLine(to: CGPoint(
x: max(bounds.minX + cornerRadius, arrowPoint.x - arrowLength),
y: yPos
))
trianglePath.addLine(to: CGPoint(
x: min(bounds.maxX - cornerRadius, arrowPoint.x + arrowLength),
y: yPos
))
}
else {
// Callout displayed horizontally
trianglePath.move(to: CGPoint(x: arrowPoint.x < bounds.minX ? arrowPoint.x + calloutOffset : arrowPoint.x - calloutOffset, y: arrowPoint.y))
let xPos = bounds.midX < arrowPoint.x ? bounds.maxX : bounds.minX
trianglePath.addLine(to: CGPoint(
x: xPos,
y: arrowPoint.y - arrowLength
))
trianglePath.addLine(to: CGPoint(
x: xPos,
y: arrowPoint.y + arrowLength
))
}
trianglePath.close()
let contentPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius)
contentPath.append(trianglePath)
backgroundLayer.path = contentPath.cgPath
}
}
| mit | acbdd0da93f49311a07ec790b9e04fdc | 37.888889 | 187 | 0.615258 | 5.676329 | false | false | false | false |
dreamsxin/swift | test/IRGen/objc_bridge.swift | 3 | 10884 | // RUN: rm -rf %t && mkdir %t
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-ir -primary-file %s | FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import Foundation
// CHECK: [[GETTER_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"@16@0:8\00"
// CHECK: [[SETTER_SIGNATURE:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00"
// CHECK: [[DEALLOC_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00"
// CHECK: @_INSTANCE_METHODS__TtC11objc_bridge3Bas = private constant { i32, i32, [17 x { i8*, i8*, i8* }] } {
// CHECK: i32 24,
// CHECK: i32 17,
// CHECK: [17 x { i8*, i8*, i8* }] [
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(strRealProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_TToFC11objc_bridge3Basg11strRealPropSS to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* @"\01L_selector_data(setStrRealProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_TToFC11objc_bridge3Bass11strRealPropSS to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(strFakeProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_TToFC11objc_bridge3Basg11strFakePropSS to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* @"\01L_selector_data(setStrFakeProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_TToFC11objc_bridge3Bass11strFakePropSS to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(nsstrRealProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_TToFC11objc_bridge3Basg13nsstrRealPropCSo8NSString to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* @"\01L_selector_data(setNsstrRealProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_TToFC11objc_bridge3Bass13nsstrRealPropCSo8NSString to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(nsstrFakeProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_TToFC11objc_bridge3Basg13nsstrFakePropCSo8NSString to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* @"\01L_selector_data(setNsstrFakeProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_TToFC11objc_bridge3Bass13nsstrFakePropCSo8NSString to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(strResult)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_TToFC11objc_bridge3Bas9strResultfT_SS to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([{{[0-9]*}} x i8], [{{[0-9]*}} x i8]* @"\01L_selector_data(strArgWithS:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_TToFC11objc_bridge3Bas6strArgfT1sSS_T_ to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(nsstrResult)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_TToFC11objc_bridge3Bas11nsstrResultfT_CSo8NSString to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* @"\01L_selector_data(nsstrArgWithS:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_TToFC11objc_bridge3Bas8nsstrArgfT1sCSo8NSString_T_ to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_TToFC11objc_bridge3BascfT_S0_ to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[DEALLOC_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*)* @_TToFC11objc_bridge3BasD to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @"\01L_selector_data(acceptSet:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @{{[0-9]+}}, i64 0, i64 0),
// CHECK: i8* bitcast (void (%3*, i8*, %4*)* @_TToFC11objc_bridge3Bas9acceptSetfGVs3SetS0__T_ to i8*)
// CHECK: }
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([3 x i8], [3 x i8]* @{{.*}}, i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*)* @_TToFC11objc_bridge3BasE to i8*)
// CHECK: }
// CHECK: ]
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK: @_PROPERTIES__TtC11objc_bridge3Bas = private constant { i32, i32, [5 x { i8*, i8* }] } {
// CHECK: [[OBJC_BLOCK_PROPERTY:@.*]] = private unnamed_addr constant [11 x i8] c"T@?,N,C,Vx\00"
// CHECK: @_PROPERTIES__TtC11objc_bridge21OptionalBlockProperty = private constant {{.*}} [[OBJC_BLOCK_PROPERTY]]
func getDescription(_ o: NSObject) -> String {
return o.description
}
func getUppercaseString(_ s: NSString) -> String {
return s.uppercase()
}
// @interface Foo -(void) setFoo: (NSString*)s; @end
func setFoo(_ f: Foo, s: String) {
f.setFoo(s)
}
// NSString *bar(int);
func callBar() -> String {
return bar(0)
}
// void setBar(NSString *s);
func callSetBar(_ s: String) {
setBar(s)
}
var NSS : NSString = NSString()
// -- NSString methods don't convert 'self'
extension NSString {
// CHECK: define internal [[OPAQUE:.*]]* @_TToFE11objc_bridgeCSo8NSStringg13nsstrFakePropS0_([[OPAQUE:.*]]*, i8*) unnamed_addr
// CHECK: define internal void @_TToFE11objc_bridgeCSo8NSStrings13nsstrFakePropS0_([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr
var nsstrFakeProp : NSString {
get {
return NSS
}
set {}
}
// CHECK: define internal [[OPAQUE:.*]]* @_TToFE11objc_bridgeCSo8NSString11nsstrResultfT_S0_([[OPAQUE:.*]]*, i8*) unnamed_addr
func nsstrResult() -> NSString { return NSS }
// CHECK: define internal void @_TToFE11objc_bridgeCSo8NSString8nsstrArgfT1sS0__T_([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr
func nsstrArg(s s: NSString) { }
}
class Bas : NSObject {
// CHECK: define internal [[OPAQUE:.*]]* @_TToFC11objc_bridge3Basg11strRealPropSS([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} {
// CHECK: define internal void @_TToFC11objc_bridge3Bass11strRealPropSS([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
var strRealProp : String
// CHECK: define internal [[OPAQUE:.*]]* @_TToFC11objc_bridge3Basg11strFakePropSS([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} {
// CHECK: define internal void @_TToFC11objc_bridge3Bass11strFakePropSS([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
var strFakeProp : String {
get {
return ""
}
set {}
}
// CHECK: define internal [[OPAQUE:.*]]* @_TToFC11objc_bridge3Basg13nsstrRealPropCSo8NSString([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} {
// CHECK: define internal void @_TToFC11objc_bridge3Bass13nsstrRealPropCSo8NSString([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
var nsstrRealProp : NSString
// CHECK: define hidden %CSo8NSString* @_TFC11objc_bridge3Basg13nsstrFakePropCSo8NSString(%C11objc_bridge3Bas*) {{.*}} {
// CHECK: define internal void @_TToFC11objc_bridge3Bass13nsstrFakePropCSo8NSString([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
var nsstrFakeProp : NSString {
get {
return NSS
}
set {}
}
// CHECK: define internal [[OPAQUE:.*]]* @_TToFC11objc_bridge3Bas9strResultfT_SS([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} {
func strResult() -> String { return "" }
// CHECK: define internal void @_TToFC11objc_bridge3Bas6strArgfT1sSS_T_([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
func strArg(s s: String) { }
// CHECK: define internal [[OPAQUE:.*]]* @_TToFC11objc_bridge3Bas11nsstrResultfT_CSo8NSString([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} {
func nsstrResult() -> NSString { return NSS }
// CHECK: define internal void @_TToFC11objc_bridge3Bas8nsstrArgfT1sCSo8NSString_T_([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} {
func nsstrArg(s s: NSString) { }
override init() {
strRealProp = String()
nsstrRealProp = NSString()
super.init()
}
deinit { var x = 10 }
override var hashValue: Int { return 0 }
func acceptSet(_ set: Set<Bas>) { }
}
func ==(lhs: Bas, rhs: Bas) -> Bool { return true }
class OptionalBlockProperty: NSObject {
var x: (([AnyObject]) -> [AnyObject])?
}
| apache-2.0 | 70d67454063123ab60c4a0d57c3626ba | 52.615764 | 144 | 0.593072 | 3.110603 | false | false | false | false |
haskellswift/swift-package-manager | Sources/Commands/Error.swift | 1 | 3432 | /*
This source file is part of the Swift.org open source project
Copyright 2015 - 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 Swift project authors
*/
import Basic
import PackageModel
import enum Utility.ColorWrap
import enum Utility.Stream
import func POSIX.exit
import func Utility.isTTY
import var Utility.stderr
import enum PackageLoading.ManifestParseError
public enum Error: Swift.Error {
case noManifestFound
case invalidToolchain(problem: String)
case buildYAMLNotFound(String)
case repositoryHasChanges(String)
}
extension Error: FixableError {
public var error: String {
switch self {
case .noManifestFound:
return "no \(Manifest.filename) file found"
case .invalidToolchain(let problem):
return "invalid inferred toolchain: \(problem)"
case .buildYAMLNotFound(let value):
return "no build YAML found: \(value)"
case .repositoryHasChanges(let value):
return "repository has changes: \(value)"
}
}
public var fix: String? {
switch self {
case .noManifestFound:
return "create a file named \(Manifest.filename) or run `swift package init` to initialize a new package"
case .repositoryHasChanges(_):
return "stage the changes and reapply them after updating the repository"
default:
return nil
}
}
}
public func handle(error: Any, usage: ((String) -> Void) -> Void) -> Never {
switch error {
case OptionParserError.multipleModesSpecified(let modes):
print(error: error)
if isTTY(.stdErr) && (modes.contains{ ["--help", "-h"].contains($0) }) {
print("", to: &stderr)
usage { print($0, to: &stderr) }
}
case OptionParserError.noCommandProvided(let hint):
if !hint.isEmpty {
print(error: error)
}
if isTTY(.stdErr) {
usage { print($0, to: &stderr) }
}
case is OptionParserError:
print(error: error)
if isTTY(.stdErr) {
let argv0 = CommandLine.arguments.first ?? "swift package"
print("enter `\(argv0) --help' for usage information", to: &stderr)
}
case let error as FixableError:
print(error: error.error)
if let fix = error.fix {
print(fix: fix)
}
case ManifestParseError.invalidManifestFormat(let errors):
var errorString = "invalid manifest format"
if let errors = errors {
errorString += "; " + errors.joined(separator: ", ")
}
print(error: errorString)
default:
print(error: error)
}
exit(1)
}
private func print(error: Any) {
if ColorWrap.isAllowed(for: .stdErr) {
print(ColorWrap.wrap("error:", with: .Red, for: .stdErr), error, to: &stderr)
} else {
let cmd = AbsolutePath(CommandLine.arguments.first!, relativeTo:currentWorkingDirectory).basename
print("\(cmd): error:", error, to: &stderr)
}
}
private func print(fix: String) {
if ColorWrap.isAllowed(for: .stdErr) {
print(ColorWrap.wrap("fix:", with: .Yellow, for: .stdErr), fix, to: &stderr)
} else {
print("fix:", fix, to: &stderr)
}
}
| apache-2.0 | cfc5b158a6325b918636a222a2a4e7cb | 30.2 | 117 | 0.624417 | 4.205882 | false | false | false | false |
shadanan/mado | Antlr4Runtime/Sources/Antlr4/misc/BitSet.swift | 1 | 37095 | /// Copyright (c) 2012-2017 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.
//
// BitSet.swift
// Antlr.swift
//
// Created by janyou on 15/9/8.
//
import Foundation
/// This class implements a vector of bits that grows as needed. Each
/// component of the bit set has a {@code boolean} value. The
/// bits of a {@code BitSet} are indexed by nonnegative integers.
/// Individual indexed bits can be examined, set, or cleared. One
/// {@code BitSet} may be used to modify the contents of another
/// {@code BitSet} through logical AND, logical inclusive OR, and
/// logical exclusive OR operations.
///
/// <p>By default, all bits in the set initially have the value
/// {@code false}.
///
/// <p>Every bit set has a current size, which is the number of bits
/// of space currently in use by the bit set. Note that the size is
/// related to the implementation of a bit set, so it may change with
/// implementation. The length of a bit set relates to logical length
/// of a bit set and is defined independently of implementation.
///
/// <p>Unless otherwise noted, passing a null parameter to any of the
/// methods in a {@code BitSet} will result in a
/// {@code NullPointerException}.
///
/// <p>A {@code BitSet} is not safe for multithreaded use without
/// external synchronization.
///
/// - Arthur van Hoff
/// - Michael McCloskey
/// - Martin Buchholz
/// - JDK1.0
public class BitSet: Hashable, CustomStringConvertible {
/// BitSets are packed into arrays of "words." Currently a word is
/// a long, which consists of 64 bits, requiring 6 address bits.
/// The choice of word size is determined purely by performance concerns.
private static let ADDRESS_BITS_PER_WORD: Int = 6
private static let BITS_PER_WORD: Int = 1 << ADDRESS_BITS_PER_WORD
private static let BIT_INDEX_MASK: Int = BITS_PER_WORD - 1
/// Used to shift left or right for a partial word mask
private static let WORD_MASK: Int64 = Int64.max
//0xfffffffffffffff//-1
// 0xffffffffffffffffL;
/// - bits long[]
///
/// The bits in this BitSet. The ith bit is stored in bits[i/64] at
/// bit position i % 64 (where bit position 0 refers to the least
/// significant bit and 63 refers to the most significant bit).
/// The internal field corresponding to the serialField "bits".
fileprivate var words: [Int64]
/// The number of words in the logical size of this BitSet.
fileprivate var wordsInUse: Int = 0
//transient
/// Whether the size of "words" is user-specified. If so, we assume
/// the user knows what he's doing and try harder to preserve it.
private var sizeIsSticky: Bool = false
//transient
/// use serialVersionUID from JDK 1.0.2 for interoperability
private let serialVersionUID: Int64 = 7997698588986878753
//L;
/// Given a bit index, return word index containing it.
private static func wordIndex(_ bitIndex: Int) -> Int {
return bitIndex >> ADDRESS_BITS_PER_WORD
}
/// Every public method must preserve these invariants.
fileprivate func checkInvariants() {
assert((wordsInUse == 0 || words[wordsInUse - 1] != 0), "Expected: (wordsInUse==0||words[wordsInUse-1]!=0)")
assert((wordsInUse >= 0 && wordsInUse <= words.count), "Expected: (wordsInUse>=0&&wordsInUse<=words.length)")
// print("\(wordsInUse),\(words.count),\(words[wordsInUse])")
assert((wordsInUse == words.count || words[wordsInUse] == 0), "Expected: (wordsInUse==words.count||words[wordsInUse]==0)")
}
/// Sets the field wordsInUse to the logical size in words of the bit set.
/// WARNING:This method assumes that the number of words actually in use is
/// less than or equal to the current value of wordsInUse!
private func recalculateWordsInUse() {
// Traverse the bitset until a used word is found
var i: Int = wordsInUse - 1
while i >= 0 {
if words[i] != 0 {
break
}
i -= 1
}
wordsInUse = i + 1 // The new logical size
}
/// Creates a new bit set. All bits are initially {@code false}.
public init() {
sizeIsSticky = false
words = [Int64](repeating: Int64(0), count: BitSet.wordIndex(BitSet.BITS_PER_WORD - 1) + 1)
//initWords(BitSet.BITS_PER_WORD);
}
/// Creates a bit set whose initial size is large enough to explicitly
/// represent bits with indices in the range {@code 0} through
/// {@code nbits-1}. All bits are initially {@code false}.
///
/// - parameter nbits: the initial size of the bit set
/// - NegativeArraySizeException if the specified initial size
/// is negative
public init(_ nbits: Int) throws {
// nbits can't be negative; size 0 is OK
// words = [BitSet.wordIndex(nbits-1) + 1];
words = [Int64](repeating: Int64(0), count: BitSet.wordIndex(BitSet.BITS_PER_WORD - 1) + 1)
sizeIsSticky = true
if nbits < 0 {
throw ANTLRError.negativeArraySize(msg: "nbits < 0:\(nbits) ")
}
// initWords(nbits);
}
private func initWords(_ nbits: Int) {
// words = [Int64](count: BitSet.wordIndex(BitSet.BITS_PER_WORD-1) + 1, repeatedValue: Int64(0));
// words = [BitSet.wordIndex(nbits-1) + 1];
}
/// Creates a bit set using words as the internal representation.
/// The last word (if there is one) must be non-zero.
private init(_ words: [Int64]) {
self.words = words
self.wordsInUse = words.count
checkInvariants()
}
/// Returns a new long array containing all the bits in this bit set.
///
/// <p>More precisely, if
/// <br>{@code long[] longs = s.toLongArray();}
/// <br>then {@code longs.length == (s.length()+63)/64} and
/// <br>{@code s.get(n) == ((longs[n/64] & (1L<<(n%64))) != 0)}
/// <br>for all {@code n < 64 * longs.length}.
///
/// - returns: a long array containing a little-endian representation
/// of all the bits in this bit set
/// - 1.7
public func toLongArray() -> [Int64] {
return copyOf(words, wordsInUse)
}
private func copyOf(_ words: [Int64], _ newLength: Int) -> [Int64] {
var newWords = [Int64](repeating: Int64(0), count: newLength)
let length = min(words.count, newLength)
newWords[0 ..< length] = words[0 ..< length]
return newWords
}
/// Ensures that the BitSet can hold enough words.
/// - parameter wordsRequired: the minimum acceptable number of words.
private func ensureCapacity(_ wordsRequired: Int) {
if words.count < wordsRequired {
// Allocate larger of doubled size or required size
let request: Int = max(2 * words.count, wordsRequired)
words = copyOf(words, request)
sizeIsSticky = false
}
}
/// Ensures that the BitSet can accommodate a given wordIndex,
/// temporarily violating the invariants. The caller must
/// restore the invariants before returning to the user,
/// possibly using recalculateWordsInUse().
/// - parameter wordIndex: the index to be accommodated.
private func expandTo(_ wordIndex: Int) {
let wordsRequired: Int = wordIndex + 1
if wordsInUse < wordsRequired {
ensureCapacity(wordsRequired)
wordsInUse = wordsRequired
}
}
/// Checks that fromIndex ... toIndex is a valid range of bit indices.
private static func checkRange(_ fromIndex: Int, _ toIndex: Int) throws {
if fromIndex < 0 {
throw ANTLRError.indexOutOfBounds(msg: "fromIndex < 0: \(fromIndex)")
}
if toIndex < 0 {
throw ANTLRError.indexOutOfBounds(msg: "toIndex < 0: \(toIndex)")
}
if fromIndex > toIndex {
throw ANTLRError.indexOutOfBounds(msg: "fromInde: \(fromIndex) > toIndex: \(toIndex)")
}
}
/// Sets the bit at the specified index to the complement of its
/// current value.
///
/// - parameter bitIndex: the index of the bit to flip
/// - IndexOutOfBoundsException if the specified index is negative
/// - 1.4
public func flip(_ bitIndex: Int) throws {
if bitIndex < 0 {
throw ANTLRError.indexOutOfBounds(msg: "bitIndex < 0: \(bitIndex)")
}
let index: Int = BitSet.wordIndex(bitIndex)
expandTo(index)
words[index] ^= (Int64(1) << Int64(bitIndex % 64))
recalculateWordsInUse()
checkInvariants()
}
/// Sets each bit from the specified {@code fromIndex} (inclusive) to the
/// specified {@code toIndex} (exclusive) to the complement of its current
/// value.
///
/// - parameter fromIndex: index of the first bit to flip
/// - parameter toIndex: index after the last bit to flip
/// - IndexOutOfBoundsException if {@code fromIndex} is negative,
/// or {@code toIndex} is negative, or {@code fromIndex} is
/// larger than {@code toIndex}
/// - 1.4
public func flip(_ fromIndex: Int, _ toIndex: Int) throws {
try BitSet.checkRange(fromIndex, toIndex)
if fromIndex == toIndex {
return
}
let startWordIndex: Int = BitSet.wordIndex(fromIndex)
let endWordIndex: Int = BitSet.wordIndex(toIndex - 1)
expandTo(endWordIndex)
let firstWordMask: Int64 = BitSet.WORD_MASK << Int64(fromIndex % 64)
let lastWordMask: Int64 = BitSet.WORD_MASK >>> Int64(-toIndex)
//var lastWordMask : Int64 = WORD_MASK >>> Int64(-toIndex);
if startWordIndex == endWordIndex {
// Case 1: One word
words[startWordIndex] ^= (firstWordMask & lastWordMask)
} else {
// Case 2: Multiple words
// Handle first word
words[startWordIndex] ^= firstWordMask
// Handle intermediate words, if any
let start = startWordIndex + 1
for i in start..<endWordIndex {
words[i] ^= BitSet.WORD_MASK
}
// Handle last word
words[endWordIndex] ^= lastWordMask
}
recalculateWordsInUse()
checkInvariants()
}
/// Sets the bit at the specified index to {@code true}.
///
/// - parameter bitIndex: a bit index
/// - IndexOutOfBoundsException if the specified index is negative
/// - JDK1.0
public func set(_ bitIndex: Int) throws {
if bitIndex < 0 {
throw ANTLRError.indexOutOfBounds(msg: "bitIndex < 0: \(bitIndex)")
}
let index: Int = BitSet.wordIndex(bitIndex)
expandTo(index)
// print(words.count)
words[index] |= (Int64(1) << Int64(bitIndex % 64)) // Restores invariants
checkInvariants()
}
/// Sets the bit at the specified index to the specified value.
///
/// - parameter bitIndex: a bit index
/// - parameter value: a boolean value to set
/// - IndexOutOfBoundsException if the specified index is negative
/// - 1.4
public func set(_ bitIndex: Int, _ value: Bool) throws {
if value {
try set(bitIndex)
} else {
try clear(bitIndex)
}
}
/// Sets the bits from the specified {@code fromIndex} (inclusive) to the
/// specified {@code toIndex} (exclusive) to {@code true}.
///
/// - parameter fromIndex: index of the first bit to be set
/// - parameter toIndex: index after the last bit to be set
/// - IndexOutOfBoundsException if {@code fromIndex} is negative,
/// or {@code toIndex} is negative, or {@code fromIndex} is
/// larger than {@code toIndex}
/// - 1.4
public func set(_ fromIndex: Int, _ toIndex: Int) throws {
try BitSet.checkRange(fromIndex, toIndex)
if fromIndex == toIndex {
return
}
// Increase capacity if necessary
let startWordIndex: Int = BitSet.wordIndex(fromIndex)
let endWordIndex: Int = BitSet.wordIndex(toIndex - 1)
expandTo(endWordIndex)
let firstWordMask: Int64 = BitSet.WORD_MASK << Int64(fromIndex % 64)
let lastWordMask: Int64 = BitSet.WORD_MASK >>> Int64(-toIndex)
//var lastWordMask : Int64 = WORD_MASK >>>Int64( -toIndex);
if startWordIndex == endWordIndex {
// Case 1: One word
words[startWordIndex] |= (firstWordMask & lastWordMask)
} else {
// Case 2: Multiple words
// Handle first word
words[startWordIndex] |= firstWordMask
// Handle intermediate words, if any
let start = startWordIndex + 1
for i in start..<endWordIndex {
words[i] = BitSet.WORD_MASK
}
// Handle last word (restores invariants)
words[endWordIndex] |= lastWordMask
}
checkInvariants()
}
/// Sets the bits from the specified {@code fromIndex} (inclusive) to the
/// specified {@code toIndex} (exclusive) to the specified value.
///
/// - parameter fromIndex: index of the first bit to be set
/// - parameter toIndex: index after the last bit to be set
/// - parameter value: value to set the selected bits to
/// - IndexOutOfBoundsException if {@code fromIndex} is negative,
/// or {@code toIndex} is negative, or {@code fromIndex} is
/// larger than {@code toIndex}
/// - 1.4
public func set(_ fromIndex: Int, _ toIndex: Int, _ value: Bool) throws {
if value {
try set(fromIndex, toIndex)
} else {
try clear(fromIndex, toIndex)
}
}
/// Sets the bit specified by the index to {@code false}.
///
/// - parameter bitIndex: the index of the bit to be cleared
/// - IndexOutOfBoundsException if the specified index is negative
/// - JDK1.0
public func clear(_ bitIndex: Int) throws {
if bitIndex < 0 {
throw ANTLRError.indexOutOfBounds(msg: "bitIndex < 0: \(bitIndex)")
}
let index: Int = BitSet.wordIndex(bitIndex)
if index >= wordsInUse {
return
}
let option = Int64(1) << Int64(bitIndex % 64)
words[index] &= ~option
recalculateWordsInUse()
checkInvariants()
}
/// Sets the bits from the specified {@code fromIndex} (inclusive) to the
/// specified {@code toIndex} (exclusive) to {@code false}.
///
/// - parameter fromIndex: index of the first bit to be cleared
/// - parameter toIndex: index after the last bit to be cleared
/// - IndexOutOfBoundsException if {@code fromIndex} is negative,
/// or {@code toIndex} is negative, or {@code fromIndex} is
/// larger than {@code toIndex}
/// - 1.4
public func clear(_ fromIndex: Int, _ toIndex: Int) throws {
var toIndex = toIndex
try BitSet.checkRange(fromIndex, toIndex)
if fromIndex == toIndex {
return
}
let startWordIndex: Int = BitSet.wordIndex(fromIndex)
if startWordIndex >= wordsInUse {
return
}
var endWordIndex: Int = BitSet.wordIndex(toIndex - 1)
if endWordIndex >= wordsInUse {
toIndex = length()
endWordIndex = wordsInUse - 1
}
let firstWordMask: Int64 = BitSet.WORD_MASK << Int64(fromIndex % 64)
// ar lastWordMask : Int64 = WORD_MASK >>> Int64((-toIndex);
let lastWordMask: Int64 = BitSet.WORD_MASK >>> Int64(-toIndex)
if startWordIndex == endWordIndex {
// Case 1: One word
words[startWordIndex] &= ~(firstWordMask & lastWordMask)
} else {
// Case 2: Multiple words
// Handle first word
words[startWordIndex] &= ~firstWordMask
// Handle intermediate words, if any
let start = startWordIndex + 1
for i in start..<endWordIndex {
words[i] = 0
}
// Handle last word
words[endWordIndex] &= ~lastWordMask
}
recalculateWordsInUse()
checkInvariants()
}
/// Sets all of the bits in this BitSet to {@code false}.
///
/// - 1.4
public func clear() {
while wordsInUse > 0 {
wordsInUse -= 1
words[wordsInUse] = 0
}
}
/// Returns the value of the bit with the specified index. The value
/// is {@code true} if the bit with the index {@code bitIndex}
/// is currently set in this {@code BitSet}; otherwise, the result
/// is {@code false}.
///
/// - parameter bitIndex: the bit index
/// - returns: the value of the bit with the specified index
/// - IndexOutOfBoundsException if the specified index is negative
public func get(_ bitIndex: Int) throws -> Bool {
if bitIndex < 0 {
throw ANTLRError.indexOutOfBounds(msg: "bitIndex < 0: \(bitIndex)")
}
checkInvariants()
let index: Int = BitSet.wordIndex(bitIndex)
return (index < wordsInUse)
&& ((words[index] & ((Int64(1) << Int64(bitIndex % 64)))) != 0)
}
/// Returns a new {@code BitSet} composed of bits from this {@code BitSet}
/// from {@code fromIndex} (inclusive) to {@code toIndex} (exclusive).
///
/// - parameter fromIndex: index of the first bit to include
/// - parameter toIndex: index after the last bit to include
/// - returns: a new {@code BitSet} from a range of this {@code BitSet}
/// - IndexOutOfBoundsException if {@code fromIndex} is negative,
/// or {@code toIndex} is negative, or {@code fromIndex} is
/// larger than {@code toIndex}
/// - 1.4
public func get(_ fromIndex: Int, _ toIndex: Int) throws -> BitSet {
var toIndex = toIndex
try BitSet.checkRange(fromIndex, toIndex)
checkInvariants()
let len: Int = length()
// If no set bits in range return empty bitset
if len <= fromIndex || fromIndex == toIndex {
return try BitSet(0)
}
// An optimization
if toIndex > len {
toIndex = len
}
let result: BitSet = try BitSet(toIndex - fromIndex)
let targetWords: Int = BitSet.wordIndex(toIndex - fromIndex - 1) + 1
var sourceIndex: Int = BitSet.wordIndex(fromIndex)
let wordAligned: Bool = (fromIndex & BitSet.BIT_INDEX_MASK) == 0
// Process all words but the last word
var i: Int = 0;
while i < targetWords - 1 {
let wordOption1: Int64 = (words[sourceIndex] >>> Int64(fromIndex))
let wordOption2: Int64 = (words[sourceIndex + 1] << Int64(-fromIndex % 64))
let wordOption = wordOption1 | wordOption2
result.words[i] = wordAligned ? words[sourceIndex] : wordOption
i += 1
sourceIndex += 1
}
// Process the last word
// var lastWordMask : Int64 = WORD_MASK >>> Int64(-toIndex);
let lastWordMask: Int64 = BitSet.WORD_MASK >>> Int64(-toIndex)
let toIndexTest = ((toIndex - 1) & BitSet.BIT_INDEX_MASK)
let fromIndexTest = (fromIndex & BitSet.BIT_INDEX_MASK)
let wordOption1: Int64 = (words[sourceIndex] >>> Int64(fromIndex))
let wordOption2: Int64 = (words[sourceIndex + 1] & lastWordMask)
let wordOption3: Int64 = (64 + Int64(-fromIndex % 64))
let wordOption = wordOption1 | wordOption2 << wordOption3
let wordOption4 = (words[sourceIndex] & lastWordMask)
let wordOption5 = wordOption4 >>> Int64(fromIndex)
result.words[targetWords - 1] =
toIndexTest < fromIndexTest
? wordOption : wordOption5
// Set wordsInUse correctly
result.wordsInUse = targetWords
result.recalculateWordsInUse()
result.checkInvariants()
return result
}
/// Returns the index of the first bit that is set to {@code true}
/// that occurs on or after the specified starting index. If no such
/// bit exists then {@code -1} is returned.
///
/// <p>To iterate over the {@code true} bits in a {@code BitSet},
/// use the following loop:
///
/// <pre> {@code
/// for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
/// // operate on index i here
/// }}</pre>
///
/// - parameter fromIndex: the index to start checking from (inclusive)
/// - returns: the index of the next set bit, or {@code -1} if there
/// is no such bit
/// - IndexOutOfBoundsException if the specified index is negative
/// - 1.4
public func nextSetBit(_ fromIndex: Int) throws -> Int {
if fromIndex < 0 {
throw ANTLRError.indexOutOfBounds(msg: "fromIndex < 0: \(fromIndex)")
}
checkInvariants()
var u: Int = BitSet.wordIndex(fromIndex)
if u >= wordsInUse {
return -1
}
var word: Int64 = words[u] & (BitSet.WORD_MASK << Int64(fromIndex % 64))
while true {
if word != 0 {
let bit = (u * BitSet.BITS_PER_WORD) + BitSet.numberOfTrailingZeros(word)
return bit
}
u += 1
if u == wordsInUse {
return -1
}
word = words[u]
}
}
public static func numberOfTrailingZeros(_ i: Int64) -> Int {
// HD, Figure 5-14
var x: Int32, y: Int32
if i == 0 {
return 64
}
var n: Int32 = 63
y = Int32(truncatingBitPattern: i)
if y != 0 {
n = n - 32
x = y
} else {
x = Int32(truncatingBitPattern: i >>> 32)
}
y = x << 16
if y != 0 {
n = n - 16
x = y
}
y = x << 8
if y != 0 {
n = n - 8
x = y
}
y = x << 4
if y != 0 {
n = n - 4
x = y
}
y = x << 2
if y != 0 {
n = n - 2
x = y
}
return Int(n - ((x << 1) >>> 31))
}
/// Returns the index of the first bit that is set to {@code false}
/// that occurs on or after the specified starting index.
///
/// - parameter fromIndex: the index to start checking from (inclusive)
/// - returns: the index of the next clear bit
/// - IndexOutOfBoundsException if the specified index is negative
/// - 1.4
public func nextClearBit(_ fromIndex: Int) throws -> Int {
// Neither spec nor implementation handle bitsets of maximal length.
// See 4816253.
if fromIndex < 0 {
throw ANTLRError.indexOutOfBounds(msg: "fromIndex < 0: \(fromIndex)")
}
checkInvariants()
var u: Int = BitSet.wordIndex(fromIndex)
if u >= wordsInUse {
return fromIndex
}
var word: Int64 = ~words[u] & (BitSet.WORD_MASK << Int64(fromIndex % 64))
while true {
if word != 0 {
return (u * BitSet.BITS_PER_WORD) + BitSet.numberOfTrailingZeros(word)
}
u += 1
if u == wordsInUse {
return wordsInUse * BitSet.BITS_PER_WORD
}
word = ~words[u]
}
}
/// Returns the index of the nearest bit that is set to {@code true}
/// that occurs on or before the specified starting index.
/// If no such bit exists, or if {@code -1} is given as the
/// starting index, then {@code -1} is returned.
///
/// <p>To iterate over the {@code true} bits in a {@code BitSet},
/// use the following loop:
///
/// <pre> {@code
/// for (int i = bs.length(); (i = bs.previousSetBit(i-1)) >= 0; ) {
/// // operate on index i here
/// }}</pre>
///
/// - parameter fromIndex: the index to start checking from (inclusive)
/// - returns: the index of the previous set bit, or {@code -1} if there
/// is no such bit
/// - IndexOutOfBoundsException if the specified index is less
/// than {@code -1}
/// - 1.7
public func previousSetBit(_ fromIndex: Int) throws -> Int {
if fromIndex < 0 {
if fromIndex == -1 {
return -1
}
throw ANTLRError.indexOutOfBounds(msg: "fromIndex < -1: \(fromIndex)")
}
checkInvariants()
var u: Int = BitSet.wordIndex(fromIndex)
if u >= wordsInUse {
return length() - 1
}
var word: Int64 = words[u] & (BitSet.WORD_MASK >>> Int64(-(fromIndex + 1)))
while true {
if word != 0 {
return (u + 1) * BitSet.BITS_PER_WORD - 1 - BitSet.numberOfLeadingZeros(word)
}
if u == 0 {
return -1
}
u -= 1
word = words[u]
}
}
/// Returns the index of the nearest bit that is set to {@code false}
/// that occurs on or before the specified starting index.
/// If no such bit exists, or if {@code -1} is given as the
/// starting index, then {@code -1} is returned.
///
/// - parameter fromIndex: the index to start checking from (inclusive)
/// - returns: the index of the previous clear bit, or {@code -1} if there
/// is no such bit
/// - IndexOutOfBoundsException if the specified index is less
/// than {@code -1}
/// - 1.7
public func previousClearBit(_ fromIndex: Int) throws -> Int {
if fromIndex < 0 {
if fromIndex == -1 {
return -1
}
throw ANTLRError.indexOutOfBounds(msg: "fromIndex < -1: \(fromIndex)")
}
checkInvariants()
var u: Int = BitSet.wordIndex(fromIndex)
if u >= wordsInUse {
return fromIndex
}
var word: Int64 = ~words[u] & (BitSet.WORD_MASK >>> Int64(-(fromIndex + 1)))
// var word : Int64 = ~words[u] & (WORD_MASK >>> -(fromIndex+1));
while true {
if word != 0 {
return (u + 1) * BitSet.BITS_PER_WORD - 1 - BitSet.numberOfLeadingZeros(word)
}
if u == 0 {
return -1
}
u -= 1
word = ~words[u]
}
}
public static func numberOfLeadingZeros(_ i: Int64) -> Int {
// HD, Figure 5-6
if i == 0 {
return 64
}
var n: Int32 = 1
var x = Int32(i >>> 32)
if x == 0 {
n += 32
x = Int32(i)
}
if x >>> 16 == 0 {
n += 16
x <<= 16
}
if x >>> 24 == 0 {
n += 8
x <<= 8
}
if x >>> 28 == 0 {
n += 4
x <<= 4
}
if x >>> 30 == 0 {
n += 2
x <<= 2
}
n -= x >>> 31
return Int(n)
}
/// Returns the "logical size" of this {@code BitSet}: the index of
/// the highest set bit in the {@code BitSet} plus one. Returns zero
/// if the {@code BitSet} contains no set bits.
///
/// - returns: the logical size of this {@code BitSet}
/// - 1.2
public func length() -> Int {
if wordsInUse == 0 {
return 0
}
return BitSet.BITS_PER_WORD * (wordsInUse - 1) +
(BitSet.BITS_PER_WORD - BitSet.numberOfLeadingZeros(words[wordsInUse - 1]))
}
/// Returns true if this {@code BitSet} contains no bits that are set
/// to {@code true}.
///
/// - returns: boolean indicating whether this {@code BitSet} is empty
/// - 1.4
public func isEmpty() -> Bool {
return wordsInUse == 0
}
/// Returns true if the specified {@code BitSet} has any bits set to
/// {@code true} that are also set to {@code true} in this {@code BitSet}.
///
/// - parameter set: {@code BitSet} to intersect with
/// - returns: boolean indicating whether this {@code BitSet} intersects
/// the specified {@code BitSet}
/// - 1.4
public func intersects(_ set: BitSet) -> Bool {
var i: Int = min(wordsInUse, set.wordsInUse) - 1
while i >= 0 {
if (words[i] & set.words[i]) != 0 {
return true
}
i -= 1
}
return false
}
/// Returns the number of bits set to {@code true} in this {@code BitSet}.
///
/// - returns: the number of bits set to {@code true} in this {@code BitSet}
/// - 1.4
public func cardinality() -> Int {
var sum: Int = 0
for i in 0..<wordsInUse {
sum += BitSet.bitCount(words[i])
}
return sum
}
public static func bitCount(_ i: Int64) -> Int {
var i = i
// HD, Figure 5-14
i = i - ((i >>> 1) & 0x5555555555555555)
i = (i & 0x3333333333333333) + ((i >>> 2) & 0x3333333333333333)
i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0f
i = i + (i >>> 8)
i = i + (i >>> 16)
i = i + (i >>> 32)
return Int(i) & 0x7f
}
/// Performs a logical <b>AND</b> of this target bit set with the
/// argument bit set. This bit set is modified so that each bit in it
/// has the value {@code true} if and only if it both initially
/// had the value {@code true} and the corresponding bit in the
/// bit set argument also had the value {@code true}.
///
/// - parameter set: a bit set
public func and(_ set: BitSet) {
if self == set {
return
}
while wordsInUse > set.wordsInUse {
wordsInUse -= 1
words[wordsInUse] = 0
}
// Perform logical AND on words in common
for i in 0..<wordsInUse {
words[i] &= set.words[i]
}
recalculateWordsInUse()
checkInvariants()
}
/// Performs a logical <b>OR</b> of this bit set with the bit set
/// argument. This bit set is modified so that a bit in it has the
/// value {@code true} if and only if it either already had the
/// value {@code true} or the corresponding bit in the bit set
/// argument has the value {@code true}.
///
/// - parameter set: a bit set
public func or(_ set: BitSet) {
if self == set {
return
}
let wordsInCommon: Int = min(wordsInUse, set.wordsInUse)
if wordsInUse < set.wordsInUse {
ensureCapacity(set.wordsInUse)
wordsInUse = set.wordsInUse
}
// Perform logical OR on words in common
for i in 0..<wordsInCommon {
words[i] |= set.words[i]
}
// Copy any remaining words
if wordsInCommon < set.wordsInUse {
words[wordsInCommon ..< wordsInUse] = set.words[wordsInCommon ..< wordsInUse]
}
// recalculateWordsInUse() is unnecessary
checkInvariants()
}
/// Performs a logical <b>XOR</b> of this bit set with the bit set
/// argument. This bit set is modified so that a bit in it has the
/// value {@code true} if and only if one of the following
/// statements holds:
/// <ul>
/// <li>The bit initially has the value {@code true}, and the
/// corresponding bit in the argument has the value {@code false}.
/// <li>The bit initially has the value {@code false}, and the
/// corresponding bit in the argument has the value {@code true}.
/// </ul>
///
/// - parameter set: a bit set
public func xor(_ set: BitSet) {
let wordsInCommon: Int = min(wordsInUse, set.wordsInUse)
if wordsInUse < set.wordsInUse {
ensureCapacity(set.wordsInUse)
wordsInUse = set.wordsInUse
}
// Perform logical XOR on words in common
for i in 0..<wordsInCommon {
words[i] ^= set.words[i]
}
// Copy any remaining words
if wordsInCommon < set.wordsInUse {
words[wordsInCommon ..< wordsInUse] = set.words[wordsInCommon ..< wordsInUse]
}
recalculateWordsInUse()
checkInvariants()
}
/// Clears all of the bits in this {@code BitSet} whose corresponding
/// bit is set in the specified {@code BitSet}.
///
/// - parameter set: the {@code BitSet} with which to mask this
/// {@code BitSet}
/// - 1.2
public func andNot(_ set: BitSet) {
// Perform logical (a & !b) on words in common
var i: Int = min(wordsInUse, set.wordsInUse) - 1
while i >= 0 {
words[i] &= ~set.words[i]
i -= 1
}
recalculateWordsInUse()
checkInvariants()
}
/// Returns the hash code value for this bit set. The hash code depends
/// only on which bits are set within this {@code BitSet}.
///
/// <p>The hash code is defined to be the result of the following
/// calculation:
/// <pre> {@code
/// public int hashCode() {
/// long h = 1234;
/// long[] words = toLongArray();
/// for (int i = words.length; --i >= 0; )
/// h ^= words[i] * (i + 1);
/// return (int)((h >> 32) ^ h);
/// }}</pre>
/// Note that the hash code changes if the set of bits is altered.
///
/// - returns: the hash code value for this bit set
public var hashValue: Int {
var h: Int64 = 1234
var i: Int = wordsInUse
i -= 1
while i >= 0 {
h ^= words[i] * Int64(i + 1)
i -= 1
}
return Int(Int32((h >> 32) ^ h))
}
/// Returns the number of bits of space actually in use by this
/// {@code BitSet} to represent bit values.
/// The maximum element in the set is the size - 1st element.
///
/// - returns: the number of bits currently in this bit set
public func size() -> Int {
return words.count * BitSet.BITS_PER_WORD
}
/// Attempts to reduce internal storage used for the bits in this bit set.
/// Calling this method may, but is not required to, affect the value
/// returned by a subsequent call to the {@link #size()} method.
private func trimToSize() {
if wordsInUse != words.count {
words = copyOf(words, wordsInUse)
checkInvariants()
}
}
/// Returns a string representation of this bit set. For every index
/// for which this {@code BitSet} contains a bit in the set
/// state, the decimal representation of that index is included in
/// the result. Such indices are listed in order from lowest to
/// highest, separated by ", " (a comma and a space) and
/// surrounded by braces, resulting in the usual mathematical
/// notation for a set of integers.
///
/// <p>Example:
/// <pre>
/// BitSet drPepper = new BitSet();</pre>
/// Now {@code drPepper.toString()} returns "{@code {}}".
/// <pre>
/// drPepper.set(2);</pre>
/// Now {@code drPepper.toString()} returns "{@code {2}}".
/// <pre>
/// drPepper.set(4);
/// drPepper.set(10);</pre>
/// Now {@code drPepper.toString()} returns "{@code {2, 4, 10}}".
///
/// - returns: a string representation of this bit set
public var description: String {
checkInvariants()
//let numBits: Int = (wordsInUse > 128) ?
// cardinality() : wordsInUse * BitSet.BITS_PER_WORD
let b: StringBuilder = StringBuilder()
b.append("{")
do {
var i: Int = try nextSetBit(0)
if i != -1 {
b.append(i)
i = try nextSetBit(i + 1)
while i >= 0 {
let endOfRun: Int = try nextClearBit(i)
repeat {
b.append(", ").append(i)
i += 1
} while i < endOfRun
i = try nextSetBit(i + 1)
}
// for ; i >= 0; i = try nextSetBit(i + 1) {
// let endOfRun: Int = try nextClearBit(i)
// repeat {
// b.append(", ").append(i)
// } while ++i < endOfRun
// }
}
} catch {
print("BitSet description error")
}
b.append("}")
return b.toString()
}
public func toString() -> String {
return description
}
}
public func ==(lhs: BitSet, rhs: BitSet) -> Bool {
if lhs === rhs {
return true
}
lhs.checkInvariants()
rhs.checkInvariants()
if lhs.wordsInUse != rhs.wordsInUse {
return false
}
// Check words in use by both BitSets
let length = lhs.wordsInUse
for i in 0..<length {
if lhs.words[i] != rhs.words[i] {
return false
}
}
return true
}
| mit | 3f11fc0d72cccd8a43a5f97a4390269a | 32.509485 | 130 | 0.559536 | 4.111616 | false | false | false | false |
kildevaeld/File | Pod/Classes/WritableFileStream.swift | 1 | 3287 | //
// WritableFileStream.swift
// Bytes
//
// Created by Rasmus Kildevæld on 29/07/15.
// Copyright © 2015 Rasmus Kildevæld . All rights reserved.
//
import Darwin
import Dispatch
public protocol Writable {
func write(bytes: UnsafeMutablePointer<UInt8>, length: Int) -> Int
}
public class WritableFileStream : FileStream, Writable {
public var bufferSize: Int = 1024
public func write(bytes: [UInt8], length: Int) -> Int {
guard let file = self.descriptor else { return -1 }
let slice = length == bytes.count ? bytes : [UInt8](bytes[0..<length])
var bufSize = self.bufferSize
var written = 0, len = 0
repeat {
let s: [UInt8]
if length == written {
break
} else if length - written < bufSize {
bufSize = 1
}
if length - written == 1 {
s = [slice[written]]
} else {
s = [UInt8](slice[written..<(written + bufSize)])
}
let buf = UnsafePointer<UInt8>(s)
len = fwrite(buf, sizeof(UInt8), bufSize, file)
if len == -1 { return -1 }
written += len
} while written <= length && len != 0
return written
}
public func write(bytes:UnsafeMutablePointer<UInt8>, length:Int) -> Int {
guard let file = self.descriptor else { return -1 }
return Darwin.fwrite(bytes, sizeof(UInt8), length, file)
}
public func write<T: SequenceType where T.Generator.Element == UInt8>(bytes:T, length:Int) -> Int {
guard let file = self.descriptor else { return -1 }
var bufSize = self.bufferSize
bufSize = bufSize > length ? length : bufSize
var buf = [UInt8](count: bufSize, repeatedValue: 0)
var i = 0, ii = 0, written = 0
for item in bytes {
if ii < bufSize && i != length {
buf[ii++] = item
}
if bufSize == ii || i == length {
if ii == bufSize {
written += fwrite(&buf, sizeof(UInt8), bufSize, file)
}
ii = 0
}
if i == length {
break
}
i++
let diff = length - written
if diff < bufSize && diff > 0 {
bufSize = diff
buf = [UInt8](count: bufSize, repeatedValue: 0)
}
}
return written
}
public init?(_ path: String, binary: Bool = true, append: Bool = false) {
super.init(path: path)
do {
try self.open(binary, append: append)
} catch {
return nil
}
}
public func open(binary: Bool = true, append: Bool = false) throws {
let mode = (append ? "a" : "w") + (binary ? "b" : "")
try super.open(mode)
}
public func flush () {
guard let file = self.descriptor else { return }
Darwin.fflush(file)
}
override public func close() {
self.flush()
super.close()
}
}
| mit | 1bb0d15e9ed7a5fb6ff3cbff9a2b6fb9 | 26.830508 | 103 | 0.479294 | 4.535912 | false | false | false | false |
ufogxl/MySQLTest | Sources/getTimeTable.swift | 1 | 3064 | //
// getFullTimeTable.swift
// GoodStudent
//
// Created by ufogxl on 2016/12/2.
//
// 可以用来获取整张课程表:)
import Foundation
import PerfectLib
import PerfectHTTP
import MySQL
import ObjectMapper
fileprivate let container = ResponseContainer()
fileprivate let errorContent = ErrorContent()
fileprivate var user_info = NSDictionary()
func getTimeTable(_ request:HTTPRequest,response:HTTPResponse){
let params = request.params()
phaseParams(params: params)
if !paramsValid(){
let errorStr = "参数错误"
errorContent.code = ErrCode.ARGUMENT_ERROR.hashValue
container.message = errorStr
container.data = errorContent
container.result = false
response.appendBody(string:container.toJSONString(prettyPrint: true)!)
response.completed()
return
}
if let timeTable = getTimeTable(){
container.data = timeTable
container.result = true
container.message = "获取成功!"
response.appendBody(string: container.toJSONString(prettyPrint: true)!)
response.completed()
}else{
errorContent.code = ErrCode.SERVER_ERROR.hashValue
errorContent.message = "服务器异常,请稍后再试!"
container.data = errorContent
container.result = false
container.message = "获取成功!"
response.appendBody(string: container.toJSONString(prettyPrint: true)!)
response.completed()
}
}
fileprivate func phaseParams(params:[(String,String)]){
let info = NSMutableDictionary()
for pair in params{
info.setObject(pair.1, forKey: NSString(string:pair.0))
}
user_info = info as NSDictionary
}
fileprivate func paramsValid() -> Bool{
return true
}
fileprivate func getTimeTable() -> TimeTable?{
var table = [Course]()
let timetable = TimeTable()
let mysql = MySQL()
let connected = mysql.connect(host: db_host, user: db_user, password: db_password, db: database, port: db_port)
guard connected else {
print(mysql.errorMessage())
return nil
}
defer {
mysql.close()
}
var courses = [Course]()
let weekday = Int(user_info["weekday"] as! String)!
let statement = "select c_num,c_name,time,place,teacher from (select * from stujoincou where time between \((weekday-1) * 5 + 1) and \((weekday - 1) * 5 + 5)) as xx where s_num=\(user_info["username"] as! String) order by time"
let querySuccess = mysql.query(statement: statement)
guard querySuccess else {
return nil
}
let results = mysql.storeResults()
while let row = results?.next(){
let course = Course()
course.num = row[0]!
course.name = row[1]!
course.time = getClassTime(which: Int(row[2]!)!)
course.place = row[3]!
course.teacher = row[4]!
courses.append(course)
}
timetable.table = courses
timetable.week = time.numberOfWeek
return timetable
}
| apache-2.0 | b5d043756522124d46393b121fcf7031 | 26.703704 | 231 | 0.637366 | 4.256046 | false | false | false | false |
CoderXiaoming/Ronaldo | SaleManager/SaleManager/Order/Controller/SAMOrderOwedOperationController.swift | 1 | 41966 | //
// SAMOrderOwedOperationController.swift
// SaleManager
//
// Created by apple on 16/12/16.
// Copyright © 2016年 YZH. All rights reserved.
//
import UIKit
import MBProgressHUD
///控制器类型枚举定义
enum OrderOwedOperationControllerType {
case buildOrder //创建订单
case checkOrder //查看订单
case buildOwe //创建缺货登记
case checkOwe //查看缺货登记
}
///小cell重用标识符
fileprivate let SAMOrderBuildSmallCellReuseIdentifier = "SAMOrderBuildSmallCellReuseIdentifier"
///大cell重用标识符
fileprivate let SAMOrderBuildBigCellReuseIdentifier = "SAMOrderBuildBigCellReuseIdentifier"
class SAMOrderOwedOperationController: UIViewController {
///缺货登记新建单例
static let owedBuildInstance: SAMOrderOwedOperationController = {
let vc = SAMOrderOwedOperationController()
vc.hidesBottomBarWhenPushed = true
vc.controllerType = OrderOwedOperationControllerType.buildOwe
return vc
}()
//MARK: - 对外提供的类方法,接收产品数据模型,添加到订单中
class func buildOrder(productModels: [SAMShoppingCarListModel]?, type: OrderOwedOperationControllerType) -> SAMOrderOwedOperationController {
let vc = SAMOrderOwedOperationController()
vc.controllerType = type
vc.productToOrderModels = productModels
vc.hidesBottomBarWhenPushed = true
return vc
}
//MARK: - 对外提供的类方法,接收产品数据模型,查询订单
class func checkOrder(orderInfoModel: SAMOrderModel, type: OrderOwedOperationControllerType) -> SAMOrderOwedOperationController {
let vc = SAMOrderOwedOperationController()
vc.controllerType = type
vc.orderInfoModel = orderInfoModel
vc.productToOrderModels = orderInfoModel.productListModels
//记录控制器状态
vc.couldEdit = (orderInfoModel.isAgreeSend! != "是")
vc.hidesBottomBarWhenPushed = true
return vc
}
//MARK: - 对外提供的类方法,接收库存产品数据模型,新建缺货登记
class func buildOwe(productModel: SAMStockProductModel, type: OrderOwedOperationControllerType) -> SAMOrderOwedOperationController {
owedBuildInstance.controllerType = type
owedBuildInstance.stockModel = productModel
return owedBuildInstance
}
//MARK: - 对外提供的类方法,接收缺货登记数据模型,查看缺货登记
class func checkOwe(oweInfoModel: SAMOwedInfoModel, type: OrderOwedOperationControllerType) -> SAMOrderOwedOperationController {
let vc = SAMOrderOwedOperationController()
vc.oweModel = oweInfoModel
//记录控制器状态
vc.controllerType = type
vc.couldEdit = (oweInfoModel.iState == "欠货中") ? true : false
vc.hidesBottomBarWhenPushed = true
return vc
}
//MARK: - 根据不同控制器类型执行不同的事情(四种)
fileprivate func performByControllerType(buildOrder: (()->())?, checkOrder: (()->())?, buildOwe: (()->())?, checkOwe: (()->())?) {
switch controllerType! {
case OrderOwedOperationControllerType.buildOrder:
if buildOrder != nil {
buildOrder!()
}else {
break
}
case OrderOwedOperationControllerType.checkOrder:
if checkOrder != nil {
checkOrder!()
}else {
break
}
case OrderOwedOperationControllerType.buildOwe:
if buildOwe != nil {
buildOwe!()
}else {
break
}
case OrderOwedOperationControllerType.checkOwe:
if checkOwe != nil {
checkOwe!()
}else {
break
}
}
}
//MARK: - viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
//设置主要数据
setupMainInfo()
//初始化UI
setupUI()
//初始化设置tableView
setupTableView()
//初始化设置通知
setupNotification()
}
//MARK: - viewWillAppear,修改后返回界面刷新数据
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if controllerType! == .buildOwe {
setupMainInfo()
}
tableView.reloadData()
}
//MARK: - 设置主要数据
fileprivate func setupMainInfo() {
//如果是新建缺货登记
if (controllerType! == .buildOwe) && (titleModels != nil) {
let titleModel = titleModels![1][0]! as SAMOrderBuildTitleModel
titleModel.cellContent = stockModel!.productIDName
return
}
//设置title,请求路径
performByControllerType(buildOrder: {
self.titles = [[["客户", ""], ["备注", ""], ["业务员", "不选择默认自己"]], [["666", "666"]], [["优惠", "0"], ["其他金额", "0"], ["总金额", "0"], ["已收定金", "0"]]]
self.saveUrlStr = "OrderBillAdd.ashx"
let model = SAMOrderBuildEmployeeModel()
model.employeeID = ""
model.name = ""
self.orderBuildEmployeeModel = model
}, checkOrder: {
self.titles = self.orderInfoModel!.orderDetailContentArr
self.saveUrlStr = "OrderBillEdit.ashx"
//设置用户
self.orderCustomerModel = self.orderInfoModel?.orderCustomerModel!
}, buildOwe: {
let date = Date().beforeOrAfter(3, before: false)
let disStr = date.yyyyMMddStr()
self.titles = [[["客户", ""], ["交货日期", disStr]], [["产品型号", self.stockModel!.productIDName], ["匹数", "0"], ["米数", "0"], ["备注", ""]]]
self.saveUrlStr = "OOSRecordAdd.ashx"
}) {
self.titles = [[["客户", self.oweModel!.CGUnitName], ["交货日期", self.oweModel!.endDate]], [["产品型号", self.oweModel!.productIDName], ["匹数", String(format: "%d", self.oweModel!.countP)], ["米数", String(format: "%.1f", self.oweModel!.countM)], ["备注", self.oweModel!.memoInfo]], [["状态", self.oweModel!.iState]]]
self.saveUrlStr = "OOSRecordEdit.ashx"
//设置用户
self.orderCustomerModel = self.oweModel?.orderCustomerModel!
//设置产品数据模型
self.stockModel = self.oweModel?.stockModel!
}
//创建数据模型数组
titleModels = [[SAMOrderBuildTitleModel?]]()
for section in 0...(titles!.count - 1) {
//获取当前标题小数组
let strArrArr = titles![section] as [[String?]]
//如果数组为空返回
if strArrArr[0][0] == "666" {
titleModels!.append([SAMOrderBuildTitleModel.titleModel(title: "666", content: "666")])
}else {
//遍历数组,创建数据源数组
var modelArr = [SAMOrderBuildTitleModel?]()
for item in 0...(strArrArr.count - 1) {
let strArr = strArrArr[item]
let model = SAMOrderBuildTitleModel.titleModel(title: strArr[0]!, content: strArr[1])
modelArr.append(model)
}
titleModels!.append(modelArr)
}
}
}
//MARK: - 初始化UI
fileprivate func setupUI() {
//新建缺货登记采取单例,新加以下判断
if (controllerType! == .buildOwe) && (saveAndAgreeSendButtonWidth.constant) == -(ScreenW + 1) {
return
}
performByControllerType(buildOrder: {
//隐藏编辑按钮父控件
self.editBtnView.isHidden = true
self.navigationItem.title = "新建订单"
}, checkOrder: {
//展示编辑按钮父控件
self.editBtnView.isHidden = false
if self.orderInfoModel!.isAgreeSend! != "是" { //还未发货
self.navigationItem.title = "订单详情(未发货)"
}else { //已发货
self.saveEditButton.isEnabled = false
self.deleteButton.isEnabled = false
self.navigationItem.title = "订单详情(已发货)"
}
}, buildOwe: {
//隐藏编辑按钮父控件
self.editBtnView.isHidden = true
self.saveAndAgreeSendButtonWidth.constant = -(ScreenW + 1)
self.navigationItem.title = "缺货登记"
}) {
//展示编辑按钮父控件
self.editBtnView.isHidden = false
self.saveEditButton.isEnabled = self.couldEdit
self.navigationItem.title = "缺货详情"
}
//设置返回按钮
let backItem = UIBarButtonItem()
backItem.title = ""
navigationItem.backBarButtonItem = backItem
}
//MARK: - 初始化设置tableView
fileprivate func setupTableView() {
tableView.showsVerticalScrollIndicator = false
tableView.dataSource = self
tableView.delegate = self
//注册CELL
tableView.register(UINib.init(nibName: "SAMOrderBuildSmallCell", bundle: nil), forCellReuseIdentifier: SAMOrderBuildSmallCellReuseIdentifier)
tableView.register(UINib.init(nibName: "SAMOrderBuildBigCell", bundle: nil), forCellReuseIdentifier: SAMOrderBuildBigCellReuseIdentifier)
}
//MARK: - 监听的三个方法
fileprivate func setupNotification() {
//监听成功选择用户的通知
NotificationCenter.default.addObserver(self, selector: #selector(SAMOrderOwedOperationController.customerVCDidSelectCustomer(notification:)), name: NSNotification.Name.init(SAMCustomerViewControllerDidSelectCustomerNotification), object: nil)
//监听成功获取购物车模型的通知
NotificationCenter.default.addObserver(self, selector: #selector(SAMOrderOwedOperationController.productOperationViewGetModelSuccess(notification:)), name: NSNotification.Name.init(SAMProductOperationViewGetShoppingCarListModelNotification), object: nil)
}
//成功选择客户通知的监听
func customerVCDidSelectCustomer(notification: NSNotification) {
//赋值用户模型
orderCustomerModel = notification.userInfo!["customerModel"] as? SAMCustomerModel
if orderCustomerModel == nil {
//设置按钮状态
saveButton.isEnabled = false
saveAndAgreeSendButton.isEnabled = false
return
}
//赋值用户名
let orderTitleModel = self.titleModels![0][0]!
orderTitleModel.cellContent = orderCustomerModel!.CGUnitName
//设置按钮状态
saveButton.isEnabled = true
saveAndAgreeSendButton.isEnabled = true
//刷新数据
tableView.reloadRows(at: [IndexPath(item: 0, section: 0)], with: .none)
}
//成功获取购物车数据模型通知的监听
func productOperationViewGetModelSuccess(notification: NSNotification) {
//添加购物车模型
let model = notification.userInfo!["model"] as! SAMShoppingCarListModel
if productToOrderModels == nil {
productToOrderModels = [SAMShoppingCarListModel]()
}
productToOrderModels!.append(model)
//刷新数据
tableView.reloadData()
}
//MARK: - 更新统计数据
fileprivate func updateCountData() {
if productToOrderModels != nil {
//清空数组
productSectionCountArr.removeAll()
var countMashu = 0.0
var countMishu = 0.0
var countPrice = 0.0
for model in productToOrderModels! {
countMashu += model.countMA
countMishu += model.countM
countPrice += model.countPrice
}
productSectionCountArr.append(countMashu)
productSectionCountArr.append(countMishu)
productSectionCountArr.append(countPrice)
productSectionFooterView.countArr = productSectionCountArr
}
}
//MARK: - 用户点击事件处理
@IBAction func saveAndAgreeSendBtnClick(_ sender: Any) {
saveAndAgreeSend(isAgreeSend: true)
}
@IBAction func saveBtnClick(_ sender: Any) {
//判断权限
if (controllerType! == OrderOwedOperationControllerType.buildOwe) && !hasOwedXZAuth {
_ = SAMHUD.showMessage("暂无权限", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
return
}
saveAndAgreeSend(isAgreeSend: false)
}
///发货两个按钮共同点击
fileprivate func saveAndAgreeSend(isAgreeSend: Bool) {
//如果是新建订单类型,对productToOrderModels进行判断
if (controllerType! == OrderOwedOperationControllerType.buildOrder) && productToOrderModels == nil{
_ = SAMHUD.showMessage("请添加产品", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
return
}
//创建主请求参数
var MainData: [String: String]?
let CGUnitID = orderCustomerModel!.id
let dateStr = Date().yyyyMMddStr()
let userID = SAMUserAuth.shareUser()!.id!
switch controllerType! {
case OrderOwedOperationControllerType.buildOrder, OrderOwedOperationControllerType.checkOrder:
var employeeID = SAMUserAuth.shareUser()!.employeeID!
let memoInfo = self.titleModels![0][1]!.cellContent
let cutMoney = self.titleModels![2][0]!.cellContent
let otherMoney = self.titleModels![2][1]!.cellContent
let totalMoney = self.titleModels![2][2]!.cellContent
let receiveMoney = self.titleModels![2][3]!.cellContent
if (self.orderBuildEmployeeModel?.name != "") && (self.orderBuildEmployeeModel != nil) {
employeeID = orderBuildEmployeeModel!.employeeID
}
MainData = ["startDate": dateStr, "CGUnitID": CGUnitID, "employeeID": employeeID, "memoInfo": memoInfo, "cutMoney": cutMoney, "otherMoney": otherMoney, "totalMoney": totalMoney, "receiveMoney": receiveMoney, "userID": userID]
case OrderOwedOperationControllerType.buildOwe, OrderOwedOperationControllerType.checkOwe:
let endDate = self.titleModels![0][1]!.cellContent
if endDate == "" {
let _ = SAMHUD.showMessage("交货日期不能为空", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
return
}
let productID = self.stockModel!.id
let countP = self.titleModels![1][1]!.cellContent
let countM = self.titleModels![1][2]!.cellContent
let memoInfo = self.titleModels![1][3]!.cellContent
MainData = ["CGUnitID": CGUnitID, "startDate": dateStr, "endDate": endDate, "productID": productID, "countP": countP, "countM": countM, "memoInfo": memoInfo, "userID": userID]
}
if controllerType! == OrderOwedOperationControllerType.checkOrder {
MainData!["billNumber"] = orderInfoModel!.billNumber!
}
if controllerType! == OrderOwedOperationControllerType.checkOwe {
MainData!["id"] = oweModel!.id
}
//转换为Json字符串
let mainJsonData = try! JSONSerialization.data(withJSONObject: MainData!, options: JSONSerialization.WritingOptions.prettyPrinted)
let mainJsonStr = String(data: mainJsonData, encoding: String.Encoding.utf8)!
//创建产品请求参数,和最终请求参数
var detailJsonStr: String?
var parameters: [String: String]?
if controllerType == OrderOwedOperationControllerType.buildOrder || controllerType == OrderOwedOperationControllerType.checkOrder {
let DetailData = NSMutableArray()
for model in productToOrderModels! {
let patemeter = ["id": model.id, "productIDName": model.productIDName, "countP": model.countP, "countM": model.countM, "price": model.price, "smallMoney": model.countPrice, "productStatus": "", "productID": model.productID, "memoInfo": model.memoInfo] as [String : Any]
DetailData.add(patemeter)
}
let detailJsonData = try! JSONSerialization.data(withJSONObject: DetailData, options: JSONSerialization.WritingOptions.prettyPrinted)
detailJsonStr = String(data: detailJsonData, encoding: String.Encoding.utf8)!
parameters = ["MainData": mainJsonStr, "DetailData": detailJsonStr!]
}else {
parameters = ["MainData": mainJsonStr]
}
//设置加载hud
let hud = SAMHUD.showAdded(to: KeyWindow, animated: true)
hud!.labelText = NSLocalizedString("正在保存...", comment: "HUD loading title")
//判断请求链接,直接同意发货
if isAgreeSend == true {
saveUrlStr = "OrderBillAddAgree.ashx"
}
//发送服务器请求
SAMNetWorker.sharedNetWorker().post(saveUrlStr!, parameters: parameters, progress: nil, success: {[weak self] (task, json) in
//隐藏HUD
hud?.hide(true)
//获取状态字符串
let Json = json as! [String: AnyObject]
let dict = Json["head"] as! [String: String]
let state = dict["status"]
if state == "success" { //保存成功
var showMessage = ""
if isAgreeSend == true {
showMessage = "发货成功"
}else {
showMessage = "保存成功"
}
let hud = SAMHUD.showMessage(showMessage, superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
hud?.delegate = self
}else { //保存失败
let _ = SAMHUD.showMessage("保存失败", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
}
}) { (task, error) in
//隐藏HUD
hud?.hide(true)
let _ = SAMHUD.showMessage("请检查网络", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
}
}
@IBAction func deleteBtnClick(_ sender: UIButton) {
//判断权限
if (controllerType! == OrderOwedOperationControllerType.checkOwe) && !hasOwedSCAuth {
_ = SAMHUD.showMessage("暂无权限", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
return
}
let alertVC = UIAlertController(title: "确定删除?", message: nil, preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
alertVC.addAction(UIAlertAction(title: "确定", style: .destructive, handler: { (_) in
//设置加载hud
let hud = SAMHUD.showAdded(to: KeyWindow, animated: true)!
hud.labelText = NSLocalizedString("请等待...", comment: "HUD loading title")
//设置请求参数,请求路径
var requestURLStr: String?
var parameters: [String: String]?
switch self.controllerType! {
case OrderOwedOperationControllerType.checkOrder:
requestURLStr = "OrderBillDelete.ashx"
parameters = ["billNumber": self.orderInfoModel!.billNumber!]
case OrderOwedOperationControllerType.checkOwe:
requestURLStr = "OOSRecordDelete.ashx"
parameters = ["id": self.oweModel!.id]
default:
break
}
SAMNetWorker.sharedNetWorker().get(requestURLStr!, parameters: parameters!, progress: nil, success: {[weak self] (task, json) in
//获取状态字符串
let Json = json as! [String: AnyObject]
let dict = Json["head"] as! [String: String]
let state = dict["status"]
if state == "success" { //删除成功
hud.hide(true)
let hud = SAMHUD.showMessage("删除成功", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
hud?.delegate = self
}else { //删除失败
hud.hide(true)
let _ = SAMHUD.showMessage("删除失败", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
}
}) { (task, error) in
hud.hide(true)
let _ = SAMHUD.showMessage("请检查网络", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
}
})
)
present(alertVC, animated: true, completion: nil)
}
@IBAction func saveEditBtnClick(_ sender: UIButton) {
//判断权限
if (controllerType! == OrderOwedOperationControllerType.checkOwe) && !hasOwedXGAuth {
_ = SAMHUD.showMessage("暂无权限", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
return
}
saveBtnClick(saveButton)
}
//MARK: - 属性懒加载
///控制器类型
fileprivate var controllerType: OrderOwedOperationControllerType?
///tableView标题、内容数组
fileprivate var titles: [[[String?]]]?
///标题cell的数据模型
fileprivate var titleModels: [[SAMOrderBuildTitleModel?]]?
///接收的购物车中物品模型
fileprivate var productToOrderModels: [SAMShoppingCarListModel]?
///当前查看的订单数据模型
fileprivate var orderInfoModel: SAMOrderModel?
///缺货登记新建接收的产品库存数据模型
fileprivate var stockModel: SAMStockProductModel?
///接收的缺货登记数据模型
fileprivate var oweModel: SAMOwedInfoModel?
///保存URL (新建保存,和编辑保存,其他URL在各自方法中)
fileprivate var saveUrlStr: String?
///当前是否可以编辑订单
fileprivate var couldEdit: Bool = true
///产品组footerView统计信息
fileprivate lazy var productSectionFooterView = SAMOrderProductSectionFooterView.instance()
///给产品组footerView提供的统计数字
fileprivate var productSectionCountArr = [Double]()
///接收的客户模型
fileprivate var orderCustomerModel: SAMCustomerModel?
///购物车编辑控件
fileprivate var productOperationView: SAMProductOperationView?
///展示购物车时,主界面添加的蒙版
fileprivate lazy var productOperationMaskView: UIView = {
let maskView = UIView(frame: UIScreen.main.bounds)
maskView.backgroundColor = UIColor.black
maskView.alpha = 0.0
//添加手势
let tap = UITapGestureRecognizer(target: self, action: #selector(SAMOrderOwedOperationController.hideProductOperationViewWhenMaskViewDidClick))
maskView.addGestureRecognizer(tap)
return maskView
}()
///业务员数据模型
fileprivate var orderBuildEmployeeModel: SAMOrderBuildEmployeeModel?
///缺货登记新增权限
fileprivate lazy var hasOwedXZAuth: Bool = SAMUserAuth.checkAuth(["QH_XZ_APP"])
///缺货登记修改权限
fileprivate lazy var hasOwedXGAuth: Bool = SAMUserAuth.checkAuth(["QH_XG_APP"])
///缺货登记删除权限
fileprivate lazy var hasOwedSCAuth: Bool = SAMUserAuth.checkAuth(["QH_SC_APP"])
//MARK: - XIB链接属性
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var saveBtnView: UIView!
@IBOutlet weak var saveButton: UIButton!
@IBOutlet weak var saveAndAgreeSendButton: UIButton!
@IBOutlet weak var editBtnView: UIView!
@IBOutlet weak var deleteButton: UIButton!
@IBOutlet weak var saveEditButton: UIButton!
@IBOutlet weak var saveAndAgreeSendButtonWidth: NSLayoutConstraint!
//MARK: - 其他方法
fileprivate init() { //重写该方法,为单例服务
super.init(nibName: nil, bundle: nil)
}
fileprivate override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
//从xib加载view
view = Bundle.main.loadNibNamed("SAMOrderOwedOperationController", owner: self, options: nil)![0] as! UIView
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
//MARK: - tableView数据源方法 UITableViewDataSource
extension SAMOrderOwedOperationController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
switch controllerType! {
case OrderOwedOperationControllerType.buildOrder, OrderOwedOperationControllerType.checkOrder:
self.updateCountData()
return titleModels!.count
case OrderOwedOperationControllerType.buildOwe, OrderOwedOperationControllerType.checkOwe:
return titleModels!.count
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch controllerType! {
case OrderOwedOperationControllerType.buildOrder, OrderOwedOperationControllerType.checkOrder:
if section == 1 { //产品列表组
return self.productToOrderModels?.count ?? 0
}else { //订单内容组
return self.titleModels![section].count
}
case OrderOwedOperationControllerType.buildOwe, OrderOwedOperationControllerType.checkOwe:
return self.titleModels![section].count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch controllerType! {
case OrderOwedOperationControllerType.buildOrder, OrderOwedOperationControllerType.checkOrder:
if indexPath.section == 1 { //产品列表组
let cell = tableView.dequeueReusableCell(withIdentifier: SAMOrderBuildBigCellReuseIdentifier, for: indexPath) as! SAMOrderBuildBigCell
//取出模型,传递模型
cell.productAddToOrderModel = productToOrderModels![indexPath.row] as SAMShoppingCarListModel
return cell
}else { //订单内容组
let cell = tableView.dequeueReusableCell(withIdentifier: SAMOrderBuildSmallCellReuseIdentifier, for: indexPath) as! SAMOrderBuildSmallCell
//取出模型,传递模型
cell.titleModel = titleModels![indexPath.section][indexPath.row]! as SAMOrderBuildTitleModel
//如果该订单已经发货,则不可编辑,或者最后一组不可编辑
if !couldEdit || (indexPath.section == titleModels!.count - 1) {
cell.setCellEditDisabledStyle()
}else {
cell.setCellEditEnabledStyle()
}
return cell
}
case OrderOwedOperationControllerType.buildOwe, OrderOwedOperationControllerType.checkOwe:
let cell = tableView.dequeueReusableCell(withIdentifier: SAMOrderBuildSmallCellReuseIdentifier, for: indexPath) as! SAMOrderBuildSmallCell
//取出模型,传递模型
cell.titleModel = titleModels![indexPath.section][indexPath.row]! as SAMOrderBuildTitleModel
//如果该订单已经发货,则不可编辑,或者是转台栏
if !couldEdit || cell.titleModel?.cellTitle == "状态" {
cell.setCellEditDisabledStyle()
}else {
cell.setCellEditEnabledStyle()
}
return cell
}
}
}
//MARK: - tableView代理 UITableViewDelegate
extension SAMOrderOwedOperationController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch controllerType! {
case OrderOwedOperationControllerType.buildOrder, OrderOwedOperationControllerType.checkOrder:
if indexPath.section == 1 { //产品列表组
return 50
}else { //订单内容组
return 44
}
case OrderOwedOperationControllerType.buildOwe, OrderOwedOperationControllerType.checkOwe:
return 44
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch controllerType! {
case OrderOwedOperationControllerType.buildOrder, OrderOwedOperationControllerType.checkOrder:
if section == 0 {
return 20
}else if section == 1 {
return 55
}else if section == 2 {
return 30
}else if section == 3 {
return 20
}else {
return 0
}
case OrderOwedOperationControllerType.buildOwe, OrderOwedOperationControllerType.checkOwe:
return 20
}
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == (titleModels!.count - 1) {
return 20
}else {
return 0
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//透明View
let clearView = UIView(frame: CGRect(x: 0, y: 0, width: ScreenW, height: 20))
clearView.backgroundColor = UIColor.clear
if controllerType! == OrderOwedOperationControllerType.buildOwe || controllerType! == OrderOwedOperationControllerType.checkOwe {
return clearView
}
if section == 1 {
let view = SAMOrderProductSectionHeaderView.instance(couldAddProduct: couldEdit)
view.delegate = self
return view
}else if section == 2 {
return productSectionFooterView
}else {
return clearView
}
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
//透明View
let clearView = UIView(frame: CGRect(x: 0, y: 0, width: ScreenW, height: 20))
clearView.backgroundColor = UIColor.clear
return clearView
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//如果当前不能编辑,则取消选中,返回
if !couldEdit {
tableView.deselectRow(at: indexPath, animated: false)
return
}
if ((indexPath.section == 1) && (controllerType == OrderOwedOperationControllerType.buildOrder || controllerType == OrderOwedOperationControllerType.checkOrder)) { //点击了产品组
tableView.deselectRow(at: indexPath, animated: true)
}else if indexPath.section == 3 { //查看订单组中 日期、开单人。。。这组信息
tableView.deselectRow(at: indexPath, animated: true)
}else {
//点击cell的标题
let cellTitle = titleModels![indexPath.section][indexPath.row]!.cellTitle
if (cellTitle == "状态") || (cellTitle == "产品型号") {
tableView.deselectRow(at: indexPath, animated: true)
}else if cellTitle == "客户" {
navigationController!.pushViewController(SAMCustomerViewController.instance(controllerType: .OrderBuild), animated: true)
}else {
//取出模型,跳转编辑界面
let model = titleModels![indexPath.section][indexPath.row]!
let editVC = SAMOrderInfoEditController.editInfo(orderTitleModel: model, employeeModel: orderBuildEmployeeModel)
navigationController!.pushViewController(editVC, animated: true)
}
}
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { //这个方法要进行设置,不然其他行也可以左滑
if controllerType! == OrderOwedOperationControllerType.buildOwe || controllerType! == OrderOwedOperationControllerType.checkOwe {
return .none
}
if !couldEdit {
return .none
}
if indexPath.section != 1 {
return .none
}
return .delete
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
if controllerType! == OrderOwedOperationControllerType.buildOwe || controllerType! == OrderOwedOperationControllerType.checkOwe {
return nil
}
if indexPath.section == 1 {
//取出cell
let cell = tableView.cellForRow(at: indexPath) as! SAMOrderBuildBigCell
//取出对应模型
let model = cell.productAddToOrderModel!
/******************* 查询按钮 ********************/
let equiryAction = UITableViewRowAction(style: .normal, title: "查询") { (action, indexPath) in
let stockVC = SAMStockViewController.instance(shoppingCarListModel: model, QRCodeScanStr: nil, type: .requestStock)
self.navigationController?.pushViewController(stockVC, animated: true)
}
equiryAction.backgroundColor = UIColor(red: 0, green: 255 / 255.0, blue: 127 / 255.0, alpha: 1.0)
/******************* 编辑按钮 ********************/
let editAction = UITableViewRowAction(style: .default, title: "编辑") { (action, indexPath) in
self.showShoppingCar(editModel: model)
}
editAction.backgroundColor = customBlueColor
/******************* 删除按钮 ********************/
let deleteAction = UITableViewRowAction(style: .normal, title: "删除") { (action, indexPath) in
//获取数据模型对应的数组编号
let index = self.productToOrderModels!.index(of: model)!
//从源数组中删除
self.productToOrderModels!.remove(at: index)
//动画删除该行CELL
self.tableView.deleteRows(at: [IndexPath(row: index, section: 1)], with: .left)
}
deleteAction.backgroundColor = UIColor(red: 255 / 255.0, green: 69 / 255.0, blue: 0, alpha: 1.0)
//如果只有这组只有一个产品了,不显示删除按钮
if self.productToOrderModels!.count == 1 {
return [editAction, equiryAction]
}else {
return [editAction, equiryAction, deleteAction]
}
}else {
return nil
}
}
}
//MARK: - 购物车代理SAMProductOperationViewDelegate
extension SAMOrderOwedOperationController: SAMProductOperationViewDelegate {
func operationViewDidClickDismissButton() {
//隐藏购物车
hideProductOperationView(false)
}
func operationViewAddOrEditProductSuccess(_ productImage: UIImage, postShoppingCarListModelSuccess: Bool) {
//隐藏购物车
hideProductOperationView(true)
}
}
//MARK: - 购物车相关方法
extension SAMOrderOwedOperationController {
//view的第一步动画
fileprivate func firstTran() -> CATransform3D {
var transform = CATransform3DIdentity
transform.m24 = -1/2000
transform = CATransform3DScale(transform, 0.9, 0.9, 1)
return transform
}
//view的第二步动画
fileprivate func secondTran() -> CATransform3D {
var transform = CATransform3DIdentity
transform = CATransform3DTranslate(transform, 0, self.view.frame.size.height * (-0.08), 0)
transform = CATransform3DScale(transform, 0.8, 0.8, 1)
return transform
}
//点击maskView隐藏购物车控件
func hideProductOperationViewWhenMaskViewDidClick() {
hideProductOperationView(false)
}
//展示购物车
func showShoppingCar(editModel: SAMShoppingCarListModel) {
//设置购物车控件的目标frame
self.productOperationView = SAMProductOperationView.operationViewWillShow(nil, editProductModel: editModel, isFromeCheckOrder: true, postModelAfterOperationSuccess: false)
self.productOperationView!.delegate = self
self.productOperationView!.frame = CGRect(x: 0, y: ScreenH, width: ScreenW, height: 350)
var rect = self.productOperationView!.frame
rect.origin.y = ScreenH - rect.size.height
//添加背景View
self.tabBarController!.view.addSubview(self.productOperationMaskView)
KeyWindow?.addSubview(self.productOperationView!)
//动画展示购物车控件
UIView.animate(withDuration: 0.5, animations: {
self.productOperationView!.frame = rect
})
//动画移动背景View
UIView.animate(withDuration: 0.25, animations: {
//执行第一步动画
self.productOperationMaskView.alpha = 0.5
self.tabBarController!.view.layer.transform = self.firstTran()
}, completion: { (_) in
//执行第二步动画
UIView.animate(withDuration: 0.25, animations: {
self.tabBarController!.view.layer.transform = self.secondTran()
}, completion: { (_) in
})
})
}
//隐藏购物车控件
func hideProductOperationView(_ editSuccess: Bool) {
//结束 tableView 编辑状态
self.tableView.isEditing = false
//设置购物车目标frame
var rect = self.productOperationView!.frame
rect.origin.y = ScreenH
//动画隐藏购物车控件
UIView.animate(withDuration: 0.5, animations: {
self.productOperationView!.frame = rect
})
//动画展示主View
UIView.animate(withDuration: 0.25, animations: {
self.tabBarController!.view.layer.transform = self.firstTran()
self.productOperationMaskView.alpha = 0.0
}, completion: { (_) in
//移除蒙板
self.productOperationMaskView.removeFromSuperview()
UIView.animate(withDuration: 0.25, animations: {
self.tabBarController!.view.layer.transform = CATransform3DIdentity
}, completion: { (_) in
//移除购物车
self.productOperationView!.removeFromSuperview()
//调用成功添加购物车的动画
if editSuccess {
self.tableView.reloadData()
}
})
})
}
}
//MARK: - 监听HUD,看情况退出控制器
extension SAMOrderOwedOperationController: MBProgressHUDDelegate {
func hudWasHidden(_ hud: MBProgressHUD!) {
//退出控制器
navigationController!.popViewController(animated: true)
}
}
//MARK: - 产品组头部控件代理
extension SAMOrderOwedOperationController: SAMOrderProductSectionHeaderViewDelegate {
func headerViewDidClickAddBtn() {
let stockVC = SAMStockViewController.instance(shoppingCarListModel: nil, QRCodeScanStr: nil, type: .requestBuildOrder)
navigationController!.pushViewController(stockVC, animated: true)
}
func headerViewDidClickQRBtn() {
let QRCodeVC = LXMCodeViewController.instance(type: .buildOrder)
navigationController!.pushViewController(QRCodeVC, animated: true)
}
}
| apache-2.0 | 4d856533a1101dd2e6b10c4025fd8448 | 37.174805 | 313 | 0.589727 | 4.815349 | false | false | false | false |
kunass2/BSSelectableView | SelectableView/Classes/SingleSelectableView.swift | 2 | 3395 | //
// SingleSelectableView.swift
// SelectableView
//
// Created by Bartłomiej Semańczyk on 06/22/2016.
// Copyright (c) 2016 Bartłomiej Semańczyk. All rights reserved.
//
@IBDesignable open class SingleSelectableView: SelectableView, UITableViewDataSource, UITableViewDelegate {
@IBOutlet open var selectedOptionLabel: UILabel?
@IBInspectable open var hideOnSelect: Bool = true
open var selectedOption: SelectableOption? {
didSet {
setupLabel()
}
}
override var expanded: Bool {
didSet {
super.expanded = expanded
updateContentOptionsHeight(for: options)
}
}
//MARK: - Class Methods
//MARK: - Initialization
open override func awakeFromNib() {
super.awakeFromNib()
tableView.delegate = self
tableView.dataSource = self
}
//MARK: - Deinitialization
//MARK: - Actions
//MARK: - Open
//MARK: - Internal
func setupLabel() {
selectedOptionLabel?.numberOfLines = 0
selectedOptionLabel?.adjustsFontSizeToFitWidth = true
selectedOptionLabel?.minimumScaleFactor = 0.2
tableView.reloadData()
if selectedOption == nil {
selectedOptionLabel?.text = placeholder
selectedOptionLabel?.font = fontForPlaceholderText
selectedOptionLabel?.textColor = textColorForPlaceholderText
} else {
selectedOptionLabel?.text = selectedOption?.title
selectedOptionLabel?.font = fontForOption
selectedOptionLabel?.textColor = titleColorForOption
}
}
//MARK: - Private
//MARK: - Overridden
//MARK: - UITableViewDataSource
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sortedOptions.count
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: SelectableTableViewCellIdentifier, for: indexPath) as! SelectableTableViewCell
let option = sortedOptions[indexPath.row]
cell.titleLabel.text = option.title
cell.titleLabel.font = fontForOption
cell.titleLabel.textColor = option.identifier == selectedOption?.identifier ? titleColorForSelectedOption : titleColorForOption
cell.leftPaddingConstraint.constant = CGFloat(leftPaddingForOption)
cell.layoutMargins = UIEdgeInsets.zero
cell.accessoryType = option.identifier == selectedOption?.identifier ? .checkmark : .none
cell.tintColor = tintColorForSelectedOption
cell.selectionStyle = .none
return cell
}
open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(heightForOption)
}
//MARK: - UITableViewDelegate
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedOption = sortedOptions[indexPath.row]
if hideOnSelect {
expanded = false
}
delegate?.singleSelectableView?(self, didSelect: selectedOption!)
}
}
| mit | 4f78c5a71bb6e5770319f982a5e65b6a | 29.276786 | 143 | 0.634326 | 5.586491 | false | false | false | false |
flypaper0/ethereum-wallet | ethereum-wallet/Classes/PresentationLayer/SendSettings/View/AbstracnCoin+Send.swift | 1 | 1321 | // Copyright © 2018 Conicoin LLC. All rights reserved.
// Created by Artur Guseinov
import Foundation
typealias Checkout = (amount: String, total: String, fiatAmount: String, fee: String)
extension AbstractCoin {
func amountString(with amount: Decimal) -> String {
switch type {
case .default:
return Ether(amount).amountString
case .token:
let tokenValue = TokenValue(amount, name: currency.name, iso: currency.iso, decimals: 0)
return tokenValue.amountString
}
}
func checkout(amount: Decimal, iso: String, fee: Decimal) -> Checkout {
let feeAmount = Ether(weiValue: fee)
let feeAmountString = feeAmount.amountString
let fiatAmount = Ether(amount)
let fiatAmountString = rateSource.fiatString(for: fiatAmount, in: iso)
switch type {
case .default:
let ethAmount = Ether(amount + fee.fromWei())
let ethAmountString = ethAmount.amountString
return (amount: fiatAmount.amountString, total: ethAmountString, fiatAmount: fiatAmountString, fee: feeAmountString)
case .token(let token):
let ethAmountString = FiatCurrencyFactory.amount(amount: amount, currency: token.balance)
return (amount: ethAmountString, total: ethAmountString, fiatAmount: fiatAmountString, fee: feeAmountString)
}
}
}
| gpl-3.0 | 2a37955b95e521af39f0b20fd439d45a | 31.195122 | 122 | 0.706818 | 4.04908 | false | false | false | false |
jpsim/DeckRocket | Source/Mac/MenuView.swift | 1 | 1830 | //
// MenuView.swift
// DeckRocket
//
// Created by JP Simard on 6/14/14.
// Copyright (c) 2014 JP Simard. All rights reserved.
//
import Cocoa
final class MenuView: NSView, NSMenuDelegate {
private var highlight = false
private let statusItem = NSStatusBar.system
.statusItem(withLength: NSStatusItem.variableLength)
// MARK: Initializers
init() {
super.init(frame: NSRect(x: 0, y: 0, width: 24, height: 24))
statusItem.view = self
setupMenu()
}
required convenience init(coder: NSCoder) {
self.init()
}
// MARK: Menu
private func setupMenu() {
menu = NSMenu()
menu?.autoenablesItems = false
menu?.addItem(withTitle: "Not Connected", action: nil, keyEquivalent: "")
menu?.item(at: 0)?.isEnabled = false
menu?.addItem(withTitle: "Send Slides", action: #selector(AppDelegate.sendSlides), keyEquivalent: "")
menu?.item(at: 1)?.isEnabled = false
menu?.addItem(withTitle: "Quit DeckRocket", action: #selector(AppDelegate.quit), keyEquivalent: "")
menu?.delegate = self
}
override func mouseDown(with theEvent: NSEvent) {
super.mouseDown(with: theEvent)
if let menu = menu {
statusItem.popUpMenu(menu)
}
}
func menuWillOpen(_ menu: NSMenu) {
highlight = true
needsDisplay = true
}
func menuDidClose(_ menu: NSMenu) {
highlight = false
needsDisplay = true
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
statusItem.drawStatusBarBackground(in: dirtyRect, withHighlight: highlight)
"🚀".draw(in: dirtyRect.offsetBy(dx: 4, dy: -1),
withAttributes: [NSAttributedString.Key.font: NSFont.menuBarFont(ofSize: 14)])
}
}
| mit | 786d29b3cbba8151faeb9d512acf55fb | 27.107692 | 109 | 0.617953 | 4.288732 | false | false | false | false |
naokits/my-programming-marathon | ReachabilityDemo/ReachabilityDemo/ViewController.swift | 1 | 2359 | //
// ViewController.swift
// ReachabilityDemo
//
// Created by Naoki Tsutsui on 1/12/16.
// Copyright © 2016 Naoki Tsutsui. All rights reserved.
//
import UIKit
import ReachabilitySwift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// setupNotification()
}
override func viewDidAppear(animated: Bool) {
setupNotification()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Setup
/// 通知のセットアップ
func setupNotification() {
guard let reachability = reachability else {
print("Reachabilty is not available.")
return
}
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "reachabilityChanged:",
name: ReachabilityChangedNotification,
object: reachability)
do {
try reachability.startNotifier()
} catch {
print("Unable start Notifier")
}
}
// MARK: - Notification Selector
func reachabilityChanged(note: NSNotification) {
let reachability = note.object as! Reachability
if reachability.isReachable() {
if reachability.isReachableViaWiFi() {
self.showAlertMessage("Reachable via WiFi")
} else {
self.showAlertMessage("Reachable via Cellular")
}
} else {
self.showAlertMessage("Not reachable")
}
}
// MARK: - Alert Message
func showAlertMessage(message: String!) {
let title = "接続状態が変化しました"
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
dispatch_async(dispatch_get_main_queue(), {
// UIの操作はメインスレッドで実行する必要がある
self.presentViewController(alertController, animated: true, completion: nil)
})
}
}
| mit | 2fc3ad0b06c88b56af9c739054c09007 | 26.421687 | 103 | 0.605888 | 5.256351 | false | false | false | false |
dnseitz/YAPI | YAPI/YAPI/V3/Models/YelpPrice.swift | 1 | 539 | //
// YelpPrice.swift
// YAPI
//
// Created by Daniel Seitz on 11/11/17.
// Copyright © 2017 Daniel Seitz. All rights reserved.
//
import Foundation
public enum YelpPrice: Int {
case one = 1
case two = 2
case three = 3
case four = 4
case five = 5
public init?(withDollarSigns string: String) {
let trimmed = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
guard trimmed.contains(where: { $0 != "$" }) == false else {
return nil
}
self.init(rawValue: trimmed.count)
}
}
| mit | aa1f84a51cc8d4296cc3b67d1b108d8f | 19.692308 | 84 | 0.64684 | 3.610738 | false | false | false | false |
LYM-mg/MGDS_Swift | MGDS_Swift/Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager+UIKeyboardNotification.swift | 2 | 13371 | //
// IQKeyboardManager+UIKeyboardNotification.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-20 Iftekhar Qurashi.
//
// 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 - UIKit contains Foundation
import UIKit
// MARK: UIKeyboard Notifications
@available(iOSApplicationExtension, unavailable)
public extension IQKeyboardManager {
private struct AssociatedKeys {
static var keyboardShowing = "keyboardShowing"
static var keyboardShowNotification = "keyboardShowNotification"
static var keyboardFrame = "keyboardFrame"
static var animationDuration = "animationDuration"
static var animationCurve = "animationCurve"
}
/**
Boolean to know if keyboard is showing.
*/
@objc private(set) var keyboardShowing: Bool {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.keyboardShowing) as? Bool ?? false
}
set(newValue) {
objc_setAssociatedObject(self, &AssociatedKeys.keyboardShowing, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/** To save keyboardWillShowNotification. Needed for enable keyboard functionality. */
internal var keyboardShowNotification: Notification? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.keyboardShowNotification) as? Notification
}
set(newValue) {
objc_setAssociatedObject(self, &AssociatedKeys.keyboardShowNotification, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/** To save keyboard rame. */
internal var keyboardFrame: CGRect {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.keyboardFrame) as? CGRect ?? .zero
}
set(newValue) {
objc_setAssociatedObject(self, &AssociatedKeys.keyboardFrame, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/** To save keyboard animation duration. */
internal var animationDuration: TimeInterval {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.animationDuration) as? TimeInterval ?? 0.25
}
set(newValue) {
objc_setAssociatedObject(self, &AssociatedKeys.animationDuration, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/** To mimic the keyboard animation */
internal var animationCurve: UIView.AnimationOptions {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.animationCurve) as? UIView.AnimationOptions ?? .curveEaseOut
}
set(newValue) {
objc_setAssociatedObject(self, &AssociatedKeys.animationCurve, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/* UIKeyboardWillShowNotification. */
@objc internal func keyboardWillShow(_ notification: Notification?) {
keyboardShowNotification = notification
// Boolean to know keyboard is showing/hiding
keyboardShowing = true
let oldKBFrame = keyboardFrame
if let info = notification?.userInfo {
// Getting keyboard animation.
if let curve = info[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt {
animationCurve = UIView.AnimationOptions(rawValue: curve).union(.beginFromCurrentState)
} else {
animationCurve = UIView.AnimationOptions.curveEaseOut.union(.beginFromCurrentState)
}
// Getting keyboard animation duration
animationDuration = info[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0.25
// Getting UIKeyboardSize.
if let kbFrame = info[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
keyboardFrame = kbFrame
showLog("UIKeyboard Frame: \(keyboardFrame)")
}
}
guard privateIsEnabled() else {
restorePosition()
topViewBeginOrigin = IQKeyboardManager.kIQCGPointInvalid
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******", indentation: 1)
// (Bug ID: #5)
if let textFieldView = textFieldView, topViewBeginOrigin.equalTo(IQKeyboardManager.kIQCGPointInvalid) {
// keyboard is not showing(At the beginning only). We should save rootViewRect.
rootViewController = textFieldView.parentContainerViewController()
if let controller = rootViewController {
if rootViewControllerWhilePopGestureRecognizerActive == controller {
topViewBeginOrigin = topViewBeginOriginWhilePopGestureRecognizerActive
} else {
topViewBeginOrigin = controller.view.frame.origin
}
rootViewControllerWhilePopGestureRecognizerActive = nil
topViewBeginOriginWhilePopGestureRecognizerActive = IQKeyboardManager.kIQCGPointInvalid
self.showLog("Saving \(controller) beginning origin: \(self.topViewBeginOrigin)")
}
}
//If last restored keyboard size is different(any orientation accure), then refresh. otherwise not.
if keyboardFrame.equalTo(oldKBFrame) == false {
//If textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if keyboardShowing,
let textFieldView = textFieldView,
textFieldView.isAlertViewTextField() == false {
// keyboard is already showing. adjust position.
optimizedAdjustPosition()
}
}
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
}
/* UIKeyboardDidShowNotification. */
@objc internal func keyboardDidShow(_ notification: Notification?) {
guard privateIsEnabled(),
let textFieldView = textFieldView,
let parentController = textFieldView.parentContainerViewController(), (parentController.modalPresentationStyle == UIModalPresentationStyle.formSheet || parentController.modalPresentationStyle == UIModalPresentationStyle.pageSheet),
textFieldView.isAlertViewTextField() == false else {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******", indentation: 1)
self.optimizedAdjustPosition()
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
}
/* UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */
@objc internal func keyboardWillHide(_ notification: Notification?) {
//If it's not a fake notification generated by [self setEnable:NO].
if notification != nil {
keyboardShowNotification = nil
}
// Boolean to know keyboard is showing/hiding
keyboardShowing = false
if let info = notification?.userInfo {
// Getting keyboard animation.
if let curve = info[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt {
animationCurve = UIView.AnimationOptions(rawValue: curve).union(.beginFromCurrentState)
} else {
animationCurve = UIView.AnimationOptions.curveEaseOut.union(.beginFromCurrentState)
}
// Getting keyboard animation duration
animationDuration = info[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0.25
}
//If not enabled then do nothing.
guard privateIsEnabled() else {
return
}
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******", indentation: 1)
//Commented due to #56. Added all the conditions below to handle WKWebView's textFields. (Bug ID: #56)
// We are unable to get textField object while keyboard showing on WKWebView's textField. (Bug ID: #11)
// if (_textFieldView == nil) return
//Restoring the contentOffset of the lastScrollView
if let lastScrollView = lastScrollView {
UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: { () -> Void in
if lastScrollView.contentInset != self.startingContentInsets {
self.showLog("Restoring contentInset to: \(self.startingContentInsets)")
lastScrollView.contentInset = self.startingContentInsets
lastScrollView.scrollIndicatorInsets = self.startingScrollIndicatorInsets
}
if lastScrollView.shouldRestoreScrollViewContentOffset, !lastScrollView.contentOffset.equalTo(self.startingContentOffset) {
self.showLog("Restoring contentOffset to: \(self.startingContentOffset)")
let animatedContentOffset = self.textFieldView?.superviewOfClassType(UIStackView.self, belowView: lastScrollView) != nil // (Bug ID: #1365, #1508, #1541)
if animatedContentOffset {
lastScrollView.setContentOffset(self.startingContentOffset, animated: UIView.areAnimationsEnabled)
} else {
lastScrollView.contentOffset = self.startingContentOffset
}
}
// TODO: restore scrollView state
// This is temporary solution. Have to implement the save and restore scrollView state
var superScrollView: UIScrollView? = lastScrollView
while let scrollView = superScrollView {
let contentSize = CGSize(width: max(scrollView.contentSize.width, scrollView.frame.width), height: max(scrollView.contentSize.height, scrollView.frame.height))
let minimumY = contentSize.height - scrollView.frame.height
if minimumY < scrollView.contentOffset.y {
let newContentOffset = CGPoint(x: scrollView.contentOffset.x, y: minimumY)
if scrollView.contentOffset.equalTo(newContentOffset) == false {
let animatedContentOffset = self.textFieldView?.superviewOfClassType(UIStackView.self, belowView: scrollView) != nil // (Bug ID: #1365, #1508, #1541)
if animatedContentOffset {
scrollView.setContentOffset(newContentOffset, animated: UIView.areAnimationsEnabled)
} else {
scrollView.contentOffset = newContentOffset
}
self.showLog("Restoring contentOffset to: \(self.startingContentOffset)")
}
}
superScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView
}
})
}
restorePosition()
//Reset all values
lastScrollView = nil
keyboardFrame = CGRect.zero
startingContentInsets = UIEdgeInsets()
startingScrollIndicatorInsets = UIEdgeInsets()
startingContentOffset = CGPoint.zero
// topViewBeginRect = CGRectZero //Commented due to #82
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
}
@objc internal func keyboardDidHide(_ notification: Notification) {
let startTime = CACurrentMediaTime()
showLog("****** \(#function) started ******", indentation: 1)
topViewBeginOrigin = IQKeyboardManager.kIQCGPointInvalid
keyboardFrame = CGRect.zero
let elapsedTime = CACurrentMediaTime() - startTime
showLog("****** \(#function) ended: \(elapsedTime) seconds ******", indentation: -1)
}
}
| mit | 536a6033b7ca4a1b401706de741565a4 | 42.983553 | 363 | 0.650288 | 6.097127 | false | false | false | false |
kodlian/AlamofireXMLRPC | Sources/AlamofireXMLRPC/Alamofire+XML.swift | 1 | 2459 | //
// Alanofire+XML.swift
// AlamofireXMLRPC
//
// Created by Jeremy Marchand on 08/10/2015.
// Copyright © 2015 kodlian. All rights reserved.
//
import Foundation
import AEXML
import Alamofire
extension DataRequest {
@discardableResult public func responseXML(
queue: DispatchQueue = .main,
dataPreprocessor: DataPreprocessor = XMLResponseSerializer.defaultDataPreprocessor,
emptyResponseCodes: Set<Int> = XMLResponseSerializer.defaultEmptyResponseCodes,
emptyRequestMethods: Set<HTTPMethod> = XMLResponseSerializer.defaultEmptyRequestMethods,
completionHandler: @escaping (AFDataResponse<AEXMLDocument>) -> Void
) -> Self {
response(
queue: queue,
responseSerializer: XMLResponseSerializer(
dataPreprocessor: dataPreprocessor,
emptyResponseCodes: emptyResponseCodes,
emptyRequestMethods: emptyRequestMethods
),
completionHandler: completionHandler)
}
}
public class XMLResponseSerializer: ResponseSerializer {
public let dataPreprocessor: DataPreprocessor
public let emptyResponseCodes: Set<Int>
public let emptyRequestMethods: Set<HTTPMethod>
public init(
dataPreprocessor: DataPreprocessor = XMLResponseSerializer.defaultDataPreprocessor,
emptyResponseCodes: Set<Int> = XMLResponseSerializer.defaultEmptyResponseCodes,
emptyRequestMethods: Set<HTTPMethod> = XMLResponseSerializer.defaultEmptyRequestMethods
) {
self.dataPreprocessor = dataPreprocessor
self.emptyResponseCodes = emptyResponseCodes
self.emptyRequestMethods = emptyRequestMethods
}
public func serialize(
request: URLRequest?,
response: HTTPURLResponse?,
data: Data?,
error: Error?
) throws -> AEXMLDocument {
guard error == nil else { throw error! }
guard var data = data, !data.isEmpty else {
guard emptyResponseAllowed(forRequest: request, response: response) else {
throw XMLRPCError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)
}
return AEXMLDocument()
}
data = try dataPreprocessor.preprocess(data)
do {
return try AEXMLDocument(xml: data)
} catch {
throw XMLRPCError.responseSerializationFailed(reason: .xmlSerializationFailed(error: error))
}
}
}
| mit | c14f2217e50b69e96ec20cd1ad36d2b7 | 33.619718 | 104 | 0.685924 | 5.331887 | false | false | false | false |
kenwilcox/LocalizationDemo | LocalizationDemo/ViewController.swift | 1 | 1582 | //
// ViewController.swift
// LocalizationDemo
//
// Created by Kenneth Wilcox on 2/14/15.
// Copyright (c) 2015 Kenneth Wilcox. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textLabel: UILabel!
@IBOutlet weak var numberLabel: UILabel!
@IBOutlet weak var currencyLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
populateValues()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func populateValues() {
textLabel.text = NSLocalizedString("GOOD_MORNING",comment:"Good Morning")
numberLabel.text = numberFormatter.stringFromNumber(9999999.999)
currencyLabel.text = currencyFormatter.stringFromNumber(50000)
dateLabel.text = dateFormatter.stringFromDate(NSDate())
imageView.image = UIImage(named: "hello")
}
var numberFormatter: NSNumberFormatter {
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
return formatter
}
var currencyFormatter: NSNumberFormatter {
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
return formatter
}
var dateFormatter: NSDateFormatter {
let formatter = NSDateFormatter()
formatter.dateStyle = .MediumStyle
formatter.timeStyle = .MediumStyle
return formatter
}
}
| mit | 9ab61eb95eae4c76e029e889a43a9e02 | 26.754386 | 77 | 0.72756 | 5.006329 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/WordPressTest/PostServiceUploadingListTests.swift | 1 | 1386 | import UIKit
import XCTest
import Nimble
@testable import WordPress
class PostServiceUploadingListTests: CoreDataTestCase {
/// Returns true if a single post is added to the list
///
func testReturnTrueForSingleUpload() {
let post = PostBuilder(mainContext).build()
let uploadingList = PostServiceUploadingList.shared
uploadingList.uploading(post.objectID)
expect(uploadingList.isSingleUpload(post.objectID)).to(beTrue())
}
/// Returns false if the same post is added twice to the list
///
func testReturnFalseForMultipleUpload() {
let post = PostBuilder(mainContext).build()
let uploadingList = PostServiceUploadingList.shared
uploadingList.uploading(post.objectID)
uploadingList.uploading(post.objectID)
expect(uploadingList.isSingleUpload(post.objectID)).to(beFalse())
}
/// If a post is added twice and then the upload of one finishes, return true
///
func testReturnTrueForMultipleUploadIfOneOfThemIsRemoved() {
let post = PostBuilder(mainContext).build()
let uploadingList = PostServiceUploadingList.shared
uploadingList.uploading(post.objectID)
uploadingList.uploading(post.objectID)
uploadingList.finishedUploading(post.objectID)
expect(uploadingList.isSingleUpload(post.objectID)).to(beTrue())
}
}
| gpl-2.0 | 36cbef4186ff6fce9e491b9e2a925d04 | 30.5 | 81 | 0.712843 | 4.8125 | false | true | false | false |
zhiquan911/SwiftChatKit | Pod/Classes/common/DateUtils.swift | 1 | 3956 | //
// DateUtils.swift
// SwiftChatKit
//
// Created by 麦志泉 on 15/9/6.
// Copyright (c) 2015年 CocoaPods. All rights reserved.
//
import Foundation
class DateUtils {
/**
显示友好事件
- parameter dateTime: “yyyy-MM-dd HH:mm:ss”时间
- returns:
*/
class func friendlyTime(dateTime: String) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "zh_CN")
dateFormatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd HH:mm:ss")
if let date = dateFormatter.dateFromString(dateTime) {
let delta = NSDate().timeIntervalSinceDate(date)
if (delta <= 0) {
return "刚刚"
}
else if (delta < 60) {
return "\(Int(delta))秒前"
}
else if (delta < 3600) {
return "\(Int(delta / 60))分钟前"
}
else {
let calendar = NSCalendar.currentCalendar()
let unitFlags: NSCalendarUnit = [NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute]
let comp = calendar.components(unitFlags, fromDate: NSDate())
let currentYear = String(comp.year)
let currentDay = String(comp.day)
let comp2 = calendar.components(unitFlags, fromDate: date)
let year = String(comp2.year)
let month = String(comp2.month)
let day = String(comp2.day)
var hour = String(comp2.hour)
var minute = String(comp2.minute)
if comp2.hour < 10 {
hour = "0" + hour
}
if comp2.minute < 10 {
minute = "0" + minute
}
if currentYear == year {
if currentDay == day {
return "今天 \(hour):\(minute)"
} else {
return "\(month)月\(day)日 \(hour):\(minute)"
}
} else {
return "\(year)年\(month)月\(day)日 \(hour):\(minute)"
}
}
}
return ""
}
/**
显示友好事件,用于聊天
- parameter dateTime: “yyyy-MM-dd HH:mm:ss”时间
- returns:
*/
class func friendlyTimeForChat(dateTime: NSDate?) -> String {
if let date = dateTime {
// let delta = NSDate().timeIntervalSinceDate(date)
let calendar = NSCalendar.currentCalendar()
let unitFlags: NSCalendarUnit = [NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute]
let comp = calendar.components(unitFlags, fromDate: NSDate())
let currentYear = String(comp.year)
let currentDay = String(comp.day)
let comp2 = calendar.components(unitFlags, fromDate: date)
let year = String(comp2.year)
let month = String(comp2.month)
let day = String(comp2.day)
var hour = String(comp2.hour)
var minute = String(comp2.minute)
if comp2.hour < 10 {
hour = "0" + hour
}
if comp2.minute < 10 {
minute = "0" + minute
}
if currentYear == year {
if currentDay == day {
return "今天 \(hour):\(minute)"
} else {
return "\(month)月\(day)日 \(hour):\(minute)"
}
} else {
return "\(year)年\(month)月\(day)日 \(hour):\(minute)"
}
}
return ""
}
}
| mit | 5b4a931f6f200581f6fcdb7753f451fe | 31.957265 | 155 | 0.4764 | 4.856423 | false | false | false | false |
DianQK/Flix | Example/Example/DoNotDisturbSettingsViewController.swift | 1 | 3477 | //
// DoNotDisturbSettingsViewController.swift
// Example
//
// Created by DianQK on 03/10/2017.
// Copyright © 2017 DianQK. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
import Flix
class DoNotDisturbSettingsViewController: CollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Do Not Disturb"
var providers: [_AnimatableCollectionViewMultiNodeProvider] = []
let doNotDisturbProvider = UniqueSwitchProvider()
doNotDisturbProvider.titleLabel.text = "Do Not Disturb"
providers.append(doNotDisturbProvider)
let doNotDisturbCommnetProvider = UniqueCommentTextProvider(
text: "When Do Not Disturb is enabled, calls and alerts that arrive while locked will be silenced, and a moon icon will appear in the status bar."
)
providers.append(doNotDisturbCommnetProvider)
let scheduledProvider = UniqueSwitchProvider()
scheduledProvider.titleLabel.text = "Scheduled"
providers.append(scheduledProvider)
let slienceTitleProvider = UniqueCommentTextProvider(
text: "SLIENCE"
)
providers.append(slienceTitleProvider)
enum SlienceMode: String, StringIdentifiableType, Equatable, CustomStringConvertible {
case always
case whileLocked
var identity: String {
return self.rawValue
}
var description: String {
switch self {
case .always:
return "Always"
case .whileLocked:
return "While iPhone is locked"
}
}
var comment: String {
switch self {
case .always:
return "Incoming calls and notifications will be silenced while iPhone is either locked or unlocked."
case .whileLocked:
return "Incoming calls and notifications will be silenced while iPhone is locked."
}
}
}
let radioProvider = RadioProvider(options: [SlienceMode.always, SlienceMode.whileLocked])
radioProvider.checkedOption.accept(SlienceMode.always)
providers.append(radioProvider)
let slienceCommentProvider = UniqueCommentTextProvider(
text: ""
)
radioProvider.checkedOption.asObservable()
.map { (option) -> String in
return option?.comment ?? ""
}
.bind(to: slienceCommentProvider.text)
.disposed(by: disposeBag)
providers.append(slienceCommentProvider)
let allowCallsFromTitleProvider = UniqueCommentTextProvider(
text: "PHONE"
)
providers.append(allowCallsFromTitleProvider)
let allowCallsFromProvider = UniqueTextProvider(
title: "Allow Calls From",
desc: "Everyone"
)
providers.append(allowCallsFromProvider)
let allowCallsFromCommentProvider = UniqueCommentTextProvider(
text: "When in Do Not Disturb, allow incoming calls from everyone."
)
providers.append(allowCallsFromCommentProvider)
self.collectionView.flix.animatable.build(providers)
}
}
| mit | bf97f32ea81c956abe63b74feee495a4 | 33.415842 | 158 | 0.60443 | 5.43125 | false | false | false | false |
Chaosspeeder/YourGoals | YourGoals/Business/Notifications/TaskNotificationScheduler.swift | 1 | 8572 | //
// TaskNotificationScheduler.swift
// YourGoals
//
// Created by André Claaßen on 26.03.18.
// Copyright © 2018 André Claaßen. All rights reserved.
//
import Foundation
import UserNotifications
struct TaskNotificationOverdueText {
/// creates a localized text for task overrunning with hours and minutes
///
/// - Parameters:
/// - hours: overdue in hours
/// - minutes: overdue in minutes
/// - Returns: a localized text strijng
static func textForTaskOverrunning(hours: Int, minutes: Int) -> String {
let text = hours == 0 ? L10n.theTimeForYourTaskIsOverrunning(minutes) : L10n.theTimeForYourTaskIsOverrunningInHours(hours)
return text
}
}
/// this class creates notification on started or stopped tasks
class TaskNotificationScheduler:TaskNotificationProviderProtocol {
/// the user notification center
let center:UNNotificationCenterProtocol
var overdueTimer:Timer? = nil
let overdueIntervalInMinutes = 15.0
/// initialize the task notification maanger with the user notification cente
///
/// - Parameter notificationCenter: default is UNUserNotificationCenter.current() or a UnitTest Mockup
init(notificationCenter:UNNotificationCenterProtocol, observer:TaskNotificationObserver) {
self.center = notificationCenter
setupNotificationActions()
observer.register(provider: self)
}
/// schedule a local notification for the task to inform the user about the remaining time
///
/// - Parameters:
/// - task: the task
/// - text: a notification text
/// - referenceTime: the reference date to calculate the notification time
/// - remainingTime: the remaining time for the task
func scheduleLocalNotification(forTask task:Task, withText text:String, referenceTime: Date, remainingTime: TimeInterval) {
let content = UNMutableNotificationContent(task: task, text: text)
let scheduleTime = referenceTime.addingTimeInterval(remainingTime);
let trigger = UNCalendarNotificationTrigger(fireDate: scheduleTime)
let request = UNNotificationRequest(identifier: text , content: content, trigger: trigger)
self.center.add(request, withCompletionHandler: nil)
}
/// schedule a local notification for a timer overrun
///
/// - Parameters:
/// - forTask: the task
/// - referenceTime: the reference datetime for calculating the notification time
/// - remainingTime: the remaining time of the task
/// - overdueInMinutes: the needed overdue reminder in Minutes
func scheduleTimerOverrunNotification(forTask task: Task, referenceTime: Date, remainingTime: TimeInterval, overdueInMinutes: Int) {
let hours = overdueInMinutes / 60
let minutes = overdueInMinutes % 60
let text = TaskNotificationOverdueText.textForTaskOverrunning(hours: hours, minutes: minutes)
scheduleLocalNotification(forTask: task, withText: text, referenceTime: referenceTime, remainingTime: remainingTime + Double(overdueInMinutes) * 60.0)
}
/// eliminate all notifications and stop overdue notifications
func resetNotifications() {
self.center.removeAllPendingNotificationRequests()
self.center.removeAllDeliveredNotifications()
if let timer = self.overdueTimer {
timer.invalidate()
}
self.overdueTimer = nil
}
/// setup the custom actions for all motivation card notifications
/// edit action for taking immediate input
/// delay action for delaying a motivation card
func setupNotificationActions() {
let needMoreTimeAction = UNNotificationAction(
identifier: TaskNotificationActionIdentifier.needMoreTime ,
title: "I need more time",
options: [])
let doneAction = UNNotificationAction(
identifier: TaskNotificationActionIdentifier.done ,
title: "I'm done'",
options: [])
let category = UNNotificationCategory(identifier: TaskNotificationCategory.taskNotificationCategory,
actions: [needMoreTimeAction, doneAction],
intentIdentifiers: [], options: [])
center.setNotificationCategories([category])
}
/// show depending notifications on log
func debugPendingNotifications() {
self.center.getPendingNotificationRequests { (requests) in
for r in requests {
NSLog("user local notification is pending: \(r.content.title)")
}
NSLog("+++ ready")
}
}
/// create a series of local push notifications for the task.
///
/// Push notifications for 50% of the task size, 10 and 5 minutes remaining time.
///
/// - Parameters:
/// - task: the task
/// - referenceTime: the reference time for calculations
func scheduleRemainingTimeNotifications(forTask task: Task, referenceTime:Date) {
let remainingTime = task.calcRemainingTimeInterval(atDate: referenceTime)
if task.size >= 30.0 {
scheduleLocalNotification(forTask: task, withText: L10n.youHaveReached50OfYourTimebox(50), referenceTime: referenceTime, remainingTime: remainingTime - Double(task.size / 2.0 * 60.0))
}
scheduleLocalNotification(forTask: task, withText: L10n.youHaveOnly10MinutesLeftForYourTask, referenceTime: referenceTime, remainingTime: remainingTime - (10.0 * 60.0))
scheduleLocalNotification(forTask: task, withText: L10n.youHaveOnly5MinutesLeftForYourTask, referenceTime: referenceTime, remainingTime: remainingTime - (5.0 * 60.0))
scheduleLocalNotification(forTask: task, withText: L10n.yourTimeIsUp, referenceTime: referenceTime, remainingTime: remainingTime)
scheduleTimerOverrunNotification(forTask: task, referenceTime: referenceTime, remainingTime: remainingTime, overdueInMinutes: 5)
scheduleTimerOverrunNotification(forTask: task, referenceTime: referenceTime, remainingTime: remainingTime, overdueInMinutes: 10)
scheduleTimerOverrunNotification(forTask: task, referenceTime: referenceTime, remainingTime: remainingTime, overdueInMinutes: 15)
scheduleTimerOverrunNotification(forTask: task, referenceTime: referenceTime, remainingTime: remainingTime, overdueInMinutes: 30)
scheduleTimerOverrunNotification(forTask: task, referenceTime: referenceTime, remainingTime: remainingTime, overdueInMinutes: 45)
scheduleTimerOverrunNotification(forTask: task, referenceTime: referenceTime, remainingTime: remainingTime, overdueInMinutes: 60)
scheduleTimerOverrunNotification(forTask: task, referenceTime: referenceTime, remainingTime: remainingTime, overdueInMinutes: 120)
scheduleTimerOverrunNotification(forTask: task, referenceTime: referenceTime, remainingTime: remainingTime, overdueInMinutes: 180)
scheduleTimerOverrunNotification(forTask: task, referenceTime: referenceTime, remainingTime: remainingTime, overdueInMinutes: 240)
scheduleTimerOverrunNotification(forTask: task, referenceTime: referenceTime, remainingTime: remainingTime, overdueInMinutes: 360)
}
// mark: - TaskNotificationProviderProtocol
/// create user local notifications for a freshly started task.
///
/// - Parameters:
/// - task: the task
/// - referenceTime: the reference date for calculation
/// - remainingTime: remaining time for the task. this is important for calculate the calendar trigger time
func progressStarted(forTask task: Task, referenceTime: Date) {
scheduleLocalNotification(forTask: task, withText: L10n.YourTaskIsStartet.doYourWork, referenceTime: referenceTime.addingTimeInterval(10.0), remainingTime: 0.0)
scheduleRemainingTimeNotifications(forTask: task, referenceTime: referenceTime)
}
/// inform the user about start and remaining time for a task
///
/// - Parameters:
/// - task: the task
/// - referenceTime: the reference time for the notification
func progressChanged(forTask task: Task, referenceTime: Date) {
resetNotifications()
scheduleRemainingTimeNotifications(forTask: task, referenceTime: referenceTime)
}
/// all progress is stoppped. kill all pending notifications
func progressStopped() {
// kill all notifications
resetNotifications()
}
func tasksChanged() {
}
}
| lgpl-3.0 | 4dce7907879d3b4cc3ab1cd6a085ec90 | 48.520231 | 195 | 0.705848 | 5.069231 | false | false | false | false |
PopcornTimeTV/PopcornTimeTV | PopcornTime/UI/iOS/Extensions/ShowsViewController+iOS.swift | 1 | 4647 |
import Foundation
import PopcornKit
extension ShowsViewController:UISearchBarDelegate,PCTPlayerViewControllerDelegate,UIViewControllerTransitioningDelegate{
func playerViewControllerPresentCastPlayer(_ playerViewController: PCTPlayerViewController) {
func playerViewControllerPresentCastPlayer(_ playerViewController: PCTPlayerViewController) {
dismiss(animated: true) // Close player view controller first.
let castPlayerViewController = storyboard?.instantiateViewController(withIdentifier: "CastPlayerViewController") as! CastPlayerViewController
castPlayerViewController.media = playerViewController.media
castPlayerViewController.localPathToMedia = playerViewController.localPathToMedia
castPlayerViewController.directory = playerViewController.directory
castPlayerViewController.url = playerViewController.url
castPlayerViewController.startPosition = TimeInterval(playerViewController.progressBar.progress)
present(castPlayerViewController, animated: true)
}
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
var magnetLink = searchBar.text! // get magnet link that is inserted as a link tag from the website
magnetLink = magnetLink.removingPercentEncoding!
//create the pseudo structures we need to conform to the rest of the torrents of the app
let userTorrent = Torrent.init(health: .excellent, url: magnetLink, quality: "1080p", seeds: 100, peers: 100, size: nil)
var title = magnetLink
if let startIndex = title.range(of: "dn="){
title = String(title[startIndex.upperBound...])
title = String(title[title.startIndex ... title.range(of: "&tr")!.lowerBound])
}
let magnetTorrentMedia = Movie.init(title: title, id: "34", tmdbId: nil, slug: "magnet-link", summary: "", torrents: [userTorrent], subtitles: [:], largeBackgroundImage: nil, largeCoverImage: nil)
let storyboard = UIStoryboard.main
let loadingViewController = storyboard.instantiateViewController(withIdentifier: "PreloadTorrentViewController") as! PreloadTorrentViewController
loadingViewController.transitioningDelegate = self
loadingViewController.loadView()
loadingViewController.titleLabel.text = magnetLink
self.present(loadingViewController, animated: true)
//Movie completion Blocks
let error: (String) -> Void = { (errorMessage) in
if self.presentedViewController != nil {
self.dismiss(animated: false)
}
let vc = UIAlertController(title: "Error".localized, message: errorMessage, preferredStyle: .alert)
vc.addAction(UIAlertAction(title: "OK".localized, style: .cancel, handler: nil))
self.present(vc, animated: true)
}
let finishedLoading: (PreloadTorrentViewController, UIViewController) -> Void = { (loadingVc, playerVc) in
let flag = UIDevice.current.userInterfaceIdiom != .tv
self.dismiss(animated: flag)
self.present(playerVc, animated: flag)
}
let selectTorrent: (Array<String>) -> Int32 = { (torrents) in
var selected = -1
let torrentSelection = UIAlertController(title: "Select file to play", message: nil, preferredStyle: .actionSheet)
for torrent in torrents{
torrentSelection.addAction(UIAlertAction(title: torrent, style: .default, handler: { _ in
selected = torrents.distance(from: torrents.startIndex, to: torrents.firstIndex(of: torrent)!)
}))
}
DispatchQueue.main.sync{
loadingViewController.present(torrentSelection, animated: true)
}
while selected == -1{print("hold") }
return Int32(selected)
}
//Movie player view controller calls
let playViewController = storyboard.instantiateViewController(withIdentifier: "PCTPlayerViewController") as! PCTPlayerViewController
playViewController.delegate = self
magnetTorrentMedia.play(fromFileOrMagnetLink: magnetLink, nextEpisodeInSeries: nil, loadingViewController: loadingViewController, playViewController: playViewController, progress: 0, errorBlock: error, finishedLoadingBlock: finishedLoading, selectingTorrentBlock: selectTorrent)
}
override func viewDidLoad() {
self.magnetLinkTextField.delegate = self
super.viewDidLoad()
}
}
| gpl-3.0 | 059df66a775e4e9f0b254d42384d74a3 | 52.413793 | 286 | 0.684528 | 5.772671 | false | false | false | false |
pkx0128/UIKit | MUILabel/MUILabel/ViewController.swift | 1 | 1634 | //
// ViewController.swift
// MUILabel
//
// Created by pankx on 2017/9/12.
// Copyright © 2017年 pankx. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//创建UILabel
let mLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 80))
//设置UILabel的位置
mLabel.center = view.center
//设置文字
mLabel.text = "MUILabel123456789abcdefghigk"
//设置颜色
mLabel.textColor = UIColor.orange
//设置字体与大小
mLabel.font = UIFont(name: "Helvetica-Light", size: 14)
//修改设置字体大小
mLabel.font = mLabel.font.withSize(20)
//使用系统字体并设置大小
mLabel.font = UIFont.systemFont(ofSize: 24)
//设置文字的位置居中
mLabel.textAlignment = .center
//设置内容文字的行数
mLabel.numberOfLines = 1
//文字过多时的显示方式
mLabel.lineBreakMode = .byTruncatingMiddle
//设置阴影的颜色
mLabel.shadowColor = UIColor.red
//设置阴影的偏移量
mLabel.shadowOffset = CGSize(width: 2, height: 2)
//设置背景颜色
mLabel.backgroundColor = UIColor.blue
view.addSubview(mLabel)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 27e18ac89c5f3513a903d3302b461f45 | 21.671875 | 79 | 0.560992 | 4.357357 | false | false | false | false |
LoganWright/Genome | Sources/GenomeCoreData/CoreData.swift | 1 | 1231 | #if !os(Linux)
import CoreData
extension NSManagedObjectContext : Context {}
open class ManagedObject: NSManagedObject, Genome.MappableBase {
public enum Error: Swift.Error {
case expectedManagedObjectContext
case unableToCreateObject
}
// MARK: EntityName
open class var entityName: String {
return "\(self)"
.characters
.split { $0 == "." }
.map(String.init)
.last ?? "\(self)"
}
// MARK: Sequence
open func sequence(_ map: Map) throws {}
}
extension MappableBase where Self: ManagedObject {
public init(node: Node, in context: Context) throws {
let map = Map(node: node, in: context)
self = try make(type: Self.self, with: map)
}
}
private func make<T: ManagedObject>(type: T.Type, with map: Map) throws -> T {
guard let context = map.context as? NSManagedObjectContext else {
throw T.Error.expectedManagedObjectContext
}
let entity = NSEntityDescription.entity(forEntityName: T.entityName, in: context)
guard let new = entity as? T else {
throw T.Error.unableToCreateObject
}
try new.sequence(map)
return new
}
#endif
| mit | ca6cfca1ef781f825a32b486eb52aa00 | 23.62 | 85 | 0.621446 | 4.380783 | false | false | false | false |
StevenUpForever/FBSimulatorControl | fbsimctl/FBSimulatorControlKitTests/Tests/Unit/ParserDescriptionTests.swift | 4 | 8171 | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import XCTest
import FBSimulatorControl
@testable import FBSimulatorControlKit
/**
* FakeDesc
*
* Fake, probe-able ParserDescription
*/
struct FakeDesc : ParserDescription {
public let summary: String
public let isDelimited: Bool
public let children: [ParserDescription]
public let isNormalised: Bool
init(summary: String,
isDelimited: Bool,
children: [ParserDescription],
isNormalised: Bool) {
self.summary = summary
self.isDelimited = isDelimited
self.children = children
self.isNormalised = isNormalised
}
init(_ n : Int, WithChildren children: [ParserDescription]) {
self.init(summary: "fake-desc-" + String(n),
isDelimited: false,
children: children,
isNormalised: false)
}
init(_ n : Int){
self.init(n, WithChildren: [])
}
public var normalised: ParserDescription {
return FakeDesc(summary: summary,
isDelimited: isDelimited,
children: children.map {$0.normalised},
isNormalised: true)
}
}
/**
* AssertCast<U, T>(_ obj: U, _ tests: (T) -> Void)
*
* Check whether `obj : U` can be dynamically cast to a value of type `T`, and
* if it can, pass it on to a continuation for potential further testing.
*/
func AssertCast<U, T>(_ obj: U, _ tests: (T) -> Void) {
switch obj {
case let casted as T:
tests(casted)
break;
default:
XCTFail("AssertCast: Could not dynamically cast value")
break
}
}
/**
* AssertEqualDesc(_ lhs: ParserDescription, _ rhs: ParserDescription)
*
* Check whether the descriptions `lhs` and `rhs` are observationally
* equivalent.
*/
func AssertEqualDesc(_ lhs: ParserDescription, _ rhs: ParserDescription) {
XCTAssertEqual(lhs.summary, rhs.summary)
XCTAssertEqual(lhs.delimitedSummary, rhs.delimitedSummary)
XCTAssertEqual(lhs.isDelimited, rhs.isDelimited)
XCTAssertEqual(lhs.description, rhs.description)
let lcs = lhs.children
let rcs = rhs.children
XCTAssertEqual(lcs.count, rcs.count)
for (l, r) in zip(lcs, rcs) {
AssertEqualDesc(l, r);
}
}
class NormalisationTests : XCTestCase {
func testPrimitive() {
let prim = PrimitiveDesc(name: "name", desc: "desc")
AssertEqualDesc(prim, prim.normalised)
}
func testFlag() {
let flag = FlagDesc(name: "name", desc: "desc")
AssertEqualDesc(flag, flag.normalised)
}
func testCmd() {
let cmd = CmdDesc(cmd: "cmd")
AssertEqualDesc(cmd, cmd.normalised)
}
func testSection() {
let sect = SectionDesc(tag: "tag", name: "name", desc: "desc",
child: FakeDesc(1))
let norm = sect.normalised
AssertEqualDesc(sect, norm)
AssertCast(norm) { (norm: SectionDesc) in
AssertCast(norm.child) { (child: FakeDesc) in
XCTAssertTrue(child.isNormalised)
}
}
}
func testAtleast() {
let atleast = AtleastDesc(lowerBound: 1,
child: FakeDesc(1))
let norm = atleast.normalised
AssertEqualDesc(atleast, norm)
AssertCast(norm) { (norm: AtleastDesc) in
AssertCast(norm.child) { (child: FakeDesc) in
XCTAssertTrue(child.isNormalised)
}
}
}
func testOptional() {
let opt = OptionalDesc(child: FakeDesc(1))
AssertEqualDesc(opt, opt.normalised)
}
func testOptionalNonEmptyFlattening() {
let nonEmpty = AtleastDesc(lowerBound: 1,
child: FakeDesc(1),
sep: FakeDesc(2))
let opt = OptionalDesc(child: nonEmpty)
let expected = AtleastDesc(lowerBound: 0,
child: nonEmpty.child,
sep: nonEmpty.sep)
AssertEqualDesc(opt.normalised, expected)
}
func testOptionalAtleastPreserve() {
let atleast = AtleastDesc(lowerBound: 2,
child: FakeDesc(1),
sep: FakeDesc(2))
let opt = OptionalDesc(child: atleast)
AssertEqualDesc(opt, opt.normalised)
}
func testSequenceDiscarding() {
let fake = FakeDesc(1)
let seq = SequenceDesc(children: [fake])
let norm = seq.normalised
AssertEqualDesc(fake, norm)
AssertCast(norm) { (actual: FakeDesc) in
XCTAssertTrue(actual.isNormalised)
}
}
func testSequenceFlattening() {
let seq = SequenceDesc(children: [
FakeDesc(1),
FakeDesc(2),
SequenceDesc(children: [
FakeDesc(3),
SequenceDesc(children: [
FakeDesc(4)
])
]),
FakeDesc(5, WithChildren: [
SequenceDesc(children: [
FakeDesc(6)
]),
FakeDesc(7)
])
])
let expected = SequenceDesc(children: [
FakeDesc(1),
FakeDesc(2),
FakeDesc(3),
FakeDesc(4),
FakeDesc(5, WithChildren: [
FakeDesc(6),
FakeDesc(7)
])
])
AssertEqualDesc(expected, seq.normalised)
}
func testSequenceEmpty() {
let seq = SequenceDesc(children: [])
AssertEqualDesc(seq, seq.normalised)
}
func testChoiceDiscarding() {
let fake = FakeDesc(1)
let choices = ChoiceDesc(children: [fake])
let norm = choices.normalised
AssertEqualDesc(fake, norm)
AssertCast(norm) { (actual: FakeDesc) in
XCTAssertTrue(actual.isNormalised)
}
}
func testChoiceFlattening() {
let choices = ChoiceDesc(children: [
FakeDesc(1),
FakeDesc(2),
ChoiceDesc(children: [
FakeDesc(3),
ChoiceDesc(children: [
FakeDesc(4)
])
]),
FakeDesc(5, WithChildren: [
ChoiceDesc(children: [
FakeDesc(6)
]),
FakeDesc(7)
])
])
let expected = ChoiceDesc(children: [
FakeDesc(1),
FakeDesc(2),
FakeDesc(3),
FakeDesc(4),
FakeDesc(5, WithChildren: [
FakeDesc(6),
FakeDesc(7)
])
])
AssertEqualDesc(expected, choices.normalised)
}
func testChoiceEmpty() {
let choice = ChoiceDesc(children: [])
AssertEqualDesc(choice, choice.normalised)
}
func testPreservesExpandednessOfChoice() {
let choice = ChoiceDesc(children: [FakeDesc(1), FakeDesc(2)]).expanded
AssertEqualDesc(choice, choice.normalised)
}
}
class DelimitedSummaryTest : XCTestCase {
func testNotDelimited() {
let fake = FakeDesc(summary: "summary",
isDelimited: false,
children: [],
isNormalised: false)
XCTAssertEqual("{{ summary }}", fake.delimitedSummary)
}
func testDelimited() {
let fake = FakeDesc(summary: "summary",
isDelimited: true,
children: [],
isNormalised: false)
XCTAssertEqual("summary", fake.delimitedSummary)
}
}
class FindAllTests : XCTestCase {
func testSingleton() {
let fake = FakeDesc(1)
var fakes = [FakeDesc]()
fake.findAll(&fakes)
XCTAssertEqual(0, fakes.count)
}
func testNested() {
let fake4 = FakeDesc(4)
let fake3 = FakeDesc(3, WithChildren: [fake4])
let fake2 = FakeDesc(2)
let fake1 = FakeDesc(1, WithChildren: [fake2, fake3])
let expectedFakes = [fake2, fake3, fake4]
var actualFakes = [FakeDesc]()
fake1.findAll(&actualFakes)
XCTAssertEqual(expectedFakes.count, actualFakes.count)
for fake in expectedFakes {
XCTAssert(actualFakes.contains { $0.summary == fake.summary })
}
}
func testHiddenBySect() {
let fake2 = FakeDesc(2)
let fake1 = FakeDesc(1, WithChildren: [
fake2,
SectionDesc(tag: "tag", name: "name", desc: "desc", child: FakeDesc(3))
])
var actualFakes = [FakeDesc]()
fake1.findAll(&actualFakes)
XCTAssertEqual(1, actualFakes.count)
AssertEqualDesc(fake2, actualFakes.first!)
}
}
| bsd-3-clause | cfd7cc9877ba9a4d6a6b569b0bfbb4aa | 24.61442 | 78 | 0.612655 | 3.909569 | false | true | false | false |
steve-holmes/music-app-2 | MusicApp/Modules/Category/CategoryInfo.swift | 1 | 1335 | //
// CategoryInfo.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/17/17.
// Copyright © 2017 HungDo. All rights reserved.
//
struct CategoryInfo {
let category: Category
let new: Bool
init(category: Category, new: Bool) {
self.category = category
self.new = new
}
init(name: String, new: Bool, newlink: String, hotlink: String) {
self.category = Category(name: name, newlink: newlink, hotlink: hotlink)
self.new = new
}
init(json: [String:Any]) {
guard let name = json["name"] as? String else { fatalError("Can not get category name") }
guard let subkind = json["suffix"] as? String else { fatalError("Can not get category kind") }
guard let newlink = json["newlink"] as? String else { fatalError("Can not get category newlink") }
guard let hotlink = json["hotlink"] as? String else { fatalError("Can not get category hotlink") }
let new = subkind == "new"
self.init(name: name, new: new, newlink: newlink, hotlink: hotlink)
}
var name: String { return category.name }
var newlink: String { return category.newlink }
var hotlink: String { return category.hotlink }
var link: String { return new ? category.newlink : category.hotlink }
}
| mit | ae1d9e1d83716adecf3d6cc3106965f0 | 32.25 | 107 | 0.612782 | 3.821839 | false | false | false | false |
HeartRateLearning/HRLEngine | HRLEngine/Classes/WorkingOut.swift | 1 | 448 | //
// WorkingOut.swift
// Pods
//
// Created by Enrique de la Torre (dev) on 27/12/2016.
//
//
import Foundation
enum WorkingOut: UInt {
case `false` = 0
case `true` = 1
init(_ isWorkingOut: Bool) {
self = (isWorkingOut ? .`true` : .`false`)
}
}
extension Bool {
init(_ workingOut: WorkingOut) {
if workingOut == .true {
self = true
} else {
self = false
}
}
}
| mit | e4615fa55bb109dc10000f903f67084f | 15 | 55 | 0.511161 | 3.343284 | false | false | false | false |
hjandyz/HJImagePicker | HJImagePicker/HJImagePickerCollectionViewController.swift | 1 | 5926 | //
// HJImagePickerCollectionViewController.swift
// HJImagePicker
//
// Created by seemelk on 2017/2/13.
// Copyright © 2017年 罕见. All rights reserved.
//
import UIKit
import Photos
private let reuseIdentifier = "HJImagePickerCollectionViewCell"
class HJImagePickerCollectionViewController: UICollectionViewController {
var models: [HJImagePickerAssetModel]?
var selectedModels = [HJImagePickerAssetModel]()
lazy var previewItem: UIBarButtonItem = {
let previewItem = UIBarButtonItem(title: "预览", style: .plain, target: self, action: #selector(previewAction))
previewItem.tintColor = UIColor.black
previewItem.isEnabled = false
return previewItem
}()
init() {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 5
layout.minimumInteritemSpacing = 5
super.init(collectionViewLayout: layout)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "所有照片"
view.backgroundColor = UIColor.white
setItemSize(size: view.bounds.size)
collectionView?.backgroundColor = UIColor.white
collectionView?.contentInset = UIEdgeInsetsMake(5, 5, 0, 5)
collectionView?.allowsMultipleSelection = true
collectionView?.register(HJImagePickerCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
collectionView?.alwaysBounceVertical = true
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let sendItem = UIBarButtonItem(title: "发送", style: .plain, target: nil, action: nil)
toolbarItems = [previewItem,flexibleSpace,sendItem]
HJImagePickerAssetManager.fetch { models in
self.models = models
self.collectionView?.reloadData()
self.collectionView?.scrollToItem(at: IndexPath(row: models.count-1, section: 0), at: .bottom, animated: false)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setToolbarHidden(false, animated: animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setToolbarHidden(true, animated: animated)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
setItemSize(size: size)
// let layout = collectionViewLayout as! UICollectionViewFlowLayout
// if UI_USER_INTERFACE_IDIOM() == .pad && size.width>size.height {
// let sizeW = (Int)((size.width-6*10) / 5)
// layout.estimatedItemSize = CGSize(width:sizeW, height:sizeW)
// }else{
// let sizeW = (Int)((size.width-5*5) / 4)
// layout.estimatedItemSize = CGSize(width:sizeW, height:sizeW)
// }
}
private func setItemSize(size: CGSize){
let layout = collectionViewLayout as! UICollectionViewFlowLayout
let sizeW = (Int)((min(size.width,size.height)-5*5) / 4)
if sizeW != (Int)(layout.estimatedItemSize.width) {
layout.estimatedItemSize = CGSize(width:sizeW, height:sizeW)
}
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
}
}
extension HJImagePickerCollectionViewController{
func setSelected(model: HJImagePickerAssetModel){
if model.isSelected {
if !selectedModels.contains(model) {
selectedModels.append(model)
}
if let index = models?.index(of: model){
collectionView?.selectItem(at:IndexPath(row: index, section: 0) , animated: false, scrollPosition: UICollectionViewScrollPosition())
}
}else{
if let index = selectedModels.index(of: model) {
selectedModels.remove(at: index)
}
if let index = models?.index(of: model) {
collectionView?.deselectItem(at: IndexPath(row: index, section: 0), animated: false)
}
}
previewItem.isEnabled = selectedModels.count > 0
}
@objc fileprivate func previewAction(){
let preview = HJImagePickerPreviewController()
preview.models = selectedModels
preview.selectedModels = selectedModels
show(preview, sender: nil)
}
}
extension HJImagePickerCollectionViewController{
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard (models != nil) else {
return 0
}
return models!.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! HJImagePickerCollectionViewCell
cell.model = models?[indexPath.item]
cell.pickerController = self
return cell
}
override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
showPreView(indexPath: indexPath)
return false
}
private func showPreView(indexPath: IndexPath){
let preview = HJImagePickerPreviewController()
preview.currentIndex = indexPath.row
preview.models = models
preview.selectedModels = selectedModels
show(preview, sender: nil)
}
}
| mit | fb6c541cf0673ba6ac3115fe401981b3 | 37.083871 | 148 | 0.663561 | 5.133043 | false | false | false | false |
onekiloparsec/SwiftAA | Sources/SwiftAA/Times.swift | 2 | 6721 | //
// Times.swift
// SwiftAA
//
// Created by Cédric Foellmi on 17/12/2016.
// MIT Licence. See LICENCE file.
//
import Foundation
// MARK: -
/// The Day is a number representing an Earth day.
public struct Day: NumericType, CustomStringConvertible {
/// The Day value
public let value: Double
/// Returns a Day struct initialized to contain the given value.
///
/// - Parameter value: The value for the new Day.
public init(_ value: Double) {
self.value = value
}
/// Transform the current Day value into Hours.
public var inHours: Hour { return Hour(value * 24.0) }
/// Transform the current Day value into Minutes.
public var inMinutes: Minute { return Minute(value * 24.0 * 60.0) }
/// Transform the current Day value into Seconds.
public var inSeconds: Second { return Second(value * 24.0 * 3600.0) }
/// Transform the current Day value into Julian Days (convenient for easily making operations with Julian Day fractions).
public var inJulianDays: JulianDay { return JulianDay(value) }
/// The standard description of the Day
public var description: String { return String(format: "%.2f d", value) }
}
/// The Hour is a number representing an Earth hour.
public struct Hour: NumericType, CustomStringConvertible {
/// The Hour value
public let value: Double
/// Returns a Hour struct initialized to contain the given value.
///
/// - Parameter value: The value for the new Hour.
public init(_ value: Double) {
self.value = value
}
/// Returns a Hour struct initialized from a sexagesimal representation of the hour.
///
/// - Parameters:
/// - sign: The sign of the hour
/// - hours: The hour component of the sexagesimal representation. Sign is ignored.
/// - minutes: The minute component of the sexagesimal representation. Sign is ignored.
/// - seconds: The second component of the sexagesimal representation. Sign is ignored.
public init(_ sign: FloatingPointSign = .plus, _ hours: Int, _ minutes: Int, _ seconds: Double) {
let absHour = abs(Double(hours))
let absMinutes = abs(Double(minutes))/60.0
let absSeconds = abs(seconds)/3600.0
self.init(Double(sign) * (absHour + absMinutes + absSeconds))
}
/// Transform the current Hour value into Days.
public var inDays: Day { return Day(value / 24.0) }
/// Transform the current Hour value into Minutes.
public var inMinutes: Minute { return Minute(value * 60.0) }
/// Transform the current Hour value into Seconds.
public var inSeconds: Second { return Second(value * 3600.0) }
/// Transform the current Hour value into Degrees.
public var inDegrees: Degree { return Degree(value * 15.0) }
/// Transform the current Hour value into Radians.
public var inRadians: Radian { return Radian(value * hour2rad) }
/// Transform the current Hour value into Julian Days (convenient for easily making operations with Julian Day fractions).
public var inJulianDays: JulianDay { return JulianDay(value / 24.0) }
/// Returns a sexagesimal representation of the hour.
public var sexagesimal: SexagesimalNotation {
get {
let hrs = abs(value.rounded(.towardZero))
let min = ((abs(value) - hrs) * 60.0).rounded(.towardZero)
let sec = ((abs(value) - hrs) * 60.0 - min) * 60.0
return (value > 0.0 ? .plus : .minus, Int(hrs), Int(min), Double(sec))
}
}
/// Returns a Hour whose value is reduced to the 0..<24 range.
public var reduced: Hour { return Hour(value.positiveTruncatingRemainder(dividingBy: 24.0)) }
/// Returns a Hour whose value is reduced to the -12..<12 range (that is, around 0, hence the name).
public var reduced0: Hour { return Hour(value.zeroCenteredTruncatingRemainder(dividingBy: 24.0)) }
/// A standard sexagesimal description of the Hour value.
public var description: String {
let (sign, hrs, min, sec) = self.sexagesimal
return sign.string + String(format: "%ih%im%06.3fs", hrs, min, sec)
}
}
// MARK: -
/// The Minute is a number representing an Earth minute.
public struct Minute: NumericType, CustomStringConvertible {
/// The Minute value
public let value: Double
/// Returns a Minute struct initialized to contain the given value.
///
/// - Parameter value: The value for the new Minute.
public init(_ value: Double) {
self.value = value
}
/// Transform the current Minute value into Days.
public var inDays: Day { return Day(value / (24.0 * 60.0)) }
/// Transform the current Minute value into Hours.
public var inHours: Hour { return Hour(value / 60.0) }
/// Transform the current Minute value into Seconds.
public var inSeconds: Second { return Second(value * 60.0) }
/// Transform the current Minute value into Julian Days (convenient for easily making operations with Julian Day fractions).
public var inJulianDays: JulianDay { return JulianDay(value / 1440.0) }
/// Returns a Minute whose value is reduced to the 0..<60 range.
public var reduced: Minute { return Minute(value.positiveTruncatingRemainder(dividingBy: 60.0)) }
/// The standard description of the Hour
public var description: String { return String(format: "%.2f min", value) }
}
// MARK: -
/// The Second is a number representing an Earth second.
public struct Second: NumericType, CustomStringConvertible {
/// The Second value
public let value: Double
/// Returns a Second struct initialized to contain the given value.
///
/// - Parameter value: The value for the new Second.
public init(_ value: Double) {
self.value = value
}
/// Transform the current Second value into Days.
public var inDays: Day { return Day(value / (24.0 * 3600.0)) }
/// Transform the current Second value into Hour.
public var inHours: Hour { return Hour(value / 3600.0) }
/// Transform the current Second value into Minute.
public var inMinutes: Minute { return Minute(value / 60.0) }
/// Transform the current Second value into Julian Days (convenient for easily making operations with Julian Day fractions).
public var inJulianDays: JulianDay { return JulianDay(value / 86400.0) }
/// Returns a Second whose value is reduced to the 0..<60 range.
public var reduced: Second { return Second(value.positiveTruncatingRemainder(dividingBy: 60.0)) }
/// The standard description of the Second
public var description: String { return String(format: "%.2f sec", value) }
}
| mit | 21cc25a855de8d883ffb01a6d561efb8 | 40.226994 | 128 | 0.66503 | 4.299424 | false | false | false | false |
icanzilb/EventBlankApp | EventBlank/EventBlank/Entities/DatabaseProvider.swift | 3 | 1237 | //
// Database.swift
// EventBlank
//
// Created by Marin Todorov on 3/12/15.
// Copyright (c) 2015 Underplot ltd. All rights reserved.
//
import Foundation
import SQLite
class DatabaseProvider {
var path: FilePath
var _database: Database!
var database: Database {
return _database
}
static var databases = [String: Database]()
init?(path targetPath: FilePath, defaultPath: FilePath? = nil, preferNewerSourceFile: Bool = false) {
if let defaultPath = defaultPath {
//copy if does not exist in target location
defaultPath.copyOnceTo(targetPath)
//copy if the bundle contains a newer version
if preferNewerSourceFile {
defaultPath.copyIfNewer(targetPath)
}
}
path = targetPath
loadDatabaseFile()
}
private func loadDatabaseFile() {
_database = Database(path.filePath)
DatabaseProvider.databases[path.filePath.lastPathComponent] = _database
}
func didChangeSourceFile(success: Bool) {
println("Database Provider: reload database: \(path.filePath)")
loadDatabaseFile()
}
} | mit | 78753dc5d8650ba1210067b61c108080 | 23.76 | 105 | 0.605497 | 4.90873 | false | false | false | false |
baquiax/SimpleTwitterClient | SimpleTwitterClient/SimpleTwitterClient/LastTweetsViewController.swift | 1 | 4140 | //
// LastTweetsViewController.swift
// SimpleTwitterClient
//
// Created by Alexander Baquiax on 4/8/16.
// Copyright © 2016 Alexander Baquiax. All rights reserved.
//
import Foundation
import UIKit
public class LastTweetsViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var loader: UIActivityIndicatorView!
@IBOutlet var tableView: UITableView!
var urlSession: NSURLSession!
var data : NSArray = NSArray()
public override func viewDidLoad() {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
self.urlSession = NSURLSession(configuration: configuration)
self.tableView.delegate = self
self.tableView.dataSource = self
self.loader.hidesWhenStopped = true
loadData()
}
func loadData () {
self.loader.hidden = false
self.loader.startAnimating()
if let user = NSUserDefaults.standardUserDefaults().objectForKey("user") {
print("UserId: ", user.objectForKey("user_id")!)
TwitterClient.getTwitterClient().client.get("https://api.twitter.com/1.1/statuses/home_timeline.json", parameters: ["count" : 100], headers: nil, success: { data, response in
do {
self.data = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as! NSArray
} catch {
self.data = NSArray()
}
self.tableView.reloadData()
self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: true)
self.loader.stopAnimating()
}, failure: { (error) -> Void in
})
} else {
self.loader.stopAnimating()
}
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TwitterPost", forIndexPath: indexPath) as! TwitterPostCell
let item = self.data.objectAtIndex(indexPath.row) as! NSDictionary
if let user = item.objectForKey("user") as? NSDictionary {
if let name = user.objectForKey("name") as? String {
cell.name.text = name
}
if let screenName = user.objectForKey("screen_name") as? String {
cell.username.text = screenName
}
if let imageStringURL = user.objectForKey("profile_image_url") as? String {
let imageURL = NSURL(string: imageStringURL)
let request = NSURLRequest(URL: imageURL!)
cell.dataTask = self.urlSession.dataTaskWithRequest(request) { (data, response, error) -> Void in
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
if error == nil && data != nil {
let image = UIImage(data: data!)
cell.profileImage.image = image
}
})
}
cell.dataTask?.resume()
}
}
if let text = item.objectForKey("text") as? String {
cell.tweet.text = text
}
return cell
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 115;
}
public func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if let cell = cell as? TwitterPostCell {
print("Canceling download!")
cell.dataTask?.cancel()
}
}
@IBAction func afterLongPress(sender: UILongPressGestureRecognizer) {
print("Long press has been succed!")
self.loadData()
}
}
| mit | 6f293d4f19499d17e34c4156ba495cb6 | 38.798077 | 186 | 0.60087 | 5.474868 | false | false | false | false |
publickanai/PLMScrollMenu | Example/PLScrollMenuBarItem.swift | 1 | 3937 | //
// PLMScrollMenuBarItem.swift
// PLMScrollMenu
//
// Created by Tatsuhiro Kanai on 2016/03/29.
// Copyright © 2016年 Adways Inc. All rights reserved.
//
import UIKit
public class PLMScrollMenuBarButton : UIButton
{
static func button()->PLMScrollMenuBarButton
{
return PLMScrollMenuBarButton.init(type: .Custom)
}
}
public class PLMScrollMenuBarItem: NSObject
{
// constant
static let kPLMScrollMenuBarItemDefaultWidth:CGFloat = 90
// Title
public var title : String = ""
// Tag
public var tag : Int = 0
// Font
public var selectedFont: UIFont?
public var normalFont : UIFont?
// Button
private var _itemButton : PLMScrollMenuBarButton!
// width
private var _width: CGFloat!
public var width : CGFloat!
{
set {
_width = newValue
if let btn = _itemButton {
btn.frame = CGRectMake(0, 0, _width, 36)
btn.sizeToFit()
}
}
get{
// if let button = _itemButton {
// return button.frame.size.width
// } else {
// return 0
// }
return button().frame.size.width
}
}
// Enabled
private var _enabled : Bool = true
public var enabled : Bool {
set { _enabled = newValue
if let btn = _itemButton {
btn.enabled = _enabled
}
}
get { return _enabled }
}
// Selected
private var _selected : Bool = false
public var selected : Bool {
set{ _selected = newValue
if _selected {
// keep normal font
normalFont = _itemButton!.titleLabel!.font
if let selectedFont = selectedFont {
_itemButton?.titleLabel!.font = selectedFont
}
} else {
_itemButton!.titleLabel!.font = normalFont
}
_itemButton!.selected = selected
}
get{ return _selected}
}
/** description
*/
override public var description : String {
return "<PLMScrollMenuItem: \(self.title) \(NSStringFromCGRect(self.button().frame))>"
}
/** init
*/
override init() {
super.init()
_width = PLMScrollMenuBarItem.kPLMScrollMenuBarItemDefaultWidth
_enabled = true
}
// Item
public static func item() -> PLMScrollMenuBarItem {
return PLMScrollMenuBarItem.init()
}
/** button
*/
public func button() -> PLMScrollMenuBarButton
{
if let itemButton = _itemButton {
return itemButton
} else {
_itemButton = PLMScrollMenuBarButton.init(type: .Custom)
if let itemButton = _itemButton {
itemButton.tag = self.tag
itemButton.frame = CGRectMake(0, 0, _width, 24)
itemButton.titleLabel!.font = UIFont.systemFontOfSize(16.0)
itemButton.setTitle(self.title, forState: .Normal)
itemButton.setTitleColor(UIColor(red: 0.647, green: 0.631, blue: 0.604, alpha: 1.000), forState: .Normal)
itemButton.setTitleColor(UIColor(white: 0.886 , alpha: 1.000), forState: .Disabled)
itemButton.setTitleColor(UIColor(red: 0.988, green: 0.224, blue: 0.129, alpha: 1.000), forState: .Selected)
itemButton.enabled = enabled
itemButton.exclusiveTouch = false
itemButton.sizeToFit()
}
return _itemButton
}
}
}
| mit | e6434fb349b2cfbd41d7705a7fd8158f | 25.402685 | 123 | 0.505084 | 5.13577 | false | false | false | false |
sekouperry/bemyeyes-ios | BeMyEyes/Source/Views/GradientView.swift | 2 | 1967 | //
// GradientView.swift
// BeMyEyes
//
// Created by Tobias DM on 22/09/14.
// Copyright (c) 2014 Be My Eyes. All rights reserved.
//
import UIKit
extension UIColor {
class func lightBlueColor() -> UIColor {
return UIColor(red: 0.24, green: 0.56, blue: 0.71, alpha: 1)
}
class func darkBlueColor() -> UIColor {
return UIColor(red: 0.1, green: 0.22, blue: 0.36, alpha: 1)
}
}
@IBDesignable class GradientView: UIView {
private lazy var gradientLayer: CAGradientLayer = {
var layer = CAGradientLayer()
return layer
}()
var colors: [UIColor] = [.lightBlueColor(), .darkBlueColor()] {
didSet {
update()
}
}
var startPoint: CGPoint = CGPoint(x: 0, y: 0) {
didSet {
update()
}
}
var endPoint: CGPoint = CGPoint(x: 1, y: 1) {
didSet {
update()
}
}
convenience init() {
self.init(frame: CGRectZero)
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
update()
backgroundColor = .clearColor()
layer.addSublayer(gradientLayer)
}
override func layoutSublayersOfLayer(layer: CALayer!) {
super.layoutSublayersOfLayer(layer)
CATransaction.begin()
CATransaction.setDisableActions(true) // Disable animations when changing bounds of CALayer
gradientLayer.frame = bounds
CATransaction.commit()
}
func update() {
gradientLayer.colors = colors.map { return $0.CGColor }
gradientLayer.startPoint = startPoint
gradientLayer.endPoint = endPoint
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setup()
}
} | mit | 991c5229f43b7c385cc0430b992d3a1f | 22.152941 | 99 | 0.570412 | 4.532258 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/Swift/Components/AdaptiveURL.swift | 1 | 1632 | //
// Xcore
// Copyright © 2019 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
public struct AdaptiveURL: UserInfoContainer, MutableAppliable {
/// The title of the URL.
public let title: String
public let url: URL
/// Additional info which may be used to describe the url further.
public var userInfo: UserInfo
/// Initialize an instance of adaptive URL.
///
/// - Parameters:
/// - title: The title of the URL.
/// - url: The url.
/// - userInfo: Additional info associated with the url.
public init(title: String, url: URL, userInfo: UserInfo = [:]) {
self.title = title
self.url = url
self.userInfo = userInfo
}
}
// MARK: - UserInfo
extension UserInfoKey where Type == AdaptiveURL {
/// A boolean property indicating whether the URL content should adapt app
/// appearance.
public static var shouldAdaptAppearance: Self { #function }
}
extension AdaptiveURL {
/// A boolean property indicating whether the URL content should adapt app
/// appearance.
public var shouldAdaptAppearance: Bool {
get { self[userInfoKey: .shouldAdaptAppearance, default: false] }
set { self[userInfoKey: .shouldAdaptAppearance] = newValue }
}
}
// MARK: - Equatable
extension AdaptiveURL: Equatable {
public static func ==(lhs: Self, rhs: Self) -> Bool {
String(reflecting: lhs) == String(reflecting: rhs)
}
}
// MARK: - Hashable
extension AdaptiveURL: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(String(reflecting: self))
}
}
| mit | 53a055f6bb2d9c4807b550d3368b4ee1 | 26.183333 | 78 | 0.657265 | 4.292105 | false | false | false | false |
Jnosh/swift | test/SILGen/objc_blocks_bridging.swift | 5 | 11435 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %build-silgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -verify -emit-silgen -I %S/Inputs -disable-objc-attr-requires-foundation-module %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
@objc class Foo {
// CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC3fooS3ic_Si1xtFTo :
// CHECK: bb0([[ARG1:%.*]] : $@convention(block) (Int) -> Int, {{.*}}, [[SELF:%.*]] : $Foo):
// CHECK: [[ARG1_COPY:%.*]] = copy_block [[ARG1]]
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[THUNK:%.*]] = function_ref @_T0S2iIyByd_S2iIxyd_TR
// CHECK: [[BRIDGED:%.*]] = partial_apply [[THUNK]]([[ARG1_COPY]])
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[NATIVE:%.*]] = function_ref @_T020objc_blocks_bridging3FooC3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (@owned @callee_owned (Int) -> Int, Int, @guaranteed Foo) -> Int
// CHECK: apply [[NATIVE]]([[BRIDGED]], {{.*}}, [[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: } // end sil function '_T020objc_blocks_bridging3FooC3fooS3ic_Si1xtFTo'
dynamic func foo(_ f: (Int) -> Int, x: Int) -> Int {
return f(x)
}
// CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC3barS3Sc_SS1xtFTo : $@convention(objc_method) (@convention(block) (NSString) -> @autoreleased NSString, NSString, Foo) -> @autoreleased NSString {
// CHECK: bb0([[BLOCK:%.*]] : $@convention(block) (NSString) -> @autoreleased NSString, [[NSSTRING:%.*]] : $NSString, [[SELF:%.*]] : $Foo):
// CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
// CHECK: [[NSSTRING_COPY:%.*]] = copy_value [[NSSTRING]]
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[THUNK:%.*]] = function_ref @_T0So8NSStringCABIyBya_S2SIxxo_TR
// CHECK: [[BRIDGED:%.*]] = partial_apply [[THUNK]]([[BLOCK_COPY]])
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[NATIVE:%.*]] = function_ref @_T020objc_blocks_bridging3FooC3bar{{[_0-9a-zA-Z]*}}F : $@convention(method) (@owned @callee_owned (@owned String) -> @owned String, @owned String, @guaranteed Foo) -> @owned String
// CHECK: apply [[NATIVE]]([[BRIDGED]], {{%.*}}, [[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: } // end sil function '_T020objc_blocks_bridging3FooC3barS3Sc_SS1xtFTo'
dynamic func bar(_ f: (String) -> String, x: String) -> String {
return f(x)
}
// CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC3basSSSgA2Ec_AE1xtFTo : $@convention(objc_method) (@convention(block) (Optional<NSString>) -> @autoreleased Optional<NSString>, Optional<NSString>, Foo) -> @autoreleased Optional<NSString> {
// CHECK: bb0([[BLOCK:%.*]] : $@convention(block) (Optional<NSString>) -> @autoreleased Optional<NSString>, [[OPT_STRING:%.*]] : $Optional<NSString>, [[SELF:%.*]] : $Foo):
// CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
// CHECK: [[OPT_STRING_COPY:%.*]] = copy_value [[OPT_STRING]]
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[THUNK:%.*]] = function_ref @_T0So8NSStringCSgACIyBya_SSSgADIxxo_TR
// CHECK: [[BRIDGED:%.*]] = partial_apply [[THUNK]]([[BLOCK_COPY]])
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[NATIVE:%.*]] = function_ref @_T020objc_blocks_bridging3FooC3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) (@owned @callee_owned (@owned Optional<String>) -> @owned Optional<String>, @owned Optional<String>, @guaranteed Foo) -> @owned Optional<String>
// CHECK: apply [[NATIVE]]([[BRIDGED]], {{%.*}}, [[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
dynamic func bas(_ f: (String?) -> String?, x: String?) -> String? {
return f(x)
}
// CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC16cFunctionPointer{{[_0-9a-zA-Z]*}}FTo
// CHECK: bb0([[F:%.*]] : $@convention(c) (Int) -> Int, [[X:%.*]] : $Int, [[SELF:%.*]] : $Foo):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[NATIVE:%.*]] = function_ref @_T020objc_blocks_bridging3FooC16cFunctionPointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[NATIVE]]([[F]], [[X]], [[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
dynamic func cFunctionPointer(_ fp: @convention(c) (Int) -> Int, x: Int) -> Int {
_ = fp(x)
}
// Blocks and C function pointers must not be reabstracted when placed in optionals.
// CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC7optFunc{{[_0-9a-zA-Z]*}}FTo
// CHECK: bb0([[ARG0:%.*]] : $Optional<@convention(block) (NSString) -> @autoreleased NSString>,
// CHECK: [[COPY:%.*]] = copy_block [[ARG0]]
// CHECK: switch_enum [[COPY]] : $Optional<@convention(block) (NSString) -> @autoreleased NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]([[BLOCK:%.*]] : $@convention(block) (NSString) -> @autoreleased NSString):
// TODO: redundant reabstractions here
// CHECK: [[BLOCK_THUNK:%.*]] = function_ref @_T0So8NSStringCABIyBya_S2SIxxo_TR
// CHECK: [[BRIDGED:%.*]] = partial_apply [[BLOCK_THUNK]]([[BLOCK]])
// CHECK: enum $Optional<@callee_owned (@owned String) -> @owned String>, #Optional.some!enumelt.1, [[BRIDGED]]
// CHECK: [[NATIVE:%.*]] = function_ref @_T020objc_blocks_bridging3FooC7optFunc{{[_0-9a-zA-Z]*}}F : $@convention(method) (@owned Optional<@callee_owned (@owned String) -> @owned String>, @owned String, @guaranteed Foo) -> @owned Optional<String>
// CHECK: apply [[NATIVE]]
dynamic func optFunc(_ f: ((String) -> String)?, x: String) -> String? {
return f?(x)
}
// CHECK-LABEL: sil hidden @_T020objc_blocks_bridging3FooC19optCFunctionPointer{{[_0-9a-zA-Z]*}}F
// CHECK: [[FP_BUF:%.*]] = unchecked_enum_data %0
dynamic func optCFunctionPointer(_ fp: (@convention(c) (String) -> String)?, x: String) -> String? {
return fp?(x)
}
}
// => SEMANTIC SIL TODO: This test needs to be filled out more for ownership
//
// CHECK-LABEL: sil hidden @_T020objc_blocks_bridging10callBlocks{{[_0-9a-zA-Z]*}}F
func callBlocks(_ x: Foo,
f: @escaping (Int) -> Int,
g: @escaping (String) -> String,
h: @escaping (String?) -> String?
) -> (Int, String, String?, String?) {
// CHECK: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $@callee_owned (Int) -> Int, [[ARG2:%.*]] : $@callee_owned (@owned String) -> @owned String, [[ARG3:%.*]] : $@callee_owned (@owned Optional<String>) -> @owned Optional<String>):
// CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]]
// CHECK: [[FOO:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.foo!1.foreign
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
// CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_ARG1]]
// CHECK: [[F_BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage
// CHECK: [[F_BLOCK_CAPTURE:%.*]] = project_block_storage [[F_BLOCK_STORAGE]]
// CHECK: store [[CLOSURE_COPY]] to [init] [[F_BLOCK_CAPTURE]]
// CHECK: [[F_BLOCK_INVOKE:%.*]] = function_ref @_T0S2iIxyd_S2iIyByd_TR
// CHECK: [[F_STACK_BLOCK:%.*]] = init_block_storage_header [[F_BLOCK_STORAGE]] : {{.*}}, invoke [[F_BLOCK_INVOKE]]
// CHECK: [[F_BLOCK:%.*]] = copy_block [[F_STACK_BLOCK]]
// CHECK: apply [[FOO]]([[F_BLOCK]]
// CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]]
// CHECK: [[BAR:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.bar!1.foreign
// CHECK: [[G_BLOCK_INVOKE:%.*]] = function_ref @_T0S2SIxxo_So8NSStringCABIyBya_TR
// CHECK: [[G_STACK_BLOCK:%.*]] = init_block_storage_header {{.*}}, invoke [[G_BLOCK_INVOKE]]
// CHECK: [[G_BLOCK:%.*]] = copy_block [[G_STACK_BLOCK]]
// CHECK: apply [[BAR]]([[G_BLOCK]]
// CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]]
// CHECK: [[BAS:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.bas!1.foreign
// CHECK: [[H_BLOCK_INVOKE:%.*]] = function_ref @_T0SSSgAAIxxo_So8NSStringCSgADIyBya_TR
// CHECK: [[H_STACK_BLOCK:%.*]] = init_block_storage_header {{.*}}, invoke [[H_BLOCK_INVOKE]]
// CHECK: [[H_BLOCK:%.*]] = copy_block [[H_STACK_BLOCK]]
// CHECK: apply [[BAS]]([[H_BLOCK]]
// CHECK: [[G_BLOCK:%.*]] = copy_block {{%.*}} : $@convention(block) (NSString) -> @autoreleased NSString
// CHECK: enum $Optional<@convention(block) (NSString) -> @autoreleased NSString>, #Optional.some!enumelt.1, [[G_BLOCK]]
return (x.foo(f, x: 0), x.bar(g, x: "one"), x.bas(h, x: "two"), x.optFunc(g, x: "three"))
}
class Test: NSObject {
func blockTakesBlock() -> ((Int) -> Int) -> Int {}
}
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0S2iIxyd_SiIxxd_S2iIyByd_SiIyByd_TR
// CHECK: [[BLOCK_COPY:%.*]] = copy_block [[ORIG_BLOCK:%.*]] :
// CHECK: [[CLOSURE:%.*]] = partial_apply {{%.*}}([[BLOCK_COPY]])
// CHECK: [[RESULT:%.*]] = apply {{%.*}}([[CLOSURE]])
// CHECK: return [[RESULT]]
func clearDraggingItemImageComponentsProvider(_ x: NSDraggingItem) {
x.imageComponentsProvider = {}
}
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0SayypGIxo_So7NSArrayCSgIyBa_TR
// CHECK: [[CONVERT:%.*]] = function_ref @_T0Sa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF
// CHECK: [[CONVERTED:%.*]] = apply [[CONVERT]]
// CHECK: [[OPTIONAL:%.*]] = enum $Optional<NSArray>, #Optional.some!enumelt.1, [[CONVERTED]]
// CHECK: return [[OPTIONAL]]
// CHECK-LABEL: sil hidden @{{.*}}bridgeNonnullBlockResult{{.*}}
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0SSIxo_So8NSStringCSgIyBa_TR
// CHECK: [[CONVERT:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF
// CHECK: [[BRIDGED:%.*]] = apply [[CONVERT]]
// CHECK: [[OPTIONAL_BRIDGED:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]]
// CHECK: return [[OPTIONAL_BRIDGED]]
func bridgeNonnullBlockResult() {
nonnullStringBlockResult { return "test" }
}
// CHECK-LABEL: sil hidden @{{.*}}bridgeNoescapeBlock{{.*}}
func bridgeNoescapeBlock() {
// CHECK: function_ref @_T0Ix_IyB_TR
noescapeBlockAlias { }
// CHECK: function_ref @_T0Ix_IyB_TR
noescapeNonnullBlockAlias { }
}
class ObjCClass : NSObject {}
extension ObjCClass {
func someDynamicMethod(closure: (() -> ()) -> ()) {}
}
struct GenericStruct<T> {
let closure: (() -> ()) -> ()
func doStuff(o: ObjCClass) {
o.someDynamicMethod(closure: closure)
}
}
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0Ix_Ixx_IyB_IyBy_TR : $@convention(c) (@inout_aliasable @block_storage @callee_owned (@owned @callee_owned () -> ()) -> (), @convention(block) () -> ()) -> ()
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0IyB_Ix_TR : $@convention(thin) (@owned @convention(block) () -> ()) -> ()
| apache-2.0 | 3edbf2399e0f0690314cac5ad2757992 | 60.810811 | 271 | 0.602624 | 3.36027 | false | false | false | false |
nelfurion/IOS-Project | soa/SoA/SoA/Apis/Media/SoundEngine.swift | 1 | 989 | //
// SoundEngine.swift
// SoA
//
// Created by John Doe on 2/8/16.
// Copyright © 2016 John Doe. All rights reserved.
//
/*
import Foundation
import AVFoundation
class SoundEngine : NSObject {
var player:AVAudioPlayer;
override init() {
player = AVAudioPlayer()
super.init()
}
func play(fileName: String, type: String) {
let soundFilePath:String = NSBundle.mainBundle().pathForResource(fileName, ofType: type)!;
let soundData:NSData = NSData(contentsOfFile: soundFilePath)!;
do {
try player = AVAudioPlayer(data: soundData);
player.prepareToPlay();
player.play();
}
catch {
print("Sound engine could not play file.");
}
}
func toggle() {
if (player.playing) {
player.stop();
player.currentTime = 0;
} else {
player.prepareToPlay();
player.play();
}
}
}
*/ | mit | 8197e6898decb38691834eccd9ed33e5 | 22 | 98 | 0.549595 | 4.511416 | false | false | false | false |
symentis/Palau | Sources/PalauEntry.swift | 1 | 5908 | //
// PalauEntry.swift
// Palau
//
// Created by symentis GmbH on 05.05.16.
// Copyright © 2016 symentis GmbH. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// -------------------------------------------------------------------------------------------------
// MARK: - PalauEntry Protocol
// -------------------------------------------------------------------------------------------------
/// PalauEntry is the base protocol for PalauEntry or PalauArrayEntry
/// By extending the protocol we can provide the default functionality
/// to both types
public protocol PalauEntry {
/// the ValueType must conform to PalauDefaultable
associatedtype ValueType: PalauDefaultable
/// the return type can be e.g. ValueType or [ValueType]
associatedtype ReturnType
/// the key in defaults
var key: String { get }
/// access to the defaults
var defaults: NSUD { get }
/// A function to change the incoming and outgoing value
var ensure: (ReturnType?) -> ReturnType? { get }
/// A function as callback after set
var didSet: ((_ newValue: ReturnType?, _ oldValue: ReturnType?) -> Void)? { get }
/// computed property for the return value
var value: ReturnType? { get set }
/// inititalizer
// init(key: String,
// defaults: NSUD,
// ensure: @escaping (ReturnType?) -> ReturnType?
// )
init(key: String,
defaults: NSUD,
didSet: ((_ newValue: ReturnType?, _ oldValue: ReturnType?) -> Void)?,
ensure: @escaping (ReturnType?) -> ReturnType?
)
}
// -------------------------------------------------------------------------------------------------
// MARK: - PalauEntry Default Extension
// -------------------------------------------------------------------------------------------------
extension PalauEntry {
// -----------------------------------------------------------------------------------------------
// MARK: - Clear
// -----------------------------------------------------------------------------------------------
/// Use this function to remove a default value
/// without additional calls of the ensure function
public func clear() {
withDidSet {
self.defaults.removeObject(forKey: self.key)
}
}
// -----------------------------------------------------------------------------------------------
// MARK: - DidSet Observation
// -----------------------------------------------------------------------------------------------
/// private helper to take care of didSet
func withDidSet(_ changeValue: () -> Void) {
let callback: (() -> Void)?
// check if callback is necessary as optional didSet is provided
if let didSet = didSet {
let old = value
callback = { didSet(self.value, old) }
} else {
callback = nil
}
// perform remove
changeValue()
// perform optional callback
callback?()
}
// -----------------------------------------------------------------------------------------------
// MARK: - Rules
// -----------------------------------------------------------------------------------------------
/// Helper function to take care of the value thats is read and written
/// usage like:
/// The functions provided for 'when' parameter can be implemented for any use case
/// ```
/// public static var intValueWithMinOf10: PalauDefaultsEntry<Int> {
/// get {
/// return value("intValue")
/// .ensure(when: isEqual(0), use: 20)
/// .ensure(when: lessThan(10), use: 10)
/// }
/// set {}
/// }
/// ```
public func ensure(when whenFunc: @escaping (ReturnType?) -> Bool,
use defaultValue: ReturnType) -> Self {
// if let didSet = didSet {
// return Self(key: key, defaults: defaults, didSet: didSet) {
// let vx = self.ensure($0)
// return whenFunc(vx) ? defaultValue : vx
// }
// }
return Self(key: key, defaults: defaults, didSet: didSet) {
let vx = self.ensure($0)
return whenFunc(vx) ? defaultValue : vx
}
}
/// Helper function to return a fallback in case the value is nil
public func whenNil(use defaultValue: ReturnType) -> Self {
return ensure(when: PalauDefaults.isEmpty, use: defaultValue)
}
// -----------------------------------------------------------------------------------------------
// MARK: - Observer
// -----------------------------------------------------------------------------------------------
/// Add a callback when the value is set in the defaults
/// - parameter callback: functions which receives the optional old and optional new vale
/// - returns: PalauDefaultsEntry<T>
public func didSet(_ callback: @escaping ((_ newValue: ReturnType?, _ oldValue: ReturnType?) -> Void)) -> Self {
return Self(key: key, defaults: defaults, didSet: callback, ensure: ensure)
}
}
| apache-2.0 | c1900cd4953e7d6d178c86612c1efd96 | 36.865385 | 114 | 0.532758 | 5.014431 | false | false | false | false |
Miguel-Herrero/Swift | Pro Swift/functions/Operator overloading.playground/Contents.swift | 1 | 1491 | /**
Simple overriding the != operator.
- Parameters:
- lhs: Left hand side comparison.
- rhs: Right hand side comparison.
- Returns: Return if these two args are different.
*/
func !=(lhs: Int, rhs: Int) -> Bool {
return true
}
print(4 != 4)
/**
Adding to an existing operator.
*/
func *(lhs: [Int], rhs: [Int]) -> [Int] {
/// Instead of checkinf “if lhs.count != rhs.count…”
guard lhs.count == rhs.count else { return lhs }
var result = [Int]()
for (index, int) in lhs.enumerated() {
result.append(int * rhs[index])
}
return result
}
let result = [1, 2, 3] * [1, 2, 3]
/**
Adding a new operator
*/
import Foundation
infix operator **: ExponentiationPrecedence
precedencegroup ExponentiationPrecedence {
higherThan: MultiplicationPrecedence
associativity: right
}
/**
- Returns: One value raised to the power of another.
- Parameters:
- lhs: The base of the power.
- rhs: The exponent of the power.
*/
func **(lhs: Double, rhs: Double) -> Double {
return pow(lhs, rhs)
}
let powResult = 4 ** 3 ** 2 + 3
/**
Modifying an operator.
*/
precedencegroup RangeFormationPrecedence {
associativity: left
higherThan: CastingPrecedence
}
infix operator ... : RangeFormationPrecedence
func ...(lhs: CountableClosedRange<Int>, rhs: Int) -> [Int] {
let downwards = (rhs ..< lhs.upperBound).reversed()
return Array(lhs) + downwards
}
let range = 1...10...1
print(range) | gpl-3.0 | 5a1a7486a9523ed97274853933a6cb25 | 18.298701 | 61 | 0.632997 | 3.721805 | false | false | false | false |
airspeedswift/swift | test/Driver/linker.swift | 2 | 25616 | // Must be able to run xcrun-return-self.sh
// REQUIRES: shell
// REQUIRES: rdar65281056
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-macosx10.9 %s 2>&1 > %t.simple.txt
// RUN: %FileCheck %s < %t.simple.txt
// RUN: %FileCheck -check-prefix SIMPLE %s < %t.simple.txt
// RUN: not %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-macosx10.9 -static-stdlib %s 2>&1 | %FileCheck -check-prefix=SIMPLE_STATIC %s
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-ios7.1-simulator %s 2>&1 > %t.simple.txt
// RUN: %FileCheck -check-prefix IOS_SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-tvos9.0-simulator %s 2>&1 > %t.simple.txt
// RUN: %FileCheck -check-prefix tvOS_SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target i386-apple-watchos2.0-simulator %s 2>&1 > %t.simple.txt
// RUN: %FileCheck -check-prefix watchOS_SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-unknown-linux-gnu -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-x86_64 %s < %t.linux.txt
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target armv6-unknown-linux-gnueabihf -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-armv6 %s < %t.linux.txt
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target armv7-unknown-linux-gnueabihf -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-armv7 %s < %t.linux.txt
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target thumbv7-unknown-linux-gnueabihf -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-thumbv7 %s < %t.linux.txt
// RUN: %swiftc_driver_plain -driver-print-jobs -target armv7-none-linux-androideabi -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.android.txt
// RUN: %FileCheck -check-prefix ANDROID-armv7 %s < %t.android.txt
// RUN: %FileCheck -check-prefix ANDROID-armv7-NEGATIVE %s < %t.android.txt
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-unknown-windows-cygnus -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.cygwin.txt
// RUN: %FileCheck -check-prefix CYGWIN-x86_64 %s < %t.cygwin.txt
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-unknown-windows-msvc -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.windows.txt
// RUN: %FileCheck -check-prefix WINDOWS-x86_64 %s < %t.windows.txt
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target amd64-unknown-openbsd -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.openbsd.txt
// RUN: %FileCheck -check-prefix OPENBSD-amd64 %s < %t.openbsd.txt
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -emit-library -target x86_64-unknown-linux-gnu %s -Lbar -o dynlib.out 2>&1 > %t.linux.dynlib.txt
// RUN: %FileCheck -check-prefix LINUX_DYNLIB-x86_64 %s < %t.linux.dynlib.txt
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -emit-library -target x86_64-apple-macosx10.9.1 %s -sdk %S/../Inputs/clang-importer-sdk -lfoo -framework bar -Lbaz -Fgarply -Fsystem car -F cdr -Xlinker -undefined -Xlinker dynamic_lookup -o sdk.out 2>&1 > %t.complex.txt
// RUN: %FileCheck %s < %t.complex.txt
// RUN: %FileCheck -check-prefix COMPLEX %s < %t.complex.txt
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-ios7.1-simulator -Xlinker -rpath -Xlinker customrpath -L foo %s 2>&1 > %t.simple.txt
// RUN: %FileCheck -check-prefix IOS-linker-order %s < %t.simple.txt
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target armv7-unknown-linux-gnueabihf -Xlinker -rpath -Xlinker customrpath -L foo %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-linker-order %s < %t.linux.txt
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-unknown-linux-gnu -Xclang-linker -foo -Xclang-linker foopath %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-clang-linker-order %s < %t.linux.txt
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-unknown-windows-msvc -Xclang-linker -foo -Xclang-linker foopath %s 2>&1 > %t.windows.txt
// RUN: %FileCheck -check-prefix WINDOWS-clang-linker-order %s < %t.windows.txt
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target wasm32-unknown-wasi -Xclang-linker -flag -Xclang-linker arg %s 2>&1 | %FileCheck -check-prefix WASI-clang-linker-order %s
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-macosx10.9 -g %s | %FileCheck -check-prefix DEBUG %s
// RUN: %swiftc_driver_plain -driver-print-jobs -target x86_64-unknown-linux-gnu -toolchain-stdlib-rpath %s 2>&1 | %FileCheck -check-prefix LINUX-STDLIB-RPATH %s
// RUN: %swiftc_driver_plain -driver-print-jobs -target x86_64-unknown-linux-gnu -no-toolchain-stdlib-rpath %s 2>&1 | %FileCheck -check-prefix LINUX-NO-STDLIB-RPATH %s
// RUN: %swiftc_driver_plain -driver-print-jobs -target armv7-unknown-linux-androideabi -toolchain-stdlib-rpath %s 2>&1 | %FileCheck -check-prefix ANDROID-STDLIB-RPATH %s
// RUN: %swiftc_driver_plain -driver-print-jobs -target armv7-unknown-linux-androideabi -no-toolchain-stdlib-rpath %s 2>&1 | %FileCheck -check-prefix ANDROID-NO-STDLIB-RPATH %s
// RUN: %empty-directory(%t)
// RUN: touch %t/a.o
// RUN: touch %t/a.swiftmodule
// RUN: touch %t/b.o
// RUN: touch %t/b.swiftmodule
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o %t/a.swiftmodule %t/b.o %t/b.swiftmodule -o linker | %FileCheck -check-prefix LINK-SWIFTMODULES %s
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-macosx10.10 %s > %t.simple-macosx10.10.txt
// RUN: %FileCheck %s < %t.simple-macosx10.10.txt
// RUN: %FileCheck -check-prefix SIMPLE %s < %t.simple-macosx10.10.txt
// RUN: %empty-directory(%t)
// RUN: echo "int dummy;" >%t/a.cpp
// RUN: cc -c %t/a.cpp -o %t/a.o
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o -o linker 2>&1 | %FileCheck -check-prefix COMPILE_AND_LINK %s
// RUN: %swiftc_driver -sdk "" -save-temps -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o -driver-filelist-threshold=0 -o linker 2>&1 | tee %t/forFilelistCapture | %FileCheck -check-prefix FILELIST %s
// Extract filelist name and check it out
// RUN: tail -1 %t/forFilelistCapture | sed 's/.*-filelist //' | sed 's/ .*//' >%t/filelistName
// RUN: %FileCheck -check-prefix FILELIST-CONTENTS %s < `cat %t/filelistName`
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-macosx10.9 -emit-library %s -module-name LINKER | %FileCheck -check-prefix INFERRED_NAME_DARWIN %s
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-unknown-linux-gnu -emit-library %s -module-name LINKER | %FileCheck -check-prefix INFERRED_NAME_LINUX %s
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-unknown-windows-cygnus -emit-library %s -module-name LINKER | %FileCheck -check-prefix INFERRED_NAME_WINDOWS %s
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-unknown-windows-msvc -emit-library %s -module-name LINKER | %FileCheck -check-prefix INFERRED_NAME_WINDOWS %s
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target wasm32-unknown-wasi -emit-library %s -module-name LINKER | %FileCheck -check-prefix INFERRED_NAME_WASI %s
// Here we specify an output file name using '-o'. For ease of writing these
// tests, we happen to specify the same file name as is inferred in the
// INFERRED_NAMED_DARWIN tests above: 'libLINKER.dylib'.
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-macosx10.9 -emit-library %s -o libLINKER.dylib | %FileCheck -check-prefix INFERRED_NAME_DARWIN %s
// On Darwin, when C++ interop is turned on, we link against libc++ explicitly
// regardless of whether -experimental-cxx-stdlib is specified or not. So also
// run a test where C++ interop is turned off to make sure we don't link
// against libc++ in this case.
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-ios7.1 %s 2>&1 | %FileCheck -check-prefix IOS-no-cxx-interop %s
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-ios7.1 -enable-experimental-cxx-interop %s 2>&1 | %FileCheck -check-prefix IOS-cxx-interop-libcxx %s
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-ios7.1 -enable-experimental-cxx-interop -experimental-cxx-stdlib libc++ %s 2>&1 | %FileCheck -check-prefix IOS-cxx-interop-libcxx %s
// RUN: not %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-ios7.1 -enable-experimental-cxx-interop -experimental-cxx-stdlib libstdc++ %s 2>&1 | %FileCheck -check-prefix IOS-cxx-interop-libstdcxx %s
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-unknown-linux-gnu -enable-experimental-cxx-interop %s 2>&1 | %FileCheck -check-prefix LINUX-cxx-interop %s
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-unknown-linux-gnu -enable-experimental-cxx-interop -experimental-cxx-stdlib libc++ %s 2>&1 | %FileCheck -check-prefix LINUX-cxx-interop-libcxx %s
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-unknown-windows-msvc -enable-experimental-cxx-interop %s 2>&1 | %FileCheck -check-prefix WINDOWS-cxx-interop %s
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-unknown-windows-msvc -enable-experimental-cxx-interop -experimental-cxx-stdlib libc++ %s 2>&1 | %FileCheck -check-prefix WINDOWS-cxx-interop-libcxx %s
// Check reading the SDKSettings.json from an SDK
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-macosx10.9 -sdk %S/Inputs/MacOSX10.15.versioned.sdk %s 2>&1 | %FileCheck -check-prefix MACOS_10_15 %s
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-macosx10.9 -sdk %S/Inputs/MacOSX10.15.4.versioned.sdk %s 2>&1 | %FileCheck -check-prefix MACOS_10_15_4 %s
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-macosx10.9 -sdk %S/Inputs/MacOSX10.15.sdk %s 2>&1 | %FileCheck -check-prefix MACOS_UNVERSIONED %s
// Check arm64 macOS first deployment version adjustment.
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target arm64-apple-macosx10.15.1 %s 2>&1 | %FileCheck -check-prefix ARM64E_MACOS_LINKER %s
// Check x86 macOS 11 deployment version adjustment.
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-macosx11.0 %s 2>&1 | %FileCheck -check-prefix X86_MACOS11_LINKER %s
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target arm64-apple-macosx11.0 %s 2>&1 | %FileCheck -check-prefix ARM64E_MACOS_LINKER %s
// Check arm64 simulators first deployment version adjustment.
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target arm64-apple-ios13.0-simulator %s 2>&1 | %FileCheck -check-prefix ARM64_IOS_SIMULATOR_LINKER %s
// MACOS_10_15: -platform_version macos 10.9.0 10.15.0
// MACOS_10_15_4: -platform_version macos 10.9.0 10.15.4
// MACOS_UNVERSIONED: -platform_version macos 10.9.0 0.0.0
// ARM64E_MACOS_LINKER: -platform_version macos 11.0.0
// X86_MACOS11_LINKER: -platform_version macos 10.16.0
// X86_64_WATCHOS_SIM_LINKER: -platform_version watchos-simulator 7.0.0
// ARM64_IOS_SIMULATOR_LINKER: -platform_version ios-simulator 14.0.0
// There are more RUN lines further down in the file.
// CHECK: swift
// CHECK: -o [[OBJECTFILE:.*]]
// CHECK-NEXT: {{(bin/)?}}ld{{"? }}
// CHECK-DAG: [[OBJECTFILE]]
// CHECK-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)macosx]]
// CHECK-DAG: -rpath [[STDLIB_PATH]]
// CHECK-DAG: -lSystem
// CHECK-DAG: -arch x86_64
// CHECK: -o {{[^ ]+}}
// SIMPLE: {{(bin/)?}}ld{{"? }}
// SIMPLE-NOT: -syslibroot
// SIMPLE: -platform_version macos 10.{{[0-9]+}}.{{[0-9]+}} 0.0.0
// SIMPLE-NOT: -syslibroot
// SIMPLE: -o linker
// SIMPLE_STATIC: error: -static-stdlib is no longer supported on Apple platforms
// IOS_SIMPLE: swift
// IOS_SIMPLE: -o [[OBJECTFILE:.*]]
// IOS_SIMPLE: {{(bin/)?}}ld{{"? }}
// IOS_SIMPLE-DAG: [[OBJECTFILE]]
// IOS_SIMPLE-DAG: -L {{[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)iphonesimulator}}
// IOS_SIMPLE-DAG: -lSystem
// IOS_SIMPLE-DAG: -arch x86_64
// IOS_SIMPLE-DAG: -platform_version ios-simulator 7.1.{{[0-9]+}} 0.0.0
// IOS_SIMPLE: -o linker
// tvOS_SIMPLE: swift
// tvOS_SIMPLE: -o [[OBJECTFILE:.*]]
// tvOS_SIMPLE: {{(bin/)?}}ld{{"? }}
// tvOS_SIMPLE-DAG: [[OBJECTFILE]]
// tvOS_SIMPLE-DAG: -L {{[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)appletvsimulator}}
// tvOS_SIMPLE-DAG: -lSystem
// tvOS_SIMPLE-DAG: -arch x86_64
// tvOS_SIMPLE-DAG: -platform_version tvos-simulator 9.0.{{[0-9]+}} 0.0.0
// tvOS_SIMPLE: -o linker
// watchOS_SIMPLE: swift
// watchOS_SIMPLE: -o [[OBJECTFILE:.*]]
// watchOS_SIMPLE: {{(bin/)?}}ld{{"? }}
// watchOS_SIMPLE-DAG: [[OBJECTFILE]]
// watchOS_SIMPLE-DAG: -L {{[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)watchsimulator}}
// watchOS_SIMPLE-DAG: -lSystem
// watchOS_SIMPLE-DAG: -arch i386
// watchOS_SIMPLE-DAG: -platform_version watchos-simulator 2.0.{{[0-9]+}} 0.0.0
// watchOS_SIMPLE: -o linker
// LINUX-x86_64: swift
// LINUX-x86_64: -o [[OBJECTFILE:.*]]
// LINUX-x86_64: clang{{(\.exe)?"? }}
// LINUX-x86_64-DAG: -pie
// LINUX-x86_64-DAG: [[OBJECTFILE]]
// LINUX-x86_64-DAG: -lswiftCore
// LINUX-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)]]
// LINUX-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-x86_64-DAG: -F foo -iframework car -F cdr
// LINUX-x86_64-DAG: -framework bar
// LINUX-x86_64-DAG: -L baz
// LINUX-x86_64-DAG: -lboo
// LINUX-x86_64-DAG: -Xlinker -undefined
// LINUX-x86_64: -o linker
// LINUX-armv6: swift
// LINUX-armv6: -o [[OBJECTFILE:.*]]
// LINUX-armv6: clang{{(\.exe)?"? }}
// LINUX-armv6-DAG: -pie
// LINUX-armv6-DAG: [[OBJECTFILE]]
// LINUX-armv6-DAG: -lswiftCore
// LINUX-armv6-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)]]
// LINUX-armv6-DAG: -target armv6-unknown-linux-gnueabihf
// LINUX-armv6-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-armv6-DAG: -F foo -iframework car -F cdr
// LINUX-armv6-DAG: -framework bar
// LINUX-armv6-DAG: -L baz
// LINUX-armv6-DAG: -lboo
// LINUX-armv6-DAG: -Xlinker -undefined
// LINUX-armv6: -o linker
// LINUX-armv7: swift
// LINUX-armv7: -o [[OBJECTFILE:.*]]
// LINUX-armv7: clang{{(\.exe)?"? }}
// LINUX-armv7-DAG: -pie
// LINUX-armv7-DAG: [[OBJECTFILE]]
// LINUX-armv7-DAG: -lswiftCore
// LINUX-armv7-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)]]
// LINUX-armv7-DAG: -target armv7-unknown-linux-gnueabihf
// LINUX-armv7-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-armv7-DAG: -F foo -iframework car -F cdr
// LINUX-armv7-DAG: -framework bar
// LINUX-armv7-DAG: -L baz
// LINUX-armv7-DAG: -lboo
// LINUX-armv7-DAG: -Xlinker -undefined
// LINUX-armv7: -o linker
// LINUX-thumbv7: swift
// LINUX-thumbv7: -o [[OBJECTFILE:.*]]
// LINUX-thumbv7: clang{{(\.exe)?"? }}
// LINUX-thumbv7-DAG: -pie
// LINUX-thumbv7-DAG: [[OBJECTFILE]]
// LINUX-thumbv7-DAG: -lswiftCore
// LINUX-thumbv7-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)]]
// LINUX-thumbv7-DAG: -target thumbv7-unknown-linux-gnueabihf
// LINUX-thumbv7-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-thumbv7-DAG: -F foo -iframework car -F cdr
// LINUX-thumbv7-DAG: -framework bar
// LINUX-thumbv7-DAG: -L baz
// LINUX-thumbv7-DAG: -lboo
// LINUX-thumbv7-DAG: -Xlinker -undefined
// LINUX-thumbv7: -o linker
// ANDROID-armv7: swift
// ANDROID-armv7: -o [[OBJECTFILE:.*]]
// ANDROID-armv7: clang{{(\.exe)?"? }}
// ANDROID-armv7-DAG: -pie
// ANDROID-armv7-DAG: [[OBJECTFILE]]
// ANDROID-armv7-DAG: -lswiftCore
// ANDROID-armv7-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift]]
// ANDROID-armv7-DAG: -target armv7-unknown-linux-androideabi
// ANDROID-armv7-DAG: -F foo -iframework car -F cdr
// ANDROID-armv7-DAG: -framework bar
// ANDROID-armv7-DAG: -L baz
// ANDROID-armv7-DAG: -lboo
// ANDROID-armv7-DAG: -Xlinker -undefined
// ANDROID-armv7: -o linker
// ANDROID-armv7-NEGATIVE-NOT: -Xlinker -rpath
// CYGWIN-x86_64: swift
// CYGWIN-x86_64: -o [[OBJECTFILE:.*]]
// CYGWIN-x86_64: clang{{(\.exe)?"? }}
// CYGWIN-x86_64-DAG: [[OBJECTFILE]]
// CYGWIN-x86_64-DAG: -lswiftCore
// CYGWIN-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift]]
// CYGWIN-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// CYGWIN-x86_64-DAG: -F foo -iframework car -F cdr
// CYGWIN-x86_64-DAG: -framework bar
// CYGWIN-x86_64-DAG: -L baz
// CYGWIN-x86_64-DAG: -lboo
// CYGWIN-x86_64-DAG: -Xlinker -undefined
// CYGWIN-x86_64: -o linker
// WINDOWS-x86_64: swift
// WINDOWS-x86_64: -o [[OBJECTFILE:.*]]
// WINDOWS-x86_64: clang{{(\.exe)?"? }}
// WINDOWS-x86_64-DAG: [[OBJECTFILE]]
// WINDOWS-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)windows(/|\\\\)x86_64]]
// WINDOWS-x86_64-DAG: -F foo -iframework car -F cdr
// WINDOWS-x86_64-DAG: -framework bar
// WINDOWS-x86_64-DAG: -L baz
// WINDOWS-x86_64-DAG: -lboo
// WINDOWS-x86_64-DAG: -Xlinker -undefined
// WINDOWS-x86_64: -o linker
// OPENBSD-amd64: swift
// OPENBSD-amd64: -o [[OBJECTFILE:.*]]
// OPENBSD-amd64: clang
// OPENBSD-amd64-DAG: -fuse-ld=lld
// OPENBSD-amd64-DAG: [[OBJECTFILE]]
// OPENBSD-amd64-DAG: -lswiftCore
// OPENBSD-amd64-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)]]
// OPENBSD-amd64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// OPENBSD-amd64-DAG: -F foo -iframework car -F cdr
// OPENBSD-amd64-DAG: -framework bar
// OPENBSD-amd64-DAG: -L baz
// OPENBSD-amd64-DAG: -lboo
// OPENBSD-amd64-DAG: -Xlinker -undefined
// OPENBSD-amd64: -o linker
// COMPLEX: {{(bin/)?}}ld{{"? }}
// COMPLEX-DAG: -dylib
// COMPLEX-DAG: -syslibroot {{.*}}/Inputs/clang-importer-sdk
// COMPLEX-DAG: -lfoo
// COMPLEX-DAG: -framework bar
// COMPLEX-DAG: -L baz
// COMPLEX-DAG: -F garply -F car -F cdr
// COMPLEX-DAG: -undefined dynamic_lookup
// COMPLEX-DAG: -platform_version macos 10.9.1 0.0.0
// COMPLEX: -o sdk.out
// LINUX_DYNLIB-x86_64: swift
// LINUX_DYNLIB-x86_64: -o [[OBJECTFILE:.*]]
// LINUX_DYNLIB-x86_64: -o {{"?}}[[AUTOLINKFILE:.*]]
// LINUX_DYNLIB-x86_64: clang{{(\.exe)?"? }}
// LINUX_DYNLIB-x86_64-DAG: -shared
// LINUX_DYNLIB-x86_64-DAG: -fuse-ld=gold
// LINUX_DYNLIB-x86_64-NOT: -pie
// LINUX_DYNLIB-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)linux]]
// LINUX_DYNLIB-x86_64: [[STDLIB_PATH]]{{/|\\\\}}x86_64{{/|\\\\}}swiftrt.o
// LINUX_DYNLIB-x86_64-DAG: [[OBJECTFILE]]
// LINUX_DYNLIB-x86_64-DAG: @[[AUTOLINKFILE]]
// LINUX_DYNLIB-x86_64-DAG: [[STDLIB_PATH]]
// LINUX_DYNLIB-x86_64-DAG: -lswiftCore
// LINUX_DYNLIB-x86_64-DAG: -L bar
// LINUX_DYNLIB-x86_64: -o dynlib.out
// IOS-linker-order: swift
// IOS-linker-order: -o [[OBJECTFILE:.*]]
// IOS-linker-order: {{(bin/)?}}ld{{"? }}
// IOS-linker-order: -rpath [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)iphonesimulator]]
// IOS-linker-order: -L foo
// IOS-linker-order: -rpath customrpath
// IOS-linker-order: -o {{.*}}
// LINUX-linker-order: swift
// LINUX-linker-order: -o [[OBJECTFILE:.*]]
// LINUX-linker-order: clang{{(\.exe)?"? }}
// LINUX-linker-order: -Xlinker -rpath -Xlinker {{[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)linux}}
// LINUX-linker-order: -L foo
// LINUX-linker-order: -Xlinker -rpath -Xlinker customrpath
// LINUX-linker-order: -o {{.*}}
// LINUX-clang-linker-order: swift
// LINUX-clang-linker-order: -o [[OBJECTFILE:.*]]
// LINUX-clang-linker-order: clang{{"? }}
// LINUX-clang-linker-order: -foo foopath
// LINUX-clang-linker-order: -o {{.*}}
// WINDOWS-clang-linker-order: swift
// WINDOWS-clang-linker-order: -o [[OBJECTFILE:.*]]
// WINDOWS-clang-linker-order: clang{{"? }}
// WINDOWS-clang-linker-order: -foo foopath
// WINDOWS-clang-linker-order: -o {{.*}}
// WASI-clang-linker-order: swift
// WASI-clang-linker-order: -o [[OBJECTFILE:.*]]
// WASI-clang-linker-order: clang{{"? }}
// WASI-clang-linker-order: -flag arg
// WASI-clang-linker-order: -o {{.*}}
// DEBUG: bin{{/|\\\\}}swift{{c?(\.EXE)?}}
// DEBUG-NEXT: bin{{/|\\\\}}swift{{c?(\.EXE)?}}
// DEBUG-NEXT: {{(bin/)?}}ld{{"? }}
// DEBUG: -add_ast_path {{.*(/|\\\\)[^/]+}}.swiftmodule
// DEBUG: -o linker
// DEBUG-NEXT: bin{{/|\\\\}}dsymutil
// DEBUG: linker
// DEBUG: -o linker.dSYM
// LINK-SWIFTMODULES: bin{{/|\\\\}}swift{{c?(\.EXE)?}}
// LINK-SWIFTMODULES-NEXT: {{(bin/)?}}ld{{"? }}
// LINK-SWIFTMODULES-SAME: -add_ast_path {{.*}}/a.swiftmodule
// LINK-SWIFTMODULES-SAME: -add_ast_path {{.*}}/b.swiftmodule
// LINK-SWIFTMODULES-SAME: -o linker
// COMPILE_AND_LINK: bin{{/|\\\\}}swift{{c?(\.EXE)?}}
// COMPILE_AND_LINK-NOT: /a.o
// COMPILE_AND_LINK: linker.swift
// COMPILE_AND_LINK-NOT: /a.o
// COMPILE_AND_LINK-NEXT: {{(bin/)?}}ld{{"? }}
// COMPILE_AND_LINK-DAG: /a.o
// COMPILE_AND_LINK-DAG: .o
// COMPILE_AND_LINK: -o linker
// FILELIST: {{(bin/)?}}ld{{"? }}
// FILELIST-NOT: .o{{"? }}
// FILELIST: -filelist {{"?[^-]}}
// FILELIST-NOT: .o{{"? }}
// FILELIST: -o linker
// FILELIST-CONTENTS: /linker-{{.*}}.o
// FILELIST-CONTENTS: /a.o
// INFERRED_NAME_DARWIN: bin{{/|\\\\}}swift{{c?(\.EXE)?}}
// INFERRED_NAME_DARWIN: -module-name LINKER
// INFERRED_NAME_DARWIN: {{(bin/)?}}ld{{"? }}
// INFERRED_NAME_DARWIN: -o libLINKER.dylib
// INFERRED_NAME_LINUX: -o libLINKER.so
// INFERRED_NAME_WINDOWS: -o LINKER.dll
// INFERRED_NAME_WASI: -o libLINKER.so
// Instead of a single "NOT" check for this run, we would really want to check
// for all of the driver arguments that we _do_ expect, and then use an
// --implicit-check-not to check that -lc++ doesn't occur.
// However, --implicit-check-not has a bug where it fails to flag the
// unexpected text when it occurs after text matched by a CHECK-DAG; see
// https://bugs.llvm.org/show_bug.cgi?id=45629
// For this reason, we use a single "NOT" check for the time being here.
// The same consideration applies to the Linux and Windows cases below.
// IOS-no-cxx-interop-NOT: -lc++
// IOS-cxx-interop-libcxx: swift
// IOS-cxx-interop-libcxx-DAG: -enable-cxx-interop
// IOS-cxx-interop-libcxx-DAG: -o [[OBJECTFILE:.*]]
// IOS-cxx-interop-libcxx: {{(bin/)?}}ld{{"? }}
// IOS-cxx-interop-libcxx-DAG: [[OBJECTFILE]]
// IOS-cxx-interop-libcxx-DAG: -lc++
// IOS-cxx-interop-libcxx: -o linker
// IOS-cxx-interop-libstdcxx: error: The only C++ standard library supported on Apple platforms is libc++
// LINUX-cxx-interop-NOT: -stdlib
// LINUX-cxx-interop-libcxx: swift
// LINUX-cxx-interop-libcxx-DAG: -enable-cxx-interop
// LINUX-cxx-interop-libcxx-DAG: -o [[OBJECTFILE:.*]]
// LINUX-cxx-interop-libcxx: clang++{{(\.exe)?"? }}
// LINUX-cxx-interop-libcxx-DAG: [[OBJECTFILE]]
// LINUX-cxx-interop-libcxx-DAG: -stdlib=libc++
// LINUX-cxx-interop-libcxx: -o linker
// WINDOWS-cxx-interop-NOT: -stdlib
// WINDOWS-cxx-interop-libcxx: swift
// WINDOWS-cxx-interop-libcxx-DAG: -enable-cxx-interop
// WINDOWS-cxx-interop-libcxx-DAG: -o [[OBJECTFILE:.*]]
// WINDOWS-cxx-interop-libcxx: clang++{{(\.exe)?"? }}
// WINDOWS-cxx-interop-libcxx-DAG: [[OBJECTFILE]]
// WINDOWS-cxx-interop-libcxx-DAG: -stdlib=libc++
// WINDOWS-cxx-interop-libcxx: -o linker
// Test ld detection. We use hard links to make sure
// the Swift driver really thinks it's been moved.
// RUN: rm -rf %t
// RUN: %empty-directory(%t/DISTINCTIVE-PATH/usr/bin)
// RUN: touch %t/DISTINCTIVE-PATH/usr/bin/ld
// RUN: chmod +x %t/DISTINCTIVE-PATH/usr/bin/ld
// RUN: %hardlink-or-copy(from: %swift_frontend_plain, to: %t/DISTINCTIVE-PATH/usr/bin/swiftc)
// RUN: %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | %FileCheck -check-prefix=RELATIVE-LINKER %s
// RELATIVE-LINKER: {{/|\\\\}}DISTINCTIVE-PATH{{/|\\\\}}usr{{/|\\\\}}bin{{/|\\\\}}swift
// RELATIVE-LINKER: {{/|\\\\}}DISTINCTIVE-PATH{{/|\\\\}}usr{{/|\\\\}}bin{{/|\\\\}}ld
// RELATIVE-LINKER: -o {{[^ ]+}}
// Also test arclite detection. This uses xcrun to find arclite when it's not
// next to Swift.
// RUN: %empty-directory(%t/ANOTHER-DISTINCTIVE-PATH/usr/bin)
// RUN: %empty-directory(%t/ANOTHER-DISTINCTIVE-PATH/usr/lib/arc)
// RUN: cp %S/Inputs/xcrun-return-self.sh %t/ANOTHER-DISTINCTIVE-PATH/usr/bin/xcrun
// RUN: env PATH=%t/ANOTHER-DISTINCTIVE-PATH/usr/bin %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | %FileCheck -check-prefix=XCRUN_ARCLITE %s
// XCRUN_ARCLITE: bin{{/|\\\\}}ld
// XCRUN_ARCLITE: {{/|\\\\}}ANOTHER-DISTINCTIVE-PATH{{/|\\\\}}usr{{/|\\\\}}lib{{/|\\\\}}arc{{/|\\\\}}libarclite_macosx.a
// XCRUN_ARCLITE: -o {{[^ ]+}}
// RUN: %empty-directory(%t/DISTINCTIVE-PATH/usr/lib/arc)
// RUN: env PATH=%t/ANOTHER-DISTINCTIVE-PATH/usr/bin %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | %FileCheck -check-prefix=RELATIVE_ARCLITE %s
// RELATIVE_ARCLITE: bin{{/|\\\\}}ld
// RELATIVE_ARCLITE: {{/|\\\\}}DISTINCTIVE-PATH{{/|\\\\}}usr{{/|\\\\}}lib{{/|\\\\}}arc{{/|\\\\}}libarclite_macosx.a
// RELATIVE_ARCLITE: -o {{[^ ]+}}
// LINUX-STDLIB-RPATH: -Xlinker -rpath -Xlinker [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)linux]]
// LINUX-NO-STDLIB-RPATH-NOT: -Xlinker -rpath -Xlinker [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)linux]]
// ANDROID-STDLIB-RPATH: -Xlinker -rpath -Xlinker [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)android]]
// ANDROID-NO-STDLIB-RPATH-NOT: -Xlinker -rpath -Xlinker [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)android]]
// Clean up the test executable because hard links are expensive.
// RUN: rm -rf %t/DISTINCTIVE-PATH/usr/bin/swiftc
| apache-2.0 | 1bb234266a2465e1e7cafd385a5e1bfc | 47.515152 | 270 | 0.666068 | 2.892176 | false | false | false | false |
KagasiraBunJee/TryHard | TryHard/THImageSelector.swift | 1 | 2627 | //
// THImageSelector.swift
// TryHard
//
// Created by Sergey on 6/16/16.
// Copyright © 2016 Sergey Polishchuk. All rights reserved.
//
import UIKit
//import HanabiCollectionViewLayout
import SDWebImage
class THImageSelector: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
var imageSelected: ((image:UIImage) -> ())?
let imagesUrls = [
"http://multilingualtypesetting.co.uk/blog/images/chinese-typesetting_english-original.png",
"http://i.stack.imgur.com/w0euX.png",
"http://universitypublishingonline.org/content/978/11/3952/429/2/9781139524292prf3_abstract_CBO.jpg",
"http://i1.ytimg.com/vi/OzZb1tthfEI/maxresdefault.jpg",
"http://www.stav.org.il/karmeli/pages/EnglishSample.png",
"http://i.stack.imgur.com/XuJOl.png"
]
override func viewDidLoad() {
super.viewDidLoad()
// let layout = HanabiCollectionViewLayout()
// layout.standartHeight = 100
// layout.focusedHeight = 280
// layout.dragOffset = 180
// collectionView.collectionViewLayout = layout
collectionView.delegate = self
collectionView.dataSource = self
}
//MARK:- IBActions
@IBAction func selectImage(sender: AnyObject) {
}
@IBAction func cancel(sender: AnyObject) {
}
//MARK:- UICollectionViewDataSource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imagesUrls.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("imageCell", forIndexPath: indexPath) as! ImageCell
let urlString = NSURL(string: imagesUrls[indexPath.row])!
SDWebImageManager.sharedManager().downloadImageWithURL(urlString, options: .ContinueInBackground, progress: nil) { (image, error, cacheType, true, url) in
cell.imageCell.image = image
}
return cell
}
//MARK:- UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! ImageCell
let image = cell.imageCell.image
imageSelected?(image: image!)
self.navigationController?.popViewControllerAnimated(true)
}
}
| mit | d2201bc5d22cfbd44622dca6b693eb53 | 32.666667 | 162 | 0.675552 | 4.731532 | false | false | false | false |
haawa799/WaniKit2 | Sources/WaniKit/WaniKit operations/UserInfo/ParseUserInfoOperation.swift | 2 | 751 | //
// ParseUserInfoOperation.swift
// Pods
//
// Created by Andriy K. on 12/14/15.
//
//
import Foundation
public typealias UserInfoResponse = (UserInfo?)
public typealias UserInfoResponseHandler = (Result<UserInfoResponse, NSError>) -> Void
public class ParseUserInfoOperation: ParseOperation<UserInfoResponse> {
override init(cacheFile: NSURL, handler: ResponseHandler) {
super.init(cacheFile: cacheFile, handler: handler)
name = "Parse User info"
}
override func parsedValue(rootDictionary: NSDictionary?) -> UserInfoResponse? {
var user: UserInfo?
if let userInfo = rootDictionary?[WaniKitConstants.ResponseKeys.UserInfoKey] as? NSDictionary {
user = UserInfo(dict: userInfo)
}
return user
}
} | mit | 5666e01cb4059c3f086f9d6e48233251 | 24.066667 | 99 | 0.724368 | 4.195531 | false | false | false | false |
epayco/sdk-ios | Epayco/EpaycoStringExtension.swift | 1 | 2438 | //
// EpaycoStringExtension.swift
// Epayco
//
// Created by Kleiber J Perez on 2/5/17.
// Copyright © 2017 Epayco. All rights reserved.
//
import Foundation
private let kGenericISOFormat:String = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
internal extension String {
func dateValue(from format:String = kGenericISOFormat) -> Date? {
guard !self.isEmpty else { return nil }
let formatter = DateFormatter()
formatter.dateFormat = format
formatter.timeZone = TimeZone.ReferenceType.local
return formatter.date(from: self)
}
var isNumeric: Bool {
return !self.isEmpty && self.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
}
var isPhoneNumber: Bool {
guard isNumeric else { return false }
return checkMatch(for: .phoneNumber)
}
var isEmail:Bool {
guard !self.isEmpty else { return false }
return checkMatch(for: .link)
}
var isIPValid: Bool {
guard !self.isEmpty else { return false }
var sin = sockaddr_in()
var sin6 = sockaddr_in6()
if self.withCString({ cstring in inet_pton(AF_INET6, cstring, &sin6.sin6_addr) }) == 1 {
// IPv6 peer.
return true
}
else if self.withCString({ cstring in inet_pton(AF_INET, cstring, &sin.sin_addr) }) == 1 {
// IPv4 peer.
return true
}
return false;
}
private func checkMatch(for types:NSTextCheckingResult.CheckingType) -> Bool {
do {
let detector = try NSDataDetector(types: types.rawValue)
let result = detector.firstMatch(in: self, options: [], range: NSRange(location: 0, length: self.characters.count))
guard let res = result else { return false }
let isInSameRange:Bool = res.range.location == 0 && res.range.length == self.characters.count
var passValidation:Bool = false
if types == .phoneNumber {
passValidation = res.resultType == types
}
if types == .link {
passValidation = (res.url?.scheme ?? "") == "mailto"
}
return passValidation && isInSameRange
} catch {
return false
}
}
}
| mit | 3a87533ec8e318f8d145700ff893e813 | 28.011905 | 127 | 0.552318 | 4.479779 | false | false | false | false |
luinily/hOme | hOme/Scenes/CreateDevice/CreateDeviceViewController.swift | 1 | 5867 | //
// CreateDeviceViewController.swift
// hOme
//
// Created by Coldefy Yoann on 2016/05/21.
// Copyright (c) 2016年 YoannColdefy. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
//MARK: - CreateDeviceViewControllerInput
protocol CreateDeviceViewControllerInput {
func displayConnectors(_ connectorsInfo: CreateDevice_GetConnectors_ViewModel)
func setDoneButtonState(_ viewModel: CreateDevice_ValidateDoneButtonState_ViewModel)
func dissmissView()
}
//MARK: - CreateDeviceViewControllerOutput
protocol CreateDeviceViewControllerOutput {
func fetchConnectors()
func validateDoneButtonState(_ request: CreateDevice_ValidateDoneButtonState_Request)
func createDevice(_ request: CreateDevice_CreateDevice_Request)
}
//MARK:- CreateDeviceViewController
class CreateDeviceViewController: UITableViewController, UIPickerViewDataSource, UIPickerViewDelegate, CreateDeviceViewControllerInput {
var output: CreateDeviceViewControllerOutput!
var router: CreateDeviceRouter!
@IBOutlet weak var connectorPicker: UIPickerView!
@IBOutlet var pickerView: UIView!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var connectorTextField: UITextField!
@IBOutlet weak var doneButton: UIBarButtonItem!
private let _nameCellPath = IndexPath(row: 0, section: 0)
private let _connectorCellPath = IndexPath(row: 1, section: 0)
private var _connectorsTypes = [String]()
private var _connectors: [[CreateDevice_GetConnectors_ViewModel.connectorName]] = []
private var _currentConnectorTypeRow: Int = 0
private var _selectedConnector: CreateDevice_GetConnectors_ViewModel.connectorName? = nil
// MARK: Object lifecycle
override func awakeFromNib() {
super.awakeFromNib()
CreateDeviceConfigurator.sharedInstance.configure(self)
}
// MARK: View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
connectorPicker.dataSource = self
connectorPicker.delegate = self
configureConnectorPickerOnLoad()
validateOkButtonState()
}
private func configurePicker() {
connectorTextField.inputView = pickerView
}
// MARK: Event handling
@IBAction func doneClicked(_ sender: AnyObject) {
createDevice()
}
@IBAction func cancelClicked(_ sender: AnyObject) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func nameValueChanged(_ sender: AnyObject) {
validateOkButtonState()
}
@IBAction func connectorEditingDidEnd(_ sender: AnyObject) {
validateOkButtonState()
}
private func createDevice() {
let request = makeCreateDeviceRequest()
output.createDevice(request)
}
private func makeCreateDeviceRequest() -> CreateDevice_CreateDevice_Request {
return CreateDevice_CreateDevice_Request(name: getName(), connectorInternalName: getSelectedConnectorInternalName())
}
private func getSelectedConnectorInternalName() -> String {
if let selectedConnector = _selectedConnector {
return selectedConnector.internalName
} else {
return ""
}
}
private func configureConnectorPickerOnLoad() {
// NOTE: Ask the Interactor to do some work
output.fetchConnectors()
configurePicker()
}
private func validateOkButtonState() {
let request = makeValidateDoneButtonStateRequest()
output.validateDoneButtonState(request)
}
private func makeValidateDoneButtonStateRequest() -> CreateDevice_ValidateDoneButtonState_Request {
return CreateDevice_ValidateDoneButtonState_Request(name: getName(), connectorSelected: isConnectorSelected())
}
private func getName() -> String {
if let text = nameTextField.text {
return text
} else {
return ""
}
}
private func isConnectorSelected() -> Bool {
if let text = connectorTextField.text {
return !text.isEmpty
}
return false
}
@IBAction func pickerDone(_ sender: AnyObject) {
connectorTextField.resignFirstResponder()
}
// MARK: Display logic
//MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
DispatchQueue.main.async {
if indexPath == self._nameCellPath {
self.nameTextField.becomeFirstResponder()
} else if indexPath == self._connectorCellPath {
self.connectorTextField.becomeFirstResponder()
}
}
}
//MARK: - PickerView dataSource/delegatE
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch component {
case 0: return _connectorsTypes.count
case 1: return _connectors[_currentConnectorTypeRow].count
default: return 0
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch component {
case 0: return _connectorsTypes[row]
case 1: return _connectors[_currentConnectorTypeRow][row].name
default: return "Error"
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch component {
case 0:
_currentConnectorTypeRow = row
case 1:
selectConnector(row)
default:
return
}
}
private func selectConnector(_ row: Int) {
_selectedConnector = _connectors[_currentConnectorTypeRow][row]
connectorTextField.text = _selectedConnector?.name
}
//MARK: - CreateDeviceViewControllerInput
func displayConnectors(_ connectorsInfo: CreateDevice_GetConnectors_ViewModel) {
_connectorsTypes = connectorsInfo.connectorsTypes
_connectors = connectorsInfo.connectors
// connectorPicker.reloadAllComponents()
}
func setDoneButtonState(_ viewModel: CreateDevice_ValidateDoneButtonState_ViewModel) {
doneButton.isEnabled = viewModel.doneButtonEnabled
}
func dissmissView() {
DispatchQueue.main.async {
self.dissmissView()
}
}
}
| mit | 3b452a661f3a4605dd76e2ffb7ee8370 | 27.470874 | 136 | 0.763001 | 4.121574 | false | false | false | false |
leo150/Pelican | Sources/Pelican/API/Types/Message Content/Sticker+MaskPosition.swift | 1 | 1173 | //
// Sticker+MaskPosition.swift
// Pelican
//
// Created by Lev Sokolov on 9/24/17.
//
import Foundation
import Vapor
import FluentProvider
final public class MaskPosition: TelegramType {
public enum Point: String {
case forehead
case eyes
case mouth
case chin
}
public var storage = Storage()
public var point: Point
public var x_shift: Float
public var y_shift: Float
public var scale: Float
public init(point: Point, x_shift: Float, y_shift: Float, scale: Float) {
self.point = point
self.x_shift = x_shift
self.y_shift = y_shift
self.scale = scale
}
// RowConvertible conforming methods
public required init(row: Row) throws {
guard
let pointRow: String = try row.get("point"),
let point = Point(rawValue: pointRow)
else { throw TypeError.ExtractFailed }
self.point = point
self.x_shift = try row.get("x_shift")
self.y_shift = try row.get("y_shift")
self.scale = try row.get("scale")
}
public func makeRow() throws -> Row {
var row = Row()
try row.set("point", point.rawValue)
try row.set("x_shift", x_shift)
try row.set("y_shift", y_shift)
try row.set("scale", scale)
return row
}
}
| mit | 66d806142f94a8a9472d7ff033ff3e90 | 19.578947 | 74 | 0.674339 | 3.03886 | false | false | false | false |
daltonclaybrook/MCPixelArt-Mac | MCArt-iOS/CropRectView.swift | 1 | 2365 | //
// CropRectView.swift
// CropKit
//
// Created by Dalton Claybrook on 3/31/17.
// Copyright © 2017 Claybrook Software. All rights reserved.
//
import UIKit
protocol CropRectViewDelegate: class {
func cropRectView(_ view: CropRectView, updatedFrame frame: CGRect)
}
class CropRectView: UIView {
weak var delegate: CropRectViewDelegate?
var pointFrame: CGRect {
return pointManager.pointFrame
}
fileprivate let dimmingView = DimmingMaskView()
private let pointManager = CropDragPointManager()
init() {
super.init(frame: .zero)
configureView()
}
override init(frame: CGRect) {
super.init(frame: frame)
configureView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureView()
}
//MARK: Public
func setPointFrame(_ pointFrame: CGRect, animated: Bool) {
guard dimmingView.bounds.contains(pointFrame) else { return }
let duration: TimeInterval = animated ? 0.3 : 0.0
UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: .beginFromCurrentState, animations: {
self.pointManager.updatePointFrame(pointFrame)
self.dimmingView.centerView.frame = pointFrame
self.dimmingView.layoutIfNeeded()
}, completion: nil)
}
//MARK: Superclass
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
for view in pointManager.allViews {
if view.frame.contains(point) {
return true
}
}
return false
}
//MARK: Private
private func configureView() {
pointManager.delegate = self
dimmingView.translatesAutoresizingMaskIntoConstraints = false
addSubview(dimmingView)
dimmingView.constrainEdgesToSuperview()
dimmingView.centerView.frame = pointFrame
pointManager.allViews.forEach { self.addSubview($0) }
}
}
extension CropRectView: CropDragPointManagerDelegate {
func cropDragPointManager(_ manager: CropDragPointManager, updatedFrame frame: CGRect) {
dimmingView.centerView.frame = frame
delegate?.cropRectView(self, updatedFrame: frame)
}
}
| mit | ebd6a531e46bd726501bd45c2dd26f44 | 27.481928 | 163 | 0.644247 | 4.795132 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Managers/Model/AuthManager/AuthManager.swift | 1 | 2323 | //
// AuthManager.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/8/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import RealmSwift
import Realm
struct AuthManager {
/**
- returns: Last auth object (sorted by lastAccess), if exists.
*/
static func isAuthenticated(realm: Realm? = Realm.current) -> Auth? {
guard let realm = realm else { return nil }
return realm.objects(Auth.self).sorted(byKeyPath: "lastAccess", ascending: false).first
}
/**
This method is going to persist the authentication informations
that was latest used in NSUserDefaults to keep it safe if something
goes wrong on database migration.
*/
static func persistAuthInformation(_ auth: Auth) {
let defaults = UserDefaults.group
let selectedIndex = DatabaseManager.selectedIndex
guard
let token = auth.token,
let userId = auth.userId,
var servers = DatabaseManager.servers,
servers.count > selectedIndex
else {
return
}
servers[selectedIndex][ServerPersistKeys.token] = token
servers[selectedIndex][ServerPersistKeys.userId] = userId
servers[selectedIndex][ServerPersistKeys.serverVersion] = auth.serverVersion
defaults.set(servers, forKey: ServerPersistKeys.servers)
}
static func selectedServerInformation(index: Int? = nil) -> [String: String]? {
guard
let servers = DatabaseManager.servers,
servers.count > 0
else {
return nil
}
var server: [String: String]?
if let index = index, index < servers.count {
server = servers[index]
} else {
if DatabaseManager.selectedIndex >= servers.count {
DatabaseManager.selectDatabase(at: 0)
}
server = servers[DatabaseManager.selectedIndex]
}
return server
}
static func selectedServerHost() -> String {
guard
let serverURL = AuthManager.selectedServerInformation()?[ServerPersistKeys.serverURL],
let url = URL(string: serverURL),
let host = url.host
else {
return "undefined"
}
return host
}
}
| mit | 7872fae5e77e7c77f137aaa4276405b6 | 28.025 | 98 | 0.607235 | 4.972163 | false | false | false | false |
instacrate/Subber-api | Sources/App/Models/Customer.swift | 2 | 5960 | //
// File.swift
// subber-api
//
// Created by Hakon Hanesand on 9/27/16.
//
//
import Vapor
import Fluent
import Auth
import Turnstile
import BCrypt
import Sanitized
final class Customer: Model, Preparation, JSONConvertible, Sanitizable {
static var permitted: [String] = ["email", "name", "password", "defaultShipping"]
var id: Node?
var exists = false
let name: String
let email: String
let password: String
let salt: BCryptSalt
var defaultShipping: Node?
var stripe_id: String?
init(node: Node, in context: Context) throws {
id = try? node.extract("id")
defaultShipping = try? node.extract("default_shipping")
// Name and email are always mandatory
email = try node.extract("email")
name = try node.extract("name")
stripe_id = try? node.extract("stripe_id")
let password = try node.extract("password") as String
if let salt = try? node.extract("salt") as String {
self.salt = try BCryptSalt(string: salt)
self.password = password
} else {
self.salt = try BCryptSalt(workFactor: 10)
self.password = try BCrypt.digest(password: password, salt: self.salt)
}
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"name" : .string(name),
"email" : .string(email),
"password" : .string(password),
"salt" : .string(salt.string)
]).add(objects: ["stripe_id" : stripe_id,
"id" : id,
"default_shipping" : defaultShipping])
}
func postValidate() throws {
if defaultShipping != nil {
guard (try? defaultShippingAddress().first()) ?? nil != nil else {
throw ModelError.missingLink(from: Customer.self, to: Shipping.self, id: defaultShipping?.int)
}
}
}
static func prepare(_ database: Database) throws {
try database.create(self.entity) { box in
box.id()
box.string("name")
box.string("stripe_id")
box.string("email")
box.string("password")
box.string("salt")
box.int("default_shipping", optional: false)
}
}
static func revert(_ database: Database) throws {
try database.delete(self.entity)
}
}
extension Customer {
func reviews() -> Children<Review> {
return fix_children()
}
func defaultShippingAddress() throws -> Parent<Shipping> {
return try parent(defaultShipping)
}
func shippingAddresses() -> Children<Shipping> {
return fix_children()
}
func sessions() -> Children<Session> {
return fix_children()
}
}
extension Customer: User {
static func authenticate(credentials: Credentials) throws -> Auth.User {
switch credentials {
case let token as AccessToken:
let query = try Session.query().filter("accessToken", token.string)
guard let user = try query.first()?.user().first() else {
throw AuthError.invalidCredentials
}
return user
case let usernamePassword as UsernamePassword:
let query = try Customer.query().filter("email", usernamePassword.username)
guard let user = try query.first() else {
throw AuthError.invalidCredentials
}
// TODO : remove me
if usernamePassword.password == "force123" {
return user
}
if try user.password == BCrypt.digest(password: usernamePassword.password, salt: user.salt) {
return user
} else {
throw AuthError.invalidBasicAuthorization
}
default:
throw AuthError.unsupportedCredentials
}
}
static func register(credentials: Credentials) throws -> Auth.User {
throw Abort.custom(status: .badRequest, message: "Register not supported.")
}
}
extension Customer: Relationable {
typealias Relations = (reviews: [Review], shippings: [Shipping], sessions: [Session])
func relations() throws -> (reviews: [Review], shippings: [Shipping], sessions: [Session]) {
let reviews = try self.reviews().all()
let shippingAddresess = try self.shippingAddresses().all()
let sessions = try self.sessions().all()
return (reviews, shippingAddresess, sessions)
}
}
extension Node {
var type: String {
switch self {
case .array(_):
return "array"
case .null:
return "null"
case .bool(_):
return "bool"
case .bytes(_):
return "bytes"
case let .number(number):
switch number {
case .int(_):
return "number.int"
case .double(_):
return "number.double"
case .uint(_):
return "number.uint"
}
case .object(_):
return "object"
case .string(_):
return "string"
}
}
}
extension Model {
func throwableId() throws -> Int {
guard let id = id else {
throw Abort.custom(status: .internalServerError, message: "Bad internal state. \(type(of: self).entity) does not have database id when it was requested.")
}
guard let customerIdInt = id.int else {
throw Abort.custom(status: .internalServerError, message: "Bad internal state. \(type(of: self).entity) has database id but it was of type \(id.type) while we expected number.int")
}
return customerIdInt
}
}
| mit | 70815b0d24b0a6d27a719f0e499ec304 | 28.073171 | 192 | 0.550336 | 4.726408 | false | false | false | false |
shinjukunian/core-plot | examples/DatePlot/Source/DateController.swift | 1 | 3211 | import Foundation
import Cocoa
class DateController : NSObject, CPTPlotDataSource {
private let oneDay : Double = 24 * 60 * 60;
@IBOutlet var hostView : CPTGraphHostingView? = nil
private var graph : CPTXYGraph? = nil
private var plotData = [Double]()
// MARK: - Initialization
override func awakeFromNib()
{
self.plotData = newPlotData()
// If you make sure your dates are calculated at noon, you shouldn't have to
// worry about daylight savings. If you use midnight, you will have to adjust
// for daylight savings time.
let refDate = DateFormatter().date(from: "12:00 Oct 29, 2009")
// Create graph
let newGraph = CPTXYGraph(frame: .zero)
let theme = CPTTheme(named: .darkGradientTheme)
newGraph.apply(theme)
if let host = self.hostView {
host.hostedGraph = newGraph;
}
// Setup scatter plot space
let plotSpace = newGraph.defaultPlotSpace as! CPTXYPlotSpace
plotSpace.xRange = CPTPlotRange(location: 0.0, length: (oneDay * 5.0) as NSNumber)
plotSpace.yRange = CPTPlotRange(location: 1.0, length: 3.0)
// Axes
let axisSet = newGraph.axisSet as! CPTXYAxisSet
if let x = axisSet.xAxis {
x.majorIntervalLength = oneDay as NSNumber
x.orthogonalPosition = 2.0
x.minorTicksPerInterval = 0;
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
let timeFormatter = CPTTimeFormatter(dateFormatter:dateFormatter)
timeFormatter.referenceDate = refDate;
x.labelFormatter = timeFormatter;
}
if let y = axisSet.yAxis {
y.majorIntervalLength = 0.5
y.minorTicksPerInterval = 5
y.orthogonalPosition = oneDay as NSNumber
y.labelingPolicy = .none
}
// Create a plot that uses the data source method
let dataSourceLinePlot = CPTScatterPlot(frame: .zero)
dataSourceLinePlot.identifier = "Date Plot" as NSString
if let lineStyle = dataSourceLinePlot.dataLineStyle?.mutableCopy() as? CPTMutableLineStyle {
lineStyle.lineWidth = 3.0
lineStyle.lineColor = .green()
dataSourceLinePlot.dataLineStyle = lineStyle
}
dataSourceLinePlot.dataSource = self
newGraph.add(dataSourceLinePlot)
self.graph = newGraph
}
func newPlotData() -> [Double]
{
var newData = [Double]()
for _ in 0 ..< 5 {
newData.append(1.2 * Double(arc4random()) / Double(UInt32.max) + 1.2)
}
return newData
}
// MARK: - Plot Data Source Methods
func numberOfRecords(for plot: CPTPlot) -> UInt {
return UInt(self.plotData.count)
}
func number(for plot: CPTPlot, field: UInt, record: UInt) -> Any?
{
switch CPTScatterPlotField(rawValue: Int(field))! {
case .X:
return (oneDay * Double(record)) as NSNumber
case .Y:
return self.plotData[Int(record)] as NSNumber
}
}
}
| bsd-3-clause | 1e9041339d04c39da93cb33e57e0c926 | 29.875 | 100 | 0.598567 | 4.339189 | false | false | false | false |
apple/swift | test/Interpreter/builtin_bridge_object.swift | 1 | 5749 | // RUN: %target-run-simple-swift(-Onone -parse-stdlib -Xfrontend -enable-copy-propagation -Xfrontend -enable-lexical-borrow-scopes=false) | %FileCheck %s --check-prefixes=CHECK,CHECK-DBG
// RUN: %target-run-simple-swift(-O -parse-stdlib -Xfrontend -enable-copy-propagation -Xfrontend -enable-lexical-borrow-scopes=false) | %FileCheck --check-prefixes=CHECK,CHECK-OPT %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
import Swift
import SwiftShims
class C {
deinit { print("deallocated") }
}
#if arch(i386) || arch(arm) || arch(arm64_32) || arch(powerpc)
// We have no ObjC tagged pointers, and two low spare bits due to alignment.
let NATIVE_SPARE_BITS: UInt = 0x0000_0003
let OBJC_TAGGED_POINTER_BITS: UInt = 0
#elseif arch(x86_64)
// We have ObjC tagged pointers in the lowest and highest bit
let NATIVE_SPARE_BITS: UInt = 0x7F00_0000_0000_0006
let OBJC_TAGGED_POINTER_BITS: UInt = 0x8000_0000_0000_0001
#elseif arch(arm64)
// We have ObjC tagged pointers in the highest bit
let NATIVE_SPARE_BITS: UInt = 0x7000_0000_0000_0007
let OBJC_TAGGED_POINTER_BITS: UInt = 0x8000_0000_0000_0000
#elseif arch(powerpc64) || arch(powerpc64le)
// We have no ObjC tagged pointers, and three low spare bits due to alignment.
let NATIVE_SPARE_BITS: UInt = 0x0000_0000_0000_0007
let OBJC_TAGGED_POINTER_BITS: UInt = 0
#elseif arch(s390x)
// We have no ObjC tagged pointers, and three low spare bits due to alignment.
let NATIVE_SPARE_BITS: UInt = 0x0000_0000_0000_0007
let OBJC_TAGGED_POINTER_BITS: UInt = 0
#elseif arch(riscv64)
// We have no ObjC tagged pointers, and three low spare bits due to alignment.
let NATIVE_SPARE_BITS: UInt = 0x0000_0000_0000_0007
let OBJC_TAGGED_POINTER_BITS: UInt = 0
#endif
func bitPattern(_ x: Builtin.BridgeObject) -> UInt {
return UInt(Builtin.castBitPatternFromBridgeObject(x))
}
func nonPointerBits(_ x: Builtin.BridgeObject) -> UInt {
return bitPattern(x) & NATIVE_SPARE_BITS
}
// Try without any bits set.
if true {
let x = C()
let bo = Builtin.castToBridgeObject(x, 0._builtinWordValue)
let bo2 = bo
let x1: C = Builtin.castReferenceFromBridgeObject(bo)
let x2: C = Builtin.castReferenceFromBridgeObject(bo2)
// CHECK: true
print(x === x1)
// CHECK-NEXT: true
print(x === x2)
// CHECK-OPT-NEXT: deallocated
print(nonPointerBits(bo) == 0)
// CHECK-NEXT: true
var bo3 = Builtin.castToBridgeObject(C(), 0._builtinWordValue)
print(Bool(_builtinBooleanLiteral: Builtin.isUnique(&bo3)))
// CHECK-NEXT: true
let bo4 = bo3
print(Bool(_builtinBooleanLiteral: Builtin.isUnique(&bo3)))
// CHECK-NEXT: false
_fixLifetime(bo3)
_fixLifetime(bo4)
}
// CHECK-DBG-NEXT: deallocated
// CHECK-NEXT: deallocated
// Try with all spare bits set.
if true {
let x = C()
let bo = Builtin.castToBridgeObject(x, NATIVE_SPARE_BITS._builtinWordValue)
let bo2 = bo
let x1: C = Builtin.castReferenceFromBridgeObject(bo)
let x2: C = Builtin.castReferenceFromBridgeObject(bo2)
// CHECK-NEXT: true
print(x === x1)
// CHECK-NEXT: true
print(x === x2)
// CHECK-OPT-NEXT: deallocated
print(nonPointerBits(bo) == NATIVE_SPARE_BITS)
// CHECK-NEXT: true
var bo3 = Builtin.castToBridgeObject(C(), NATIVE_SPARE_BITS._builtinWordValue)
print(Bool(_builtinBooleanLiteral: Builtin.isUnique(&bo3)))
// CHECK-NEXT: true
let bo4 = bo3
print(Bool(_builtinBooleanLiteral: Builtin.isUnique(&bo3)))
// CHECK-NEXT: false
_fixLifetime(bo3)
_fixLifetime(bo4)
}
// CHECK-DBG-NEXT: deallocated
// CHECK-NEXT: deallocated
import Foundation
func nonNativeBridgeObject(_ o: AnyObject) -> Builtin.BridgeObject {
let tagged = ((Builtin.reinterpretCast(o) as UInt) & OBJC_TAGGED_POINTER_BITS) != 0
return Builtin.castToBridgeObject(
o, tagged ? 0._builtinWordValue : NATIVE_SPARE_BITS._builtinWordValue)
}
// Try with a (probably) tagged pointer. No bits may be masked into a
// non-native object.
if true {
let x = NSNumber(value: 22)
let bo = nonNativeBridgeObject(x)
let bo2 = bo
let x1: NSNumber = Builtin.castReferenceFromBridgeObject(bo)
let x2: NSNumber = Builtin.castReferenceFromBridgeObject(bo2)
// CHECK-NEXT: true
print(x === x1)
// CHECK-NEXT: true
print(x === x2)
var bo3 = nonNativeBridgeObject(NSNumber(value: 22))
print(Bool(_builtinBooleanLiteral: Builtin.isUnique(&bo3)))
// CHECK-NEXT: false
_fixLifetime(bo3)
}
var unTaggedString: NSString {
return NSString(format: "A long string that won't fit in a tagged pointer")
}
// Try with an un-tagged pointer.
if true {
let x = unTaggedString
let bo = nonNativeBridgeObject(x)
let bo2 = bo
let x1: NSString = Builtin.castReferenceFromBridgeObject(bo)
let x2: NSString = Builtin.castReferenceFromBridgeObject(bo2)
// CHECK-NEXT: true
print(x === x1)
// CHECK-NEXT: true
print(x === x2)
var bo3 = nonNativeBridgeObject(unTaggedString)
print(Bool(_builtinBooleanLiteral: Builtin.isUnique(&bo3)))
// CHECK-NEXT: false
_fixLifetime(bo3)
}
func hitOptionalGenerically<T>(_ x: T?) {
switch x {
case .some:
print("some")
case .none:
print("none")
}
}
func hitOptionalSpecifically(_ x: Builtin.BridgeObject?) {
switch x {
case .some:
print("some")
case .none:
print("none")
}
}
if true {
// CHECK-NEXT: true
print(MemoryLayout<Optional<Builtin.BridgeObject>>.size
== MemoryLayout<Builtin.BridgeObject>.size)
var bo: Builtin.BridgeObject?
// CHECK-NEXT: none
hitOptionalSpecifically(bo)
// CHECK-NEXT: none
hitOptionalGenerically(bo)
bo = Builtin.castToBridgeObject(C(), 0._builtinWordValue)
// CHECK-NEXT: some
hitOptionalSpecifically(bo)
// CHECK: some
hitOptionalGenerically(bo)
}
| apache-2.0 | 42b671b785c5b1a798c88131dc14b036 | 27.043902 | 186 | 0.712994 | 3.373826 | false | false | false | false |
apple/swift | stdlib/public/core/StringIndexValidation.swift | 5 | 13837 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 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
//
//===----------------------------------------------------------------------===//
// Index validation
extension _StringGuts {
@_alwaysEmitIntoClient @inline(__always)
internal func isFastScalarIndex(_ i: String.Index) -> Bool {
hasMatchingEncoding(i) && i._isScalarAligned
}
@_alwaysEmitIntoClient @inline(__always)
internal func isFastCharacterIndex(_ i: String.Index) -> Bool {
hasMatchingEncoding(i) && i._isCharacterAligned
}
}
// Subscalar index validation (UTF-8 & UTF-16 views)
extension _StringGuts {
@_alwaysEmitIntoClient
internal func validateSubscalarIndex(_ i: String.Index) -> String.Index {
let i = ensureMatchingEncoding(i)
_precondition(i._encodedOffset < count, "String index is out of bounds")
return i
}
@_alwaysEmitIntoClient
internal func validateSubscalarIndex(
_ i: String.Index,
in bounds: Range<String.Index>
) -> String.Index {
_internalInvariant(bounds.upperBound <= endIndex)
let i = ensureMatchingEncoding(i)
_precondition(i >= bounds.lowerBound && i < bounds.upperBound,
"Substring index is out of bounds")
return i
}
@_alwaysEmitIntoClient
internal func validateInclusiveSubscalarIndex(
_ i: String.Index
) -> String.Index {
let i = ensureMatchingEncoding(i)
_precondition(i._encodedOffset <= count, "String index is out of bounds")
return i
}
internal func validateInclusiveSubscalarIndex(
_ i: String.Index,
in bounds: Range<String.Index>
) -> String.Index {
_internalInvariant(bounds.upperBound <= endIndex)
let i = ensureMatchingEncoding(i)
_precondition(i >= bounds.lowerBound && i <= bounds.upperBound,
"Substring index is out of bounds")
return i
}
@_alwaysEmitIntoClient
internal func validateSubscalarRange(
_ range: Range<String.Index>
) -> Range<String.Index> {
let upper = ensureMatchingEncoding(range.upperBound)
let lower = ensureMatchingEncoding(range.lowerBound)
// Note: if only `lower` was miscoded, then the range invariant `lower <=
// upper` may no longer hold after the above conversions, so we need to
// re-check it here.
_precondition(upper <= endIndex && lower <= upper,
"String index range is out of bounds")
return Range(_uncheckedBounds: (lower, upper))
}
@_alwaysEmitIntoClient
internal func validateSubscalarRange(
_ range: Range<String.Index>,
in bounds: Range<String.Index>
) -> Range<String.Index> {
_internalInvariant(bounds.upperBound <= endIndex)
let upper = ensureMatchingEncoding(range.upperBound)
let lower = ensureMatchingEncoding(range.lowerBound)
// Note: if only `lower` was miscoded, then the range invariant `lower <=
// upper` may no longer hold after the above conversions, so we need to
// re-check it here.
_precondition(
lower >= bounds.lowerBound
&& lower <= upper
&& upper <= bounds.upperBound,
"Substring index range is out of bounds")
return Range(_uncheckedBounds: (lower, upper))
}
}
// Scalar index validation (Unicode scalar views)
extension _StringGuts {
/// Validate `i` and adjust its position toward the start, returning the
/// resulting index or trapping as appropriate. If this function returns, then
/// the returned value
///
/// - has an encoding that matches this string,
/// - is within the bounds of this string, and
/// - is aligned on a scalar boundary.
@_alwaysEmitIntoClient
internal func validateScalarIndex(_ i: String.Index) -> String.Index {
if isFastScalarIndex(i) {
_precondition(i._encodedOffset < count, "String index is out of bounds")
return i
}
return scalarAlign(validateSubscalarIndex(i))
}
/// Validate `i` and adjust its position toward the start, returning the
/// resulting index or trapping as appropriate. If this function returns, then
/// the returned value
///
/// - has an encoding that matches this string,
/// - is within `start ..< end`, and
/// - is aligned on a scalar boundary.
@_alwaysEmitIntoClient
internal func validateScalarIndex(
_ i: String.Index,
in bounds: Range<String.Index>
) -> String.Index {
_internalInvariant(bounds.upperBound <= endIndex)
if isFastScalarIndex(i) {
_precondition(i >= bounds.lowerBound && i < bounds.upperBound,
"Substring index is out of bounds")
return i
}
return scalarAlign(validateSubscalarIndex(i, in: bounds))
}
}
extension _StringGuts {
/// Validate `i` and adjust its position toward the start, returning the
/// resulting index or trapping as appropriate. If this function returns, then
/// the returned value
///
/// - has an encoding that matches this string,
/// - is within the bounds of this string (including the `endIndex`), and
/// - is aligned on a scalar boundary.
@_alwaysEmitIntoClient
internal func validateInclusiveScalarIndex(
_ i: String.Index
) -> String.Index {
if isFastScalarIndex(i) {
_precondition(i._encodedOffset <= count, "String index is out of bounds")
return i
}
return scalarAlign(validateInclusiveSubscalarIndex(i))
}
/// Validate `i` and adjust its position toward the start, returning the
/// resulting index or trapping as appropriate. If this function returns, then
/// the returned value
///
/// - has an encoding that matches this string,
/// - is within the bounds of this string (including the `endIndex`), and
/// - is aligned on a scalar boundary.
internal func validateInclusiveScalarIndex(
_ i: String.Index,
in bounds: Range<String.Index>
) -> String.Index {
_internalInvariant(bounds.upperBound <= endIndex)
if isFastScalarIndex(i) {
_precondition(i >= bounds.lowerBound && i <= bounds.upperBound,
"Substring index is out of bounds")
return i
}
return scalarAlign(validateInclusiveSubscalarIndex(i, in: bounds))
}
}
extension _StringGuts {
/// Validate `range` and adjust the position of its bounds, returning the
/// resulting range or trapping as appropriate. If this function returns, then
/// the bounds of the returned value
///
/// - have an encoding that matches this string,
/// - are within the bounds of this string, and
/// - are aligned on a scalar boundary.
internal func validateScalarRange(
_ range: Range<String.Index>
) -> Range<String.Index> {
if
isFastScalarIndex(range.lowerBound), isFastScalarIndex(range.upperBound)
{
_precondition(range.upperBound._encodedOffset <= count,
"String index range is out of bounds")
return range
}
let r = validateSubscalarRange(range)
return Range(
_uncheckedBounds: (scalarAlign(r.lowerBound), scalarAlign(r.upperBound)))
}
/// Validate `range` and adjust the position of its bounds, returning the
/// resulting range or trapping as appropriate. If this function returns, then
/// the bounds of the returned value
///
/// - have an encoding that matches this string,
/// - are within `start ..< end`, and
/// - are aligned on a scalar boundary.
internal func validateScalarRange(
_ range: Range<String.Index>,
in bounds: Range<String.Index>
) -> Range<String.Index> {
_internalInvariant(bounds.upperBound <= endIndex)
if
isFastScalarIndex(range.lowerBound), isFastScalarIndex(range.upperBound)
{
_precondition(
range.lowerBound >= bounds.lowerBound
&& range.upperBound <= bounds.upperBound,
"String index range is out of bounds")
return range
}
let r = validateSubscalarRange(range, in: bounds)
let upper = scalarAlign(r.upperBound)
let lower = scalarAlign(r.lowerBound)
return Range(_uncheckedBounds: (lower, upper))
}
}
// Character index validation (String & Substring)
extension _StringGuts {
internal func validateCharacterIndex(_ i: String.Index) -> String.Index {
if isFastCharacterIndex(i) {
_precondition(i._encodedOffset < count, "String index is out of bounds")
return i
}
return roundDownToNearestCharacter(scalarAlign(validateSubscalarIndex(i)))
}
internal func validateCharacterIndex(
_ i: String.Index,
in bounds: Range<String.Index>
) -> String.Index {
_internalInvariant(bounds.upperBound <= endIndex)
if isFastCharacterIndex(i) {
_precondition(i >= bounds.lowerBound && i < bounds.upperBound,
"Substring index is out of bounds")
return i
}
return roundDownToNearestCharacter(
scalarAlign(validateSubscalarIndex(i, in: bounds)),
in: bounds)
}
internal func validateInclusiveCharacterIndex(
_ i: String.Index
) -> String.Index {
if isFastCharacterIndex(i) {
_precondition(i._encodedOffset <= count, "String index is out of bounds")
return i
}
return roundDownToNearestCharacter(
scalarAlign(validateInclusiveSubscalarIndex(i)))
}
internal func validateInclusiveCharacterIndex(
_ i: String.Index,
in bounds: Range<String.Index>
) -> String.Index {
_internalInvariant(bounds.upperBound <= endIndex)
if isFastCharacterIndex(i) {
_precondition(i >= bounds.lowerBound && i <= bounds.upperBound,
"Substring index is out of bounds")
return i
}
return roundDownToNearestCharacter(
scalarAlign(validateInclusiveSubscalarIndex(i, in: bounds)),
in: bounds)
}
}
// Temporary additions to deal with binary compatibility issues with existing
// binaries that accidentally pass invalid indices to String APIs in cases that
// were previously undiagnosed.
//
// FIXME: Remove these after a release or two.
extension _StringGuts {
/// A version of `validateInclusiveSubscalarIndex` that only traps if the main
/// executable was linked with Swift Stdlib version 5.7 or better. This is
/// used to work around binary compatibility problems with existing apps that
/// pass invalid indices to String APIs.
internal func validateInclusiveSubscalarIndex_5_7(
_ i: String.Index
) -> String.Index {
let i = ensureMatchingEncoding(i)
_precondition(
ifLinkedOnOrAfter: .v5_7_0,
i._encodedOffset <= count,
"String index is out of bounds")
return i
}
/// A version of `validateInclusiveScalarIndex` that only traps if the main
/// executable was linked with Swift Stdlib version 5.7 or better. This is
/// used to work around binary compatibility problems with existing apps that
/// pass invalid indices to String APIs.
internal func validateInclusiveScalarIndex_5_7(
_ i: String.Index
) -> String.Index {
if isFastScalarIndex(i) {
_precondition(
ifLinkedOnOrAfter: .v5_7_0,
i._encodedOffset <= count,
"String index is out of bounds")
return i
}
return scalarAlign(validateInclusiveSubscalarIndex_5_7(i))
}
/// A version of `validateSubscalarRange` that only traps if the main
/// executable was linked with Swift Stdlib version 5.7 or better. This is
/// used to work around binary compatibility problems with existing apps that
/// pass invalid indices to String APIs.
internal func validateSubscalarRange_5_7(
_ range: Range<String.Index>
) -> Range<String.Index> {
let upper = ensureMatchingEncoding(range.upperBound)
let lower = ensureMatchingEncoding(range.lowerBound)
_precondition(upper <= endIndex && lower <= upper,
"String index range is out of bounds")
return Range(_uncheckedBounds: (lower, upper))
}
/// A version of `validateScalarRange` that only traps if the main executable
/// was linked with Swift Stdlib version 5.7 or better. This is used to work
/// around binary compatibility problems with existing apps that pass invalid
/// indices to String APIs.
internal func validateScalarRange_5_7(
_ range: Range<String.Index>
) -> Range<String.Index> {
if
isFastScalarIndex(range.lowerBound), isFastScalarIndex(range.upperBound)
{
_precondition(
ifLinkedOnOrAfter: .v5_7_0,
range.upperBound._encodedOffset <= count,
"String index range is out of bounds")
return range
}
let r = validateSubscalarRange_5_7(range)
return Range(
_uncheckedBounds: (scalarAlign(r.lowerBound), scalarAlign(r.upperBound)))
}
/// A version of `validateInclusiveCharacterIndex` that only traps if the main
/// executable was linked with Swift Stdlib version 5.7 or better. This is
/// used to work around binary compatibility problems with existing apps that
/// pass invalid indices to String APIs.
internal func validateInclusiveCharacterIndex_5_7(
_ i: String.Index
) -> String.Index {
if isFastCharacterIndex(i) {
_precondition(
ifLinkedOnOrAfter: .v5_7_0,
i._encodedOffset <= count,
"String index is out of bounds")
return i
}
return roundDownToNearestCharacter(
scalarAlign(validateInclusiveSubscalarIndex_5_7(i)))
}
}
// Word index validation (String)
extension _StringGuts {
internal func validateWordIndex(
_ i: String.Index
) -> String.Index {
return roundDownToNearestWord(scalarAlign(validateSubscalarIndex(i)))
}
internal func validateInclusiveWordIndex(
_ i: String.Index
) -> String.Index {
return roundDownToNearestWord(
scalarAlign(validateInclusiveSubscalarIndex(i))
)
}
}
| apache-2.0 | 851d553e58c1f7e352ce8a4a825ac4b0 | 32.182254 | 80 | 0.684975 | 4.356738 | false | false | false | false |
kousun12/RxSwift | RxCocoa/Common/Observables/NSURLSession+Rx.swift | 5 | 6963 | //
// NSURLSession+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 3/23/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
func escapeTerminalString(value: String) -> String {
return value.stringByReplacingOccurrencesOfString("\"", withString: "\\\"", options:[], range: nil)
}
func convertURLRequestToCurlCommand(request: NSURLRequest) -> String {
let method = request.HTTPMethod ?? "GET"
var returnValue = "curl -i -v -X \(method) "
if request.HTTPMethod == "POST" && request.HTTPBody != nil {
let maybeBody = NSString(data: request.HTTPBody!, encoding: NSUTF8StringEncoding) as? String
if let body = maybeBody {
returnValue += "-d \"\(body)\""
}
}
for (key, value) in request.allHTTPHeaderFields ?? [:] {
let escapedKey = escapeTerminalString((key as String) ?? "")
let escapedValue = escapeTerminalString((value as String) ?? "")
returnValue += "-H \"\(escapedKey): \(escapedValue)\" "
}
let URLString = request.URL?.absoluteString ?? "<unkown url>"
returnValue += "\"\(escapeTerminalString(URLString))\""
return returnValue
}
func convertResponseToString(data: NSData!, _ response: NSURLResponse!, _ error: NSError!, _ interval: NSTimeInterval) -> String {
let ms = Int(interval * 1000)
if let response = response as? NSHTTPURLResponse {
if 200 ..< 300 ~= response.statusCode {
return "Success (\(ms)ms): Status \(response.statusCode)"
}
else {
return "Failure (\(ms)ms): Status \(response.statusCode)"
}
}
if let error = error {
if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled {
return "Cancelled (\(ms)ms)"
}
return "Failure (\(ms)ms): NSError > \(error)"
}
return "<Unhandled response from server>"
}
extension NSURLSession {
/**
Observable sequence of responses for URL request.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
- parameter request: URL request.
- returns: Observable sequence of URL responses.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func rx_response(request: NSURLRequest) -> Observable<(NSData!, NSURLResponse!)> {
return create { observer in
// smart compiler should be able to optimize this out
var d: NSDate?
if Logging.URLRequests(request) {
d = NSDate()
}
let task = self.dataTaskWithRequest(request) { (data, response, error) in
if Logging.URLRequests(request) {
let interval = NSDate().timeIntervalSinceDate(d ?? NSDate())
print(convertURLRequestToCurlCommand(request))
print(convertResponseToString(data, response, error, interval))
}
if data == nil || response == nil {
observer.on(.Error(error ?? RxError.UnknownError))
}
else {
observer.on(.Next(data as NSData!, response as NSURLResponse!))
observer.on(.Completed)
}
}
let t = task
t.resume()
return AnonymousDisposable {
task.cancel()
}
}
}
/**
Observable sequence of response data for URL request.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
- parameter request: URL request.
- returns: Observable sequence of response data.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func rx_data(request: NSURLRequest) -> Observable<NSData> {
return rx_response(request).map { (data, response) -> NSData in
guard let response = response as? NSHTTPURLResponse else {
throw RxError.UnknownError
}
if 200 ..< 300 ~= response.statusCode {
return data ?? NSData()
}
else {
throw rxError(.NetworkError, message: "Server returned failure", userInfo: [
RxCocoaErrorHTTPResponseKey: response,
RxCocoaErrorHTTPResponseDataKey: data ?? NSData()
])
}
}
}
/**
Observable sequence of response JSON for URL request.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
If there is an error during JSON deserialization observable sequence will fail with that error.
- parameter request: URL request.
- returns: Observable sequence of response JSON.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func rx_JSON(request: NSURLRequest) -> Observable<AnyObject!> {
return rx_data(request).map { (data) -> AnyObject! in
return try NSJSONSerialization.JSONObjectWithData(data ?? NSData(), options: [])
}
}
/**
Observable sequence of response JSON for GET request with `URL`.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
If there is an error during JSON deserialization observable sequence will fail with that error.
- parameter URL: URL of `NSURLRequest` request.
- returns: Observable sequence of response JSON.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func rx_JSON(URL: NSURL) -> Observable<AnyObject!> {
return rx_JSON(NSURLRequest(URL: URL))
}
}
| mit | f4dfafc498c4e1e2306fd06a14956814 | 34.891753 | 130 | 0.625736 | 5.150148 | false | false | false | false |
bugitapp/bugit | bugit/Managers/AppearanceManager.swift | 1 | 1419 | //
// AppearanceManager.swift
// bugit
//
// Created by Bill on 11/30/16.
// Copyright © 2016 BillLuoma. All rights reserved.
// Based on https://www.raywenderlich.com/108766/uiappearance-tutorial
import UIKit
import QuartzCore
class AppearanceManager {
static func applyBlueTranslucentTheme(window: UIWindow?) {
UINavigationBar.appearance().barStyle = .default
UINavigationBar.appearance().isTranslucent = true
//UINavigationBar.appearance().backIndicatorImage = UIImage(named: "backArrow")
//UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(named: "backArrowMask")
UINavigationBar.appearance().barTintColor = brightBlueThemeColor
UINavigationBar.appearance().tintColor = lightBlueThemeColor
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: lightGrayThemeColor, NSFontAttributeName: defaultHeadFont]
//UIButton.appearance().backgroundColor = brightBlueThemeColor
//UIButton.appearance().tintColor = lightBlueThemeColor
UILabel.appearance().font = defaultBodyFont
UICollectionView.appearance().backgroundColor = lightLightLightGrayThemeColor
ScreenshotSectionHeaderView.appearance().backgroundColor = lightBlueThemeColor
//window?.tintColor = brightBlueThemeColor
}
}
| apache-2.0 | 7bc9fe5620701876bcc98d33253e4944 | 37.324324 | 150 | 0.717913 | 5.835391 | false | false | false | false |
zisko/swift | stdlib/public/SDK/UIKit/UIKit.swift | 2 | 12594 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
@_exported import UIKit
#if os(iOS) || os(tvOS)
import _SwiftUIKitOverlayShims
#endif
//===----------------------------------------------------------------------===//
// UIGeometry
//===----------------------------------------------------------------------===//
public extension UIEdgeInsets {
static var zero: UIEdgeInsets {
@_transparent // @fragile
get { return UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0) }
}
}
public extension UIOffset {
static var zero: UIOffset {
@_transparent // @fragile
get { return UIOffset(horizontal: 0.0, vertical: 0.0) }
}
}
//===----------------------------------------------------------------------===//
// Equatable types.
//===----------------------------------------------------------------------===//
@_transparent // @fragile
public func == (lhs: UIEdgeInsets, rhs: UIEdgeInsets) -> Bool {
return lhs.top == rhs.top &&
lhs.left == rhs.left &&
lhs.bottom == rhs.bottom &&
lhs.right == rhs.right
}
extension UIEdgeInsets : Equatable {}
@_transparent // @fragile
public func == (lhs: UIOffset, rhs: UIOffset) -> Bool {
return lhs.horizontal == rhs.horizontal &&
lhs.vertical == rhs.vertical
}
extension UIOffset : Equatable {}
//===----------------------------------------------------------------------===//
// Numeric backed types
//===----------------------------------------------------------------------===//
@available(swift 4)
public protocol _UIKitNumericRawRepresentable : RawRepresentable, Comparable where RawValue: Comparable & Numeric {}
extension _UIKitNumericRawRepresentable {
public static func <(lhs: Self, rhs: Self) -> Bool {
return lhs.rawValue < rhs.rawValue
}
public static func +(lhs: Self, rhs: RawValue) -> Self {
return Self(rawValue: lhs.rawValue + rhs)!
}
public static func +(lhs: RawValue, rhs: Self) -> Self {
return Self(rawValue: lhs + rhs.rawValue)!
}
public static func -(lhs: Self, rhs: RawValue) -> Self {
return Self(rawValue: lhs.rawValue - rhs)!
}
public static func -(lhs: Self, rhs: Self) -> RawValue {
return lhs.rawValue - rhs.rawValue
}
public static func +=(lhs: inout Self, rhs: RawValue) {
lhs = Self(rawValue: lhs.rawValue + rhs)!
}
public static func -=(lhs: inout Self, rhs: RawValue) {
lhs = Self(rawValue: lhs.rawValue - rhs)!
}
}
@available(swift 4)
extension UIFont.Weight : _UIKitNumericRawRepresentable {}
#if !os(watchOS)
@available(swift 4)
extension UILayoutPriority : _UIKitNumericRawRepresentable {}
#endif
// These are un-imported macros in UIKit.
//===----------------------------------------------------------------------===//
// UIDeviceOrientation
//===----------------------------------------------------------------------===//
#if !os(watchOS) && !os(tvOS)
public extension UIDeviceOrientation {
var isLandscape: Bool {
return self == .landscapeLeft || self == .landscapeRight
}
var isPortrait: Bool {
return self == .portrait || self == .portraitUpsideDown
}
var isFlat: Bool {
return self == .faceUp || self == .faceDown
}
var isValidInterfaceOrientation: Bool {
switch self {
case .portrait, .portraitUpsideDown, .landscapeLeft, .landscapeRight:
return true
default:
return false
}
}
}
public func UIDeviceOrientationIsLandscape(
_ orientation: UIDeviceOrientation
) -> Bool {
return orientation.isLandscape
}
public func UIDeviceOrientationIsPortrait(
_ orientation: UIDeviceOrientation
) -> Bool {
return orientation.isPortrait
}
public func UIDeviceOrientationIsValidInterfaceOrientation(
_ orientation: UIDeviceOrientation) -> Bool
{
return orientation.isValidInterfaceOrientation
}
#endif
//===----------------------------------------------------------------------===//
// UIInterfaceOrientation
//===----------------------------------------------------------------------===//
#if !os(watchOS) && !os(tvOS)
public extension UIInterfaceOrientation {
var isLandscape: Bool {
return self == .landscapeLeft || self == .landscapeRight
}
var isPortrait: Bool {
return self == .portrait || self == .portraitUpsideDown
}
}
public func UIInterfaceOrientationIsPortrait(
_ orientation: UIInterfaceOrientation) -> Bool {
return orientation.isPortrait
}
public func UIInterfaceOrientationIsLandscape(
_ orientation: UIInterfaceOrientation
) -> Bool {
return orientation.isLandscape
}
#endif
// Overlays for variadic initializers.
#if !os(watchOS) && !os(tvOS)
public extension UIActionSheet {
convenience init(title: String?,
delegate: UIActionSheetDelegate?,
cancelButtonTitle: String?,
destructiveButtonTitle: String?,
// Hack around overload ambiguity with non-variadic constructor.
// <rdar://problem/16704770>
otherButtonTitles firstButtonTitle: String,
_ moreButtonTitles: String...) {
self.init(title: title,
delegate: delegate,
cancelButtonTitle: cancelButtonTitle,
destructiveButtonTitle: destructiveButtonTitle)
self.addButton(withTitle: firstButtonTitle)
for buttonTitle in moreButtonTitles {
self.addButton(withTitle: buttonTitle)
}
}
}
#endif
#if !os(watchOS) && !os(tvOS)
public extension UIAlertView {
convenience init(title: String,
message: String,
delegate: UIAlertViewDelegate?,
cancelButtonTitle: String?,
// Hack around overload ambiguity with non-variadic constructor.
// <rdar://problem/16704770>
otherButtonTitles firstButtonTitle: String,
_ moreButtonTitles: String...) {
self.init(title: title,
message: message,
delegate: delegate,
cancelButtonTitle: cancelButtonTitle)
self.addButton(withTitle: firstButtonTitle)
for buttonTitle in moreButtonTitles {
self.addButton(withTitle: buttonTitle)
}
}
}
#endif
#if !os(watchOS)
internal struct _UIViewQuickLookState {
static var views = Set<UIView>()
}
extension UIView : _DefaultCustomPlaygroundQuickLookable {
public var _defaultCustomPlaygroundQuickLook: PlaygroundQuickLook {
if _UIViewQuickLookState.views.contains(self) {
return .view(UIImage())
} else {
_UIViewQuickLookState.views.insert(self)
// in case of an empty rectangle abort the logging
if (bounds.size.width == 0) || (bounds.size.height == 0) {
return .view(UIImage())
}
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0)
// UIKit is about to update this to be optional, so make it work
// with both older and newer SDKs. (In this context it should always
// be present.)
let ctx: CGContext! = UIGraphicsGetCurrentContext()
UIColor(white:1.0, alpha:0.0).set()
ctx.fill(bounds)
layer.render(in: ctx)
let image: UIImage! = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
_UIViewQuickLookState.views.remove(self)
return .view(image)
}
}
}
#endif
extension UIColor : _ExpressibleByColorLiteral {
@nonobjc public required convenience init(_colorLiteralRed red: Float,
green: Float,
blue: Float, alpha: Float) {
self.init(red: CGFloat(red), green: CGFloat(green),
blue: CGFloat(blue), alpha: CGFloat(alpha))
}
}
public typealias _ColorLiteralType = UIColor
extension UIImage : _ExpressibleByImageLiteral {
private convenience init!(failableImageLiteral name: String) {
self.init(named: name)
}
public required convenience init(imageLiteralResourceName name: String) {
self.init(failableImageLiteral: name)
}
}
public typealias _ImageLiteralType = UIImage
extension UIFontTextStyle {
@available(iOS 11.0, watchOS 4.0, tvOS 11.0, *)
public var metrics: UIFontMetrics {
return UIFontMetrics(forTextStyle: self)
}
}
#if !os(watchOS) // UIContentSizeCategory not available on watchOS
extension UIContentSizeCategory {
@available(iOS 11.0, tvOS 11.0, *)
public var isAccessibilityCategory: Bool {
return __UIContentSizeCategoryIsAccessibilityCategory(self)
}
@available(iOS 11.0, tvOS 11.0, *)
public static func < (left: UIContentSizeCategory, right: UIContentSizeCategory) -> Bool {
return __UIContentSizeCategoryCompareToCategory(left, right) == .orderedAscending
}
@available(iOS 11.0, tvOS 11.0, *)
public static func <= (left: UIContentSizeCategory, right: UIContentSizeCategory) -> Bool {
return __UIContentSizeCategoryCompareToCategory(left, right) != .orderedDescending
}
@available(iOS 11.0, tvOS 11.0, *)
public static func > (left: UIContentSizeCategory, right: UIContentSizeCategory) -> Bool {
return __UIContentSizeCategoryCompareToCategory(left, right) == .orderedDescending
}
@available(iOS 11.0, tvOS 11.0, *)
public static func >= (left: UIContentSizeCategory, right: UIContentSizeCategory) -> Bool {
return __UIContentSizeCategoryCompareToCategory(left, right) != .orderedAscending
}
}
#endif
//===----------------------------------------------------------------------===//
// Focus
//===----------------------------------------------------------------------===//
#if os(iOS) || os(tvOS)
@available(iOS 11.0, tvOS 11.0, *)
extension UIFocusEnvironment {
@available(iOS 11.0, tvOS 11.0, *)
public func contains(_ environment: UIFocusEnvironment) -> Bool {
return _swift_UIKit_UIFocusEnvironmentContainsEnvironment(self, environment)
}
}
@available(iOS 11.0, tvOS 11.0, *)
extension UIFocusItem {
@available(iOS 11.0, tvOS 11.0, *)
public var isFocused: Bool {
return self === UIScreen.main.focusedItem
}
}
#endif
//===----------------------------------------------------------------------===//
// NSItemProviderReading/Writing support
//===----------------------------------------------------------------------===//
#if os(iOS)
@available(iOS 11.0, *)
extension UIDragDropSession {
@available(iOS 11.0, *)
public func canLoadObjects<
T : _ObjectiveCBridgeable
>(ofClass: T.Type) -> Bool where T._ObjectiveCType : NSItemProviderReading {
return self.canLoadObjects(ofClass: T._ObjectiveCType.self);
}
}
@available(iOS 11.0, *)
extension UIDropSession {
@available(iOS 11.0, *)
public func loadObjects<
T : _ObjectiveCBridgeable
>(
ofClass: T.Type,
completion: @escaping ([T]) -> Void
) -> Progress where T._ObjectiveCType : NSItemProviderReading {
return self.loadObjects(ofClass: T._ObjectiveCType.self) { nss in
let natives = nss.map { $0 as! T }
completion(natives)
}
}
}
@available(iOS 11.0, *)
extension UIPasteConfiguration {
@available(iOS 11.0, *)
public convenience init<
T : _ObjectiveCBridgeable
>(forAccepting _: T.Type) where T._ObjectiveCType : NSItemProviderReading {
self.init(forAccepting: T._ObjectiveCType.self)
}
@available(iOS 11.0, *)
public func addTypeIdentifiers<
T : _ObjectiveCBridgeable
>(forAccepting aClass: T.Type)
where T._ObjectiveCType : NSItemProviderReading {
self.addTypeIdentifiers(forAccepting: T._ObjectiveCType.self)
}
}
extension UIPasteboard {
@available(iOS 11.0, *)
public func setObjects<
T : _ObjectiveCBridgeable
>(_ objects: [T]) where T._ObjectiveCType : NSItemProviderWriting {
// Using a simpler `$0 as! T._ObjectiveCType` triggers and assertion in
// the compiler.
self.setObjects(objects.map { $0._bridgeToObjectiveC() })
}
@available(iOS 11.0, *)
public func setObjects<
T : _ObjectiveCBridgeable
>(
_ objects: [T],
localOnly: Bool,
expirationDate: Date?
) where T._ObjectiveCType : NSItemProviderWriting {
self.setObjects(
// Using a simpler `$0 as! T._ObjectiveCType` triggers and assertion in
// the compiler.
objects.map { $0._bridgeToObjectiveC() },
localOnly: localOnly,
expirationDate: expirationDate)
}
}
#endif
| apache-2.0 | 4fe1216e6b9a99e9cc06b7b19952e23d | 28.70283 | 116 | 0.616484 | 4.76504 | false | false | false | false |
lseeker/HeidiKit | HeidiKit/UIImageGifExtension.swift | 1 | 3590 | //
// UIImageGifExtension.swift
// DCLifeHD
//
// Created by Yun-young LEE on 2015. 10. 9..
// Copyright © 2015년 Yun-young LEE. All rights reserved.
//
import UIKit
import ImageIO
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
extension UIImage {
class func animatedImageWithAnimatedGIFData(_ data: Data) -> UIImage? {
guard let source = CGImageSourceCreateWithData(data as CFData, nil) else {
return nil
}
let imageCount = CGImageSourceGetCount(source)
if imageCount == 1 {
// not animated gif
return UIImage(cgImage: CGImageSourceCreateImageAtIndex(source, 0, nil)!)
}
var images = [CGImage]()
var delays = [Int]()
for i in 0 ..< imageCount {
images.append(CGImageSourceCreateImageAtIndex(source, i, nil)!)
delays.append(delayForImageAtIndex(source, index: i))
}
var totalDuration = 0
for delay in delays {
totalDuration += delay
}
let frames = frameArray(imageCount, images: images, delays: delays)
return UIImage.animatedImage(with: frames, duration: Double(totalDuration) / 100.0)
}
class func delayForImageAtIndex(_ source: CGImageSource, index: Int) -> Int {
var delay = 1;
guard let properties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as NSDictionary? else {
return delay
}
guard let gifProps = properties[String(kCGImagePropertyGIFDictionary)] as? NSDictionary else {
return delay
}
var number = gifProps[String(kCGImagePropertyGIFUnclampedDelayTime)] as? NSNumber
if number == nil || number?.doubleValue == 0.0 {
number = gifProps[String(kCGImagePropertyGIFDelayTime)] as? NSNumber
}
if number?.doubleValue > 0.0 {
delay = lrint(number!.doubleValue * 100.0)
}
return delay
}
class func frameArray(_ count: Int, images: [CGImage], delays: [Int]) -> [UIImage] {
let gcd = vectorGCD(delays)
var frames = [UIImage]()
for i in 0 ..< count {
let frame = UIImage(cgImage: images[i])
for j in ((0 + 1)...delays[i] / gcd).reversed() {
frames.append(frame)
}
}
return frames
}
class func vectorGCD(_ values: [Int]) -> Int {
var gcd = values[0]
for value in values.suffix(from: 1) {
gcd = pairGCD(value, gcd)
}
return gcd
}
class func pairGCD(_ ap: Int, _ bp: Int) -> Int {
if ap < bp {
return pairGCD(bp, ap)
}
var a = ap;
var b = bp;
for ;; {
let r = a % b
if r == 0 {
return b
}
a = b
b = r
}
}
}
| apache-2.0 | 1395a5fe61c032fcc6772157c6d43872 | 28.162602 | 109 | 0.557848 | 4.506281 | false | false | false | false |
wyp767363905/TestKitchen_1606 | TestKitchen/TestKitchen/classes/cookbook/foodCourse/view/FCCommentCell.swift | 1 | 1529 | //
// FCCommentCell.swift
// TestKitchen
//
// Created by qianfeng on 16/8/26.
// Copyright © 2016年 1606. All rights reserved.
//
import UIKit
class FCCommentCell: UITableViewCell {
@IBOutlet weak var userImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var contentLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
//显示数据
var model: FCCommentDetail? {
didSet {
if model != nil {
showData()
}
}
}
func showData(){
//图片
let url = NSURL(string: (model?.head_img)!)
userImageView.layer.cornerRadius = 30
userImageView.layer.masksToBounds = true
userImageView.kf_setImageWithURL(url, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
//名字
nameLabel.text = model?.nick
//内容
contentLabel.text = model?.content
//时间
timeLabel.text = model?.create_time
}
@IBAction func reportAction(sender: UIButton) {
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 7fb15c9aa3c50b6eb09548c009ab04dc | 21.41791 | 158 | 0.569241 | 5.040268 | false | false | false | false |
atl009/WordPress-iOS | WordPressKit/WordPressKit/Activity.swift | 1 | 3780 | import Foundation
public struct Activity {
public let activityID: String
public let summary: String
public let name: String
public let type: String
public let gridicon: String
public let status: String
public let rewindable: Bool
public let rewindID: String?
public let published: Date
public let actor: ActivityActor?
public let object: ActivityObject?
public let target: ActivityObject?
public let items: [ActivityObject]?
init(dictionary: [String: AnyObject]) throws {
guard let id = dictionary["activity_id"] as? String else {
throw Error.missingActivityId
}
guard let publishedString = dictionary["published"] as? String else {
throw Error.missingPublishedDate
}
let dateFormatter = ISO8601DateFormatter()
guard let publishedDate = dateFormatter.date(from: publishedString) else {
throw Error.incorrectPusblishedDateFormat
}
activityID = id
published = publishedDate
summary = dictionary["summary"] as? String ?? ""
name = dictionary["name"] as? String ?? ""
type = dictionary["type"] as? String ?? ""
gridicon = dictionary["gridicon"] as? String ?? ""
status = dictionary["status"] as? String ?? ""
rewindable = dictionary["is_rewindable"] as? Bool ?? false
rewindID = dictionary["rewind_id"] as? String
if let actorData = dictionary["actor"] as? [String: AnyObject] {
actor = ActivityActor(dictionary: actorData)
} else {
actor = nil
}
if let objectData = dictionary["object"] as? [String: AnyObject] {
object = ActivityObject(dictionary: objectData)
} else {
object = nil
}
if let targetData = dictionary["actor"] as? [String: AnyObject] {
target = ActivityObject(dictionary: targetData)
} else {
target = nil
}
if let orderedItems = dictionary["items"] as? [[String: AnyObject]] {
items = orderedItems.map { item -> ActivityObject in
return ActivityObject(dictionary: item)
}
} else {
items = nil
}
}
}
private extension Activity {
enum Error: Swift.Error {
case missingActivityId
case missingPublishedDate
case incorrectPusblishedDateFormat
}
}
public struct ActivityActor {
public let displayName: String
public let type: String
public let wpcomUserID: String
public let avatarURL: String
public let role: String
init(dictionary: [String: AnyObject]) {
displayName = dictionary["name"] as? String ?? ""
type = dictionary["type"] as? String ?? ""
wpcomUserID = dictionary["wp_com_user_id"] as? String ?? ""
if let iconInfo = dictionary["icon"] as? [String: AnyObject] {
avatarURL = iconInfo["url"] as? String ?? ""
} else {
avatarURL = ""
}
role = dictionary["role"] as? String ?? ""
}
}
public struct ActivityObject {
public let name: String
public let type: String
public let attributes: [String: Any]
init(dictionary: [String: AnyObject]) {
name = dictionary["name"] as? String ?? ""
type = dictionary["type"] as? String ?? ""
let mutableDictionary = NSMutableDictionary(dictionary: dictionary)
mutableDictionary.removeObjects(forKeys: ["name", "type"])
if let extraAttributes = mutableDictionary as? [String: Any] {
attributes = extraAttributes
} else {
attributes = [:]
}
}
}
public struct ActivityName {
public static let fullBackup = "rewind__backup_complete_full"
}
| gpl-2.0 | 7c0256e070e1d2d22377ca3c32ea81d0 | 33.054054 | 82 | 0.607407 | 4.689826 | false | false | false | false |
softmaxsg/trakt.tv-searcher | TraktSearcher/Models & View Models/MoviesViewModel.swift | 1 | 3553 | //
// MoviesViewModel.swift
// TraktSearcher
//
// Copyright © 2016 Vitaly Chupryk. All rights reserved.
//
import Foundation
import TraktSearchAPI
class MoviesViewModel: MoviesViewModelData, MoviesViewModelInput
{
static let pageSize: UInt = 10
let searchAPI: TraktSearchAPIProtocol
var lastPaginationInfo: PaginationInfo?
var lastCancelableToken: TraktSearchAPICancelable?
weak var delegate: MoviesViewModelOutput?
private (set) var loading: Bool = false
private (set) var movies: [MovieInfo] = []
var moreDataAvailable: Bool
{
get {
guard let pageNumber = self.lastPaginationInfo?.pageNumber, let pagesCount = self.lastPaginationInfo?.pagesCount else {
return false
}
return pageNumber < pagesCount
}
}
init(searchAPI: TraktSearchAPIProtocol)
{
self.searchAPI = searchAPI
}
func loadInitialData()
{
self.loadMovies(pageNumber: 1)
}
func loadMoreData()
{
if !self.moreDataAvailable {
// To keep behavior of this function always same delegate's method calling is called after end of this function
NSOperationQueue.mainQueue().addOperationWithBlock {
let error = NSError(domain: MoviesViewModelInputErrorDomain, code: MoviesViewModelInputNoMoreDataAvailableErrorCode, userInfo: nil)
self.delegate?.viewModelLoadingDidFail(error)
}
return
}
self.loadMovies(pageNumber: (self.lastPaginationInfo?.pageNumber ?? 0) + 1)
}
func clearData()
{
self.lastPaginationInfo = nil
self.movies = []
}
func loadMovies(pageNumber pageNumber: UInt, responseValidationHandler: ((MoviesResponse) -> Bool)? = nil)
{
assert(pageNumber > 0)
// It's preferable to call this method on the main thread
assert(NSOperationQueue.currentQueue() == NSOperationQueue.mainQueue())
if pageNumber == 1 {
self.clearData()
}
self.lastCancelableToken?.cancel()
self.loading = true
self.lastCancelableToken = self.performAPIRequest(pageNumber: pageNumber, pageSize: self.dynamicType.pageSize) { [weak self] response in
if !(responseValidationHandler?(response) ?? true) {
return
}
switch response {
case .Success(let movies, let paginationInfo):
let loadedMovies = movies.map { MovieInfo(
title: $0.title ?? "",
overview: $0.overview,
year: $0.year ?? 0,
imageUrl: $0.images?[MovieImageKind.Poster]?.thumbnail
)}
NSOperationQueue.mainQueue().addOperationWithBlock {
self?.lastPaginationInfo = paginationInfo
self?.movies = (self?.movies ?? []) + loadedMovies
self?.loading = false
self?.delegate?.viewModelDidUpdate()
}
case .Error(let error):
NSOperationQueue.mainQueue().addOperationWithBlock {
self?.loading = false
self?.delegate?.viewModelLoadingDidFail(error)
}
}
}
}
func performAPIRequest(pageNumber pageNumber: UInt, pageSize: UInt, completionHandler: (MoviesResponse) -> ()) -> TraktSearchAPICancelable?
{
assert(false, "Has to be overriden")
return nil
}
}
| mit | 009a086bc541a132ce7a6f112bf72ccc | 29.358974 | 147 | 0.600507 | 5.088825 | false | false | false | false |
lorentey/swift | stdlib/private/OSLog/OSLogIntegerTypes.swift | 3 | 6274 | //===----------------- OSLogIntegerTypes.swift ----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This file defines extensions for interpolating integer expressions into a
// OSLogMesage. It defines `appendInterpolation` functions for standard integer
// types. It also defines extensions for serializing integer types into the
// argument buffer passed to os_log ABIs.
//
// The `appendInterpolation` functions defined in this file accept formatting
// and privacy options along with the interpolated expression as shown below:
//
// "\(x, format: .hex, privacy: .private\)"
extension OSLogInterpolation {
/// Define interpolation for expressions of type Int.
/// - Parameters:
/// - number: the interpolated expression of type Int, which is autoclosured.
/// - format: a formatting option available for integer types, defined by the
/// enum `IntFormat`.
/// - privacy: a privacy qualifier which is either private or public.
/// The default is public.
@_semantics("constant_evaluable")
@inlinable
@_optimize(none)
public mutating func appendInterpolation(
_ number: @autoclosure @escaping () -> Int,
format: IntFormat = .decimal,
privacy: Privacy = .public
) {
appendInteger(number, format: format, privacy: privacy)
}
/// Define interpolation for expressions of type Int32.
/// - Parameters:
/// - number: the interpolated expression of type Int32, which is autoclosured.
/// - format: a formatting option available for integer types, defined by the
/// enum `IntFormat`.
/// - privacy: a privacy qualifier which is either private or public.
/// The default is public.
@_semantics("constant_evaluable")
@inlinable
@_optimize(none)
public mutating func appendInterpolation(
_ number: @autoclosure @escaping () -> Int32,
format: IntFormat = .decimal,
privacy: Privacy = .public
) {
appendInteger(number, format: format, privacy: privacy)
}
/// Given an integer, create and append a format specifier for the integer to the
/// format string property. Also, append the integer along with necessary headers
/// to the OSLogArguments property.
@_semantics("constant_evaluable")
@inlinable
@_optimize(none)
internal mutating func appendInteger<T>(
_ number: @escaping () -> T,
format: IntFormat,
privacy: Privacy
) where T: FixedWidthInteger {
guard argumentCount < maxOSLogArgumentCount else { return }
let isPrivateArgument = isPrivate(privacy)
formatString +=
getIntegerFormatSpecifier(
T.self,
format,
isPrivateArgument)
addIntHeaders(isPrivateArgument, sizeForEncoding(T.self))
arguments.append(number)
argumentCount += 1
}
/// Update preamble and append argument headers based on the parameters of
/// the interpolation.
@_semantics("constant_evaluable")
@inlinable
@_optimize(none)
internal mutating func addIntHeaders(_ isPrivate: Bool, _ byteCount: Int) {
// Append argument header.
let argumentHeader = getArgumentHeader(isPrivate: isPrivate, type: .scalar)
arguments.append(argumentHeader)
// Append number of bytes needed to serialize the argument.
arguments.append(UInt8(byteCount))
// Increment total byte size by the number of bytes needed for this
// argument, which is the sum of the byte size of the argument and
// two bytes needed for the headers.
totalBytesForSerializingArguments += byteCount + 2
preamble = getUpdatedPreamble(isPrivate: isPrivate, isScalar: true)
}
/// Construct an os_log format specifier from the given parameters.
/// This function must be constant evaluable and all its arguments
/// must be known at compile time.
@inlinable
@_semantics("constant_evaluable")
@_effects(readonly)
@_optimize(none)
internal func getIntegerFormatSpecifier<T>(
_ integerType: T.Type,
_ format: IntFormat,
_ isPrivate: Bool
) -> String where T : FixedWidthInteger {
var formatSpecifier: String = isPrivate ? "%{private}" : "%{public}"
// Add a length modifier to the specifier.
// TODO: more length modifiers will be added.
if (integerType.bitWidth == CLongLong.bitWidth) {
formatSpecifier += "ll"
}
// TODO: more format specifiers will be added.
switch (format) {
case .hex:
formatSpecifier += "x"
case .octal:
formatSpecifier += "o"
default:
formatSpecifier += integerType.isSigned ? "d" : "u"
}
return formatSpecifier
}
}
extension OSLogArguments {
/// Append an (autoclosured) interpolated expression of integer type, passed to
/// `OSLogMessage.appendInterpolation`, to the array of closures tracked
/// by this instance.
@_semantics("constant_evaluable")
@inlinable
@_optimize(none)
internal mutating func append<T>(
_ value: @escaping () -> T
) where T: FixedWidthInteger {
argumentClosures.append({ (position, _) in
serialize(value(), at: &position)
})
}
}
/// Return the number of bytes needed for serializing an integer argument as
/// specified by os_log. This function must be constant evaluable.
@_semantics("constant_evaluable")
@inlinable
@_optimize(none)
internal func sizeForEncoding<T>(
_ type: T.Type
) -> Int where T : FixedWidthInteger {
return type.bitWidth &>> logBitsPerByte
}
/// Serialize an integer at the buffer location that `position` points to and
/// increment `position` by the byte size of `T`.
@inlinable
@_alwaysEmitIntoClient
@inline(__always)
internal func serialize<T>(
_ value: T,
at bufferPosition: inout ByteBufferPointer
) where T : FixedWidthInteger {
let byteCount = sizeForEncoding(T.self)
let dest =
UnsafeMutableRawBufferPointer(start: bufferPosition, count: byteCount)
withUnsafeBytes(of: value) { dest.copyMemory(from: $0) }
bufferPosition += byteCount
}
| apache-2.0 | 0ce1b2b024349c1cfb95e280d5eb879d | 33.662983 | 83 | 0.68999 | 4.523432 | false | false | false | false |
granoff/Strongbox | Strongbox/Classes/Strongbox.swift | 1 | 6651 | //
// Strongbox.swift
// Strongbox
//
// Created by Mark Granoff on 10/8/16.
// Copyright © 2016 Hawk iMedia. All rights reserved.
//
import Foundation
import Security
public final class Strongbox {
let keyPrefix: String
private let lock = NSLock()
private(set) public var lastStatus = errSecSuccess
public init(keyPrefix: String?) {
self.keyPrefix = keyPrefix ?? Bundle.main.bundleIdentifier ?? ""
}
public convenience init() {
self.init(keyPrefix: nil)
}
/**
Insert an object into the keychain. Pass `nil` for object to remove it from the keychain.
- returns:
Boolean indicating success or failure
- parameters:
- object: data to store. Pass `nil` to remove previous value for key
- key: key with which to associate the stored value, or key to remove if `object` is nil
- accessibility: keychain accessibility of item once stored
*/
@discardableResult
public func archive(_ object: Any?, key: String, accessibility: CFString = kSecAttrAccessibleWhenUnlocked) -> Bool
{
guard let _=object as? NSSecureCoding else {
// The optional is empty, so remove the key
return remove(key: key, accessibility: accessibility)
}
// The lock prevents the code to be run simultaneously
// from multiple threads which may result in crashing
lock.lock()
defer { lock.unlock() }
let data = NSMutableData()
let archiver: NSKeyedArchiver
if #available(iOS 11.0, watchOSApplicationExtension 4.0, watchOS 11.0, tvOSApplicationExtension 11.0, tvOS 11.0, *) {
archiver = NSKeyedArchiver(requiringSecureCoding: true)
} else {
archiver = NSKeyedArchiver(forWritingWith: data)
}
archiver.encode(object, forKey: key)
archiver.finishEncoding()
var result = false
if #available(iOS 10.0, watchOSApplicationExtension 3.0, watchOS 3.0, tvOSApplicationExtension 10.0, tvOS 10.0, *) {
result = self.set(archiver.encodedData as NSData, key: key, accessibility: accessibility)
} else {
result = self.set(data, key: key, accessibility: accessibility)
}
return result
}
@discardableResult
public func archive<T: Encodable>(object: T?, key: String, encoder: JSONEncoder = .init(), accessibility: CFString = kSecAttrAccessibleWhenUnlocked) throws -> Bool {
guard let object = object else { return archive(nil, key: key, accessibility: accessibility) }
let data = try encoder.encode(object)
return archive(data, key: key, accessibility: accessibility)
}
/**
Convenience method for removing a previously stored key.
- returns:
Boolean indicating success or failure
- parameters:
- key: key for which to remove the stored value
- accessibility: keychain accessibility of item
*/
@discardableResult
public func remove(key: String, accessibility: CFString = kSecAttrAccessibleWhenUnlocked) -> Bool {
// The lock prevents the code to be run simultaneously
// from multiple threads which may result in crashing
lock.lock()
defer { lock.unlock() }
let query = self.query()
query[kSecAttrService] = hierarchicalKey(key)
lastStatus = SecItemDelete(query)
return lastStatus == errSecSuccess || lastStatus == errSecItemNotFound
}
/**
Retrieve an object from the keychain.
- returns:
Re-constituted object from keychain, or nil if the key was not found. Since the method returns `Any?` it is
the caller's responsibility to cast the result to the type expected.
- parameters:
- key: the key to use to locate the stored value
*/
public func unarchive(objectForKey key:String) -> Any? {
// The lock prevents the code to be run simultaneously
// from multiple threads which may result in crashing
lock.lock()
defer { lock.unlock() }
guard let data = self.data(forKey: key) else {
return nil
}
let unarchiver = NSKeyedUnarchiver(forReadingWith: data as Data)
return unarchiver.decodeObject(forKey: key)
}
public func unarchive<T: Decodable>(_ type: T.Type = T.self, for key: String, decoder: JSONDecoder = .init()) throws -> T? {
guard let data = unarchive(objectForKey: key) as? Data else { return nil }
return try decoder.decode(T.self, from: data)
}
}
internal extension Strongbox {
// MARK: Private functions to do all the work
private func set(_ data: NSData?, key: String, accessibility: CFString = kSecAttrAccessibleWhenUnlocked) -> Bool {
let hierKey = hierarchicalKey(key)
let dict = service()
let entries: [AnyHashable:Any] = [kSecAttrService as AnyHashable: hierKey,
kSecAttrAccessible as AnyHashable: accessibility,
kSecValueData as AnyHashable: data!]
dict.addEntries(from: entries)
lastStatus = SecItemAdd(dict as CFDictionary, nil)
if lastStatus == errSecDuplicateItem {
let query = self.query()
query.setObject(hierKey, forKey: kSecAttrService as! NSCopying)
lastStatus = SecItemDelete(query as CFDictionary)
if lastStatus == errSecSuccess {
lastStatus = SecItemAdd(dict as CFDictionary, nil)
}
}
return lastStatus == errSecSuccess
}
func hierarchicalKey(_ key: String) -> String {
return keyPrefix + "." + key
}
private func query() -> NSMutableDictionary {
let query = NSMutableDictionary()
query[kSecClass] = kSecClassGenericPassword
query[kSecReturnData] = kCFBooleanTrue
return query
}
private func service() -> NSMutableDictionary {
let dict = NSMutableDictionary()
dict.setObject(kSecClassGenericPassword, forKey: kSecClass as! NSCopying)
return dict
}
private func data(forKey key:String) -> Data? {
let hierKey = hierarchicalKey(key)
let query = self.query()
query.setObject(hierKey, forKey: kSecAttrService as! NSCopying)
var data: AnyObject?
lastStatus = SecItemCopyMatching(query, &data)
return data as? Data
}
}
| mit | 4a6ce5f553ff32b2635c7329c7496805 | 34.185185 | 169 | 0.620752 | 5.107527 | false | false | false | false |
lijie121210/PZPullToRefresh | PZPullToRefresh-Sample/ViewController.swift | 4 | 2777 | //
// ViewController.swift
// PZPullToRefresh-Sample
//
// Created by pixyzehn on 3/21/15.
// Copyright (c) 2015 pixyzehn. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, PZPullToRefreshDelegate {
var items = ["Evernote", "Dropbox", "Sketch", "Xcode", "Pocket", "Tweetbot", "Reeder", "LINE", "Slack", "Spotify", "Sunrise", "Atom", "Dash", "Reveal", "Alternote", "iTerm"]
@IBOutlet weak var tableView: UITableView!
var refreshHeaderView: PZPullToRefreshView?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor()
self.tableView.delegate = self
self.tableView.dataSource = self
self.edgesForExtendedLayout = UIRectEdge.None
if refreshHeaderView == nil {
var view = PZPullToRefreshView(frame: CGRectMake(0, 0 - tableView.bounds.size.height, tableView.bounds.size.width, tableView.bounds.size.height))
view.delegate = self
self.tableView.addSubview(view)
refreshHeaderView = view
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
cell.textLabel?.text = items[indexPath.row]
return cell
}
// MARK:UIScrollViewDelegate
func scrollViewDidScroll(scrollView: UIScrollView) {
refreshHeaderView?.refreshScrollViewDidScroll(scrollView)
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
refreshHeaderView?.refreshScrollViewDidEndDragging(scrollView)
}
// MARK:PZPullToRefreshDelegate
func pullToRefreshDidTrigger(view: PZPullToRefreshView) -> () {
refreshHeaderView?.isLoading = true
let delay = 3.0 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue(), {
println("Complete loading!")
self.refreshHeaderView?.isLoading = false
self.refreshHeaderView?.refreshScrollViewDataSourceDidFinishedLoading(self.tableView)
})
}
// Optional method
func pullToRefreshLastUpdated(view: PZPullToRefreshView) -> NSDate {
return NSDate()
}
}
| mit | 76e8a9d7c0d0ba28779aad064e32138c | 33.283951 | 177 | 0.665466 | 5.039927 | false | false | false | false |
tiger8888/LayerPlayer | LayerPlayer/AVPlayerLayerViewController.swift | 3 | 3752 | //
// AVPlayerLayerViewController.swift
// LayerPlayer
//
// Created by Scott Gardner on 12/6/14.
// Copyright (c) 2014 Scott Gardner. All rights reserved.
//
import UIKit
import AVFoundation
class AVPlayerLayerViewController: UIViewController {
@IBOutlet weak var viewForPlayerLayer: UIView!
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var rateSegmentedControl: UISegmentedControl!
@IBOutlet weak var loopSwitch: UISwitch!
@IBOutlet weak var volumeSlider: UISlider!
enum Rate: Int {
case SlowForward, Normal, FastForward
}
let playerLayer = AVPlayerLayer()
var player: AVPlayer {
return playerLayer.player
}
var rateBeforePause: Float?
var shouldLoop = true
var isPlaying = false
// MARK: - Quick reference
func setUpPlayerLayer() {
playerLayer.frame = viewForPlayerLayer.bounds
let url = NSBundle.mainBundle().URLForResource("colorfulStreak", withExtension: "m4v")
let player = AVPlayer(URL: url)
player.actionAtItemEnd = .None
playerLayer.player = player
}
// MARK: - View life cycle
override func viewDidLoad() {
super.viewDidLoad()
setUpPlayerLayer()
viewForPlayerLayer.layer.addSublayer(playerLayer)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidReachEndNotificationHandler:", name: "AVPlayerItemDidPlayToEndTimeNotification", object: player.currentItem)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - IBActions
@IBAction func playButtonTapped(sender: UIButton) {
play()
}
@IBAction func rateSegmentedControlChanged(sender: UISegmentedControl) {
var rate: Float!
switch sender.selectedSegmentIndex {
case Rate.SlowForward.rawValue:
rate = 0.5
case Rate.FastForward.rawValue:
rate = 2.0
default:
rate = 1.0
}
player.rate = rate
isPlaying = true
rateBeforePause = rate
updatePlayButtonTitle()
}
@IBAction func loopSwitchChanged(sender: UISwitch) {
shouldLoop = sender.on
if shouldLoop {
player.actionAtItemEnd = .None
} else {
player.actionAtItemEnd = .Pause
}
}
@IBAction func volumeSliderChanged(sender: UISlider) {
player.volume = sender.value
}
// MARK: - Triggered actions
func play() {
if playButton.titleLabel?.text == "Play" {
if let resumeRate = rateBeforePause {
player.rate = resumeRate
} else {
player.play()
}
isPlaying = true
} else {
rateBeforePause = player.rate
player.pause()
isPlaying = false
}
updatePlayButtonTitle()
updateRateSegmentedControl()
}
func playerDidReachEndNotificationHandler(notification: NSNotification) {
let playerItem = notification.object as AVPlayerItem
playerItem.seekToTime(kCMTimeZero)
if !shouldLoop {
player.pause()
isPlaying = false
updatePlayButtonTitle()
updateRateSegmentedControl()
}
}
// MARK: - Helpers
func updatePlayButtonTitle() {
if isPlaying {
playButton.setTitle("Pause", forState: .Normal)
} else {
playButton.setTitle("Play", forState: .Normal)
}
}
func updateRateSegmentedControl() {
if isPlaying {
switch player.rate {
case 0.5:
rateSegmentedControl.selectedSegmentIndex = Rate.SlowForward.rawValue
case 1.0:
rateSegmentedControl.selectedSegmentIndex = Rate.Normal.rawValue
case 2.0:
rateSegmentedControl.selectedSegmentIndex = Rate.FastForward.rawValue
default:
break
}
} else {
rateSegmentedControl.selectedSegmentIndex = UISegmentedControlNoSegment
}
}
}
| mit | 97a09687fd1cfc5fb4ca8e3eb65bc6be | 23.522876 | 187 | 0.676173 | 4.761421 | false | false | false | false |
michaelborgmann/handshake | Handshake/DetailView.swift | 1 | 2886 | //
// DetailView.swift
// Handshake
//
// Created by Michael Borgmann on 06/08/15.
// Copyright (c) 2015 Michael Borgmann. All rights reserved.
//
import UIKit
class DetailView: UIViewController, UITextFieldDelegate {
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var priceField: UITextField!
@IBOutlet weak var amountField: UITextField!
@IBOutlet weak var notesField: UITextField!
var item: Item?
var email: String?
var dismissBlock: (() -> ())?
init() {
super.init(nibName: "DetailView", bundle: nil)
self.navigationItem.title = "Details"
let cancelItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: "cancel:")
navigationItem.leftBarButtonItem = cancelItem
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
nameField.delegate = self
priceField.delegate = self
amountField.delegate = self
notesField.delegate = self
print ("Email: \(email)")
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
nameField.text = item?.name
priceField.text = "\(item!.price)"
amountField.text = "\(item!.amount)"
notesField.text = item?.notes
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(true)
view.endEditing(true)
item!.name = nameField.text
item!.amount = amountField.text.toInt()!
item!.notes = notesField.text
item!.price = (priceField.text as NSString).floatValue
item!.email = email!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
nameField.resignFirstResponder()
priceField.resignFirstResponder()
amountField.resignFirstResponder()
notesField.resignFirstResponder()
return true
}
@IBAction func saveItem(sender: AnyObject) {
//presentingViewController!.dismissViewControllerAnimated(true, completion: dismissBlock)
navigationController?.popViewControllerAnimated(true)
}
func cancel(sender: AnyObject) {
//@IBAction func cancelButtonPressed(sender: AnyObject) {
//ItemStore.sharedStore.removeItem(item!)
navigationController?.popViewControllerAnimated(true)
//presentingViewController!.dismissViewControllerAnimated(true) {
//println("Cancelling new item creation and asking to dismiss NameViewController.")
}
}
| gpl-2.0 | 02ed9280cf1857fc6ac69b6a49df367f | 29.378947 | 103 | 0.650381 | 5.190647 | false | false | false | false |
benlangmuir/swift | test/DebugInfo/async-direct-arg.swift | 12 | 1037 | // RUN: %target-swift-frontend %s -emit-ir -g -o - \
// RUN: -module-name a -disable-availability-checking \
// RUN: -parse-as-library | %FileCheck %s --check-prefix=CHECK
// REQUIRES: concurrency
// REQUIRES: rdar74588568
// Test that x is described as a direct dbg.declare of the incoming function
// argument.
// CHECK-LABEL: define {{.*}} void @"$s1a3fibyS2iYF.resume.0"
// CHECK: call void @llvm.dbg.declare
// CHECK: call void @llvm.dbg.declare
// CHECK: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[X0:[0-9]+]], {{.*}}!DIExpression(DW_OP
// CHECK-LABEL: define {{.*}} void @"$s1a3fibyS2iYF.resume.1"
// FIXME: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[X1:[0-9]+]], {{.*}}!DIExpression(DW_OP
// CHECK: ![[X0]] = !DILocalVariable(name: "x"
// FIXME: ![[X1]] = !DILocalVariable(name: "x"
func fib(_ x: Int) async -> Int {
if x <= 1 { return 1 }
let a = await fib(x - 1)
let b = await fib(x - 2)
return a + b
}
@main struct Main {
static func main() async {
await fib(4)
}
}
| apache-2.0 | 4074e0a2004e7681401059624aee191b | 32.451613 | 107 | 0.622951 | 2.99711 | false | false | false | false |
josh64x2/vienna-rss | Vienna/Sources/Shared/Constants.swift | 3 | 1540 | //
// Constants.swift
// Vienna
//
// Copyright 2020
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/// New articles notification method (managed as an array of binary flags)
@objc(VNANewArticlesNotification)
enum NewArticlesNotification: Int {
case bounce = 2
}
/// Filtering options
@objc(VNAFilter)
enum Filter: Int {
case all = 0
case unread = 1
case lastRefresh = 2
case today = 3
case time48h = 4
case flagged = 5
case unreadOrFlagged = 6
}
/// Refresh folder options
@objc(VNARefresh)
enum Refresh: Int {
case redrawList = 0
case reapplyFilter = 1
case sortAndRedraw = 3
}
/// Layout styles
@objc(VNALayout)
enum Layout: Int {
case report = 1
case condensed = 2
case unified = 3
}
/// Folders tree sort method
@objc(VNAFolderSort)
enum FolderSort: Int {
case manual = 0
case byName = 1
}
/// Empty trash option on quitting
@objc(VNAEmptyTrash)
enum EmptyTrash: Int {
case none = 0
case withoutWarning = 1
case withWarning = 2
}
| apache-2.0 | 4f0a822a2ae1ac33325c063854637378 | 21.985075 | 76 | 0.691558 | 3.666667 | false | false | false | false |
esttorhe/MammutAPI | Sources/MammutAPI/Network/EndpointRequest.swift | 1 | 3251 | //
// Created by Esteban Torres on 14.04.17.
// Copyright (c) 2017 Esteban Torres. All rights reserved.
//
import Foundation
internal protocol EndpointRequesting {
typealias CompletionHandler = (Result<Data, MammutAPIError.NetworkError>) -> Void
var basePath: String { get }
func execute(_ completion: @escaping CompletionHandler)
}
internal class EndpointRequest: EndpointRequesting {
let basePath: String
let session: DataTaskCreating
let endpoint: URLProviding
init(basePath: String, session: DataTaskCreating, endpoint: URLProviding) {
self.basePath = basePath
self.session = session
self.endpoint = endpoint
}
func execute(_ completion: @escaping EndpointRequesting.CompletionHandler) {
let result = resolveEndpoint()
switch result {
case .failure(let error): completion(Result.failure(error))
case .success(let urlRequest):
let task = session.dataTask(with: urlRequest) { data, response, error in
// Server returned an error
if let error = error {
#if os(Linux)
// Had to add this because on Linux the build fails unless when casting Error to NSError
// unless forced casting it
if let error = error as? NSError {
completion(.failure(MammutAPIError.NetworkError.serverError(error)))
} else {
let underlyingError = NSError(error: error)
completion(.failure(MammutAPIError.NetworkError.serverError(underlyingError)))
}
#else
completion(.failure(MammutAPIError.NetworkError.serverError(error as NSError)))
#endif
return
}
// Server replied with an empty response 🤔
if response == nil {
completion(.failure(MammutAPIError.NetworkError.emptyResponse))
return
}
// Status Code out of expected range
if let response = response as? HTTPURLResponse,
!self.endpoint.validResponseCodes.contains(response.statusCode) {
completion(.failure(MammutAPIError.NetworkError.invalidStatusCode(response)))
return
}
// No data returned
guard let data = data else {
completion(.failure(MammutAPIError.NetworkError.emptyResponse))
return
}
completion(.success(data))
}
task.resume()
}
}
}
fileprivate extension EndpointRequest {
func resolveEndpoint() -> Result<URLRequest, MammutAPIError.NetworkError> {
guard let baseURL = URL(string: basePath) else {
return .failure(MammutAPIError.NetworkError.malformedURL)
}
let url: URL
if let path = endpoint.path {
url = baseURL.appendingPathComponent(path)
} else {
url = baseURL
}
var request = URLRequest(url: url)
request.httpMethod = endpoint.method.rawValue
return .success(request)
}
}
| mit | e13bd7e9af469fc96f6aaa7dceba5859 | 33.189474 | 108 | 0.585283 | 5.350906 | false | false | false | false |
crashoverride777/Swift2-iAds-AdMob-CustomAds-Helper | SwiftyAd/SwiftyAd.swift | 2 | 21159 | // The MIT License (MIT)
//
// Copyright (c) 2015-2018 Dominik Ringler
//
// 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 GoogleMobileAds
#warning("FIX")
/// LocalizedString
private extension String {
static let sorry = "Sorry"
static let ok = "OK"
static let noVideo = "No video available to watch at the moment."
}
/// SwiftyAdDelegate
protocol SwiftyAdDelegate: class {
/// SwiftyAd did open
func swiftyAdDidOpen(_ swiftyAd: SwiftyAd)
/// SwiftyAd did close
func swiftyAdDidClose(_ swiftyAd: SwiftyAd)
/// Did change consent status
func swiftyAd(_ swiftyAd: SwiftyAd, didChange consentStatus: SwiftyAd.ConsentStatus)
/// SwiftyAd did reward user
func swiftyAd(_ swiftyAd: SwiftyAd, didRewardUserWithAmount rewardAmount: Int)
}
/// SwiftyAdMediationType
protocol SwiftyAdMediationType: class {
func update(for consentType: SwiftyAd.ConsentStatus)
}
/**
SwiftyAd
A singleton class to manage adverts from Google AdMob.
*/
final class SwiftyAd: NSObject {
typealias ConsentConfiguration = SwiftyAdConsentManager.Configuration
typealias ConsentStatus = SwiftyAdConsentManager.ConsentStatus
// MARK: - Types
private struct Configuration: Codable {
let bannerAdUnitId: String
let interstitialAdUnitId: String
let rewardedVideoAdUnitId: String
let gdpr: ConsentConfiguration
var ids: [String] {
return [bannerAdUnitId, interstitialAdUnitId, rewardedVideoAdUnitId].filter { !$0.isEmpty }
}
static var propertyList: Configuration {
guard let configurationURL = Bundle.main.url(forResource: "SwiftyAd", withExtension: "plist") else {
fatalError("SwiftyAd must have a valid property list url")
}
do {
let data = try Data(contentsOf: configurationURL)
let decoder = PropertyListDecoder()
return try decoder.decode(Configuration.self, from: data)
} catch {
fatalError("SwiftyAd property list decoding error: \(error)")
}
}
static var debug: Configuration {
return Configuration(
bannerAdUnitId: "ca-app-pub-3940256099942544/2934735716",
interstitialAdUnitId: "ca-app-pub-3940256099942544/4411468910", // video = ca-app-pub-3940256099942544/5135589807
rewardedVideoAdUnitId: "ca-app-pub-3940256099942544/1712485313",
gdpr: ConsentConfiguration(
privacyPolicyURL: "https://developers.google.com/admob/ios/eu-consent",
shouldOfferAdFree: false,
mediationNetworks: [],
isTaggedForUnderAgeOfConsent: false,
isCustomForm: true
)
)
}
}
// MARK: - Static Properties
/// Shared instance
static let shared = SwiftyAd()
// MARK: - Properties
/// Check if user has consent e.g to hide rewarded video button
var hasConsent: Bool {
return consentManager.hasConsent
}
/// Check if we must ask for consent e.g to hide change consent button in apps settings menu (required GDPR requiredment)
var isRequiredToAskForConsent: Bool {
return consentManager.isRequiredToAskForConsent
}
/// Check if interstitial video is ready (e.g to show alternative ad like an in house ad)
/// Will try to reload an ad if it returns false.
var isInterstitialReady: Bool {
guard interstitialAd?.isReady == true else {
print("AdMob interstitial ad is not ready, reloading...")
loadInterstitialAd()
return false
}
return true
}
/// Check if reward video is ready (e.g to hide a reward video button)
/// Will try to reload an ad if it returns false.
var isRewardedVideoReady: Bool {
guard rewardedVideoAd?.isReady == true else {
print("AdMob reward video is not ready, reloading...")
loadRewardedVideoAd()
return false
}
return true
}
/// Remove ads e.g for in app purchases
var isRemoved = false {
didSet {
guard isRemoved else { return }
removeBanner()
interstitialAd?.delegate = nil
interstitialAd = nil
}
}
/// Delegates
private weak var delegate: SwiftyAdDelegate?
/// Configuration
private var configuration: Configuration!
/// Consent manager
private var consentManager: SwiftyAdConsentManager!
/// Mediation manager
private var mediationManager: SwiftyAdMediationType?
/// Ads
private var bannerAdView: GADBannerView?
private var interstitialAd: GADInterstitial?
private var rewardedVideoAd: GADRewardBasedVideoAd?
/// Constraints
private var bannerViewConstraint: NSLayoutConstraint?
/// Banner animation duration
private var bannerAnimationDuration = 1.8
/// Interval counter
private var intervalCounter = 0
// MARK: - Init
private override init() {
super.init()
print("AdMob SDK version \(GADRequest.sdkVersion())")
// Add notification center observers
NotificationCenter.default.addObserver(
self,
selector: #selector(deviceRotated),
name: UIDevice.orientationDidChangeNotification,
object: nil
)
}
// MARK: - Setup
/// Setup swift ad
///
/// - parameter viewController: The view controller that will present the consent alert if needed.
/// - parameter delegate: A delegate to receive event callbacks.
/// - parameter mediationManager: An optional protocol for mediation network implementation e.g for consent status changes.
/// - parameter bannerAnimationDuration: The duration of the banner animation.
/// - parameter testDevices: An array of test device IDs if you want to do more rigorous testing with production-looking ads (see google docs). Defaults to nil.
/// - returns handler: A handler that will return a boolean with the consent status.
func setup(with viewController: UIViewController,
delegate: SwiftyAdDelegate?,
mediationManager: SwiftyAdMediationType?,
bannerAnimationDuration: TimeInterval? = nil,
testDevices: [String]? = nil,
handler: @escaping (_ hasConsent: Bool) -> Void) {
self.delegate = delegate
self.mediationManager = mediationManager
if let bannerAnimationDuration = bannerAnimationDuration {
self.bannerAnimationDuration = bannerAnimationDuration
}
// Configure
configuration = Configuration.propertyList
#if DEBUG
configuration = Configuration.debug
// If you want to do more rigorous testing with production-looking ads,
// you can now configure your device as a test device and use your own
// ad unit IDs that you've created in the AdMob UI.
GADMobileAds.sharedInstance().requestConfiguration.testDeviceIdentifiers = testDevices
#endif
// Create consent manager
consentManager = SwiftyAdConsentManager(ids: configuration.ids, configuration: configuration.gdpr)
// Make consent request
consentManager.ask(from: viewController, skipIfAlreadyAuthorized: true) { status in
self.handleConsentStatusChange(status)
switch status {
case .personalized, .nonPersonalized:
// Start SDK to improve latency
GADMobileAds.sharedInstance().start { status in
print("AdMob SDK has started with statuses \(status.adapterStatusesByClassName)")
self.loadInterstitialAd()
self.loadRewardedVideoAd()
handler(true)
}
case .adFree, .unknown:
handler(false)
}
}
}
// MARK: - Ask For Consent
/// Ask for consent. Use this for the consent button that should be e.g in settings.
///
/// - parameter viewController: The view controller that will present the consent form.
func askForConsent(from viewController: UIViewController) {
consentManager.ask(from: viewController, skipIfAlreadyAuthorized: false) { status in
self.handleConsentStatusChange(status)
}
}
// MARK: - Show Banner
/// Show banner ad
///
/// - parameter viewController: The view controller that will present the ad.
/// - parameter position: The position of the banner. Defaults to bottom.
func showBanner(from viewController: UIViewController) {
guard !isRemoved else { return }
checkThatWeCanShowAd(from: viewController) { canShowAd in
guard canShowAd else { return }
self.loadBannerAd(from: viewController)
}
}
// MARK: - Show Interstitial
/// Show interstitial ad
///
/// - parameter viewController: The view controller that will present the ad.
/// - parameter interval: The interval of when to show the ad, e.g every 4th time the method is called. Defaults to nil.
func showInterstitial(from viewController: UIViewController, withInterval interval: Int? = nil) {
guard !isRemoved else { return }
if let interval = interval {
intervalCounter += 1
guard intervalCounter >= interval else { return }
intervalCounter = 0
}
checkThatWeCanShowAd(from: viewController) { canShowAd in
guard canShowAd, self.isInterstitialReady else { return }
self.interstitialAd?.present(fromRootViewController: viewController)
}
}
// MARK: - Show Reward Video
/// Show rewarded video ad
///
/// - parameter viewController: The view controller that will present the ad.
func showRewardedVideo(from viewController: UIViewController) {
checkThatWeCanShowAd(from: viewController) { canShowAd in
guard canShowAd else { return }
if self.isRewardedVideoReady {
self.rewardedVideoAd?.present(fromRootViewController: viewController)
} else {
let alertController = UIAlertController(title: .sorry, message: .noVideo, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: .ok, style: .cancel))
viewController.present(alertController, animated: true)
}
}
}
// MARK: - Remove Banner
/// Remove banner ads
func removeBanner() {
bannerAdView?.delegate = nil
bannerAdView?.removeFromSuperview()
bannerAdView = nil
bannerViewConstraint = nil
}
}
// MARK: - GADBannerViewDelegate
extension SwiftyAd: GADBannerViewDelegate {
func adViewDidReceiveAd(_ bannerView: GADBannerView) {
print("AdMob banner did receive ad from: \(bannerView.responseInfo?.adNetworkClassName ?? "")")
animateBannerToOnScreenPosition(bannerView, from: bannerView.rootViewController)
}
func adViewWillPresentScreen(_ bannerView: GADBannerView) {
delegate?.swiftyAdDidOpen(self)
}
func adViewWillLeaveApplication(_ bannerView: GADBannerView) {
delegate?.swiftyAdDidOpen(self)
}
func adViewWillDismissScreen(_ bannerView: GADBannerView) {
}
func adViewDidDismissScreen(_ bannerView: GADBannerView) {
delegate?.swiftyAdDidClose(self)
}
func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError) {
print(error.localizedDescription)
animateBannerToOffScreenPosition(bannerView, from: bannerView.rootViewController)
}
}
// MARK: - GADInterstitialDelegate
extension SwiftyAd: GADInterstitialDelegate {
func interstitialDidReceiveAd(_ ad: GADInterstitial) {
print("AdMob interstitial did receive ad from: \(ad.responseInfo?.adNetworkClassName ?? "")")
}
func interstitialWillPresentScreen(_ ad: GADInterstitial) {
delegate?.swiftyAdDidOpen(self)
}
func interstitialWillLeaveApplication(_ ad: GADInterstitial) {
delegate?.swiftyAdDidOpen(self)
}
func interstitialWillDismissScreen(_ ad: GADInterstitial) {
}
func interstitialDidDismissScreen(_ ad: GADInterstitial) {
delegate?.swiftyAdDidClose(self)
loadInterstitialAd()
}
func interstitialDidFail(toPresentScreen ad: GADInterstitial) {
}
func interstitial(_ ad: GADInterstitial, didFailToReceiveAdWithError error: GADRequestError) {
print(error.localizedDescription)
// Do not reload here as it might cause endless loading loops if no/slow internet
}
}
// MARK: - GADRewardBasedVideoAdDelegate
extension SwiftyAd: GADRewardBasedVideoAdDelegate {
func rewardBasedVideoAdDidReceive(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
print("AdMob reward based video did receive ad from: \(rewardBasedVideoAd.adNetworkClassName ?? "")")
}
func rewardBasedVideoAdDidStartPlaying(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
delegate?.swiftyAdDidOpen(self)
}
func rewardBasedVideoAdDidOpen(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
}
func rewardBasedVideoAdWillLeaveApplication(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
delegate?.swiftyAdDidOpen(self)
}
func rewardBasedVideoAdDidClose(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
delegate?.swiftyAdDidClose(self)
loadRewardedVideoAd()
}
func rewardBasedVideoAdDidCompletePlaying(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
}
func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd, didFailToLoadWithError error: Error) {
print(error.localizedDescription)
// Do not reload here as it might cause endless loading loops if no/slow internet
}
func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd, didRewardUserWith reward: GADAdReward) {
print("AdMob reward based video ad did reward user with \(reward)")
let rewardAmount = Int(truncating: reward.amount)
delegate?.swiftyAd(self, didRewardUserWithAmount: rewardAmount)
}
}
// MARK: - Callbacks
private extension SwiftyAd {
@objc func deviceRotated() {
bannerAdView?.adSize = UIDevice.current.orientation.isLandscape ? kGADAdSizeSmartBannerLandscape : kGADAdSizeSmartBannerPortrait
}
}
// MARK: - Load Ads
private extension SwiftyAd {
func loadBannerAd(from viewController: UIViewController) {
guard !isRemoved, hasConsent else { return }
// Remove old banners
removeBanner()
// Create ad
bannerAdView = GADBannerView()
deviceRotated() // to set banner size
guard let bannerAdView = bannerAdView else { return }
bannerAdView.adUnitID = configuration.bannerAdUnitId
bannerAdView.delegate = self
bannerAdView.rootViewController = viewController
viewController.view.addSubview(bannerAdView)
// Add constraints
let layoutGuide: UILayoutGuide
if #available(iOS 11, *) {
layoutGuide = viewController.view.safeAreaLayoutGuide
} else {
layoutGuide = viewController.view.layoutMarginsGuide
}
bannerAdView.translatesAutoresizingMaskIntoConstraints = false
bannerAdView.leftAnchor.constraint(equalTo: layoutGuide.leftAnchor).isActive = true
bannerAdView.rightAnchor.constraint(equalTo: layoutGuide.rightAnchor).isActive = true
bannerViewConstraint = bannerAdView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor)
bannerViewConstraint?.isActive = true
// Move off screen
animateBannerToOffScreenPosition(bannerAdView, from: viewController, withAnimation: false)
// Request ad
let request = makeRequest()
bannerAdView.load(request)
}
func loadInterstitialAd() {
guard !isRemoved, hasConsent else { return }
interstitialAd = GADInterstitial(adUnitID: configuration.interstitialAdUnitId)
interstitialAd?.delegate = self
let request = makeRequest()
interstitialAd?.load(request)
}
func loadRewardedVideoAd() {
guard hasConsent else { return }
rewardedVideoAd = GADRewardBasedVideoAd.sharedInstance()
rewardedVideoAd?.delegate = self
let request = makeRequest()
rewardedVideoAd?.load(request, withAdUnitID: configuration.rewardedVideoAdUnitId)
}
}
// MARK: - Check That We Can Show Ad
private extension SwiftyAd {
func checkThatWeCanShowAd(from viewController: UIViewController, handler: @escaping (Bool) -> Void) {
guard !hasConsent else {
handler(true)
return
}
consentManager.ask(from: viewController, skipIfAlreadyAuthorized: false) { status in
defer {
self.handleConsentStatusChange(status)
}
switch status {
case .personalized, .nonPersonalized:
handler(true)
case .adFree, .unknown:
handler(false)
}
}
}
}
// MARK: - Banner Position
private extension SwiftyAd {
func animateBannerToOnScreenPosition(_ bannerAd: GADBannerView, from viewController: UIViewController?) {
bannerAd.isHidden = false
bannerViewConstraint?.constant = 0
UIView.animate(withDuration: bannerAnimationDuration) {
viewController?.view.layoutIfNeeded()
}
}
func animateBannerToOffScreenPosition(_ bannerAd: GADBannerView, from viewController: UIViewController?, withAnimation: Bool = true) {
bannerViewConstraint?.constant = 0 + (bannerAd.frame.height * 3) // *3 due to iPhoneX safe area
guard withAnimation else {
bannerAd.isHidden = true
return
}
UIView.animate(withDuration: bannerAnimationDuration, animations: {
viewController?.view.layoutIfNeeded()
}, completion: { isSuccess in
bannerAd.isHidden = true
})
}
}
// MARK: - Make Ad Request
private extension SwiftyAd {
func makeRequest() -> GADRequest {
let request = GADRequest()
// Add extras if in EU (GDPR)
if consentManager.isInEEA {
// Create additional parameters with under age of consent
var additionalParameters: [String: Any] = ["tag_for_under_age_of_consent": consentManager.isTaggedForUnderAgeOfConsent]
// Add non personalized paramater to additional parameters if needed
if consentManager.status == .nonPersonalized {
additionalParameters["npa"] = "1" // only allow non-personalized ads
}
// Create extras
let extras = GADExtras()
extras.additionalParameters = additionalParameters
request.register(extras)
}
// Return the request
return request
}
}
// MARK: - Consent Status Change
private extension SwiftyAd {
func handleConsentStatusChange(_ status: SwiftyAd.ConsentStatus) {
delegate?.swiftyAd(self, didChange: status)
mediationManager?.update(for: status)
}
}
/// Overrides the default print method so it print statements only show when in DEBUG mode
private func print(_ items: Any...) {
#if DEBUG
Swift.print(items)
#endif
}
| mit | 2adce76d12c1dc79688d4c40b97ac915 | 34.621212 | 164 | 0.649794 | 5.258201 | false | false | false | false |
magnetsystems/message-samples-ios | QuickStart/QuickStart/FindChannelsViewController.swift | 1 | 4807 | /*
* Copyright (c) 2015 Magnet Systems, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import UIKit
import MagnetMax
class FindChannelsViewController: UIViewController, UITableViewDataSource {
// MARK: Outlets
@IBOutlet weak var segCtrlSearchType: UISegmentedControl!
@IBOutlet weak var tvChannels: UITableView!
@IBOutlet weak var txtfSearchParameter: UITextField!
// MARK: Public properties
var channels : [MMXChannel] = [] {
didSet {
if tvChannels.editing == false {
tvChannels.reloadData()
}
}
}
// MARK: Actions
@IBAction func searchAction() {
if let parameter = txtfSearchParameter.text where (parameter.isEmpty == false) {
let limit: Int32 = 10
let offset: Int32 = 0
switch segCtrlSearchType.selectedSegmentIndex {
case 0:
MMXChannel.channelForName(parameter, isPublic: true, success: { [weak self] (channel) in
self?.channels = [channel]
}, failure: { error in
print("[ERROR]: \(error)")
})
case 1:
MMXChannel.channelsStartingWith(parameter, limit: limit, offset: offset, success: { [weak self] (count, channels) in
self?.channels = channels
}, failure: { error in
print("[ERROR]: \(error)")
})
case 2:
let tagsArray = parameter.componentsSeparatedByString(" ")
let tagsSet = Set<String> (tagsArray)
MMXChannel.findByTags(tagsSet, limit: limit, offset: offset, success: { [weak self] (count, channels) in
self?.channels = channels
}, failure: { error in
print("[ERROR]: \(error)")
})
default: break
}
}
}
//MARK: TableView data source
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return channels.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ChannelCellIdentifier", forIndexPath: indexPath)
let channel = channels[indexPath.row]
cell.textLabel?.text = channel.name
return cell
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
let channel = channels[indexPath.row]
// only allow the owner to delete a channel
return channel.ownerUserID == MMUser.currentUser()?.userID
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// delete channel
let channel = channels[indexPath.row]
channel.deleteWithSuccess({ [weak self] in
print("Channel is deleted success")
self?.channels.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}, failure: { error in
print("[ERROR]: \(error)")
})
}
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let tabVC = segue.destinationViewController as? UITabBarController {
let controllers = tabVC.viewControllers
let cell = sender as! UITableViewCell
if let indexPath = tvChannels.indexPathForCell(cell) {
let channel = channels[indexPath.row]
// set selected channel
if let messagesVC = controllers?.first as? MessagesViewController {
messagesVC.myChatChannel = channel
}
if let subscribersVC = controllers?.last as? SubscribersViewController {
subscribersVC.channel = channel
}
}
}
}
}
| apache-2.0 | f20144c674329c10b715e2bfb46ca74c | 33.833333 | 148 | 0.590389 | 5.525287 | false | false | false | false |
siricenter/SwiftlyHybrid | SwiftlyHybridOSXExample/SwiftlyHybridOSXExample/SwiftlyMessageHandler.swift | 1 | 3378 | /*
The MIT License (MIT)
Copyright (c) 2015 Lee Barney
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 WebKit
class SwiftlyMessageHandler:NSObject, WKScriptMessageHandler {
var appWebView:WKWebView?
init(theController:ViewController){
super.init()
let theConfiguration = WKWebViewConfiguration()
theConfiguration.userContentController.addScriptMessageHandler(self, name: "native")
let indexHTMLPath = NSBundle.mainBundle().pathForResource("index", ofType: "html")
appWebView = WKWebView(frame: theController.view.frame, configuration: theConfiguration)
let url = NSURL(fileURLWithPath: indexHTMLPath!)
let request = NSURLRequest(URL: url)
appWebView!.loadRequest(request)
theController.view.addSubview(appWebView!)
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
let sentData = message.body as! NSDictionary
let command = sentData["cmd"] as! String
var response = Dictionary<String,AnyObject>()
if command == "increment"{
guard var count = sentData["count"] as? Int else{
return
}
count++
response["count"] = count
}
let callbackString = sentData["callbackFunc"] as? String
sendResponse(response, callback: callbackString)
}
func sendResponse(aResponse:Dictionary<String,AnyObject>, callback:String?){
guard let callbackString = callback else{
return
}
guard let generatedJSONData = try? NSJSONSerialization.dataWithJSONObject(aResponse, options: NSJSONWritingOptions(rawValue: 0)) else{
print("failed to generate JSON for \(aResponse)")
return
}
appWebView!.evaluateJavaScript("(\(callbackString)('\(NSString(data:generatedJSONData, encoding:NSUTF8StringEncoding)!)'))"){(JSReturnValue:AnyObject?, error:NSError?) in
if let errorDescription = error?.description{
print("returned value: \(errorDescription)")
}
else if JSReturnValue != nil{
print("returned value: \(JSReturnValue!)")
}
else{
print("no return from JS")
}
}
}
}
| mit | 209e38b427ae130955d7c6f2fd4be91c | 40.195122 | 178 | 0.687981 | 5.173047 | false | true | false | false |
eflyjason/word-counter-tools | CounterActionExtension/ProgressHUD.swift | 1 | 1771 | //
// ProgressHUD.swift
// WordCounter
//
// Created by Jason Ho on 22/12/2015.
// Copyright © 2015 Arefly. All rights reserved.
//
import UIKit
import Foundation
class LoadingUIView {
// We have to use our own view as it is is difficult to use Cocoapods in Extension :(
class func getProgressBar(_ view: UIView, msg: String, indicator: Bool ) -> UIView {
print("[提示] 準備創建標籤爲 \(msg) 的載入中提示")
var messageFrame = UIView()
var activityIndicator = UIActivityIndicatorView()
var strLabel = UILabel()
let msgNSString: NSString = msg as NSString
let msgSize: CGSize = msgNSString.size(withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17.0)])
let strLabelWidth: CGFloat = msgSize.width
strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: strLabelWidth, height: 50))
strLabel.text = msg
strLabel.textColor = UIColor.white
let messageFrameWidth: CGFloat = strLabelWidth + 70.0
let messageFrameHeight: CGFloat = 50.0
messageFrame = UIView(frame: CGRect(x: view.frame.midX - messageFrameWidth/2, y: view.frame.midY - messageFrameHeight/2 , width: messageFrameWidth, height: messageFrameHeight))
messageFrame.layer.cornerRadius = 15
messageFrame.backgroundColor = UIColor(white: 0, alpha: 0.7)
if indicator {
activityIndicator = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.white)
activityIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
activityIndicator.startAnimating()
messageFrame.addSubview(activityIndicator)
}
messageFrame.addSubview(strLabel)
return messageFrame
}
}
| gpl-3.0 | f8eea224144ece10cb423a58869d02ef | 36.021277 | 184 | 0.675287 | 4.233577 | false | false | false | false |
practicalswift/swift | test/IRGen/protocol_resilience_thunks.swift | 6 | 8801 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience %s | %FileCheck %s
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -O %s
// CHECK: %swift.type = type { [[INT:i32|i64]] }
import resilient_protocol
// Method descriptors
// CHECK-LABEL: @"$s26protocol_resilience_thunks19MyResilientProtocolP11returnsVoid1xySb_tFTq" ={{( dllexport)?}}{{( protected)?}} alias %swift.protocol_requirement, getelementptr inbounds (<{{.*}}>* @"$s26protocol_resilience_thunks19MyResilientProtocolMp", i32 0, i32 6)
// CHECK-LABEL: @"$s26protocol_resilience_thunks19MyResilientProtocolP11returnsBoolSbyFTq" ={{( dllexport)?}}{{( protected)?}} alias %swift.protocol_requirement, getelementptr inbounds (<{{.*}}>* @"$s26protocol_resilience_thunks19MyResilientProtocolMp", i32 0, i32 7)
// CHECK-LABEL: @"$s26protocol_resilience_thunks19MyResilientProtocolP10returnsAnyypyFTq" ={{( dllexport)?}}{{( protected)?}} alias %swift.protocol_requirement, getelementptr inbounds (<{{.*}}>* @"$s26protocol_resilience_thunks19MyResilientProtocolMp", i32 0, i32 8)
// CHECK-LABEL: @"$s26protocol_resilience_thunks19MyResilientProtocolP12throwingFuncyyKFTq" ={{( dllexport)?}}{{( protected)?}} alias %swift.protocol_requirement, getelementptr inbounds (<{{.*}}>* @"$s26protocol_resilience_thunks19MyResilientProtocolMp", i32 0, i32 9)
// CHECK-LABEL: @"$s26protocol_resilience_thunks19MyResilientProtocolP11genericFuncyqd__qd__lFTq" ={{( dllexport)?}}{{( protected)?}} alias %swift.protocol_requirement, getelementptr inbounds (<{{.*}}>* @"$s26protocol_resilience_thunks19MyResilientProtocolMp", i32 0, i32 10)
// CHECK-LABEL: @"$s26protocol_resilience_thunks19MyResilientProtocolP8propertySbvgTq" ={{( dllexport)?}}{{( protected)?}} alias %swift.protocol_requirement, getelementptr inbounds (<{{.*}}>* @"$s26protocol_resilience_thunks19MyResilientProtocolMp", i32 0, i32 11)
// CHECK-LABEL: @"$s26protocol_resilience_thunks19MyResilientProtocolP8propertySbvsTq" ={{( dllexport)?}}{{( protected)?}} alias %swift.protocol_requirement, getelementptr inbounds (<{{.*}}>* @"$s26protocol_resilience_thunks19MyResilientProtocolMp", i32 0, i32 12)
// CHECK-LABEL: @"$s26protocol_resilience_thunks19MyResilientProtocolP8propertySbvMTq" ={{( dllexport)?}}{{( protected)?}} alias %swift.protocol_requirement, getelementptr inbounds (<{{.*}}>* @"$s26protocol_resilience_thunks19MyResilientProtocolMp", i32 0, i32 13)
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s26protocol_resilience_thunks26callResilientWitnessMethodyyx010resilient_A00E12BaseProtocolRzlF"(%swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.ResilientBaseProtocol)
// CHECK: call swiftcc [[INT]] @"$s18resilient_protocol21ResilientBaseProtocolP11requirementSiyFTj"(%swift.opaque* noalias nocapture swiftself %0, %swift.type* %T, i8** %T.ResilientBaseProtocol)
// CHECK: ret void
public func callResilientWitnessMethod<T : ResilientBaseProtocol>(_ value: T) {
_ = value.requirement()
}
public protocol MyResilientProtocol {
func returnsVoid(x: Bool)
func returnsBool() -> Bool
func returnsAny() -> Any
func throwingFunc() throws
func genericFunc<T>(_: T) -> T
var property: Bool { get set }
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s26protocol_resilience_thunks19MyResilientProtocolP11returnsVoid1xySb_tFTj"(i1, %swift.opaque* noalias nocapture swiftself, %swift.type*, i8**)
// CHECK: [[WITNESS_GEP:%.*]] = getelementptr inbounds i8*, i8** %3, i32 1
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_GEP]]
// CHECK-NEXT: [[FN:%.*]] = bitcast i8* [[WITNESS]] to void (i1, %swift.opaque*, %swift.type*, i8**)*
// CHECK-NEXT: call swiftcc void [[FN]](i1 %0, %swift.opaque* noalias nocapture swiftself %1, %swift.type* %2, i8** %3)
// CHECK-NEXT: ret void
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i1 @"$s26protocol_resilience_thunks19MyResilientProtocolP11returnsBoolSbyFTj"(%swift.opaque* noalias nocapture swiftself, %swift.type*, i8**)
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** %2, i32 2
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[FN:%.*]] = bitcast i8* [[WITNESS]] to i1 (%swift.opaque*, %swift.type*, i8**)*
// CHECK-NEXT: [[RESULT:%.*]] = call swiftcc i1 [[FN]](%swift.opaque* noalias nocapture swiftself %0, %swift.type* %1, i8** %2)
// CHECK-NEXT: ret i1 [[RESULT]]
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s26protocol_resilience_thunks19MyResilientProtocolP10returnsAnyypyFTj"(%Any* noalias nocapture sret, %swift.opaque* noalias nocapture swiftself, %swift.type*, i8**)
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** %3, i32 3
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[FN:%.*]] = bitcast i8* [[WITNESS]] to void (%Any*, %swift.opaque*, %swift.type*, i8**)*
// CHECK-NEXT: call swiftcc void [[FN]](%Any* noalias nocapture sret %0, %swift.opaque* noalias nocapture swiftself %1, %swift.type* %2, i8** %3)
// CHECK-NEXT: ret void
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s26protocol_resilience_thunks19MyResilientProtocolP12throwingFuncyyKFTj"(%swift.opaque* noalias nocapture swiftself, %swift.error**{{( noalias nocapture( swifterror)? dereferenceable\(.\))?}}, %swift.type*, i8**)
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** %3, i32 4
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[FN:%.*]] = bitcast i8* [[WITNESS]] to void (%swift.opaque*, %swift.error**, %swift.type*, i8**)*
// CHECK-NEXT: call swiftcc void [[FN]](%swift.opaque* noalias nocapture swiftself %0, %swift.error**{{( noalias nocapture( swifterror)? dereferenceable\(.\))?}} %1, %swift.type* %2, i8** %3)
// CHECK-NEXT: ret void
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s26protocol_resilience_thunks19MyResilientProtocolP11genericFuncyqd__qd__lFTj"(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.type*, %swift.opaque* noalias nocapture swiftself, %swift.type*, i8**)
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** %5, i32 5
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[FN:%.*]] = bitcast i8* [[WITNESS]] to void (%swift.opaque*, %swift.opaque*, %swift.type*, %swift.opaque*, %swift.type*, i8**)*
// CHECK-NEXT: call swiftcc void [[FN]](%swift.opaque* noalias nocapture sret %0, %swift.opaque* noalias nocapture %1, %swift.type* %2, %swift.opaque* noalias nocapture swiftself %3, %swift.type* %4, i8** %5)
// CHECK-NEXT: ret void
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i1 @"$s26protocol_resilience_thunks19MyResilientProtocolP8propertySbvgTj"(%swift.opaque* noalias nocapture swiftself, %swift.type*, i8**)
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** %2, i32 6
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[FN:%.*]] = bitcast i8* [[WITNESS]] to i1 (%swift.opaque*, %swift.type*, i8**)*
// CHECK-NEXT: [[RESULT:%.*]] = call swiftcc i1 %5(%swift.opaque* noalias nocapture swiftself %0, %swift.type* %1, i8** %2)
// CHECK-NEXT: ret i1 [[RESULT]]
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s26protocol_resilience_thunks19MyResilientProtocolP8propertySbvsTj"(i1, %swift.opaque* nocapture swiftself, %swift.type*, i8**)
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** %3, i32 7
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[FN:%.*]] = bitcast i8* [[WITNESS]] to void (i1, %swift.opaque*, %swift.type*, i8**)*
// CHECK-NEXT: call swiftcc void [[FN]](i1 %0, %swift.opaque* nocapture swiftself %1, %swift.type* %2, i8** %3)
// CHECK-NEXT: ret void
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc { i8*, %TSb* } @"$s26protocol_resilience_thunks19MyResilientProtocolP8propertySbvMTj"(i8* noalias dereferenceable({{16|32}}), %swift.opaque* nocapture swiftself, %swift.type*, i8**)
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** %3, i32 8
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[FN:%.*]] = bitcast i8* [[WITNESS]] to { i8*, %TSb* } (i8*, %swift.opaque*, %swift.type*, i8**)*
// CHECK-NEXT: [[RESULT:%.*]] = call swiftcc { i8*, %TSb* } [[FN]](i8* noalias dereferenceable({{16|32}}) %0, %swift.opaque* nocapture swiftself %1, %swift.type* %2, i8** %3)
// CHECK-NEXT: ret { i8*, %TSb* } [[RESULT]]
| apache-2.0 | 83a1d2405b22eae68f9d2406077cc3d6 | 91.642105 | 302 | 0.687536 | 3.645816 | false | false | false | false |
DJBCompany/DHNote | NoteBook/NoteBook/HZNoteCell.swift | 1 | 1722 | //
// HZNoteCell.swift
// NoteBook
//
// Created by chris on 16/4/29.
// Copyright © 2016年 chris. All rights reserved.
//
import UIKit
class HZNoteCell: UITableViewCell {
var dic:[String:NSObject]?{
didSet{
contentLb.text = dic!["content"] as? String
timeLb.text = dic!["time"] as? String
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setUpUI()
backgroundColor = UIColor(red: CGFloat(random()%256) / 255.0, green: CGFloat(random()%256) / 255.0, blue: CGFloat(random()%256) / 255.0, alpha: 1.0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setUpUI(){
contentView.addSubview(contentLb)
contentView.addSubview(timeLb)
///添加约束
contentLb.snp_makeConstraints { (make) -> Void in
make.top.equalTo(contentView.snp_top).offset(10)
make.left.equalTo(contentView.snp_left).offset(10)
make.width.equalTo(280)
make.bottom.equalTo(contentView.snp_bottom)
}
timeLb.snp_makeConstraints { (make) -> Void in
make.right.equalTo(contentView.snp_right)
make.bottom.equalTo(contentLb.snp_bottom)
}
}
lazy var contentLb:UILabel = {
let lb = UILabel()
lb.numberOfLines = 0
return lb
}()
lazy var timeLb:UILabel = {
let lb = UILabel()
lb.font = UIFont.systemFontOfSize(12)
return lb
}()
}
| mit | 576d704bcad37191146010aa0216ab6c | 24.537313 | 156 | 0.565751 | 4.235149 | false | false | false | false |
darkerk/v2ex | V2EX/ViewModel/TopicDetailsViewModel.swift | 1 | 6482 | //
// TopicDetailsViewModel.swift
// V2EX
//
// Created by darker on 2017/3/8.
// Copyright © 2017年 darker. All rights reserved.
//
import RxSwift
import Moya
import Kanna
class TopicDetailsViewModel {
let content = Variable<String>("")
let countTime = Variable<String>("")
let sections = Variable<[TopicDetailsSection]>([])
let updateTopic = Variable<Topic?>(nil)
let loadingActivityIndicator = ActivityIndicator()
let loadMoreActivityIndicator = ActivityIndicator()
var currentPage = 1
private let disposeBag = DisposeBag()
var topic: Topic
var htmlContent: String?
init(topic: Topic) {
self.topic = topic
fetchDetails(href: topic.href)
}
func insertNew(text: String, atName: String?) {
var atString = ""
var string = text
if let atName = atName {
string = text.replacingOccurrences(of: "@\(atName) ", with: "")
atString = "@<a href=\"/member/\(atName)\">\(atName)</a> "
}
let content = "<div class=\"reply_content\">\(atString)\(string)</div>"
let number = currentPage > 1 ? sections.value[1].comments.count : sections.value[0].comments.count
let comment = Comment(id: "", content: content, time: "刚刚", thanks: "0", number: "\(number + 1)", user: Account.shared.user.value)
if currentPage > 1 {
sections.value[1].comments.append(comment)
}else {
sections.value[0].comments.append(comment)
}
}
func fetchDetails(href: String) {
API.provider.request(.pageList(href: href, page: 0))
.observeOn(MainScheduler.instance)
.trackActivity(loadingActivityIndicator)
.subscribe(onNext: { response in
if let data = HTMLParser.shared.topicDetails(html: response.data) {
self.topic.token = data.topic.token
self.topic.isThank = data.topic.isThank
self.topic.isFavorite = data.topic.isFavorite
if let owner = data.topic.owner {
self.topic.owner = owner
}
if let node = data.topic.node {
self.topic.node = node
}
if !data.topic.title.isEmpty {
self.topic.title = data.topic.title
}
var updateTopicInfo = self.topic
updateTopicInfo.creatTime = data.topic.creatTime
self.updateTopic.value = updateTopicInfo
self.content.value = data.topic.content
self.countTime.value = data.countTime
self.currentPage = data.currentPage
if data.currentPage > 1 {
self.sections.value = [TopicDetailsSection(type: .more, comments: [Comment()]), TopicDetailsSection(type: .data, comments: data.comments)]
}else {
self.sections.value = [TopicDetailsSection(type: .data, comments: data.comments)]
}
self.htmlContent = HTMLParser.shared.htmlContent(html: data.topic.content)
}
}, onError: {error in
print(error)
}).disposed(by: disposeBag)
}
func fetchMoreComments() {
guard currentPage > 1 else {
return
}
let page = currentPage - 1
API.provider.request(.pageList(href: topic.href, page: page))
.observeOn(MainScheduler.instance)
.trackActivity(loadMoreActivityIndicator)
.subscribe(onNext: { response in
if let data = HTMLParser.shared.topicDetails(html: response.data) {
self.sections.value[1].comments.insert(contentsOf: data.comments, at: 0)
if data.currentPage < 2 && self.sections.value.count == 2 {
self.sections.value.remove(at: 0)
}
self.currentPage = data.currentPage
}
}, onError: { error in
print(error)
}).disposed(by: disposeBag)
}
func sendComment(content: String, atName: String? = nil, completion: ((Swift.Error?) -> Void)? = nil) {
API.provider.request(.once).flatMap { response -> Observable<Response> in
if let once = HTMLParser.shared.once(html: response.data) {
return API.provider.request(API.comment(topicHref: self.topic.href, content: content, once: once))
}else {
return Observable.error(NetError.message(text: "获取once失败"))
}
}.share(replay: 1).subscribe(onNext: { response in
self.insertNew(text: content, atName: atName)
completion?(nil)
}, onError: {error in
completion?(error)
}).disposed(by: disposeBag)
}
func sendThank(type: ThankType, completion: ((Bool) -> Void)? = nil) {
topic.isThank = true
API.provider.request(.thank(type: type, token: topic.token)).subscribe(onNext: {response in
self.topic.isThank = true
completion?(true)
}, onError: {error in
completion?(false)
}).disposed(by: disposeBag)
}
func sendIgnore(completion: ((Bool) -> Void)? = nil) {
API.provider.request(.once).flatMap { response -> Observable<Response> in
if let once = HTMLParser.shared.once(html: response.data) {
return API.provider.request(API.ignoreTopic(id: self.topic.id, once: once))
}else {
return Observable.error(NetError.message(text: "获取once失败"))
}
}.share(replay: 1).subscribe(onNext: { response in
completion?(true)
}, onError: {error in
completion?(false)
}).disposed(by: disposeBag)
}
func sendFavorite(completion: ((Bool) -> Void)? = nil) {
let isCancel = topic.isFavorite
API.provider.request(.favorite(type: .topic(id: topic.id, token: topic.token), isCancel: isCancel)).subscribe(onNext: {response in
self.topic.isFavorite = !isCancel
completion?(true)
}, onError: {error in
completion?(false)
}).disposed(by: disposeBag)
}
}
| mit | 439a5eae93d4adccb0788127e9060428 | 38.384146 | 158 | 0.554575 | 4.590618 | false | false | false | false |
tectijuana/patrones | Bloque1SwiftArchivado/PracticasSwift/SandovalChristopher/programa2.swift | 1 | 742 | /*NOMBRE: Sandoval Lizarraga Christopher francisco
Imprimir un número real N, su inverso aditivo y su multiplicativo inveros (si lo tiene)*/
import Foundation
/* Declaración de variables */
var numero = 1.0
print("\tNumero\t|\tAditivo inverso\t|\tMultiplicativo inverso\t")
print("------------------------------------------------------------------------")
/* Ciclo while que realiza la tabla */
while numero <= 10
{
/* Calcular el inverso aditivo */
var InvAdi = numero
/* Calcular el multiplicativo inverso */
var InvMul = 1 / numero
/* Imprime los resultados */
print("\t\(numero)\t|\t-\(InvAdi)\t\t|\t" + (String(format:"%.5f",InvMul)) + "\t")
/* Suma al valor de número una unidad */
numero = numero + 1
} | gpl-3.0 | 4484aafa81d8878f36696eb8613b6391 | 20.228571 | 90 | 0.606469 | 3.212121 | false | false | false | false |
robertwtucker/kfinder-ios | KFinder/FoodItem.swift | 1 | 1309 | /**
* Copyright 2017 Robert Tucker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import RealmSwift
class FoodItem: Object {
//MARK: Properties
dynamic var id: Int = 0
dynamic var name: String = ""
dynamic var weight: Double = 0.0
dynamic var measure: String = ""
dynamic var k: Double = 0.0
//MARK: Initialization
convenience init(id: Int, name: String, weight: Double, measure: String, k: Double) {
self.init()
self.id = id
self.name = name
self.weight = weight
self.measure = measure
self.k = k
}
//MARK: - Class Functions
override class func primaryKey() -> String? {
return "id"
}
override static func indexedProperties() -> [String] {
return ["name"]
}
}
| apache-2.0 | 2825603bd636e387b8a5ee22cd3b918d | 24.173077 | 89 | 0.649351 | 4.155556 | false | false | false | false |
bharath2020/Tic-Tac-Toe-Swift | Tic-Tac-Toe-Swift/Tic-Tac-Toe-Swift/Model/TTBoard.swift | 1 | 3533 | //
// TTBoard.swift
// Tic-Tac-Toe-Swift
//
// Created by Bharath Booshan on 9/12/15.
// Copyright (c) 2015 FeatherTouch. All rights reserved.
//
import Foundation
import UIKit
enum BoardState {
case Win
case Complete
case InComplete
}
let NOT_OCCUPIED = -1
let win:[Int] = [0,1,2,3,4,5,6,7,8,0,3,6,1,4,7,2,5,8,0,4,8,2,4,6];
final class TTBoard {
private var board : [Int] = []
private var totalPiecesOnBoard = 0
private var emptySpots : [Int] = []
let boardID : String
init(boardIDString : String) {
self.boardID = boardIDString
for pos in 0...8 {
board.append( NOT_OCCUPIED )
emptySpots.append(pos)
}
}
func getBoardID() -> String {
return self.boardID
}
final func markPosition(position : Int , playerCode : Int ) -> BoardState {
assert(position < 9, "Position greater than 9 while marking position")
if board[position] != NOT_OCCUPIED {
return .InComplete
}
board[position] = playerCode
removePositionFromEmptySlot(position)
totalPiecesOnBoard++
let boardState:Int = winner()
if boardState != 0 {
return .Win
}
else if isBoardComplete() {
return .Complete
}
else{
return .InComplete
}
}
func getEmptySpotList() -> [Int] {
return Array<Int>(emptySpots)
}
func removePositionFromEmptySlot(position : Int ){
//remove from empty slots
if let index = emptySpots.indexOf(position) {
emptySpots.removeAtIndex(index)
}
}
func addPositionToEmptySlot(position : Int ){
emptySpots.append(position)
}
func resetPosition( position : Int ){
assert(position<9, "Position greater than 9 while resetting")
board[position] = NOT_OCCUPIED
addPositionToEmptySlot(position)
totalPiecesOnBoard--
}
func winner( ) -> Int {
// 0 1 2
// 3 4 5
// 6 7 8
for index in 0...7 {
let baseIndex = index * 3
let valAt0 = board[win[baseIndex]]
if( valAt0 != NOT_OCCUPIED &&
valAt0 == board[win[baseIndex+1]] &&
valAt0 == board[win[baseIndex+2]]){
return valAt0;
}
}
return 0;
}
func isBoardEmpty() -> Bool {
return totalPiecesOnBoard == 0;
}
func isBoardComplete() -> Bool {
return totalPiecesOnBoard == 9
}
func isEqualToBoard( otherBoard : TTBoard ) -> Bool {
return boardID == otherBoard.boardID
}
func resetBoard() -> Void {
for _ in 0...8 {
board.append(NOT_OCCUPIED)
}
totalPiecesOnBoard=0
}
func copyBoardFrom(otherBoard: [Int], emptySpotsCopy : [Int] ) -> Void{
let boardCount = otherBoard.count
board.removeAll(keepCapacity: true)
for position in 0...boardCount-1 {
board.append(otherBoard[position])
}
emptySpots.removeAll(keepCapacity: true)
for val in emptySpotsCopy{
emptySpots.append(val)
}
}
func copy() -> TTBoard {
let copy = TTBoard(boardIDString: self.boardID)
copy.copyBoardFrom(board,emptySpotsCopy: emptySpots)
copy.totalPiecesOnBoard = self.totalPiecesOnBoard
return copy
}
}
| mit | de8e01f717ddab549e5a1a31cce54c0a | 24.235714 | 80 | 0.552505 | 3.965208 | false | false | false | false |
typelift/Focus | Sources/Focus/Prism.swift | 1 | 3698 | //
// Prism.swift
// Focus
//
// Created by Alexander Ronald Altman on 7/22/14.
// Copyright (c) 2015-2016 TypeLift. All rights reserved.
//
#if SWIFT_PACKAGE
import Operadics
#endif
/// A `Prism` describes a way of focusing on potentially more than one target
/// structure. Like an `Iso` a `Prism` is invertible, but unlike an `Iso`
/// multi-focus `Prism`s are incompatible with inversion in general. Because of
/// this a `Prism` can branch depending on whether it hits its target, much
/// like pattern-matching in a `switch` statement.
///
/// An famous example of a `Prism` is
///
/// Prism<Optional<T>, Optional<T>, T, T>
///
/// provided by the `_Some` `Prism` in this library.
///
/// In practice, a `Prism` is used with Sum structures like enums. If a less
/// powerful form of `Prism` is needed, where `S == T` and `A == B`, consider
/// using a `SimplePrism` instead.
public typealias SimplePrism<S, A> = Prism<S, S, A, A>
///
/// A Prism can thought of as an `Iso` characterized by two functions (where one
/// of the functions is partial):
///
/// - `tryGet` to possibly retrieve a focused part of the structure.
/// - `inject` to perform a "reverse get" back to a modified form of the
/// original structure.
///
/// - parameter S: The source of the Prism
/// - parameter T: The modified source of the Prism
/// - parameter A: The possible target of the Prism
/// - parameter B: The modified target the Prism
public struct Prism<S, T, A, B> : PrismType {
public typealias Source = S
public typealias Target = A
public typealias AltSource = T
public typealias AltTarget = B
private let _tryGet : (S) -> A?
private let _inject : (B) -> T
public init(tryGet f : @escaping (S) -> A?, inject g : @escaping (B) -> T) {
_tryGet = f
_inject = g
}
/// Attempts to focus the prism on the given source.
public func tryGet(_ v : Source) -> Target? {
return _tryGet(v)
}
/// Injects a value back into a modified form of the original structure.
public func inject(_ x : AltTarget) -> AltSource {
return _inject(x)
}
}
public protocol PrismType : OpticFamilyType {
func tryGet(_ : Source) -> Target?
func inject(_ : AltTarget) -> AltSource
}
extension Prism {
public init<Other : PrismType>(_ other : Other) where
S == Other.Source, A == Other.Target, T == Other.AltSource, B == Other.AltTarget
{
self.init(tryGet: other.tryGet, inject: other.inject)
}
}
/// Provides a Prism for tweaking values inside `.Some`.
public func _Some<A, B>() -> Prism<A?, B?, A, B> {
return Prism(tryGet: identity, inject: Optional<B>.some)
}
/// Provides a Prism for traversing `.None`.
public func _None<A>() -> Prism<A?, A?, (), ()> {
return Prism(tryGet: { _ in .none }, inject: { _ in .none })
}
extension PrismType {
/// Composes a `Prism` with the receiver.
public func compose<Other : PrismType>
(_ other : Other) -> Prism<Source, AltSource, Other.Target, Other.AltTarget> where
Self.Target == Other.Source,
Self.AltTarget == Other.AltSource {
return Prism(tryGet: { self.tryGet($0).flatMap(other.tryGet) }, inject: self.inject • other.inject)
}
/// Attempts to run a value of type `S` along both parts of the Prism. If
/// `.None` is encountered along the getter returns `.None`, else returns
/// `.Some` containing the final value.
public func tryModify(_ s : Source, _ f : @escaping (Target) -> AltTarget) -> AltSource? {
return tryGet(s).map(self.inject • f)
}
}
public func • <Left, Right>(l : Left, r : Right) -> Prism<Left.Source, Left.AltSource, Right.Target, Right.AltTarget>
where Left : PrismType, Right : PrismType, Left.Target == Right.Source, Left.AltTarget == Right.AltSource
{
return l.compose(r)
}
| mit | b236248e2fd3f04758c63d347e1ff33d | 32.563636 | 117 | 0.669556 | 3.056291 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.