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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
iadmir/Signal-iOS | Signal/src/UserInterface/SlideOffAnimatedTransition.swift | 2 | 1753 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import UIKit
@objc
class SlideOffAnimatedTransition: NSObject, UIViewControllerAnimatedTransitioning {
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
guard let fromView = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)?.view else {
owsFail("No fromView")
return
}
guard let toView = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)?.view else {
owsFail("No toView")
return
}
let width = containerView.frame.width
let offsetLeft = fromView.frame.offsetBy(dx: -width, dy: 0)
toView.frame = fromView.frame
fromView.layer.shadowRadius = 15.0
fromView.layer.shadowOpacity = 1.0
toView.layer.opacity = 0.9
containerView.insertSubview(toView, belowSubview: fromView)
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay:0, options: .curveLinear, animations: {
fromView.frame = offsetLeft
toView.layer.opacity = 1.0
fromView.layer.shadowOpacity = 0.1
}, completion: { _ in
toView.layer.opacity = 1.0
toView.layer.shadowOpacity = 0
fromView.layer.opacity = 1.0
fromView.layer.shadowOpacity = 0
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
}
| gpl-3.0 | 8eccb42df8043ef18253a401b76aba42 | 33.372549 | 128 | 0.675414 | 5.512579 | false | false | false | false |
sunzeboy/PermissionScope | PermissionScope/PermissionScope.swift | 2 | 32529 | //
// PermissionScope.swift
// PermissionScope
//
// Created by Nick O'Neill on 4/5/15.
// Copyright (c) 2015 That Thing in Swift. All rights reserved.
//
import UIKit
import CoreLocation
import AddressBook
import AVFoundation
import Photos
import EventKit
import CoreBluetooth
struct PermissionScopeConstants {
static let requestedInUseToAlwaysUpgrade = "requestedInUseToAlwaysUpgrade"
static let requestedForBluetooth = "askedForBluetooth"
}
public enum PermissionType: String {
case Contacts = "Contacts"
case LocationAlways = "LocationAlways"
case LocationInUse = "LocationInUse"
case Notifications = "Notifications"
case Microphone = "Microphone"
case Camera = "Camera"
case Photos = "Photos"
case Reminders = "Reminders"
case Events = "Events"
case Bluetooth = "Bluetooth"
var prettyName: String {
switch self {
case .LocationAlways, .LocationInUse:
return "Location"
default:
return self.rawValue
}
}
static let allValues = [Contacts, LocationAlways, LocationInUse, Notifications, Microphone, Camera, Photos, Reminders, Events]
}
public enum PermissionStatus: String {
case Authorized = "Authorized"
case Unauthorized = "Unauthorized"
case Unknown = "Unknown"
case Disabled = "Disabled" // System-level
}
public enum PermissionDemands: String {
case Required = "Required"
case Optional = "Optional"
}
private let PermissionScopeAskedForNotificationsDefaultsKey = "PermissionScopeAskedForNotificationsDefaultsKey"
public struct PermissionConfig {
let type: PermissionType
let demands: PermissionDemands
let message: String
let notificationCategories: Set<UIUserNotificationCategory>?
public init(type: PermissionType, demands: PermissionDemands, message: String, notificationCategories: Set<UIUserNotificationCategory>? = .None) {
if type != .Notifications && notificationCategories != .None {
assertionFailure("notificationCategories only apply to the .Notifications permission")
}
self.type = type
self.demands = demands
self.message = message
self.notificationCategories = notificationCategories
}
}
public struct PermissionResult: Printable {
public let type: PermissionType
public let status: PermissionStatus
public let demands: PermissionDemands
public var description: String {
return "\(type.rawValue) \(status.rawValue)"
}
}
extension UIColor {
var inverseColor: UIColor{
var r:CGFloat = 0.0; var g:CGFloat = 0.0; var b:CGFloat = 0.0; var a:CGFloat = 0.0;
if self.getRed(&r, green: &g, blue: &b, alpha: &a) {
return UIColor(red: 1.0-r, green: 1.0 - g, blue: 1.0 - b, alpha: a)
}
return self
}
}
extension String {
var localized: String {
return NSLocalizedString(self, comment: "")
}
}
public class PermissionScope: UIViewController, CLLocationManagerDelegate, UIGestureRecognizerDelegate, CBPeripheralManagerDelegate {
// constants
let contentWidth: CGFloat = 280.0
// configurable things
public let headerLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
public let bodyLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 240, height: 70))
public var tintColor = UIColor(red: 0, green: 0.47, blue: 1, alpha: 1)
public var buttonFont = UIFont.boldSystemFontOfSize(14)
public var labelFont = UIFont.systemFontOfSize(14)
public var closeButton = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 32))
public var closeOffset = CGSize(width: 0, height: 0)
// some view hierarchy
let baseView = UIView()
let contentView = UIView()
// various managers
lazy var locationManager:CLLocationManager = {
let lm = CLLocationManager()
lm.delegate = self
return lm
}()
lazy var bluetoothManager:CBPeripheralManager = {
return CBPeripheralManager(delegate: self, queue: nil)
}()
// internal state and resolution
var configuredPermissions: [PermissionConfig] = []
var permissionButtons: [UIButton] = []
var permissionLabels: [UILabel] = []
// properties that may be useful for direct use of the request* methods
public var authChangeClosure: ((Bool, [PermissionResult]) -> Void)? = nil
public var cancelClosure: (([PermissionResult]) -> Void)? = nil
/** Called when the user has disabled or denied access to notifications, and we're presenting them with a help dialog. */
public var disabledOrDeniedClosure: (([PermissionResult]) -> Void)? = nil
/** View controller to be used when presenting alerts. Defaults to self. You'll want to set this if you are calling the `request*` methods directly. */
public var viewControllerForAlerts : UIViewController?
// Computed variables
var allAuthorized: Bool {
let permissionsArray = getResultsForConfig()
return permissionsArray.filter { $0.status != .Authorized }.isEmpty
}
var requiredAuthorized: Bool {
let permissionsArray = getResultsForConfig()
return permissionsArray.filter { $0.status != .Authorized && $0.demands == .Required }.isEmpty
}
// use the code we have to see permission status
public func permissionStatuses(permissionTypes: [PermissionType]?) -> Dictionary<PermissionType, PermissionStatus> {
var statuses: Dictionary<PermissionType, PermissionStatus> = [:]
var types = permissionTypes
if types == nil {
types = PermissionType.allValues
}
if let types = types {
for type in types {
statuses[type] = self.statusForPermission(type)
}
}
return statuses
}
public init(backgroundTapCancels: Bool) {
super.init(nibName: nil, bundle: nil)
viewControllerForAlerts = self
// Set up main view
view.frame = UIScreen.mainScreen().bounds
view.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth
view.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:0.7)
view.addSubview(baseView)
// Base View
baseView.frame = view.frame
baseView.addSubview(contentView)
if backgroundTapCancels {
let tap = UITapGestureRecognizer(target: self, action: Selector("cancel"))
tap.delegate = self
baseView.addGestureRecognizer(tap)
}
// Content View
contentView.backgroundColor = UIColor.whiteColor()
contentView.layer.cornerRadius = 10
contentView.layer.masksToBounds = true
contentView.layer.borderWidth = 0.5
// header label
headerLabel.font = UIFont.systemFontOfSize(22)
headerLabel.textColor = UIColor.blackColor()
headerLabel.textAlignment = NSTextAlignment.Center
headerLabel.text = "Hey, listen!"
// headerLabel.backgroundColor = UIColor.redColor()
contentView.addSubview(headerLabel)
// body label
bodyLabel.font = UIFont.boldSystemFontOfSize(16)
bodyLabel.textColor = UIColor.blackColor()
bodyLabel.textAlignment = NSTextAlignment.Center
bodyLabel.text = "We need a couple things\r\nbefore you get started."
bodyLabel.numberOfLines = 2
// bodyLabel.text = "We need\r\na couple things before you\r\nget started."
// bodyLabel.backgroundColor = UIColor.redColor()
contentView.addSubview(bodyLabel)
// close button
closeButton.setTitle("Close", forState: UIControlState.Normal)
closeButton.addTarget(self, action: Selector("cancel"), forControlEvents: UIControlEvents.TouchUpInside)
contentView.addSubview(closeButton)
}
public convenience init() {
self.init(backgroundTapCancels: true)
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil)
}
public override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
var screenSize = UIScreen.mainScreen().bounds.size
// Set background frame
view.frame.size = screenSize
// Set frames
var x = (screenSize.width - contentWidth) / 2
let dialogHeight: CGFloat
switch self.configuredPermissions.count {
case 2:
dialogHeight = 360
case 3:
dialogHeight = 460
default:
dialogHeight = 260
}
var y = (screenSize.height - dialogHeight) / 2
contentView.frame = CGRect(x:x, y:y, width:contentWidth, height:dialogHeight)
// offset the header from the content center, compensate for the content's offset
headerLabel.center = contentView.center
headerLabel.frame.offset(dx: -contentView.frame.origin.x, dy: -contentView.frame.origin.y)
headerLabel.frame.offset(dx: 0, dy: -((dialogHeight/2)-50))
// ... same with the body
bodyLabel.center = contentView.center
bodyLabel.frame.offset(dx: -contentView.frame.origin.x, dy: -contentView.frame.origin.y)
bodyLabel.frame.offset(dx: 0, dy: -((dialogHeight/2)-100))
closeButton.center = contentView.center
closeButton.frame.offset(dx: -contentView.frame.origin.x, dy: -contentView.frame.origin.y)
closeButton.frame.offset(dx: 105, dy: -((dialogHeight/2)-20))
closeButton.frame.offset(dx: self.closeOffset.width, dy: self.closeOffset.height)
if closeButton.imageView?.image != nil {
closeButton.setTitle("", forState: UIControlState.Normal)
}
closeButton.setTitleColor(tintColor, forState: UIControlState.Normal)
let baseOffset = 95
var index = 0
for button in permissionButtons {
button.center = contentView.center
button.frame.offset(dx: -contentView.frame.origin.x, dy: -contentView.frame.origin.y)
button.frame.offset(dx: 0, dy: -((dialogHeight/2)-160) + CGFloat(index * baseOffset))
let type = configuredPermissions[index].type
let currentStatus = statusForPermission(type)
let prettyName = type.prettyName
if currentStatus == .Authorized {
setButtonAuthorizedStyle(button)
button.setTitle("Allowed \(prettyName)".localized.uppercaseString, forState: .Normal)
} else if currentStatus == .Unauthorized {
setButtonUnauthorizedStyle(button)
button.setTitle("Denied \(prettyName)".localized.uppercaseString, forState: .Normal)
} else if currentStatus == .Disabled {
// setButtonDisabledStyle(button)
button.setTitle("\(prettyName) Disabled".localized.uppercaseString, forState: .Normal)
}
let label = permissionLabels[index]
label.center = contentView.center
label.frame.offset(dx: -contentView.frame.origin.x, dy: -contentView.frame.origin.y)
label.frame.offset(dx: 0, dy: -((dialogHeight/2)-205) + CGFloat(index * baseOffset))
index++
}
}
// MARK: customizing the permissions
public func addPermission(config: PermissionConfig) {
assert(!config.message.isEmpty, "Including a message about your permission usage is helpful")
assert(configuredPermissions.count < 3, "Ask for three or fewer permissions at a time")
assert(configuredPermissions.filter { $0.type == config.type }.isEmpty, "Permission for \(config.type.rawValue) already set")
configuredPermissions.append(config)
}
func permissionStyledButton(type: PermissionType) -> UIButton {
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 220, height: 40))
button.setTitleColor(tintColor, forState: UIControlState.Normal)
button.titleLabel?.font = buttonFont
button.layer.borderWidth = 1
button.layer.borderColor = tintColor.CGColor
button.layer.cornerRadius = 6
// this is a bit of a mess, eh?
switch type {
case .LocationAlways, .LocationInUse:
button.setTitle("Enable \(type.prettyName)".localized.uppercaseString, forState: UIControlState.Normal)
default:
button.setTitle("Allow \(type.rawValue)".localized.uppercaseString, forState: UIControlState.Normal)
}
button.addTarget(self, action: Selector("request\(type.rawValue)"), forControlEvents: UIControlEvents.TouchUpInside)
return button
}
func setButtonAuthorizedStyle(button: UIButton) {
button.layer.borderWidth = 0
button.backgroundColor = tintColor
button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
}
func setButtonUnauthorizedStyle(button: UIButton) {
// TODO: Complete
button.layer.borderWidth = 0
button.backgroundColor = tintColor.inverseColor
button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
}
func permissionStyledLabel(message: String) -> UILabel {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 260, height: 50))
label.font = labelFont
label.numberOfLines = 2
label.textAlignment = NSTextAlignment.Center
label.text = message
// label.backgroundColor = UIColor.greenColor()
return label
}
// MARK: status and requests for each permission
public func statusLocationAlways() -> PermissionStatus {
if !CLLocationManager.locationServicesEnabled() {
return .Disabled
}
let status = CLLocationManager.authorizationStatus()
switch status {
case .AuthorizedAlways:
return .Authorized
case .Restricted, .Denied:
return .Unauthorized
case .AuthorizedWhenInUse:
let defaults = NSUserDefaults.standardUserDefaults()
// curious why this happens? Details on upgrading from WhenInUse to Always:
// https://github.com/nickoneill/PermissionScope/issues/24
if defaults.boolForKey(PermissionScopeConstants.requestedInUseToAlwaysUpgrade) == true {
return .Unauthorized
} else {
return .Unknown
}
case .NotDetermined:
return .Unknown
}
}
public func requestLocationAlways() {
switch statusLocationAlways() {
case .Unknown:
if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setBool(true, forKey: PermissionScopeConstants.requestedInUseToAlwaysUpgrade)
defaults.synchronize()
}
locationManager.requestAlwaysAuthorization()
case .Unauthorized:
self.showDeniedAlert(.LocationAlways)
case .Disabled:
self.showDisabledAlert(.LocationInUse)
default:
break
}
}
public func statusLocationInUse() -> PermissionStatus {
if !CLLocationManager.locationServicesEnabled() {
return .Disabled
}
let status = CLLocationManager.authorizationStatus()
// if you're already "always" authorized, then you don't need in use
// but the user can still demote you! So I still use them separately.
switch status {
case .AuthorizedWhenInUse, .AuthorizedAlways:
return .Authorized
case .Restricted, .Denied:
return .Unauthorized
case .NotDetermined:
return .Unknown
}
}
public func requestLocationInUse() {
switch statusLocationInUse() {
case .Unknown:
locationManager.requestWhenInUseAuthorization()
case .Unauthorized:
self.showDeniedAlert(.LocationInUse)
case .Disabled:
self.showDisabledAlert(.LocationInUse)
default:
break
}
}
public func statusContacts() -> PermissionStatus {
let status = ABAddressBookGetAuthorizationStatus()
switch status {
case .Authorized:
return .Authorized
case .Restricted, .Denied:
return .Unauthorized
case .NotDetermined:
return .Unknown
}
}
public func requestContacts() {
switch statusContacts() {
case .Unknown:
ABAddressBookRequestAccessWithCompletion(nil) { (success, error) -> Void in
self.detectAndCallback()
}
case .Unauthorized:
self.showDeniedAlert(.Contacts)
default:
break
}
}
// TODO: can we tell if notifications has been denied?
public func statusNotifications() -> PermissionStatus {
let settings = UIApplication.sharedApplication().currentUserNotificationSettings()
if settings.types != UIUserNotificationType.None {
return .Authorized
} else {
if NSUserDefaults.standardUserDefaults().boolForKey(PermissionScopeAskedForNotificationsDefaultsKey) {
return .Unauthorized
} else {
return .Unknown
}
}
}
func showingNotificationPermission () {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("finishedShowingNotificationPermission"), name: UIApplicationDidBecomeActiveNotification, object: nil)
notificationTimer?.invalidate()
}
var notificationTimer : NSTimer?
func finishedShowingNotificationPermission () {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil)
notificationTimer?.invalidate()
let allResults = getResultsForConfig().filter {
$0.type == PermissionType.Notifications
}
if let notificationResult : PermissionResult = allResults.first {
if notificationResult.status == PermissionStatus.Unknown {
showDeniedAlert(notificationResult.type)
} else {
detectAndCallback()
}
}
}
public func requestNotifications() {
switch statusNotifications() {
case .Unknown:
// There should be only one...
let notificationsPermissionSet = self.configuredPermissions.filter { $0.notificationCategories != .None && !$0.notificationCategories!.isEmpty }.first?.notificationCategories
NSUserDefaults.standardUserDefaults().setBool(true, forKey: PermissionScopeAskedForNotificationsDefaultsKey)
NSUserDefaults.standardUserDefaults().synchronize()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("showingNotificationPermission"), name: UIApplicationWillResignActiveNotification, object: nil)
notificationTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("finishedShowingNotificationPermission"), userInfo: nil, repeats: false)
UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Alert | .Sound | .Badge,
categories: notificationsPermissionSet))
case .Unauthorized:
showDeniedAlert(PermissionType.Notifications)
default:
break
}
}
public func statusMicrophone() -> PermissionStatus {
let status = AVAudioSession.sharedInstance().recordPermission()
if status == .Granted {
return .Authorized
} else if status == .Denied {
return .Unauthorized
}
return .Unknown
}
public func requestMicrophone() {
switch statusMicrophone() {
case .Unknown:
AVAudioSession.sharedInstance().requestRecordPermission({ (granted) -> Void in
self.detectAndCallback()
})
case .Unauthorized:
self.showDeniedAlert(.Microphone)
default:
break
}
}
public func statusCamera() -> PermissionStatus {
let status = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo)
switch status {
case .Authorized:
return .Authorized
case .Restricted, .Denied:
return .Unauthorized
case .NotDetermined:
return .Unknown
}
}
public func requestCamera() {
switch statusCamera() {
case .Unknown:
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo,
completionHandler: { (granted) -> Void in
self.detectAndCallback()
})
case .Unauthorized:
self.showDeniedAlert(.Camera)
default:
break
}
}
public func statusPhotos() -> PermissionStatus {
let status = PHPhotoLibrary.authorizationStatus()
switch status {
case .Authorized:
return .Authorized
case .Denied, .Restricted:
return .Unauthorized
case .NotDetermined:
return .Unknown
}
}
public func requestPhotos() {
switch statusPhotos() {
case .Unknown:
PHPhotoLibrary.requestAuthorization({ (status) -> Void in
self.detectAndCallback()
})
case .Unauthorized:
self.showDeniedAlert(.Photos)
default:
break
}
}
public func statusReminders() -> PermissionStatus {
let status = EKEventStore.authorizationStatusForEntityType(EKEntityTypeReminder)
switch status {
case .Authorized:
return .Authorized
case .Restricted, .Denied:
return .Unauthorized
case .NotDetermined:
return .Unknown
}
}
public func requestReminders() {
switch statusReminders() {
case .Unknown:
EKEventStore().requestAccessToEntityType(EKEntityTypeReminder,
completion: { (granted, error) -> Void in
self.detectAndCallback()
})
case .Unauthorized:
self.showDeniedAlert(.Reminders)
default:
break
}
}
public func statusEvents() -> PermissionStatus {
let status = EKEventStore.authorizationStatusForEntityType(EKEntityTypeEvent)
switch status {
case .Authorized:
return .Authorized
case .Restricted, .Denied:
return .Unauthorized
case .NotDetermined:
return .Unknown
}
}
public func requestEvents() {
switch statusEvents() {
case .Unknown:
EKEventStore().requestAccessToEntityType(EKEntityTypeEvent,
completion: { (granted, error) -> Void in
self.detectAndCallback()
})
case .Unauthorized:
self.showDeniedAlert(.Events)
default:
break
}
}
public func statusBluetooth() -> PermissionStatus{
let askedBluetooth = NSUserDefaults.standardUserDefaults().boolForKey(PermissionScopeConstants.requestedForBluetooth)
// if already asked for bluetooth before, do a request to get status, else wait for user to request
if askedBluetooth{
triggerBluetoothStatusUpdate()
} else {
return .Unknown
}
switch (bluetoothManager.state, CBPeripheralManager.authorizationStatus()) {
case (.Unsupported, _), (.PoweredOff, _), (_, .Restricted):
return .Disabled
case (.Unauthorized, _), (_, .Denied):
return .Unauthorized
case (.PoweredOn, .Authorized):
return .Authorized
default:
return .Unknown
}
}
func requestBluetooth() {
switch statusBluetooth() {
case .Disabled:
showDisabledAlert(.Bluetooth)
case .Unauthorized:
showDeniedAlert(.Bluetooth)
case .Unknown:
triggerBluetoothStatusUpdate()
default:
break
}
}
private func triggerBluetoothStatusUpdate() {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: PermissionScopeConstants.requestedForBluetooth)
NSUserDefaults.standardUserDefaults().synchronize()
bluetoothManager.startAdvertising(nil)
bluetoothManager.stopAdvertising()
}
// MARK: finally, displaying the panel
public func show(authChange: ((finished: Bool, results: [PermissionResult]) -> Void)? = nil, cancelled: ((results: [PermissionResult]) -> Void)? = nil) {
assert(configuredPermissions.count > 0, "Please add at least one permission")
authChangeClosure = authChange
cancelClosure = cancelled
// no missing required perms? callback and do nothing
if requiredAuthorized {
if let authChangeClosure = authChangeClosure {
authChangeClosure(true, getResultsForConfig())
}
return
}
// add the backing views
let window = UIApplication.sharedApplication().keyWindow!
window.addSubview(view)
view.frame = window.bounds
baseView.frame = window.bounds
for button in permissionButtons {
button.removeFromSuperview()
}
permissionButtons = []
for label in permissionLabels {
label.removeFromSuperview()
}
permissionLabels = []
// create the buttons
for config in configuredPermissions {
let button = permissionStyledButton(config.type)
permissionButtons.append(button)
contentView.addSubview(button)
let label = permissionStyledLabel(config.message)
permissionLabels.append(label)
contentView.addSubview(label)
}
self.view.setNeedsLayout()
// slide in the view
self.baseView.frame.origin.y = -400
UIView.animateWithDuration(0.2, animations: {
self.baseView.center.y = window.center.y + 15
self.view.alpha = 1
}, completion: { finished in
UIView.animateWithDuration(0.2, animations: {
self.baseView.center = window.center
})
})
}
public func hide() {
let window = UIApplication.sharedApplication().keyWindow!
UIView.animateWithDuration(0.2, animations: {
self.baseView.frame.origin.y = window.center.y + 400
self.view.alpha = 0
}, completion: { finished in
self.view.removeFromSuperview()
})
notificationTimer?.invalidate()
notificationTimer = nil
}
func cancel() {
self.hide()
if let cancelClosure = cancelClosure {
cancelClosure(getResultsForConfig())
}
}
func finish() {
self.hide()
if let authChangeClosure = authChangeClosure {
authChangeClosure(true, getResultsForConfig())
}
}
func detectAndCallback() {
// compile the results and pass them back if necessary
if let authChangeClosure = authChangeClosure {
authChangeClosure(allAuthorized, getResultsForConfig())
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.view.setNeedsLayout()
// and hide if we've sucessfully got all permissions
if self.allAuthorized {
self.hide()
}
})
}
func getResultsForConfig() -> [PermissionResult] {
var results: [PermissionResult] = []
for config in configuredPermissions {
var status = statusForPermission(config.type)
let result = PermissionResult(type: config.type, status: status, demands: config.demands)
results.append(result)
}
return results
}
func appForegroundedAfterSettings (){
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil)
detectAndCallback()
}
func showDeniedAlert(permission: PermissionType) {
if let disabledOrDeniedClosure = self.disabledOrDeniedClosure {
disabledOrDeniedClosure(self.getResultsForConfig())
}
var alert = UIAlertController(title: "Permission for \(permission.rawValue) was denied.",
message: "Please enable access to \(permission.rawValue) in the Settings app",
preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK",
style: .Cancel,
handler: nil))
alert.addAction(UIAlertAction(title: "Show me",
style: .Default,
handler: { (action) -> Void in
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("appForegroundedAfterSettings"), name: UIApplicationDidBecomeActiveNotification, object: nil)
let settingsUrl = NSURL(string: UIApplicationOpenSettingsURLString)
UIApplication.sharedApplication().openURL(settingsUrl!)
}))
viewControllerForAlerts?.presentViewController(alert,
animated: true, completion: nil)
}
func showDisabledAlert(permission: PermissionType) {
if let disabledOrDeniedClosure = self.disabledOrDeniedClosure {
disabledOrDeniedClosure(self.getResultsForConfig())
}
var alert = UIAlertController(title: "\(permission.rawValue) is currently disabled.",
message: "Please enable access to \(permission.rawValue) in Settings",
preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK",
style: .Cancel,
handler: nil))
viewControllerForAlerts?.presentViewController(alert,
animated: true, completion: nil)
}
// MARK: gesture delegate
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
// this prevents our tap gesture from firing for subviews of baseview
if touch.view == baseView {
return true
}
return false
}
// MARK: location delegate
public func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
detectAndCallback()
}
// MARK: bluetooth delegate
public func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager!) {
detectAndCallback()
}
// MARK: Helpers
func statusForPermission(type: PermissionType) -> PermissionStatus {
// :(
switch type {
case .LocationAlways:
return statusLocationAlways()
case .LocationInUse:
return statusLocationInUse()
case .Contacts:
return statusContacts()
case .Notifications:
return statusNotifications()
case .Microphone:
return statusMicrophone()
case .Camera:
return statusCamera()
case .Photos:
return statusPhotos()
case .Reminders:
return statusReminders()
case .Events:
return statusEvents()
case .Bluetooth:
return statusBluetooth()
}
}
} | mit | 96e1d7e493770565df0fc24ef9b11c6b | 34.397171 | 186 | 0.627809 | 5.553867 | false | false | false | false |
tkester/swift-algorithm-club | Shell Sort/ShellSortExample.swift | 5 | 744 | //
// ShellSortExample.swift
//
//
// Created by Cheer on 2017/2/26.
//
//
import Foundation
public func shellSort(_ list : inout [Int]) {
var sublistCount = list.count / 2
while sublistCount > 0 {
for var index in 0..<list.count {
guard index + sublistCount < list.count else { break }
if list[index] > list[index + sublistCount] {
swap(&list[index], &list[index + sublistCount])
}
guard sublistCount == 1 && index > 0 else { continue }
while index > 0 && list[index - 1] > list[index] {
swap(&list[index - 1], &list[index])
index -= 1
}
}
sublistCount = sublistCount / 2
}
}
| mit | 79b95229c7cec869fd1fa646a4f41a04 | 22.25 | 66 | 0.514785 | 4.065574 | false | false | false | false |
NSManchester/nsmanchester-app-ios | NSManchester/WhereViewController+MKMapViewDelegate.swift | 1 | 2420 | //
// WhereMapViewDelegate.swift
// NSManchester
//
// Created by Ross Butler on 30/01/2016.
// Copyright © 2016 Ross Butler. All rights reserved.
//
import Foundation
import MapKit
extension WhereViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView,
viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? MapLocation {
let identifier = "pin"
var view: MKPinAnnotationView
if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
as? MKPinAnnotationView {
dequeuedView.annotation = annotation
view = dequeuedView
} else {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 5)
view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) as UIView
}
view.pinTintColor = annotation.pinTintColor()
return view
}
return nil
}
func mapViewDidFinishLoadingMap(_ mapView: MKMapView) {
activityIndicatorView.stopAnimating()
}
func mapViewDidFailLoadingMap(_ mapView: MKMapView, withError error: Error) {
activityIndicatorView.stopAnimating()
let alertController = UIAlertController(title: "Unable to download map data",
message: "Please check that you are connected to the Internet and try again.",
preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { _ in }
alertController.addAction(okAction)
self.present(alertController, animated: true) {}
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if let location = view.annotation as? MapLocation {
let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
location.mapItem()?.openInMaps(launchOptions: launchOptions)
}
}
}
| mit | 42547d05428e22e2a811e6159dde9bd7 | 34.057971 | 129 | 0.594047 | 6.315927 | false | false | false | false |
paul8263/ImageBoardBrowser | ImageBoardBrowser/UIview+LoadingIndicatorViewExtension.swift | 1 | 904 | //
// UIview+LoadingIndicatorViewExtension.swift
// ImageBoardBrowser
//
// Created by Paul Zhang on 23/12/2016.
// Copyright © 2016 Paul Zhang. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
func showLoadingIndicatorView() {
let rect = CGRect(x: CGFloat(view.bounds.width) / 2, y: CGFloat(view.bounds.height) / 2, width: CGFloat(50.0), height: CGFloat(50.0))
let indicatorView = LoadingIndicatorView(frame: rect)
indicatorView.tag = 1000
view.addSubview(indicatorView)
}
func centerLoadingIndicatorView() {
let rect = CGRect(x: CGFloat(view.bounds.width) / 2, y: CGFloat(view.bounds.height) / 2, width: CGFloat(50.0), height: CGFloat(50.0))
view.viewWithTag(1000)?.frame = rect
}
func hideLoadingIndicatorView() {
view.viewWithTag(1000)?.removeFromSuperview()
}
}
| mit | e831d91ac112bd15c3cd9cb78ebe485a | 30.137931 | 141 | 0.671096 | 3.977974 | false | false | false | false |
jcgruenhage/dendrite | vendor/src/github.com/apache/thrift/lib/cocoa/src/TProtocol.swift | 37 | 5540 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import Foundation
public extension TProtocol {
public func readMessageBegin() throws -> (String, TMessageType, Int) {
var name : NSString?
var type : Int32 = -1
var sequenceID : Int32 = -1
try readMessageBeginReturningName(&name, type: &type, sequenceID: &sequenceID)
return (name as String!, TMessageType(rawValue: type)!, Int(sequenceID))
}
public func writeMessageBeginWithName(name: String, type: TMessageType, sequenceID: Int) throws {
try writeMessageBeginWithName(name, type: type.rawValue, sequenceID: Int32(sequenceID))
}
public func readStructBegin() throws -> (String?) {
var name : NSString? = nil
try readStructBeginReturningName(&name)
return (name as String?)
}
public func readFieldBegin() throws -> (String?, TType, Int) {
var name : NSString? = nil
var type : Int32 = -1
var fieldID : Int32 = -1
try readFieldBeginReturningName(&name, type: &type, fieldID: &fieldID)
return (name as String?, TType(rawValue: type)!, Int(fieldID))
}
public func writeFieldBeginWithName(name: String, type: TType, fieldID: Int) throws {
try writeFieldBeginWithName(name, type: type.rawValue, fieldID: Int32(fieldID))
}
public func readMapBegin() throws -> (TType, TType, Int32) {
var keyType : Int32 = -1
var valueType : Int32 = -1
var size : Int32 = 0
try readMapBeginReturningKeyType(&keyType, valueType: &valueType, size: &size)
return (TType(rawValue: keyType)!, TType(rawValue: valueType)!, size)
}
public func writeMapBeginWithKeyType(keyType: TType, valueType: TType, size: Int) throws {
try writeMapBeginWithKeyType(keyType.rawValue, valueType: valueType.rawValue, size: Int32(size))
}
public func readSetBegin() throws -> (TType, Int32) {
var elementType : Int32 = -1
var size : Int32 = 0
try readSetBeginReturningElementType(&elementType, size: &size)
return (TType(rawValue: elementType)!, size)
}
public func writeSetBeginWithElementType(elementType: TType, size: Int) throws {
try writeSetBeginWithElementType(elementType.rawValue, size: Int32(size))
}
public func readListBegin() throws -> (TType, Int32) {
var elementType : Int32 = -1
var size : Int32 = 0
try readListBeginReturningElementType(&elementType, size: &size)
return (TType(rawValue: elementType)!, size)
}
public func writeListBeginWithElementType(elementType: TType, size: Int) throws {
try writeListBeginWithElementType(elementType.rawValue, size: Int32(size))
}
public func writeFieldValue<T: TSerializable>(value: T, name: String, type: TType, id: Int32) throws {
try writeFieldBeginWithName(name, type: type.rawValue, fieldID: id)
try writeValue(value)
try writeFieldEnd()
}
public func readValue<T: TSerializable>() throws -> T {
return try T.readValueFromProtocol(self)
}
public func writeValue<T: TSerializable>(value: T) throws {
try T.writeValue(value, toProtocol: self)
}
public func readResultMessageBegin() throws {
let (_, type, _) = try readMessageBegin();
if type == .EXCEPTION {
let x = try readException()
throw x
}
return
}
public func validateValue(value: Any?, named name: String) throws {
if value == nil {
throw NSError(
domain: TProtocolErrorDomain,
code: Int(TProtocolError.Unknown.rawValue),
userInfo: [TProtocolErrorFieldNameKey: name])
}
}
public func readException() throws -> ErrorType {
var reason : String?
var type = TApplicationError.Unknown
try readStructBegin()
fields: while (true) {
let (_, fieldType, fieldID) = try readFieldBegin()
switch (fieldID, fieldType) {
case (_, .STOP):
break fields
case (1, .STRING):
reason = try readValue() as String
case (2, .I32):
let typeVal = try readValue() as Int32
if let tmp = TApplicationError(rawValue: typeVal) {
type = tmp
}
case let (_, unknownType):
try skipType(unknownType)
}
try readFieldEnd()
}
try readStructEnd()
return NSError(type:type, reason:reason ?? "")
}
public func writeExceptionForMessageName(name: String, sequenceID: Int, ex: NSError) throws {
try writeMessageBeginWithName(name, type: .EXCEPTION, sequenceID: sequenceID)
try ex.write(self)
try writeMessageEnd()
}
public func skipType(type: TType) throws {
try TProtocolUtil.skipType(type.rawValue, onProtocol: self)
}
}
| apache-2.0 | 8de395be5dd97290a135cc8555c3b874 | 28.157895 | 104 | 0.663177 | 4.318005 | false | false | false | false |
xuech/OMS-WH | OMS-WH/Classes/OrderDetail/Controller/仓库配货/KitDetailViewController.swift | 1 | 5370 | //
// KitDetailViewController.swift
// OMS
//
// Created by ___Gwy on 2017/8/28.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
import SVProgressHUD
class KitDetailViewController: UIViewController {
fileprivate var viewModel = OrderDetailViewModel()
var kitCode:String?
var isOpenArray:[Any]?
var kitDetailModel:KitDetailModel?{
didSet{
if let prodLns = kitDetailModel?.prodLns{
for _ in 0..<prodLns.count{
let isOpen = false
isOpenArray?.append(isOpen)
}
table.reloadData()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
title = "套件详情"
isOpenArray = [Any]()
initdata()
view.addSubview(table)
}
fileprivate lazy var table:UITableView = {
let table = UITableView()
table.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight - 64)
table.separatorStyle = .none
table.delegate = self
table.dataSource = self
table.register(UINib(nibName:"KitDetailTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
return table
}()
func initdata(){
viewModel.requestKitDetailData("oms-api-v3/businessData/hMedKitDetail", ["medKitInternalNo":kitCode!]) { (model, error) in
self.kitDetailModel = model
}
}
@objc func tapAction(tap:UITapGestureRecognizer){
let index = tap.view?.tag
var isOpen = isOpenArray![index!] as! Bool
isOpen = !isOpen
isOpenArray![index!] = NSNumber(value: isOpen)
let set = NSMutableIndexSet.init(index: index!)
table.reloadSections(set as IndexSet, with: .fade)
}
}
extension KitDetailViewController:UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let detail = kitDetailModel?.prodLns?[indexPath.section].materials?[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! KitDetailTableViewCell
cell.nameLB.text = "名称:\(detail!.medMIName)"
cell.codeLB.text = "编码:\(detail!.medMICode)"
cell.specificationLB.text = "规格:\(detail!.specification)"
cell.typeLB.text = "类型:\(detail!.categoryByPlatformName)"
if let req = detail?.reqQty{
cell.countLB.text = "数量:\(req)"
}
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let isOpen = isOpenArray![section] as! Bool
if isOpen == true{
return kitDetailModel?.prodLns?[section].materials?.count ?? 0
}
return 0
}
func numberOfSections(in tableView: UITableView) -> Int {
return kitDetailModel?.prodLns?.count ?? 0
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let kitModel = kitDetailModel?.prodLns?[section]
let isOpen = isOpenArray![section] as! Bool
let backView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth-25, height: 88))
backView.backgroundColor = UIColor.white
let brandLB = UILabel(frame: CGRect(x: 10,y: 0, width: kScreenWidth,height: 43))
brandLB.font = UIFont.systemFont(ofSize: 16)
brandLB.text = kitModel?.medBrandName
backView.addSubview(brandLB)
let lineOne = UIView(frame: CGRect(x: 0, y: 43, width: kScreenWidth, height: 1))
lineOne.backgroundColor = KlineColor
backView.addSubview(lineOne)
let prolnsLB = UILabel(frame: CGRect(x: 12,y: 44, width: kScreenWidth-24,height: 43))
prolnsLB.font = UIFont.systemFont(ofSize: 14)
prolnsLB.text = kitModel?.medProdLnName
prolnsLB.tag = section
backView.addSubview(prolnsLB)
let arrowPush = UIImageView(frame: CGRect(x: kScreenWidth-24, y: 54, width: 24, height: 24))
if isOpen == false{
arrowPush.image = UIImage(named: "r_rightPush")
}else{
arrowPush.image = UIImage(named: "r_downPush")
}
arrowPush.contentMode = .scaleAspectFit
backView.addSubview(arrowPush)
let lineTwo = UIView(frame: CGRect(x: 0, y: 87, width: kScreenWidth, height: 1))
lineTwo.backgroundColor = KlineColor
backView.addSubview(lineTwo)
prolnsLB.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
tap.numberOfTapsRequired = 1
tap.numberOfTouchesRequired = 1
prolnsLB.addGestureRecognizer(tap)
return backView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 88
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 110
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 5
}
}
| mit | 3b6fb96649d508ed27d772b329d8baca | 32.942675 | 130 | 0.617189 | 4.758036 | false | false | false | false |
laurennicoleroth/Tindergram | Tindergram/ChatViewController.swift | 1 | 2711 |
import Foundation
class ChatViewController: JSQMessagesViewController {
var messages: [JSQMessage] = []
var matchID: String?
var messageListener: MessageListener?
let outgoingBubble = JSQMessagesBubbleImageFactory().outgoingMessagesBubbleImageWithColor(UIColor.jsq_messageBubbleLightGrayColor())
let incomingBubble = JSQMessagesBubbleImageFactory().incomingMessagesBubbleImageWithColor(UIColor.jsq_messageBubbleBlueColor())
override func viewWillAppear(animated: Bool) {
if let id = matchID {
messageListener = MessageListener(matchID: id, startDate: NSDate(), callback: {
message in
self.messages.append(JSQMessage(senderId: message.senderID, senderDisplayName: message.senderID, date: message.date, text: message.message))
})
}
}
override func viewDidLoad() {
super.viewDidLoad()
senderDisplayName = currentUser()!.id
senderId = currentUser()!.id
collectionView.collectionViewLayout.incomingAvatarViewSize = CGSizeZero
collectionView.collectionViewLayout.outgoingAvatarViewSize = CGSizeZero
inputToolbar.contentView.leftBarButtonItem = nil
if let id = matchID {
fetchMessages(id, {
messages in
for m in messages {
self.messages.append(JSQMessage(senderId: m.senderID, senderDisplayName: m.senderID, date: m.date, text: m.message))
}
self.finishReceivingMessage()
})
}
}
override func viewWillDisappear(animated: Bool) {
messageListener?.stop()
}
override func collectionView(collectionView: JSQMessagesCollectionView!, messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageData! {
var data = self.messages[indexPath.row]
return data
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return messages.count
}
override func collectionView(collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageBubbleImageDataSource! {
var data = messages[indexPath.row]
if data.senderId == PFUser.currentUser()!.objectId! {
return outgoingBubble
} else {
return incomingBubble
}
}
override func didPressSendButton(button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: NSDate!) {
let m = JSQMessage(senderId: senderId, senderDisplayName: senderDisplayName, date: date, text: text)
messages.append(m)
if let id = matchID {
saveMessage(id, Message(message: text, senderID: senderId, date: date))
}
finishSendingMessage()
}
} | mit | d6c796abeb0ba0a099f8f4a8e4205102 | 32.9 | 178 | 0.718185 | 5.476768 | false | false | false | false |
codefellows/sea-b23-iOS | core-graphics.playground/section-8.swift | 2 | 831 | class AJSCircleView: UIView {
override class func layerClass() -> AnyClass {
return CAShapeLayer.self
}
override init(frame: CGRect) {
super.init(frame: frame)
let layer = self.layer as CAShapeLayer
layer.lineWidth = 2.0
layer.strokeColor = UIColor.redColor().CGColor
layer.fillColor = UIColor.blueColor().CGColor
layer.contentsScale = UIScreen.mainScreen().scale;
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.mainScreen().scale * 2.0
let path = UIBezierPath(ovalInRect: CGRectInset(self.bounds, 4.0, 4.0)).CGPath
layer.path = path
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
let circleView = AJSCircleView(frame: frame)
| mit | 6af26239feafcf93c436a3122f19eb42 | 28.678571 | 86 | 0.626955 | 4.694915 | false | false | false | false |
jjatie/Charts | ChartsDemo-macOS/PlaygroundChart.playground/Pages/StackedBarChart.xcplaygroundpage/Contents.swift | 1 | 3556 | //
// PlayGround
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// Copyright © 2017 thierry Hentic.
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
/*:
****
[Menu](Menu)
[Previous](@previous) | [Next](@next)
****
*/
import Charts
//: # Stacked Bar
import Cocoa
import PlaygroundSupport
let r = CGRect(x: 0, y: 0, width: 600, height: 600)
var chartView = HorizontalBarChartView(frame: r)
//: ### General
chartView.drawBarShadowEnabled = false
chartView.drawValueAboveBarEnabled = false
chartView.maxVisibleCount = 60
chartView.fitBars = true
chartView.gridBackgroundColor = NSUIColor.white
chartView.drawGridBackgroundEnabled = true
//: ### xAxis
let xAxis = chartView.xAxis
xAxis.labelPosition = .bothSided
xAxis.labelTextColor = #colorLiteral(red: 0.01680417731, green: 0.1983509958, blue: 1, alpha: 1)
xAxis.labelFont = NSUIFont.systemFont(ofSize: CGFloat(12.0))
xAxis.drawAxisLineEnabled = true
xAxis.drawGridLinesEnabled = true
xAxis.granularity = 1.0
xAxis.avoidFirstLastClippingEnabled = false
//: ### LeftAxis
let leftAxis = chartView.leftAxis
leftAxis.labelFont = NSUIFont.systemFont(ofSize: CGFloat(12.0))
leftAxis.labelTextColor = #colorLiteral(red: 0, green: 0.9768045545, blue: 0, alpha: 1)
leftAxis.drawAxisLineEnabled = false
leftAxis.drawGridLinesEnabled = true
leftAxis.axisMinimum = 0.0
leftAxis.enabled = true
leftAxis.spaceTop = 0.0
leftAxis.spaceBottom = 0.0
//: ### RightAxis
let rightAxis = chartView.rightAxis
rightAxis.labelFont = NSUIFont.systemFont(ofSize: CGFloat(12.0))
rightAxis.labelTextColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1)
rightAxis.drawAxisLineEnabled = true
rightAxis.drawGridLinesEnabled = true
rightAxis.axisMinimum = 0.0
rightAxis.enabled = true
rightAxis.spaceTop = 0.5
rightAxis.spaceBottom = 0.5
//: ### Legend
let legend = chartView.legend
legend.horizontalAlignment = .left
legend.verticalAlignment = .bottom
legend.orientation = .horizontal
legend.drawInside = false
legend.form = .square
legend.formSize = 8.0
legend.font = NSUIFont(name: "HelveticaNeue-Light", size: CGFloat(11.0))!
legend.xEntrySpace = 4.0
//: ### Description
chartView.chartDescription?.text = "Horizontal Bar Chart"
//: ### BarChartDataEntry
let count = 12
let range = 100.0
let mult = 30.0
var yVals = [ChartDataEntry]()
for i in 0 ..< count {
let val1 = Double(arc4random_uniform(UInt32(mult)))
let val2 = Double(arc4random_uniform(UInt32(mult)))
let val3 = 100.0 - val1 - val2
yVals.append(BarChartDataEntry(x: Double(i), yValues: [val1, val2, val3]))
}
//: ### BarChartDataSet
var set1 = BarChartDataSet()
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 1
formatter.negativeSuffix = " %"
formatter.positiveSuffix = " %"
set1 = BarChartDataSet(values: yVals, label: "Stack")
set1.colors = [ChartColorTemplates.material()[0], ChartColorTemplates.material()[1], ChartColorTemplates.material()[2]]
set1.valueFont = NSUIFont(name: "HelveticaNeue-Light", size: CGFloat(10.0))!
set1.valueFormatter = DefaultValueFormatter(formatter: formatter)
set1.valueTextColor = NSUIColor.white
set1.stackLabels = ["stack1", "stack2", "stack3"]
var dataSets = [BarChartDataSet]()
dataSets.append(set1)
//: ### BarChartData
let data = BarChartData()
data.addDataSet(dataSets[0])
chartView.fitBars = true
chartView.data = data
/*:---*/
//: ### Setup for the live view
PlaygroundPage.current.liveView = chartView
/*:
****
[Previous](@previous) | [Next](@next)
*/
| apache-2.0 | 232dcd5f5efe7530825e186a47a24395 | 30.184211 | 119 | 0.744585 | 3.789979 | false | false | false | false |
sadawi/ModelKit | ModelKitTests/ModelTests.swift | 1 | 14766 | //
// FieldModelTests.swift
// APIKit
//
// Created by Sam Williams on 12/8/15.
// Copyright © 2015 Sam Williams. All rights reserved.
//
import XCTest
import ModelKit
import PromiseKit
class ModelTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
fileprivate class Profile: Model {
let person:ModelField<Person> = ModelField<Person>(inverse: { $0.profile })
}
fileprivate class Company: Model {
let id = Field<Identifier>()
let name = Field<String>()
let size = Field<Int>()
let parentCompany = ModelField<Company>()
let employees:ModelArrayField<Person> = ModelField<Person>(inverse: { person in return person.company })*
override var identifierField: FieldType? {
return id
}
}
fileprivate class Person: Model {
let id = Field<String>()
let name = Field<String>()
let rank = Field<Int>()
let company = ModelField<Company>(inverse: { company in return company.employees })
let profile = ModelField<Profile>(inverse: { $0.person })
override var identifierField: FieldType? {
return id
}
}
fileprivate class Item: Model {
let item:ModelField<Item> = {
let field = ModelField<Item>()
field.findInverse = { item in
return item.item
}
return field
}()
}
fileprivate class Club: Model {
let name = Field<String>()
let members = ModelField<Person>()*
}
func testCopySomeFields() {
let company = Company()
company.id.value = "c1"
company.name.value = "Apple"
XCTAssertNotNil(company.id.value)
let company2 = company.copy(fields: [company.name]) as! Company
XCTAssertEqual(company2.name.value, "Apple")
XCTAssertNil(company2.id.value)
}
func testModelArrayFields() {
let a = Company()
a.id.value = "1"
a.name.value = "Apple"
let person = Person()
person.name.value = "Bob"
a.employees.value = [person]
XCTAssertEqual(a.employees.value?.count, 1)
}
func testFieldModel() {
let co = Company()
co.name.value = "The Widget Company"
co.size.value = 22
let fields = co.interface
XCTAssertNotNil(fields["name"])
let co2 = Company()
co2.name.value = "Parent Company"
co.parentCompany.value = co2
let dict = co.dictionaryValue()
print(dict)
XCTAssertEqual(dict["name"] as? String, "The Widget Company")
XCTAssertEqual(dict["size"] as? Int, 22)
let parentDict = dict["parentCompany"]
XCTAssert(parentDict is AttributeDictionary)
if let parentDict = parentDict as? AttributeDictionary {
XCTAssertEqual(parentDict["name"] as? String, "Parent Company")
}
}
fileprivate class InitializedFields: Model {
let name = Field<String>()
fileprivate override func initializeField(_ field: FieldType) {
if field.key == "name" {
field.name = "Test"
}
}
}
func testArrayFields() {
let a = Person()
a.name.value = "Alice"
let b = Person()
b.name.value = "Bob"
let c = Club()
c.name.value = "Chess Club"
c.members.value = [a,b]
let cDict = c.dictionaryValue()
XCTAssertEqual(cDict["name"] as? String, "Chess Club")
let members = cDict["members"] as? [AttributeDictionary]
XCTAssertEqual(members?.count, 2)
if let first = members?[0] {
XCTAssertEqual(first["name"] as? String, "Alice")
} else {
XCTFail()
}
}
func testFieldInitialization() {
let model = InitializedFields()
XCTAssertEqual(model.name.name, "Test")
}
func testSelectiveDictionary() {
let co = Company()
co.name.value = "Apple"
let dictionary = co.dictionaryValue(fields: [co.name])
XCTAssertEqual(dictionary as! [String: String], ["name": "Apple"])
}
func testObservationCycles() {
let item1 = Item()
let item2 = Item()
item1.item.value = item1
item1.item.value = item2
}
func testCopy() {
let a = Company()
a.id.value = "1"
a.name.value = "Apple"
let person0 = Person()
person0.id.value = "p0"
person0.name.value = "Bob"
a.employees.value = [person0]
let person1 = Person()
person1.id.value = "p1"
person1.company.value = a
XCTAssertEqual(a.employees.value?.count, 2)
let b = a.copy() as! Company
XCTAssertFalse(a === b)
XCTAssertEqual(b.id.value, a.id.value)
XCTAssertEqual(b.employees.value?.count, 2)
XCTAssertEqual(a.employees.value?.count, 2)
XCTAssert(b.employees.value![0].company.value === b)
b.name.value = "Microsoft"
XCTAssertEqual(a.name.value, "Apple")
let person2 = Person()
person2.id.value = "p2"
person2.company.value = b
XCTAssertEqual(b.employees.value?.count, 3)
XCTAssertEqual(a.employees.value?.count, 2)
}
func testInverseFields() {
let person1 = Person()
person1.id.value = "p1"
let profileA = Profile()
let profileB = Profile()
// Setting side A of 1:1 field should also set inverse.
person1.profile.value = profileA
XCTAssertEqual(profileA.person.value, person1)
// Set side B of 1:1 field. Should also set new side A, and nil out original side A.
profileB.person.value = person1
XCTAssertEqual(person1.profile.value, profileB)
XCTAssertNil(profileA.person.value)
let company1 = Company()
company1.id.value = "c1"
let company2 = Company()
company2.id.value = "c2"
person1.company.value = company1
XCTAssertEqual(1, company1.employees.value?.count)
company1.employees.removeFirst(person1)
XCTAssertEqual(0, company1.employees.value?.count)
XCTAssertNil(person1.company.value)
company2.employees.value = [person1]
XCTAssertEqual(person1.company.value, company2)
XCTAssertEqual(0, company1.employees.value?.count)
}
fileprivate class Letter: Model {
override class func instanceClass<T>(for dictionaryValue: AttributeDictionary) -> T.Type? {
if let letter = dictionaryValue["letter"] as? String {
if letter == "a" {
return A.self as? T.Type
} else if letter == "b" {
return B.self as? T.Type
} else if letter == "x" {
return UnrelatedClass.self as? T.Type
} else {
return nil
}
}
return nil
}
}
fileprivate class A: Letter {
}
fileprivate class B: Letter {
}
fileprivate class UnrelatedClass: Model {
}
func testCustomSubclass() {
let a = Letter.from(dictionaryValue: ["letter": "a"])
XCTAssert(a is A)
let b = Letter.from(dictionaryValue: ["letter": "b"])
XCTAssert(b is B)
// We didn't define the case for "c", so it falls back to Letter.
let c = Letter.from(dictionaryValue: ["letter": "c"])
XCTAssert(type(of: c!) == Letter.self)
// Note that the unrelated type falls back to Letter!
let x = Letter.from(dictionaryValue: ["letter": "x"])
XCTAssert(type(of: x!) == Letter.self)
}
fileprivate class Object: Model {
let id = Field<String>()
let name = Field<String>().requireNotNil()
let component = ModelField<Component>()
let essentialComponent = ModelField<EssentialComponent>().requireValid()
override var identifierField: FieldType? {
return self.id
}
}
fileprivate class EssentialComponent: Model {
let number = Field<Int>().requireNotNil()
}
fileprivate class Component: Model {
let id = Field<String>()
let name = Field<String>().requireNotNil()
let age = Field<String>().requireNotNil()
override var identifierField: FieldType? {
return self.id
}
}
func testNestedValidations() {
let object = Object()
let component = Component()
let essentialComponent = EssentialComponent()
object.component.value = component
object.essentialComponent.value = essentialComponent
// Object is missing name and a valid EssentialComponent
XCTAssertTrue(object.validate().isInvalid)
object.name.value = "Widget"
// Object is still missing a valid EssentialComponent
XCTAssertFalse(object.validate().isValid)
// Object has a valid EssentialComponent. Component is still invalid, but that's OK.
object.essentialComponent.value?.number.value = 1
XCTAssertTrue(object.validate().isValid)
XCTAssert(object.component.value?.validate().isInvalid == true)
}
func testValidationMessages() {
let component = EssentialComponent()
let state = component.validate()
XCTAssertEqual(state, ValidationState.invalid(["is required"]))
}
// func testCascadeDelete() {
// let memory = MemoryModelStore()
//
//// Model.registry = MemoryRegistry(modelStore: memory)
// let didSave = expectationWithDescription("save")
// let didDelete = expectationWithDescription("delete")
// let object = Object()
// let component = Component()
// object.component.value = component
//
// when(memory.save(object), memory.save(component)).then { _ in
// memory.list(Object.self).then { objects -> () in
// XCTAssertEqual(objects.count, 1)
// }.then {
// memory.list(Component.self).then { components -> () in
// XCTAssertEqual(components.count, 1)
// didSave.fulfill()
// }
//
// }.then {
// memory.delete(object).then { _ in
// memory.list(Component.self).then { components -> () in
// XCTAssertEqual(components.count, 0)
// didDelete.fulfill()
// }
// }
// }
// }
//
// self.waitForExpectationsWithTimeout(1, handler: nil)
// }
func testExplicitNulls() {
let model = Company()
let parent = Company()
let context = ValueTransformerContext(name: "nulls")
context.explicitNull = false
model.parentCompany.value = parent
var d0 = model.dictionaryValue(in: context)
var parentDictionary = d0["parentCompany"] as? AttributeDictionary
XCTAssertNotNil(parentDictionary)
XCTAssertNil(parentDictionary?["name"])
context.explicitNull = true
d0 = model.dictionaryValue(in: context)
parentDictionary = d0["parentCompany"] as? AttributeDictionary
XCTAssertNotNil(parentDictionary?["name"])
// TODO
// XCTAssertEqual(parentDictionary?["name"] is NSNull)
// We haven't set any values, so nothing will be serialized anyway
let d = model.dictionaryValue(in: context)
XCTAssert(d["name"] == nil)
// Now, set a value explicitly, and it should appear in the dictionary
model.name.value = nil
let d2 = model.dictionaryValue(in: context)
XCTAssert(d2["name"] is NSNull)
}
func testMerging() {
let model = Company()
let model2 = Company()
model.identifier = "1"
model2.identifier = "2"
model.name.value = "Apple"
model2.name.value = "Google"
model.merge(from: model2, exclude: [model.id])
XCTAssertEqual(model.name.value, "Google")
XCTAssertEqual(model.identifier, "1")
model.merge(from: model2)
XCTAssertEqual(model.identifier, "2")
}
func testMergingUnsetFields() {
let model = Company()
let model2 = Company()
model.id.value = "1"
model.merge(from: model2)
XCTAssertEqual(model.id.value, "1")
model2.id.value = "2"
model2.id.loadState = .notLoaded
model.merge(from: model2)
XCTAssertEqual(model.id.value, "1")
}
func testFieldLoadStates() {
let company = Company()
XCTAssertEqual(company.id.loadState, .notLoaded)
XCTAssertEqual(company.employees.loadState, .notLoaded)
}
fileprivate class TransformerFieldModel: Model {
let title = Field<String>()
let people = ModelField<Person>().transform(with: ModelValueTransformer(fields: { [$0.name] })).arrayField()
let person = ModelField<Person>()
}
func testTransformerFields() {
let model = TransformerFieldModel()
let person = Person()
person.rank.value = 100
person.name.value = "John"
let person2 = Person()
person2.rank.value = 2
person2.name.value = "person 2"
model.people.value = [person]
model.person.value = person
let dict = model.dictionaryValue()
let johnDict = (dict["people"] as! [AttributeDictionary])[0]
XCTAssertEqual(johnDict.count, 1)
XCTAssertEqual(johnDict["name"] as! String, "John")
}
}
| mit | 1ff83a79d237cffa8a141990ca96496a | 30.684549 | 116 | 0.551981 | 4.676908 | false | true | false | false |
pauljohanneskraft/Math | Example/CoreMath/Cocoa/NSTextField.swift | 1 | 602 | //
// NSTextField.swift
// Math
//
// Created by Paul Kraft on 09.12.17.
// Copyright © 2017 pauljohanneskraft. All rights reserved.
//
import Cocoa
extension NSTextField {
convenience init(string: String, textColor: NSColor = .black) {
self.init()
self.stringValue = string
self.font = NSFont.systemFont(ofSize: 15)
self.textColor = textColor
self.isEditable = false
self.isSelectable = false
self.bezelStyle = .squareBezel
self.isBordered = false
self.drawsBackground = false
backgroundColor = .clear
}
}
| mit | 8b5562a2969176e96d63fe9d7be28366 | 24.041667 | 67 | 0.637271 | 4.355072 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/People/PeopleCell.swift | 1 | 2717 | import UIKit
import WordPressShared
class PeopleCell: WPTableViewCell {
@IBOutlet var avatarImageView: CircularImageView!
@IBOutlet var displayNameLabel: UILabel!
@IBOutlet var usernameLabel: UILabel!
@IBOutlet var roleBadge: PeopleRoleBadgeLabel!
@IBOutlet var superAdminRoleBadge: PeopleRoleBadgeLabel!
override func awakeFromNib() {
WPStyleGuide.configureLabel(displayNameLabel, textStyle: .callout)
WPStyleGuide.configureLabel(usernameLabel, textStyle: .caption2)
}
func bindViewModel(_ viewModel: PeopleCellViewModel) {
setAvatarURL(viewModel.avatarURL as URL?)
displayNameLabel.text = viewModel.displayName
displayNameLabel.textColor = viewModel.usernameColor
usernameLabel.text = viewModel.usernameText
roleBadge.borderColor = viewModel.roleBorderColor
roleBadge.backgroundColor = viewModel.roleBackgroundColor
roleBadge.textColor = viewModel.roleTextColor
roleBadge.text = viewModel.roleText
roleBadge.isHidden = viewModel.roleHidden
superAdminRoleBadge.text = viewModel.superAdminText
superAdminRoleBadge.isHidden = viewModel.superAdminHidden
superAdminRoleBadge.borderColor = viewModel.superAdminBorderColor
superAdminRoleBadge.backgroundColor = viewModel.superAdminBackgroundColor
}
@objc func setAvatarURL(_ avatarURL: URL?) {
let gravatar = avatarURL.flatMap { Gravatar($0) }
let placeholder = UIImage(named: "gravatar")!
avatarImageView.downloadGravatar(gravatar, placeholder: placeholder, animate: false)
}
/*
It seems UIKit clears the background of all the cells' subviews when
highlighted/selected, so he have to set our wanted color again.
Otherwise we get this: https://cldup.com/NT3pbaeIc1.png
*/
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
let roleBackgroundColor = roleBadge.backgroundColor
let superAdminBackgroundColor = superAdminRoleBadge.backgroundColor
super.setHighlighted(highlighted, animated: animated)
if highlighted {
roleBadge.backgroundColor = roleBackgroundColor
superAdminRoleBadge.backgroundColor = superAdminBackgroundColor
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
let roleBackgroundColor = roleBadge.backgroundColor
let superAdminBackgroundColor = superAdminRoleBadge.backgroundColor
super.setSelected(selected, animated: animated)
if selected {
roleBadge.backgroundColor = roleBackgroundColor
superAdminRoleBadge.backgroundColor = superAdminBackgroundColor
}
}
}
| gpl-2.0 | bb16179188e32a9769ecbae71dd2faa3 | 39.552239 | 92 | 0.730953 | 5.868251 | false | false | false | false |
BoutFitness/Concept2-SDK | Pod/Classes/Services/RowingCharacteristic.swift | 1 | 5060 | //
// RowingCharacteristic.swift
// Pods
//
// Created by Jesse Curry on 10/24/15.
//
//
import CoreBluetooth
public enum RowingCharacteristic:Characteristic {
case generalStatus
case additionalStatus1
case additionalStatus2
case statusSampleRate
case strokeData
case additionalStrokeData
case intervalData
case additionalIntervalData
case workoutSummaryData
case additionalWorkoutSummaryData
case heartRateBeltInformation
case mutliplexedInformation
init?(uuid:CBUUID) {
switch uuid {
case Self.generalStatus.uuid:
self = .generalStatus
case Self.additionalStatus1.uuid:
self = .additionalStatus1
case Self.additionalStatus2.uuid:
self = .additionalStatus2
case Self.statusSampleRate.uuid:
self = .statusSampleRate
case Self.strokeData.uuid:
self = .strokeData
case Self.additionalStrokeData.uuid:
self = .additionalStrokeData
case Self.intervalData.uuid:
self = .intervalData
case Self.additionalIntervalData.uuid:
self = .additionalIntervalData
case Self.workoutSummaryData.uuid:
self = .workoutSummaryData
case Self.additionalWorkoutSummaryData.uuid:
self = .additionalWorkoutSummaryData
case Self.heartRateBeltInformation.uuid:
self = .heartRateBeltInformation
case Self.mutliplexedInformation.uuid:
self = .mutliplexedInformation
default:
return nil
}
}
var id: String {
switch self {
case .generalStatus:
return "CE060031-43E5-11E4-916C-0800200C9A66"
case .additionalStatus1:
return "CE060032-43E5-11E4-916C-0800200C9A66"
case .additionalStatus2:
return "CE060033-43E5-11E4-916C-0800200C9A66"
case .statusSampleRate:
return "CE060034-43E5-11E4-916C-0800200C9A66"
case .strokeData:
return "CE060035-43E5-11E4-916C-0800200C9A66"
case .additionalStrokeData:
return "CE060036-43E5-11E4-916C-0800200C9A66"
case .intervalData:
return "CE060037-43E5-11E4-916C-0800200C9A66"
case .additionalIntervalData:
return "CE060038-43E5-11E4-916C-0800200C9A66"
case .workoutSummaryData:
return "CE060039-43E5-11E4-916C-0800200C9A66"
case .additionalWorkoutSummaryData:
return "CE06003A-43E5-11E4-916C-0800200C9A66"
case .heartRateBeltInformation:
return "CE06003B-43E5-11E4-916C-0800200C9A66"
case .mutliplexedInformation:
return "CE060080-43E5-11E4-916C-0800200C9A66"
}
}
var uuid:CBUUID {
switch self {
case .generalStatus:
return CBUUID(string: "CE060031-43E5-11E4-916C-0800200C9A66")
case .additionalStatus1:
return CBUUID(string: "CE060032-43E5-11E4-916C-0800200C9A66")
case .additionalStatus2:
return CBUUID(string: "CE060033-43E5-11E4-916C-0800200C9A66")
case .statusSampleRate:
return CBUUID(string: "CE060034-43E5-11E4-916C-0800200C9A66")
case .strokeData:
return CBUUID(string: "CE060035-43E5-11E4-916C-0800200C9A66")
case .additionalStrokeData:
return CBUUID(string: "CE060036-43E5-11E4-916C-0800200C9A66")
case .intervalData:
return CBUUID(string: "CE060037-43E5-11E4-916C-0800200C9A66")
case .additionalIntervalData:
return CBUUID(string: "CE060038-43E5-11E4-916C-0800200C9A66")
case .workoutSummaryData:
return CBUUID(string: "CE060039-43E5-11E4-916C-0800200C9A66")
case .additionalWorkoutSummaryData:
return CBUUID(string: "CE06003A-43E5-11E4-916C-0800200C9A66")
case .heartRateBeltInformation:
return CBUUID(string: "CE06003B-43E5-11E4-916C-0800200C9A66")
case .mutliplexedInformation:
return CBUUID(string: "CE060080-43E5-11E4-916C-0800200C9A66")
}
}
func parse(data:Data?) -> CharacteristicModel? {
if let data = data {
switch self {
case .generalStatus:
return RowingGeneralStatus(fromData: data)
case .additionalStatus1:
return RowingAdditionalStatus1(fromData: data)
case .additionalStatus2:
return RowingAdditionalStatus2(fromData: data)
case .statusSampleRate:
return RowingStatusSampleRate(fromData: data)
case .strokeData:
return RowingStrokeData(fromData: data)
case .additionalStrokeData:
return RowingAdditionalStrokeData(fromData: data)
case .intervalData:
return RowingIntervalData(fromData: data)
case .additionalIntervalData:
return RowingAdditionalIntervalData(fromData: data)
case .workoutSummaryData:
return RowingWorkoutSummaryData(fromData: data)
case .additionalWorkoutSummaryData:
return RowingAdditionalWorkoutSummaryData(fromData: data)
case .heartRateBeltInformation:
return RowingHeartRateBeltInformation(fromData: data)
case .mutliplexedInformation:
return nil // JLC: this service gives the same data as the others
}
}
else {
return nil
}
}
}
| mit | 5d956f91f93a3c735fc136c6a3e115bd | 33.421769 | 73 | 0.699605 | 3.862595 | false | false | false | false |
dpricha89/DrApp | Pods/SwiftDate/Sources/SwiftDate/Commons.swift | 1 | 8893 | //
// SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones.
// Created by: Daniele Margutti
// Main contributors: Jeroen Houtzager
//
//
// 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
/// Time interval reference
///
/// - start: start of the specified component
/// - end: end of the specified component
/// - auto: value is the result of the operation
public enum TimeReference {
case start
case end
case auto
}
/// Rounding mode of the interval
///
/// - round: round
/// - ceil: ceil
/// - floor: floor
public enum IntervalRoundingType {
case round
case ceil
case floor
}
public enum IntervalType {
case seconds(_: Int)
case minutes(_: Int)
internal var seconds: TimeInterval {
switch self {
case .seconds(let secs): return TimeInterval(secs)
case .minutes(let mins): return TimeInterval(mins * 60)
}
}
}
/// This define the weekdays
///
/// - sunday: sunday
/// - monday: monday
/// - tuesday: tuesday
/// - wednesday: wednesday
/// - thursday: thursday
/// - friday: friday
/// - saturday: saturday
public enum WeekDay: Int {
case sunday = 1
case monday = 2
case tuesday = 3
case wednesday = 4
case thursday = 5
case friday = 6
case saturday = 7
}
/// Provide a mechanism to create and return local-thread object you can share.
///
/// Basically you assign a key to the object and return the initializated instance in `create`
/// block. Again this code is used internally to provide a common way to create local-thread date
/// formatter as like `NSDateFormatter` (which is expensive to create) or
/// `NSDateComponentsFormatter`.
/// Instance is saved automatically into current thread own dictionary.
///
/// - parameter key: identification string of the object
/// - parameter create: creation block. At the end of the block you need to provide the instance you
/// want to save.
///
/// - returns: the instance you have created into the current thread
internal func localThreadSingleton<T: AnyObject>(key: String, create: () -> T) -> T {
if let cachedObj = Thread.current.threadDictionary[key] as? T {
return cachedObj
} else {
let newObject = create()
Thread.current .threadDictionary[key] = newObject
return newObject
}
}
/// This is the list of all possible errors you can get from the library
///
/// - FailedToParse: Failed to parse a specific date using provided format
/// - FailedToCalculate: Failed to calculate new date from passed parameters
/// - MissingCalTzOrLoc: Provided components does not include a valid TimeZone or Locale
/// - DifferentCalendar: Provided dates are expressed in different calendars and cannot be compared
/// - MissingRsrcBundle: Missing SwiftDate resource bundle
/// - FailedToSetComponent: Failed to set a calendar com
public enum DateError: Error {
case FailedToParse
case FailedToCalculate
case MissingCalTzOrLoc
case DifferentCalendar
case MissingRsrcBundle
case FailedToSetComponent(Calendar.Component)
case InvalidLocalizationFile
}
/// Available date formats used to parse strings and format date into string
///
/// - custom: custom format expressed in Unicode tr35-31 (see http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns and Apple's Date Formatting Guide). Formatter uses heuristics to guess the date if it's invalid.
/// This may end in a wrong parsed date. Use `strict` to disable heuristics parsing.
/// - strict: strict format is like custom but does not apply heuristics to guess at the date which is intended by the string.
/// So, if you pass an invalid date (like 1999-02-31) formatter fails instead of returning guessing date (in our case
/// 1999-03-03).
/// - iso8601: ISO8601 date format (see https://en.wikipedia.org/wiki/ISO_8601).
/// - iso8601Auto: ISO8601 date format. You should use it to parse a date (parsers evaluate automatically the format of
/// the ISO8601 string). Passed as options to transform a date to string it's equal to [.withInternetDateTime] options.
/// - extended: extended date format ("eee dd-MMM-yyyy GG HH:mm:ss.SSS zzz")
/// - rss: RSS and AltRSS date format
/// - dotNET: .NET date format
public enum DateFormat {
case custom(String)
case strict(String)
case iso8601(options: ISO8601DateTimeFormatter.Options)
case iso8601Auto
case extended
case rss(alt: Bool)
case dotNET
}
/// This struct group the options you can choose to output a string which represent
/// the interval between two dates.
public struct ComponentsFormatterOptions {
/// The default formatting behavior. When using positional units, this behavior drops leading zeroes but pads middle and trailing values with zeros as needed. For example, with hours, minutes, and seconds displayed, the value for one hour and 10 seconds is “1:00:10”. For all other unit styles, this behavior drops all units whose values are 0. For example, when days, hours, minutes, and seconds are allowed, the abbreviated version of one hour and 10 seconds is displayed as “1h 10s”.*
public var zeroBehavior: DateComponentsFormatter.ZeroFormattingBehavior = .pad
// The maximum number of time units to include in the output string.
// By default is nil, which does not cause the elimination of any units.
public var maxUnitCount: Int? = nil
// Configures the strings to use (if any) for unit names such as days, hours, minutes, and seconds.
// By default is `positional`.
public var style: DateComponentsFormatter.UnitsStyle = .positional
// Setting this property to true results in output strings like “30 minutes remaining”. The default value of this property is false.
public var includeTimeRemaining: Bool = false
/// The bitmask of calendrical units such as day and month to include in the output string
/// Allowed components are: `year,month,weekOfMonth,day,hour,minute,second`.
/// By default it's set as nil which means set automatically based upon the interval.
public var allowedUnits: NSCalendar.Unit? = nil
/// The locale to use to format the string.
/// If `ComponentsFormatterOptions` is used from a `TimeInterval` object the default value
/// value is set to the current device's locale.
/// If `ComponentsFormatterOptions` is used from a `DateInRegion` object the default value
/// is set the `DateInRegion`'s locale.
public var locale: Locale = LocaleName.current.locale
/// Initialize a new ComponentsFormatterOptions struct
/// - parameter allowedUnits: allowed units or nil if you want to keep the default value
/// - parameter style: units style or nil if you want to keep the default value
/// - parameter zero: zero behavior or nil if you want to keep the default value
public init(allowedUnits: NSCalendar.Unit? = nil, style: DateComponentsFormatter.UnitsStyle? = nil, zero: DateComponentsFormatter.ZeroFormattingBehavior? = nil) {
if allowedUnits != nil { self.allowedUnits = allowedUnits! }
if style != nil { self.style = style! }
if zero != nil { self.zeroBehavior = zero! }
}
/// Evaluate the best allowed units to workaround NSException of the DateComponentsFormatter
internal func bestAllowedUnits(forInterval interval: TimeInterval) -> NSCalendar.Unit {
switch interval {
case 0...(SECONDS_IN_MINUTE-1):
return [.second]
case SECONDS_IN_MINUTE...(SECONDS_IN_HOUR-1):
return [.minute,.second]
case SECONDS_IN_HOUR...(SECONDS_IN_DAY-1):
return [.hour,.minute,.second]
case SECONDS_IN_DAY...(SECONDS_IN_WEEK-1):
return [.day,.hour,.minute,.second]
default:
return [.year,.month,.weekOfMonth,.day,.hour,.minute,.second]
}
}
}
private let SECONDS_IN_MINUTE: TimeInterval = 60
private let SECONDS_IN_HOUR: TimeInterval = SECONDS_IN_MINUTE * 60
private let SECONDS_IN_DAY: TimeInterval = SECONDS_IN_HOUR * 24
private let SECONDS_IN_WEEK: TimeInterval = SECONDS_IN_DAY * 7
| apache-2.0 | c586995f37f0a0100b0929de0cb0afb2 | 42.11165 | 488 | 0.741921 | 4.04233 | false | false | false | false |
AshkanImmortal/RWPickFlavor | RWPickFlavor/PickFlavorViewController.swift | 1 | 2525 | //
// ViewController.swift
// IceCreamShop
//
// Created by Joshua Greene on 2/8/15.
// Copyright (c) 2015 Razeware, LLC. All rights reserved.
//
import UIKit
import Alamofire
import BetterBaseClasses
import MBProgressHUD
public class PickFlavorViewController: BaseViewController, UICollectionViewDelegate {
// MARK: Instance Variables
var flavors: [Flavor] = [] {
didSet {
pickFlavorDataSource?.flavors = flavors
}
}
private var pickFlavorDataSource: PickFlavorDataSource? {
return collectionView?.dataSource as! PickFlavorDataSource?
}
private let flavorFactory = FlavorFactory()
// MARK: Outlets
@IBOutlet var contentView: UIView!
@IBOutlet var collectionView: UICollectionView!
@IBOutlet var iceCreamView: IceCreamView!
@IBOutlet var label: UILabel!
// MARK: View Lifecycle
public override func viewDidLoad() {
super.viewDidLoad()
loadFlavors()
}
private func loadFlavors() {
let urlString = "http://www.raywenderlich.com/downloads/Flavors.plist"
self.showLoadingHUD()
Alamofire.request(.GET, urlString, encoding: .PropertyList(.XMLFormat_v1_0, 0))
.responsePropertyList { request, response, array, error in
self.hideLoadingHUD()
if let error = error {
println("Error= \(error)")
} else if let array = array as? [[String:String]] {
if array.isEmpty {
println("No flavor were found!")
} else {
self.flavors = self.flavorFactory.flavorsFromDictionaryArray(array)
self.collectionView.reloadData()
self.selectFirstFlavor()
}
}
}
}
private func showLoadingHUD() {
let hud = MBProgressHUD.showHUDAddedTo(contentView, animated: true)
hud.labelText = "Loading..."
}
private func hideLoadingHUD() {
MBProgressHUD.hideAllHUDsForView(contentView, animated: true)
}
private func selectFirstFlavor() {
if let flavor = flavors.first {
updateWithFlavor(flavor)
}
}
// MARK: UICollectionViewDelegate
public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let flavor = flavors[indexPath.row]
updateWithFlavor(flavor)
}
// MARK: Internal
private func updateWithFlavor(flavor: Flavor) {
iceCreamView.updateWithFlavor(flavor)
label.text = flavor.name
}
}
| mit | 72ba8d4654794cb6dac3d0d1bf01610d | 23.047619 | 113 | 0.649505 | 4.95098 | false | false | false | false |
CodeCatalyst/MaterialDesignColorPicker | MaterialDesignColorPicker/MaterialDesignColorSwatchCollectionViewHeaderView.swift | 1 | 1035 | //
// MaterialDesignColorSwatchCollectionViewHeaderView.swift
// MaterialDesignColorPicker
//
// Created by John Yanarella on 2/5/17.
// Copyright © 2017-2020 John Yanarella.
//
import Cocoa
class MaterialDesignColorSwatchCollectionViewHeaderView: NSView {
@IBOutlet fileprivate weak var nameLabel: NSTextField!
override init(frame: NSRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
wantsLayer = true
layerContentsRedrawPolicy = .duringViewResize
}
var colorGroup: MaterialDesignColorGroup? {
didSet {
guard let colorGroup = colorGroup else {
return
}
let color = colorGroup.primaryColor
nameLabel.stringValue = colorGroup.name
nameLabel.textColor = color.labelColor
layer?.backgroundColor = color.color.cgColor
}
}
}
| mit | ea47d314a5798878b83691aef43a484a | 21.977778 | 65 | 0.639265 | 5.043902 | false | false | false | false |
kumabook/FeedlyKit | Spec/CategoriesAPISPec.swift | 1 | 3946 | //
// CategoriesAPISPec.swift
// FeedlyKit
//
// Created by Hiroki Kumamoto on 3/12/16.
// Copyright © 2016 Hiroki Kumamoto. All rights reserved.
//
import Foundation
import FeedlyKit
import Quick
import Nimble
class CategoriesAPISpec: CloudAPISpec {
let feedId = "feed/https://news.ycombinator.com/rss"
let categoryLabel = "test"
func fetchCategories(callback: @escaping (Int, [FeedlyKit.Category]) -> ()) {
let _ = self.client.fetchCategories {
guard let code = $0.response?.statusCode,
let categories = $0.result.value else { return }
callback(code, categories)
}
}
func createCategory(callback: @escaping () -> ()) {
let feed = Feed(id: feedId, title: "", description: "", subscribers: 0)
let _ = self.client.subscribeTo(feed, categories: [self.profile!.category(categoryLabel)]) { _ in
callback()
}
}
override func spec() {
beforeSuite {
self.client.setAccessToken(SpecHelper.accessToken)
}
describe("fetchCategories") {
if SpecHelper.accessToken == nil { return }
var statusCode = 0
var categories: [FeedlyKit.Category]? = nil
beforeEach {
self.fetchCategories {
statusCode = $0
categories = $1
}
}
it("fetches categories") {
expect(statusCode).toFinally(equal(200))
expect(categories).toFinallyNot(beNil())
}
}
describe("updateCategories") {
if SpecHelper.accessToken == nil { return }
var statusCode = 0
var categories: [FeedlyKit.Category]? = nil
var isFinish = false
let label = "test"
beforeEach {
self.fetchProfile {
self.createCategory {
let _ = self.client.updateCategory(self.profile!.category(label).id, label: label) {
guard let code = $0.response?.statusCode else { return }
statusCode = code
self.fetchCategories {
categories = $1
isFinish = true
}
}
}
}
}
it("updates categories") {
expect(statusCode).toFinally(equal(200))
expect(isFinish).toFinally(beTrue())
expect(categories).toFinallyNot(beNil())
expect(categories!.map { $0.label }).to(contain(label))
}
}
describe("deleteCategory") {
if SpecHelper.accessToken == nil { return }
var statusCode = 0
var categories: [FeedlyKit.Category]? = nil
var isFinish = false
var deletedCategory: FeedlyKit.Category? = nil
beforeEach {
self.fetchCategories { code, _categories in
if _categories.count == 0 { return }
deletedCategory = _categories[0]
let _ = self.client.deleteCategory(deletedCategory!.id) {
guard let code = $0.response?.statusCode else { return }
statusCode = code
self.fetchCategories {
categories = $1
isFinish = true
}
}
}
}
it("deletes a categories") {
expect(statusCode).toFinally(equal(200))
expect(isFinish).toFinally(beTrue())
expect(deletedCategory).notTo(beNil())
expect(categories!.map { $0.id }).notTo(contain(deletedCategory!.id))
}
}
}
}
| mit | 78e3c87a232a14ad542c45c105643551 | 35.527778 | 108 | 0.491001 | 5.352782 | false | false | false | false |
HTWDD/HTWDresden-iOS | HTWDD/Components/Timetable/Main/TimetableWeekViewController.swift | 1 | 6626 | //
// TimetableWeekViewController.swift
// HTWDD
//
// Created by Chris Herlemann on 04.12.20.
// Copyright © 2020 HTW Dresden. All rights reserved.
//
import JZCalendarWeekView
import Action
import RxSwift
class TimetableWeekViewController: TimetableBaseViewController {
@IBOutlet weak var weekControllsBackgroundView: UIView!
@IBOutlet weak var timetableWeekView: TimetableWeekView!
@IBOutlet weak var currentWeekBtn: UIButton!
@IBOutlet weak var nextWeekBtn: UIButton!
lazy var action: Action<Void, [LessonEvent]> = Action { [weak self] (_) -> Observable<[LessonEvent]> in
guard let self = self else { return Observable.empty() }
return self.viewModel.load().observeOn(MainScheduler.instance)
}
var events: [LessonEvent] = [] {
didSet {
reloadData()
}
}
override func setup() {}
override func viewDidLoad() {
super.viewDidLoad()
timetableWeekView.setupCalendar(numOfDays: 5,
setDate: Date().dateOfWeek(for: .beginn),
allEvents: JZWeekViewHelper.getIntraEventsByDate(originalEvents: events),
scrollType: .pageScroll,
firstDayOfWeek: .Monday,
visibleTime:Calendar.current.date(bySettingHour: 7, minute: 15, second: 0, of: Date())!)
weekControllsBackgroundView.backgroundColor = isDarkMode ? .black : UIColor.htw.blue
currentWeekBtn.setTitle(R.string.localizable.currentWeek(), for: .normal)
nextWeekBtn.setTitle(R.string.localizable.nextWeek(), for: .normal)
timetableWeekView.collectionView.delegate = self
timetableWeekView.delegate = self
action.elements.subscribe(onNext: { [weak self] items in
guard let self = self else { return }
self.events = items
self.stateView.isHidden = true
}).disposed(by: rx_disposeBag)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
load()
}
private func load() {
action.execute()
}
override func reloadData(){
timetableWeekView.forceReload(reloadEvents: JZWeekViewHelper.getIntraEventsByDate(originalEvents: events))
}
override func scrollToToday(notAnimated: Bool = true) {
guard let today = Calendar.current.date(bySettingHour: 7, minute: 15, second: 0, of: Date().dateOfWeek(for: .beginn))
else { return }
timetableWeekView.scrollWeekView(to: today)
timetableWeekView.updateWeekView(to: today)
}
override func getAllLessons() -> [Lesson]? {
return events.map { event in
event.lesson
}
}
override func getSemesterWeeks() -> [Int] {
var semesterWeeks: [Int] = []
events.forEach {event in
semesterWeeks.append(Calendar.current.component(.weekOfYear, from: event.startDate))
}
semesterWeeks.removeDuplicates()
semesterWeeks.sort()
return semesterWeeks
}
@IBAction func setCurrentWeek(_ sender: Any) {
scrollToToday(notAnimated: false)
}
@IBAction func setNextWeek(_ sender: Any) {
var nextWeek = Calendar.current.date(byAdding: .weekOfYear, value: 1, to: Date().dateOfWeek(for: .beginn))
nextWeek = Calendar.current.date(bySettingHour: 7, minute: 15, second: 0, of: nextWeek!)
timetableWeekView.scrollWeekView(to: nextWeek!)
timetableWeekView.updateWeekView(to: nextWeek!)
}
}
extension TimetableWeekViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let event = timetableWeekView.getCurrentEvent(with: indexPath) as? LessonEvent else { return }
let detailsLessonViewController = R.storyboard.timetable.timetableLessonDetailsViewController()!.also {
$0.context = context
$0.semseterWeeks = getSemesterWeeks()
}
detailsLessonViewController.setup(model: event.lesson)
self.navigationController?.pushViewController(detailsLessonViewController, animated: true)
}
}
extension TimetableWeekViewController: TimetableWeekViewDelegate {
func export(_ lessonEvent: LessonEvent) {
let exportMenu = UIAlertController(title: R.string.localizable.exportTitle(), message: R.string.localizable.exportMessage(), preferredStyle: .actionSheet)
let singleExportAction = UIAlertAction(title: R.string.localizable.exportSingleLesson(), style: .default, handler: { _ in
let exportSingleLesson = Lesson(id: lessonEvent.lesson.id,
lessonTag: lessonEvent.lesson.lessonTag,
name: lessonEvent.lesson.name,
type: lessonEvent.lesson.type,
day: lessonEvent.lesson.day,
beginTime: lessonEvent.lesson.beginTime,
endTime: lessonEvent.lesson.endTime,
week: lessonEvent.lesson.week,
weeksOnly: [Calendar.current.component(.weekOfYear, from: lessonEvent.startDate)],
professor: lessonEvent.lesson.professor,
rooms: lessonEvent.lesson.rooms,
lastChanged: lessonEvent.lesson.lastChanged)
self.viewModel.export(lessons: [exportSingleLesson])
self.showSuccessMessage()
})
let fullExportAction = UIAlertAction(title: R.string.localizable.exportAll(), style: .default, handler: { _ in
self.viewModel.export(lessons: [lessonEvent.lesson])
self.showSuccessMessage()
})
let cancelAction = UIAlertAction(title: R.string.localizable.cancel(), style: .cancel)
exportMenu.addAction(singleExportAction)
exportMenu.addAction(fullExportAction)
exportMenu.addAction(cancelAction)
self.present(exportMenu, animated: true, completion: nil)
}
}
| gpl-2.0 | 7d0ffe1cd029636d18a7184770162d95 | 38.434524 | 162 | 0.595019 | 5.355699 | false | false | false | false |
ibm-bluemix-mobile-services/bms-clientsdk-swift-analytics | Tests/Test Apps/TestApp iOS/AppDelegate.swift | 1 | 2536 | /*
* Copyright 2016 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 UIKit
import BMSCore
import BMSAnalytics
#if swift(>=3.0)
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
BMSClient.sharedInstance.initialize(bluemixRegion: ".stage1.ng.bluemix.net")
// IMPORTANT: Replace the apiKey parameter with a key from a real Analytics service instance
Analytics.initialize(appName: "TestAppiOS", apiKey: "1234", hasUserContext: true, collectLocation: true, deviceEvents: DeviceEvent.lifecycle, DeviceEvent.network)
Analytics.isEnabled = true
Logger.isLogStorageEnabled = true
Logger.isInternalDebugLoggingEnabled = true
return true
}
}
/**************************************************************************************************/
// MARK: - Swift 2
#else
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
BMSClient.sharedInstance.initialize(bluemixRegion: ".stage1.ng.bluemix.net")
// IMPORTANT: Replace the apiKey parameter with a key from a real Analytics service instance
Analytics.initialize(appName: "TestAppiOS", apiKey: "1234", hasUserContext: true, collectLocation: true, deviceEvents: DeviceEvent.lifecycle, DeviceEvent.network)
Analytics.isEnabled = true
Logger.isLogStorageEnabled = true
Logger.isInternalDebugLoggingEnabled = true
return true
}
}
#endif
| apache-2.0 | ef964302d4839bcabdbd71ffb9860c88 | 27.804598 | 170 | 0.652833 | 5.231733 | false | false | false | false |
swift8/anim-app | SwiftTest/SwiftTest/ViewController.swift | 1 | 2393 | //
// ViewController.swift
// SwiftTest
//
// Created by hzsydev on 15/6/4.
// Copyright (c) 2015年 HZSY_XG. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var display: UILabel!
//
var haveNumber = false
// 盛放数字的数组
var operandStack = [Double]()
//盛放运算符号的数组
var operationMark:Int = 0
// 可以加入数组
var isAction = false
// 数字按钮点击
@IBAction func numberButtonAction(sender: UIButton) {
if isAction {
display.text = "0"
haveNumber = false
isAction = false
}
if haveNumber {
display.text = display.text! + sender.currentTitle!
enter()
}else{
display.text = sender.currentTitle!
haveNumber = true
}
}
// 运算
@IBAction func operation(sender: UIButton) {
operandStack.append(displayValue)
isAction = true
let tempStr = sender.currentTitle!
switch tempStr {
case "x":operationMark = 1
case "/":operationMark = 2
case "+":operationMark = 3
case "-":operationMark = 4
default:break
}
}
@IBAction func clearButton(sender: AnyObject) {
operandStack.removeAll(keepCapacity: false)
display.text = "0"
}
// 运算
func operationAction(operations: (Double,Double) -> Double){
if operandStack.count >= 2 {
displayValue = operations(operandStack.removeLast(), operandStack.removeLast())
//enter()
operandStack.append(displayValue)
}
}
//
var displayValue: Double {
get{
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set{
display.text = "\(newValue)"
haveNumber = false
}
}
//
@IBAction func enter() {
println("==========")
switch operationMark{
case 1 :operationAction({$0 * $1})
case 2 :operationAction({$1 / $0})
case 3 :operationAction({$0 + $1})
case 4 :operationAction({$1 - $0})
default:break
}
operationMark = 0
}
}
| apache-2.0 | db777642cee04d6c42b5176e4b601a4a | 21.592233 | 91 | 0.518264 | 4.797938 | false | false | false | false |
mitchtreece/Bulletin | Example/Bulletin/RootViewController.swift | 1 | 11249 | //
// RootViewController.swift
// Bulletin_Example
//
// Created by Mitch Treece on 7/17/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import SnapKit
import Bulletin
class RootViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
fileprivate var bulletin: BulletinView?
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.tintColor = UIColor.white
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
fileprivate func bulletin(for row: BulletinRow) -> BulletinView {
var bulletin: BulletinView!
switch row {
case .notification:
let view = NotificationView()
view.iconImageView.image = #imageLiteral(resourceName: "app_icon")
view.iconTitleLabel.text = "BULLETIN"
view.timeLabel.text = "now"
view.titleLabel.text = "Trending News"
view.messageLabel.text = "Elon Musk reveals his next big project. The revolutionary new quantum teleporting Tesla Model 12! 🚗🚙🚗"
bulletin = BulletinView.notification()
bulletin.style.roundedCornerRadius = 8
bulletin.style.shadowRadius = 10
bulletin.style.shadowAlpha = 0.3
if UIDevice.current.isModern {
bulletin.style.roundedCornerRadius = 18
bulletin.style.edgeInsets = UIEdgeInsets(horizontal: 14, vertical: UIScreen.main.displayFeatureInsets.top + 4)
}
bulletin.embed(content: view)
case .banner:
let view = BannerView()
view.iconImageView.image = #imageLiteral(resourceName: "app_icon")
view.titleLabel.text = "The Dude"
view.timeLabel.text = "now"
view.messageLabel.text = "I’m the Dude, so that’s what you call me. That or, uh His Dudeness, or uh Duder, or El Duderino, if you’re not into the whole brevity thing. 😎"
bulletin = BulletinView.banner()
bulletin.style.statusBar = .lightContent
bulletin.embed(content: view)
case .statusBar:
var view: UIView!
if !UIDevice.current.isModern {
view = UILabel()
view.backgroundColor = UIColor.groupTableViewBackground
(view as! UILabel).text = "Mmmmmm toasty."
(view as! UILabel).textAlignment = .center
(view as! UILabel).textColor = UIColor.black
(view as! UILabel).font = UIFont.boldSystemFont(ofSize: 10)
}
else {
view = UIView()
view.backgroundColor = UIColor.groupTableViewBackground
let labelWidth = ((UIScreen.main.bounds.width - UIScreen.main.topNotch!.size.width) / 2)
let leftLabel = UILabel()
leftLabel.backgroundColor = UIColor.clear
leftLabel.text = "😍"
leftLabel.textAlignment = .center
leftLabel.textColor = UIColor.black
leftLabel.font = UIFont.boldSystemFont(ofSize: 24)
view.addSubview(leftLabel)
leftLabel.snp.makeConstraints { (make) in
make.left.top.bottom.equalTo(0)
make.width.equalTo(labelWidth)
}
let rightLabel = UILabel()
rightLabel.backgroundColor = UIColor.clear
rightLabel.text = "😘"
rightLabel.textAlignment = .center
rightLabel.textColor = UIColor.black
rightLabel.font = UIFont.boldSystemFont(ofSize: 24)
view.addSubview(rightLabel)
rightLabel.snp.makeConstraints { (make) in
make.right.top.bottom.equalTo(0)
make.width.equalTo(labelWidth)
}
}
bulletin = BulletinView.statusBar()
bulletin.embed(content: view, usingStrictHeight: UIApplication.shared.statusBarFrame.height)
case .alert:
let view = AlertView()
view.titleLabel.text = "Alert"
view.messageLabel.text = "This is an alert. It's a little boring, but it gets the job done. 😴"
view.button.setTitle("Okay", for: .normal)
view.delegate = self
bulletin = BulletinView.alert()
bulletin.style.isBackgroundDismissEnabled = false
bulletin.embed(content: view)
case .hud:
let view = HudView()
bulletin = BulletinView.hud()
bulletin.duration = .limit(2)
bulletin.snp_embed(content: view, usingStrictHeightConstraint: view.snp.width)
case .sheet:
let view = SheetView()
view.delegate = self
var bottomInset = UIScreen.main.displayFeatureInsets.bottom + 4
if !UIDevice.current.isModern {
bottomInset += 4
}
bulletin = BulletinView.sheet()
bulletin.style.edgeInsets = UIEdgeInsets(horizontal: 8, vertical: bottomInset)
bulletin.style.shadowAlpha = 0
bulletin.embed(content: view)
case .notch:
let view = NotchView()
view.titleLabel.text = "Hello, iPhone X"
let height = ((UIApplication.shared.statusBarFrame.height + 44) - 14)
bulletin = BulletinView.banner()
bulletin.style.edgeInsets = UIEdgeInsets(horizontal: UIScreen.main.topNotch!.frame.origin.x, vertical: 0)
bulletin.embed(content: view, usingStrictHeight: height)
}
return bulletin
}
}
extension RootViewController: UITableViewDelegate, UITableViewDataSource {
enum BulletinRow: Int {
case notification
case banner
case statusBar
case alert
case hud
case sheet
case notch
}
enum BackgroundEffectRow: Int {
case none
case darken
case blur
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0: return "Bulletins"
case 1: return "Background Effects"
case 2: return "Other"
default: return nil
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0: return UIDevice.current.isModern ? 7 : 6
case 1: return 3
case 2: return 1
default: return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
guard let row = BulletinRow(rawValue: indexPath.row) else { return UITableViewCell() }
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
cell?.accessoryType = .disclosureIndicator
switch row {
case .notification: cell?.textLabel?.text = "Notification"
case .banner: cell?.textLabel?.text = "Banner"
case .statusBar: cell?.textLabel?.text = "Toast"
case .alert: cell?.textLabel?.text = "Alert"
case .hud: cell?.textLabel?.text = "HUD"
case .sheet: cell?.textLabel?.text = "Sheet"
case .notch: cell?.textLabel?.text = "Notch"
}
return cell ?? UITableViewCell()
}
else if indexPath.section == 1 {
guard let row = BackgroundEffectRow(rawValue: indexPath.row) else { return UITableViewCell() }
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
cell?.accessoryType = .disclosureIndicator
switch row {
case .none: cell?.textLabel?.text = "None"
case .darken: cell?.textLabel?.text = "Darken"
case .blur: cell?.textLabel?.text = "Blur"
}
return cell ?? UITableViewCell()
}
else if indexPath.section == 2 {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
cell?.textLabel?.text = "Objective-C"
cell?.accessoryType = .disclosureIndicator
return cell ?? UITableViewCell()
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == 0 {
guard let row = BulletinRow(rawValue: indexPath.row) else { return }
let bulletin = self.bulletin(for: row)
self.bulletin = bulletin
bulletin.present()
}
else if indexPath.section == 1 {
guard let row = BackgroundEffectRow(rawValue: indexPath.row) else { return }
switch row {
case .none:
let bulletin = self.bulletin(for: .notification)
self.bulletin = bulletin
bulletin.present()
case .darken:
let bulletin = self.bulletin(for: .alert)
bulletin.style.backgroundEffect = .darken(alpha: 0.7)
self.bulletin = bulletin
bulletin.present()
case .blur:
let bulletin = self.bulletin(for: .sheet)
bulletin.style.backgroundEffect = .blur(style: .dark)
self.bulletin = bulletin
bulletin.present()
}
}
else if indexPath.section == 2 {
let vc = ObjcViewController()
navigationController?.pushViewController(vc, animated: true)
}
}
}
extension RootViewController: AlertViewDelegate {
func alertViewDidTapButton(_ alert: AlertView) {
bulletin?.dismiss()
bulletin = nil
}
}
extension RootViewController: SheetViewDelegate {
func sheetViewDidTapButton(_ sheet: SheetView) {
bulletin?.dismiss()
bulletin = nil
}
}
| mit | 88b961da63f974e3ba85482abc602c63 | 32.198225 | 181 | 0.535068 | 5.53031 | false | false | false | false |
freshOS/Komponents | Source/ViewForNode.swift | 1 | 6913 | //
// ViewForNode.swift
// Komponents
//
// Created by Sacha Durand Saint Omer on 12/05/2017.
// Copyright © 2017 freshOS. All rights reserved.
//
import Foundation
import UIKit
import MapKit
protocol UIKitRenderable {
func uiKitView() -> UIView
}
func fill(view: UIView, withViewProps props: HasViewProps) {
view.backgroundColor = props.backgroundColor
view.isHidden = props.isHidden
view.alpha = props.alpha
view.layer.borderColor = props.borderColor.cgColor
view.layer.borderWidth = props.borderWidth
view.layer.cornerRadius = props.cornerRadius
view.clipsToBounds = props.clipsToBounds
view.isUserInteractionEnabled = props.isUserInteractionEnabled
}
extension View: UIKitRenderable {
func uiKitView() -> UIView {
let v = UIView()
fill(view: v, withViewProps: props)
v.layer.anchorPoint = props.anchorPoint
v.clipsToBounds = props.clipsToBounds
v.isUserInteractionEnabled = props.isUserInteractionEnabled
return v
}
}
extension Label: UIKitRenderable {
func uiKitView() -> UIView {
let l = UILabel()
fill(view: l, withViewProps: props)
l.text = props.text
l.textColor = props.textColor
l.font = props.font
l.numberOfLines = props.numberOfLines
l.textAlignment = props.textAlignment
return l
}
}
extension Field: UIKitRenderable {
func uiKitView() -> UIView {
let v = BlockBasedUITextField()
fill(view: v, withViewProps: props)
v.placeholder = props.placeholder
v.text = props.text
return v
}
}
extension TextView: UIKitRenderable {
func uiKitView() -> UIView {
let v = BlockBasedUITextView()
fill(view: v, withViewProps: props)
v.text = props.text
return v
}
}
extension Image: UIKitRenderable {
func uiKitView() -> UIView {
let v = UIImageView()
fill(view: v, withViewProps: props)
v.image = props.image
v.contentMode = props.contentMode
return v
}
}
extension Switch: UIKitRenderable {
func uiKitView() -> UIView {
let v = BlockBasedUISwitch()
fill(view: v, withViewProps: props)
v.isOn = props.isOn
return v
}
}
extension Slider: UIKitRenderable {
func uiKitView() -> UIView {
let v = BlockBasedUISlider()
fill(view: v, withViewProps: props)
v.value = props.value
return v
}
}
extension Progress: UIKitRenderable {
func uiKitView() -> UIView {
let v = UIProgressView()
fill(view: v, withViewProps: props)
v.progress = props.progress
return v
}
}
extension Map: UIKitRenderable {
func uiKitView() -> UIView {
let v = MKMapView()
fill(view: v, withViewProps: props)
return v
}
}
extension PageControl: UIKitRenderable {
func uiKitView() -> UIView {
let v = UIPageControl()
fill(view: v, withViewProps: props)
v.numberOfPages = props.numberOfPages
v.currentPage = props.currentPage
v.pageIndicatorTintColor = props.pageIndicatorTintColor
v.currentPageIndicatorTintColor = props.currentPageIndicatorTintColor
return v
}
}
extension ActivityIndicatorView: UIKitRenderable {
func uiKitView() -> UIView {
let v = UIActivityIndicatorView(style: props.activityIndicatorStyle)
fill(view: v, withViewProps: props)
v.hidesWhenStopped = true
if props.isHidden {
v.stopAnimating()
} else {
v.startAnimating()
}
return v
}
}
extension HorizontalStack: UIKitRenderable {
func uiKitView() -> UIView {
let v = UIStackView()
v.axis = .horizontal
v.spacing = props.spacing
return v
}
}
extension VerticalStack: UIKitRenderable {
func uiKitView() -> UIView {
let v = UIStackView()
v.axis = .vertical
v.spacing = props.spacing
return v
}
}
extension Button: UIKitRenderable {
func uiKitView() -> UIView {
let v = BlockBasedUIButton()
fill(view: v, withViewProps: props)
v.setTitle(props.text, for: .normal)
v.setTitleColor(props.titleColorForNormalState, for: .normal)
v.setTitleColor(props.titleColorForHighlightedState, for: .highlighted)
if let backgroundColorForNormalState = props.backgroundColorForNormalState {
v.setBackgroundColor(backgroundColorForNormalState, for: .normal)
}
if let backgroundForHighlightedState = props.backgroundForHighlightedState {
v.setBackgroundColor(backgroundForHighlightedState, for: .highlighted)
}
v.isEnabled = props.isEnabled
v.titleLabel?.font = props.font
if let bi = props.image {
v.setBackgroundImage(bi, for: .normal)
}
return v
}
}
extension ScrollView: UIKitRenderable {
func uiKitView() -> UIView {
let v = UIScrollView()
fill(view: v, withViewProps: props)
return v
}
}
extension Table: UIKitRenderable {
func uiKitView() -> UIView {
let table = CallBackTableView(frame: CGRect.zero, style: tableStyle)
fill(view: table, withViewProps: props)
table.estimatedRowHeight = 100
table.rowHeight = UITableView.automaticDimension
if let rc = refreshCallback {
let refreshControl = BlockBasedUIRefreshControl()
table.addSubview(refreshControl)
let newRefreshCallback: ( ( @escaping EndRefreshingCallback) -> Void) = { done in
rc {
done()
table.reloadData()
}
}
refreshControl.setCallback(newRefreshCallback)
}
table.numberOfRows = {
return self.data().count
}
table.cellForRowAt = { tbv, ip in
if ip.section == 0 {
let child = self.data()[ip.row]
let component = self.configure(child)
return ComponentCell(component: component)
}
return UITableViewCell()
}
if let deleteCallback = deleteCallback {
table.didDeleteRowAt = { ip in
let shouldDeleteBlock = { (b: Bool) in
if b {
// Remove cell
// node.cells().remove(at: ip.row)
// Delete corresponding row.
table.deleteRows(at: [ip], with: .none)
} else {
table.reloadRows(at: [ip], with: .none)
}
}
deleteCallback(ip.row, shouldDeleteBlock)
}
}
return table
}
}
| mit | 11f6fa2980ba041f99c96e395ac0f6e3 | 27.680498 | 93 | 0.591725 | 4.958393 | false | false | false | false |
miracl/amcl | version22/swift/mpin.swift | 3 | 23003 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
//
// mpin.swift
//
// Created by Michael Scott on 08/07/2015.
// Copyright (c) 2015 Michael Scott. All rights reserved.
//
import Foundation
final public class MPIN
{
static public let EFS=Int(ROM.MODBYTES)
static public let EGS=Int(ROM.MODBYTES)
static public let PAS:Int=16
static let INVALID_POINT:Int = -14
static let BAD_PARAMS:Int = -11
static let WRONG_ORDER:Int = -18
static public let BAD_PIN:Int = -19
static public let SHA256=32
static public let SHA384=48
static public let SHA512=64
/* Configure your PIN here */
static let MAXPIN:Int32 = 10000 // PIN less than this
static let PBLEN:Int32 = 14 // Number of bits in PIN
static let TS:Int = 10 // 10 for 4 digit PIN, 14 for 6-digit PIN - 2^TS/TS approx = sqrt(MAXPIN)
static let TRAP:Int = 200 // 200 for 4 digit PIN, 2000 for 6-digit PIN - approx 2*sqrt(MAXPIN)
static public let HASH_TYPE=SHA256
private static func mpin_hash(_ sha:Int,_ c: FP4,_ U: ECP) -> [UInt8]
{
var w=[UInt8](repeating: 0,count: EFS)
var t=[UInt8](repeating: 0,count: 6*EFS)
var h=[UInt8]()
c.geta().getA().toBytes(&w); for i in 0 ..< EFS {t[i]=w[i]}
c.geta().getB().toBytes(&w); for i in EFS ..< 2*EFS {t[i]=w[i-EFS]}
c.getb().getA().toBytes(&w); for i in 2*EFS ..< 3*EFS {t[i]=w[i-2*EFS]}
c.getb().getB().toBytes(&w); for i in 3*EFS ..< 4*EFS {t[i]=w[i-3*EFS]}
U.getX().toBytes(&w); for i in 4*EFS ..< 5*EFS {t[i]=w[i-4*EFS]}
U.getY().toBytes(&w); for i in 5*EFS ..< 6*EFS {t[i]=w[i-5*EFS]}
if sha==SHA256
{
let H=HASH256()
H.process_array(t)
h=H.hash()
}
if sha==SHA384
{
let H=HASH384()
H.process_array(t)
h=H.hash()
}
if sha==SHA512
{
let H=HASH512()
H.process_array(t)
h=H.hash()
}
if h.isEmpty {return h}
var R=[UInt8](repeating: 0,count: PAS)
for i in 0 ..< PAS {R[i]=h[i]}
return R
}
// Hash number (optional) and string to point on curve
private static func hashit(_ sha:Int,_ n:Int32,_ ID:[UInt8]) -> [UInt8]
{
var R=[UInt8]()
if sha==SHA256
{
let H=HASH256()
if n != 0 {H.process_num(n)}
H.process_array(ID)
R=H.hash()
}
if sha==SHA384
{
let H=HASH384()
if n != 0 {H.process_num(n)}
H.process_array(ID)
R=H.hash()
}
if sha==SHA512
{
let H=HASH512()
if n != 0 {H.process_num(n)}
H.process_array(ID)
R=H.hash()
}
if R.isEmpty {return R}
let RM=Int(ROM.MODBYTES)
var W=[UInt8](repeating: 0,count: RM)
if sha >= RM
{
for i in 0 ..< RM {W[i]=R[i]}
}
else
{
for i in 0 ..< sha {W[i]=R[i]}
}
return W
}
static func mapit(_ h:[UInt8]) -> ECP
{
let q=BIG(ROM.Modulus)
let x=BIG.fromBytes(h)
x.mod(q)
var P=ECP(x,0)
while (true)
{
if !P.is_infinity() {break}
x.inc(1); x.norm();
P=ECP(x,0);
}
if ROM.CURVE_PAIRING_TYPE != ROM.BN_CURVE {
let c=BIG(ROM.CURVE_Cof)
P=P.mul(c)
}
return P
}
// needed for SOK
static func mapit2(_ h:[UInt8]) -> ECP2
{
let q=BIG(ROM.Modulus)
var x=BIG.fromBytes(h)
let one=BIG(1)
var Q=ECP2()
x.mod(q);
while (true)
{
let X=FP2(one,x);
Q=ECP2(X);
if !Q.is_infinity() {break}
x.inc(1); x.norm();
}
// Fast Hashing to G2 - Fuentes-Castaneda, Knapp and Rodriguez-Henriquez
let Fra=BIG(ROM.CURVE_Fra);
let Frb=BIG(ROM.CURVE_Frb);
let X=FP2(Fra,Frb);
x=BIG(ROM.CURVE_Bnx);
let T=ECP2(); T.copy(Q)
T.mul(x); T.neg()
let K=ECP2(); K.copy(T)
K.dbl(); K.add(T); K.affine()
K.frob(X)
Q.frob(X); Q.frob(X); Q.frob(X)
Q.add(T); Q.add(K)
T.frob(X); T.frob(X)
Q.add(T)
Q.affine()
return Q
}
// return time in slots since epoch
static public func today() -> Int32
{
let date=Date()
return (Int32(date.timeIntervalSince1970/(60*1440)))
}
// these next two functions help to implement elligator squared - http://eprint.iacr.org/2014/043
// maps a random u to a point on the curve
static func map(_ u:BIG,_ cb:Int) -> ECP
{
let x=BIG(u)
let p=BIG(ROM.Modulus)
x.mod(p)
var P=ECP(x,cb)
while (true)
{
if !P.is_infinity() {break}
x.inc(1); x.norm()
P=ECP(x,cb)
}
return P
}
// returns u derived from P. Random value in range 1 to return value should then be added to u
static func unmap(_ u:inout BIG,_ P:ECP) -> Int
{
let s=P.getS()
var r:Int32=0
let x=P.getX()
u.copy(x)
var R=ECP()
while (true)
{
u.dec(1); u.norm()
r += 1
R=ECP(u,s)
if !R.is_infinity() {break}
}
return Int(r)
}
static public func HASH_ID(_ sha:Int,_ ID:[UInt8]) -> [UInt8]
{
return hashit(sha,0,ID)
}
// these next two functions implement elligator squared - http://eprint.iacr.org/2014/043
// Elliptic curve point E in format (0x04,x,y} is converted to form {0x0-,u,v}
// Note that u and v are indistinguisible from random strings
static public func ENCODING(_ rng:RAND,_ E:inout [UInt8]) -> Int
{
var T=[UInt8](repeating: 0,count: EFS)
for i in 0 ..< EFS {T[i]=E[i+1]}
var u=BIG.fromBytes(T);
for i in 0 ..< EFS {T[i]=E[i+EFS+1]}
var v=BIG.fromBytes(T)
let P=ECP(u,v);
if P.is_infinity() {return INVALID_POINT}
let p=BIG(ROM.Modulus)
u=BIG.randomnum(p,rng)
var su=rng.getByte();
su%=2
let W=MPIN.map(u,Int(su))
P.sub(W);
let sv=P.getS();
let rn=MPIN.unmap(&v,P)
let m=rng.getByte();
let incr=1+Int(m)%rn
v.inc(incr)
E[0]=(su+UInt8(2*sv))
u.toBytes(&T)
for i in 0 ..< EFS {E[i+1]=T[i]}
v.toBytes(&T)
for i in 0 ..< EFS {E[i+EFS+1]=T[i]}
return 0;
}
static public func DECODING(_ D:inout [UInt8]) -> Int
{
var T=[UInt8](repeating: 0,count: EFS)
if (D[0]&0x04) != 0 {return INVALID_POINT}
for i in 0 ..< EFS {T[i]=D[i+1]}
var u=BIG.fromBytes(T)
for i in 0 ..< EFS {T[i]=D[i+EFS+1]}
var v=BIG.fromBytes(T)
let su=D[0]&1
let sv=(D[0]>>1)&1
let W=map(u,Int(su))
let P=map(v,Int(sv))
P.add(W)
u=P.getX()
v=P.getY()
D[0]=0x04
u.toBytes(&T);
for i in 0 ..< EFS {D[i+1]=T[i]}
v.toBytes(&T)
for i in 0 ..< EFS {D[i+EFS+1]=T[i]}
return 0
}
// R=R1+R2 in group G1
static public func RECOMBINE_G1(_ R1:[UInt8],_ R2:[UInt8],_ R:inout [UInt8]) -> Int
{
let P=ECP.fromBytes(R1)
let Q=ECP.fromBytes(R2)
if P.is_infinity() || Q.is_infinity() {return INVALID_POINT}
P.add(Q)
P.toBytes(&R)
return 0;
}
// W=W1+W2 in group G2
static public func RECOMBINE_G2(_ W1:[UInt8],_ W2:[UInt8],_ W:inout [UInt8]) -> Int
{
let P=ECP2.fromBytes(W1)
let Q=ECP2.fromBytes(W2)
if P.is_infinity() || Q.is_infinity() {return INVALID_POINT}
P.add(Q)
P.toBytes(&W)
return 0
}
// create random secret S
static public func RANDOM_GENERATE(_ rng:RAND,_ S:inout [UInt8]) -> Int
{
let r=BIG(ROM.CURVE_Order)
let s=BIG.randomnum(r,rng)
if ROM.AES_S>0
{
s.mod2m(2*ROM.AES_S)
}
s.toBytes(&S);
return 0;
}
// Extract PIN from TOKEN for identity CID
static public func EXTRACT_PIN(_ sha:Int,_ CID:[UInt8],_ pin:Int32,_ TOKEN:inout [UInt8]) -> Int
{
let P=ECP.fromBytes(TOKEN)
if P.is_infinity() {return INVALID_POINT}
let h=MPIN.hashit(sha,0,CID)
var R=MPIN.mapit(h)
R=R.pinmul(pin%MAXPIN,MPIN.PBLEN)
P.sub(R)
P.toBytes(&TOKEN)
return 0
}
// Implement step 2 on client side of MPin protocol
static public func CLIENT_2(_ X:[UInt8],_ Y:[UInt8],_ SEC:inout [UInt8]) -> Int
{
let r=BIG(ROM.CURVE_Order)
var P=ECP.fromBytes(SEC)
if P.is_infinity() {return INVALID_POINT}
let px=BIG.fromBytes(X)
let py=BIG.fromBytes(Y)
px.add(py)
px.mod(r)
// px.rsub(r)
P=PAIR.G1mul(P,px)
P.neg()
P.toBytes(&SEC);
// PAIR.G1mul(P,px).toBytes(&SEC)
return 0
}
// Implement step 1 on client side of MPin protocol
static public func CLIENT_1(_ sha:Int,_ date:Int32,_ CLIENT_ID:[UInt8],_ rng:RAND?,_ X:inout [UInt8],_ pin:Int32,_ TOKEN:[UInt8],_ SEC:inout [UInt8],_ xID:inout [UInt8]?,_ xCID:inout [UInt8]?,_ PERMIT:[UInt8]) -> Int
{
let r=BIG(ROM.CURVE_Order)
// let q=BIG(ROM.Modulus)
var x:BIG
if rng != nil
{
x=BIG.randomnum(r,rng!)
if ROM.AES_S>0
{
x.mod2m(2*ROM.AES_S)
}
x.toBytes(&X);
}
else
{
x=BIG.fromBytes(X);
}
// var t=[UInt8](count:EFS,repeatedValue:0)
var h=MPIN.hashit(sha,0,CLIENT_ID)
var P=mapit(h);
let T=ECP.fromBytes(TOKEN);
if T.is_infinity() {return INVALID_POINT}
var W=P.pinmul(pin%MPIN.MAXPIN,MPIN.PBLEN)
T.add(W)
if date != 0
{
W=ECP.fromBytes(PERMIT)
if W.is_infinity() {return INVALID_POINT}
T.add(W);
h=MPIN.hashit(sha,date,h)
W=MPIN.mapit(h);
if xID != nil
{
P=PAIR.G1mul(P,x)
P.toBytes(&xID!)
W=PAIR.G1mul(W,x)
P.add(W)
}
else
{
P.add(W);
P=PAIR.G1mul(P,x);
}
if xCID != nil {P.toBytes(&xCID!)}
}
else
{
if xID != nil
{
P=PAIR.G1mul(P,x)
P.toBytes(&xID!)
}
}
T.toBytes(&SEC);
return 0;
}
// Extract Server Secret SST=S*Q where Q is fixed generator in G2 and S is master secret
static public func GET_SERVER_SECRET(_ S:[UInt8],_ SST:inout [UInt8]) -> Int
{
var Q=ECP2(FP2(BIG(ROM.CURVE_Pxa),BIG(ROM.CURVE_Pxb)),FP2(BIG(ROM.CURVE_Pya),BIG(ROM.CURVE_Pyb)))
let s=BIG.fromBytes(S)
Q=PAIR.G2mul(Q,s)
Q.toBytes(&SST)
return 0
}
//W=x*H(G);
//if RNG == NULL then X is passed in
//if RNG != NULL the X is passed out
//if type=0 W=x*G where G is point on the curve, else W=x*M(G), where M(G) is mapping of octet G to point on the curve
static public func GET_G1_MULTIPLE(_ rng:RAND?,_ type:Int,_ X:inout [UInt8],_ G:[UInt8],_ W:inout [UInt8]) -> Int
{
var x:BIG
let r=BIG(ROM.CURVE_Order)
if rng != nil
{
x=BIG.randomnum(r,rng!)
if ROM.AES_S>0
{
x.mod2m(2*ROM.AES_S)
}
x.toBytes(&X)
}
else
{
x=BIG.fromBytes(X);
}
var P:ECP
if type==0
{
P=ECP.fromBytes(G)
if P.is_infinity() {return INVALID_POINT}
}
else
{P=MPIN.mapit(G)}
PAIR.G1mul(P,x).toBytes(&W)
return 0;
}
// Client secret CST=S*H(CID) where CID is client ID and S is master secret
// CID is hashed externally
static public func GET_CLIENT_SECRET(_ S:inout [UInt8],_ CID:[UInt8],_ CST:inout [UInt8]) -> Int
{
return GET_G1_MULTIPLE(nil,1,&S,CID,&CST)
}
// Time Permit CTT=S*(date|H(CID)) where S is master secret
static public func GET_CLIENT_PERMIT(_ sha:Int,_ date:Int32,_ S:[UInt8],_ CID:[UInt8],_ CTT:inout [UInt8]) -> Int
{
let h=MPIN.hashit(sha,date,CID)
let P=MPIN.mapit(h)
let s=BIG.fromBytes(S)
PAIR.G1mul(P,s).toBytes(&CTT)
return 0;
}
// Outputs H(CID) and H(T|H(CID)) for time permits. If no time permits set HID=HTID
static public func SERVER_1(_ sha:Int,_ date:Int32,_ CID:[UInt8],_ HID:inout [UInt8],_ HTID:inout [UInt8])
{
var h=MPIN.hashit(sha,0,CID)
let P=MPIN.mapit(h)
P.toBytes(&HID)
if date != 0
{
// if HID != nil {P.toBytes(&HID!)}
h=hashit(sha,date,h)
let R=MPIN.mapit(h)
P.add(R)
P.toBytes(&HTID)
}
//else {P.toBytes(&HID!)}
}
// Implement step 2 of MPin protocol on server side
static public func SERVER_2(_ date:Int32,_ HID:[UInt8]?,_ HTID:[UInt8]?,_ Y:[UInt8],_ SST:[UInt8],_ xID:[UInt8]?,_ xCID:[UInt8]?,_ mSEC:[UInt8],_ E:inout [UInt8]?,_ F:inout [UInt8]?) -> Int
{
// _=BIG(ROM.Modulus);
let Q=ECP2(FP2(BIG(ROM.CURVE_Pxa),BIG(ROM.CURVE_Pxb)),FP2(BIG(ROM.CURVE_Pya),BIG(ROM.CURVE_Pyb)))
let sQ=ECP2.fromBytes(SST)
if sQ.is_infinity() {return INVALID_POINT}
var R:ECP
if date != 0
{R=ECP.fromBytes(xCID!)}
else
{
if xID==nil {return MPIN.BAD_PARAMS}
R=ECP.fromBytes(xID!)
}
if R.is_infinity() {return INVALID_POINT}
let y=BIG.fromBytes(Y)
var P:ECP
if date != 0 {P=ECP.fromBytes(HTID!)}
else
{
if HID==nil {return MPIN.BAD_PARAMS}
P=ECP.fromBytes(HID!)
}
if P.is_infinity() {return INVALID_POINT}
P=PAIR.G1mul(P,y)
P.add(R)
R=ECP.fromBytes(mSEC)
if R.is_infinity() {return MPIN.INVALID_POINT}
var g=PAIR.ate2(Q,R,sQ,P)
g=PAIR.fexp(g)
if !g.isunity()
{
if HID != nil && xID != nil && E != nil && F != nil
{
g.toBytes(&E!)
if date != 0
{
P=ECP.fromBytes(HID!)
if P.is_infinity() {return MPIN.INVALID_POINT}
R=ECP.fromBytes(xID!)
if R.is_infinity() {return MPIN.INVALID_POINT}
P=PAIR.G1mul(P,y);
P.add(R);
}
g=PAIR.ate(Q,P);
g=PAIR.fexp(g);
g.toBytes(&F!);
}
return MPIN.BAD_PIN;
}
return 0
}
// Pollards kangaroos used to return PIN error
static public func KANGAROO(_ E:[UInt8],_ F:[UInt8]) -> Int
{
let ge=FP12.fromBytes(E)
let gf=FP12.fromBytes(F)
var distance=[Int]();
let t=FP12(gf);
var table=[FP12]()
var s:Int=1
for _ in 0 ..< Int(TS)
{
distance.append(s)
table.append(FP12(t))
s*=2
t.usqr()
}
t.one()
var dn:Int=0
for _ in 0 ..< TRAP
{
let i=Int(t.geta().geta().getA().lastbits(8))%TS
t.mul(table[i])
dn+=distance[i]
}
gf.copy(t); gf.conj()
var steps=0; var dm:Int=0
var res=0;
while (dm-dn<Int(MAXPIN))
{
steps += 1;
if steps>4*TRAP {break}
let i=Int(ge.geta().geta().getA().lastbits(8))%TS
ge.mul(table[i])
dm+=distance[i]
if (ge.equals(t))
{
res=dm-dn;
break;
}
if (ge.equals(gf))
{
res=dn-dm
break
}
}
if steps>4*TRAP || dm-dn>=Int(MAXPIN) {res=0 } // Trap Failed - probable invalid token
return res
}
// Functions to support M-Pin Full
static public func PRECOMPUTE(_ TOKEN:[UInt8],_ CID:[UInt8],_ G1:inout [UInt8],_ G2:inout [UInt8]) -> Int
{
let T=ECP.fromBytes(TOKEN);
if T.is_infinity() {return INVALID_POINT}
let P=MPIN.mapit(CID)
let Q=ECP2(FP2(BIG(ROM.CURVE_Pxa),BIG(ROM.CURVE_Pxb)),FP2(BIG(ROM.CURVE_Pya),BIG(ROM.CURVE_Pyb)))
var g=PAIR.ate(Q,T)
g=PAIR.fexp(g)
g.toBytes(&G1)
g=PAIR.ate(Q,P)
g=PAIR.fexp(g)
g.toBytes(&G2)
return 0
}
static public func HASH_ALL(_ sha:Int,_ HID:[UInt8],_ xID:[UInt8]?,_ xCID:[UInt8]?,_ SEC:[UInt8],_ Y:[UInt8],_ R:[UInt8],_ W:[UInt8] ) -> [UInt8]
{
var T=[UInt8](repeating: 0,count: 10*EFS+4)
var tlen=0
for i in 0 ..< HID.count {T[i]=HID[i]}
tlen+=HID.count
if xCID != nil {
for i in 0 ..< xCID!.count {T[i+tlen]=xCID![i]}
tlen+=xCID!.count
} else {
for i in 0 ..< xID!.count {T[i+tlen]=xID![i]}
tlen+=xID!.count
}
for i in 0 ..< SEC.count {T[i+tlen]=SEC[i]}
tlen+=SEC.count;
for i in 0 ..< Y.count {T[i+tlen]=Y[i]}
tlen+=Y.count;
for i in 0 ..< R.count {T[i+tlen]=R[i]}
tlen+=R.count;
for i in 0 ..< W.count {T[i+tlen]=W[i]}
tlen+=W.count;
return hashit(sha,0,T);
}
// calculate common key on client side
// wCID = w.(A+AT)
static public func CLIENT_KEY(_ sha:Int,_ G1:[UInt8],_ G2:[UInt8],_ pin:Int32,_ R:[UInt8],_ X:[UInt8],_ H:[UInt8],_ wCID:[UInt8],_ CK:inout [UInt8]) -> Int
{
let g1=FP12.fromBytes(G1)
let g2=FP12.fromBytes(G2)
let z=BIG.fromBytes(R)
let x=BIG.fromBytes(X)
let h=BIG.fromBytes(H)
var W=ECP.fromBytes(wCID)
if W.is_infinity() {return INVALID_POINT}
W=PAIR.G1mul(W,x)
let f=FP2(BIG(ROM.CURVE_Fra),BIG(ROM.CURVE_Frb))
let r=BIG(ROM.CURVE_Order)
let q=BIG(ROM.Modulus)
z.add(h) // new
z.mod(r)
let m=BIG(q)
m.mod(r)
let a=BIG(z)
a.mod(m)
let b=BIG(z)
b.div(m);
g2.pinpow(pin,PBLEN);
g1.mul(g2);
var c=g1.trace()
g2.copy(g1)
g2.frob(f)
let cp=g2.trace()
g1.conj()
g2.mul(g1)
let cpm1=g2.trace()
g2.mul(g1)
let cpm2=g2.trace()
c=c.xtr_pow2(cp,cpm1,cpm2,a,b)
let t=mpin_hash(sha,c,W)
for i in 0 ..< PAS {CK[i]=t[i]}
return 0
}
// calculate common key on server side
// Z=r.A - no time permits involved
static public func SERVER_KEY(_ sha:Int,_ Z:[UInt8],_ SST:[UInt8],_ W:[UInt8],_ H:[UInt8],_ HID:[UInt8],_ xID:[UInt8],_ xCID:[UInt8]?,_ SK:inout [UInt8]) -> Int
{
// var t=[UInt8](count:EFS,repeatedValue:0)
let sQ=ECP2.fromBytes(SST)
if sQ.is_infinity() {return INVALID_POINT}
let R=ECP.fromBytes(Z)
if R.is_infinity() {return INVALID_POINT}
var A=ECP.fromBytes(HID)
if A.is_infinity() {return INVALID_POINT}
var U:ECP
if xCID != nil
{U=ECP.fromBytes(xCID!)}
else
{U=ECP.fromBytes(xID)}
if U.is_infinity() {return INVALID_POINT}
let w=BIG.fromBytes(W)
let h=BIG.fromBytes(H)
A=PAIR.G1mul(A,h)
R.add(A)
U=PAIR.G1mul(U,w)
var g=PAIR.ate(sQ,R)
g=PAIR.fexp(g)
let c=g.trace()
let t=mpin_hash(sha,c,U)
for i in 0 ..< PAS {SK[i]=t[i]}
return 0
}
// return time since epoch
static public func GET_TIME() -> Int32
{
let date=Date()
return (Int32(date.timeIntervalSince1970))
}
// Generate Y = H(epoch, xCID/xID)
static public func GET_Y(_ sha:Int,_ TimeValue:Int32,_ xCID:[UInt8],_ Y:inout [UInt8])
{
let h = MPIN.hashit(sha,TimeValue,xCID)
let y = BIG.fromBytes(h)
let q=BIG(ROM.CURVE_Order)
y.mod(q)
if ROM.AES_S>0
{
y.mod2m(2*ROM.AES_S)
}
y.toBytes(&Y)
}
// One pass MPIN Client
static public func CLIENT(_ sha:Int,_ date:Int32,_ CLIENT_ID:[UInt8],_ RNG:RAND?,_ X:inout [UInt8],_ pin:Int32,_ TOKEN:[UInt8],_ SEC:inout [UInt8],_ xID:inout [UInt8]?,_ xCID:inout [UInt8]?,_ PERMIT:[UInt8],_ TimeValue:Int32,_ Y:inout [UInt8]) -> Int
{
var rtn=0
rtn = MPIN.CLIENT_1(sha,date,CLIENT_ID,RNG,&X,pin,TOKEN,&SEC,&xID,&xCID,PERMIT)
if rtn != 0 {return rtn}
if date==0 {MPIN.GET_Y(sha,TimeValue,xID!,&Y)}
else {MPIN.GET_Y(sha,TimeValue,xCID!,&Y)}
rtn = MPIN.CLIENT_2(X,Y,&SEC)
if (rtn != 0) {return rtn}
return 0
}
// One pass MPIN Server
static public func SERVER(_ sha:Int,_ date:Int32,_ HID:inout [UInt8],_ HTID:inout [UInt8]?,_ Y:inout [UInt8],_ SST:[UInt8],_ xID:[UInt8]?,_ xCID:[UInt8],_ SEC:[UInt8],_ E:inout [UInt8]?,_ F:inout [UInt8]?,_ CID:[UInt8],_ TimeValue:Int32) -> Int
{
var rtn=0
var pID:[UInt8]
if date == 0
{pID = xID!}
else
{pID = xCID}
SERVER_1(sha,date,CID,&HID,&HTID!);
GET_Y(sha,TimeValue,pID,&Y);
rtn = SERVER_2(date,HID,HTID!,Y,SST,xID,xCID,SEC,&E,&F);
if rtn != 0 {return rtn}
return 0
}
static public func printBinary(_ array: [UInt8])
{
for i in 0 ..< array.count
{
let h=String(format:"%02x",array[i])
print("\(h)", terminator: "")
}
print(" ");
}
}
| apache-2.0 | b8f91bb697249936cc51b6068b2af41e | 26.614646 | 255 | 0.494457 | 3.183806 | false | false | false | false |
mihaicris/digi-cloud | Digi Cloud/Controller/Actions/MoreActionsViewController.swift | 1 | 6536 | //
// MoreActionsViewController.swift
// Digi Cloud
//
// Created by Mihai Cristescu on 02/02/2017.
// Copyright © 2017 Mihai Cristescu. All rights reserved.
//
import UIKit
final class MoreActionsViewController: UITableViewController {
// MARK: - Properties
var onSelect: ((ActionType) -> Void)?
private let rootNode: Node
private var actions: [ActionType] = []
private let childs: Int
// MARK: - Initializers and Deinitializers
init(rootNode: Node, childs: Int) {
self.rootNode = rootNode
self.childs = childs
super.init(style: .plain)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Overridden Methods and Properties
override func viewDidLoad() {
super.viewDidLoad()
registerForNotificationCenter()
setupViews()
setupActions()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.preferredContentSize.width = 350
self.preferredContentSize.height = tableView.contentSize.height - 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return actions.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
cell.textLabel?.textColor = UIColor.defaultColor
switch actions[indexPath.row] {
case .sendDownloadLink:
cell.textLabel?.text = NSLocalizedString("Send Link", comment: "")
case .sendUploadLink:
cell.textLabel?.text = NSLocalizedString("Receive Files", comment: "")
case .makeShare:
cell.textLabel?.text = NSLocalizedString("Share", comment: "")
case .manageShare:
cell.textLabel?.text = NSLocalizedString("Manage Share", comment: "")
case .shareInfo:
cell.textLabel?.text = NSLocalizedString("See Share Members", comment: "")
case .bookmark:
cell.textLabel?.text = self.rootNode.bookmark == nil
? NSLocalizedString("Add Bookmark", comment: "")
: NSLocalizedString("Remove Bookmark", comment: "")
case .createFolder:
cell.textLabel?.text = NSLocalizedString("Create Folder", comment: "")
case .selectionMode:
cell.textLabel?.text = NSLocalizedString("Select Mode", comment: "")
default:
break
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.dismiss(animated: true) {
self.onSelect?(self.actions[indexPath.row])
}
}
// MARK: - Helper Functions
private func registerForNotificationCenter() {
NotificationCenter.default.addObserver(
self,
selector: #selector(handleCancel),
name: .UIApplicationWillResignActive,
object: nil)
}
private func setupViews() {
if navigationController != nil {
title = NSLocalizedString("More actions", comment: "")
let closeButton: UIBarButtonItem = {
let button = UIBarButtonItem(title: NSLocalizedString("Close", comment: ""), style: .done, target: self, action: #selector(handleCancel))
return button
}()
self.navigationItem.rightBarButtonItem = closeButton
} else {
let headerView: UIView = {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 40))
view.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
return view
}()
let titleName: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .center
label.text = NSLocalizedString("More actions", comment: "")
label.font = UIFont.boldSystemFont(ofSize: 16)
return label
}()
let separator: UIView = {
let view = UIView()
view.backgroundColor = UIColor(white: 0.8, alpha: 1)
return view
}()
headerView.addSubview(titleName)
titleName.centerXAnchor.constraint(equalTo: headerView.centerXAnchor).isActive = true
titleName.centerYAnchor.constraint(equalTo: headerView.centerYAnchor).isActive = true
headerView.addSubview(separator)
headerView.addConstraints(with: "H:|[v0]|", views: separator)
headerView.addConstraints(with: "V:[v0(\(1 / UIScreen.main.scale))]|", views: separator)
tableView.rowHeight = AppSettings.tableViewRowHeight
tableView.tableHeaderView = headerView
}
tableView.isScrollEnabled = false
tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
}
private func setupActions() {
guard let mount = rootNode.mount else {
dismiss(animated: false, completion: nil)
return
}
if mount.permissions.createLink {
actions.append(.sendDownloadLink)
}
if mount.permissions.createReceiver {
actions.append(.sendUploadLink)
}
if mount.type == "device" {
if mount.root == nil && rootNode.mountPath == "/" {
if mount.users.count > 1 {
actions.append(.manageShare)
} else {
actions.append(.makeShare)
}
}
} else if mount.type == "export" {
if rootNode.mountPath == "/" {
actions.append(.manageShare)
}
} else if rootNode.mountPath == "/" {
if mount.permissions.mount {
actions.append(.manageShare)
} else {
actions.append(.shareInfo)
}
}
actions.append(.bookmark)
if mount.canWrite {
actions.append(.createFolder)
}
if childs > 1 {
actions.append(.selectionMode)
}
}
@objc private func handleCancel() {
dismiss(animated: true, completion: nil)
}
}
| mit | 560716986940c1d5764591bbca59379c | 29.680751 | 153 | 0.58378 | 5.261675 | false | false | false | false |
jengelsma/cis657-summer2016-class-demos | Lecture08-PuppyFlixDemo/Lecture08-PuppyFlixDemo/DetailViewController.swift | 1 | 3106 | //
// DetailViewController.swift
// Lecture08-PuppyFlixDemo
//
// Created by Jonathan Engelsma on 5/31/16.
// Copyright © 2016 Jonathan Engelsma. All rights reserved.
//
import UIKit
import TUSafariActivity
class DetailViewController: UIViewController {
@IBOutlet weak var videoTitle: UILabel!
@IBOutlet weak var videoImage: UIImageView!
@IBOutlet weak var videoDescription: UITextView!
var detailItem: Dictionary<String, AnyObject>? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail = self.detailItem {
if let snippet = detail["snippet"] as? Dictionary<String,AnyObject> {
if let title = self.videoTitle {
title.text = snippet["title"] as? String
}
if let descript = self.videoDescription {
descript.text = snippet["description"] as? String
}
self.videoImage?.image = UIImage(named:"YouTubeIcon")
if let images = snippet["thumbnails"] as? Dictionary<String,AnyObject> {
if let firstImage = images["medium"] as? Dictionary<String,AnyObject> {
if let imageUrl : String = firstImage["url"] as! String {
self.videoImage?.loadImageFromURL(NSURL(string:imageUrl), placeholderImage: self.videoImage?.image, cachingKey: imageUrl)
}
}
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
let safari : UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Action, target: self, action: #selector(DetailViewController.share))
self.navigationItem.rightBarButtonItems = [safari]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func share()
{
if let detail = self.detailItem {
if let ytId = detail["id"] as? NSDictionary {
if let videoId = ytId["videoId"] as? String {
let url = NSURL(string: "http://www.youtube.com/watch?v=" + videoId )
let msg = "Check out my favorite puppy video on YouTube"
let items = [ msg, url! ]
let activity = TUSafariActivity()
//let avc = UIActivityViewController(activityItems: items, applicationActivities: nil)
let avc = UIActivityViewController(activityItems: items, applicationActivities: [activity])
self.navigationController?.presentViewController(avc, animated: true, completion: nil)
}
}
}
}
}
| mit | f21ccab9f48f8519b3436f2eee0135ca | 33.5 | 166 | 0.57037 | 5.390625 | false | false | false | false |
Restofire/Restofire-Gloss | Tests/ServiceSpec/FloatService+GETSpec.swift | 1 | 1596 | // _____ ____ __.
// / _ \ _____ _______ | |/ _|____ ___.__.
// / /_\ \\__ \\_ __ \ | < \__ \< | |
// / | \/ __ \| | \/ | | \ / __ \\___ |
// \____|__ (____ /__| |____|__ (____ / ____|
// \/ \/ \/ \/\/
//
// Copyright (c) 2016 RahulKatariya. All rights reserved.
//
import Quick
import Nimble
import Alamofire
class FloatGETServiceSpec: ServiceSpec {
override func spec() {
describe("FloatGETService") {
it("executeTask") {
let actual: Float = 12345.6789
var expected: Float!
FloatGETService().executeTask() {
if let value = $0.result.value {
expected = value
}
}
expect(expected).toEventually(equal(actual), timeout: self.timeout, pollInterval: self.pollInterval)
}
it("executeRequestOperation") {
let actual: Float = 12345.6789
var expected: Float!
let requestOperation = FloatGETService().requestOperation() {
if let value = $0.result.value {
expected = value
}
}
requestOperation.start()
expect(expected).toEventually(equal(actual), timeout: self.timeout, pollInterval: self.pollInterval)
}
}
}
}
| mit | 5ee4007321d01d1d3675a90a640dfbd5 | 28.018182 | 116 | 0.379073 | 4.707965 | false | false | false | false |
yonadev/yona-app-ios | Yona/Yona/PinResetRequestManager.swift | 1 | 8383 | //
// pinResetRequestManager.swift
// Yona
//
// Created by Ben Smith on 28/04/16.
// Copyright © 2016 Yona. All rights reserved.
//
import Foundation
//MARK: - New Device Requests APIService
class PinResetRequestManager {
let APIService = APIServiceManager.sharedInstance
let APIUserRequestManager = UserRequestManager.sharedInstance
static let sharedInstance = PinResetRequestManager()
fileprivate init() {}
/**
Generic method to request, verify or clear pin requests
- parameter httpmethodParam: httpMethods, The httpmethod enum, POST GET etc
- parameter pinRequestType: pinRequestTypes, enum of different pin requests depending on if we verify, reset or clear a pin
- parameter body: BodyDataDictionary?, body that is needed in a POST call, can be nil
- parameter onCompletion: APIPinResetResponse, Sends back the pin ISO code (optional) and also the server messages and success or fail of the request
*/
fileprivate func pinResetHelper(_ httpmethodParam: httpMethods, pinRequestType: pinRequestTypes, body: BodyDataDictionary?, onCompletion: @escaping APIPinResetResponse){
switch pinRequestType
{
case .resetRequest:
UserRequestManager.sharedInstance.getUser(GetUserRequest.allowed) { (success, message, code, user) in
//success so get the user?
if success {
if let path = user?.requestPinResetLink {
self.APIService.callRequestWithAPIServiceResponse(nil, path: path, httpMethod: httpmethodParam) { (success, json, error) in
if success {
if let jsonUnwrap = json,
let pincode = jsonUnwrap[YonaConstants.jsonKeys.pinResetDelay] as? PinCode {
onCompletion(true, pincode, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error))
}
} else {
onCompletion(false, nil, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error))
}
}
} else {
onCompletion(false, nil , YonaConstants.serverMessages.FailedToGetResetPinLink, String(responseCodes.internalErrorCode.rawValue))
}
} else {
onCompletion(false, nil , YonaConstants.serverMessages.FailedToRetrieveUpdateUserDetails, String(responseCodes.internalErrorCode.rawValue))
}
}
case .resendResetRequest:
UserRequestManager.sharedInstance.getUser(GetUserRequest.allowed) { (success, message, code, user) in
//success so get the user?
if success {
if let path = user?.resendRequestPinResetLinks{
self.APIService.callRequestWithAPIServiceResponse(body, path: path, httpMethod: httpmethodParam) { (success, json, error) in
onCompletion(success, nil, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error))
}
} else {
onCompletion(false, nil , YonaConstants.serverMessages.FailedToGetResendResetRequestLink, String(responseCodes.internalErrorCode.rawValue))
}
} else {
onCompletion(false, nil , YonaConstants.serverMessages.FailedToRetrieveUpdateUserDetails, String(responseCodes.internalErrorCode.rawValue))
}
}
case .verifyRequest:
UserRequestManager.sharedInstance.getUser(GetUserRequest.allowed) { (success, message, code, user) in
//success so get the user?
if success {
if let path = user?.requestPinVerifyLink{
self.APIService.callRequestWithAPIServiceResponse(body, path: path, httpMethod: httpmethodParam) { (success, json, error) in
onCompletion(success, nil, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error))
}
} else {
onCompletion(false, nil , YonaConstants.serverMessages.FailedToGetResetPinVerifyLink, String(responseCodes.internalErrorCode.rawValue))
}
} else {
onCompletion(false, nil , YonaConstants.serverMessages.FailedToRetrieveUpdateUserDetails, String(responseCodes.internalErrorCode.rawValue))
}
}
case .clearRequest:
UserRequestManager.sharedInstance.getUser(GetUserRequest.notAllowed) { (success, message, code, user) in
//success so get the user?
if success {
if let path = user?.requestPinClearLink{
self.APIService.callRequestWithAPIServiceResponse(nil, path: path, httpMethod: httpmethodParam) { (success, json, error) in
onCompletion(success, nil, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error))
}
} else {
onCompletion(false, nil , YonaConstants.serverMessages.FailedToGetResetPinVerifyLink, String(responseCodes.internalErrorCode.rawValue))
}
}
}
}
}
/**
Resends the pin reset request, clears and requests making it simpler
- parameter onCompletion: APIPinResetResponse, Returns the pincode in ISO (if available as optional) format so UI knows how long the user has to wait, also success, fail and server messages
*/
func pinResendResetRequest(_ onCompletion: @escaping APIPinResetResponse) {
pinResetHelper(httpMethods.post, pinRequestType: pinRequestTypes.resendResetRequest, body: nil) { (success, ISOCode, serverMessage, serverCode) in
onCompletion(success, ISOCode, serverMessage, serverCode)
}
}
/**
Resets the pin when the user enters their pin (password) wrong 5 times
- parameter onCompletion: APIPinResetResponse, Returns the pincode in ISO (if available as optional) format so UI knows how long the user has to wait, also success, fail and server messages
*/
func pinResetRequest(_ onCompletion: @escaping APIPinResetResponse) {
pinResetHelper(httpMethods.post, pinRequestType: pinRequestTypes.resetRequest, body: nil) { (success, ISOCode, serverMessage, serverCode) in
onCompletion(success, ISOCode, serverMessage, serverCode)
}
}
/**
Called when the user enters the confirmation code sent to them after 24 hours so that the reset password can be verified
- parameter body: BodyDataDictionary, Body containing the confirmation code sent by text to user
- parameter onCompletion: APIPinResetResponse, Returns the pincode in ISO (if available as optional) format so UI knows how long the user has to wait, also success, fail and server messages
*/
func pinResetVerify(_ body: BodyDataDictionary, onCompletion: @escaping APIPinResetResponse) {
pinResetHelper(httpMethods.post, pinRequestType: pinRequestTypes.verifyRequest, body: body) { (success, nil, serverMessage, serverCode) in
onCompletion(success, nil, serverMessage, serverCode)
}
}
/**
Called after a successful verify message so that the pin reset is cleared
- parameter onCompletion: APIPinResetResponse, Returns the pincode in ISO (if available as optional) format so UI knows how long the user has to wait, also success, fail and server messages
*/
func pinResetClear(_ onCompletion: @escaping APIPinResetResponse) {
pinResetHelper(httpMethods.post, pinRequestType: pinRequestTypes.clearRequest, body: nil) { (success, nil, serverMessage, serverCode) in
if success {
onCompletion(true, nil, serverMessage, serverCode)
} else {
onCompletion(false, nil, serverMessage, serverCode)
}
}
}
}
| mpl-2.0 | 5b1aa968aabae419810be207a22bbb18 | 55.255034 | 194 | 0.641136 | 5.792674 | false | false | false | false |
ibm-bluemix-mobile-services/bms-clientsdk-swift-security | Source/mca/api/MCAAuthorizationManager.swift | 1 | 19768 | /*
* Copyright 2015 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 BMSCore
import BMSAnalyticsAPI
#if swift (>=3.0)
public class MCAAuthorizationManager : AuthorizationManager {
/// Default scheme to use (default is https)
public static var defaultProtocol: String = HTTPS_SCHEME
public static let HTTP_SCHEME = "http"
public static let HTTPS_SCHEME = "https"
public static let CONTENT_TYPE = "Content-Type"
private static let logger = Logger.logger(name: Logger.bmsLoggerPrefix + "MCAAuthorizationManager")
internal var preferences:AuthorizationManagerPreferences
//lock constant
private var lockQueue = DispatchQueue(label: "MCAAuthorizationManagerQueue", attributes: DispatchQueue.Attributes.concurrent)
private var challengeHandlers:[String:ChallengeHandler]
// Specifies the bluemix region of the MCA service instance
public private(set) var bluemixRegion: String?
// Specifies the tenant id of the MCA service instance
public private(set) var tenantId: String?
/**
- returns: The singelton instance
*/
public static let sharedInstance = MCAAuthorizationManager()
var processManager : AuthorizationProcessManager
/**
The intializer for the `MCAAuthorizationManager` class.
- parameter tenantId: The tenant id of the MCA service instance
- parameter bluemixRegion: The region where your MCA service instance is hosted. Use one of the `BMSClient.REGION` constants.
*/
public func initialize (tenantId: String? = nil, bluemixRegion: String? = nil) {
self.tenantId = tenantId != nil ? tenantId : BMSClient.sharedInstance.bluemixAppGUID
self.bluemixRegion = bluemixRegion != nil ? bluemixRegion: BMSClient.sharedInstance.bluemixRegion
}
/**
- returns: The locally stored authorization header or nil if the value does not exist.
*/
public var cachedAuthorizationHeader:String? {
get{
var returnedValue:String? = nil
lockQueue.sync(flags: .barrier, execute: {
if let accessToken = self.preferences.accessToken.get(), let idToken = self.preferences.idToken.get() {
returnedValue = "\(BMSSecurityConstants.BEARER) \(accessToken) \(idToken)"
}
})
return returnedValue
}
}
/**
- returns: User identity
*/
public var userIdentity:UserIdentity? {
get{
let userIdentityJson = preferences.userIdentity.getAsMap()
return MCAUserIdentity(map: userIdentityJson)
}
}
/**
- returns: Device identity
*/
public var deviceIdentity:DeviceIdentity {
get{
let deviceIdentityJson = preferences.deviceIdentity.getAsMap()
return MCADeviceIdentity(map: deviceIdentityJson)
}
}
/**
- returns: Application identity
*/
public var appIdentity:AppIdentity {
get{
let appIdentityJson = preferences.appIdentity.getAsMap()
return MCAAppIdentity(map: appIdentityJson)
}
}
private init() {
self.preferences = AuthorizationManagerPreferences()
processManager = AuthorizationProcessManager(preferences: preferences)
self.challengeHandlers = [String:ChallengeHandler]()
challengeHandlers = [String:ChallengeHandler]()
if preferences.deviceIdentity.get() == nil {
preferences.deviceIdentity.set(MCADeviceIdentity().jsonData as [String:Any])
}
if preferences.appIdentity.get() == nil {
preferences.appIdentity.set(MCAAppIdentity().jsonData as [String:Any])
}
self.tenantId = BMSClient.sharedInstance.bluemixAppGUID
self.bluemixRegion = BMSClient.sharedInstance.bluemixRegion
}
/**
A response is an OAuth error response only if,
1. it's status is 401 or 403.
2. The value of the "WWW-Authenticate" header contains 'Bearer'.
- Parameter httpResponse - Response to check the authorization conditions for.
- returns: True if the response satisfies both conditions
*/
public func isAuthorizationRequired(for httpResponse: Response) -> Bool {
if let header = httpResponse.headers![caseInsensitive : BMSSecurityConstants.WWW_AUTHENTICATE_HEADER], let authHeader : String = header as? String {
guard let statusCode = httpResponse.statusCode else {
return false
}
return isAuthorizationRequired(for: statusCode, httpResponseAuthorizationHeader: authHeader)
}
return false
}
/**
Check if the params came from response that requires authorization
- Parameter statusCode - Status code of the response
- Parameter responseAuthorizationHeader - Response header
- returns: True if status is 401 or 403 and The value of the header contains 'Bearer'
*/
public func isAuthorizationRequired(for statusCode: Int, httpResponseAuthorizationHeader responseAuthorizationHeader: String) -> Bool {
if (statusCode == 401 || statusCode == 403) &&
responseAuthorizationHeader.lowercased().contains(BMSSecurityConstants.BEARER.lowercased()) &&
responseAuthorizationHeader.lowercased().contains(BMSSecurityConstants.AUTH_REALM.lowercased()) {
return true
}
return false
}
private func clearCookie(cookieName name : String) {
let cookiesStorage = HTTPCookieStorage.shared
if let cookies = cookiesStorage.cookies {
let filteredCookies = cookies.filter() {$0.name == name}
for cookie in filteredCookies {
cookiesStorage.deleteCookie(cookie)
}
}
}
/**
Clear the local stored authorization data
*/
public func clearAuthorizationData() {
preferences.userIdentity.clear()
preferences.idToken.clear()
preferences.accessToken.clear()
processManager.authorizationFailureCount = 0
clearCookie(cookieName: "JSESSIONID")
clearCookie(cookieName: "LtpaToken2")
}
/**
Adds the cached authorization header to the given URL connection object.
If the cached authorization header is equal to nil then this operation has no effect.
- Parameter request - The request to add the header to.
*/
public func addCachedAuthorizationHeader(_ request: NSMutableURLRequest) {
addAuthorizationHeader(request, header: cachedAuthorizationHeader)
}
private func addAuthorizationHeader(_ request: NSMutableURLRequest, header:String?) {
guard let unWrappedHeader = header else {
return
}
request.setValue(unWrappedHeader, forHTTPHeaderField: BMSSecurityConstants.AUTHORIZATION_HEADER)
}
/**
Invoke process for obtaining authorization header.
*/
public func obtainAuthorization(completionHandler: BMSCompletionHandler?) {
(lockQueue).async(flags: .barrier, execute: {
self.processManager.startAuthorizationProcess(completionHandler)
})
}
/**
Registers a delegate that will handle authentication for the specified realm.
- Parameter delegate - The delegate that will handle authentication challenges
- Parameter realm - The realm name
*/
public func registerAuthenticationDelegate(_ delegate: AuthenticationDelegate, realm: String) {
guard !realm.isEmpty else {
MCAAuthorizationManager.logger.error(message: "The realm name can't be empty")
return;
}
let handler = ChallengeHandler(realm: realm, authenticationDelegate: delegate)
challengeHandlers[realm] = handler
}
/**
Unregisters the authentication delegate for the specified realm.
- Parameter realm - The realm name
*/
public func unregisterAuthenticationDelegate(_ realm: String) {
guard !realm.isEmpty else {
return
}
challengeHandlers.removeValue(forKey: realm)
}
/**
Returns the current persistence policy
- returns: The current persistence policy
*/
public func authorizationPersistencePolicy() -> PersistencePolicy {
return preferences.persistencePolicy.get()
}
/**
Sets a persistence policy
- parameter policy - The policy to be set
*/
public func setAuthorizationPersistencePolicy(_ policy: PersistencePolicy) {
if preferences.persistencePolicy.get() != policy {
preferences.persistencePolicy.set(policy, shouldUpdateTokens: true);
}
}
/**
Returns a challenge handler for realm
- parameter realm - The realm for which a challenge handler is required.
- returns: Challenge handler for the input's realm.
*/
public func challengeHandlerForRealm(_ realm:String) -> ChallengeHandler?{
return challengeHandlers[realm]
}
/**
Logs out user from MCA
- parameter completionHandler - This is an optional parameter. A completion handler that the app is calling this function wants to be called.
*/
public func logout(_ completionHandler: BMSCompletionHandler?){
self.clearAuthorizationData()
processManager.logout(completionHandler)
}
}
#else
public class MCAAuthorizationManager : AuthorizationManager {
/// Default scheme to use (default is https)
public static var defaultProtocol: String = HTTPS_SCHEME
public static let HTTP_SCHEME = "http"
public static let HTTPS_SCHEME = "https"
public static let CONTENT_TYPE = "Content-Type"
private static let logger = Logger.logger(name: Logger.bmsLoggerPrefix + "MCAAuthorizationManager")
internal var preferences:AuthorizationManagerPreferences
//lock constant
private var lockQueue = dispatch_queue_create("MCAAuthorizationManagerQueue", DISPATCH_QUEUE_CONCURRENT)
private var challengeHandlers:[String:ChallengeHandler]
// Specifies the bluemix region of the MCA service instance
public private(set) var bluemixRegion: String?
// Specifies the tenant id of the MCA service instance
public private(set) var tenantId: String?
/**
- returns: The singelton instance
*/
public static let sharedInstance = MCAAuthorizationManager()
var processManager : AuthorizationProcessManager
/**
The intializer for the `MCAAuthorizationManager` class.
- parameter tenantId: The tenant id of the MCA service instance
- parameter bluemixRegion: The region where your MCA service instance is hosted. Use one of the `BMSClient.REGION` constants.
*/
public func initialize (tenantId tenantId: String? = nil, bluemixRegion: String? = nil) {
self.tenantId = tenantId != nil ? tenantId : BMSClient.sharedInstance.bluemixAppGUID
self.bluemixRegion = bluemixRegion != nil ? bluemixRegion: BMSClient.sharedInstance.bluemixRegion
}
/**
- returns: The locally stored authorization header or nil if the value does not exist.
*/
public var cachedAuthorizationHeader:String? {
get{
var returnedValue:String? = nil
dispatch_barrier_sync(lockQueue){
if let accessToken = self.preferences.accessToken.get(), idToken = self.preferences.idToken.get() {
returnedValue = "\(BMSSecurityConstants.BEARER) \(accessToken) \(idToken)"
}
}
return returnedValue
}
}
/**
- returns: User identity
*/
public var userIdentity:UserIdentity? {
get{
let userIdentityJson = preferences.userIdentity.getAsMap()
return MCAUserIdentity(map: userIdentityJson)
}
}
/**
- returns: Device identity
*/
public var deviceIdentity:DeviceIdentity {
get{
let deviceIdentityJson = preferences.deviceIdentity.getAsMap()
return MCADeviceIdentity(map: deviceIdentityJson)
}
}
/**
- returns: Application identity
*/
public var appIdentity:AppIdentity {
get{
let appIdentityJson = preferences.appIdentity.getAsMap()
return MCAAppIdentity(map: appIdentityJson)
}
}
private init() {
self.preferences = AuthorizationManagerPreferences()
processManager = AuthorizationProcessManager(preferences: preferences)
self.challengeHandlers = [String:ChallengeHandler]()
challengeHandlers = [String:ChallengeHandler]()
if preferences.deviceIdentity.get() == nil {
preferences.deviceIdentity.set(MCADeviceIdentity().jsonData)
}
if preferences.appIdentity.get() == nil {
preferences.appIdentity.set(MCAAppIdentity().jsonData)
}
self.tenantId = BMSClient.sharedInstance.bluemixAppGUID
self.bluemixRegion = BMSClient.sharedInstance.bluemixRegion
}
/**
A response is an OAuth error response only if,
1. it's status is 401 or 403.
2. The value of the "WWW-Authenticate" header starts with 'Bearer'.
3. The value of the "WWW-Authenticate" header contains "imfAuthentication"
- Parameter httpResponse - Response to check the authorization conditions for.
- returns: True if the response satisfies both conditions
*/
public func isAuthorizationRequired(for httpResponse: Response) -> Bool {
if let header = httpResponse.headers![caseInsensitive : BMSSecurityConstants.WWW_AUTHENTICATE_HEADER], authHeader : String = header as? String {
guard let statusCode = httpResponse.statusCode else {
return false
}
return isAuthorizationRequired(for: statusCode, httpResponseAuthorizationHeader: authHeader)
}
return false
}
/**
Check if the params came from response that requires authorization
- Parameter statusCode - Status code of the response
- Parameter responseAuthorizationHeader - Response header
- returns: True if status is 401 or 403 and The value of the header contains 'Bearer'
*/
public func isAuthorizationRequired(for statusCode: Int, httpResponseAuthorizationHeader responseAuthorizationHeader: String) -> Bool {
if (statusCode == 401 || statusCode == 403) && responseAuthorizationHeader.lowercaseString.containsString(BMSSecurityConstants.BEARER.lowercaseString) &&
responseAuthorizationHeader.lowercaseString.containsString(BMSSecurityConstants.AUTH_REALM.lowercaseString) {
return true
}
return false
}
private func clearCookie(cookieName name : String) {
let cookiesStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
if let cookies = cookiesStorage.cookies {
let filteredCookies = cookies.filter() {$0.name == name}
for cookie in filteredCookies {
cookiesStorage.deleteCookie(cookie)
}
}
}
/**
Clear the local stored authorization data
*/
public func clearAuthorizationData() {
preferences.userIdentity.clear()
preferences.idToken.clear()
preferences.accessToken.clear()
processManager.authorizationFailureCount = 0
clearCookie(cookieName: "JSESSIONID")
clearCookie(cookieName: "LtpaToken2")
}
/**
Adds the cached authorization header to the given URL connection object.
If the cached authorization header is equal to nil then this operation has no effect.
- Parameter request - The request to add the header to.
*/
public func addCachedAuthorizationHeader(request: NSMutableURLRequest) {
addAuthorizationHeader(request, header: cachedAuthorizationHeader)
}
private func addAuthorizationHeader(request: NSMutableURLRequest, header:String?) {
guard let unWrappedHeader = header else {
return
}
request.setValue(unWrappedHeader, forHTTPHeaderField: BMSSecurityConstants.AUTHORIZATION_HEADER)
}
/**
Invoke process for obtaining authorization header.
*/
public func obtainAuthorization(completionHandler completionHandler: BMSCompletionHandler?) {
dispatch_barrier_async(lockQueue){
self.processManager.startAuthorizationProcess(completionHandler)
}
}
/**
Registers a delegate that will handle authentication for the specified realm.
- Parameter delegate - The delegate that will handle authentication challenges
- Parameter realm - The realm name
*/
public func registerAuthenticationDelegate(delegate: AuthenticationDelegate, realm: String) {
guard !realm.isEmpty else {
MCAAuthorizationManager.logger.error(message: "The realm name can't be empty")
return;
}
let handler = ChallengeHandler(realm: realm, authenticationDelegate: delegate)
challengeHandlers[realm] = handler
}
/**
Unregisters the authentication delegate for the specified realm.
- Parameter realm - The realm name
*/
public func unregisterAuthenticationDelegate(realm: String) {
guard !realm.isEmpty else {
return
}
challengeHandlers.removeValueForKey(realm)
}
/**
Returns the current persistence policy
- returns: The current persistence policy
*/
public func authorizationPersistencePolicy() -> PersistencePolicy {
return preferences.persistencePolicy.get()
}
/**
Sets a persistence policy
- parameter policy - The policy to be set
*/
public func setAuthorizationPersistencePolicy(policy: PersistencePolicy) {
if preferences.persistencePolicy.get() != policy {
preferences.persistencePolicy.set(policy, shouldUpdateTokens: true);
}
}
/**
Returns a challenge handler for realm
- parameter realm - The realm for which a challenge handler is required.
- returns: Challenge handler for the input's realm.
*/
public func challengeHandlerForRealm(realm:String) -> ChallengeHandler?{
return challengeHandlers[realm]
}
/**
Logs out user from MCA
- parameter completionHandler - This is an optional parameter. A completion handler that the app is calling this function wants to be called.
*/
public func logout(completionHandler: BMSCompletionHandler?){
self.clearAuthorizationData()
processManager.logout(completionHandler)
}
}
#endif
| apache-2.0 | f3da42923ff64d1234be86717ff1edbb | 33.996454 | 161 | 0.659185 | 5.719502 | false | false | false | false |
maxbritto/cours-ios11-swift4 | Apprendre/Objectif 2/Convertisseur/Convertisseur/ViewController.swift | 1 | 2286 | //
// ViewController.swift
// Convertisseur
//
// Created by Maxime Britto on 25/07/2017.
// Copyright © 2017 Purple Giraffe. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var ui_inputValueType: UISegmentedControl!
@IBOutlet weak var ui_inputValueField: UITextField!
@IBOutlet weak var ui_outputMeterLabel: UILabel!
@IBOutlet weak var ui_outputCentimeterLabel: UILabel!
@IBOutlet weak var ui_outputInchesLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func getInputMeterValue() -> Double? {
let inputMeters:Double?
if let inputString:String = ui_inputValueField.text,
let inputDouble:Double = Double(inputString) {
switch ui_inputValueType.selectedSegmentIndex {
case 0: //m
inputMeters = inputDouble
case 1: //cm
inputMeters = UnitLength.centimeters.converter.baseUnitValue(fromValue: inputDouble)
case 2: //inches
inputMeters = UnitLength.inches.converter.baseUnitValue(fromValue: inputDouble)
default:
inputMeters = nil
}
} else {
inputMeters = nil
}
return inputMeters
}
func convertInputValue() {
if let inputMeters:Double = getInputMeterValue() {
ui_outputMeterLabel.text = "\(inputMeters) m"
ui_outputInchesLabel.text = "\(UnitLength.inches.converter.value(fromBaseUnitValue: inputMeters)) pouces"
ui_outputCentimeterLabel.text = "\(UnitLength.centimeters.converter.value(fromBaseUnitValue: inputMeters)) cm"
} else {
ui_outputCentimeterLabel.text = nil
ui_outputInchesLabel.text = nil
ui_outputMeterLabel.text = nil
}
}
@IBAction func inputValueTypeChanged() {
convertInputValue()
}
@IBAction func inputValueChanged() {
convertInputValue()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 3c3a3f04baddbf705360ab25d983c984 | 30.30137 | 122 | 0.628884 | 4.989083 | false | false | false | false |
JeffESchmitz/RideNiceRide | RideNiceRide/Constants.swift | 1 | 940 | //
// Constants.swift
// RideNiceRide
//
// Created by Jeff Schmitz on 1/27/17.
// Copyright © 2017 Jeff Schmitz. All rights reserved.
//
import Foundation
//swiftlint:disable variable_name
//swiftlint:disable type_name
//swiftlint:disable type_body_length
//swiftlint:disable nesting
struct K {
struct Map {
static let Latitude = "MapLatitude"
static let LatitudeDelta = "MapLatitudeDelta"
static let Longitude = "MapLongitude"
static let LongitudeDelta = "MapLongitudeDelta"
}
struct HubwayAPI {
static let hubwayURL = "https://feeds.thehubway.com/stations/stations.json"
static let hubwayProfileUrlString = "https://secure.thehubway.com/profile/"
}
struct GoogleServices {
static let APIKey = "AIzaSyBCHjbd41ZVXvy3HBu-J1c8rn6d3Or6AFk"
}
}
//swiftlint:enable nesting
//swiftlint:enable type_body_length
//swiftlint:enable type_name
//swiftlint:enable variable_name
| mit | d0b804fd410a04ff080fac293df67f8a | 25.828571 | 79 | 0.72098 | 3.625483 | false | false | false | false |
jianghongbing/APIReferenceDemo | UIKit/UIGestureRecognizer/UIGestureRecognizer/TableViewController.swift | 1 | 3136 | //
// TableViewController.swift
// UIGestureRecognizer
//
// Created by pantosoft on 2018/7/23.
// Copyright © 2018年 jianghongbing. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 3ee4367881c67bbce9109406791a2abb | 31.978947 | 136 | 0.672199 | 5.373928 | false | false | false | false |
t-ae/ImageTrimmer | ImageTrimmer/etc/Util.swift | 1 | 4309 | import Foundation
import Cocoa
import RxSwift
import Swim
func saveImage(image: NSImage, directory: String, fileNumber: Int) -> Bool {
let directoryUrl = URL(fileURLWithPath: directory, isDirectory: true)
let url = URL(fileURLWithPath: "\(fileNumber).png", isDirectory: false, relativeTo: directoryUrl)
let data = image.tiffRepresentation!
let b = NSBitmapImageRep.imageReps(with: data).first! as! NSBitmapImageRep
let pngData = b.representation(using: NSBitmapImageRep.FileType.png, properties: [:])!
do {
try pngData.write(to: url, options: Data.WritingOptions.atomic)
Swift.print("save: \(url)")
return true
} catch(let e) {
showAlert("failed to write: \(url) \n\(e.localizedDescription)")
return false
}
}
enum SelectDirectoryResult {
case ok(URL?)
case cancel
}
func selectDirectory(title: String? = nil, url: URL? = nil) -> Observable<SelectDirectoryResult> {
return Observable.create { observer in
let panel = NSOpenPanel()
panel.title = title
panel.allowsMultipleSelection = false
panel.canCreateDirectories = true
panel.canChooseDirectories = true
panel.canChooseFiles = false
panel.directoryURL = url
panel.begin() { result in
switch result {
case NSApplication.ModalResponse.OK:
observer.onNext(.ok(panel.urls.first))
case NSApplication.ModalResponse.cancel:
observer.onNext(.cancel)
default:
fatalError("never reaches here.")
}
observer.onCompleted()
}
return Disposables.create {
panel.close()
}
}
}
extension NSImage {
var bitmapRep: NSBitmapImageRep? {
for rep in representations {
guard let rep = rep as? NSBitmapImageRep else {
continue
}
return rep
}
return nil
}
}
extension Array {
func partition(cvarRate: Float) -> (Array<Element>, Array<Element>) {
let shuffled = self.shuffled()
let cvarCount = Int(cvarRate * Float(shuffled.count))
return (Array(shuffled[cvarCount..<self.count]),
Array(shuffled[0..<cvarCount]))
}
func shuffled() -> Array<Element> {
var array = self
for i in 0..<array.count {
let ub = UInt32(array.count - i)
let d = Int(arc4random_uniform(ub))
let tmp = array[i]
array[i] = array[i+d]
array[i+d] = tmp
}
return array
}
func combine<T, R>(with other: Array<T>, f: (Element, T)->R) -> Array<R> {
return self.flatMap { a in
other.map { f(a, $0) }
}
}
func zip<T,R>(with other: Array<T>, f: (Element, T)->R) -> Array<R> {
return Swift.zip(self, other).map(f)
}
}
func zip3<T1,T2, T3, R>(a: [T1], b: [T2], c: [T3], f:(T1, T2, T3)->R) -> [R] {
return a.zip(with: b, f: { ($0, $1) }).zip(with: c, f: { f($0.0, $0.1, $1) })
}
func showAlert(_ message: String) {
let alert = NSAlert()
alert.messageText = message
alert.runModal()
}
func linspace(minimum: Double, maximum: Double, count: Int) -> StrideTo<Double> {
let strider = (maximum - minimum) / Double(count)
return stride(from: minimum, to: maximum, by: strider)
}
// For observable conversion
func intToStr(_ i: Int) -> String {
return "\(i)"
}
func strToObservableInt(_ str: String?) -> Observable<Int> {
return str.flatMap(Int.init).flatMap(Observable.just) ?? Observable.empty()
}
// CATransform3D
func * (lhs: CATransform3D, rhs: CATransform3D) -> CATransform3D {
return CATransform3DConcat(lhs, rhs)
}
func *= (lhs: inout CATransform3D, rhs: CATransform3D) {
lhs = lhs * rhs
}
func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
func * (lhs: CGPoint, rhs: CGFloat) -> CGPoint {
return CGPoint(x: lhs.x * rhs, y: lhs.y * rhs)
}
func / (lhs: CGPoint, rhs: CGFloat) -> CGPoint {
return CGPoint(x: lhs.x / rhs, y: lhs.y / rhs)
}
| mit | 0d1e3c9a0f91930bf37fffecd9aa3c1c | 27.726667 | 101 | 0.585055 | 3.733969 | false | false | false | false |
loudnate/LoopKit | LoopKitUI/Views/TextButtonTableViewCell.swift | 2 | 1251 | //
// TextButtonTableViewCell.swift
// LoopKitUI
//
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import UIKit
open class TextButtonTableViewCell: LoadingTableViewCell {
override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
textLabel?.tintAdjustmentMode = .automatic
textLabel?.textColor = tintColor
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public var isEnabled = true {
didSet {
tintAdjustmentMode = isEnabled ? .normal : .dimmed
selectionStyle = isEnabled ? .default : .none
}
}
open override func tintColorDidChange() {
super.tintColorDidChange()
textLabel?.textColor = tintColor
}
open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
textLabel?.textColor = tintColor
}
open override func prepareForReuse() {
super.prepareForReuse()
textLabel?.textAlignment = .natural
tintColor = nil
isEnabled = true
}
}
| mit | 777bdd2d2d9328359a814367ec8254a8 | 24.510204 | 96 | 0.668 | 5.580357 | false | false | false | false |
hujiaweibujidao/Gank | Gank/Extension/UIView+Extension.swift | 2 | 2175 | //
// UIView+Extension.swift
// Gank
//
// Created by CoderAhuan on 2016/12/7.
// Copyright © 2016年 CoderAhuan. All rights reserved.
//
import UIKit
extension UIView {
var X: CGFloat {
get {
return self.frame.origin.x
}
set(newX) {
self.frame.origin.x = newX
}
}
var Y: CGFloat {
get {
return self.frame.origin.y
}
set(newY) {
self.frame.origin.y = newY
}
}
var Height: CGFloat {
get {
return self.frame.size.height
}
set(newHeight) {
self.frame.size.height = newHeight
}
}
var Width: CGFloat {
get {
return self.frame.size.width
}
set(newWidth) {
self.frame.size.width = newWidth
}
}
var CenterX: CGFloat {
get {
return self.center.x
}
set(newCenterX) {
self.center.x = newCenterX
}
}
var CenterY: CGFloat {
get {
return self.center.y
}
set(newCenterY) {
self.center.y = newCenterY
}
}
var MaxX: CGFloat {
get {
return self.frame.maxX
}
}
var MaxY: CGFloat {
get {
return self.frame.maxY
}
}
class func viewFromNib() -> Any? {
return Bundle.main.loadNibNamed(self.className, owner: nil, options: nil)?.last as Any?
}
class func nib() -> UINib {
return UINib(nibName: self.className, bundle: nil)
}
// 判断一个控件是否真正显示在主窗口
func isShowingOnKeyWindow() -> Bool {
// 以主窗口左上角为坐标原点, 计算self的矩形框
let newFrame = kWindow!.convert(self.frame, from: self.superview)
let winBounds = kWindow!.bounds
// 主窗口的bounds 和 self的矩形框 是否有重叠
let intersects = newFrame.intersects(winBounds)
return !self.isHidden && self.alpha > 0.01 && self.window == kWindow && intersects
}
}
| mit | f9be5ae396c086b9cb04acb63b793b32 | 20.183673 | 95 | 0.497592 | 4.102767 | false | false | false | false |
Wolox/wolmo-core-ios | WolmoCore/Extensions/UIKit/UIImage.swift | 1 | 4078 | //
// UIImage.swift
// WolmoCore
//
// Created by Nahuel Gladstein on 6/8/17.
// Copyright © 2017 Wolox. All rights reserved.
//
import UIKit
public extension UIImage {
/**
Returns a resized copy of the image, with cornerRadius if used.
- parameter toSize: The wanted size to fit the new image in.
- parameter maintainAspectRatio: Determines if the resulting image will keep the aspect ratio of the original image,
If set to true the size of the resulting image will be the closest smaller size to the one specified that maintains the aspect ratio of the original image.
If set to false it will stretch the image to fill the size specified.
- parameter useScreenScale: Determines if the screen scale will be used when creating the image context. Default: true.
Set to true if you want to make the size relative to the scale of the screen
(So the resized image looks the same relative size on all devices, you probably want this if you're showing the resized image).
Set to false if you want the size to be actual pixels
(This is useful to generate a resized image of a particular size in real pixels to send to API regardless of the device screen scale).
- parameter cornerRadius: The cornerRadius to be used. Any number lower or equal to zero will not add cornerRadius. Default: 0.0, no corner radius.
*/
func resized(toSize: CGSize, maintainAspectRatio: Bool, useScreenScale: Bool = true, cornerRadius: CGFloat = 0.0, insets: UIEdgeInsets = .zero) -> UIImage {
let newSize = maintainAspectRatio ? size.resizedMaintainingRatio(wantedSize: toSize) : toSize
let scale: CGFloat = useScreenScale ? 0.0 : 1.0
let imageRect = CGRect(origin: CGPoint.zero, size: newSize)
UIGraphicsBeginImageContextWithOptions(newSize, false, scale)
if cornerRadius > 0 {
let path = UIBezierPath(roundedRect: imageRect, cornerRadius: cornerRadius)
path.addClip()
}
resizableImage(withCapInsets: capInsets).draw(in: imageRect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
/**
Returns the aspect ratio of the image represented by a CGFloat.
For example an image with a 4:3 ratio will give 1.333... as output.
*/
var aspectRatio: CGFloat {
return size.width / size.height
}
/**
Returns an image painted with the selected color,
so that wherever the image is inserted, it will have that color (the original if color is .none).
- parameter color: UIColor by which to tint image, or nothing to copy the image as it is.
- seealso: withRenderingMode(.alwaysOriginal)
*/
func tintedWith(_ color: UIColor?) -> UIImage {
if let color = color {
var newImage = withRenderingMode(.alwaysTemplate)
UIGraphicsBeginImageContextWithOptions(size, false, newImage.scale)
color.set()
newImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage.withRenderingMode(.alwaysOriginal)
}
return self.withRenderingMode(.alwaysOriginal)
}
}
fileprivate extension CGSize {
/**
Returns a resized copy of the size maintaining it's aspect ratio.
- parameter wantedSize: The wanted new size to fit.
Note that the size of the resulting CGSize will be the smaller closest size to the one specified that maintains the aspect ratio of the original.
*/
func resizedMaintainingRatio(wantedSize: CGSize) -> CGSize {
let widthFactor = wantedSize.width / width
let heightFactor = wantedSize.height / height
let resizeFactor = min(heightFactor, widthFactor)
return CGSize(width: width * resizeFactor, height: height * resizeFactor)
}
}
| mit | 6df6f58bdccf57f3434ba2c7bc679397 | 45.329545 | 167 | 0.680893 | 5.033333 | false | false | false | false |
ONode/actor-platform | actor-apps/app-ios/ActorApp/View/BigPlaceholderView.swift | 24 | 9076 | //
// Copyright (c) 2015 Actor LLC. <https://actor.im>
//
import UIKit
class BigPlaceholderView: UIView {
// MARK: -
// MARK: Private vars
private var contentView: UIView!
private var bgView: UIView!
private var imageView: UIImageView!
private var titleLabel: UILabel!
private var subtitleLabel: UILabel!
private var actionButton: UIButton!
private var topOffset: CGFloat!
private var subtitle2Label: UILabel!
private var action2Button: UIButton!
// MARK: -
// MARK: Public vars
// MARK: -
// MARK: Constructors
init(topOffset: CGFloat!) {
super.init(frame: CGRectZero)
self.topOffset = topOffset
backgroundColor = UIColor.whiteColor()
contentView = UIView()
contentView.backgroundColor = UIColor.whiteColor()
addSubview(contentView)
imageView = UIImageView()
imageView.hidden = true
bgView = UIView()
bgView.backgroundColor = MainAppTheme.navigation.barSolidColor
contentView.addSubview(bgView)
contentView.addSubview(imageView)
titleLabel = UILabel()
titleLabel.textColor = MainAppTheme.placeholder.textTitle
titleLabel.font = UIFont(name: "HelveticaNeue", size: 22.0);
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.text = " "
titleLabel.sizeToFit()
contentView.addSubview(titleLabel)
subtitleLabel = UILabel()
subtitleLabel.textColor = MainAppTheme.placeholder.textHint
subtitleLabel.font = UIFont.systemFontOfSize(16.0)
subtitleLabel.textAlignment = NSTextAlignment.Center
subtitleLabel.numberOfLines = 0
contentView.addSubview(subtitleLabel)
actionButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
actionButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Medium", size: 21.0)
contentView.addSubview(actionButton)
subtitle2Label = UILabel()
subtitle2Label.textColor = MainAppTheme.placeholder.textHint
subtitle2Label.font = UIFont.systemFontOfSize(16.0)
subtitle2Label.textAlignment = NSTextAlignment.Center
subtitle2Label.numberOfLines = 0
contentView.addSubview(subtitle2Label)
action2Button = UIButton.buttonWithType(UIButtonType.System) as! UIButton
action2Button.titleLabel!.font = UIFont(name: "HelveticaNeue-Medium", size: 21.0)
contentView.addSubview(action2Button)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
// MARK: Setters
func setImage(image: UIImage?, title: String?, subtitle: String?) {
setImage(image, title: title, subtitle: subtitle, actionTitle: nil, subtitle2: nil, actionTarget: nil, actionSelector: nil, action2title: nil, action2Selector: nil)
}
func setImage(image: UIImage?, title: String?, subtitle: String?, actionTitle: String?, subtitle2: String?, actionTarget: AnyObject?, actionSelector: Selector?, action2title: String?, action2Selector: Selector?) {
if image != nil {
imageView.image = image!
imageView.hidden = false
} else {
imageView.hidden = true
}
if title != nil {
titleLabel.text = title
titleLabel.hidden = false
} else {
titleLabel.hidden = true
}
if subtitle != nil {
var paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineHeightMultiple = 1.11
paragraphStyle.alignment = NSTextAlignment.Center
var attrString = NSMutableAttributedString(string: subtitle!)
attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
subtitleLabel.attributedText = attrString
subtitleLabel.hidden = false
} else {
subtitleLabel.hidden = true
}
if actionTitle != nil && actionTarget != nil && actionSelector != nil {
actionButton.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
actionButton.addTarget(actionTarget!, action: actionSelector!, forControlEvents: UIControlEvents.TouchUpInside)
actionButton.setTitle(actionTitle, forState: UIControlState.Normal)
actionButton.hidden = false
} else {
actionButton.hidden = true
}
if (subtitle2 != nil) {
var paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineHeightMultiple = 1.11
paragraphStyle.alignment = NSTextAlignment.Center
var attrString = NSMutableAttributedString(string: subtitle2!)
attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
subtitle2Label.attributedText = attrString
subtitle2Label.hidden = false
} else {
subtitle2Label.hidden = true
}
if action2title != nil && actionTarget != nil && actionSelector != nil {
action2Button.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents)
action2Button.addTarget(actionTarget!, action: action2Selector!, forControlEvents: UIControlEvents.TouchUpInside)
action2Button.setTitle(action2title, forState: UIControlState.Normal)
action2Button.hidden = false
} else {
action2Button.hidden = true
}
setNeedsLayout()
}
// MARK: -
// MARK: Layout
override func layoutSubviews() {
super.layoutSubviews()
var contentHeight: CGFloat = 0
var maxContentWidth = bounds.size.width - 40
var originY = 0
if imageView.hidden == false {
imageView.frame = CGRect(x: 20 + (maxContentWidth - imageView.image!.size.width) / 2.0, y: topOffset, width: imageView.image!.size.width, height: imageView.image!.size.height)
contentHeight += imageView.image!.size.height + topOffset
}
bgView.frame = CGRect(x: 0, y: 0, width: bounds.size.width, height: imageView.frame.height * 0.75 + topOffset)
if titleLabel.hidden == false {
if contentHeight > 0 {
contentHeight += 10
}
titleLabel.frame = CGRect(x: 20, y: contentHeight, width: maxContentWidth, height: titleLabel.bounds.size.height)
contentHeight += titleLabel.bounds.size.height
}
if subtitleLabel.hidden == false {
if contentHeight > 0 {
contentHeight += 14
}
let subtitleLabelSize = subtitleLabel.sizeThatFits(CGSize(width: maxContentWidth, height: CGFloat.max))
subtitleLabel.frame = CGRect(x: 20, y: contentHeight, width: maxContentWidth, height: subtitleLabelSize.height)
contentHeight += subtitleLabelSize.height
}
if actionButton.hidden == false {
if contentHeight > 0 {
contentHeight += 14
}
let actionButtonTitleLabelSize = actionButton.titleLabel!.sizeThatFits(CGSize(width: maxContentWidth, height: CGFloat.max))
actionButton.frame = CGRect(x: 20, y: contentHeight, width: maxContentWidth, height: actionButtonTitleLabelSize.height)
contentHeight += actionButtonTitleLabelSize.height
}
if subtitle2Label.hidden == false {
if contentHeight > 0 {
contentHeight += 14
}
let subtitleLabelSize = subtitle2Label.sizeThatFits(CGSize(width: maxContentWidth, height: CGFloat.max))
subtitle2Label.frame = CGRect(x: 20, y: contentHeight, width: maxContentWidth, height: subtitleLabelSize.height)
contentHeight += subtitleLabelSize.height
}
if action2Button.hidden == false {
if contentHeight > 0 {
contentHeight += 14
}
let actionButtonTitleLabelSize = action2Button.titleLabel!.sizeThatFits(CGSize(width: maxContentWidth, height: CGFloat.max))
action2Button.frame = CGRect(x: 20, y: contentHeight, width: maxContentWidth, height: actionButtonTitleLabelSize.height)
contentHeight += actionButtonTitleLabelSize.height
}
// contentView.frame = CGRect(x: (bounds.size.width - maxContentWidth) / 2.0, y: (bounds.size.height - contentHeight) / 2.0, width: maxContentWidth, height: contentHeight)
contentView.frame = CGRect(x: 0, y: 0, width: maxContentWidth, height: contentHeight)
}
}
| mit | e571f1fd6552083e1ed99bff452ac03f | 38.633188 | 217 | 0.624063 | 5.480676 | false | false | false | false |
Superkazuya/zimcher2015 | Zimcher/UIKit Objects/SignUp&LoginScenes/SignUpViewController.swift | 1 | 1914 | //
// SignUpViewController.swift
// SwiftPort
//
// Created by Weiyu Huang on 11/14/15.
// Copyright © 2015 Kappa. All rights reserved.
//
import UIKit
class SignUpViewController: ViewControllerWithKBLayoutGuide, ValidationAndTopAlertView{
@IBOutlet weak var termsView: UIStackView!
@IBOutlet weak var tableView: TableViewWithIntrinsicSize!
struct LOCAL_CONSTANT {
static let TERMS_TO_BOTTOM: CGFloat = 15
}
var entryField: EntryField!
override func viewDidLoad()
{
super.viewDidLoad()
entryField = EntryField(tableView: tableView)
entryField.headerFooterHeight = 0
navigationItem.leftBarButtonItem?.title = ""
kbLayoutGuide.topAnchor.constraintEqualToAnchor(termsView.bottomAnchor, constant: LOCAL_CONSTANT.TERMS_TO_BOTTOM).active = true
entryField.feedData(generateData())
}
private func generateData() -> [EntryFieldData]
{
var r = [EntryFieldData]()
var basic0 = BasicEntryFieldData()
basic0.promptText = "FeelsBadMan"
basic0.placeholderText = "I know that feel bro"
basic0.onSubmitCallback = {[weak self] con in
let f = (OnSubmitCallbackGenerator.TextFieldValidation(IsValid.userName))
let r = f(con)
if !r{
self!.showTopAlert("alert")
}
return r
}
var basic1 = BasicEntryFieldData()
basic1.promptText = "Hungry"
r.append(basic0)
r.append(basic1)
r.append(basic1)
return r
}
@IBAction func donePressed() {
guard entryField.onSubmitCallback() else { return }
//Networking.userRegisterWithUserJSON(payload: ["userName": nameInput.text!, "email":emailInput.text!, "password":passwordInput.text!]) { data, response, error in }
//stub
}
}
| apache-2.0 | 8261cc4ddf1d00eaca30282974813b63 | 28.430769 | 172 | 0.62781 | 4.565632 | false | false | false | false |
aboutsajjad/Bridge | Bridge/DownloadCoordinator/DownloadViewController.swift | 1 | 10091 | //
// DownloadViewController.swift
// Bridge
//
// Created by Sajjad Aboutalebi on 3/8/18.
// Copyright © 2018 Sajjad Aboutalebi. All rights reserved.
//
import UIKit
import MZDownloadManager
class DownloadViewController: UITableViewController {
var selectedIndexPath : IndexPath!
let alertControllerViewTag: Int = 500
lazy var downloadManager: MZDownloadManager = {
[unowned self] in
let sessionIdentifer: String = "co.rishe.Bridge.MZDownloadManager.BackgroundSession"
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var completion = appDelegate.backgroundSessionCompletionHandler
let downloadmanager = MZDownloadManager(session: sessionIdentifer, delegate: self, completion: completion)
return downloadmanager
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(DownloadTableViewCell.self, forCellReuseIdentifier: "downloadingCell")
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: nil, style: .done, target: nil, action: #selector(pauseAll))
}
@objc func pauseAll() {
assert(false)
}
// MARK: - Table view data source
func refreshCellForIndex(_ downloadModel: MZDownloadModel, index: Int) {
let indexPath = IndexPath.init(row: index, section: 0)
let cell = self.tableView.cellForRow(at: indexPath)
if let cell = cell {
let downloadCell = cell as! DownloadTableViewCell
downloadCell.updateCellForRowAtIndexPath(indexPath, downloadModel: downloadModel)
}
}
}
// MARK: UITableViewDatasource Handler Extension
extension DownloadViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return downloadManager.downloadingArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "downloadingCell", for: indexPath) as! DownloadTableViewCell
let downloadModel = downloadManager.downloadingArray[indexPath.row]
cell.updateCellForRowAtIndexPath(indexPath, downloadModel: downloadModel)
cell.layoutIfNeeded()
return cell
}
}
// MARK: UITableViewDelegate Handler Extension
extension DownloadViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedIndexPath = indexPath
let downloadModel = downloadManager.downloadingArray[indexPath.row]
self.showAppropriateActionController(downloadModel.status)
tableView.deselectRow(at: indexPath, animated: true)
}
}
// MARK: UIAlertController Handler Extension
extension DownloadViewController {
func showAppropriateActionController(_ requestStatus: String) {
if requestStatus == TaskStatus.downloading.description() {
self.showAlertControllerForPause()
} else if requestStatus == TaskStatus.failed.description() {
self.showAlertControllerForRetry()
} else if requestStatus == TaskStatus.paused.description() {
self.showAlertControllerForStart()
}
}
func showAlertControllerForPause() {
let pauseAction = UIAlertAction(title: "Pause", style: .default) { (alertAction: UIAlertAction) in
self.downloadManager.pauseDownloadTaskAtIndex(self.selectedIndexPath.row)
}
let removeAction = UIAlertAction(title: "Remove", style: .destructive) { (alertAction: UIAlertAction) in
self.downloadManager.cancelTaskAtIndex(self.selectedIndexPath.row)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alertController.view.tag = alertControllerViewTag
alertController.addAction(pauseAction)
alertController.addAction(removeAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
func showAlertControllerForRetry() {
let retryAction = UIAlertAction(title: "Retry", style: .default) { (alertAction: UIAlertAction) in
self.downloadManager.retryDownloadTaskAtIndex(self.selectedIndexPath.row)
}
let removeAction = UIAlertAction(title: "Remove", style: .destructive) { (alertAction: UIAlertAction) in
self.downloadManager.cancelTaskAtIndex(self.selectedIndexPath.row)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alertController.view.tag = alertControllerViewTag
alertController.addAction(retryAction)
alertController.addAction(removeAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
func showAlertControllerForStart() {
let startAction = UIAlertAction(title: "Start", style: .default) { (alertAction: UIAlertAction) in
self.downloadManager.resumeDownloadTaskAtIndex(self.selectedIndexPath.row)
}
let removeAction = UIAlertAction(title: "Remove", style: .destructive) { (alertAction: UIAlertAction) in
self.downloadManager.cancelTaskAtIndex(self.selectedIndexPath.row)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alertController.view.tag = alertControllerViewTag
alertController.addAction(startAction)
alertController.addAction(removeAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
func safelyDismissAlertController() {
/***** Dismiss alert controller if and only if it exists and it belongs to MZDownloadManager *****/
/***** E.g App will eventually crash if download is completed and user tap remove *****/
/***** As it was already removed from the array *****/
if let controller = self.presentedViewController {
guard controller is UIAlertController && controller.view.tag == alertControllerViewTag else {
return
}
controller.dismiss(animated: true, completion: nil)
}
}
}
extension DownloadViewController: MZDownloadManagerDelegate {
func downloadRequestStarted(_ downloadModel: MZDownloadModel, index: Int) {
let indexPath = IndexPath.init(row: index, section: 0)
tableView.insertRows(at: [indexPath], with: UITableViewRowAnimation.fade)
}
func downloadRequestDidPopulatedInterruptedTasks(_ downloadModels: [MZDownloadModel]) {
tableView.reloadData()
}
func downloadRequestDidUpdateProgress(_ downloadModel: MZDownloadModel, index: Int) {
self.refreshCellForIndex(downloadModel, index: index)
}
func downloadRequestDidPaused(_ downloadModel: MZDownloadModel, index: Int) {
self.refreshCellForIndex(downloadModel, index: index)
}
func downloadRequestDidResumed(_ downloadModel: MZDownloadModel, index: Int) {
self.refreshCellForIndex(downloadModel, index: index)
}
func downloadRequestCanceled(_ downloadModel: MZDownloadModel, index: Int) {
self.safelyDismissAlertController()
let indexPath = IndexPath.init(row: index, section: 0)
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.left)
}
func downloadRequestFinished(_ downloadModel: MZDownloadModel, index: Int) {
self.safelyDismissAlertController()
downloadManager.presentNotificationForDownload("Ok", notifBody: "Download did completed")
let indexPath = IndexPath.init(row: index, section: 0)
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.left)
let docDirectoryPath : NSString = (MZUtility.baseFilePath as NSString).appendingPathComponent(downloadModel.fileName) as NSString
NotificationCenter.default.post(name: NSNotification.Name(rawValue: MZUtility.DownloadCompletedNotif as String), object: docDirectoryPath)
}
func downloadRequestDidFailedWithError(_ error: NSError, downloadModel: MZDownloadModel, index: Int) {
self.safelyDismissAlertController()
self.refreshCellForIndex(downloadModel, index: index)
debugPrint("Error while downloading file: \(downloadModel.fileName) Error: \(error)")
}
//Oppotunity to handle destination does not exists error
//This delegate will be called on the session queue so handle it appropriately
func downloadRequestDestinationDoestNotExists(_ downloadModel: MZDownloadModel, index: Int, location: URL) {
let myDownloadPath = MZUtility.baseFilePath + "/Default folder"
if !FileManager.default.fileExists(atPath: myDownloadPath) {
try! FileManager.default.createDirectory(atPath: myDownloadPath, withIntermediateDirectories: true, attributes: nil)
}
let fileName = MZUtility.getUniqueFileNameWithPath((myDownloadPath as NSString).appendingPathComponent(downloadModel.fileName as String) as NSString)
let path = myDownloadPath + "/" + (fileName as String)
try! FileManager.default.moveItem(at: location, to: URL(fileURLWithPath: path))
debugPrint("Default folder path: \(myDownloadPath)")
}
}
| mit | 024ea35b93d01f8ea28beea8932fbc40 | 41.394958 | 157 | 0.694549 | 5.574586 | false | false | false | false |
tbajis/Bop | Bop/InterestPickerViewController.swift | 1 | 5487 | //
// InterestPickerViewController.swift
// Bop
//
// Created by Thomas Manos Bajis on 4/17/17.
// Copyright © 2017 Thomas Manos Bajis. All rights reserved.
//
import Foundation
import UIKit
import CoreData
import Crashlytics
import TwitterKit
import DigitsKit
// MARK: - InterestPickerViewController: UIViewController. SegueHandlerType
class InterestPickerViewController: UIViewController, SegueHandlerType {
// MARK: Properties
enum SegueIdentifier: String {
case ContinueButtonPressed
case PinButtonPressed
}
// MARK: Outlets
@IBOutlet var interestButtons: [InterestButton]!
@IBOutlet weak var continueButton: UIButton!
@IBOutlet weak var navigationBar: UINavigationBar!
@IBOutlet weak var mapButton: UIBarButtonItem!
@IBOutlet weak var logoutButton: UIBarButtonItem!
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
}
// MARK: Actions
@IBAction func logout(_ sender: Any) {
// Remove pins from Core Data
CoreDataObject.sharedInstance().executePinSearch()
if let pins = CoreDataObject.sharedInstance().fetchedPinResultsController.fetchedObjects as? [Pin] {
for pin in pins {
AppDelegate.stack.context.delete(pin)
AppDelegate.stack.save()
}
}
// Remove any Twitter or Digits local session for this app.
let sessionStore = Twitter.sharedInstance().sessionStore
if let userId = sessionStore.session()?.userID {
sessionStore.logOutUserID(userId)
}
Digits.sharedInstance().logOut()
// Remove user information for any upcoming crashes in Crashlytics.
Crashlytics.sharedInstance().setUserIdentifier(nil)
Crashlytics.sharedInstance().setUserName(nil)
// Log Answers Custom Event.
Answers.logCustomEvent(withName: "Signed Out", customAttributes: nil)
// Set Guest Login to false
UserDefaults.standard.set(false, forKey: "guestLoggedIn")
// Present the Login Screen again
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if let _ = appDelegate.window?.rootViewController as? LoginViewController {
// if Login View is window's root view, dismiss to it. Otherwise set it and dismiss to it.
self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
} else {
let loginViewController = storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
appDelegate.window?.rootViewController = loginViewController
self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
}
}
@IBAction func mapButtonPressed(_ sender: Any) {
performSegue(withIdentifier: .PinButtonPressed, sender: self)
}
@IBAction func interestButtonPressed(_ sender: InterestButton) {
toggleButton(sender, {
self.updateContinueButton()
})
}
@IBAction func continueButtonPressed(_ sender: UIButton) {
for button in interestButtons {
if button.isToggle {
let query = button.queryString(for: InterestButton.Category(rawValue: button.tag)!)
UserDefaults.standard.set(query, forKey: "Interest")
performSegue(withIdentifier: .ContinueButtonPressed, sender: self)
}
}
}
// MARK: Utilities
func configureUI() {
for button in interestButtons {
button.backgroundColor = UIColor.clear
}
logoutButton.setTitleTextAttributes([NSAttributedStringKey.foregroundColor:UIColor.white, NSAttributedStringKey.font:UIFont(name: "Avenir-Light", size: 15)!], for: .normal)
continueButton.isHidden = true
CoreDataObject.sharedInstance().executePinSearch()
if let pins = CoreDataObject.sharedInstance().fetchedPinResultsController.fetchedObjects as? [Pin], pins.count > 0 {
self.mapButton.isEnabled = true
} else {
self.mapButton.isEnabled = false
}
}
func toggleButton(_ sender: InterestButton, _ handler: @escaping () -> Void) {
for button in interestButtons {
if button == sender {
button.isToggle = true
} else {
button.isToggle = false
}
}
handler()
}
func updateContinueButton() {
for button in interestButtons {
if button.isToggle == true {
print(button.tag)
self.continueButton.isHidden = false
}
}
}
// MARK: Helpers
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segueIdentifierForSegue(segue: segue) {
case .ContinueButtonPressed:
deletePins()
case .PinButtonPressed: break
}
}
func deletePins() {
if let pins = CoreDataObject.sharedInstance().fetchedPinResultsController.fetchedObjects as? [Pin] {
for pin in pins {
AppDelegate.stack.context.delete(pin)
AppDelegate.stack.save()
}
}
}
}
| apache-2.0 | 0467a6e808216665ce564cb2c9fa7623 | 31.654762 | 180 | 0.617572 | 5.496994 | false | false | false | false |
webelectric/AspirinKit | AspirinKit/Sources/AppKit/Keyboard.swift | 1 | 19253 | //
// Keyboard.swift
// AspirinKit
//
// Copyright © 2014 - 2017 The Web Electric Corp.
//
// 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 AppKit
import Carbon
import Cocoa
public typealias KeyComboAction = (Keyboard.KeyCombo,NSEvent?) -> Void
public class GlobalHotKey : Hashable, Equatable {
public let hotKeyRef:EventHotKeyRef
public let hotKeyID:UInt32
public init(_ id:UInt32, hotKeyReference:EventHotKeyRef) {
hotKeyID = id
hotKeyRef = hotKeyReference
}
public var hashValue: Int {
return Int(hotKeyID)
}
}
public func ==(lhs:GlobalHotKey, rhs:GlobalHotKey) -> Bool {
return lhs.hashValue == rhs.hashValue
}
private var signaturesToKeyboards:[OSType: Keyboard] = [OSType: Keyboard]()
/**
Blocks-aware class to simplify OS X keyboard binding on OS X apps using Swift 3
Features:
* Supports app as well as global hotkeys
* Swift-friendly wrapper on common Cocoa/Carbon functions
* Supports multiple instances, plus one default shared keyboard
Example use
```
let cmdShiftSpaceCombo = Keyboard.KeyCombo(keyCode: Keyboard.Keys.Space,
modifierFlags: [.command, .shift])
//register (bind) global keycombo
Keyboard.sharedKeyboard.bindGlobalKeyCombo(cmdShiftSpaceCombo, action: { [unowned self] (keyCombo:Keyboard.KeyCombo, event: NSEvent?) -> Void in
print("CMD-Shift-Space pressed")
})
....
//deregister (unbind) global keycombo
Keyboard.sharedKeyboard.unbindGlobalKeyCombo(cmdShiftSpaceCombo1)
```
*/
public class Keyboard {
private static let defaultHotKeySignature:String = "akey"
var nextHotKeyID:UInt32 = UInt32(1)
private static let __once: () = { () -> Void in
//one-time init tasks
}()
/*
* Virtual keycodes // Values (not constant names)
* are From Carbon/Frameworks/HIToolbox/Events.h:
*
* //Original Events.h comment
* These constants are the virtual keycodes defined originally in
* Inside Mac Volume V, pg. V-191. They identify physical keys on a
* keyboard. Those constants with "ANSI" in the name are labeled
* according to the key position on an ANSI-standard US keyboard.
* For example, kVK_ANSI_A indicates the virtual keycode for the key
* with the static letter 'A' in the US keyboard layout. Other keyboard
* layouts may have the 'A' key label on a different physical key;
* in this case, pressing 'A' will generate a different virtual
* keycode.
*/
public struct Keys {
public static let A:UInt16 = 0x00
public static let S:UInt16 = 0x01
public static let D:UInt16 = 0x02
public static let F:UInt16 = 0x03
public static let H:UInt16 = 0x04
public static let G:UInt16 = 0x05
public static let Z:UInt16 = 0x06
public static let X:UInt16 = 0x07
public static let C:UInt16 = 0x08
public static let V:UInt16 = 0x09
public static let B:UInt16 = 0x0B
public static let Q:UInt16 = 0x0C
public static let W:UInt16 = 0x0D
public static let E:UInt16 = 0x0E
public static let R:UInt16 = 0x0F
public static let Y:UInt16 = 0x10
public static let T:UInt16 = 0x11
public static let NUM_1:UInt16 = 0x12
public static let NUM_2:UInt16 = 0x13
public static let NUM_3:UInt16 = 0x14
public static let NUM_4:UInt16 = 0x15
public static let NUM_6:UInt16 = 0x16
public static let NUM_5:UInt16 = 0x17
public static let Equal:UInt16 = 0x18
public static let NUM_9:UInt16 = 0x19
public static let NUM_7:UInt16 = 0x1A
public static let Minus:UInt16 = 0x1B
public static let NUM_8:UInt16 = 0x1C
public static let NUM_0:UInt16 = 0x1D
public static let RightBracket:UInt16 = 0x1E
public static let O:UInt16 = 0x1F
public static let U:UInt16 = 0x20
public static let LeftBracket:UInt16 = 0x21
public static let I:UInt16 = 0x22
public static let P:UInt16 = 0x23
public static let L:UInt16 = 0x25
public static let J:UInt16 = 0x26
public static let Quote:UInt16 = 0x27
public static let K:UInt16 = 0x28
public static let Semicolon:UInt16 = 0x29
public static let Backslash:UInt16 = 0x2A
public static let Comma:UInt16 = 0x2B
public static let Slash:UInt16 = 0x2C
public static let N:UInt16 = 0x2D
public static let M:UInt16 = 0x2E
public static let Period:UInt16 = 0x2F
public static let Grave:UInt16 = 0x32
public static let KeypadDecimal:UInt16 = 0x41
public static let KeypadMultiply:UInt16 = 0x43
public static let KeypadPlus:UInt16 = 0x45
public static let KeypadClear:UInt16 = 0x47
public static let KeypadDivide:UInt16 = 0x4B
public static let KeypadEnter:UInt16 = 0x4C
public static let KeypadMinus:UInt16 = 0x4E
public static let KeypadEquals:UInt16 = 0x51
public static let Keypad0:UInt16 = 0x52
public static let Keypad1:UInt16 = 0x53
public static let Keypad2:UInt16 = 0x54
public static let Keypad3:UInt16 = 0x55
public static let Keypad4:UInt16 = 0x56
public static let Keypad5:UInt16 = 0x57
public static let Keypad6:UInt16 = 0x58
public static let Keypad7:UInt16 = 0x59
public static let Keypad8:UInt16 = 0x5B
public static let Keypad9:UInt16 = 0x5C
/* keycodes for keys that are independent of keyboard layout*/
public static let Return:UInt16 = 0x24
public static let Tab :UInt16 = 0x30
public static let Space :UInt16 = 0x31
public static let Delete:UInt16 = 0x33
public static let Escape:UInt16 = 0x35
public static let Command:UInt16 = 0x37
public static let Shift:UInt16 = 0x38
public static let CapsLock:UInt16 = 0x39
public static let Option:UInt16 = 0x3A
public static let Control:UInt16 = 0x3B
public static let RightShift:UInt16 = 0x3C
public static let RightOption:UInt16 = 0x3D
public static let RightControl:UInt16 = 0x3E
public static let Function:UInt16 = 0x3F
public static let F17 :UInt16 = 0x40
public static let VolumeUp:UInt16 = 0x48
public static let VolumeDown:UInt16 = 0x49
public static let Mute :UInt16 = 0x4A
public static let F18 :UInt16 = 0x4F
public static let F19 :UInt16 = 0x50
public static let F20 :UInt16 = 0x5A
public static let F5 :UInt16 = 0x60
public static let F6 :UInt16 = 0x61
public static let F7 :UInt16 = 0x62
public static let F3 :UInt16 = 0x63
public static let F8 :UInt16 = 0x64
public static let F9 :UInt16 = 0x65
public static let F11 :UInt16 = 0x67
public static let F13 :UInt16 = 0x69
public static let F16 :UInt16 = 0x6A
public static let F14 :UInt16 = 0x6B
public static let F10 :UInt16 = 0x6D
public static let F12 :UInt16 = 0x6F
public static let F15 :UInt16 = 0x71
public static let Help :UInt16 = 0x72
public static let Home :UInt16 = 0x73
public static let PageUp:UInt16 = 0x74
public static let ForwardDelete:UInt16 = 0x75
public static let F4 :UInt16 = 0x76
public static let End :UInt16 = 0x77
public static let F2 :UInt16 = 0x78
public static let PageDown:UInt16 = 0x79
public static let F1 :UInt16 = 0x7A
public static let LeftArrow:UInt16 = 0x7B
public static let RightArrow:UInt16 = 0x7C
public static let DownArrow:UInt16 = 0x7D
public static let UpArrow:UInt16 = 0x7E
//convenience pre-set combos
public static let CTRL_LEFT_ARROW:KeyCombo = KeyCombo(keyCode: Keys.LeftArrow, modifierFlags: NSEventModifierFlags.control)
public static let CTRL_RIGHT_ARROW:KeyCombo = KeyCombo(keyCode: Keys.RightArrow, modifierFlags: NSEventModifierFlags.control)
public static let CTRL_DOWN_ARROW:KeyCombo = KeyCombo(keyCode: Keys.DownArrow, modifierFlags: NSEventModifierFlags.control)
public static let CTRL_UP_ARROW:KeyCombo = KeyCombo(keyCode: Keys.UpArrow, modifierFlags: NSEventModifierFlags.control)
public static let CTRL_SHIFT_LEFT_ARROW:KeyCombo = KeyCombo(keyCode: Keys.LeftArrow, modifierFlags: [.control, .shift])
public static let CTRL_SHIFT_RIGHT_ARROW:KeyCombo = KeyCombo(keyCode: Keys.RightArrow, modifierFlags: [.control, .shift])
public static let CTRL_SHIFT_DOWN_ARROW:KeyCombo = KeyCombo(keyCode: Keys.DownArrow, modifierFlags: [.control, .shift])
public static let CTRL_SHIFT_UP_ARROW:KeyCombo = KeyCombo(keyCode: Keys.UpArrow, modifierFlags: [.control,.shift])
public static let CMD_LEFT_ARROW:KeyCombo = KeyCombo(keyCode: Keys.LeftArrow, modifierFlags: NSEventModifierFlags.command)
public static let CMD_RIGHT_ARROW:KeyCombo = KeyCombo(keyCode: Keys.RightArrow, modifierFlags: NSEventModifierFlags.command)
public static let CMD_DOWN_ARROW:KeyCombo = KeyCombo(keyCode: Keys.DownArrow, modifierFlags: NSEventModifierFlags.command)
public static let CMD_UP_ARROW:KeyCombo = KeyCombo(keyCode: Keys.UpArrow, modifierFlags: NSEventModifierFlags.command)
}
//IMPORTANT: internally, NEVER use the "modifier flags" value for comparisons since it may contain additional data
//from an event generated by the system
public class KeyCombo : Hashable, Equatable {
public var keyCode:UInt16
var modifierFlags:NSEventModifierFlags
public var hasModifiers:Bool { return !modifierFlags.isEmpty }
public var isCtrlPressed:Bool { return modifierFlags.contains(.control) }
public var isCommandPressed:Bool { return modifierFlags.contains(.command) }
public var isAltPressed:Bool { return modifierFlags.contains(NSEventModifierFlags.option) }
public var isShiftPressed:Bool { return modifierFlags.contains(.shift) }
var globalHotKey:GlobalHotKey!
public var carbonModifierFlags:UInt32 {
var newFlags:Int = 0
if (self.isCtrlPressed) { newFlags |= controlKey }
if (self.isCommandPressed) { newFlags |= cmdKey }
if (self.isShiftPressed) { newFlags |= shiftKey }
if (self.isAltPressed) { newFlags |= optionKey }
return UInt32(newFlags)
}
var _precomputedHash:Int = 0
public convenience init(event: NSEvent) {
self.init(keyCode: event.keyCode, modifierFlags: event.modifierFlags)
}
public init(keyCode:UInt16, modifierFlags:NSEventModifierFlags = []) {
self.keyCode = keyCode
self.modifierFlags = modifierFlags
//the hash is simply the keycode plus a power of two value above 2^16 for each
//of the modifiers, using the bitspace between 17 and 32
_precomputedHash = Int(keyCode)
_precomputedHash = isCommandPressed ? ((2 << 17)+_precomputedHash) : _precomputedHash
_precomputedHash = isCtrlPressed ? ((2 << 18)+_precomputedHash) : _precomputedHash
_precomputedHash = isAltPressed ? ((2 << 19)+_precomputedHash) : _precomputedHash
_precomputedHash = isShiftPressed ? ((2 << 20)+_precomputedHash) : _precomputedHash
}
public var hashValue:Int {
return _precomputedHash
}
}
//app keybindings
var keyBindings:[KeyCombo: KeyComboAction] = [KeyCombo: KeyComboAction]()
//global os-wide keybindings
var globalKeyBindings:[KeyCombo: KeyComboAction] = [KeyCombo: KeyComboAction]()
var globalHotKeyIDsToKeyCombo:[UInt32:KeyCombo] = [UInt32:KeyCombo]()
var globalKeyCombostoHotKeyID:[KeyCombo:UInt32] = [KeyCombo:UInt32]()
public static let sharedKeyboard:Keyboard = Keyboard(withSignature:Keyboard.defaultHotKeySignature)!
private var hotKeySignature:OSType
private var eventHandlerReference:EventHandlerRef!
init?(withSignature hkSignature:String) {
let sigCode = OSType(hkSignature.fourCharCode)
if signaturesToKeyboards[sigCode] != nil {
print("Error, can't register Keyboard signature [\(hkSignature)] twice.")
return nil
}
_ = Keyboard.__once
self.hotKeySignature = sigCode
self.installGlobalEventHandler()
}
deinit {
_ = RemoveEventHandler(eventHandlerReference)
}
func installGlobalEventHandler() {
signaturesToKeyboards[self.hotKeySignature] = self
var eventTypeSpec = EventTypeSpec()
eventTypeSpec.eventClass = OSType(kEventClassKeyboard)
eventTypeSpec.eventKind = OSType(kEventHotKeyPressed)
var handlerRef:EventHandlerRef? = nil
InstallEventHandler(GetApplicationEventTarget(), {(nextHandler, theEventRef, userData) -> OSStatus in
guard let eventRef = theEventRef else {
return noErr
}
var hkCom = EventHotKeyID()
GetEventParameter(eventRef, EventParamName(kEventParamDirectObject), EventParamType(typeEventHotKeyID), nil, MemoryLayout<EventHotKeyID>.size, nil, &hkCom)
//we place the keyboard objects in a global (private) map to be able to use the simpler
//registration using a closure. A C function pointer cannot be formed from a closure that captures context
if let keyboard = signaturesToKeyboards[hkCom.signature] {
if let keyCombo = keyboard.globalHotKeyIDsToKeyCombo[hkCom.id] {
_ = keyboard.processKeyCombo(keyCombo, event: nil, bindings: keyboard.globalKeyBindings)
}
}
return noErr
}, 1, &eventTypeSpec, nil, &handlerRef)
self.eventHandlerReference = handlerRef
assert(self.eventHandlerReference != nil)
}
public func bindKey(_ key:UInt16, action:@escaping KeyComboAction) {
bindKeyCombo(KeyCombo(keyCode: key), action: action)
}
public func bindKeyCombo(_ keyCombo:KeyCombo, action:@escaping KeyComboAction) {
keyBindings[keyCombo] = action
}
@discardableResult
public func bindGlobalKeyCombo(_ keyCombo:KeyCombo, action:@escaping KeyComboAction) -> Bool {
if (globalKeyBindings[keyCombo] != nil) {
NSLog("Warning: Attempting to re-register global keycombo \(keyCombo), ignoring.")
return true
}
var newHotKeyID = EventHotKeyID()
newHotKeyID.signature = self.hotKeySignature
newHotKeyID.id = nextHotKeyID
nextHotKeyID = nextHotKeyID.advanced(by: 1)
var carbonHotKey:EventHotKeyRef? = nil
let status = RegisterEventHotKey(UInt32(keyCombo.keyCode), keyCombo.carbonModifierFlags, newHotKeyID, GetApplicationEventTarget(), 0, &carbonHotKey)
if let cHK = carbonHotKey {
keyCombo.globalHotKey = GlobalHotKey(newHotKeyID.id, hotKeyReference: cHK)
globalKeyBindings[keyCombo] = action
globalHotKeyIDsToKeyCombo[newHotKeyID.id] = keyCombo
globalKeyCombostoHotKeyID[keyCombo] = newHotKeyID.id
}
else {
print("ERROR, carbon hot key nil. RegisterEventHotKey returned [\(status)].")
}
return true
}
public func unbindKey(_ key:UInt16) {
unbindKeyCombo(KeyCombo(keyCode: key))
}
public func unbindKeyCombo(_ keyCombo: KeyCombo) {
keyBindings.removeValue(forKey: keyCombo)
}
public func unbindGlobalKeyCombo(_ keyCombo: KeyCombo) {
if (globalKeyBindings[keyCombo] == nil) {
NSLog("Warning: Attempting to unregister global keycombo \(keyCombo) that is not in dictionary of bindings, ignoring.")
return
}
if let hotKeyID = globalKeyCombostoHotKeyID[keyCombo] {
let actualKeyCombo = globalHotKeyIDsToKeyCombo.removeValue(forKey: hotKeyID)!
UnregisterEventHotKey(actualKeyCombo.globalHotKey.hotKeyRef)
globalKeyCombostoHotKeyID.removeValue(forKey: keyCombo)
}
globalKeyBindings.removeValue(forKey: keyCombo)
}
///process key event, returns false if no bindings match
public func processEvent(_ event: NSEvent!) -> Bool {
return self.processEvent(event, bindings: self.keyBindings)
}
func processEvent(_ e: NSEvent!, bindings:[KeyCombo: KeyComboAction]) -> Bool {
if let event = e {
let keyCombo:KeyCombo = event.toKeyCombo()
return processKeyCombo(keyCombo, event: event, bindings: bindings)
}
return false
}
func processKeyCombo(_ keyCombo: KeyCombo, event: NSEvent!, bindings:[KeyCombo: KeyComboAction]) -> Bool {
let block:KeyComboAction? = bindings[keyCombo]
if let runBlock = block {
Thread.dispatchAsyncInBackground({ () -> Void in
runBlock(keyCombo, event)
})
}
return block != nil
}
}
public func == (lhs: Keyboard.KeyCombo, rhs: Keyboard.KeyCombo) -> Bool {
//we compare the precomputed hash since comparing keycode + modifierFlags runs the risk that modifierFlags has extraneous data
return lhs.hashValue == rhs.hashValue
}
public extension NSEvent {
public func toKeyCombo() -> Keyboard.KeyCombo { return Keyboard.KeyCombo(keyCode: self.keyCode, modifierFlags: self.modifierFlags) }
}
| mit | 0078aff1fbe4ba2114f65c4319d481b2 | 40.943355 | 167 | 0.654218 | 4.452359 | false | false | false | false |
tevye/DemoIconPalette | DemoIconPalette/SwiftButtonDialog/ButtonPaletteController.swift | 1 | 5471 | //
// ButtonPaletteController.swift
// Wibber
//
// Created by Steve Lu on 2/12/17.
// Copyright © 2017 Steve Lu. All rights reserved.
//
import Foundation
import UIKit
func noop() {
return
}
@objc public class ButtonPaletteController : NSObject, PopupViewDismissalProtocol {
var popView: UIView?
var ctrlr: UIViewController?
var provider: PaletteProviderProtocol?
let popupHeight: Float = 80
let popupWidth: Float = 100
let minWidthPercent: Float = 0.1
let refinedMargin: Float = 0.03
let wrapper:FontAwesomeWrapper = FontAwesomeWrapper()
var exchangeAction: (() -> ())
var homeAction: (() -> ())
init(controller: UIViewController, paletteProvider: PaletteProviderProtocol!) {
ctrlr = controller
exchangeAction = noop
homeAction = noop
provider = paletteProvider
super.init()
provider!.popCloser = self
}
func viewDidLoadAdjunct() {
let gesture = UITapGestureRecognizer(target: self, action: #selector (self.buttonPaletteAction (_:)))
ctrlr!.view.addGestureRecognizer(gesture)
}
func refinedAction(_ sender:UITapGestureRecognizer) {
if popView != nil {
// popView!.backgroundColor = UIColor.whiteColor()
ctrlr!.view.willRemoveSubview(popView!)
popView!.removeFromSuperview()
}
var left = sender.location(ofTouch: 0, in: ctrlr!.view)
if ctrlr!.view.window != nil {
let winDims = ctrlr!.view.window!.screen.bounds
let leftLimit = Float(winDims.width) * refinedMargin + popupWidth / 2
let slideLeft = (Float(winDims.width) * (Float(1.0) - refinedMargin)) - popupWidth
let lx = ((Float(left.x) > (Float(winDims.width) - popupWidth))
? slideLeft
: ((Float(left.x) < leftLimit)
? Float(left.x)
: Float(left.x) - popupWidth / 2))
left.x = CGFloat(lx)
let topLimit = popupHeight + refinedMargin * Float(winDims.height)
let topOffset: Float = refinedMargin * Float(winDims.height)
left.y = CGFloat((Float(left.y) < topLimit)
? Float(left.y) + topOffset
: Float(left.y) - popupHeight)
popView = PopupView(frame: CGRect(x:left.x, y: left.y, width: CGFloat(popupWidth), height: CGFloat(popupHeight)))
ctrlr!.view.addSubview(popView!)
}
}
@objc func setExchangeAction(f: @escaping (() -> ())) {
exchangeAction = f
}
@objc func setHomeAction(f: @escaping (() -> ())) {
homeAction = f
}
public func dismiss() {
NSLog("Dismissing...")
if popView != nil {
ctrlr!.view.willRemoveSubview(popView!)
popView!.removeFromSuperview()
}
}
@objc func exchange() -> Int {
dismiss()
self.exchangeAction();
return 0
}
@objc func home() -> Int {
dismiss()
self.homeAction();
return 0
}
func buildIconList() -> [IconData] {
var rv:[IconData] = [IconData]()
let exchangeButton = UIButton()
var buttonString: String = wrapper.symbolCode("fa-exchange")
var buttonStringAttributed = NSMutableAttributedString(string: buttonString, attributes: [NSFontAttributeName:UIFont(name: "FontAwesome", size: 48)!])
// let buttonStringAttributed = NSMutableAttributedString(string: buttonString, attributes: [NSFontAttributeName:UIFont(name: "HelveticaNeue", size: 11.00)!])
// buttonStringAttributed.addAttribute(NSFontAttributeName, value: UIFont.iconFontOfSize("FontAwesome", fontSize: 50), range: NSRange(location: 0,length: 1))
exchangeButton.titleLabel?.textAlignment = .center
exchangeButton.titleLabel?.numberOfLines = 1
exchangeButton.setAttributedTitle(buttonStringAttributed, for: UIControlState())
exchangeButton.backgroundColor = UIColor.white
exchangeButton.addTarget(self, action: #selector(self.exchange), for: .touchUpInside)
let exb = IconData(h: 50, w: 50, view: exchangeButton, action: exchange)
rv.append(exb)
buttonString = wrapper.symbolCode("fa-home")
let homeButton = UIButton()
buttonStringAttributed = NSMutableAttributedString(string: buttonString, attributes: [NSFontAttributeName:UIFont(name: "FontAwesome", size: 48)!])
homeButton.titleLabel?.textAlignment = .center
homeButton.titleLabel?.numberOfLines = 1
homeButton.setAttributedTitle(buttonStringAttributed, for: UIControlState())
homeButton.backgroundColor = UIColor.white
homeButton.addTarget(self, action: #selector(self.home), for: .touchUpInside)
let homeb = IconData(h: 50, w: 50, view: homeButton, action: home)
rv.append(homeb)
return rv
}
@objc func buttonPaletteAction(_ sender:UITapGestureRecognizer) {
NSLog("In buttonPaletteAction...")
dismiss()
let pt = sender.location(ofTouch: 0, in: ctrlr!.view)
//let icons:[IconData] = buildIconList()
if ctrlr!.view.window != nil {
popView = ButtonDialog(bounds: ctrlr!.view.window!.screen.bounds, point: pt, icons: provider!.getPalette(), maxColumns: 4)
ctrlr!.view.addSubview(popView!)
}
}
}
| mit | 5de9f65f251e3942e8b386c5931f062e | 37.251748 | 167 | 0.621572 | 4.623838 | false | false | false | false |
mchakravarty/goalsapp | Goals/Goals/DetailController.swift | 1 | 1804 | //
// DetailController.swift
// Goals
//
// Created by Manuel M T Chakravarty on 17/07/2016.
// Copyright © 2016 Chakravarty & Keller. All rights reserved.
//
import UIKit
class DetailController: UIViewController {
@IBOutlet fileprivate weak var titleLabel: UILabel!
@IBOutlet fileprivate weak var titleTextField: UITextField!
@IBOutlet fileprivate weak var intervalLabel: UILabel!
@IBOutlet fileprivate weak var frequency: UILabel!
@IBOutlet fileprivate weak var colour: UIImageView?
/// The goal presented and edited by this view controller.
///
var goal: Goal? {
didSet {
updateGoalUI()
}
}
/// Changes inlet consuming goal detail edits.
///
var goalEdits: ChangesInlet<GoalEdit>?
override func viewDidLoad() {
super.viewDidLoad()
updateGoalUI()
titleTextField.isHidden = true
}
private func updateGoalUI() {
if isViewLoaded {
navigationItem.title = goal?.title
titleLabel.text = goal?.title
intervalLabel.text = goal?.interval.description
frequency.text = goal?.frequencyPerInterval
colour?.backgroundColor = goal?.colour
}
}
// TODO: Add support to edit the other properties of a goal.
@IBAction func tappedTitle(_ sender: AnyObject) {
titleTextField.text = goal?.title
titleTextField.isHidden = false
titleLabel.isHidden = true
titleTextField.becomeFirstResponder()
}
@IBAction func titleFinishedEditing(_ sender: AnyObject) {
titleTextField.isHidden = true
titleLabel.isHidden = false
}
@IBAction func titleChanged(_ sender: AnyObject) {
let newTitle = titleTextField.text ?? ""
goal?.title = newTitle
if let goal = goal { goalEdits?.announce(change: .update(goal: goal)) }
}
}
| bsd-2-clause | f2b20beef27138421cb257ffd85e2d51 | 25.130435 | 75 | 0.678314 | 4.496259 | false | false | false | false |
RMizin/PigeonMessenger-project | FalconMessenger/Supporting Files/UIComponents/INSPhotosGallery/INSPhotosDataSource.swift | 1 | 1695 | //
// INSPhotosViewControllerDataSource.swift
// INSPhotoViewer
//
// Created by Michal Zaborowski on 28.02.2016.
// Copyright © 2016 Inspace Labs Sp z o. o. Spółka Komandytowa. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this library except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
public struct INSPhotosDataSource {
private(set) var photos: [INSPhotoViewable] = []
public var numberOfPhotos: Int {
return photos.count
}
public func photoAtIndex(_ index: Int) -> INSPhotoViewable? {
if (index < photos.count && index >= 0) {
return photos[index]
}
return nil
}
public func indexOfPhoto(_ photo: INSPhotoViewable) -> Int? {
return photos.firstIndex(where: { $0 === photo})
}
public func containsPhoto(_ photo: INSPhotoViewable) -> Bool {
return indexOfPhoto(photo) != nil
}
public mutating func deletePhoto(_ photo: INSPhotoViewable){
if let index = self.indexOfPhoto(photo){
photos.remove(at: index)
}
}
public subscript(index: Int) -> INSPhotoViewable? {
get {
return photoAtIndex(index)
}
}
}
| gpl-3.0 | d3c18bba2d68a0c5fc1dc40c2d68cbeb | 29.763636 | 85 | 0.654846 | 4.272727 | false | false | false | false |
longjianjiang/BlogDemo | VCInteractiveNavigationAnimation/VCInteractiveNavigationAnimation/InteractiveAnimator.swift | 1 | 2417 | //
// InteractiveAnimator.swift
// VCInteractiveNavigationAnimation
//
// Created by longjianjiang on 2017/10/13.
// Copyright © 2017年 Jiang. All rights reserved.
//
import UIKit
class InteractiveAnimator: NSObject, UIViewControllerAnimatedTransitioning {
let animationDuration = 2.0
var interactive = false
var reverse: Bool = false
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return animationDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
let toVC = transitionContext.viewController(forKey: .to)!
let fromVC = transitionContext.viewController(forKey: .from)!
let toView = toVC.view!
let fromView = fromVC.view!
let direction: CGFloat = reverse ? -1 : 1
let const: CGFloat = -0.005
toView.layer.anchorPoint = CGPoint(x: direction == 1 ? 0 : 1, y: 0.5)
fromView.layer.anchorPoint = CGPoint(x: direction == 1 ? 1 : 0, y: 0.5)
var viewFromTransform = CATransform3DMakeRotation(direction * .pi/2, 0.0, 1.0, 0.0)
var viewToTransform = CATransform3DMakeRotation(-direction * .pi/2, 0.0, 1.0, 0.0)
viewFromTransform.m34 = const
viewToTransform.m34 = const
containerView.transform = CGAffineTransform(translationX: direction * containerView.frame.width / 2.0, y: 0)
toView.layer.transform = viewToTransform
containerView.addSubview(toView)
UIView.animate(withDuration: animationDuration, animations: {
containerView.transform = CGAffineTransform(translationX: -direction * containerView.frame.width / 2.0, y: 0)
fromView.layer.transform = viewFromTransform
toView.layer.transform = CATransform3DIdentity
}, completion: { _ in
containerView.transform = CGAffineTransform.identity
fromView.layer.transform = CATransform3DIdentity
toView.layer.transform = CATransform3DIdentity
fromView.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
toView.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
| apache-2.0 | 38dbf2b20a6ad9a35fcf1ce4f1368b5d | 39.915254 | 121 | 0.666114 | 4.906504 | false | false | false | false |
ahoppen/swift | test/SILGen/function_conversion.swift | 4 | 37453 |
// RUN: %target-swift-emit-silgen -module-name function_conversion -primary-file %s | %FileCheck %s
// RUN: %target-swift-emit-ir -module-name function_conversion -primary-file %s
// Check SILGen against various FunctionConversionExprs emitted by Sema.
// ==== Representation conversions
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion7cToFuncyS2icS2iXCF : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @callee_guaranteed (Int) -> Int
// CHECK: [[THUNK:%.*]] = function_ref @$sS2iIetCyd_S2iIegyd_TR
// CHECK: [[FUNC:%.*]] = partial_apply [callee_guaranteed] [[THUNK]](%0)
// CHECK: return [[FUNC]]
func cToFunc(_ arg: @escaping @convention(c) (Int) -> Int) -> (Int) -> Int {
return arg
}
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion8cToBlockyS2iXBS2iXCF : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @convention(block) (Int) -> Int
// CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage
// CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]]
// CHECK: [[COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) (Int) -> Int
// CHECK: return [[COPY]]
func cToBlock(_ arg: @escaping @convention(c) (Int) -> Int) -> @convention(block) (Int) -> Int {
return arg
}
// ==== Throws variance
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12funcToThrowsyyyKcyycF : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @owned @callee_guaranteed () -> @error Error
// CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed () -> ()):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[FUNC:%.*]] = convert_function [[ARG_COPY]] : $@callee_guaranteed () -> () to $@callee_guaranteed () -> @error Error
// CHECK: return [[FUNC]]
// CHECK: } // end sil function '$s19function_conversion12funcToThrowsyyyKcyycF'
func funcToThrows(_ x: @escaping () -> ()) -> () throws -> () {
return x
}
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12thinToThrowsyyyKXfyyXfF : $@convention(thin) (@convention(thin) () -> ()) -> @convention(thin) () -> @error Error
// CHECK: [[FUNC:%.*]] = convert_function %0 : $@convention(thin) () -> () to $@convention(thin) () -> @error Error
// CHECK: return [[FUNC]] : $@convention(thin) () -> @error Error
func thinToThrows(_ x: @escaping @convention(thin) () -> ()) -> @convention(thin) () throws -> () {
return x
}
// FIXME: triggers an assert because we always do a thin to thick conversion on DeclRefExprs
/*
func thinFunc() {}
func thinToThrows() {
let _: @convention(thin) () -> () = thinFunc
}
*/
// ==== Class downcasts and upcasts
class Feral {}
class Domesticated : Feral {}
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12funcToUpcastyAA5FeralCycAA12DomesticatedCycF : $@convention(thin) (@guaranteed @callee_guaranteed () -> @owned Domesticated) -> @owned @callee_guaranteed () -> @owned Feral {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed () -> @owned Domesticated):
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[FUNC:%.*]] = convert_function [[ARG_COPY]] : $@callee_guaranteed () -> @owned Domesticated to $@callee_guaranteed () -> @owned Feral
// CHECK: return [[FUNC]]
// CHECK: } // end sil function '$s19function_conversion12funcToUpcastyAA5FeralCycAA12DomesticatedCycF'
func funcToUpcast(_ x: @escaping () -> Domesticated) -> () -> Feral {
return x
}
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12funcToUpcastyyAA12DomesticatedCcyAA5FeralCcF : $@convention(thin) (@guaranteed @callee_guaranteed (@guaranteed Feral) -> ()) -> @owned @callee_guaranteed (@guaranteed Domesticated) -> ()
// CHECK: bb0([[ARG:%.*]] :
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[FUNC:%.*]] = convert_function [[ARG_COPY]] : $@callee_guaranteed (@guaranteed Feral) -> () to $@callee_guaranteed (@guaranteed Domesticated) -> (){{.*}}
// CHECK: return [[FUNC]]
func funcToUpcast(_ x: @escaping (Feral) -> ()) -> (Domesticated) -> () {
return x
}
// ==== Optionals
struct Trivial {
let n: Int8
}
class C {
let n: Int8
init(n: Int8) {
self.n = n
}
}
struct Loadable {
let c: C
var n: Int8 {
return c.n
}
init(n: Int8) {
c = C(n: n)
}
}
struct AddrOnly {
let a: Any
var n: Int8 {
return a as! Int8
}
init(n: Int8) {
a = n
}
}
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion19convOptionalTrivialyyAA0E0VADSgcF
func convOptionalTrivial(_ t1: @escaping (Trivial?) -> Trivial) {
// CHECK: function_ref @$s19function_conversion7TrivialVSgACIegyd_AcDIegyd_TR
// CHECK: partial_apply
let _: (Trivial) -> Trivial? = t1
// CHECK: function_ref @$s19function_conversion7TrivialVSgACIegyd_A2DIegyd_TR
// CHECK: partial_apply
let _: (Trivial?) -> Trivial? = t1
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion7TrivialVSgACIegyd_AcDIegyd_TR : $@convention(thin) (Trivial, @guaranteed @callee_guaranteed (Optional<Trivial>) -> Trivial) -> Optional<Trivial>
// CHECK: [[ENUM:%.*]] = enum $Optional<Trivial>
// CHECK-NEXT: apply %1([[ENUM]])
// CHECK-NEXT: enum $Optional<Trivial>
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion7TrivialVSgACIegyd_A2DIegyd_TR : $@convention(thin) (Optional<Trivial>, @guaranteed @callee_guaranteed (Optional<Trivial>) -> Trivial) -> Optional<Trivial>
// CHECK: apply %1(%0)
// CHECK-NEXT: enum $Optional<Trivial>
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion20convOptionalLoadableyyAA0E0VADSgcF
func convOptionalLoadable(_ l1: @escaping (Loadable?) -> Loadable) {
// CHECK: function_ref @$s19function_conversion8LoadableVSgACIeggo_AcDIeggo_TR
// CHECK: partial_apply
let _: (Loadable) -> Loadable? = l1
// CHECK: function_ref @$s19function_conversion8LoadableVSgACIeggo_A2DIeggo_TR
// CHECK: partial_apply
let _: (Loadable?) -> Loadable? = l1
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion8LoadableVSgACIeggo_A2DIeggo_TR : $@convention(thin) (@guaranteed Optional<Loadable>, @guaranteed @callee_guaranteed (@guaranteed Optional<Loadable>) -> @owned Loadable) -> @owned Optional<Loadable>
// CHECK: apply %1(%0)
// CHECK-NEXT: enum $Optional<Loadable>
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion20convOptionalAddrOnlyyyAA0eF0VADSgcF
func convOptionalAddrOnly(_ a1: @escaping (AddrOnly?) -> AddrOnly) {
// CHECK: function_ref @$s19function_conversion8AddrOnlyVSgACIegnr_A2DIegnr_TR
// CHECK: partial_apply
let _: (AddrOnly?) -> AddrOnly? = a1
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion8AddrOnlyVSgACIegnr_A2DIegnr_TR : $@convention(thin) (@in_guaranteed Optional<AddrOnly>, @guaranteed @callee_guaranteed (@in_guaranteed Optional<AddrOnly>) -> @out AddrOnly) -> @out Optional<AddrOnly>
// CHECK: [[TEMP:%.*]] = alloc_stack $AddrOnly
// CHECK-NEXT: apply %2([[TEMP]], %1)
// CHECK-NEXT: init_enum_data_addr %0 : $*Optional<AddrOnly>
// CHECK-NEXT: copy_addr [take] {{.*}} to [initialization] {{.*}} : $*AddrOnly
// CHECK-NEXT: inject_enum_addr %0 : $*Optional<AddrOnly>
// CHECK-NEXT: tuple ()
// CHECK-NEXT: dealloc_stack {{.*}} : $*AddrOnly
// CHECK-NEXT: return
// ==== Existentials
protocol Q {
var n: Int8 { get }
}
protocol P : Q {}
extension Trivial : P {}
extension Loadable : P {}
extension AddrOnly : P {}
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion22convExistentialTrivial_2t3yAA0E0VAA1Q_pc_AeaF_pSgctF
func convExistentialTrivial(_ t2: @escaping (Q) -> Trivial, t3: @escaping (Q?) -> Trivial) {
// CHECK: function_ref @$s19function_conversion1Q_pAA7TrivialVIegnd_AdA1P_pIegyr_TR
// CHECK: partial_apply
let _: (Trivial) -> P = t2
// CHECK: function_ref @$s19function_conversion1Q_pSgAA7TrivialVIegnd_AESgAA1P_pIegyr_TR
// CHECK: partial_apply
let _: (Trivial?) -> P = t3
// CHECK: function_ref @$s19function_conversion1Q_pAA7TrivialVIegnd_AA1P_pAaE_pIegnr_TR
// CHECK: partial_apply
let _: (P) -> P = t2
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pAA7TrivialVIegnd_AdA1P_pIegyr_TR : $@convention(thin) (Trivial, @guaranteed @callee_guaranteed (@in_guaranteed Q) -> Trivial) -> @out P
// CHECK: alloc_stack $Q
// CHECK-NEXT: init_existential_addr
// CHECK-NEXT: store
// CHECK-NEXT: apply
// CHECK-NEXT: init_existential_addr
// CHECK-NEXT: store
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pSgAA7TrivialVIegnd_AESgAA1P_pIegyr_TR
// CHECK: switch_enum
// CHECK: bb1([[TRIVIAL:%.*]] : $Trivial):
// CHECK: init_existential_addr
// CHECK: init_enum_data_addr
// CHECK: copy_addr
// CHECK: inject_enum_addr
// CHECK: bb2:
// CHECK: inject_enum_addr
// CHECK: bb3:
// CHECK: apply
// CHECK: init_existential_addr
// CHECK: store
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pAA7TrivialVIegnd_AA1P_pAaE_pIegnr_TR : $@convention(thin) (@in_guaranteed P, @guaranteed @callee_guaranteed (@in_guaranteed Q) -> Trivial) -> @out P
// CHECK: [[TMP:%.*]] = alloc_stack $Q
// CHECK-NEXT: open_existential_addr immutable_access %1 : $*P
// CHECK-NEXT: init_existential_addr [[TMP]] : $*Q
// CHECK-NEXT: copy_addr {{.*}} to [initialization] {{.*}}
// CHECK-NEXT: apply
// CHECK-NEXT: init_existential_addr
// CHECK-NEXT: store
// CHECK: destroy_addr
// CHECK: return
// ==== Existential metatypes
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion23convExistentialMetatypeyyAA7TrivialVmAA1Q_pXpSgcF
func convExistentialMetatype(_ em: @escaping (Q.Type?) -> Trivial.Type) {
// CHECK: function_ref @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtAA1P_pXmTIegyd_TR
// CHECK: partial_apply
let _: (Trivial.Type) -> P.Type = em
// CHECK: function_ref @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtSgAA1P_pXmTIegyd_TR
// CHECK: partial_apply
let _: (Trivial.Type?) -> P.Type = em
// CHECK: function_ref @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AA1P_pXmTAaF_pXmTIegyd_TR
// CHECK: partial_apply
let _: (P.Type) -> P.Type = em
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtAA1P_pXmTIegyd_TR : $@convention(thin) (@thin Trivial.Type, @guaranteed @callee_guaranteed (Optional<@thick Q.Type>) -> @thin Trivial.Type) -> @thick P.Type
// CHECK: [[META:%.*]] = metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype [[META]] : $@thick Trivial.Type, $@thick Q.Type
// CHECK-NEXT: enum $Optional<@thick Q.Type>
// CHECK-NEXT: apply
// CHECK-NEXT: metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AEXMtSgAA1P_pXmTIegyd_TR : $@convention(thin) (Optional<@thin Trivial.Type>, @guaranteed @callee_guaranteed (Optional<@thick Q.Type>) -> @thin Trivial.Type) -> @thick P.Type
// CHECK: switch_enum %0 : $Optional<@thin Trivial.Type>
// CHECK: bb1([[META:%.*]] : $@thin Trivial.Type):
// CHECK-NEXT: metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick Q.Type
// CHECK-NEXT: enum $Optional<@thick Q.Type>
// CHECK: bb2:
// CHECK-NEXT: enum $Optional<@thick Q.Type>
// CHECK: bb3({{.*}}):
// CHECK-NEXT: apply
// CHECK-NEXT: metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pXmTSgAA7TrivialVXMtIegyd_AA1P_pXmTAaF_pXmTIegyd_TR : $@convention(thin) (@thick P.Type, @guaranteed @callee_guaranteed (Optional<@thick Q.Type>) -> @thin Trivial.Type) -> @thick P.Type
// CHECK: open_existential_metatype %0 : $@thick P.Type to $@thick (@opened({{.*}}) P).Type
// CHECK-NEXT: init_existential_metatype %2 : $@thick (@opened({{.*}}) P).Type, $@thick Q.Type
// CHECK-NEXT: enum $Optional<@thick Q.Type>
// CHECK-NEXT: apply %1
// CHECK-NEXT: metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type
// CHECK-NEXT: return
// ==== Class metatype upcasts
class Parent {}
class Child : Parent {}
// Note: we add a Trivial => Trivial? conversion here to force a thunk
// to be generated
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion18convUpcastMetatype_2c5yAA5ChildCmAA6ParentCm_AA7TrivialVSgtc_AEmAGmSg_AJtctF
func convUpcastMetatype(_ c4: @escaping (Parent.Type, Trivial?) -> Child.Type,
c5: @escaping (Parent.Type?, Trivial?) -> Child.Type) {
// CHECK: function_ref @$s19function_conversion6ParentCXMTAA7TrivialVSgAA5ChildCXMTIegyyd_AHXMTAeCXMTIegyyd_TR
// CHECK: partial_apply
let _: (Child.Type, Trivial) -> Parent.Type = c4
// CHECK: function_ref @$s19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTAfCXMTIegyyd_TR
// CHECK: partial_apply
let _: (Child.Type, Trivial) -> Parent.Type = c5
// CHECK: function_ref @$s19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTSgAfDIegyyd_TR
// CHECK: partial_apply
let _: (Child.Type?, Trivial) -> Parent.Type? = c5
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCXMTAA7TrivialVSgAA5ChildCXMTIegyyd_AHXMTAeCXMTIegyyd_TR : $@convention(thin) (@thick Child.Type, Trivial, @guaranteed @callee_guaranteed (@thick Parent.Type, Optional<Trivial>) -> @thick Child.Type) -> @thick Parent.Type
// CHECK: upcast %0 : $@thick Child.Type to $@thick Parent.Type
// CHECK: apply
// CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTAfCXMTIegyyd_TR : $@convention(thin) (@thick Child.Type, Trivial, @guaranteed @callee_guaranteed (Optional<@thick Parent.Type>, Optional<Trivial>) -> @thick Child.Type) -> @thick Parent.Type
// CHECK: upcast %0 : $@thick Child.Type to $@thick Parent.Type
// CHECK: enum $Optional<@thick Parent.Type>
// CHECK: apply
// CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCXMTSgAA7TrivialVSgAA5ChildCXMTIegyyd_AIXMTSgAfDIegyyd_TR : $@convention(thin) (Optional<@thick Child.Type>, Trivial, @guaranteed @callee_guaranteed (Optional<@thick Parent.Type>, Optional<Trivial>) -> @thick Child.Type) -> Optional<@thick Parent.Type>
// CHECK: unchecked_trivial_bit_cast %0 : $Optional<@thick Child.Type> to $Optional<@thick Parent.Type>
// CHECK: apply
// CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type
// CHECK: enum $Optional<@thick Parent.Type>
// CHECK: return
// ==== Function to existential -- make sure we maximally abstract it
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion19convFuncExistentialyyS2icypcF : $@convention(thin) (@guaranteed @callee_guaranteed (@in_guaranteed Any) -> @owned @callee_guaranteed (Int) -> Int) -> ()
// CHECK: bb0([[ARG:%.*]] :
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: [[REABSTRACT_THUNK:%.*]] = function_ref @$sypS2iIegyd_Iegno_S2iIegyd_ypIeggr_TR :
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT_THUNK]]([[ARG_COPY]])
// CHECK: destroy_value [[PA]]
// CHECK: } // end sil function '$s19function_conversion19convFuncExistentialyyS2icypcF'
func convFuncExistential(_ f1: @escaping (Any) -> (Int) -> Int) {
let _: (@escaping (Int) -> Int) -> Any = f1
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sypS2iIegyd_Iegno_S2iIegyd_ypIeggr_TR : $@convention(thin) (@guaranteed @callee_guaranteed (Int) -> Int, @guaranteed @callee_guaranteed (@in_guaranteed Any) -> @owned @callee_guaranteed (Int) -> Int) -> @out Any {
// CHECK: [[EXISTENTIAL:%.*]] = alloc_stack $Any
// CHECK: [[COPIED_VAL:%.*]] = copy_value
// CHECK: function_ref @$sS2iIegyd_S2iIegnr_TR
// CHECK-NEXT: [[PA:%.*]] = partial_apply [callee_guaranteed] {{%.*}}([[COPIED_VAL]])
// CHECK-NEXT: [[CF:%.*]] = convert_function [[PA]]
// CHECK-NEXT: init_existential_addr [[EXISTENTIAL]] : $*Any, $(Int) -> Int
// CHECK-NEXT: store [[CF]]
// CHECK-NEXT: apply
// CHECK: function_ref @$sS2iIegyd_S2iIegnr_TR
// CHECK-NEXT: partial_apply
// CHECK-NEXT: convert_function
// CHECK-NEXT: init_existential_addr %0 : $*Any, $(Int) -> Int
// CHECK-NEXT: store {{.*}} to {{.*}} : $*@callee_guaranteed @substituted <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0) -> @out τ_0_1 for <Int, Int>
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sS2iIegyd_S2iIegnr_TR : $@convention(thin) (@in_guaranteed Int, @guaranteed @callee_guaranteed (Int) -> Int) -> @out Int
// CHECK: [[LOADED:%.*]] = load [trivial] %1 : $*Int
// CHECK-NEXT: apply %2([[LOADED]])
// CHECK-NEXT: store {{.*}} to [trivial] %0
// CHECK-NEXT: [[VOID:%.*]] = tuple ()
// CHECK: return [[VOID]]
// ==== Class-bound archetype upcast
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion29convClassBoundArchetypeUpcast{{[_0-9a-zA-Z]*}}F
func convClassBoundArchetypeUpcast<T : Parent>(_ f1: @escaping (Parent) -> (T, Trivial)) {
// CHECK: function_ref @$s19function_conversion6ParentCxAA7TrivialVIeggod_xAcESgIeggod_ACRbzlTR
// CHECK: partial_apply
let _: (T) -> (Parent, Trivial?) = f1
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCxAA7TrivialVIeggod_xAcESgIeggod_ACRbzlTR : $@convention(thin) <T where T : Parent> (@guaranteed T, @guaranteed @callee_guaranteed (@guaranteed Parent) -> (@owned T, Trivial)) -> (@owned Parent, Optional<Trivial>)
// CHECK: bb0([[ARG:%.*]] : @guaranteed $T, [[CLOSURE:%.*]] : @guaranteed $@callee_guaranteed (@guaranteed Parent) -> (@owned T, Trivial)):
// CHECK: [[CASTED_ARG:%.*]] = upcast [[ARG]] : $T to $Parent
// CHECK: [[RESULT:%.*]] = apply %1([[CASTED_ARG]])
// CHECK: ([[LHS:%.*]], [[RHS:%.*]]) = destructure_tuple [[RESULT]]
// CHECK: [[LHS_CAST:%.*]] = upcast [[LHS]] : $T to $Parent
// CHECK: [[RHS_OPT:%.*]] = enum $Optional<Trivial>, #Optional.some!enumelt, [[RHS]]
// CHECK: [[RESULT:%.*]] = tuple ([[LHS_CAST]] : $Parent, [[RHS_OPT]] : $Optional<Trivial>)
// CHECK: return [[RESULT]]
// CHECK: } // end sil function '$s19function_conversion6ParentCxAA7TrivialVIeggod_xAcESgIeggod_ACRbzlTR'
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion37convClassBoundMetatypeArchetypeUpcast{{[_0-9a-zA-Z]*}}F
func convClassBoundMetatypeArchetypeUpcast<T : Parent>(_ f1: @escaping (Parent.Type) -> (T.Type, Trivial)) {
// CHECK: function_ref @$s19function_conversion6ParentCXMTxXMTAA7TrivialVIegydd_xXMTACXMTAESgIegydd_ACRbzlTR
// CHECK: partial_apply
let _: (T.Type) -> (Parent.Type, Trivial?) = f1
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion6ParentCXMTxXMTAA7TrivialVIegydd_xXMTACXMTAESgIegydd_ACRbzlTR : $@convention(thin) <T where T : Parent> (@thick T.Type, @guaranteed @callee_guaranteed (@thick Parent.Type) -> (@thick T.Type, Trivial)) -> (@thick Parent.Type, Optional<Trivial>)
// CHECK: bb0([[META:%.*]] :
// CHECK: upcast %0 : $@thick T.Type
// CHECK-NEXT: apply
// CHECK-NEXT: destructure_tuple
// CHECK-NEXT: upcast {{.*}} : $@thick T.Type to $@thick Parent.Type
// CHECK-NEXT: enum $Optional<Trivial>
// CHECK-NEXT: tuple
// CHECK-NEXT: return
// ==== Make sure we destructure one-element tuples
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion15convTupleScalar_2f22f3yyAA1Q_pc_yAaE_pcySi_SitSgctF
// CHECK: function_ref @$s19function_conversion1Q_pIegn_AA1P_pIegn_TR
// CHECK: function_ref @$s19function_conversion1Q_pIegn_AA1P_pIegn_TR
// CHECK: function_ref @$sSi_SitSgIegy_S2iIegyy_TR
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$s19function_conversion1Q_pIegn_AA1P_pIegn_TR : $@convention(thin) (@in_guaranteed P, @guaranteed @callee_guaranteed (@in_guaranteed Q) -> ()) -> ()
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sSi_SitSgIegy_S2iIegyy_TR : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (Optional<(Int, Int)>) -> ()) -> ()
func convTupleScalar(_ f1: @escaping (Q) -> (),
f2: @escaping (_ parent: Q) -> (),
f3: @escaping (_ tuple: (Int, Int)?) -> ()) {
let _: (P) -> () = f1
let _: (P) -> () = f2
let _: ((Int, Int)) -> () = f3
}
func convTupleScalarOpaque<T>(_ f: @escaping (T...) -> ()) -> ((_ args: T...) -> ())? {
return f
}
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion25convTupleToOptionalDirectySi_SitSgSicSi_SitSicF : $@convention(thin) (@guaranteed @callee_guaranteed (Int) -> (Int, Int)) -> @owned @callee_guaranteed (Int) -> Optional<(Int, Int)>
// CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed (Int) -> (Int, Int)):
// CHECK: [[FN:%.*]] = copy_value [[ARG]]
// CHECK: [[THUNK_FN:%.*]] = function_ref @$sS3iIegydd_S2i_SitSgIegyd_TR
// CHECK-NEXT: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]([[FN]])
// CHECK-NEXT: return [[THUNK]]
// CHECK-NEXT: } // end sil function '$s19function_conversion25convTupleToOptionalDirectySi_SitSgSicSi_SitSicF'
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sS3iIegydd_S2i_SitSgIegyd_TR : $@convention(thin) (Int, @guaranteed @callee_guaranteed (Int) -> (Int, Int)) -> Optional<(Int, Int)>
// CHECK: bb0(%0 : $Int, %1 : @guaranteed $@callee_guaranteed (Int) -> (Int, Int)):
// CHECK: [[RESULT:%.*]] = apply %1(%0)
// CHECK-NEXT: ([[LEFT:%.*]], [[RIGHT:%.*]]) = destructure_tuple [[RESULT]]
// CHECK-NEXT: [[RESULT:%.*]] = tuple ([[LEFT]] : $Int, [[RIGHT]] : $Int)
// CHECK-NEXT: [[OPTIONAL:%.*]] = enum $Optional<(Int, Int)>, #Optional.some!enumelt, [[RESULT]]
// CHECK-NEXT: return [[OPTIONAL]]
// CHECK-NEXT: } // end sil function '$sS3iIegydd_S2i_SitSgIegyd_TR'
func convTupleToOptionalDirect(_ f: @escaping (Int) -> (Int, Int)) -> (Int) -> (Int, Int)? {
return f
}
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion27convTupleToOptionalIndirectyx_xtSgxcx_xtxclF : $@convention(thin) <T> (@guaranteed @callee_guaranteed @substituted <τ_0_0, τ_0_1, τ_0_2> (@in_guaranteed τ_0_0) -> (@out τ_0_1, @out τ_0_2) for <T, T, T>) -> @owned @callee_guaranteed @substituted <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_1 == (τ_0_2, τ_0_3)> (@in_guaranteed τ_0_0) -> @out Optional<(τ_0_2, τ_0_3)> for <T, (T, T), T, T>
// CHECK: bb0([[ARG:%.*]] : @guaranteed $@callee_guaranteed @substituted <τ_0_0, τ_0_1, τ_0_2> (@in_guaranteed τ_0_0) -> (@out τ_0_1, @out τ_0_2) for <T, T, T>):
// CHECK: [[FN:%.*]] = copy_value [[ARG]]
// CHECK-NEXT: [[FN_CONV:%.*]] = convert_function [[FN]]
// CHECK: [[THUNK_FN:%.*]] = function_ref @$sxxxIegnrr_xx_xtSgIegnr_lTR
// CHECK-NEXT: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<T>([[FN_CONV]])
// CHECK-NEXT: [[THUNK_CONV:%.*]] = convert_function [[THUNK]]
// CHECK-NEXT: return [[THUNK_CONV]]
// CHECK-NEXT: } // end sil function '$s19function_conversion27convTupleToOptionalIndirectyx_xtSgxcx_xtxclF'
// CHECK: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sxxxIegnrr_xx_xtSgIegnr_lTR : $@convention(thin) <T> (@in_guaranteed T, @guaranteed @callee_guaranteed (@in_guaranteed T) -> (@out T, @out T)) -> @out Optional<(T, T)>
// CHECK: bb0(%0 : $*Optional<(T, T)>, %1 : $*T, %2 : @guaranteed $@callee_guaranteed (@in_guaranteed T) -> (@out T, @out T)):
// CHECK: [[OPTIONAL:%.*]] = init_enum_data_addr %0 : $*Optional<(T, T)>, #Optional.some!enumelt
// CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[OPTIONAL]] : $*(T, T), 0
// CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[OPTIONAL]] : $*(T, T), 1
// CHECK-NEXT: apply %2([[LEFT]], [[RIGHT]], %1)
// CHECK-NEXT: inject_enum_addr %0 : $*Optional<(T, T)>, #Optional.some!enumelt
// CHECK-NEXT: [[VOID:%.*]] = tuple ()
// CHECK: return [[VOID]]
func convTupleToOptionalIndirect<T>(_ f: @escaping (T) -> (T, T)) -> (T) -> (T, T)? {
return f
}
// ==== Make sure we support AnyHashable erasure
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion15convAnyHashable1tyx_tSHRzlF
// CHECK: function_ref @$s19function_conversion15convAnyHashable1tyx_tSHRzlFSbs0dE0V_AEtcfU_
// CHECK: function_ref @$ss11AnyHashableVABSbIegnnd_xxSbIegnnd_SHRzlTR
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$ss11AnyHashableVABSbIegnnd_xxSbIegnnd_SHRzlTR : $@convention(thin) <T where T : Hashable> (@in_guaranteed T, @in_guaranteed T, @guaranteed @callee_guaranteed (@in_guaranteed AnyHashable, @in_guaranteed AnyHashable) -> Bool) -> Bool
// CHECK: alloc_stack $AnyHashable
// CHECK: function_ref @$ss21_convertToAnyHashableys0cD0VxSHRzlF
// CHECK: apply {{.*}}<T>
// CHECK: alloc_stack $AnyHashable
// CHECK: function_ref @$ss21_convertToAnyHashableys0cD0VxSHRzlF
// CHECK: apply {{.*}}<T>
// CHECK: return
func convAnyHashable<T : Hashable>(t: T) {
let fn: (T, T) -> Bool = {
(x: AnyHashable, y: AnyHashable) in x == y
}
}
// ==== Convert exploded tuples to Any or Optional<Any>
// CHECK-LABEL: sil hidden [ossa] @$s19function_conversion12convTupleAnyyyyyc_Si_SitycyypcyypSgctF
// CHECK: function_ref @$sIeg_ypIegr_TR
// CHECK: partial_apply
// CHECK: function_ref @$sIeg_ypSgIegr_TR
// CHECK: partial_apply
// CHECK: function_ref @$sS2iIegdd_ypIegr_TR
// CHECK: partial_apply
// CHECK: function_ref @$sS2iIegdd_ypSgIegr_TR
// CHECK: partial_apply
// CHECK: function_ref @$sypIegn_S2iIegyy_TR
// CHECK: partial_apply
// CHECK: function_ref @$sypSgIegn_S2iIegyy_TR
// CHECK: partial_apply
func convTupleAny(_ f1: @escaping () -> (),
_ f2: @escaping () -> (Int, Int),
_ f3: @escaping (Any) -> (),
_ f4: @escaping (Any?) -> ()) {
let _: () -> Any = f1
let _: () -> Any? = f1
let _: () -> Any = f2
let _: () -> Any? = f2
let _: ((Int, Int)) -> () = f3
let _: ((Int, Int)) -> () = f4
}
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sIeg_ypIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @out Any
// CHECK: init_existential_addr %0 : $*Any, $()
// CHECK-NEXT: apply %1()
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sIeg_ypSgIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> ()) -> @out Optional<Any>
// CHECK: [[ENUM_PAYLOAD:%.*]] = init_enum_data_addr %0 : $*Optional<Any>, #Optional.some!enumelt
// CHECK-NEXT: init_existential_addr [[ENUM_PAYLOAD]] : $*Any, $()
// CHECK-NEXT: apply %1()
// CHECK-NEXT: inject_enum_addr %0 : $*Optional<Any>, #Optional.some!enumelt
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sS2iIegdd_ypIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> (Int, Int)) -> @out Any
// CHECK: [[ANY_PAYLOAD:%.*]] = init_existential_addr %0
// CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]]
// CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]]
// CHECK-NEXT: [[RESULT:%.*]] = apply %1()
// CHECK-NEXT: ([[LEFT:%.*]], [[RIGHT:%.*]]) = destructure_tuple [[RESULT]]
// CHECK-NEXT: store [[LEFT:%.*]] to [trivial] [[LEFT_ADDR]]
// CHECK-NEXT: store [[RIGHT:%.*]] to [trivial] [[RIGHT_ADDR]]
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sS2iIegdd_ypSgIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> (Int, Int)) -> @out Optional<Any> {
// CHECK: [[OPTIONAL_PAYLOAD:%.*]] = init_enum_data_addr %0
// CHECK-NEXT: [[ANY_PAYLOAD:%.*]] = init_existential_addr [[OPTIONAL_PAYLOAD]]
// CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]]
// CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]]
// CHECK-NEXT: [[RESULT:%.*]] = apply %1()
// CHECK-NEXT: ([[LEFT:%.*]], [[RIGHT:%.*]]) = destructure_tuple [[RESULT]]
// CHECK-NEXT: store [[LEFT:%.*]] to [trivial] [[LEFT_ADDR]]
// CHECK-NEXT: store [[RIGHT:%.*]] to [trivial] [[RIGHT_ADDR]]
// CHECK-NEXT: inject_enum_addr %0
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sypIegn_S2iIegyy_TR : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (@in_guaranteed Any) -> ()) -> ()
// CHECK: [[ANY_VALUE:%.*]] = alloc_stack $Any
// CHECK-NEXT: [[ANY_PAYLOAD:%.*]] = init_existential_addr [[ANY_VALUE]]
// CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]]
// CHECK-NEXT: store %0 to [trivial] [[LEFT_ADDR]]
// CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]]
// CHECK-NEXT: store %1 to [trivial] [[RIGHT_ADDR]]
// CHECK-NEXT: apply %2([[ANY_VALUE]])
// CHECK-NEXT: tuple ()
// CHECK-NEXT: destroy_addr [[ANY_VALUE]]
// CHECK-NEXT: dealloc_stack [[ANY_VALUE]]
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [serialized] [reabstraction_thunk] [ossa] @$sypSgIegn_S2iIegyy_TR : $@convention(thin) (Int, Int, @guaranteed @callee_guaranteed (@in_guaranteed Optional<Any>) -> ()) -> ()
// CHECK: [[ANY_VALUE:%.*]] = alloc_stack $Any
// CHECK-NEXT: [[ANY_PAYLOAD:%.*]] = init_existential_addr [[ANY_VALUE]]
// CHECK-NEXT: [[LEFT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]]
// CHECK-NEXT: store %0 to [trivial] [[LEFT_ADDR]]
// CHECK-NEXT: [[RIGHT_ADDR:%.*]] = tuple_element_addr [[ANY_PAYLOAD]]
// CHECK-NEXT: store %1 to [trivial] [[RIGHT_ADDR]]
// CHECK-NEXT: [[OPTIONAL_VALUE:%.*]] = alloc_stack $Optional<Any>
// CHECK-NEXT: [[OPTIONAL_PAYLOAD:%.*]] = init_enum_data_addr [[OPTIONAL_VALUE]]
// CHECK-NEXT: copy_addr [take] [[ANY_VALUE]] to [initialization] [[OPTIONAL_PAYLOAD]]
// CHECK-NEXT: inject_enum_addr [[OPTIONAL_VALUE]]
// CHECK-NEXT: apply %2([[OPTIONAL_VALUE]])
// CHECK-NEXT: tuple ()
// CHECK-NEXT: destroy_addr [[OPTIONAL_VALUE]]
// CHECK-NEXT: dealloc_stack [[OPTIONAL_VALUE]]
// CHECK-NEXT: dealloc_stack [[ANY_VALUE]]
// CHECK-NEXT: return
// ==== Support collection subtyping in function argument position
protocol Z {}
class A: Z {}
func foo_arr<T: Z>(type: T.Type, _ fn: ([T]?) -> Void) {}
func foo_map<T: Z>(type: T.Type, _ fn: ([Int: T]) -> Void) {}
func rdar35702810() {
let fn_arr: ([Z]?) -> Void = { _ in }
let fn_map: ([Int: Z]) -> Void = { _ in }
// CHECK: function_ref @$ss15_arrayForceCastySayq_GSayxGr0_lF : $@convention(thin) <τ_0_0, τ_0_1> (@guaranteed Array<τ_0_0>) -> @owned Array<τ_0_1>
// CHECK: apply %5<A, Z>(%4) : $@convention(thin) <τ_0_0, τ_0_1> (@guaranteed Array<τ_0_0>) -> @owned Array<τ_0_1>
foo_arr(type: A.self, fn_arr)
// CHECK: function_ref @$ss17_dictionaryUpCastySDyq0_q1_GSDyxq_GSHRzSHR0_r2_lF : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3>
// CHECK: apply %2<Int, A, Int, Z>(%0) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3>
// CHECK: apply %1(%4) : $@callee_guaranteed (@guaranteed Dictionary<Int, Z>) -> ()
foo_map(type: A.self, fn_map)
}
protocol X: Hashable {}
class B: X {
func hash(into hasher: inout Hasher) {}
static func == (lhs: B, rhs: B) -> Bool { return true }
}
func bar_arr<T: X>(type: T.Type, _ fn: ([T]?) -> Void) {}
func bar_map<T: X>(type: T.Type, _ fn: ([T: Int]) -> Void) {}
func bar_set<T: X>(type: T.Type, _ fn: (Set<T>) -> Void) {}
func rdar35702810_anyhashable() {
let fn_arr: ([AnyHashable]?) -> Void = { _ in }
let fn_map: ([AnyHashable: Int]) -> Void = { _ in }
let fn_set: (Set<AnyHashable>) -> Void = { _ in }
// CHECK: [[FN:%.*]] = function_ref @$sSays11AnyHashableVGSgIegg_Say19function_conversion1BCGSgIegg_TR : $@convention(thin) (@guaranteed Optional<Array<B>>, @guaranteed @callee_guaranteed (@guaranteed Optional<Array<AnyHashable>>) -> ()) -> ()
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[FN]](%{{[0-9]+}}) : $@convention(thin) (@guaranteed Optional<Array<B>>, @guaranteed @callee_guaranteed (@guaranteed Optional<Array<AnyHashable>>) -> ()) -> ()
// CHECK: convert_escape_to_noescape [not_guaranteed] [[PA]] : $@callee_guaranteed (@guaranteed Optional<Array<B>>) -> () to $@noescape @callee_guaranteed (@guaranteed Optional<Array<B>>) -> ()
bar_arr(type: B.self, fn_arr)
// CHECK: [[FN:%.*]] = function_ref @$sSDys11AnyHashableVSiGIegg_SDy19function_conversion1BCSiGIegg_TR : $@convention(thin) (@guaranteed Dictionary<B, Int>, @guaranteed @callee_guaranteed (@guaranteed Dictionary<AnyHashable, Int>) -> ()) -> ()
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[FN]](%{{[0-9]+}}) : $@convention(thin) (@guaranteed Dictionary<B, Int>, @guaranteed @callee_guaranteed (@guaranteed Dictionary<AnyHashable, Int>) -> ()) -> ()
// CHECK: convert_escape_to_noescape [not_guaranteed] [[PA]] : $@callee_guaranteed (@guaranteed Dictionary<B, Int>) -> () to $@noescape @callee_guaranteed (@guaranteed Dictionary<B, Int>) -> ()
bar_map(type: B.self, fn_map)
// CHECK: [[FN:%.*]] = function_ref @$sShys11AnyHashableVGIegg_Shy19function_conversion1BCGIegg_TR : $@convention(thin) (@guaranteed Set<B>, @guaranteed @callee_guaranteed (@guaranteed Set<AnyHashable>) -> ()) -> ()
// CHECK: [[PA:%.*]] = partial_apply [callee_guaranteed] [[FN]](%{{[0-9]+}}) : $@convention(thin) (@guaranteed Set<B>, @guaranteed @callee_guaranteed (@guaranteed Set<AnyHashable>) -> ()) -> ()
// CHECK: convert_escape_to_noescape [not_guaranteed] [[PA]] : $@callee_guaranteed (@guaranteed Set<B>) -> () to $@noescape @callee_guaranteed (@guaranteed Set<B>) -> ()
bar_set(type: B.self, fn_set)
}
// ==== Function conversion with parameter substToOrig reabstraction.
struct FunctionConversionParameterSubstToOrigReabstractionTest {
typealias SelfTy = FunctionConversionParameterSubstToOrigReabstractionTest
class Klass: Error {}
struct Foo<T> {
static func enum1Func(_ : (T) -> Foo<Error>) -> Foo<Error> {
// Just to make it compile.
return Optional<Foo<Error>>.none!
}
}
static func bar<T>(t: T) -> Foo<T> {
// Just to make it compile.
return Optional<Foo<T>>.none!
}
static func testFunc() -> Foo<Error> {
return Foo<Klass>.enum1Func(SelfTy.bar)
}
}
// CHECK: sil {{.*}} [ossa] @$sS4SIgggoo_S2Ss11AnyHashableVyps5Error_pIegggrrzo_TR
// CHECK: [[TUPLE:%.*]] = apply %4(%2, %3) : $@noescape @callee_guaranteed (@guaranteed String, @guaranteed String) -> (@owned String, @owned String)
// CHECK: ([[LHS:%.*]], [[RHS:%.*]]) = destructure_tuple [[TUPLE]]
// CHECK: [[ADDR:%.*]] = alloc_stack $String
// CHECK: store [[LHS]] to [init] [[ADDR]] : $*String
// CHECK: [[CVT:%.*]] = function_ref @$ss21_convertToAnyHashableys0cD0VxSHRzlF : $@convention(thin) <τ_0_0 where τ_0_0 : Hashable> (@in_guaranteed τ_0_0) -> @out AnyHashable
// CHECK: apply [[CVT]]<String>(%0, [[ADDR]])
// CHECK: } // end sil function '$sS4SIgggoo_S2Ss11AnyHashableVyps5Error_pIegggrrzo_TR'
func dontCrash() {
let userInfo = ["hello": "world"]
let d = [AnyHashable: Any](uniqueKeysWithValues: userInfo.map { ($0.key, $0.value) })
}
struct Butt<T> {
var foo: () throws -> T
}
@_silgen_name("butt")
func butt() -> Butt<Any>
func foo() throws -> Any {
return try butt().foo()
}
| apache-2.0 | 3dcfe83018d9cccfa4a17fa1b5b2489b | 53.275762 | 441 | 0.640871 | 3.303825 | false | false | false | false |
davidahouse/Attributed | Sources/Attributed.swift | 1 | 6535 | //
// Attributed.swift
// Attributed
//
// Created by David House on 1/10/16.
// Copyright © 2016 David House. All rights reserved.
//
import Foundation
/// A helper class for creating NSAttributedString objects
public class Attributed {
let attributes: [String: AnyObject]
// MARK: Initializers
/// Initialize with an empty set of attributes
public init() {
attributes = [String: AnyObject]()
}
/// Initialize with only a foreground color attribute
///
/// - parameter color: The foreground color attribute
public init(color: AttributedColor) {
attributes = [AttributedColorAttributeName: color]
}
/// Initialize with only a font attribute
///
/// - parameter font: The font attribute
public init(font: AttributedFont) {
attributes = [AttributedFontAttributeName: font]
}
/// Initialize with a dictionary of attributes
///
/// - parameter attributes: A dictionary of attributed string attributes
public init(attributes: [String: AnyObject]) {
self.attributes = attributes
}
// MARK: String methods
/// Create an NSAttributedString from a String,
/// while applying attributes.
///
/// - parameter inner: A String
/// - returns: An NSAttributedString that has the attributes applied to it
public func toString(inner: String) -> NSAttributedString {
return NSAttributedString(string: inner, attributes: attributes)
}
/// Create an NSAttributedString from a closure that returns a String,
/// while applying attributes.
///
/// - parameter inner: A closure that returns a String
/// - returns: An NSAttributedString that has the attributes applied to it
public func toString(inner:() -> String) -> NSAttributedString {
return NSAttributedString(string: inner(), attributes: attributes)
}
/// Create an NSAttributedString from an NSAttributedString, while also applying our attributes
///
/// This method will not overwrite any attribute that has already been
/// applied to the string.
///
/// - parameter inner: An NSAttributedString
/// - returns: An NSAttributedString that has the attributes applied to it
public func toString(inner: NSAttributedString) -> NSAttributedString {
let output = NSMutableAttributedString(attributedString: inner)
guard output.length > 0 else {
return output
}
var startIndex = 0
while ( startIndex < output.length ) {
var range = NSRange()
let attributesAt = output.attributesAtIndex(startIndex, effectiveRange: &range)
for attribute in attributes {
if !attributesAt.keys.contains(attribute.0) {
output.addAttribute(attribute.0, value: attribute.1, range: range)
}
}
startIndex = startIndex + range.length
}
return output
}
/// Create an NSAttributedString from a closure that returns an NSAttributedString, while also applying our attributes
///
/// This method will not overwrite any attribute that has already been
/// applied to the string.
///
/// - parameter inner: A closure that returns an NSAttributedString
/// - returns: An NSAttributedString that has the attributes applied to it
public func toString(inner:() -> NSAttributedString) -> NSAttributedString {
return toString(inner())
}
/// Create an NSAttributedString by combining multiple Strings using
/// a separator, while also applying our attributes.
///
/// - parameter separator: The separator to use between each String, with space being the default
/// - parameter strings: A variable number of String objects that will be combined
/// - returns: An NSAttributedString with all the Strings combined and attributes applied
public func combine(separator: String = " ", strings: String...) -> NSAttributedString {
let output = NSMutableAttributedString()
for inner in strings {
if output.length > 0 {
output.appendAttributedString(NSAttributedString(string: separator))
}
output.appendAttributedString(toString{ inner })
}
return output
}
/// Create an NSAttributedString by combining multiple NSAttributedStrings using
/// a separator, while also applying our attributes.
///
/// - parameter separator: The separator to use between each String, with space being the default
/// - parameter strings: A variable number of NSAttributedString objects that will be combined
/// - returns: An NSAttributedString with all the NSAttributedStrings combined and attributes applied
public func combine(separator: String = " ", strings: NSAttributedString...) -> NSAttributedString {
let output = NSMutableAttributedString()
for inner in strings {
if output.length > 0 {
output.appendAttributedString(NSAttributedString(string: separator))
}
output.appendAttributedString(toString{ inner })
}
return output
}
}
/// Add two NSAttributedStrings together
///
/// - parameter left: An NSAttributedString
/// - parameter right: Another NSAttributedString
/// - returns: An NSAttributedString representing left + right
public func + (left:NSAttributedString, right:NSAttributedString) -> NSAttributedString {
let output = NSMutableAttributedString(attributedString: left)
output.appendAttributedString(right)
return output
}
/// Add an NSAttributedString and String together
///
/// - parameter left: An NSAttributedString
/// - parameter right: A String
/// - returns: An NSAttributedString representing left + right
public func + (left:NSAttributedString, right:String) -> NSAttributedString {
let output = NSMutableAttributedString(attributedString: left)
output.appendAttributedString(NSAttributedString(string: right))
return output
}
/// Add a String and NSAttributedString together
///
/// - parameter left: A String
/// - parameter right: An NSAttributedString
/// - returns: An NSAttributedString representing left + right
public func + (left:String, right:NSAttributedString) -> NSAttributedString {
let output = NSMutableAttributedString(attributedString: NSAttributedString(string: left))
output.appendAttributedString(right)
return output
}
| mit | e6e39bd648c75ead3f594062ab2f130c | 37.662722 | 122 | 0.678298 | 5.589393 | false | false | false | false |
JigarM/Swift-Tutorials | SwiftUITableView/SwiftUITableView/DetailViewController.swift | 3 | 3872 | //
// DetailViewController.swift
// SwiftUITableView
//
// Created by Mobmaxime on 03/08/14.
// Copyright (c) 2014 Jigar M. All rights reserved.
//
import UIKit
import QuartzCore
class DetailViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {
@IBOutlet var ProfileBannerImage : UIImageView
@IBOutlet var ProfileDPImage : UIImageView
@IBOutlet var Username : UILabel
@IBOutlet var Screenname : UILabel
@IBOutlet var MyTableview : UITableView
var Dict : AnyObject = []
var list = Array<AnyObject>()
//var d : AnyObject
override func viewDidLoad() {
super.viewDidLoad()
println(Dict)
let d = Dict as NSDictionary
let pb = d["ProfileBanner"] as String
ProfileBannerImage.image = UIImage(named:pb)
ProfileDPImage.image = UIImage(named:d["image"] as String)
Username.text = d["Name"] as String
Screenname.text = d["screenname"] as String
self.title = d["Name"] as String
list = d["recent"] as Array
//println(list.count)
var layer:CALayer = ProfileDPImage.layer!
layer.shadowPath = UIBezierPath(rect: layer.bounds).CGPath
layer.shouldRasterize = true;
layer.rasterizationScale = UIScreen.mainScreen().scale
layer.borderColor = UIColor.whiteColor().CGColor
layer.borderWidth = 2.0
layer.shadowColor = UIColor.grayColor().CGColor
layer.shadowOpacity = 0.4
layer.shadowOffset = CGSizeMake(1, 3)
layer.shadowRadius = 1.5
ProfileDPImage.clipsToBounds = false
//Tableview Datasource & Delegates
self.MyTableview.dataSource = self
self.MyTableview.delegate = self
}
// #pragma mark - Table view data source
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return list.count
}
func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
return 107
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell {
let cell:DetailTableViewCell = tableView?.dequeueReusableCellWithIdentifier("DetailCell", forIndexPath: indexPath) as DetailTableViewCell
var data : NSDictionary = self.list[indexPath.row] as NSDictionary
var Username : String = data.objectForKey("Name") as String
var description : String = data.objectForKey("description") as String
var dp : String = data.objectForKey("image") as String
/*
Time & Date Formatting
*/
let date = NSDate.date(); // "Jul 23, 2014, 11:01 AM" <-- looks local without seconds. But:
var formatter = NSDateFormatter();
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ";
let defaultTimeZoneStr = formatter.stringFromDate(date);// "2014-07-23 11:01:35 -0700" <-- same date, local, but with seconds
formatter.timeZone = NSTimeZone(abbreviation: "UTC");
let utcTimeZoneStr = formatter.stringFromDate(date);// "2014-07-23 18:01:41 +0000" <-- same date, now in UTC
cell.Username.text = Username
cell.Timestamp.text = defaultTimeZoneStr
cell.Recent.text = description
cell.ProfileDP.image = UIImage(named:dp)
return cell
}
/*
// #pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | cd052e68a74ed0070e9a31c848e0dabb | 35.528302 | 145 | 0.646952 | 4.964103 | false | false | false | false |
BelledonneCommunications/linphone-iphone | Classes/Swift/Voip/Views/Fragments/CallsList/CallsListView.swift | 1 | 5303 | /*
* Copyright (c) 2010-2020 Belledonne Communications SARL.
*
* This file is part of linphone-iphone
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
import Foundation
import linphonesw
@objc class CallsListView: DismissableView, UITableViewDataSource {
// Layout constants
let buttons_distance_from_center_x = 38
let buttons_size = 60
let callsListTableView = UITableView()
let menuView = VoipCallContextMenu()
var callsDataObserver : MutableLiveDataOnChangeClosure<[CallData]>? = nil
init() {
super.init(title: VoipTexts.call_action_calls_list)
accessibilityIdentifier = "calls_list_view"
// New Call
let newCall = CallControlButton(width: buttons_size,height: buttons_size, imageInset:UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10), buttonTheme: VoipTheme.call_add, onClickAction: {
let view: DialerView = self.VIEW(DialerView.compositeViewDescription());
view.setAddress("")
CallManager.instance().nextCallIsTransfer = false
PhoneMainView.instance().changeCurrentView(view.compositeViewDescription())
})
addSubview(newCall)
newCall.centerX(withDx: -buttons_distance_from_center_x).alignParentBottom(withMargin:SharedLayoutConstants.buttons_bottom_margin).done()
// Merge Calls
let mergeIntoLocalConference = CallControlButton(width: buttons_size,height: buttons_size, buttonTheme: VoipTheme.call_merge, onClickAction: {
self.removeFromSuperview()
if (ConferenceViewModel.shared.conferenceExists.value == true) {
ConferenceViewModel.shared.addCallsToConference()
} else {
CallsViewModel.shared.mergeCallsIntoLocalConference()
}
})
addSubview(mergeIntoLocalConference)
mergeIntoLocalConference.centerX(withDx: buttons_distance_from_center_x).alignParentBottom(withMargin:SharedLayoutConstants.buttons_bottom_margin).done()
CallsViewModel.shared.callsData.readCurrentAndObserve { _ in
self.callsListTableView.reloadData()
mergeIntoLocalConference.isEnabled = self.mergeToConferencePossible()
}
ConferenceViewModel.shared.conferenceExists.readCurrentAndObserve { _ in
mergeIntoLocalConference.isEnabled = self.mergeToConferencePossible()
}
// CallsList
super.contentView.addSubview(callsListTableView)
callsListTableView.matchParentDimmensions().done()
callsListTableView.dataSource = self
callsListTableView.register(VoipCallCell.self, forCellReuseIdentifier: "VoipCallCell")
callsListTableView.allowsSelection = false
if #available(iOS 15.0, *) {
callsListTableView.allowsFocus = false
}
callsListTableView.separatorStyle = .singleLine
callsListTableView.separatorColor = .white
callsListTableView.onClick {
self.hideMenu()
}
// Floating menu
super.contentView.addSubview(menuView)
menuView.isHidden = true
}
func numberOfCallsNotInConf() -> Int {
let core = Core.get()
var result = 0
core.calls.forEach { call in
if (call.conference == nil && core.findConferenceInformationFromUri(uri: call.remoteAddress!) == nil) {
result += 1
}
}
return result
}
func mergeToConferencePossible() -> Bool { // 2 calls or more not in conf or 1 call or more and 1 conf
let callsNotInConf = numberOfCallsNotInConf()
return (ConferenceViewModel.shared.conferenceExists.value == true && callsNotInConf >= 1) || (ConferenceViewModel.shared.conferenceExists.value != true && callsNotInConf >= 2 )
}
func toggleMenu(forCell:VoipCallCell) {
if (menuView.isHidden) {
showMenu(forCell: forCell)
} else if (menuView.callData?.call.callLog?.callId != forCell.callData?.call.callLog?.callId) {
hideMenu()
showMenu(forCell: forCell)
} else {
hideMenu()
}
}
func showMenu(forCell:VoipCallCell) {
menuView.removeConstraints().alignUnder(view: forCell).alignParentRight().done()
menuView.callData = forCell.callData
menuView.isHidden = false
}
func hideMenu() {
menuView.isHidden = true
}
// TableView datasource delegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let callsData = CallsViewModel.shared.callsData.value else {
return 0
}
return callsData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:VoipCallCell = tableView.dequeueReusableCell(withIdentifier: "VoipCallCell") as! VoipCallCell
guard let callData = CallsViewModel.shared.callsData.value?[indexPath.row] else {
return cell
}
cell.selectionStyle = .none
cell.callData = callData
cell.owningCallsListView = self
return cell
}
// View controller
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| gpl-3.0 | 49d53092db332efa711c54c924f133c6 | 31.734568 | 192 | 0.750707 | 4.014383 | false | false | false | false |
velvetroom/columbus | Source/Model/CreateTravel/MCreateTravel+Factory.swift | 1 | 944 | import Foundation
extension MCreateTravel
{
//MARK: internal
class func factoryItems() -> [MCreateTravelProtocol]
{
let itemWalking:MCreateTravelWalking = MCreateTravelWalking()
let itemCycling:MCreateTravelCycling = MCreateTravelCycling()
let itemTransit:MCreateTravelTransit = MCreateTravelTransit()
let itemDriving:MCreateTravelDriving = MCreateTravelDriving()
let items:[MCreateTravelProtocol] = [
itemWalking,
itemCycling,
itemTransit,
itemDriving]
return items
}
class func factoryIndexMap(items:[MCreateTravelProtocol]) -> [DPlanTravelMode:Int]
{
var index:Int = 0
var map:[DPlanTravelMode:Int] = [:]
for item:MCreateTravelProtocol in items
{
map[item.mode] = index
index += 1
}
return map
}
}
| mit | 72ed6db0d52614903198e9069bfdc9ea | 25.222222 | 86 | 0.595339 | 5.186813 | false | false | false | false |
emilstahl/swift | test/Serialization/autolinking.swift | 11 | 2755 | // RUN: rm -rf %t
// RUN: mkdir %t
// RUN: %target-swift-frontend -emit-module -parse-stdlib -o %t -module-name someModule -module-link-name module %S/../Inputs/empty.swift
// RUN: %target-swift-frontend -emit-ir -lmagic %s -I %t > %t/out.txt
// RUN: FileCheck %s < %t/out.txt
// RUN: FileCheck -check-prefix=NO-FORCE-LOAD %s < %t/out.txt
// RUN: mkdir -p %t/someModule.framework/Modules/someModule.swiftmodule/
// RUN: mv %t/someModule.swiftmodule %t/someModule.framework/Modules/someModule.swiftmodule/%target-swiftmodule-name
// RUN: %target-swift-frontend -emit-ir -lmagic %s -F %t > %t/framework.txt
// RUN: FileCheck -check-prefix=FRAMEWORK %s < %t/framework.txt
// RUN: FileCheck -check-prefix=NO-FORCE-LOAD %s < %t/framework.txt
// RUN: %target-swift-frontend -emit-module -parse-stdlib -o %t -module-name someModule -module-link-name module %S/../Inputs/empty.swift -autolink-force-load
// RUN: %target-swift-frontend -emit-ir -lmagic %s -I %t > %t/force-load.txt
// RUN: FileCheck %s < %t/force-load.txt
// RUN: FileCheck -check-prefix=FORCE-LOAD-CLIENT %s < %t/force-load.txt
// RUN: %target-swift-frontend -emit-ir -parse-stdlib -module-name someModule -module-link-name module %S/../Inputs/empty.swift | FileCheck --check-prefix=NO-FORCE-LOAD %s
// RUN: %target-swift-frontend -emit-ir -parse-stdlib -module-name someModule -module-link-name module %S/../Inputs/empty.swift -autolink-force-load | FileCheck --check-prefix=FORCE-LOAD %s
// RUN: %target-swift-frontend -emit-ir -parse-stdlib -module-name someModule -module-link-name 0module %S/../Inputs/empty.swift -autolink-force-load | FileCheck --check-prefix=FORCE-LOAD-HEX %s
// UNSUPPORTED: OS=linux-gnu
import someModule
// CHECK: !{{[0-9]+}} = !{i32 6, !"Linker Options", ![[LINK_LIST:[0-9]+]]}
// CHECK: ![[LINK_LIST]] = !{
// CHECK-DAG: !{{[0-9]+}} = !{!"-lmagic"}
// CHECK-DAG: !{{[0-9]+}} = !{!"-lmodule"}
// FRAMEWORK: !{{[0-9]+}} = !{i32 6, !"Linker Options", ![[LINK_LIST:[0-9]+]]}
// FRAMEWORK: ![[LINK_LIST]] = !{
// FRAMEWORK-DAG: !{{[0-9]+}} = !{!"-lmagic"}
// FRAMEWORK-DAG: !{{[0-9]+}} = !{!"-lmodule"}
// FRAMEWORK-DAG: !{{[0-9]+}} = !{!"-framework", !"someModule"}
// NO-FORCE-LOAD-NOT: FORCE_LOAD
// FORCE-LOAD: @"_swift_FORCE_LOAD_$_module" = common global i1 false
// FORCE-LOAD-HEX: @"_swift_FORCE_LOAD_$306d6f64756c65" = common global i1 false
// FORCE-LOAD-CLIENT: @"_swift_FORCE_LOAD_$_module" = external global i1
// FORCE-LOAD-CLIENT: @"_swift_FORCE_LOAD_$_module_$_autolinking" = weak hidden constant i1* @"_swift_FORCE_LOAD_$_module"
// FORCE-LOAD-CLIENT: @llvm.used = appending global [{{[0-9]+}} x i8*] [
// FORCE-LOAD-CLIENT: i8* bitcast (i1** @"_swift_FORCE_LOAD_$_module_$_autolinking" to i8*)
// FORCE-LOAD-CLIENT: ], section "llvm.metadata"
| apache-2.0 | b995620302213c345b06c92b20ad2615 | 57.617021 | 194 | 0.667151 | 3.044199 | false | false | false | false |
josve05a/wikipedia-ios | Wikipedia/Code/InsertMediaSelectedImageViewController.swift | 2 | 3990 | protocol InsertMediaSelectedImageViewControllerDelegate: AnyObject {
func insertMediaSelectedImageViewController(_ insertMediaSelectedImageViewController: InsertMediaSelectedImageViewController, didSetSelectedImage selectedImage: UIImage?, from searchResult: InsertMediaSearchResult)
func insertMediaSelectedImageViewController(_ insertMediaSelectedImageViewController: InsertMediaSelectedImageViewController, willSetSelectedImageFrom searchResult: InsertMediaSearchResult)
}
final class InsertMediaSelectedImageViewController: UIViewController {
private let selectedView = InsertMediaSelectedImageView()
private let activityIndicator = UIActivityIndicatorView(style: .whiteLarge)
private var theme = Theme.standard
weak var delegate: InsertMediaSelectedImageViewControllerDelegate?
var image: UIImage? {
return selectedView.image
}
var searchResult: InsertMediaSearchResult? {
return selectedView.searchResult
}
override func viewDidLoad() {
super.viewDidLoad()
apply(theme: theme)
view.addCenteredSubview(activityIndicator)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if image == nil {
wmf_showEmptyView(of: .noSelectedImageToInsert, theme: theme, frame: view.bounds)
} else {
wmf_hideEmptyView()
}
}
private func startActivityIndicator() {
wmf_hideEmptyView()
cancelPreviousActivityIndicatorSelectors()
selectedView.isHidden = true
perform(#selector(_startActivityIndicator), with: nil, afterDelay: 0.3)
}
@objc private func _startActivityIndicator() {
activityIndicator.startAnimating()
}
@objc private func stopActivityIndicator() {
cancelPreviousActivityIndicatorSelectors()
selectedView.isHidden = false
activityIndicator.stopAnimating()
}
@objc private func cancelPreviousActivityIndicatorSelectors() {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(_startActivityIndicator), object: nil)
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(stopActivityIndicator), object: nil)
}
}
extension InsertMediaSelectedImageViewController: InsertMediaSearchResultsCollectionViewControllerDelegate {
func insertMediaSearchResultsCollectionViewControllerDidSelect(_ insertMediaSearchResultsCollectionViewController: InsertMediaSearchResultsCollectionViewController, searchResult: InsertMediaSearchResult) {
delegate?.insertMediaSelectedImageViewController(self, willSetSelectedImageFrom: searchResult)
startActivityIndicator()
guard let imageURL = searchResult.imageURL(for: view.bounds.width) else {
stopActivityIndicator()
return
}
if selectedView.moreInformationAction == nil {
selectedView.moreInformationAction = { [weak self] url in
self?.navigate(to: url, useSafari: true)
}
}
selectedView.configure(with: imageURL, searchResult: searchResult, theme: theme) { error in
guard error == nil else {
self.stopActivityIndicator()
return
}
self.stopActivityIndicator()
if self.selectedView.superview == nil {
self.view.wmf_addSubviewWithConstraintsToEdges(self.selectedView)
}
self.delegate?.insertMediaSelectedImageViewController(self, didSetSelectedImage: self.image, from: searchResult)
}
}
}
extension InsertMediaSelectedImageViewController: Themeable {
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
wmf_applyTheme(toEmptyView: theme)
view.backgroundColor = theme.colors.baseBackground
activityIndicator.style = theme.isDark ? .white : .gray
}
}
| mit | 350e57c2ecd8f07860614a4f3867e3ad | 41 | 218 | 0.714787 | 6.224649 | false | false | false | false |
ephread/Instructions | Sources/Instructions/Helpers/Public/CoachMarkCoordinateConverter.swift | 2 | 4548 | // Copyright (c) 2021-present Frédéric Maquin <[email protected]> and contributors.
// Licensed under the terms of the MIT License.
import UIKit
public class CoachMarkCoordinateConverter {
private let rootView: InstructionsRootView
init(rootView: InstructionsRootView) {
self.rootView = rootView
}
/// Converts a rectangle from the specified coordinate space
/// to the coordinate space of Instructions.
///
/// - Parameters:
/// - frame: A rectangle in the specified coordinate space.
/// - superview: The coordinate space in which `rect` is specified.
/// - Returns: A rectangle specified in the coordinate space of Instructions.
public func convert(rect: CGRect, from superview: UIView?) -> CGRect {
// No superview, assuming frame in `instructionsRootView`'s coordinate system.
guard let superview = superview else {
print(ErrorMessage.Warning.anchorViewIsNotInTheViewHierarchy)
return rect
}
// Either `superview` and `instructionsRootView` is not in the hierarchy,
// the result is undefined.
guard let superviewWindow = superview.window,
let instructionsWindow = rootView.window else {
print(ErrorMessage.Warning.anchorViewIsNotInTheViewHierarchy)
return rootView.convert(rect, from: superview)
}
// If both windows are the same, we can directly convert, because
// `superview` and `instructionsRootView` are in the same hierarchy.
//
// This is the case when showing Instructions either in the parent
// view controller or the parent window.
guard superviewWindow != instructionsWindow else {
return rootView.convert(rect, from: superview)
}
// 1. Converts the coordinates of the frame from its superview to its window.
let rectInWindow = superviewWindow.convert(rect, from: superview)
// 2. Converts the coordinates of the frame from its window to Instructions' window.
let rectInInstructionsWindow = instructionsWindow.convert(rectInWindow,
from: superviewWindow)
// 3. Converts the coordinates of the frame from Instructions' window to
// `instructionsRootView`.
return rootView.convert(rectInInstructionsWindow, from: instructionsWindow)
}
/// Converts a point from the specified coordinate space
/// to the coordinate space of Instructions.
///
/// - Parameters:
/// - frame: A point in the specified coordinate space.
/// - superview: The coordinate space in which `point` is specified.
/// - Returns: A point specified in the coordinate space of Instructions.
public func convert(point: CGPoint, from superview: UIView?) -> CGPoint {
// No superview, assuming frame in `instructionsRootView`'s coordinate system.
guard let superview = superview else {
print(ErrorMessage.Warning.anchorViewIsNotInTheViewHierarchy)
return point
}
// Either `superview` and `instructionsRootView` is not in the hierarchy,
// the result is undefined.
guard let superviewWindow = superview.window,
let instructionsWindow = rootView.window else {
print(ErrorMessage.Warning.anchorViewIsNotInTheViewHierarchy)
return rootView.convert(point, from: superview)
}
// If both windows are the same, we can directly convert, because
// `superview` and `instructionsRootView` are in the same hierarchy.
//
// This is the case when showing Instructions either in the parent
// view controller or the parent window.
guard superviewWindow != instructionsWindow else {
return rootView.convert(point, from: superview)
}
// 1. Converts the coordinates of the frame from its superview to its window.
let frameInWindow = superviewWindow.convert(point, from: superview)
// 2. Converts the coordinates of the frame from its window to Instructions' window.
let frameInInstructionsWindow = instructionsWindow.convert(frameInWindow,
from: superviewWindow)
// 3. Converts the coordinates of the frame from Instructions' window to
// `instructionsRootView`.
return rootView.convert(frameInInstructionsWindow, from: instructionsWindow)
}
}
| mit | 96169ecd773501fc1fee15546f51ad91 | 45.387755 | 92 | 0.660361 | 5.530414 | false | false | false | false |
Higgcz/Buildasaur | Buildasaur/StatusProjectViewController.swift | 2 | 13529 | //
// StatusProjectViewController.swift
// Buildasaur
//
// Created by Honza Dvorsky on 07/03/2015.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import AppKit
import BuildaUtils
import XcodeServerSDK
import BuildaKit
let kBuildTemplateAddNewString = "Create New..."
class StatusProjectViewController: StatusViewController, NSComboBoxDelegate, SetupViewControllerDelegate {
//no project yet
@IBOutlet weak var addProjectButton: NSButton!
//we have a project
@IBOutlet weak var statusContentView: NSView!
@IBOutlet weak var projectNameLabel: NSTextField!
@IBOutlet weak var projectPathLabel: NSTextField!
@IBOutlet weak var projectURLLabel: NSTextField!
@IBOutlet weak var buildTemplateComboBox: NSComboBox!
@IBOutlet weak var selectSSHPrivateKeyButton: NSButton!
@IBOutlet weak var selectSSHPublicKeyButton: NSButton!
@IBOutlet weak var sshPassphraseTextField: NSSecureTextField!
//GitHub.com: Settings -> Applications -> Personal access tokens - create one for Buildasaur and put it in this text field
@IBOutlet weak var tokenTextField: NSTextField!
override func availabilityChanged(state: AvailabilityCheckState) {
if let project = self.project() {
project.availabilityState = state
}
super.availabilityChanged(state)
}
override func viewWillAppear() {
super.viewWillAppear()
self.buildTemplateComboBox.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
self.tokenTextField.delegate = self
self.lastAvailabilityCheckStatus = .Unchecked
}
func project() -> Project? {
return self.storageManager.projects.first
}
func buildTemplates() -> [BuildTemplate] {
return self.storageManager.buildTemplates.filter { (template: BuildTemplate) -> Bool in
if
let projectName = template.projectName,
let project = self.project()
{
return projectName == project.workspaceMetadata?.projectName ?? ""
} else {
//if it doesn't yet have a project name associated, assume we have to show it
return true
}
}
}
override func reloadStatus() {
//if there is a local project, show status. otherwise show button to add one.
if let project = self.project() {
self.statusContentView.hidden = false
self.addProjectButton.hidden = true
self.buildTemplateComboBox.enabled = self.editing
self.deleteButton.hidden = !self.editing
self.editButton.title = self.editing ? "Done" : "Edit"
self.selectSSHPrivateKeyButton.enabled = self.editing
self.selectSSHPublicKeyButton.enabled = self.editing
self.sshPassphraseTextField.enabled = self.editing
self.selectSSHPublicKeyButton.title = project.publicSSHKeyUrl?.lastPathComponent ?? "Select SSH Public Key"
self.selectSSHPrivateKeyButton.title = project.privateSSHKeyUrl?.lastPathComponent ?? "Select SSH Private Key"
self.sshPassphraseTextField.stringValue = project.sshPassphrase ?? ""
//fill data in
self.projectNameLabel.stringValue = project.workspaceMetadata?.projectName ?? "<NO NAME>"
self.projectURLLabel.stringValue = project.workspaceMetadata?.projectURL.absoluteString ?? "<NO URL>"
self.projectPathLabel.stringValue = project.url.path ?? "<NO PATH>"
if let githubToken = project.githubToken {
self.tokenTextField.stringValue = githubToken
}
self.tokenTextField.enabled = self.editing
let selectedBefore = self.buildTemplateComboBox.objectValueOfSelectedItem as? String
self.buildTemplateComboBox.removeAllItems()
let buildTemplateNames = self.buildTemplates().map { $0.name! }
self.buildTemplateComboBox.addItemsWithObjectValues(buildTemplateNames + [kBuildTemplateAddNewString])
self.buildTemplateComboBox.selectItemWithObjectValue(selectedBefore)
if
let preferredTemplateId = project.preferredTemplateId,
let template = self.buildTemplates().filter({ $0.uniqueId == preferredTemplateId }).first
{
self.buildTemplateComboBox.selectItemWithObjectValue(template.name!)
}
} else {
self.statusContentView.hidden = true
self.addProjectButton.hidden = false
self.tokenTextField.stringValue = ""
self.buildTemplateComboBox.removeAllItems()
}
}
override func checkAvailability(statusChanged: ((status: AvailabilityCheckState, done: Bool) -> ())?) {
let statusChangedPersist: (status: AvailabilityCheckState, done: Bool) -> () = {
(status: AvailabilityCheckState, done: Bool) -> () in
self.lastAvailabilityCheckStatus = status
statusChanged?(status: status, done: done)
}
if let _ = self.project() {
statusChangedPersist(status: .Checking, done: false)
NetworkUtils.checkAvailabilityOfGitHubWithCurrentSettingsOfProject(self.project()!, completion: { (success, error) -> () in
let status: AvailabilityCheckState
if success {
status = .Succeeded
} else {
Log.error("Checking github availability error: " + (error?.description ?? "Unknown error"))
status = AvailabilityCheckState.Failed(error)
}
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
statusChangedPersist(status: status, done: true)
})
})
} else {
statusChangedPersist(status: .Unchecked, done: true)
}
}
@IBAction func addProjectButtonTapped(sender: AnyObject) {
if let url = StorageUtils.openWorkspaceOrProject() {
do {
try self.storageManager.addProjectAtURL(url)
//we have just added a local source, good stuff!
//check if we have everything, if so, enable the "start syncing" button
self.editing = true
} catch {
//local source is malformed, something terrible must have happened, inform the user this can't be used (log should tell why exactly)
UIUtils.showAlertWithText("Couldn't add Xcode project at path \(url.absoluteString), error: \((error as NSError).localizedDescription).", style: NSAlertStyle.CriticalAlertStyle, completion: { (resp) -> () in
//
})
}
self.reloadStatus()
} else {
//user cancelled
}
}
//Combo Box Delegate
func comboBoxWillDismiss(notification: NSNotification) {
if let templatePulled = self.buildTemplateComboBox.objectValueOfSelectedItem as? String {
//it's string
var buildTemplate: BuildTemplate?
if templatePulled != kBuildTemplateAddNewString {
buildTemplate = self.buildTemplates().filter({ $0.name == templatePulled }).first
}
if buildTemplate == nil {
buildTemplate = BuildTemplate(projectName: self.project()!.workspaceMetadata!.projectName)
}
self.delegate.showBuildTemplateViewControllerForTemplate(buildTemplate, project: self.project()!, sender: self)
}
}
func pullTemplateFromUI() -> Bool {
if let _ = self.project() {
let selectedIndex = self.buildTemplateComboBox.indexOfSelectedItem
if selectedIndex == -1 {
//not yet selected
UIUtils.showAlertWithText("You need to select a Build Template first")
return false
}
let template = self.buildTemplates()[selectedIndex]
if let project = self.project() {
project.preferredTemplateId = template.uniqueId
return true
}
return false
}
return false
}
override func pullDataFromUI() -> Bool {
if super.pullDataFromUI() {
let successCreds = self.pullCredentialsFromUI()
let template = self.pullTemplateFromUI()
return successCreds && template
}
return false
}
func pullCredentialsFromUI() -> Bool {
if let project = self.project() {
_ = self.pullTokenFromUI()
let privateUrl = project.privateSSHKeyUrl
let publicUrl = project.publicSSHKeyUrl
_ = self.pullSSHPassphraseFromUI() //can't fail
let githubToken = project.githubToken
let tokenPresent = githubToken != nil
let sshValid = privateUrl != nil && publicUrl != nil
let success = tokenPresent && sshValid
if success {
return true
}
UIUtils.showAlertWithText("Credentials error - you need to specify a valid personal GitHub token and valid SSH keys - SSH keys are used by Git and the token is used for talking to the API (Pulling Pull Requests, updating commit statuses etc). Please, also make sure all are added correctly.")
}
return false
}
func pullSSHPassphraseFromUI() -> Bool {
let string = self.sshPassphraseTextField.stringValue
if let project = self.project() {
if !string.isEmpty {
project.sshPassphrase = string
} else {
project.sshPassphrase = nil
}
}
return true
}
func pullTokenFromUI() -> Bool {
let string = self.tokenTextField.stringValue
if let project = self.project() {
if !string.isEmpty {
project.githubToken = string
} else {
project.githubToken = nil
}
}
return true
}
func control(control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool {
if control == self.tokenTextField {
self.pullTokenFromUI()
}
if control == self.sshPassphraseTextField {
self.pullSSHPassphraseFromUI()
}
return true
}
override func removeCurrentConfig() {
if let project = self.project() {
//also cleanup comboBoxes
self.buildTemplateComboBox.stringValue = ""
self.storageManager.removeProject(project)
self.storageManager.saveProjects()
self.reloadStatus()
}
}
func selectKey(type: String) {
if let url = StorageUtils.openSSHKey(type) {
do {
_ = try NSString(contentsOfURL: url, encoding: NSASCIIStringEncoding)
let project = self.project()!
if type == "public" {
project.publicSSHKeyUrl = url
} else {
project.privateSSHKeyUrl = url
}
} catch {
UIUtils.showAlertWithError(error as NSError)
}
}
self.reloadStatus()
}
@IBAction func selectPublicKeyTapped(sender: AnyObject) {
self.selectKey("public")
}
@IBAction func selectPrivateKeyTapped(sender: AnyObject) {
self.selectKey("private")
}
func setupViewControllerDidSave(viewController: SetupViewController) {
if let templateViewController = viewController as? BuildTemplateViewController {
//select the passed in template
var foundIdx: Int? = nil
let template = templateViewController.buildTemplate
for (idx, obj) in self.buildTemplates().enumerate() {
if obj.uniqueId == template.uniqueId {
foundIdx = idx
break
}
}
if let project = self.project() {
project.preferredTemplateId = template.uniqueId
}
if let foundIdx = foundIdx {
self.buildTemplateComboBox.selectItemAtIndex(foundIdx)
} else {
UIUtils.showAlertWithText("Couldn't find saved template, please report this error!")
}
self.reloadStatus()
}
}
func setupViewControllerDidCancel(viewController: SetupViewController) {
if let _ = viewController as? BuildTemplateViewController {
//nothing to do really, reset the selection of the combo box to nothing
self.buildTemplateComboBox.deselectItemAtIndex(self.buildTemplateComboBox.indexOfSelectedItem)
self.reloadStatus()
}
}
}
| mit | 835ae12480dc1f63aeb87b0bb0353fe0 | 36.065753 | 304 | 0.582157 | 5.803947 | false | false | false | false |
mattfenwick/TodoRx | TodoRx/Extensions/Sequence+Group.swift | 1 | 668 | //
// Sequence+Group.swift
// TodoRx
//
// Created by Matt Fenwick on 7/19/17.
// Copyright © 2017 mf. All rights reserved.
//
import Foundation
extension Sequence {
func groupElements<K: Hashable>(projection: (Iterator.Element) -> K) -> [K: [Iterator.Element]] {
let emptyDict: [K: [Iterator.Element]] = [K: Array<Iterator.Element>]()
return self.reduce(emptyDict, { (dict, e) in
var newDict = dict
let key = projection(e)
var group: [Iterator.Element] = newDict[key] ?? Array<Iterator.Element>()
group.append(e)
newDict[key] = group
return newDict
})
}
}
| mit | 0644829f5971245b5c4ade34ff6a2195 | 28 | 101 | 0.583208 | 3.705556 | false | false | false | false |
ericvergnaud/antlr4 | runtime/Swift/Sources/Antlr4/RuntimeMetaData.swift | 4 | 8141 | /* 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.
*/
///
/// This class provides access to the current version of the ANTLR 4 runtime
/// library as compile-time and runtime constants, along with methods for
/// checking for matching version numbers and notifying listeners in the case
/// where a version mismatch is detected.
///
///
/// The runtime version information is provided by _#VERSION_ and
/// _#getRuntimeVersion()_. Detailed information about these values is
/// provided in the documentation for each member.
///
///
/// The runtime version check is implemented by _#checkVersion_. Detailed
/// information about incorporating this call into user code, as well as its use
/// in generated code, is provided in the documentation for the method.
///
///
/// Version strings x.y and x.y.z are considered "compatible" and no error
/// would be generated. Likewise, version strings x.y-SNAPSHOT and x.y.z are
/// considered "compatible" because the major and minor components x.y
/// are the same in each.
///
///
/// To trap any error messages issued by this code, use System.setErr()
/// in your main() startup code.
///
///
/// - Since: 4.3
///
public class RuntimeMetaData {
///
/// A compile-time constant containing the current version of the ANTLR 4
/// runtime library.
///
/// This compile-time constant value allows generated parsers and other
/// libraries to include a literal reference to the version of the ANTLR 4
/// runtime library the code was compiled against. At each release, we
/// change this value.
///
/// Version numbers are assumed to have the form
///
/// __major__.__minor__.__patch__.__revision__-__suffix__,
///
/// with the individual components defined as follows.
///
/// * __major__ is a required non-negative integer, and is equal to
/// `4` for ANTLR 4.
/// * __minor__ is a required non-negative integer.
/// * __patch__ is an optional non-negative integer. When
/// patch is omitted, the `.` (dot) appearing before it is
/// also omitted.
/// * __revision__ is an optional non-negative integer, and may only
/// be included when __patch__ is also included. When __revision__
/// is omitted, the `.` (dot) appearing before it is also omitted.
/// * __suffix__ is an optional string. When __suffix__ is
/// omitted, the `-` (hyphen-minus) appearing before it is also
/// omitted.
///
public static let VERSION: String = "4.11.1"
///
/// Gets the currently executing version of the ANTLR 4 runtime library.
///
///
/// This method provides runtime access to the _#VERSION_ field, as
/// opposed to directly referencing the field as a compile-time constant.
///
/// - Returns: The currently executing version of the ANTLR 4 library
///
public static func getRuntimeVersion() -> String {
return RuntimeMetaData.VERSION
}
///
/// This method provides the ability to detect mismatches between the version
/// of ANTLR 4 used to generate a parser, the version of the ANTLR runtime a
/// parser was compiled against, and the version of the ANTLR runtime which
/// is currently executing.
///
/// The version check is designed to detect the following two specific
/// scenarios.
///
/// * The ANTLR Tool version used for code generation does not match the
/// currently executing runtime version.
/// * The ANTLR Runtime version referenced at the time a parser was
/// compiled does not match the currently executing runtime version.
///
/// Starting with ANTLR 4.3, the code generator emits a call to this method
/// using two constants in each generated lexer and parser: a hard-coded
/// constant indicating the version of the tool used to generate the parser
/// and a reference to the compile-time constant _#VERSION_. At
/// runtime, this method is called during the initialization of the generated
/// parser to detect mismatched versions, and notify the registered listeners
/// prior to creating instances of the parser.
///
/// This method does not perform any detection or filtering of semantic
/// changes between tool and runtime versions. It simply checks for a
/// version match and emits an error to stderr if a difference
/// is detected.
///
/// Note that some breaking changes between releases could result in other
/// types of runtime exceptions, such as a _LinkageError_, prior to
/// calling this method. In these cases, the underlying version mismatch will
/// not be reported here. This method is primarily intended to
/// notify users of potential semantic changes between releases that do not
/// result in binary compatibility problems which would be detected by the
/// class loader. As with semantic changes, changes that break binary
/// compatibility between releases are mentioned in the release notes
/// accompanying the affected release.
///
/// __ Additional note for target developers:__ The version check
/// implemented by this class is designed to address specific compatibility
/// concerns that may arise during the execution of Java applications. Other
/// targets should consider the implementation of this method in the context
/// of that target's known execution environment, which may or may not
/// resemble the design provided for the Java target.
///
/// - Parameter generatingToolVersion: The version of the tool used to generate a parser.
/// This value may be null when called from user code that was not generated
/// by, and does not reference, the ANTLR 4 Tool itself.
/// - Parameter compileTimeVersion: The version of the runtime the parser was
/// compiled against. This should always be passed using a direct reference
/// to _#VERSION_.
///
public static func checkVersion(_ generatingToolVersion: String, _ compileTimeVersion: String) {
let runtimeVersion: String = RuntimeMetaData.VERSION
var runtimeConflictsWithGeneratingTool: Bool = false
var runtimeConflictsWithCompileTimeTool: Bool = false
//if ( generatingToolVersion != nil ) {
runtimeConflictsWithGeneratingTool =
!(runtimeVersion == (generatingToolVersion)) &&
!(getMajorMinorVersion(runtimeVersion) == (getMajorMinorVersion(generatingToolVersion)))
//}
runtimeConflictsWithCompileTimeTool =
!(runtimeVersion == (compileTimeVersion)) &&
!(getMajorMinorVersion(runtimeVersion) == (getMajorMinorVersion(compileTimeVersion)))
if runtimeConflictsWithGeneratingTool {
print("ANTLR Tool version \(generatingToolVersion) used for code generation does not match the current runtime version \(runtimeVersion)")
}
if runtimeConflictsWithCompileTimeTool {
print("ANTLR Runtime version \(compileTimeVersion)used for parser compilation does not match the current runtime version \(runtimeVersion)")
}
}
///
/// Gets the major and minor version numbers from a version string. For
/// details about the syntax of the input `version`.
/// E.g., from x.y.z return x.y.
///
/// - Parameter version: The complete version string.
/// - Returns: A string of the form __major__.__minor__ containing
/// only the major and minor components of the version string.
///
public static func getMajorMinorVersion(_ version: String) -> String {
var result = version
let dotBits = version.split(separator: ".", maxSplits: 2, omittingEmptySubsequences: false)
if dotBits.count >= 2 {
result = dotBits[0..<2].joined(separator: ".")
}
let dashBits = result.split(separator: "-", maxSplits: 1, omittingEmptySubsequences: false)
return String(dashBits[0])
}
}
| bsd-3-clause | 66a7e0c07980678a7757a6afa8a161d0 | 45.255682 | 152 | 0.677067 | 4.936931 | false | false | false | false |
y-hryk/ViewPager | ViewPagerDemo/ArtistViewController.swift | 1 | 5621 | //
// ArtistViewController.swift
// ViewPagerDemo
//
// Created by yamaguchi on 2016/08/31.
// Copyright © 2016年 h.yamaguchi. All rights reserved.
//
import UIKit
class ArtistViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier")
// self.tableView.contentOffset = CGPoint(x: 0, y: self.tableView.contentInset.top)
self.tableView.contentInset.top = 64 + 40
self.tableView.contentOffset = CGPoint(x: 0, y: -self.tableView.contentInset.top)
self.viewPagerController.viewPagerWillBeginDraggingHandler = { viewpager -> Void in
// print("viewPagerWillBeginDraggingHandler")
}
self.viewPagerController.viewPagerDidEndDraggingHandler = { viewpager -> Void in
// print("viewPagerDidEndDraggingHandler")
}
}
override func viewDidAppear(_ animated: Bool) {
// NSLog("\(tableView.contentInset)")
// self.tableView.contentInset.top = 64 + 40
// self.tableView.contentOffset = CGPoint(x: 0, y: -self.tableView.contentInset.top)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.scrollsToTop = true
self.viewPagerController.syncScrollViewOffset(scrollView: self.tableView)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
tableView.scrollsToTop = false
}
override func viewDidLayoutSubviews() {
// print("viewDidLayoutSubviews")
// print(self.view.frame)
// tableView.frame = self.view.frame
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 20
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
cell.textLabel!.text = "\((indexPath as NSIndexPath).row)"
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = UIViewController()
vc.view.backgroundColor = UIColor.white
self.navigationController?.pushViewController(vc, animated: true)
print(self.parent?.parent)
}
// override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
// self.viewPagerController.startScroll()
// }
//
// override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
// self.viewPagerController.endScroll()
// }
//
// override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
// self.viewPagerController.defaultPosition()
// }
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.viewPagerController.updateScrollViewOffset(scrollView: scrollView)
}
}
extension ArtistViewController: ViewPagerProtocol {
var viewPagerController: ViewPager {
return self.parent?.parent as! ViewPager
}
var scrollView: UIScrollView {
return self.tableView
}
}
| mit | 573d8e652d6e26f58530c4afcf647643 | 32.047059 | 157 | 0.661267 | 5.386385 | false | false | false | false |
joerocca/GitHawk | Pods/Apollo/Sources/Apollo/GraphQLExecutor.swift | 2 | 12097 | import Foundation
import Dispatch
/// A resolver is responsible for resolving a value for a field.
public typealias GraphQLResolver = (_ object: JSONObject, _ info: GraphQLResolveInfo) -> ResultOrPromise<JSONValue?>
public struct GraphQLResolveInfo {
let variables: GraphQLMap?
var responsePath: [String] = []
var responseKeyForField: String = ""
var cachePath: [String] = []
var cacheKeyForField: String = ""
var fields: [GraphQLField] = []
init(rootKey: CacheKey?, variables: GraphQLMap?) {
self.variables = variables
if let rootKey = rootKey {
cachePath = [rootKey]
}
}
}
func joined(path: [String]) -> String {
return path.joined(separator: ".")
}
public struct GraphQLResultError: Error, LocalizedError {
let path: [String]
let underlying: Error
public var errorDescription: String? {
return "Error at path \"\(joined(path: path))\": \(underlying)"
}
}
/// A GraphQL executor is responsible for executing a selection set and generating a result. It is initialized with a resolver closure that gets called repeatedly to resolve field values.
///
/// An executor is used both to parse a response received from the server, and to read from the normalized cache. It can also be configured with a accumulator that receives events during execution, and these execution events are used by `GraphQLResultNormalizer` to normalize a response into a flat set of records and keep track of dependent keys.
///
/// The methods in this class closely follow the [execution algorithm described in the GraphQL specification](https://facebook.github.io/graphql/#sec-Execution), but an important difference is that execution returns a value for every selection in a selection set, not the merged fields. This means we get a separate result for every fragment, even though all fields that share a response key are still executed at the same time for efficiency.
///
/// So given the following query:
///
/// ```
/// query HeroAndFriendsNames {
/// hero {
/// name
/// friends {
/// name
/// }
/// ...FriendsAppearsIn
/// }
/// }
///
/// fragment FriendsAppearsIn on Character {
/// friends {
/// appearsIn
/// }
/// }
/// ```
///
/// A server would return a response with `name` and `appearsIn` merged into one object:
///
/// ```
/// ...
/// {
/// "name": "R2-D2",
/// "friends": [
/// {
/// "name": "Luke Skywalker",
/// "appearsIn": ["NEWHOPE", "EMPIRE", "JEDI"]
/// }
/// }
/// ...
/// ```
///
/// The executor on the other hand, will return a separate value for every selection:
///
/// - `String`
/// - `[HeroAndFriendsNames.Data.Hero.Friend]`
/// - `FriendsAppearsIn`
/// - `[FriendsAppearsIn.Friend]`
///
/// These values then get passed into a generated `GraphQLMappable` initializer, and this is how type safe results get built up.
///
public final class GraphQLExecutor {
private let queue: DispatchQueue
private let resolver: GraphQLResolver
var dispatchDataLoads: (() -> Void)? = nil
var dispatchDataLoadsScheduled: Bool = false
var cacheKeyForObject: CacheKeyForObject?
var shouldComputeCachePath = true
/// Creates a GraphQLExecutor that resolves field values by calling the provided resolver.
public init(resolver: @escaping GraphQLResolver) {
queue = DispatchQueue(label: "com.apollographql.GraphQLExecutor")
self.resolver = resolver
}
private func runtimeType(of object: JSONObject) -> String? {
return object["__typename"] as? String
}
private func cacheKey(for object: JSONObject) -> String? {
guard let value = cacheKeyForObject?(object) else { return nil }
if let array = value as? [Any?] {
return array.flatMap { $0 }.map { String(describing: $0) }.joined(separator: "_")
} else {
return String(describing: value)
}
}
// MARK: - Execution
func execute<Accumulator: GraphQLResultAccumulator>(selections: [GraphQLSelection], on object: JSONObject, withKey key: CacheKey? = nil, variables: GraphQLMap? = nil, accumulator: Accumulator) throws -> Promise<Accumulator.FinalResult> {
let info = GraphQLResolveInfo(rootKey: key, variables: variables)
return try execute(selections: selections, on: object, info: info, accumulator: accumulator).map {
try accumulator.finish(rootValue: $0, info: info)
}.asPromise()
}
private func execute<Accumulator: GraphQLResultAccumulator>(selections: [GraphQLSelection], on object: JSONObject, info: GraphQLResolveInfo, accumulator: Accumulator) throws -> ResultOrPromise<Accumulator.ObjectResult> {
var groupedFields = GroupedSequence<String, GraphQLField>()
try collectFields(selections: selections, forRuntimeType: runtimeType(of: object), into: &groupedFields, info: info)
var fieldEntries: [ResultOrPromise<Accumulator.FieldEntry>] = []
fieldEntries.reserveCapacity(groupedFields.keys.count)
for (_, fields) in groupedFields {
let fieldEntry = try execute(fields: fields, on: object, info: info, accumulator: accumulator)
fieldEntries.append(fieldEntry)
}
if let dispatchDataLoads = dispatchDataLoads, !dispatchDataLoadsScheduled {
dispatchDataLoadsScheduled = true
queue.async {
self.dispatchDataLoadsScheduled = false
dispatchDataLoads()
}
}
return whenAll(fieldEntries, notifyOn: queue).map {
try accumulator.accept(fieldEntries: $0, info: info)
}
}
/// Before execution, the selection set is converted to a grouped field set. Each entry in the grouped field set is a list of fields that share a response key. This ensures all fields with the same response key (alias or field name) included via referenced fragments are executed at the same time.
private func collectFields(selections: [GraphQLSelection], forRuntimeType runtimeType: String?, into groupedFields: inout GroupedSequence<String, GraphQLField>, info: GraphQLResolveInfo) throws {
for selection in selections {
switch selection {
case let field as GraphQLField:
_ = groupedFields.append(value: field, forKey: field.responseKey)
case let booleanCondition as GraphQLBooleanCondition:
guard let value = info.variables?[booleanCondition.variableName] else {
throw GraphQLError("Variable \(booleanCondition.variableName) was not provided.")
}
if value as? Bool == !booleanCondition.inverted {
try collectFields(selections: booleanCondition.selections, forRuntimeType: runtimeType, into: &groupedFields, info: info)
}
case let fragmentSpread as GraphQLFragmentSpread:
let fragment = fragmentSpread.fragment
if let runtimeType = runtimeType, fragment.possibleTypes.contains(runtimeType) {
try collectFields(selections: fragment.selections, forRuntimeType: runtimeType, into: &groupedFields, info: info)
}
case let typeCase as GraphQLTypeCase:
let selections: [GraphQLSelection]
if let runtimeType = runtimeType {
selections = typeCase.variants[runtimeType] ?? typeCase.default
} else {
selections = typeCase.default
}
try collectFields(selections: selections, forRuntimeType: runtimeType, into: &groupedFields, info: info)
default:
preconditionFailure()
}
}
}
/// Each field requested in the grouped field set that is defined on the selected objectType will result in an entry in the response map. Field execution first coerces any provided argument values, then resolves a value for the field, and finally completes that value either by recursively executing another selection set or coercing a scalar value.
private func execute<Accumulator: GraphQLResultAccumulator>(fields: [GraphQLField], on object: JSONObject, info: GraphQLResolveInfo, accumulator: Accumulator) throws -> ResultOrPromise<Accumulator.FieldEntry> {
// GraphQL validation makes sure all fields sharing the same response key have the same arguments and are of the same type, so we only need to resolve one field.
let firstField = fields[0]
var info = info
let responseKey = firstField.responseKey
info.responseKeyForField = responseKey
info.responsePath.append(responseKey)
if shouldComputeCachePath {
let cacheKey = try firstField.cacheKey(with: info.variables)
info.cacheKeyForField = cacheKey
info.cachePath.append(cacheKey)
}
// We still need all fields to complete the value, because they may have different selection sets.
info.fields = fields
let resultOrPromise = resolver(object, info)
return resultOrPromise.on(queue: queue).flatMap { value in
guard let value = value else {
throw JSONDecodingError.missingValue
}
return try self.complete(value: value, ofType: firstField.type, info: info, accumulator: accumulator)
}.map {
try accumulator.accept(fieldEntry: $0, info: info)
}.catch { error in
if !(error is GraphQLResultError) {
throw GraphQLResultError(path: info.responsePath, underlying: error)
}
}
}
/// After resolving the value for a field, it is completed by ensuring it adheres to the expected return type. If the return type is another Object type, then the field execution process continues recursively.
private func complete<Accumulator: GraphQLResultAccumulator>(value: JSONValue, ofType returnType: GraphQLOutputType, info: GraphQLResolveInfo, accumulator: Accumulator) throws -> ResultOrPromise<Accumulator.PartialResult> {
if case .nonNull(let innerType) = returnType {
if value is NSNull {
return .result(.failure(JSONDecodingError.nullValue))
}
return try complete(value: value, ofType: innerType, info: info, accumulator: accumulator)
}
if value is NSNull {
return ResultOrPromise { try accumulator.acceptNullValue(info: info) }
}
switch returnType {
case .scalar:
return ResultOrPromise { try accumulator.accept(scalar: value, info: info) }
case .list(let innerType):
guard let array = value as? [JSONValue] else { return .result(.failure(JSONDecodingError.wrongType)) }
return try whenAll(array.enumerated().map { index, element -> ResultOrPromise<Accumulator.PartialResult> in
var info = info
let indexSegment = String(index)
info.responsePath.append(indexSegment)
info.cachePath.append(indexSegment)
return try self.complete(value: element, ofType: innerType, info: info, accumulator: accumulator)
}, notifyOn: queue).map { completedArray in
return try accumulator.accept(list: completedArray, info: info)
}
case .object:
guard let object = value as? JSONObject else { return .result(.failure(JSONDecodingError.wrongType)) }
// The merged selection set is a list of fields from all sub‐selection sets of the original fields.
let selections = mergeSelectionSets(for: info.fields)
var info = info
if shouldComputeCachePath, let cacheKeyForObject = self.cacheKey(for: object) {
info.cachePath = [cacheKeyForObject]
}
// We execute the merged selection set on the object to complete the value. This is the recursive step in the GraphQL execution model.
return try execute(selections: selections, on: object, info: info, accumulator: accumulator).map { return $0 as! Accumulator.PartialResult }
default:
preconditionFailure()
}
}
/// When fields are selected multiple times, their selection sets are merged together when completing the value in order to continue execution of the sub‐selection sets.
private func mergeSelectionSets(for fields: [GraphQLField]) -> [GraphQLSelection] {
var selections: [GraphQLSelection] = []
for field in fields {
if case let .object(fieldSelections) = field.type.namedType {
selections.append(contentsOf: fieldSelections)
}
}
return selections
}
}
| mit | 470accc3cd9dc2ae70b23721395e6335 | 41.283217 | 443 | 0.701398 | 4.689027 | false | false | false | false |
radex/swift-compiler-crashes | crashes-duplicates/23299-vtable.swift | 11 | 2390 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
i>
0.a
struct A {
class
}
class a
class d<T> {
func a<T> : B, d where B : d.h
struct g<T where B : d
let end = [ {
class A {
case c,
let a {
"[Void{
func h=B<T>
func b:a{
typealias e:a
struct A
class
let end = [ {
let end = j
protocol a {
class
case c,
let end = a
let end = [Void{
{
let end = j
class
func b:a
let end = [ {
t ) {
func b
class
struct A {
class
println( ) {
for b {
class a {
func < = [Void{
let f = [Void{
protocol A<T where k.b { func h
typealias e = {
typealias e : e
class
func a"[Void{class a {
init( 1 )
let end = [ {
}
struct A {
case ,
func f
class A {
case c,
class a {
class
"
{
let end = a<T> (d
let end = j
var b { func a<d where f(d
protocol B : a {
typealias e : {
struct A {
func a<T where k.h=
let end = [ {
func a<d where k.a<T>: f:a<T:b:A<d = [ {
case ,
struct g<T>: a {
var b = [Void{
case c,
i: b {
class
let end = [Void{
struct S {
func e
struct A {
typealias e = B<d = j
D T where k.h
class
struct A<T> (a
class
let f = j
class A {
protocol a {
class A {
case c,
protocol B : b = [Void{
protocol c {
{
typealias e = [Void{
deinit {
enum S<T:a
{
D : P
class d
case c,
func a
class a
init( 1 )
case c,
var d where B : e
let end = [ {
case ,y)
let end = a<T where B : d<T>
i:b
}
typealias e : b {
struct A<d<d
class
let end = [Void{
class
func < <T>
let a {
}
let a<d where k.h
let a {
enum A {
class B : B<T>: a {
enum B? {
let a<T>: e
}
D {
class
case c,
typealias e = a<T where k.a<T>: d<d {}
deinit {
class
let end = [ {
{
0.b {
case c,
func a
"
let f = [Void{
class d : d.b { func b
var d where B : B? {
struct . {
struct A<l {
protocol A,
class A {
protocol a {
func a
struct c,
var b = [Void{
class A,
func b
struct A<T > (v: d<T where k.e : e
i>: d
struct c,
func a<T>
{
typealias e = [ {
var d where H : {
class
case c,
class a
protocol a {
protocol a {
{
let f = j
typealias e = [Void{
struct B? {
typealias e : d< <T where k.b {
let f = a{
"
let f = B<T where H : a {
let a {
deinit {
let i: e
}
case c,
let a
let end = B? {
{
deinit {
let a {
case c,
class
class a {
func a
protocol B : B, leng
var b { func b
typealias e.h
func f:A<T:A:a{
class a T>: b = [Void{class B : a {
typealias e = {
struct g<T where k.b = B? {
let a {
protocol A {
protocol B {
protocol a {
case c
| mit | 2182beaa0c5011077a363cb4731c6777 | 11.13198 | 87 | 0.602092 | 2.327167 | false | false | false | false |
glock45/swiftX | Source/http/sha1.swift | 1 | 4577 | //
// sha1.swift
// swiftx
//
// Copyright © 2016 kolakowski. All rights reserved.
//
import Foundation
public struct SHA1 {
public static func hash(_ input: [UInt8]) -> [UInt8] {
// Alghorithm from: https://en.wikipedia.org/wiki/SHA-1
var message = input
var h0 = UInt32(littleEndian: 0x67452301)
var h1 = UInt32(littleEndian: 0xEFCDAB89)
var h2 = UInt32(littleEndian: 0x98BADCFE)
var h3 = UInt32(littleEndian: 0x10325476)
var h4 = UInt32(littleEndian: 0xC3D2E1F0)
// ml = message length in bits (always a multiple of the number of bits in a character).
let ml = UInt64(message.count * 8)
// append the bit '1' to the message e.g. by adding 0x80 if message length is a multiple of 8 bits.
message.append(0x80)
// append 0 ≤ k < 512 bits '0', such that the resulting message length in bits is congruent to −64 ≡ 448 (mod 512)
let padBytesCount = ( message.count + 8 ) % 64
message.append(contentsOf: [UInt8](repeating: 0, count: 64 - padBytesCount))
// append ml, in a 64-bit big-endian integer. Thus, the total length is a multiple of 512 bits.
var mlBigEndian = ml.bigEndian
withUnsafePointer(to: &mlBigEndian) {
message.append(contentsOf: Array(UnsafeBufferPointer<UInt8>(start: UnsafePointer(OpaquePointer($0)), count: 8)))
}
// Process the message in successive 512-bit chunks ( 64 bytes chunks ):
for chunkStart in 0..<message.count/64 {
var words = [UInt32]()
let chunk = message[chunkStart*64..<chunkStart*64+64]
// break chunk into sixteen 32-bit big-endian words w[i], 0 ≤ i ≤ 15
for i in 0...15 {
let value = chunk.withUnsafeBufferPointer({ UnsafePointer<UInt32>(OpaquePointer($0.baseAddress! + (i*4))).pointee})
words.append(value.bigEndian)
}
// Extend the sixteen 32-bit words into eighty 32-bit words:
for i in 16...79 {
let value: UInt32 = ((words[i-3]) ^ (words[i-8]) ^ (words[i-14]) ^ (words[i-16]))
words.append(rotateLeft(value, 1))
}
// Initialize hash value for this chunk:
var a = h0
var b = h1
var c = h2
var d = h3
var e = h4
for i in 0..<80 {
var f = UInt32(0)
var k = UInt32(0)
switch i {
case 0...19:
f = (b & c) | ((~b) & d)
k = 0x5A827999
case 20...39:
f = b ^ c ^ d
k = 0x6ED9EBA1
case 40...59:
f = (b & c) | (b & d) | (c & d)
k = 0x8F1BBCDC
case 60...79:
f = b ^ c ^ d
k = 0xCA62C1D6
default: break
}
let temp = (rotateLeft(a, 5) &+ f &+ e &+ k &+ words[i]) & 0xFFFFFFFF
e = d
d = c
c = rotateLeft(b, 30)
b = a
a = temp
}
// Add this chunk's hash to result so far:
h0 = ( h0 &+ a ) & 0xFFFFFFFF
h1 = ( h1 &+ b ) & 0xFFFFFFFF
h2 = ( h2 &+ c ) & 0xFFFFFFFF
h3 = ( h3 &+ d ) & 0xFFFFFFFF
h4 = ( h4 &+ e ) & 0xFFFFFFFF
}
// Produce the final hash value (big-endian) as a 160 bit number:
var digest = [UInt8]()
[h0, h1, h2, h3, h4].forEach { value in
var bigEndianVersion = value.bigEndian
withUnsafePointer(to: &bigEndianVersion) {
digest.append(contentsOf: Array(UnsafeBufferPointer<UInt8>(start: UnsafePointer(OpaquePointer($0)), count: 4)))
}
}
return digest
}
private static func rotateLeft(_ v: UInt32, _ n: UInt32) -> UInt32 {
return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n))
}
}
extension String {
public func sha1() -> [UInt8] {
return SHA1.hash([UInt8](self.utf8))
}
public func sha1() -> String {
return self.sha1().reduce("") { $0 + String(format: "%02x", $1) }
}
}
| bsd-3-clause | cbc398bf76dd0a26eeb5ca40ac378222 | 32.573529 | 131 | 0.471967 | 4.069519 | false | false | false | false |
pietgk/EuropeanaApp | EuropeanaApp/EuropeanaApp/Classes/Model/IXHistoricPoi.swift | 1 | 1263 | //
// IXHistoricPoi.swift
// ArtWhisper
//
// Created by Axel Roest on 07/01/16.
// Copyright © 2016 Phluxus. All rights reserved.
//
import Foundation
@objc class IXHistoricPoi : NSObject , NSCoding {
var visitDate: NSDate?
var visitDuration: NSTimeInterval?
var poi: IXPoi?
init(poi: IXPoi, date:NSDate, duration:NSTimeInterval) {
self.poi = poi
self.visitDate = date
self.visitDuration = duration
super.init()
}
required convenience init?(coder aDecoder: NSCoder) {
let visitDate = aDecoder.decodeObjectForKey("AWHistoricVisitDate") as! NSDate
// let visitDuration = NSTimeInterval(aDecoder.decodeDoubleForKey("AWHistoricVisitDuration"))
let visitDuration = aDecoder.decodeDoubleForKey("AWHistoricVisitDuration")
let poi = aDecoder.decodeObjectForKey("AWHistoricPoi") as! IXPoi
self.init(poi:poi, date:visitDate, duration:visitDuration)
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(visitDate, forKey: "AWHistoricVisitDate")
let dur = visitDuration ?? 0.0
aCoder.encodeDouble(dur, forKey: "AWHistoricVisitDuration")
aCoder.encodeObject(poi, forKey: "AWHistoricPoi")
}
} | mit | fc716307cd395039d33c15f9972401c2 | 31.384615 | 100 | 0.678288 | 4.475177 | false | false | false | false |
festrs/Plantinfo | PlantInfo/PhotosController.swift | 1 | 2718 | //
// PhotosController.swift
// PlantInfo
//
// Created by Felipe Dias Pereira on 2016-09-08.
// Copyright © 2016 Felipe Dias Pereira. All rights reserved.
//
import UIKit
import Kingfisher
import ReachabilitySwift
class PhotosController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate,ReceivedPlantProtocol {
@IBOutlet weak var collectionView: UICollectionView!
private var plant:Plant!
private let reuseIdentifier = "photoCell"
@IBOutlet var photsCollection: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let layout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
let itemWidth = view.bounds.width / 2.0
let itemHeight = layout.itemSize.height
layout.itemSize = CGSize(width: itemWidth-7, height: itemHeight)
layout.invalidateLayout()
}
}
func receivePlant(plant: Plant) {
self.plant = plant
}
func numberOfSectionsInCollectionView(collectionView:
UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return (plant.imageLinks?.count)!
}
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) ->
UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier,
forIndexPath: indexPath) as! PhotosCellController
// Configure the cell
cell.plantImageView.kf_setImageWithURL(NSURL(string: URL_IMAGE_BASE+plant.imageLinks![indexPath.row])!, placeholderImage: UIImage(named: "default-placeholder"), optionsInfo: nil, progressBlock: nil) { (image, error, cacheType, imageURL) in
}
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//let cell = collectionView.cellForItemAtIndexPath(indexPath) as! PhotosCellController
}
}
class PhotosCellController : UICollectionViewCell{
@IBOutlet weak var plantImageView: UIImageView!
}
| mit | ab049d4dc9783191945b91d19ae04ddf | 32.134146 | 251 | 0.65403 | 5.91939 | false | false | false | false |
kevinskyba/ReadyForCoffee | ReadyForCoffee/Commons.swift | 1 | 2616 | //
// Commons.swift
// ReadyForCoffee
//
// Created by Kevin Skyba on 13.08.15.
// Copyright (c) 2015 Kevin Skyba. All rights reserved.
//
import Foundation
import Cocoa
struct Commons {
struct Settings {
static var serviceNamePrefix : String {
get {
var version : AnyObject? = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]
var versionString = (version as! String).stringByReplacingOccurrencesOfString(".", withString: "-", options: NSStringCompareOptions.LiteralSearch, range: nil)
return "RFC-" + versionString + "-"
}
}
}
struct Colors {
static let primaryColor : NSColor = NSColor(deviceRed: 153/255, green: 98/255, blue: 42/255, alpha: 1)
static let secondaryColor : NSColor = NSColor(deviceRed: 201/255, green: 159/255, blue: 105/255, alpha: 1)
static let primaryFontColor : NSColor = NSColor(deviceRed: 221/255, green: 204/255, blue: 173/255, alpha: 1)
}
struct Dimensions {
struct CoffeeCupView {
static let steamHeightPercentage : CGFloat = 0.3
static let spacePercentage : CGFloat = 0.1
static let coffeeCupHeightPercentage : CGFloat = 0.6
static let steamWidthPercentage : CGFloat = 0.06
}
struct MainPopoverView {
static let titleOffsetTop : CGFloat = 15
static let titleFontName : String = "Channel"
static let titleFontSize : CGFloat = 30
static let titleHeight : CGFloat = 60
static let subTitleOffsetBottom : CGFloat = 15
static let subTitleFontName : String = "Channel"
static let subTitleFontSize : CGFloat = 15
static let subTitleHeight : CGFloat = 18
static let optionsFontName : String = "Channel"
static let optionsFontSize : CGFloat = 14
static let optionsHeight : CGFloat = 20
static let optionsOffset : CGFloat = 10
static let optionsWidth : CGFloat = 50
static let coffeeCupSize : CGFloat = 125
static let informationButtonSize : CGFloat = 25
static let informationButtonOffset : CGFloat = 10
static let sliderOffsetTop : CGFloat = 10
static let sliderHeight : CGFloat = 50
static let sliderWidth : CGFloat = 150
}
}
} | mit | 803e0a067a55b82e638fd0b5622d4573 | 33.434211 | 174 | 0.574159 | 5.484277 | false | false | false | false |
sclukey/Regex | Tests/RegexTests/RegexSpec.swift | 1 | 5085 | final class RegexSpec: QuickSpec {
override func spec() {
describe("Regex") {
it("matches with no capture groups") {
let regex = Regex("now you're matching with regex")
expect(regex).to(match("now you're matching with regex"))
}
it("matches a single capture group") {
let regex = Regex("foo (bar|baz)")
expect(regex).to(capture("bar", from: "foo bar"))
}
it("matches multiple capture groups") {
let regex = Regex("foo (bar|baz) (123|456)")
expect(regex).to(capture("baz", "456", from: "foo baz 456"))
}
it("doesn't include the entire match in the list of captures") {
let regex = Regex("foo (bar|baz)")
expect(regex).notTo(capture("foo bar", from: "foo bar"))
}
it("provides access to the entire matched string") {
let regex = Regex("foo (bar|baz)")
expect(regex.firstMatch(in: "foo bar")?.matchedString).to(equal("foo bar"))
}
it("can match a regex multiple times in the same string") {
let regex = Regex("(foo)")
let matches = regex
.allMatches(in: "foo foo foo")
.flatMap { $0.captures }
.flatMap { $0 }
expect(matches).to(equal(["foo", "foo", "foo"]))
}
it("supports the match operator") {
let matched: Bool
switch "eat some food" {
case Regex("foo"):
matched = true
default:
matched = false
}
expect(matched).to(beTrue())
}
it("supports the match operator in reverse") {
let matched: Bool
switch Regex("foo") {
case "fool me twice":
matched = true
default:
matched = false
}
expect(matched).to(beTrue())
}
}
describe("optional capture groups") {
let regex = Regex("(a)?(b)")
it("maintains the position of captures regardless of optionality") {
expect(regex.firstMatch(in: "ab")?.captures[1]).to(equal("b"))
expect(regex.firstMatch(in: "b")?.captures[1]).to(equal("b"))
}
it("returns nil for an unmatched capture") {
expect(regex.firstMatch(in: "b")?.captures[0]).to(beNil())
}
}
describe("capture ranges") {
it("correctly converts from the underlying index type") {
// U+0061 LATIN SMALL LETTER A
// U+0065 LATIN SMALL LETTER E
// U+0301 COMBINING ACUTE ACCENT
// U+221E INFINITY
// U+1D11E MUSICAL SYMBOL G CLEF
let string = "\u{61}\u{65}\u{301}\u{221E}\u{1D11E}"
let infinity = Regex("(\u{221E})").firstMatch(in: string)!.captures[0]!
let rangeOfInfinity = string.range(of: infinity)!
let location = string.distance(from: string.startIndex, to: rangeOfInfinity.lowerBound)
let length = string.distance(from: rangeOfInfinity.lowerBound, to: rangeOfInfinity.upperBound)
expect(location).to(equal(2))
expect(length).to(equal(1))
}
}
describe("matching at line anchors") {
it("can anchor matches to the start of each line") {
let regex = Regex("(?m)^foo")
let multilineString = "foo\nbar\nfoo\nbaz"
expect(regex.allMatches(in: multilineString).count).to(equal(2))
}
it("validates that the example in the README is correct") {
let totallyUniqueExamples = Regex(
"^(hello|foo).*$",
options: [.ignoreCase, .anchorsMatchLines])
let multilineText = "hello world\ngoodbye world\nFOOBAR\n"
let matchingLines = totallyUniqueExamples.allMatches(in: multilineText).map { $0.matchedString }
expect(matchingLines).to(equal(["hello world", "FOOBAR"]))
}
}
describe("last match") {
it("is available in a pattern matching context") {
switch "hello" {
case Regex("l+"):
expect(Regex.lastMatch?.matchedString).to(equal("ll"))
default:
fail("expected regex to match")
}
}
it("resets the last match to nil when a match fails") {
_ = "foo" ~= Regex("foo")
expect(Regex.lastMatch).notTo(beNil())
_ = "foo" ~= Regex("bar")
expect(Regex.lastMatch).to(beNil())
}
}
}
}
private func match(_ string: String) -> NonNilMatcherFunc<Regex> {
return NonNilMatcherFunc { actual, failureMessage throws in
let regex: Regex! = try actual.evaluate()
failureMessage.stringValue = "expected <\(regex)> to match <\(string)>"
return regex.matches(string)
}
}
private func capture(_ captures: String..., from string: String) -> NonNilMatcherFunc<Regex> {
return NonNilMatcherFunc { actual, failureMessage throws in
let regex: Regex! = try actual.evaluate()
failureMessage.stringValue = "expected <\(regex)> to capture <\(captures)> from <\(string)>"
for expected in captures {
guard let match = regex.firstMatch(in: string), match.captures.contains(where: { $0 == expected }) else {
return false
}
}
return true
}
}
import Quick
import Nimble
import Regex
| mit | 08e459f094098a192a8deb1445d1b3b4 | 30.78125 | 111 | 0.589971 | 4.120746 | false | false | false | false |
RobotsAndPencils/SwiftCharts | SwiftCharts/Utils/Trendlines/TrendlineGenerator.swift | 2 | 1546 | //
// TrendlineGenerator.swift
// Examples
//
// Created by ischuetz on 03/08/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public struct TrendlineGenerator {
public static func trendline(chartPoints: [ChartPoint]) -> [ChartPoint] {
guard chartPoints.count > 1 else {return []}
let doubleO: Double = 0
let (sumX, sumY, sumXY, sumXX): (sumX: Double, sumY: Double, sumXY: Double, sumXX: Double) = chartPoints.reduce((sumX: doubleO, sumY: doubleO, sumXY: doubleO, sumXX: doubleO)) {(tuple, chartPoint) in
let x: Double = chartPoint.x.scalar
let y: Double = chartPoint.y.scalar
return (
tuple.sumX + x,
tuple.sumY + y,
tuple.sumXY + x * y,
tuple.sumXX + x * x
)
}
let count = Double(chartPoints.count)
let b = (count * sumXY - sumX * sumY) / (count * sumXX - sumX * sumX)
let a = (sumY - b * sumX) / count
// equation of line: y = a + bx
func y(x: Double) -> Double {
return a + b * x
}
let first = chartPoints.first!
let last = chartPoints.last!
return [
ChartPoint(x: ChartAxisValueDouble(first.x.scalar), y: ChartAxisValueDouble(y(first.x.scalar))),
ChartPoint(x: ChartAxisValueDouble(last.x.scalar), y: ChartAxisValueDouble(y(last.x.scalar)))
]
}
} | apache-2.0 | bdf91b89541022793734bde30924094b | 30.571429 | 207 | 0.535576 | 4.282548 | false | false | false | false |
criticalmaps/criticalmaps-ios | CriticalMapsKit/Sources/MapFeature/RiderAnnoationView.swift | 1 | 1929 | import MapKit
import UIKit
final class RiderAnnoationView: MKAnnotationView {
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
canShowCallout = false
backgroundColor = UIColor.label.resolvedColor(with: traitCollection)
frame = defineFrame()
layer.cornerRadius = frame.height / 2
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
isAccessibilityElement = false
}
private func defineFrame() -> CGRect {
switch traitCollection.preferredContentSizeCategory {
case .extraSmall, .small, .medium, .large:
return .defaultSize
case .extraLarge:
return .large
case .extraExtraLarge:
return .extraLarge
case .extraExtraExtraLarge,
.accessibilityMedium,
.accessibilityLarge,
.accessibilityExtraLarge,
.accessibilityExtraExtraLarge,
.accessibilityExtraExtraExtraLarge:
return .extraExtraLarge
default:
return .defaultSize
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// For some reason when this active the annotions disappear when sheets dismiss
// frame = defineFrame()
// layer.cornerRadius = frame.height / 2
backgroundColor = UIColor.label.resolvedColor(with: traitCollection)
setNeedsDisplay()
}
}
extension CGRect {
static let defaultSize = Self(x: 0, y: 0, width: 7, height: 7)
static let large = Self(x: 0, y: 0, width: 10, height: 10)
static let extraLarge = Self(x: 0, y: 0, width: 14, height: 14)
static let extraExtraLarge = Self(x: 0, y: 0, width: 20, height: 20)
}
| mit | cb9134bffbb79fea9c77f53bc49164f3 | 30.622951 | 89 | 0.703992 | 4.7866 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/NUX/ContentViews/Editor/UnifiedPrologueReaderContentView.swift | 2 | 9481 | import SwiftUI
/// Prologue reader page contents
struct UnifiedPrologueReaderContentView: View {
var body: some View {
GeometryReader { content in
let spacingUnit = content.size.height * 0.06
let feedSize = content.size.height * 0.1
let smallIconSize = content.size.height * 0.175
let largerIconSize = content.size.height * 0.25
let fontSize = content.size.height * 0.05
let smallFontSize = content.size.height * 0.045
let smallFont = Font.system(size: smallFontSize, weight: .regular, design: .default)
let feedFont = Font.system(size: fontSize,
weight: .regular,
design: .default)
VStack {
RoundRectangleView {
HStack {
VStack {
FeedRow(image: Appearance.feedTopImage,
imageSize: feedSize,
title: Strings.feedTopTitle,
font: feedFont)
FeedRow(image: Appearance.feedMiddleImage,
imageSize: feedSize,
title: Strings.feedMiddleTitle,
font: feedFont)
FeedRow(image: Appearance.feedBottomImage,
imageSize: feedSize,
title: Strings.feedBottomTitle,
font: feedFont)
}
}
.padding(spacingUnit / 2)
HStack {
Spacer()
CircledIcon(size: largerIconSize,
xOffset: largerIconSize * 0.7,
yOffset: -largerIconSize * 0.05,
iconType: .readerFollow,
backgroundColor: Color(UIColor.muriel(name: .red, .shade40)))
}
}
.fixedSize(horizontal: false, vertical: true)
.padding(.horizontal, spacingUnit)
Spacer(minLength: spacingUnit / 2)
.fixedSize(horizontal: false, vertical: true)
RoundRectangleView {
ScrollView(.horizontal) {
VStack(alignment: .leading) {
HStack {
ForEach([Strings.tagArt, Strings.tagCooking, Strings.tagFootball], id: \.self) { item in
Text(item)
.tagItemStyle(with: smallFont, horizontalPadding: spacingUnit, verticalPadding: spacingUnit * 0.25)
}
}
HStack {
ForEach([Strings.tagGardening, Strings.tagMusic, Strings.tagPolitics], id: \.self) { item in
Text(item)
.tagItemStyle(with: smallFont, horizontalPadding: spacingUnit, verticalPadding: spacingUnit * 0.25)
}
}
}
.padding(spacingUnit / 2)
}
.disabled(true)
HStack {
CircledIcon(size: smallIconSize,
xOffset: -smallIconSize * 0.5,
yOffset: -smallIconSize * 0.7,
iconType: .star,
backgroundColor: Color(UIColor.muriel(name: .yellow, .shade20)))
Spacer()
}
}
.fixedSize(horizontal: false, vertical: true)
Spacer(minLength: spacingUnit / 2)
.fixedSize(horizontal: false, vertical: true)
let postWidth = content.size.width * 0.3
RoundRectangleView {
ScrollView(.horizontal) {
HStack {
PostView(image: Appearance.firstPostImage, title: Strings.firstPostTitle, size: postWidth, font: smallFont)
PostView(image: Appearance.secondPostImage, title: Strings.secondPostTitle, size: postWidth, font: smallFont)
PostView(image: Appearance.thirdPostImage, title: Strings.thirdPostTitle, size: postWidth, font: smallFont)
}
.padding(spacingUnit / 2)
}
.disabled(true)
HStack {
Spacer()
CircledIcon(size: smallIconSize,
xOffset: smallIconSize * 0.75,
yOffset: -smallIconSize * 0.85,
iconType: .bookmarkOutline,
backgroundColor: Color(UIColor.muriel(name: .purple, .shade50)))
}
}
.fixedSize(horizontal: false, vertical: true)
.padding(.horizontal, spacingUnit)
}
}
}
}
private extension UnifiedPrologueReaderContentView {
enum Appearance {
static let feedTopImage = "page5Avatar1"
static let feedMiddleImage = "page5Avatar2"
static let feedBottomImage = "page5Avatar3"
static let firstPostImage = "page5Img1Coffee"
static let secondPostImage = "page5Img2Stadium"
static let thirdPostImage = "page5Img3Museum"
}
enum Strings {
static let feedTopTitle: String = "Pamela Nguyen"
static let feedMiddleTitle: String = NSLocalizedString("Web News", comment: "Example Reader feed title")
static let feedBottomTitle: String = NSLocalizedString("Rock 'n Roll Weekly", comment: "Example Reader feed title")
static let tagArt: String = NSLocalizedString("Art", comment: "An example tag used in the login prologue screens.")
static let tagCooking: String = NSLocalizedString("Cooking", comment: "An example tag used in the login prologue screens.")
static let tagFootball: String = NSLocalizedString("Football", comment: "An example tag used in the login prologue screens.")
static let tagGardening: String = NSLocalizedString("Gardening", comment: "An example tag used in the login prologue screens.")
static let tagMusic: String = NSLocalizedString("Music", comment: "An example tag used in the login prologue screens.")
static let tagPolitics: String = NSLocalizedString("Politics", comment: "An example tag used in the login prologue screens.")
static let firstPostTitle: String = NSLocalizedString("My Top Ten Cafes", comment: "Example post title used in the login prologue screens.")
static let secondPostTitle: String = NSLocalizedString("The World's Best Fans", comment: "Example post title used in the login prologue screens. This is a post about football fans.")
static let thirdPostTitle: String = NSLocalizedString("Museums to See In London", comment: "Example post title used in the login prologue screens.")
}
}
// MARK: - Views
/// A view showing an icon followed by a title for an example feed.
///
private struct FeedRow: View {
let image: String
let imageSize: CGFloat
let title: String
let font: Font
private let cornerRadius: CGFloat = 4.0
var body: some View {
HStack {
Image(image)
.resizable()
.frame(width: imageSize, height: imageSize)
.cornerRadius(cornerRadius)
Text(title)
.font(font)
.bold()
Spacer()
}
}
}
/// A view modifier that applies style to a text to make it look like a tag token.
///
private struct TagItem: ViewModifier {
let font: Font
let horizontalPadding: CGFloat
let verticalPadding: CGFloat
func body(content: Content) -> some View {
content
.font(font)
.lineLimit(1)
.truncationMode(.tail)
.padding(.horizontal, horizontalPadding)
.padding(.vertical, verticalPadding)
.background(Color(UIColor(light: UIColor.muriel(color: MurielColor(name: .gray, shade: .shade0)),
dark: UIColor.muriel(color: MurielColor(name: .gray, shade: .shade70)))))
.clipShape(Capsule())
}
}
extension View {
func tagItemStyle(with font: Font, horizontalPadding: CGFloat, verticalPadding: CGFloat) -> some View {
self.modifier(TagItem(font: font, horizontalPadding: horizontalPadding, verticalPadding: verticalPadding))
}
}
/// A view showing an image with title below for an example post.
///
private struct PostView: View {
let image: String
let title: String
let size: CGFloat
let font: Font
var body: some View {
VStack(alignment: .leading) {
Image(image)
.resizable()
.aspectRatio(contentMode: .fit)
Text(title)
.lineLimit(2)
.font(font)
}
.frame(width: size)
}
}
| gpl-2.0 | 8fd3113966ef57e16b1ff4c94d3fb4c3 | 41.707207 | 190 | 0.521991 | 5.448851 | false | false | false | false |
tryswift/trySwiftData | Example/Tests/NYC-2017/TKO2017Conferences.swift | 1 | 2111 | //
// NYC2016Conferences.swift
// TrySwiftData
//
// Created by Tim Oliver on 1/28/17.
// Copyright © 2017 NatashaTheRobot. All rights reserved.
//
import Foundation
import RealmSwift
import TrySwiftData
public let tko2017Conferences: [Conference] = [
{
let trySwift = Conference()
trySwift.name = "try! Conference"
trySwift.twitter = "tryswiftconf"
trySwift.logoAssetName = "Logo.png"
trySwift.conferenceDescription = "try! Conference is an immersive community gathering about Swift Language Best Practices, Application Development in Swift, Server-Side Swift, Open Source Swift, and the Swift Community, taking place in Tokyo on March 2nd through 4th, 2017."
trySwift.conferenceDescriptionJP = "「try! Swift」はプログラミング言語Swiftに関する ミュニティ主催のカンファレンスです。ベストプラクティス、アプリケーション開発、サーバーサイドSwift、オープンソースSwiftなど、Swiftに関する技術情報とコミュニケーションを目的に2017年3月2日〜4日の3日間にわたって開催されます。 3月2日、3日はSwiftコミュニティのエキスパートに る講演、4日はハッカソンを行います。すべての講演は同時通訳されます。(日本語→英語、英語→日本語)"
trySwift.organizers.append(tko2017Organizers["natashatherobot"]!)
trySwift.organizers.append(tko2017Organizers["katsumi"]!)
trySwift.organizers.append(tko2017Organizers["kazunobu"]!)
trySwift.organizers.append(tko2017Organizers["satoshi"]!)
trySwift.organizers.append(tko2017Organizers["himi"]!)
trySwift.organizers.append(tko2017Organizers["shingo"]!)
trySwift.organizers.append(tko2017Organizers["matt"]!)
trySwift.organizers.append(tko2017Organizers["nino"]!)
trySwift.venues.append(tko2017Venues["bellesalle-shinjuku"]!)
trySwift.venues.append(tko2017Venues["bellesalle-kanda"]!)
trySwift.venues.append(tko2017Venues["christon"]!)
return trySwift
}()
]
| mit | c7962cd1407517fff61482febe974492 | 50.352941 | 282 | 0.741695 | 3.364162 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Features/LandingPage/Views/LandingPageStatsView.swift | 1 | 3211 | import Library
import Prelude
import UIKit
internal enum StatsCardLayout {
enum Card {
static let height: CGFloat = 100
}
}
final class LandingPageStatsView: UIView {
// MARK: - Properties
private let cardView: UIView = { UIView(frame: .zero) }()
private let descriptionLabel: UILabel = { UILabel(frame: .zero) }()
private let quantityLabel: UILabel = { UILabel(frame: .zero) }()
private let rootStackView: UIStackView = { UIStackView(frame: .zero) }()
private let titleLabel: UILabel = { UILabel(frame: .zero) }()
private let viewModel: LandingPageStatsViewModelType = LandingPageStatsViewModel()
public func configure(with card: LandingPageCardType) {
self.viewModel.inputs.configure(with: card)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.configureViews()
self.setupConstraints()
self.bindViewModel()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configureViews() {
_ = ([self.titleLabel, self.quantityLabel, self.descriptionLabel], self.rootStackView)
|> ksr_addArrangedSubviewsToStackView()
_ = (self.rootStackView, self.cardView)
|> ksr_addSubviewToParent()
|> ksr_constrainViewToEdgesInParent()
_ = (self.cardView, self)
|> ksr_addSubviewToParent()
|> ksr_constrainViewToMarginsInParent()
}
private func setupConstraints() {
NSLayoutConstraint.activate([
self.cardView.heightAnchor.constraint(greaterThanOrEqualToConstant: StatsCardLayout.Card.height)
])
}
override func bindViewModel() {
super.bindViewModel()
self.descriptionLabel.rac.text = self.viewModel.outputs.descriptionLabelText
self.quantityLabel.rac.hidden = self.viewModel.outputs.quantityLabelIsHidden
self.quantityLabel.rac.text = self.viewModel.outputs.quantityLabelText
self.titleLabel.rac.text = self.viewModel.outputs.titleLabelText
}
override func bindStyles() {
super.bindStyles()
_ = self.cardView
|> cardViewStyle
_ = self.descriptionLabel
|> descriptionLabelStyle
_ = self.quantityLabel
|> quantityLabelStyle
_ = self.rootStackView
|> rootStackViewStyle
_ = self.titleLabel
|> titleLabelStyle
}
}
// MARK: - Styles
private let cardViewStyle: ViewStyle = { view in
view
|> roundedStyle(cornerRadius: Styles.grid(1))
|> \.backgroundColor .~ .ksr_white
}
private let descriptionLabelStyle: LabelStyle = { label in
label
|> \.textColor .~ .ksr_support_700
|> \.font .~ UIFont.ksr_footnote()
|> \.numberOfLines .~ 0
}
private let quantityLabelStyle: LabelStyle = { label in
label
|> \.textColor .~ .ksr_trust_500
|> \.font .~ .ksr_title2()
}
private let rootStackViewStyle: StackViewStyle = { stackView in
stackView
|> verticalStackViewStyle
|> \.distribution .~ .fill
|> \.spacing .~ Styles.grid(1)
|> \.isLayoutMarginsRelativeArrangement .~ true
|> \.layoutMargins .~ .init(all: Styles.grid(3))
}
private let titleLabelStyle: LabelStyle = { label in
label
|> \.textColor .~ .ksr_support_700
|> \.font .~ UIFont.ksr_callout().bolded
|> \.numberOfLines .~ 0
}
| apache-2.0 | 4123283498bbcff3be685f388accde21 | 25.758333 | 102 | 0.686702 | 4.453537 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Features/SettingsPrivacy/Views/Cells/SettingsFollowCell.swift | 1 | 2739 | import KsApi
import Library
import Prelude
import Prelude_UIKit
import ReactiveSwift
import UIKit
internal protocol SettingsFollowCellDelegate: AnyObject {
/// Called when follow switch is switched off
func settingsFollowCellDidDisableFollowing(_ cell: SettingsFollowCell)
func settingsFollowCellDidUpdate(user: User)
}
internal final class SettingsFollowCell: UITableViewCell, ValueCell {
fileprivate let viewModel: SettingsFollowCellViewModelType = SettingsFollowCellViewModel()
internal weak var delegate: SettingsFollowCellDelegate?
@IBOutlet fileprivate var followingLabel: UILabel!
@IBOutlet fileprivate var followStackView: UIStackView!
@IBOutlet fileprivate var followingSwitch: UISwitch!
@IBOutlet fileprivate var separatorView: [UIView]!
override func awakeFromNib() {
super.awakeFromNib()
_ = self
|> \.accessibilityElements .~ [self.followingSwitch].compact()
_ = self.followingSwitch
|> \.accessibilityLabel %~ { _ in Strings.Following() }
}
internal func configureWith(value: SettingsPrivacyStaticCellValue) {
self.viewModel.inputs.configureWith(user: value.user)
_ = self.followingSwitch
|> \.accessibilityHint .~ value.cellType.description
}
internal override func bindStyles() {
super.bindStyles()
_ = self
|> baseTableViewCellStyle()
|> UITableViewCell.lens.contentView.layoutMargins %~~ { _, cell in
cell.traitCollection.isRegularRegular
? .init(topBottom: Styles.grid(2), leftRight: Styles.grid(20))
: .init(topBottom: Styles.grid(1), leftRight: Styles.grid(2))
}
_ = self.separatorView
||> settingsSeparatorStyle
_ = self.followingSwitch
|> settingsSwitchStyle
_ = self.followingLabel
|> settingsTitleLabelStyle
|> UILabel.lens.text %~ { _ in Strings.Following() }
|> UILabel.lens.numberOfLines .~ 1
}
internal override func bindViewModel() {
super.bindViewModel()
self.viewModel.outputs.updateCurrentUser
.observeForUI()
.observeValues { [weak self] user in
self?.delegate?.settingsFollowCellDidUpdate(user: user)
}
self.viewModel.outputs.showPrivacyFollowingPrompt
.observeForUI()
.observeValues { [weak self] in
guard let _self = self else { return }
self?.delegate?.settingsFollowCellDidDisableFollowing(_self)
}
self.followingSwitch.rac.on = self.viewModel.outputs.followingPrivacyOn
}
func toggleOn(animated: Bool = true) {
self.followingSwitch.setOn(true, animated: animated)
}
@IBAction func followingPrivacySwitchTapped(_ followingPrivacySwitch: UISwitch) {
self.viewModel.inputs.followTapped(on: followingPrivacySwitch.isOn)
}
}
| apache-2.0 | d1cd42565c769a69502ded6578f744ab | 29.775281 | 92 | 0.718876 | 4.882353 | false | false | false | false |
cheyongzi/MGTV-Swift | MGTV-Swift/Share/Extension/CommonExtension.swift | 1 | 1664 | //
// CommonExtension.swift
// MGTV-Swift
//
// Created by Che Yongzi on 16/6/24.
// Copyright © 2016年 Che Yongzi. All rights reserved.
//
import UIKit
let HNTVDeviceHeight = UIScreen.main.bounds.size.height
let HNTVDeviceWidth = UIScreen.main.bounds.size.width
let HNTVNavigationBarHeight = 64
let HNTVTabBarHeight = 49
func +(leftSize: CGSize, rightSize: CGSize) -> CGSize {
return CGSize(width: leftSize.width + rightSize.width, height: rightSize.height)
}
func isEmpty(data: Any?) -> Bool {
if let stringValue = data as? String {
if !stringValue.isEmpty {
return false
}
}
return true
}
extension String {
func pathExtension() -> String {
return (self as NSString).pathExtension
}
}
extension UIColor {
public convenience init(hexString: String) {
let hexString = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let scanner = Scanner(string: hexString)
if (hexString.hasPrefix("#")) {
scanner.scanLocation = 1
}
var color: UInt32 = 0
if scanner.scanHexInt32(&color) {
self.init(hex: color)
}
else {
self.init(hex: 0x000000)
}
}
public convenience init(hex: UInt32) {
let mask = 0x000000FF
let r = Int(hex >> 16) & mask
let g = Int(hex >> 8) & mask
let b = Int(hex) & mask
let red = CGFloat(r) / 255
let green = CGFloat(g) / 255
let blue = CGFloat(b) / 255
self.init(red:red, green:green, blue:blue, alpha:1)
}
}
| mit | 50cf2fbda19075f7b0012bcbf37d8255 | 23.426471 | 93 | 0.586996 | 4.00241 | false | false | false | false |
RCacheaux/OAuthKit | OAuthKit/Sources/iOS/Models/Account.swift | 3 | 544 | // Copyright © 2016 Atlassian. All rights reserved.
import Foundation
public struct Account {
public let identifier: String
public let username: String
public let displayName: String
public let avatarURL: NSURL
public let credential: Credential
public init(identifier: String, username: String, displayName: String, avatarURL: NSURL, credential: Credential) {
self.identifier = identifier
self.username = username
self.displayName = displayName
self.avatarURL = avatarURL
self.credential = credential
}
}
| apache-2.0 | 7f391e00bf276ee13803cf3306c11321 | 27.578947 | 116 | 0.74954 | 4.891892 | false | false | false | false |
apple/swift-nio | Sources/_NIODataStructures/Heap.swift | 1 | 7694 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin.C
#elseif os(Linux) || os(FreeBSD) || os(Android)
import Glibc
#elseif os(Windows)
import ucrt
#endif
@usableFromInline
internal struct Heap<Element: Comparable> {
@usableFromInline
internal private(set) var storage: Array<Element>
@inlinable
internal init() {
self.storage = []
}
@inlinable
internal func comparator(_ lhs: Element, _ rhs: Element) -> Bool {
// This heap is always a min-heap.
return lhs < rhs
}
// named `PARENT` in CLRS
@inlinable
internal func parentIndex(_ i: Int) -> Int {
return (i-1) / 2
}
// named `LEFT` in CLRS
@inlinable
internal func leftIndex(_ i: Int) -> Int {
return 2*i + 1
}
// named `RIGHT` in CLRS
@inlinable
internal func rightIndex(_ i: Int) -> Int {
return 2*i + 2
}
// named `MAX-HEAPIFY` in CLRS
/* private but */ @inlinable
mutating func _heapify(_ index: Int) {
let left = self.leftIndex(index)
let right = self.rightIndex(index)
var root: Int
if left <= (self.storage.count - 1) && self.comparator(storage[left], storage[index]) {
root = left
} else {
root = index
}
if right <= (self.storage.count - 1) && self.comparator(storage[right], storage[root]) {
root = right
}
if root != index {
self.storage.swapAt(index, root)
self._heapify(root)
}
}
// named `HEAP-INCREASE-KEY` in CRLS
/* private but */ @inlinable
mutating func _heapRootify(index: Int, key: Element) {
var index = index
if self.comparator(storage[index], key) {
fatalError("New key must be closer to the root than current key")
}
self.storage[index] = key
while index > 0 && self.comparator(self.storage[index], self.storage[self.parentIndex(index)]) {
self.storage.swapAt(index, self.parentIndex(index))
index = self.parentIndex(index)
}
}
@inlinable
internal mutating func append(_ value: Element) {
var i = self.storage.count
self.storage.append(value)
while i > 0 && self.comparator(self.storage[i], self.storage[self.parentIndex(i)]) {
self.storage.swapAt(i, self.parentIndex(i))
i = self.parentIndex(i)
}
}
@discardableResult
@inlinable
internal mutating func removeRoot() -> Element? {
return self._remove(index: 0)
}
@discardableResult
@inlinable
internal mutating func remove(value: Element) -> Bool {
if let idx = self.storage.firstIndex(of: value) {
self._remove(index: idx)
return true
} else {
return false
}
}
@inlinable
internal mutating func removeFirst(where shouldBeRemoved: (Element) throws -> Bool) rethrows {
guard self.storage.count > 0 else {
return
}
guard let index = try self.storage.firstIndex(where: shouldBeRemoved) else {
return
}
self._remove(index: index)
}
@discardableResult
/* private but */ @inlinable
mutating func _remove(index: Int) -> Element? {
guard self.storage.count > 0 else {
return nil
}
let element = self.storage[index]
if self.storage.count == 1 || self.storage[index] == self.storage[self.storage.count - 1] {
self.storage.removeLast()
} else if !self.comparator(self.storage[index], self.storage[self.storage.count - 1]) {
self._heapRootify(index: index, key: self.storage[self.storage.count - 1])
self.storage.removeLast()
} else {
self.storage[index] = self.storage[self.storage.count - 1]
self.storage.removeLast()
self._heapify(index)
}
return element
}
}
extension Heap: CustomDebugStringConvertible {
@inlinable
var debugDescription: String {
guard self.storage.count > 0 else {
return "<empty heap>"
}
let descriptions = self.storage.map { String(describing: $0) }
let maxLen: Int = descriptions.map { $0.count }.max()! // storage checked non-empty above
let paddedDescs = descriptions.map { (desc: String) -> String in
var desc = desc
while desc.count < maxLen {
if desc.count % 2 == 0 {
desc = " \(desc)"
} else {
desc = "\(desc) "
}
}
return desc
}
var all = "\n"
let spacing = String(repeating: " ", count: maxLen)
func subtreeWidths(rootIndex: Int) -> (Int, Int) {
let lcIdx = self.leftIndex(rootIndex)
let rcIdx = self.rightIndex(rootIndex)
var leftSpace = 0
var rightSpace = 0
if lcIdx < self.storage.count {
let sws = subtreeWidths(rootIndex: lcIdx)
leftSpace += sws.0 + sws.1 + maxLen
}
if rcIdx < self.storage.count {
let sws = subtreeWidths(rootIndex: rcIdx)
rightSpace += sws.0 + sws.1 + maxLen
}
return (leftSpace, rightSpace)
}
for (index, desc) in paddedDescs.enumerated() {
let (leftWidth, rightWidth) = subtreeWidths(rootIndex: index)
all += String(repeating: " ", count: leftWidth)
all += desc
all += String(repeating: " ", count: rightWidth)
func height(index: Int) -> Int {
return Int(log2(Double(index + 1)))
}
let myHeight = height(index: index)
let nextHeight = height(index: index + 1)
if myHeight != nextHeight {
all += "\n"
} else {
all += spacing
}
}
all += "\n"
return all
}
}
@usableFromInline
struct HeapIterator<Element: Comparable>: IteratorProtocol {
/* private but */ @usableFromInline
var _heap: Heap<Element>
@inlinable
init(heap: Heap<Element>) {
self._heap = heap
}
@inlinable
mutating func next() -> Element? {
return self._heap.removeRoot()
}
}
extension Heap: Sequence {
@inlinable
var startIndex: Int {
return self.storage.startIndex
}
@inlinable
var endIndex: Int {
return self.storage.endIndex
}
@inlinable
var underestimatedCount: Int {
return self.storage.count
}
@inlinable
func makeIterator() -> HeapIterator<Element> {
return HeapIterator(heap: self)
}
@inlinable
subscript(position: Int) -> Element {
return self.storage[position]
}
@inlinable
func index(after i: Int) -> Int {
return i + 1
}
@inlinable
var count: Int {
return self.storage.count
}
}
extension Heap: Sendable where Element: Sendable {}
extension HeapIterator: Sendable where Element: Sendable {}
| apache-2.0 | 3812c7a1c9323acf99c24687399e3700 | 27.708955 | 104 | 0.550039 | 4.339538 | false | false | false | false |
uphold/uphold-sdk-ios | Source/Model/Reserve.swift | 1 | 5468 | import Foundation
import PromiseKit
import SwiftClient
/// Reserve model.
open class Reserve: BaseModel {
/**
Gets the ledger.
- returns: A paginator with the array of deposits.
*/
open func getLedger() -> Paginator<Deposit> {
let request = self.adapter.buildRequest(request: ReserveService.getLedger(range: Header.buildRangeHeader(start: Paginator<Deposit>.DEFAULT_START, end: Paginator<Deposit>.DEFAULT_OFFSET - 1)))
let paginator: Paginator<Deposit> = Paginator(countClosure: { () -> Promise<Int> in
return Promise { fulfill, reject in
self.adapter.buildRequest(request: ReserveService.getLedger(range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in
guard let count = Header.getTotalNumberOfResults(headers: response.headers) else {
reject(UnexpectedResponseError(message: "Content-Type header should not be nil."))
return
}
fulfill(count)
})
}
},
elements: self.adapter.buildResponse(request: request),
hasNextPageClosure: { (currentPage) -> Promise<Bool> in
return Promise { fulfill, reject in
self.adapter.buildRequest(request: ReserveService.getLedger(range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in
guard let count = Header.getTotalNumberOfResults(headers: response.headers) else {
reject(UnexpectedResponseError(message: "Content-Type header should not be nil."))
return
}
fulfill((currentPage * Paginator<Deposit>.DEFAULT_OFFSET) < count)
})
}
},
nextPageClosure: { (range) -> Promise<[Deposit]> in
let request = self.adapter.buildRequest(request: ReserveService.getLedger(range: range))
let promise: Promise<[Deposit]> = self.adapter.buildResponse(request: request)
return promise
})
return paginator
}
/**
Gets the reserve summary of all the obligations and assets within it.
- returns: A promise with the reserve summary of all the obligations and assets within it.
*/
open func getStatistics() -> Promise<[ReserveStatistics]> {
let request = self.adapter.buildRequest(request: ReserveService.getStatistics())
return self.adapter.buildResponse(request: request)
}
/**
Gets the information of any transaction.
- parameter transactionId: The id of the transaction.
- returns: A promise with the transaction.
*/
open func getTransactionById(transactionId: String) -> Promise<Transaction> {
let request = self.adapter.buildRequest(request: ReserveService.getReserveTransactionById(transactionId: transactionId))
return self.adapter.buildResponse(request: request)
}
/**
Gets information of all the transactions from the beginning of time.
- returns: A paginator with the array of transactions.
*/
open func getTransactions() -> Paginator<Transaction> {
let request = self.adapter.buildRequest(request: ReserveService.getReserveTransactions(range: Header.buildRangeHeader(start: Paginator<Transaction>.DEFAULT_START, end: Paginator<Transaction>.DEFAULT_OFFSET - 1)))
let paginator: Paginator<Transaction> = Paginator(countClosure: { () -> Promise<Int> in
return Promise { fulfill, reject in
self.adapter.buildRequest(request: ReserveService.getReserveTransactions(range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in
guard let count = Header.getTotalNumberOfResults(headers: response.headers) else {
reject(UnexpectedResponseError(message: "Content-Type header should not be nil."))
return
}
fulfill(count)
})
}
},
elements: self.adapter.buildResponse(request: request),
hasNextPageClosure: { (currentPage) -> Promise<Bool> in
return Promise { fulfill, reject in
self.adapter.buildRequest(request: ReserveService.getReserveTransactions(range: Header.buildRangeHeader(start: 0, end: 1))).end(done: { (response: Response) -> Void in
guard let count = Header.getTotalNumberOfResults(headers: response.headers) else {
reject(UnexpectedResponseError(message: "Content-Type header should not be nil."))
return
}
fulfill((currentPage * Paginator<Transaction>.DEFAULT_OFFSET) < count)
})
}
},
nextPageClosure: { (range) -> Promise<[Transaction]> in
let request = self.adapter.buildRequest(request: ReserveService.getReserveTransactions(range: range))
let promise: Promise<[Transaction]> = self.adapter.buildResponse(request: request)
return promise
})
return paginator
}
}
| mit | 44cc7cc693fa6eec3b8dade6b20b5b6d | 43.819672 | 220 | 0.600768 | 5.397828 | false | false | false | false |
BYCHEN/BYMoyaHttpRequestDemo | BYMoyaHttpRequestDemo/RestAPIRequest.swift | 1 | 5360 | //
// RestAPIRequest.swift
// BYMoyaHttpRequestDeom
//
// Created by by_chen on 2017/6/21.
// Copyright © 2017年 BYChen. All rights reserved.
//
import Foundation
import Moya
import Alamofire
// 自行定義Response Status Code
public enum httpStatusCode: Int {
case ok = 200
case created = 201
case badRequest = 400
case unAuthorized = 401
case forbidden = 403
case timeout = 408
case internalServerError = 500
case badGateway = 502
case gatewayTimeOut = 504
}
// 創建Request類型
enum RestAPIReqeust {
// 使用ObjectId 取得單張Photo, 使用HTTP GET方式取得, Response 的資料格式為 JSON
case photo(objectId: String)
// 創建單張Photo並且使用form-data方式傳送相關訊息與圖片檔案, 使用HTTP POST方法
case createPhoto(image: Data)
// 更新單張Photo, 使用HTTP PUT方法
case putPhoto(objectId: String, title: String, description: String)
}
// 自行建立Header的參數
extension TargetType {
var header: [String: String] {
return [:]
}
var multiParts: [Moya.MultipartFormData] {
return []
}
}
extension RestAPIReqeust: TargetType {
/// The target's base `URL`.
var baseURL: URL {
return URL(string: "https://{Domain Name}/1")!
}
/// The path to be appended to `baseURL` to form the full `URL`.
var path: String {
switch self {
case .createPhoto:
return "classes/Photo"
case let .photo(objectId):
return "classes/Photo/\(objectId)"
case let .putPhoto(objectId, _, _):
return "classes/Photo/\(objectId)"
}
}
/// The HTTP method used in the request.
var method: Moya.Method {
switch self {
case .createPhoto:
return .post
case .photo:
return .get
case .putPhoto:
return .put
}
}
/// The parameters to be encoded in the request.
var parameters: [String : Any]? {
switch self {
case .createPhoto:
return nil
case .photo:
return [:]
case let .putPhoto(_, title, description):
return [
"title": title,
"description": description
]
}
}
/// The method used for parameter encoding.
var parameterEncoding: Moya.ParameterEncoding {
switch self {
case .createPhoto:
return Moya.PropertyListEncoding.default
default:
return Moya.JSONEncoding.default
}
}
var task: Task {
switch self {
case .createPhoto:
return .upload(UploadType.multipart(multiParts))
default:
return .request
}
}
/// Provides stub data for use in testing.
var sampleData: Data {
return "{}".data(using: .utf8)!
}
/// 自行定義Header要傳送的參數, 如: Content-Type
var header: [String : String] {
return [
"Content-Type" : "application/json"
]
}
/// 自行封裝form-data的格式
var multiParts: [Moya.MultipartFormData] {
switch self {
case let .createPhoto(image):
var multiparts: [Moya.MultipartFormData] = []
let m = Moya.MultipartFormData(provider: .data(image), name: "file", fileName: "test.png", mimeType: "image/png")
multiparts.append(m)
return multiparts
default:
return []
}
}
// 自行封裝Endpoint
private func endpoint() -> (RestAPIReqeust) -> Endpoint<RestAPIReqeust> {
let endpointClosure = { (target: RestAPIReqeust) -> Endpoint<RestAPIReqeust> in
// 取得預設的Endpoint
var defaultEndpoint = MoyaProvider.defaultEndpointMapping(for: target)
// 加入自行定義的Header
if !self.header.isEmpty {
defaultEndpoint = defaultEndpoint.adding(newHTTPHeaderFields: self.header)
}
return defaultEndpoint
}
return endpointClosure
}
public func execute() {
// endpointClosure: 傳入客製化的Endpoint
// plugins: 啟動debugMode 會在Console印出 verbose 跟 cURL
let provider = MoyaProvider<RestAPIReqeust>(endpointClosure: self.endpoint(),
plugins: [NetworkLoggerPlugin(verbose: true, cURL: true)])
// 執行request, 並且以background Mode執行
provider.request(self, queue: DispatchQueue.global(qos: .background), completion: {
(request) in
switch request {
case let .success(response):
if let _ = httpStatusCode(rawValue: response.statusCode) {
print("Parse Response JSON Format \(response.data)")
} else {
print("Status Code : \(response.statusCode)")
}
case let .failure(error):
print("Error Status Code : \(error.localizedDescription)")
}
})
}
}
| mit | 98ef23e29565362742cf97813e56ed79 | 25.790576 | 125 | 0.546805 | 4.576923 | false | false | false | false |
samodom/TestableUIKit | TestableUIKit/UIResponder/UIView/UITableView/UITableViewMoveRowSpy.swift | 1 | 3455 | //
// UITableViewMoveRowSpy.swift
// TestableUIKit
//
// Created by Sam Odom on 2/21/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import UIKit
import TestSwagger
import FoundationSwagger
public extension UITableView {
private static let moveRowCalledKeyString = UUIDKeyString()
private static let moveRowCalledKey =
ObjectAssociationKey(moveRowCalledKeyString)
private static let moveRowCalledReference =
SpyEvidenceReference(key: moveRowCalledKey)
private static let moveRowFromRowKeyString = UUIDKeyString()
private static let moveRowFromRowKey =
ObjectAssociationKey(moveRowFromRowKeyString)
private static let moveRowFromRowReference =
SpyEvidenceReference(key: moveRowFromRowKey)
private static let moveRowToRowKeyString = UUIDKeyString()
private static let moveRowToRowKey =
ObjectAssociationKey(moveRowToRowKeyString)
private static let moveRowToRowReference =
SpyEvidenceReference(key: moveRowToRowKey)
private static let moveRowCoselectors = SpyCoselectors(
methodType: .instance,
original: #selector(UITableView.moveRow(at:to:)),
spy: #selector(UITableView.spy_moveRow(at:to:))
)
/// Spy controller for ensuring that a table view has had `moveRow(at:to:)` called on it.
public enum MoveRowSpyController: SpyController {
public static let rootSpyableClass: AnyClass = UITableView.self
public static let vector = SpyVector.direct
public static let coselectors: Set = [moveRowCoselectors]
public static let evidence: Set = [
moveRowCalledReference,
moveRowFromRowReference,
moveRowToRowReference
]
public static let forwardsInvocations = true
}
/// Spy method that replaces the true implementation of `moveRow(at:to:)`
dynamic public func spy_moveRow(at fromRow: IndexPath, to toRow: IndexPath) {
moveRowCalled = true
moveRowFromRow = fromRow
moveRowToRow = toRow
spy_moveRow(at: fromRow, to: toRow)
}
/// Indicates whether the `moveRow(at:to:)` method has been called on this object.
public final var moveRowCalled: Bool {
get {
return loadEvidence(with: UITableView.moveRowCalledReference) as? Bool ?? false
}
set {
saveEvidence(newValue, with: UITableView.moveRowCalledReference)
}
}
/// Provides the source row passed to `moveRow(at:to:)` if called.
public final var moveRowFromRow: IndexPath? {
get {
return loadEvidence(with: UITableView.moveRowFromRowReference) as? IndexPath
}
set {
let reference = UITableView.moveRowFromRowReference
guard let row = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(row, with: reference)
}
}
/// Provides the destination row passed to `moveRow(at:to:)` if called.
public final var moveRowToRow: IndexPath? {
get {
return loadEvidence(with: UITableView.moveRowToRowReference) as? IndexPath
}
set {
let reference = UITableView.moveRowToRowReference
guard let row = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(row, with: reference)
}
}
}
| mit | 7ee161221620df1de921f2ed21bef0ff | 30.981481 | 93 | 0.663578 | 5.43937 | false | false | false | false |
nakau1/Formations | Formations/Sources/Extensions/Rswift+CellIdentifier.swift | 1 | 743 | // =============================================================================
// Formations
// Copyright 2017 yuichi.nakayasu All rights reserved.
// =============================================================================
import UIKit
import Rswift
extension ReuseIdentifierType where ReusableType: UITableViewCell {
func reuse(_ tableView: UITableView) -> ReusableType {
return tableView.dequeueReusableCell(withIdentifier: self)!
}
}
extension ReuseIdentifierType where ReusableType: UICollectionViewCell {
func reuse(_ collectionView: UICollectionView, _ indexPath: IndexPath) -> ReusableType {
return collectionView.dequeueReusableCell(withReuseIdentifier: self, for: indexPath)!
}
}
| apache-2.0 | 6c3358bac8c1bef05ddf74633aaabf34 | 36.15 | 93 | 0.589502 | 6.816514 | false | false | false | false |
jmgc/swift | benchmark/single-source/ChaCha.swift | 1 | 14403 | //===--- ChaCha.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
//
//===----------------------------------------------------------------------===//
import TestsUtils
/// This benchmark tests two things:
///
/// 1. Swift's ability to optimise low-level bit twiddling code.
/// 2. Swift's ability to optimise generic code when using contiguous data structures.
///
/// In principle initializing ChaCha20's state and then xoring the keystream with the
/// plaintext should be able to be vectorised.
enum ChaCha20 { }
extension ChaCha20 {
@inline(never)
public static func encrypt<Key: Collection, Nonce: Collection, Bytes: MutableCollection>(bytes: inout Bytes, key: Key, nonce: Nonce, initialCounter: UInt32 = 0) where Bytes.Element == UInt8, Key.Element == UInt8, Nonce.Element == UInt8 {
var baseState = ChaChaState(key: key, nonce: nonce, counter: initialCounter)
var index = bytes.startIndex
while index < bytes.endIndex {
let keyStream = baseState.block()
keyStream.xorBytes(bytes: &bytes, at: &index)
baseState.incrementCounter()
}
}
}
typealias BackingState = (UInt32, UInt32, UInt32, UInt32,
UInt32, UInt32, UInt32, UInt32,
UInt32, UInt32, UInt32, UInt32,
UInt32, UInt32, UInt32, UInt32)
struct ChaChaState {
/// The ChaCha20 algorithm has 16 32-bit integer numbers as its state.
/// They are traditionally laid out as a matrix: we do the same.
var _state: BackingState
/// Create a ChaChaState.
///
/// The inputs to ChaCha20 are:
///
/// - A 256-bit key, treated as a concatenation of eight 32-bit little-
/// endian integers.
/// - A 96-bit nonce, treated as a concatenation of three 32-bit little-
/// endian integers.
/// - A 32-bit block count parameter, treated as a 32-bit little-endian
/// integer.
init<Key: Collection, Nonce: Collection>(key: Key, nonce: Nonce, counter: UInt32) where Key.Element == UInt8, Nonce.Element == UInt8 {
guard key.count == 32 && nonce.count == 12 else {
fatalError("Invalid key or nonce length.")
}
// The ChaCha20 state is initialized as follows:
//
// - The first four words (0-3) are constants: 0x61707865, 0x3320646e,
// 0x79622d32, 0x6b206574.
self._state.0 = 0x61707865
self._state.1 = 0x3320646e
self._state.2 = 0x79622d32
self._state.3 = 0x6b206574
// - The next eight words (4-11) are taken from the 256-bit key by
// reading the bytes in little-endian order, in 4-byte chunks.
//
// We force unwrap here because we have already preconditioned on the length.
var keyIterator = CollectionOf32BitLittleEndianIntegers(key).makeIterator()
self._state.4 = keyIterator.next()!
self._state.5 = keyIterator.next()!
self._state.6 = keyIterator.next()!
self._state.7 = keyIterator.next()!
self._state.8 = keyIterator.next()!
self._state.9 = keyIterator.next()!
self._state.10 = keyIterator.next()!
self._state.11 = keyIterator.next()!
// - Word 12 is a block counter. Since each block is 64-byte, a 32-bit
// word is enough for 256 gigabytes of data.
self._state.12 = counter
// - Words 13-15 are a nonce, which should not be repeated for the same
// key. The 13th word is the first 32 bits of the input nonce taken
// as a little-endian integer, while the 15th word is the last 32
// bits.
//
// Again, we forcibly unwrap these bytes.
var nonceIterator = CollectionOf32BitLittleEndianIntegers(nonce).makeIterator()
self._state.13 = nonceIterator.next()!
self._state.14 = nonceIterator.next()!
self._state.15 = nonceIterator.next()!
}
/// As a performance enhancement, it is often useful to be able to increment the counter portion directly. This avoids the
/// expensive construction cost of the ChaCha state for each next sequence of bytes of the keystream.
mutating func incrementCounter() {
self._state.12 &+= 1
}
private mutating func add(_ otherState: ChaChaState) {
self._state.0 &+= otherState._state.0
self._state.1 &+= otherState._state.1
self._state.2 &+= otherState._state.2
self._state.3 &+= otherState._state.3
self._state.4 &+= otherState._state.4
self._state.5 &+= otherState._state.5
self._state.6 &+= otherState._state.6
self._state.7 &+= otherState._state.7
self._state.8 &+= otherState._state.8
self._state.9 &+= otherState._state.9
self._state.10 &+= otherState._state.10
self._state.11 &+= otherState._state.11
self._state.12 &+= otherState._state.12
self._state.13 &+= otherState._state.13
self._state.14 &+= otherState._state.14
self._state.15 &+= otherState._state.15
}
private mutating func columnRound() {
// The column round:
//
// 1. QUARTERROUND ( 0, 4, 8,12)
// 2. QUARTERROUND ( 1, 5, 9,13)
// 3. QUARTERROUND ( 2, 6,10,14)
// 4. QUARTERROUND ( 3, 7,11,15)
ChaChaState.quarterRound(a: &self._state.0, b: &self._state.4, c: &self._state.8, d: &self._state.12)
ChaChaState.quarterRound(a: &self._state.1, b: &self._state.5, c: &self._state.9, d: &self._state.13)
ChaChaState.quarterRound(a: &self._state.2, b: &self._state.6, c: &self._state.10, d: &self._state.14)
ChaChaState.quarterRound(a: &self._state.3, b: &self._state.7, c: &self._state.11, d: &self._state.15)
}
private mutating func diagonalRound() {
// The diagonal round:
//
// 5. QUARTERROUND ( 0, 5,10,15)
// 6. QUARTERROUND ( 1, 6,11,12)
// 7. QUARTERROUND ( 2, 7, 8,13)
// 8. QUARTERROUND ( 3, 4, 9,14)
ChaChaState.quarterRound(a: &self._state.0, b: &self._state.5, c: &self._state.10, d: &self._state.15)
ChaChaState.quarterRound(a: &self._state.1, b: &self._state.6, c: &self._state.11, d: &self._state.12)
ChaChaState.quarterRound(a: &self._state.2, b: &self._state.7, c: &self._state.8, d: &self._state.13)
ChaChaState.quarterRound(a: &self._state.3, b: &self._state.4, c: &self._state.9, d: &self._state.14)
}
}
extension ChaChaState {
static func quarterRound(a: inout UInt32, b: inout UInt32, c: inout UInt32, d: inout UInt32) {
// The ChaCha quarter round. This is almost identical to the definition from RFC 7539
// except that we use &+= instead of += because overflow modulo 32 is expected.
a &+= b; d ^= a; d <<<= 16
c &+= d; b ^= c; b <<<= 12
a &+= b; d ^= a; d <<<= 8
c &+= d; b ^= c; b <<<= 7
}
}
extension ChaChaState {
func block() -> ChaChaKeystreamBlock {
var stateCopy = self // We need this copy. This is cheaper than initializing twice.
// The ChaCha20 block runs 10 double rounds (a total of 20 rounds), made of one column and
// one diagonal round.
for _ in 0..<10 {
stateCopy.columnRound()
stateCopy.diagonalRound()
}
// We add the original input words to the output words.
stateCopy.add(self)
return ChaChaKeystreamBlock(stateCopy)
}
}
/// The result of running the ChaCha block function on a given set of ChaCha state.
///
/// This result has a distinct set of behaviours compared to the ChaChaState object, so we give it a different
/// (and more constrained) type.
struct ChaChaKeystreamBlock {
var _state: BackingState
init(_ state: ChaChaState) {
self._state = state._state
}
/// A nice thing we can do with a ChaCha keystream block is xor it with some bytes.
///
/// This helper function exists because we want a hook to do fast, in-place encryption of bytes.
func xorBytes<Bytes: MutableCollection>(bytes: inout Bytes, at index: inout Bytes.Index) where Bytes.Element == UInt8 {
// This is a naive implementation of this loop but I'm interested in testing the Swift compiler's ability
// to optimise this. If we have a programmatic way to roll up this loop I'd love to hear it!
self._state.0.xorLittleEndianBytes(bytes: &bytes, at: &index)
if index == bytes.endIndex { return }
self._state.1.xorLittleEndianBytes(bytes: &bytes, at: &index)
if index == bytes.endIndex { return }
self._state.2.xorLittleEndianBytes(bytes: &bytes, at: &index)
if index == bytes.endIndex { return }
self._state.3.xorLittleEndianBytes(bytes: &bytes, at: &index)
if index == bytes.endIndex { return }
self._state.4.xorLittleEndianBytes(bytes: &bytes, at: &index)
if index == bytes.endIndex { return }
self._state.5.xorLittleEndianBytes(bytes: &bytes, at: &index)
if index == bytes.endIndex { return }
self._state.6.xorLittleEndianBytes(bytes: &bytes, at: &index)
if index == bytes.endIndex { return }
self._state.7.xorLittleEndianBytes(bytes: &bytes, at: &index)
if index == bytes.endIndex { return }
self._state.8.xorLittleEndianBytes(bytes: &bytes, at: &index)
if index == bytes.endIndex { return }
self._state.9.xorLittleEndianBytes(bytes: &bytes, at: &index)
if index == bytes.endIndex { return }
self._state.10.xorLittleEndianBytes(bytes: &bytes, at: &index)
if index == bytes.endIndex { return }
self._state.11.xorLittleEndianBytes(bytes: &bytes, at: &index)
if index == bytes.endIndex { return }
self._state.12.xorLittleEndianBytes(bytes: &bytes, at: &index)
if index == bytes.endIndex { return }
self._state.13.xorLittleEndianBytes(bytes: &bytes, at: &index)
if index == bytes.endIndex { return }
self._state.14.xorLittleEndianBytes(bytes: &bytes, at: &index)
if index == bytes.endIndex { return }
self._state.15.xorLittleEndianBytes(bytes: &bytes, at: &index)
}
}
infix operator <<<: BitwiseShiftPrecedence
infix operator <<<=: AssignmentPrecedence
extension FixedWidthInteger {
func leftRotate(_ distance: Int) -> Self {
return (self << distance) | (self >> (Self.bitWidth - distance))
}
mutating func rotatedLeft(_ distance: Int) {
self = self.leftRotate(distance)
}
static func <<<(lhs: Self, rhs: Int) -> Self {
return lhs.leftRotate(rhs)
}
static func <<<=(lhs: inout Self, rhs: Int) {
lhs.rotatedLeft(rhs)
}
}
struct CollectionOf32BitLittleEndianIntegers<BaseCollection: Collection> where BaseCollection.Element == UInt8 {
var baseCollection: BaseCollection
init(_ baseCollection: BaseCollection) {
precondition(baseCollection.count % 4 == 0)
self.baseCollection = baseCollection
}
}
extension CollectionOf32BitLittleEndianIntegers: Collection {
typealias Element = UInt32
struct Index {
var baseIndex: BaseCollection.Index
init(_ baseIndex: BaseCollection.Index) {
self.baseIndex = baseIndex
}
}
var startIndex: Index {
return Index(self.baseCollection.startIndex)
}
var endIndex: Index {
return Index(self.baseCollection.endIndex)
}
func index(after index: Index) -> Index {
return Index(self.baseCollection.index(index.baseIndex, offsetBy: 4))
}
subscript(_ index: Index) -> UInt32 {
var baseIndex = index.baseIndex
var result = UInt32(0)
for shift in stride(from: 0, through: 24, by: 8) {
result |= UInt32(self.baseCollection[baseIndex]) << shift
self.baseCollection.formIndex(after: &baseIndex)
}
return result
}
}
extension CollectionOf32BitLittleEndianIntegers.Index: Equatable {
static func ==(lhs: Self, rhs: Self) -> Bool {
return lhs.baseIndex == rhs.baseIndex
}
}
extension CollectionOf32BitLittleEndianIntegers.Index: Comparable {
static func <(lhs: Self, rhs: Self) -> Bool {
return lhs.baseIndex < rhs.baseIndex
}
static func <=(lhs: Self, rhs: Self) -> Bool {
return lhs.baseIndex <= rhs.baseIndex
}
static func >(lhs: Self, rhs: Self) -> Bool {
return lhs.baseIndex > rhs.baseIndex
}
static func >=(lhs: Self, rhs: Self) -> Bool {
return lhs.baseIndex >= rhs.baseIndex
}
}
extension UInt32 {
/// Performs an xor operation on up to 4 bytes of the mutable collection.
func xorLittleEndianBytes<Bytes: MutableCollection>(bytes: inout Bytes, at index: inout Bytes.Index) where Bytes.Element == UInt8 {
var loopCount = 0
while index < bytes.endIndex && loopCount < 4 {
bytes[index] ^= UInt8((self >> (loopCount * 8)) & UInt32(0xFF))
bytes.formIndex(after: &index)
loopCount += 1
}
}
}
public let ChaCha = BenchmarkInfo(
name: "ChaCha",
runFunction: run_ChaCha,
tags: [.runtime, .cpubench])
@inline(never)
func checkResult(_ plaintext: [UInt8]) {
CheckResults(plaintext.first! == 6 && plaintext.last! == 254)
var hash: UInt64 = 0
for byte in plaintext {
// rotate
hash = (hash &<< 8) | (hash &>> (64 - 8))
hash ^= UInt64(byte)
}
CheckResults(hash == 0xa1bcdb217d8d14e4)
}
@inline(never)
public func run_ChaCha(_ N: Int) {
let key = Array(repeating: UInt8(1), count: 32)
let nonce = Array(repeating: UInt8(2), count: 12)
var checkedtext = Array(repeating: UInt8(0), count: 1024)
ChaCha20.encrypt(bytes: &checkedtext, key: key, nonce: nonce)
checkResult(checkedtext)
var plaintext = Array(repeating: UInt8(0), count: 30720) // Chosen for CI runtime
for _ in 1...N {
ChaCha20.encrypt(bytes: &plaintext, key: key, nonce: nonce)
blackHole(plaintext.first!)
}
}
| apache-2.0 | b89c2da128bc5ee5a95b2e43dc401119 | 37.204244 | 241 | 0.619524 | 3.97105 | false | false | false | false |
ps2/rileylink_ios | OmniKitUI/Views/NotificationSettingsView.swift | 1 | 6473 | //
// NotificationSettingsView.swift
// OmniKit
//
// Created by Pete Schwamb on 2/3/21.
// Copyright © 2021 LoopKit Authors. All rights reserved.
//
import SwiftUI
import LoopKit
import LoopKitUI
import HealthKit
struct NotificationSettingsView: View {
var dateFormatter: DateFormatter
@Binding var expirationReminderDefault: Int
@State private var showingHourPicker: Bool = false
var scheduledReminderDate: Date?
var allowedScheduledReminderDates: [Date]?
var lowReservoirReminderValue: Int
var onSaveScheduledExpirationReminder: ((_ selectedDate: Date?, _ completion: @escaping (_ error: Error?) -> Void) -> Void)?
var onSaveLowReservoirReminder: ((_ selectedValue: Int, _ completion: @escaping (_ error: Error?) -> Void) -> Void)?
var insulinQuantityFormatter = QuantityFormatter(for: .internationalUnit())
var body: some View {
RoundedCardScrollView {
RoundedCard(
title: LocalizedString("Omnipod Reminders", comment: "Title for omnipod reminders section"),
footer: LocalizedString("The app configures a reminder on the pod to notify you in advance of Pod expiration. Set the number of hours advance notice you would like to configure when pairing a new Pod.", comment: "Footer text for omnipod reminders section")
) {
ExpirationReminderPickerView(expirationReminderDefault: $expirationReminderDefault)
}
if let allowedDates = allowedScheduledReminderDates {
RoundedCard(
footer: LocalizedString("This is a reminder that you scheduled when you paired your current Pod.", comment: "Footer text for scheduled reminder area"))
{
Text("Scheduled Reminder")
Divider()
scheduledReminderRow(scheduledDate: scheduledReminderDate, allowedDates: allowedDates)
}
}
RoundedCard(footer: LocalizedString("The App notifies you when the amount of insulin in the Pod reaches this level.", comment: "Footer text for low reservoir value row")) {
lowReservoirValueRow
}
RoundedCard<EmptyView>(
title: LocalizedString("Critical Alerts", comment: "Title for critical alerts description"),
footer: LocalizedString("The reminders above will not sound if your device is in Silent or Do Not Disturb mode.\n\nThere are other critical Pod alerts and alarms that will sound even if you device is set to Silent or Do Not Disturb mode.", comment: "Description text for critical alerts")
)
}
.navigationBarTitle(LocalizedString("Notification Settings", comment: "navigation title for notification settings"))
}
@State private var scheduleReminderDateEditViewIsShown: Bool = false
private func scheduledReminderRow(scheduledDate: Date?, allowedDates: [Date]) -> some View {
Group {
if let scheduledDate = scheduledDate, scheduledDate <= Date() {
scheduledReminderRowContents(disclosure: false)
} else {
NavigationLink(
destination: ScheduledExpirationReminderEditView(
scheduledExpirationReminderDate: scheduledDate,
allowedDates: allowedDates,
dateFormatter: dateFormatter,
onSave: onSaveScheduledExpirationReminder,
onFinish: { scheduleReminderDateEditViewIsShown = false }),
isActive: $scheduleReminderDateEditViewIsShown)
{
scheduledReminderRowContents(disclosure: true)
}
}
}
}
private func scheduledReminderRowContents(disclosure: Bool) -> some View {
RoundedCardValueRow(
label: LocalizedString("Time", comment: "Label for scheduled reminder value row"),
value: scheduledReminderDateString(scheduledReminderDate),
highlightValue: false,
disclosure: disclosure
)
}
private func scheduledReminderDateString(_ scheduledDate: Date?) -> String {
if let scheduledDate = scheduledDate {
return dateFormatter.string(from: scheduledDate)
} else {
return LocalizedString("No Reminder", comment: "Value text for no expiration reminder")
}
}
@State private var lowReservoirReminderEditViewIsShown: Bool = false
var lowReservoirValueRow: some View {
NavigationLink(
destination: LowReservoirReminderEditView(
lowReservoirReminderValue: lowReservoirReminderValue,
insulinQuantityFormatter: insulinQuantityFormatter,
onSave: onSaveLowReservoirReminder,
onFinish: { lowReservoirReminderEditViewIsShown = false }),
isActive: $lowReservoirReminderEditViewIsShown)
{
RoundedCardValueRow(
label: LocalizedString("Low Reservoir Reminder", comment: "Label for low reservoir reminder row"),
value: insulinQuantityFormatter.string(from: HKQuantity(unit: .internationalUnit(), doubleValue: Double(lowReservoirReminderValue)), for: .internationalUnit()) ?? "",
highlightValue: false,
disclosure: true)
}
}
}
struct NotificationSettingsView_Previews: PreviewProvider {
static var previews: some View {
return Group {
NavigationView {
NotificationSettingsView(dateFormatter: DateFormatter(), expirationReminderDefault: .constant(2), scheduledReminderDate: Date(), allowedScheduledReminderDates: [Date()], lowReservoirReminderValue: 20)
.previewDevice(PreviewDevice(rawValue:"iPod touch (7th generation)"))
.previewDisplayName("iPod touch (7th generation)")
}
NavigationView {
NotificationSettingsView(dateFormatter: DateFormatter(), expirationReminderDefault: .constant(2), scheduledReminderDate: Date(), allowedScheduledReminderDates: [Date()], lowReservoirReminderValue: 20)
.colorScheme(.dark)
.previewDevice(PreviewDevice(rawValue: "iPhone XS Max"))
.previewDisplayName("iPhone XS Max - Dark")
}
}
}
}
| mit | fa7abdb8444afc1ae2afb493ce963d39 | 44.900709 | 304 | 0.643696 | 6.099906 | false | false | false | false |
gitizenme/SwiftKeyboardExtension | SwiftKeyboardExtension/Keyboard/KeyboardViewController.swift | 1 | 5669 | //
// KeyboardViewController.swift
// Keyboard
//
// Created by Joe Chavez on 8/10/15.
// Copyright (c) 2015 izen.me, Inc. All rights reserved.
//
import UIKit
class KeyboardViewController: UIInputViewController {
var shiftStatus: Int! // 0 = off, 1 = on, 2 = caps lock
@IBOutlet var numbersRow1View: UIView!
@IBOutlet var numbersRow2View: UIView!
@IBOutlet var symbolsRow1View: UIView!
@IBOutlet var symbolsRow2View: UIView!
@IBOutlet var numbersSymbolsRow3View: UIView!
@IBOutlet var letterButtonsArray: [UIButton]!
@IBOutlet var switchModeRow3Button: UIButton!
@IBOutlet var switchModeRow4Button: UIButton!
@IBOutlet var shiftButton: UIButton!
@IBOutlet var spaceButton: UIButton!
private var proxy: UITextDocumentProxy {
return textDocumentProxy as! UITextDocumentProxy
}
override func updateViewConstraints() {
super.updateViewConstraints()
// Add custom view sizing constraints here
}
override func viewDidLoad() {
super.viewDidLoad()
shiftStatus = 1;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated
}
@IBAction func globeKeyPressed(sender: UIButton) {
advanceToNextInputMode()
}
@IBAction func shiftKeyPressedX(sender: UITapGestureRecognizer) {
}
@IBAction func keyPressed(sender: UIButton) {
proxy.insertText(sender.titleLabel!.text!)
if(shiftStatus == 1) {
shiftKeyPressed(self.shiftButton)
}
}
@IBAction func backspaceKeyPressed(sender: UIButton) {
proxy.deleteBackward()
}
@IBAction func spaceKeyPressed(sender: UIButton)
{
proxy.insertText(" ")
}
@IBAction func shifKeyDoubleTapped(sender: UITapGestureRecognizer) {
shiftStatus = 2;
shiftKeys()
}
@IBAction func shiftKeyTripleTapped(sender: UITapGestureRecognizer) {
shiftStatus = 0
shiftKeyPressed(self.shiftButton)
}
@IBAction func spaceKeyDoubleTapped(sender: UITapGestureRecognizer) {
proxy.deleteBackward()
proxy.insertText(". ")
if(shiftStatus == 0) {
shiftKeyPressed(self.shiftButton)
}
}
@IBAction func returnKeyPressed(sender: UIButton) {
proxy.insertText("\n");
}
@IBAction func shiftKeyPressed(sender: UIButton) {
shiftStatus = shiftStatus > 0 ? 0 : 1;
shiftKeys()
}
func shiftKeys() {
if(shiftStatus == 0) {
for (letterButtonIndex, letterButton) in enumerate(letterButtonsArray) {
letterButton.setTitle(letterButton.titleLabel?.text!.lowercaseString, forState: UIControlState.Normal)
}
}
else {
for (letterButtonIndex, letterButton) in enumerate(letterButtonsArray) {
letterButton.setTitle(letterButton.titleLabel?.text!.uppercaseString, forState: UIControlState.Normal)
}
}
var shiftButtonImageName = String(format: "shift_%i.png", shiftStatus)
shiftButton.setImage(UIImage(named: shiftButtonImageName), forState: UIControlState.Normal)
var shiftButtonHLImageName = String(format: "shift_%i.png", shiftStatus)
shiftButton.setImage(UIImage(named: shiftButtonHLImageName), forState: UIControlState.Highlighted)
}
@IBAction func switchKeyboardMode(sender: UIButton) {
numbersRow1View.hidden = true;
numbersRow2View.hidden = true;
symbolsRow1View.hidden = true;
symbolsRow2View.hidden = true;
numbersSymbolsRow3View.hidden = true;
switch (sender.tag) {
case 1:
numbersRow1View.hidden = false
numbersRow2View.hidden = false
numbersSymbolsRow3View.hidden = false
switchModeRow3Button.setImage(UIImage(named: "symbols.png"), forState: UIControlState.Normal)
switchModeRow3Button.setImage(UIImage(named: "symbolsHL.png"), forState: UIControlState.Highlighted)
switchModeRow3Button.tag = 2
switchModeRow4Button.setImage(UIImage(named: "abc.png"), forState: UIControlState.Normal)
switchModeRow4Button.setImage(UIImage(named: "abcHL.png"), forState: UIControlState.Highlighted)
switchModeRow4Button.tag = 0
break;
case 2:
symbolsRow1View.hidden = false
symbolsRow2View.hidden = false
numbersSymbolsRow3View.hidden = false
switchModeRow3Button.setImage(UIImage(named: "numbers.png"), forState: UIControlState.Normal)
switchModeRow3Button.setImage(UIImage(named: "numbersHL.png"), forState: UIControlState.Highlighted)
switchModeRow3Button.tag = 1
break;
default:
switchModeRow4Button.setImage(UIImage(named: "numbers.png"), forState: UIControlState.Normal)
switchModeRow4Button.setImage(UIImage(named: "numbersHL.png"), forState: UIControlState.Highlighted)
switchModeRow4Button.tag = 1
break;
}
}
override func textWillChange(textInput: UITextInput) {
// The app is about to change the document's contents. Perform any preparation here.
}
override func textDidChange(textInput: UITextInput) {
// The app has just changed the document's contents, the document context has been updated.
}
}
| mit | eef21540ab8e5e523215ec02a2cd658d | 31.959302 | 118 | 0.641207 | 5.052585 | false | false | false | false |
dcilia/csv-export-swift | Playgrounds/CSVExporter.playground/Contents.swift | 1 | 1843 | //: Playground - noun: a place where people can play
/**
Use as a reference example
Note that you may need to add PlaygroundSupport
and indefinite execution in order to use NSFileHandle.
*/
import Cocoa
import CSVExporter
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
struct Car : CSVExporting {
var make : String
var model : String
var year : String
static func templateString() -> String {
return "Manufacturer, Model, Year\n"
}
func exportAsCommaSeparatedString() -> String {
return "\(self.make), \(self.model), \(self.year)\n"
}
func go() -> Void {
let documents = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
guard let path = documents.first else { return }
let filePath = String(NSString(string:path).appendingPathComponent("Cars.csv"))
guard let url = URL(string: filePath) else { return }
let items = [
Car(make: "BMW", model: "325", year: "1999"),
Car(make: "Toyota", model: "Rav4", year: "2003"),
Car(make: "Hyundai", model: "Elantra", year: "2011"),
Car(make: "Tesla", model: "Model 3", year: "2017")
]
let operation = CSVOperation(filePath: url, source: items)
operation.completionBlock = {
if operation.finishedState == .success {
//File has been saved to disk ...
print("Saved successfully.")
}
}
OperationQueue().addOperation(operation)
}
}
let car = Car(make: "Ford", model: "Focus", year: "1998")
car.go()
| mit | 765849155aeaae39f976f78c0c9e2814 | 26.924242 | 165 | 0.583288 | 4.81201 | false | false | false | false |
Driftt/drift-sdk-ios | Drift/Helpers/AvatarImage.swift | 2 | 3636 | //
// AvatarImage.swift
// Drift
//
// Created by Brian McDonald on 19/06/2017.
// Copyright © 2017 Drift. All rights reserved.
//
import UIKit
import AlamofireImage
class AvatarView: UIView {
var cornerRadius: CGFloat = 3{
didSet{
setUpCorners()
}
}
var imageView = UIImageView()
var initialsLabel = UILabel()
override func awakeFromNib() {
super.awakeFromNib()
imageView.isUserInteractionEnabled = true
self.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
imageView.leadingAnchor.constraint(equalTo: leadingAnchor),
imageView.topAnchor.constraint(equalTo: topAnchor),
imageView.trailingAnchor.constraint(equalTo: trailingAnchor),
imageView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
self.addSubview(initialsLabel)
imageView.contentMode = .scaleAspectFill
imageView.backgroundColor = UIColor.clear
layer.masksToBounds = true
backgroundColor = ColorPalette.subtitleTextColor
initialsLabel.isHidden = true
setUpCorners()
}
func setUpCorners(){
layer.cornerRadius = cornerRadius
}
func setUpForAvatarURL(avatarUrl: String?){
if let avatarUrl = avatarUrl{
if let url = URL(string: avatarUrl){
initialsLabel.isHidden = true
imageView.backgroundColor = UIColor.clear
imageView.isHidden = false
let placeholder = UIImage(named: "placeholderAvatar", in: Bundle.drift_getResourcesBundle(), compatibleWith: nil)
imageView.af.setImage(withURL: url, placeholderImage: nil, filter: nil, imageTransition: .crossDissolve(0.1), runImageTransitionIfCached: false, completion: { result in
self.initialsLabel.text = ""
switch result.result {
case .success(let image):
self.imageView.image = image
self.initialsLabel.isHidden = true
case .failure(_):
self.imageView.image = placeholder
}
self.imageView.layer.removeAllAnimations()
})
}
}else{
let placeholder = UIImage(named: "placeholderAvatar", in: Bundle.drift_getResourcesBundle(), compatibleWith: nil)
self.imageView.image = placeholder
}
}
func setupForBot(embed: Embed?){
imageView.image = UIImage(named: "robot", in: Bundle.drift_getResourcesBundle(), compatibleWith: nil)
if let backgroundColorString = embed?.backgroundColor {
let color = UIColor(hexString: "#\(backgroundColorString)")
imageView.backgroundColor = color
}else{
imageView.backgroundColor = ColorPalette.driftBlue
}
}
func setupForUser(user: UserDisplayable?) {
if let user = user {
if user.bot {
setupForBot(embed: DriftDataStore.sharedInstance.embed)
} else {
setUpForAvatarURL(avatarUrl: user.avatarURL)
}
} else {
let placeholder = UIImage(named: "placeholderAvatar", in: Bundle.drift_getResourcesBundle(), compatibleWith: nil)
self.imageView.image = placeholder
}
}
}
| mit | 0d82c50b4258c5215616c269b390168b | 33.619048 | 184 | 0.579642 | 5.881877 | false | false | false | false |
nathawes/swift | stdlib/public/Darwin/Foundation/Publishers+NotificationCenter.swift | 8 | 6613 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Only support 64bit
#if !(os(iOS) && (arch(i386) || arch(arm)))
@_exported import Foundation // Clang module
import Combine
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension NotificationCenter {
/// Returns a publisher that emits events when broadcasting notifications.
///
/// - Parameters:
/// - name: The name of the notification to publish.
/// - object: The object posting the named notfication. If `nil`, the publisher emits elements for any object producing a notification with the given name.
/// - Returns: A publisher that emits events when broadcasting notifications.
public func publisher(
for name: Notification.Name,
object: AnyObject? = nil
) -> NotificationCenter.Publisher {
return NotificationCenter.Publisher(center: self, name: name, object: object)
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension NotificationCenter {
/// A publisher that emits elements when broadcasting notifications.
public struct Publisher: Combine.Publisher {
public typealias Output = Notification
public typealias Failure = Never
/// The notification center this publisher uses as a source.
public let center: NotificationCenter
/// The name of notifications published by this publisher.
public let name: Notification.Name
/// The object posting the named notfication.
public let object: AnyObject?
/// Creates a publisher that emits events when broadcasting notifications.
///
/// - Parameters:
/// - center: The notification center to publish notifications for.
/// - name: The name of the notification to publish.
/// - object: The object posting the named notfication. If `nil`, the publisher emits elements for any object producing a notification with the given name.
public init(center: NotificationCenter, name: Notification.Name, object: AnyObject? = nil) {
self.center = center
self.name = name
self.object = object
}
public func receive<S: Subscriber>(subscriber: S) where S.Input == Output, S.Failure == Failure {
subscriber.receive(subscription: Notification.Subscription(center, name, object, subscriber))
}
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension NotificationCenter.Publisher: Equatable {
public static func == (
lhs: NotificationCenter.Publisher,
rhs: NotificationCenter.Publisher
) -> Bool {
return lhs.center === rhs.center
&& lhs.name == rhs.name
&& lhs.object === rhs.object
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Notification {
fileprivate final class Subscription<S: Subscriber>: Combine.Subscription, CustomStringConvertible, CustomReflectable, CustomPlaygroundDisplayConvertible
where
S.Input == Notification
{
private let lock = Lock()
// This lock can only be held for the duration of downstream callouts
private let downstreamLock = RecursiveLock()
private var demand: Subscribers.Demand // GuardedBy(lock)
private var center: NotificationCenter? // GuardedBy(lock)
private let name: Notification.Name // Stored only for debug info
private var object: AnyObject? // Stored only for debug info
private var observation: AnyObject? // GuardedBy(lock)
var description: String { return "NotificationCenter Observer" }
var customMirror: Mirror {
lock.lock()
defer { lock.unlock() }
return Mirror(self, children: [
"center": center as Any,
"name": name as Any,
"object": object as Any,
"demand": demand
])
}
var playgroundDescription: Any { return description }
init(_ center: NotificationCenter,
_ name: Notification.Name,
_ object: AnyObject?,
_ next: S)
{
self.demand = .max(0)
self.center = center
self.name = name
self.object = object
self.observation = center.addObserver(
forName: name,
object: object,
queue: nil
) { [weak self] note in
guard let self = self else { return }
self.lock.lock()
guard self.observation != nil else {
self.lock.unlock()
return
}
let demand = self.demand
if demand > 0 {
self.demand -= 1
}
self.lock.unlock()
if demand > 0 {
self.downstreamLock.lock()
let additionalDemand = next.receive(note)
self.downstreamLock.unlock()
if additionalDemand > 0 {
self.lock.lock()
self.demand += additionalDemand
self.lock.unlock()
}
} else {
// Drop it on the floor
}
}
}
deinit {
lock.cleanupLock()
downstreamLock.cleanupLock()
}
func request(_ d: Subscribers.Demand) {
lock.lock()
demand += d
lock.unlock()
}
func cancel() {
lock.lock()
guard let center = self.center,
let observation = self.observation else {
lock.unlock()
return
}
self.center = nil
self.observation = nil
self.object = nil
lock.unlock()
center.removeObserver(observation)
}
}
}
#endif /* !(os(iOS) && (arch(i386) || arch(arm))) */
| apache-2.0 | 384d32c3f4b5fc3e6f47b3b4f608629d | 35.136612 | 165 | 0.55527 | 5.130334 | false | false | false | false |
shahmishal/swift | stdlib/private/OSLog/OSLogMessage.swift | 1 | 16771 | //===----------------- OSLogMessage.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 contains data structures and helper functions that are used by
// the new OS log APIs. These are prototype implementations and should not be
// used outside of tests.
/// Formatting options supported by the logging APIs for logging integers.
/// These can be specified in the string interpolation passed to the log APIs.
/// For Example,
/// log.info("Writing to file with permissions: \(perm, format: .octal)")
///
/// See `OSLogInterpolation.appendInterpolation` definitions for default options
/// for integer types.
public enum IntFormat {
case decimal
case hex
case octal
}
/// Privacy qualifiers for indicating the privacy level of the logged data
/// to the logging system. These can be specified in the string interpolation
/// passed to the log APIs.
/// For Example,
/// log.info("Login request from user id \(userid, privacy: .private)")
///
/// See `OSLogInterpolation.appendInterpolation` definitions for default options
/// for each supported type.
public enum Privacy {
case `private`
case `public`
}
/// Maximum number of arguments i.e., interpolated expressions that can
/// be used in the string interpolations passed to the log APIs.
/// This limit is imposed by the ABI of os_log.
@_transparent
public var maxOSLogArgumentCount: UInt8 { return 48 }
@usableFromInline
@_transparent
internal var logBitsPerByte: Int { return 3 }
/// Represents a string interpolation passed to the log APIs.
///
/// This type converts (through its methods) the given string interpolation into
/// a C-style format string and a sequence of arguments, which is represented
/// by the type `OSLogArguments`.
///
/// Do not create an instance of this type directly. It is used by the compiler
/// when you pass a string interpolation to the log APIs.
/// Extend this type with more `appendInterpolation` overloads to enable
/// interpolating additional types.
@frozen
public struct OSLogInterpolation : StringInterpolationProtocol {
/// A format string constructed from the given string interpolation to be
/// passed to the os_log ABI.
@usableFromInline
internal var formatString: String
/// A representation of a sequence of arguments that must be serialized
/// to a byte buffer and passed to the os_log ABI. Each argument, which is
/// an (autoclosured) expressions that is interpolated, is prepended with a
/// two byte header. The first header byte consists of a four bit flag and
/// a four bit type. The second header byte has the size of the argument in
/// bytes. This is schematically illustrated below.
/// ----------------------------
/// | 4-bit type | 4-bit flag |
/// ----------------------------
/// | 1st argument size in bytes|
/// ----------------------------
/// | 1st argument bytes |
/// ----------------------------
/// | 4-bit type | 4-bit flag |
/// -----------------------------
/// | 2nd argument size in bytes|
/// ----------------------------
/// | 2nd argument bytes |
/// ----------------------------
/// ...
@usableFromInline
internal var arguments: OSLogArguments
/// The possible values for the argument flag, as defined by the os_log ABI,
/// which occupies four least significant bits of the first byte of the
/// argument header. The first two bits are used to indicate privacy and
/// the other two are reserved.
@usableFromInline
@_frozen
internal enum ArgumentFlag {
case privateFlag
case publicFlag
@inlinable
internal var rawValue: UInt8 {
switch self {
case .privateFlag:
return 0x1
case .publicFlag:
return 0x2
}
}
}
/// The possible values for the argument type, as defined by the os_log ABI,
/// which occupies four most significant bits of the first byte of the
/// argument header.
@usableFromInline
@_frozen
internal enum ArgumentType {
case scalar
// TODO: more types will be added here.
@inlinable
internal var rawValue: UInt8 {
switch self {
case .scalar:
return 0
}
}
}
/// The first summary byte in the byte buffer passed to the os_log ABI that
/// summarizes the privacy and nature of the arguments.
@usableFromInline
internal var preamble: UInt8
/// Bit mask for setting bits in the peamble. The bits denoted by the bit
/// mask indicate whether there is an argument that is private, and whether
/// there is an argument that is non-scalar: String, NSObject or Pointer.
@usableFromInline
@_frozen
internal enum PreambleBitMask {
case privateBitMask
case nonScalarBitMask
@inlinable
internal var rawValue: UInt8 {
switch self {
case .privateBitMask:
return 0x1
case .nonScalarBitMask:
return 0x2
}
}
}
/// The second summary byte that denotes the number of arguments, which is
/// also the number of interpolated expressions. This will be determined
/// on the fly in order to support concatenation and interpolation of
/// instances of `OSLogMessage`.
@usableFromInline
internal var argumentCount: UInt8
/// Sum total of all the bytes (including header bytes) needed for
/// serializing the arguments.
@usableFromInline
internal var totalBytesForSerializingArguments: Int
// Some methods defined below are marked @_optimize(none) to prevent inlining
// of string internals (such as String._StringGuts) which will interfere with
// constant evaluation and folding. Note that these methods will be inlined,
// constant evaluated/folded and optimized in the context of a caller.
@_transparent
@_optimize(none)
public init(literalCapacity: Int, interpolationCount: Int) {
// Since the format string is fully constructed at compile time,
// the parameter `literalCapacity` is ignored.
formatString = ""
arguments = OSLogArguments(capacity: interpolationCount)
preamble = 0
argumentCount = 0
totalBytesForSerializingArguments = 0
}
/// An internal initializer that should be used only when there are no
/// interpolated expressions. This function must be constant evaluable.
@inlinable
@_semantics("oslog.interpolation.init")
@_optimize(none)
internal init() {
formatString = ""
arguments = OSLogArguments()
preamble = 0
argumentCount = 0
totalBytesForSerializingArguments = 0
}
@_transparent
@_optimize(none)
public mutating func appendLiteral(_ literal: String) {
formatString += literal.percentEscapedString
}
/// Define interpolation for expressions of type Int. This definition enables
/// passing a formatting option and a privacy qualifier along with the
/// interpolated expression as shown below:
///
/// "\(x, format: .hex, privacy: .private\)"
///
/// - Parameters:
/// - number: the interpolated expression of type Int, which is autoclosured.
/// - format: a formatting option available for Int types, defined by the
/// enum `IntFormat`.
/// - privacy: a privacy qualifier which is either private or public.
/// The default is public.
@_transparent
@_optimize(none)
public mutating func appendInterpolation(
_ number: @autoclosure @escaping () -> Int,
format: IntFormat = .decimal,
privacy: Privacy = .public
) {
guard argumentCount < maxOSLogArgumentCount else { return }
addIntHeadersAndFormatSpecifier(
format,
isPrivate: isPrivate(privacy),
bitWidth: Int.bitWidth,
isSigned: true)
arguments.append(number)
argumentCount += 1
}
/// Construct/update format string and headers from the parameters of the
/// interpolation.
@_transparent
@_optimize(none)
public mutating func addIntHeadersAndFormatSpecifier(
_ format: IntFormat,
isPrivate: Bool,
bitWidth: Int,
isSigned: Bool
) {
formatString += getIntegerFormatSpecifier(
format,
isPrivate: isPrivate,
bitWidth: bitWidth,
isSigned: isSigned)
// Append argument header.
let argumentHeader =
getArgumentHeader(isPrivate: isPrivate, bitWidth: bitWidth, type: .scalar)
arguments.append(argumentHeader)
// Append number of bytes needed to serialize the argument.
let argumentByteCount = OSLogSerializationInfo.sizeForEncoding(Int.self)
arguments.append(UInt8(argumentByteCount))
// 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 += argumentByteCount + 2
preamble = getUpdatedPreamble(isPrivate: isPrivate)
}
/// Return true if and only if the parameter is .private.
/// This function must be constant evaluable.
@inlinable
@_semantics("oslog.interpolation.isPrivate")
@_effects(readonly)
@_optimize(none)
internal func isPrivate(_ privacy: Privacy) -> Bool {
// Do not use equality comparisons on enums as it is not supported by
// the constant evaluator.
if case .private = privacy {
return true
}
return false
}
/// compute a byte-sized argument header consisting of flag and type.
/// Flag and type take up the least and most significant four bits
/// of the header byte, respectively.
/// This function should be constant evaluable.
@inlinable
@_semantics("oslog.interpolation.getArgumentHeader")
@_effects(readonly)
@_optimize(none)
internal func getArgumentHeader(
isPrivate: Bool,
bitWidth: Int,
type: ArgumentType
) -> UInt8 {
let flag: ArgumentFlag = isPrivate ? .privateFlag : .publicFlag
let flagAndType: UInt8 = (type.rawValue &<< 4) | flag.rawValue
return flagAndType
}
/// Compute the new preamble based whether the current argument is private
/// or not. This function must be constant evaluable.
@inlinable
@_semantics("oslog.interpolation.getUpdatedPreamble")
@_effects(readonly)
@_optimize(none)
internal func getUpdatedPreamble(isPrivate: Bool) -> UInt8 {
if isPrivate {
return preamble | PreambleBitMask.privateBitMask.rawValue
}
return preamble
}
/// 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("oslog.interpolation.getFormatSpecifier")
@_effects(readonly)
@_optimize(none)
internal func getIntegerFormatSpecifier(
_ format: IntFormat,
isPrivate: Bool,
bitWidth: Int,
isSigned: Bool
) -> String {
var formatSpecifier: String = isPrivate ? "%{private}" : "%{public}"
// Add a length modifier, if needed, to the specifier
// TODO: more length modifiers will be added.
if (bitWidth == CLongLong.bitWidth) {
formatSpecifier += "ll"
}
// TODO: more format specifiers will be added.
switch (format) {
case .hex:
formatSpecifier += "x"
case .octal:
formatSpecifier += "o"
default:
formatSpecifier += isSigned ? "d" : "u"
}
return formatSpecifier
}
}
extension String {
/// Replace all percents "%" in the string by "%%" so that the string can be
/// interpreted as a C format string.
public var percentEscapedString: String {
@_semantics("string.escapePercent.get")
@_effects(readonly)
@_optimize(none)
get {
return self
.split(separator: "%", omittingEmptySubsequences: false)
.joined(separator: "%%")
}
}
}
@frozen
public struct OSLogMessage :
ExpressibleByStringInterpolation, ExpressibleByStringLiteral
{
public let interpolation: OSLogInterpolation
/// Initializer for accepting string interpolations. This function must be
/// constant evaluable.
@inlinable
@_optimize(none)
@_semantics("oslog.message.init_interpolation")
public init(stringInterpolation: OSLogInterpolation) {
self.interpolation = stringInterpolation
}
/// Initializer for accepting string literals. This function must be
/// constant evaluable.
@inlinable
@_optimize(none)
@_semantics("oslog.message.init_stringliteral")
public init(stringLiteral value: String) {
var s = OSLogInterpolation()
s.appendLiteral(value)
self.interpolation = s
}
/// The byte size of the buffer that will be passed to the C os_log ABI.
/// It will contain the elements of `interpolation.arguments` and the two
/// summary bytes: preamble and argument count.
@_transparent
@_optimize(none)
public var bufferSize: Int {
return interpolation.totalBytesForSerializingArguments + 2
}
}
/// A representation of a sequence of arguments and headers (of possibly
/// different types) that have to be serialized to a byte buffer. The arguments
/// are captured within closures and stored in an array. The closures accept an
/// instance of `OSLogByteBufferBuilder`, and when invoked, serialize the
/// argument using the passed `OSLogByteBufferBuilder` instance.
@frozen
@usableFromInline
internal struct OSLogArguments {
/// An array of closures that captures arguments of possibly different types.
@usableFromInline
internal var argumentClosures: [(inout OSLogByteBufferBuilder) -> ()]?
/// This function must be constant evaluable.
@inlinable
@_semantics("oslog.arguments.init_empty")
@_optimize(none)
internal init() {
argumentClosures = nil
}
@usableFromInline
internal init(capacity: Int) {
argumentClosures = []
argumentClosures!.reserveCapacity(capacity)
}
/// Append a byte-sized header, constructed by
/// `OSLogMessage.appendInterpolation`, to the tracked array of closures.
@usableFromInline
internal mutating func append(_ header: UInt8) {
argumentClosures!.append({ $0.serialize(header) })
}
/// Append an (autoclosured) interpolated expression of type Int, passed to
/// `OSLogMessage.appendInterpolation`, to the tracked array of closures.
@usableFromInline
internal mutating func append(_ value: @escaping () -> Int) {
argumentClosures!.append({ $0.serialize(value()) })
}
@usableFromInline
internal func serialize(into bufferBuilder: inout OSLogByteBufferBuilder) {
argumentClosures?.forEach { $0(&bufferBuilder) }
}
}
/// A struct that provides information regarding the serialization of types
/// to a byte buffer as specified by the C os_log ABIs.
@usableFromInline
internal struct OSLogSerializationInfo {
/// Return the number of bytes needed for serializing an UInt8 value.
@usableFromInline
@_transparent
internal static func sizeForEncoding(_ type: UInt8.Type) -> Int {
return 1
}
/// Return the number of bytes needed for serializing an Int value.
@usableFromInline
@_transparent
internal static func sizeForEncoding(_ type: Int.Type) -> Int {
return Int.bitWidth &>> logBitsPerByte
}
}
/// A struct that manages serialization of instances of specific types to a
/// byte buffer. The byte buffer is provided as an argument to the initializer
/// so that its lifetime can be managed by the caller.
@usableFromInline
internal struct OSLogByteBufferBuilder {
internal var position: UnsafeMutablePointer<UInt8>
/// Initializer that accepts a pointer to a preexisting buffer.
/// - Parameter bufferStart: the starting pointer to a byte buffer
/// that must contain the serialized bytes.
@usableFromInline
internal init(_ bufferStart: UnsafeMutablePointer<UInt8>) {
position = bufferStart
}
/// Serialize a UInt8 value at the buffer location pointed to by `position`.
@usableFromInline
internal mutating func serialize(_ value: UInt8) {
position[0] = value
position += 1
}
/// Serialize an Int at the buffer location pointed to by `position`.
@usableFromInline
internal mutating func serialize(_ value: Int) {
let byteCount = OSLogSerializationInfo.sizeForEncoding(Int.self)
let dest = UnsafeMutableRawBufferPointer(start: position, count: byteCount)
withUnsafeBytes(of: value) { dest.copyMemory(from: $0) }
position += byteCount
}
}
| apache-2.0 | 109f16d8a1e57b4a77677e18768f5c89 | 32.880808 | 80 | 0.685469 | 4.779424 | false | false | false | false |
apple/swift-format | Tests/SwiftFormatPrettyPrintTests/BinaryOperatorExprTests.swift | 1 | 3922 | final class BinaryOperatorExprTests: PrettyPrintTestCase {
func testNonRangeFormationOperatorsAreSurroundedByBreaks() {
let input =
"""
x=1+8-9 ^*^ 5*4/10
"""
let expected80 =
"""
x = 1 + 8 - 9 ^*^ 5 * 4 / 10
"""
assertPrettyPrintEqual(input: input, expected: expected80, linelength: 80)
let expected10 =
"""
x =
1 + 8
- 9
^*^ 5
* 4 / 10
"""
assertPrettyPrintEqual(input: input, expected: expected10, linelength: 10)
}
func testRangeFormationOperatorsAreCompactedWhenPossible() {
let input =
"""
x = 1...100
x = 1..<100
x = (1++)...(-100)
x = 1 ... 100
x = 1 ..< 100
x = (1++) ... (-100)
"""
let expected =
"""
x = 1...100
x = 1..<100
x = (1++)...(-100)
x = 1...100
x = 1..<100
x = (1++)...(-100)
"""
assertPrettyPrintEqual(input: input, expected: expected, linelength: 80)
}
func testRangeFormationOperatorsAreNotCompactedWhenFollowingAPostfixOperator() {
let input =
"""
x = 1++ ... 100
x = 1-- ..< 100
x = 1++ ... 100
x = 1-- ..< 100
"""
let expected80 =
"""
x = 1++ ... 100
x = 1-- ..< 100
x = 1++ ... 100
x = 1-- ..< 100
"""
assertPrettyPrintEqual(input: input, expected: expected80, linelength: 80)
let expected10 =
"""
x =
1++
... 100
x =
1--
..< 100
x =
1++
... 100
x =
1--
..< 100
"""
assertPrettyPrintEqual(input: input, expected: expected10, linelength: 10)
}
func testRangeFormationOperatorsAreNotCompactedWhenPrecedingAPrefixOperator() {
let input =
"""
x = 1 ... -100
x = 1 ..< -100
x = 1 ... √100
x = 1 ..< √100
"""
let expected80 =
"""
x = 1 ... -100
x = 1 ..< -100
x = 1 ... √100
x = 1 ..< √100
"""
assertPrettyPrintEqual(input: input, expected: expected80, linelength: 80)
let expected10 =
"""
x =
1
... -100
x =
1
..< -100
x =
1
... √100
x =
1
..< √100
"""
assertPrettyPrintEqual(input: input, expected: expected10, linelength: 10)
}
func testRangeFormationOperatorsAreNotCompactedWhenUnaryOperatorsAreOnEachSide() {
let input =
"""
x = 1++ ... -100
x = 1-- ..< -100
x = 1++ ... √100
x = 1-- ..< √100
"""
let expected80 =
"""
x = 1++ ... -100
x = 1-- ..< -100
x = 1++ ... √100
x = 1-- ..< √100
"""
assertPrettyPrintEqual(input: input, expected: expected80, linelength: 80)
let expected10 =
"""
x =
1++
... -100
x =
1--
..< -100
x =
1++
... √100
x =
1--
..< √100
"""
assertPrettyPrintEqual(input: input, expected: expected10, linelength: 10)
}
func testRangeFormationOperatorsAreNotCompactedWhenPrecedingPrefixDot() {
let input =
"""
x = .first ... .last
x = .first ..< .last
x = .first ... .last
x = .first ..< .last
"""
let expected80 =
"""
x = .first ... .last
x = .first ..< .last
x = .first ... .last
x = .first ..< .last
"""
assertPrettyPrintEqual(input: input, expected: expected80, linelength: 80)
let expected10 =
"""
x =
.first
... .last
x =
.first
..< .last
x =
.first
... .last
x =
.first
..< .last
"""
assertPrettyPrintEqual(input: input, expected: expected10, linelength: 10)
}
}
| apache-2.0 | f645b956dc651a433738cb7ca580b377 | 17.300469 | 84 | 0.43843 | 4.039378 | false | false | false | false |
ParadropLabs/riffle-swift | Example/Tests/Tests.swift | 1 | 1874 | import UIKit
import XCTest
import Riffle
// Static testing methods
func add(a: Int, b: Int) -> Int {
return a + b
}
func nothing() {
}
func echo(a: String) -> String {
return a
}
class Dog: RiffleModel {
var name: String?
// Cant implement an init! Not sure why.
}
// Cuminication tests. Ensure the cuminicated functions are able to receive the parameters they expect
class CuminTests: XCTestCase {
func testString() {
let c = cumin(echo)
XCTAssertEqual(c(["a"]), "a")
}
func testNSString() {
let c = cumin(echo)
let oldString = NSString(string: "a")
XCTAssertEqual(c([oldString]), "a")
}
}
// Tests for the converter functions and related functionality
// The name of the testing function describes what we're converting from
//NOTE: These may not work as expected given that the equality may not be checking the classes
//class IntConverterTests: XCTestCase {
// func testInt() {
// let x: Int = 1
// let y = 1
// XCTAssertEqual(x, convert(y, Int.self))
// }
//
// func testNumber() {
// let x: Int = 1
// let y = NSNumber(integer: 1)
// XCTAssertEqual(x, convert(y, Int.self))
// }
//}
//
//
//class StringConverterTests: XCTestCase {
// func testString() {
// let x: String = "hello"
// let y = "hello"
// XCTAssertEqual(x, convert(y, String.self))
// }
//
// func testNSString() {
// let x: String = "hello"
// let y = NSString(string: "hello")
// XCTAssertEqual(x, convert(y, String.self))
// }
//}
//
//class ObjectConverterTests: XCTestCase {
// func testSerialization() {
// let json: [NSObject: AnyObject] = ["name": "Fido"]
// let result = convert(json, Dog.self)!
//
// XCTAssertEqual(result.name, "Fido")
// }
//} | mit | d399c78a2bff14fbbcd06d9475d226cb | 22.4375 | 102 | 0.584312 | 3.624758 | false | true | false | false |
Masteryyz/CSYMicroBlog_TestSina | CSSinaMicroBlog_Test/CSSinaMicroBlog_Test/Class/Module(窗体界面)/Home(主界面)/HomeTableViewController.swift | 1 | 3373 | //
// HomeTableViewController.swift
// CSSinaMicroBlog_Test
//
// Created by 姚彦兆 on 15/11/11.
// Copyright © 2015年 姚彦兆. All rights reserved.
//
import UIKit
class HomeTableViewController: CSYBasicTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
visitorView?.setItems(nil, tipsInfo: "关注一些人,然后回这里看看有什么惊喜")
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 507042a65f8321d27970c7669a7c5453 | 33.268041 | 157 | 0.68562 | 5.54 | false | false | false | false |
cornerAnt/PilesSugar | PilesSugar/PilesSugar/Module/Home/HomeAttention/Controller/HomeAttentionController.swift | 1 | 4305 | //
// HomeAttentionController.swift
// PilesSugar
//
// Created by SoloKM on 16/1/12.
// Copyright © 2016年 SoloKM. All rights reserved.
//
import UIKit
private let HomeHotCellID = "HomeHotCell"
class HomeAttentionController: UICollectionViewController {
var models = [HomeHotModel]()
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
}
init() {
let layout = WaterfallLayout()
super.init(collectionViewLayout: layout)
layout.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupCollectionView() {
collectionView!.backgroundColor = UIColor.groupTableViewBackgroundColor()
collectionView!.contentInset.top = kNavgationBarH
registerCellWithID(HomeHotCellID)
collectionView!.mj_header = RefreshHeader.init(refreshingBlock: { () -> Void in
self.loadNewData()
})
collectionView!.mj_header.beginRefreshing()
collectionView!.mj_footer = RefreshFooter.init(refreshingBlock: { () -> Void in
self.loadMoreData()
})
}
private func loadNewData(){
let urlString = "http://www.duitang.com/napi/index/hot/?app_code=gandalf&app_version=5.8%20rv%3A149591&device_name=Unknown%20iPhone&device_platform=iPhone6%2C1&include_fields=sender%2Cfavroite_count%2Calbum%2Cicon_url%2Creply_count%2Clike_count&limit=0&locale=zh_CN&platform_name=iPhone%20OS&platform_version=9.2.1&screen_height=568&screen_width=320&start=0"
NetWorkTool.sharedInstance.get(urlString, parameters: nil, success: { (response) -> () in
self.models = HomeHotModel.loadHomeModels(response!)
self.collectionView!.reloadData()
self.collectionView!.mj_header.endRefreshing()
}) { (error) -> () in
self.collectionView!.mj_header.endRefreshing()
DEBUGLOG(error)
}
}
private func loadMoreData(){
let urlString = "http://www.duitang.com/napi/index/hot/?__dtac=%257B%2522_r%2522%253A%2520%2522538800%2522%257D&app_code=gandalf&app_version=5.9%20rv%3A150681&device_name=Unknown%20iPhone&device_platform=iPhone6%2C1&include_fields=sender%2Cfavroite_count%2Calbum%2Cicon_url%2Creply_count%2Clike_count&limit=0&locale=zh_CN&platform_name=iPhone%20OS&platform_version=9.2.1&screen_height=568&screen_width=320&start=0"
NetWorkTool.sharedInstance.get(urlString, parameters: nil, success: { (response) -> () in
self.models += HomeHotModel.loadHomeModels(response!)
self.collectionView!.reloadData()
self.collectionView!.mj_footer.endRefreshing()
}) { (error) -> () in
self.collectionView!.mj_footer.endRefreshing()
DEBUGLOG(error)
}
}
}
extension HomeAttentionController {
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return models.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HomeHotCellID, forIndexPath: indexPath) as! HomeHotCell
cell.homeHotModel = models[indexPath.row]
return cell
}
}
extension HomeAttentionController: WaterfallLayoutDetegate {
func waterfallLayout(waterfallLayout: WaterfallLayout, heightForRowAtIndexPath indexPath: NSIndexPath, columnWidth: CGFloat) -> CGFloat {
let model = models[indexPath.row]
model.columnWidth = columnWidth
return model.modelHeight!
}
func columnCountInWaterflowLayout(waterfallLayout: WaterfallLayout) -> Int {
return 2
}
}
| apache-2.0 | 901e2f6e77151db3d2ef7251b37e99e0 | 29.295775 | 422 | 0.616225 | 4.691385 | false | false | false | false |
finder39/resumod | Resumod/ViewController.swift | 1 | 3389 | //
// ViewController.swift
// Resumod
//
// Created by Joseph Neuman on 7/16/14.
// Copyright (c) 2014 Joseph Neuman. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var labelName: UILabel!
@IBOutlet weak var labelLocation: UILabel!
@IBOutlet weak var textSummary: UITextView!
@IBOutlet weak var textSummaryHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var textBioInfo: UITextView!
@IBOutlet weak var textBioInfoHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var imageGravatar: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
navigationController.navigationBar.barTintColor = CONSTANTS().color1
// selectable has to be true in storyboard or accessing font (and thus font size) will crash it
for theView in self.view.subviews {
if theView is UITextView {
(theView as UITextView).selectable = false
}
}
DataManager.sharedInstance.getResume(user_id: 1,
onSuccess: {resume -> Void in
dispatch_async(dispatch_get_main_queue(), {
self.labelName.text = "\(resume.bio.firstName) \(resume.bio.lastName)"
// setup and display location
var location = ""
if let locationCity = resume.bio.location["city"] {
location = locationCity
}
if let locationState = resume.bio.location["state"] {
location += ", \(locationState)"
}
self.labelLocation.text = location
// setup and display bio info
var bioInfo = NSMutableAttributedString()
for (key, value) in resume.bio.email {
if !value.isEmpty {
var email = NSMutableAttributedString(string: "Email: \(value)")
email.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(self.textBioInfo.font.pointSize), range: NSMakeRange(0, 6))
bioInfo.appendAttributedString(email)
}
}
for (key, value) in resume.bio.profiles {
if !value.isEmpty {
var profile = NSMutableAttributedString(string: "\n\(key): \(value)")
profile.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(self.textBioInfo.font.pointSize), range: NSMakeRange(1, key.utf16Count+1))
bioInfo.appendAttributedString(profile)
}
}
self.textBioInfo.attributedText = bioInfo
self.textBioInfoHeightConstraint.constant = ceil(self.textBioInfo.sizeThatFits(CGSizeMake(self.textBioInfo.frame.size.width, CGFloat.max)).height)
self.textSummary.text = resume.bio.summary
self.textSummaryHeightConstraint.constant = ceil(self.textSummary.sizeThatFits(CGSizeMake(self.textSummary.frame.size.width, CGFloat.max)).height)
// get image
let imageURL = "https://secure.gravatar.com/avatar/" + resume.bio.email["work"]!.lowercaseString.md5() + "?s=256&d=mm"
DataManager.sharedInstance.setImageView(self.imageGravatar, withURL: imageURL)
})
}
)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
} | mit | 119f969e2c88e0a591fb9c3666975863 | 39.843373 | 165 | 0.653585 | 4.81392 | false | false | false | false |
vector-im/riot-ios | Riot/Modules/Room/ReactionHistory/ReactionHistoryViewController.swift | 2 | 7031 | // File created from ScreenTemplate
// $ createScreen.sh ReactionHistory ReactionHistory
/*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
final class ReactionHistoryViewController: UIViewController {
// MARK: - Constants
private enum TableView {
static let estimatedRowHeight: CGFloat = 21.0
static let contentInset = UIEdgeInsets(top: 10.0, left: 0.0, bottom: 10.0, right: 0.0)
}
// MARK: - Properties
// MARK: Outlets
@IBOutlet private weak var tableView: UITableView!
// MARK: Private
private var viewModel: ReactionHistoryViewModelType!
private var theme: Theme!
private var errorPresenter: MXKErrorPresentation!
private var activityPresenter: ActivityIndicatorPresenter!
private var isViewAppearedOnce: Bool = false
private var reactionHistoryViewDataList: [ReactionHistoryViewData] = []
// MARK: - Setup
class func instantiate(with viewModel: ReactionHistoryViewModelType) -> ReactionHistoryViewController {
let viewController = StoryboardScene.ReactionHistoryViewController.initialScene.instantiate()
viewController.viewModel = viewModel
viewController.theme = ThemeService.shared().theme
return viewController
}
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = VectorL10n.reactionHistoryTitle
self.viewModel.viewDelegate = self
self.activityPresenter = ActivityIndicatorPresenter()
self.errorPresenter = MXKErrorAlertPresentation()
self.setupViews()
self.registerThemeServiceDidChangeThemeNotification()
self.update(theme: self.theme)
self.viewModel.process(viewAction: .loadMore)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if self.isViewAppearedOnce == false {
self.isViewAppearedOnce = true
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return self.theme.statusBarStyle
}
// MARK: - Private
private func update(theme: Theme) {
self.theme = theme
self.view.backgroundColor = theme.headerBackgroundColor
self.tableView.backgroundColor = theme.backgroundColor
if let navigationBar = self.navigationController?.navigationBar {
theme.applyStyle(onNavigationBar: navigationBar)
}
}
private func registerThemeServiceDidChangeThemeNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil)
}
@objc private func themeDidChange() {
self.update(theme: ThemeService.shared().theme)
}
private func setupTableView() {
self.tableView.contentInset = TableView.contentInset
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.estimatedRowHeight = TableView.estimatedRowHeight
self.tableView.register(cellType: ReactionHistoryViewCell.self)
self.tableView.tableFooterView = UIView()
}
private func setupViews() {
let closeBarButtonItem = MXKBarButtonItem(title: VectorL10n.close, style: .plain) { [weak self] in
self?.closeButtonAction()
}
self.navigationItem.rightBarButtonItem = closeBarButtonItem
self.setupTableView()
}
private func render(viewState: ReactionHistoryViewState) {
switch viewState {
case .loading:
self.renderLoading()
case .loaded(reactionHistoryViewDataList: let reactionHistoryViewDataList, allDataLoaded: let allDataLoaded):
self.renderLoaded(reactionHistoryViewDataList: reactionHistoryViewDataList, allDataLoaded: allDataLoaded)
case .error(let error):
self.render(error: error)
}
}
private func renderLoading() {
self.activityPresenter.presentActivityIndicator(on: self.view, animated: true)
}
private func renderLoaded(reactionHistoryViewDataList: [ReactionHistoryViewData], allDataLoaded: Bool) {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
self.reactionHistoryViewDataList = reactionHistoryViewDataList
self.tableView.reloadData()
}
private func render(error: Error) {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil)
}
// MARK: - Actions
private func closeButtonAction() {
self.viewModel.process(viewAction: .close)
}
}
// MARK: - UITableViewDataSource
extension ReactionHistoryViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.reactionHistoryViewDataList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let reactionHistoryCell = tableView.dequeueReusableCell(for: indexPath, cellType: ReactionHistoryViewCell.self)
let reactionHistoryViewData = self.reactionHistoryViewDataList[indexPath.row]
reactionHistoryCell.update(theme: self.theme)
reactionHistoryCell.fill(with: reactionHistoryViewData)
return reactionHistoryCell
}
}
// MARK: - UITableViewDelegate
extension ReactionHistoryViewController: UITableViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard self.isViewAppearedOnce else {
return
}
// Check if a scroll beyond scroll view content occurs
let distanceFromBottom = scrollView.contentSize.height - scrollView.contentOffset.y
if distanceFromBottom < scrollView.frame.size.height {
self.viewModel.process(viewAction: .loadMore)
}
}
}
// MARK: - ReactionHistoryViewModelViewDelegate
extension ReactionHistoryViewController: ReactionHistoryViewModelViewDelegate {
func reactionHistoryViewModel(_ viewModel: ReactionHistoryViewModelType, didUpdateViewState viewSate: ReactionHistoryViewState) {
self.render(viewState: viewSate)
}
}
| apache-2.0 | 71c47077210f051a87318f5bd345a0d1 | 33.131068 | 137 | 0.695634 | 5.796373 | false | false | false | false |
philchia/ZGParallaxView | ParallaxView/ViewController.swift | 1 | 1838 | //
// ViewController.swift
// ParallaxView
//
// Created by Phil Chia on 15/11/4.
// Copyright © 2015年 TouchDream. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var tableView: UITableView!
var parallaxView: ZGParallaxView?
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier")
let view = UIImageView(image: UIImage(named: "1.png"))
view.contentMode = .ScaleAspectFill
var frame = view.frame
frame.size = CGSizeMake(self.tableView.frame.size.width, 64)
view.frame = frame
parallaxView = ZGParallaxView.parallaxView(withSubView: view, andSize: CGSizeMake(self.tableView.frame.size.width, 64))
parallaxView!.maxHeight = 150
parallaxView!.minHeight = 64
parallaxView!.maxBlurAlpha = 0.4
parallaxView!.blurEffect = .Light
tableView.tableHeaderView = parallaxView
tableView.showsVerticalScrollIndicator = false
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
cell.textLabel!.text = "Override Me!!"
return cell
}
func limitScrollViewOffset(offset: CGFloat) {
self.tableView.contentOffset.y = offset
}
func scrollViewDidScroll(scrollView: UIScrollView) {
parallaxView?.scrollViewDidScroll(scrollView)
}
}
| mit | 737fe91ba8cd1788071e9407478a4ac3 | 30.637931 | 121 | 0.770027 | 4.237875 | false | false | false | false |
Feyluu/DouYuZB | DouYuZB/DouYuZB/Classes/Tools/NetworkTools.swift | 1 | 896 | //
// NetworkTools.swift
// AlamofireDemo
//
// Created by DuLu on 19/06/2017.
// Copyright © 2017 DuLu. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType {
case GET
case POST
}
class NetworkTools {
class func requestData(type:MethodType, URLString:String,parameters:[String:String]?=nil,finishedCallback : @escaping (_ result:AnyObject) -> ()) {
// 获取type类型
let method = type == .GET ? HTTPMethod.get : HTTPMethod.post
Alamofire.request(URLString, method: method, parameters: parameters, encoding:URLEncoding.default , headers: nil).responseJSON { (response) in
guard let result = response.result.value else {
print(response.result.error!)
return
}
// 回调结果
finishedCallback(result as AnyObject)
}
}
}
| mit | 36849d0c69b3bd1163c0cb0fc2297031 | 26.46875 | 151 | 0.61661 | 4.484694 | false | false | false | false |
fellipecaetano/Democracy-iOS | Sources/Redux/Store.swift | 1 | 1480 | import Foundation
final class Store<State>: StoreProtocol {
private(set) var state: State { didSet { publish(state) }}
private let reduce: Reducer<State>
private var subscribers = [String: (State) -> Void]()
private var dispatcher: Dispatch!
init (initialState: State,
reducer: @escaping Reducer<State>,
middleware: @escaping Middleware<State>) {
self.state = initialState
self.reduce = reducer
self.dispatcher = middleware({ state }, _dispatch)(_dispatch)
}
init (initialState: State, reducer: @escaping Reducer<State>) {
self.state = initialState
self.reduce = reducer
self.dispatcher = _dispatch
}
func dispatch(_ action: Action) {
dispatcher(action)
}
private func _dispatch(_ action: Action) {
state = reduce(state, action)
}
func subscribe(_ subscription: @escaping (State) -> Void) -> () -> Void {
let token = UUID().uuidString
subscribers[token] = subscription
subscription(state)
return { [weak self] in
_ = self?.subscribers.removeValue(forKey: token)
}
}
private func publish(_ newState: State) {
subscribers.values.forEach { $0(newState) }
}
}
protocol StoreProtocol {
associatedtype State
var state: State { get }
func dispatch(_ action: Action)
func subscribe(_ subscription: @escaping (State) -> Void) -> () -> Void
}
| mit | bce9b968201596ef56a1456864f70541 | 28.019608 | 77 | 0.610135 | 4.539877 | false | false | false | false |
mitolog/AutoLockScreen | AutoLockScreen/ViewController.swift | 1 | 6118 | //
// ViewController.swift
// AutoLockScreen
//
// Created by Yuhei Miyazato on 12/15/15.
// Copyright © 2015 mitolab. All rights reserved.
//
import Cocoa
import SocketIO
import RxSwift
import RxCocoa
class ViewModel {
var socket:SocketIOClient?
var hostUrlSeq = PublishSubject<String>()
var sioConnectedSeq = PublishSubject<Bool>()
var connectBtnSeq = PublishSubject<Bool>()
var isSleeping = Variable<Bool>(false)
var walkingCnt = Variable<Int>(0)
let disposeBag = DisposeBag()
func getPreviousHostUrl() {
let sud = NSUserDefaults.standardUserDefaults()
let storedHostUrl = sud.objectForKey(Consts.hostUrlKey) as! String?
if let hostUrl = storedHostUrl {
self.hostUrlSeq.on(.Next(hostUrl))
}
}
func showAlertAndImmitateToggleButton(msg:String, content:String, viewController:ViewController) {
dispatch_async(dispatch_get_main_queue(), {
let alert = NSAlert()
alert.messageText = msg
alert.informativeText = content
alert.runModal()
viewController.connectBtn.state = NSOffState // imitate button press
})
}
func setupAndStartSocketIO(hostUrl:String, _ viewController:ViewController) {
self.socket = SocketIOClient(socketURL: hostUrl)
self.socket?.on("connect") { [unowned self] data, ack in
self.sioConnectedSeq.on(.Next(true))
self.socket?.emit("connected", Consts.appName)
}
self.socket?.on("error", callback: { [unowned self, unowned viewController] data, ack in
self.showAlertAndImmitateToggleButton("SocketIO Error", content: "some error occured while connecting socket. Program automatically disconnect socket, please retry.", viewController: viewController)
self.connectBtnSeq.on(.Next(false))
})
self.socket?.on("publish", callback: { [unowned self, unowned viewController] data, ack in
//print("data: \(data)\n ack:\(ack)")
let csvStr = data.first as! String
viewController.dataLabel.stringValue = csvStr
let comps = csvStr.componentsSeparatedByString(",")
let isWalking = Int(comps[1])
if !self.isSleeping.value && isWalking > 0 {
self.walkingCnt.value++
}
})
/* automatically disconnect when another one(might be ios app) has disconnected
self.socket?.on("exit", callback: { [unowned self, unowned viewController] data, ack in
if (data.first as! String) != Consts.appName && self.socket != nil {
self.showAlertAndImmitateToggleButton("SocketIO Disconnectd", content: "Another one has disconnected from socket.io server.", viewController: viewController)
self.connectBtnSeq.on(.Next(false))
}
})
*/
self.socket?.on("disconnect", callback: { [unowned self, unowned viewController] data, ack in
self.showAlertAndImmitateToggleButton("SocketIO Disconnectd", content: "I'm disconnected from socket.io server.", viewController: viewController)
})
self.socket?.connect()
}
func bindViews(controller:ViewController) {
/* Bind Model -> View */
self.hostUrlSeq
.subscribeOn(MainScheduler.sharedInstance)
.filter({ hostUrl in
return hostUrl.characters.count > 0
})
.bindTo(controller.hostUrlTextField.rx_text)
.addDisposableTo(self.disposeBag)
self.connectBtnSeq
.subscribeOn(MainScheduler.sharedInstance)
.subscribeNext { [unowned self, unowned controller] currentState in
if !currentState {
self.disconnect()
self.isSleeping.value = false
} else {
let hostUrl = controller.hostUrlTextField.stringValue
self.setupAndStartSocketIO(hostUrl, controller)
// Save current IP/Port
let sud = NSUserDefaults.standardUserDefaults()
sud.setValue(hostUrl, forKey: Consts.hostUrlKey)
sud.synchronize()
}
}.addDisposableTo(self.disposeBag)
controller.connectBtn.rx_tap.map { [unowned controller] in
return (controller.connectBtn.state == NSOnState) ?? false
}
.bindTo(self.connectBtnSeq)
.addDisposableTo(self.disposeBag)
combineLatest(self.walkingCnt, self.isSleeping) { walkCnt, isSleeping in
return (walkCnt > Consts.walkThresholdNum && !isSleeping) ?? false
}
.subscribeOn(MainScheduler.sharedInstance)
.subscribeNext { [unowned self] canSleep in
if canSleep {
// activate task
let task = NSTask()
task.launchPath = NSBundle.mainBundle().pathForResource("CGSession", ofType: nil)!
task.arguments = ["-suspend"]
task.launch()
// reset parameters
self.isSleeping.value = true
self.walkingCnt.value = 0
}
}.addDisposableTo(self.disposeBag)
}
func disconnect() {
self.socket?.disconnect()
self.socket = nil
}
}
class ViewController: NSViewController {
@IBOutlet weak var dataLabel: NSTextField!
@IBOutlet weak var hostUrlTextField: NSTextField!
@IBOutlet weak var connectBtn: NSButton!
let vm = ViewModel()
override func viewDidLoad() {
super.viewDidLoad()
self.vm.bindViews(self)
self.vm.getPreviousHostUrl()
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
| mit | 9a07a42d900fba11b80019b033bd67de | 34.358382 | 210 | 0.585581 | 5.201531 | false | false | false | false |
cactis/SwiftEasyKit | Source/Classes/CollectionView.swift | 1 | 1477 | //
// CollectionView.swift
//
// Created by ctslin on 2016/11/5.
import UIKit
open class CollectionView: DefaultView, UICollectionViewDataSource, UICollectionViewDelegate {
public var columns: CGFloat = 2
public var collectionView: UICollectionView!
public var collectionViewLayout = UICollectionViewFlowLayout()
public let CellIdentifier = "CELL"
public var sectionInset: UIEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)
override open func layoutUI() {
super.layoutUI()
collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewLayout)
}
override open func styleUI() {
super.styleUI()
collectionView.backgroundColor = K.Color.collectionView
}
override open func layoutSubviews() {
super.layoutSubviews()
collectionView.fillSuperview()
styleUI()
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return UICollectionViewCell() }
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 0 }
open func registerClass(_ registeredClass: AnyClass!, sectionInset: UIEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10), direction: UICollectionViewScrollDirection = .horizontal) -> UICollectionView {
return collectionView(collectionViewLayout, registeredClass: registeredClass, identifier: CellIdentifier, sectionInset: sectionInset, direction: direction)
}
}
| mit | 8a2dd966e9d04d00804c6f7c1ef14a06 | 36.871795 | 199 | 0.771835 | 5.552632 | false | false | false | false |
liuweicode/LinkimFoundation | Example/LinkimFoundation/MainViewController.swift | 1 | 4460 | //
// MainViewController.swift
// LinkimFoundation
//
// Created by liuwei on 06/30/2016.
// Copyright (c) 2016 liuwei. All rights reserved.
//
import UIKit
import LinkimFoundation
import SnapKit
class MainViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,CycleViewDataSource,CycleViewDelegate {
let dataSource: [String] = {
let dataSource = ["AD_1.jpg","AD_2.jpg"]
return dataSource
}()
let rootView: MainView = {
let rooView = MainView()
return rooView
}()
let vcList = [ "Notification",
"Timer",
"String",
"UIImageView",
"AlertView",
"Sandbox",
"IQKeyboardManagerSwift",
"HUD"
]
override func viewDidLoad() {
super.viewDidLoad()
rootView.advertView.cycleView.dataSource = self
rootView.advertView.cycleView.delegate = self
rootView.advertView.cycleView.getPageView()?.setPageSize(dataSource.count)
rootView.tableView.dataSource = self
rootView.tableView.delegate = self
view.addSubview(rootView)
rootView.snp_makeConstraints { (make) in
make.edges.equalTo(view)
}
}
// UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return vcList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell = tableView.dequeueReusableCellWithIdentifier("CELL")
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: "CELL")
}
cell!.textLabel?.text = vcList[indexPath.row]
return cell!
}
// UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
switch indexPath.row {
case 0: // Notification
let controller = NotificationViewController()
self.navigationController?.pushViewController(controller, animated: true)
case 1: // Timer
let controller = TimerViewController()
self.navigationController?.pushViewController(controller, animated: true)
case 2: // String
let controller = StringDemoViewController()
self.navigationController?.pushViewController(controller, animated: true)
case 3: // UIImageView
let controller = UIimageViewViewController()
self.navigationController?.pushViewController(controller, animated: true)
case 4: // AlertView
let controller = AlertViewDemoViewController()
self.navigationController?.pushViewController(controller, animated: true)
case 5: // Sandbox
let controller = SandboxTestViewController()
self.navigationController?.pushViewController(controller, animated: true)
case 6: // IQKeyboardManagerSwift test
let controller = KeyboardManagerTestViewController()
controller.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(controller, animated: true)
case 7: // HUD
let controller = HUDViewController()
controller.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(controller, animated: true)
default:
break
}
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
tableView.cellLineFull(cell)
}
// CycleViewDataSource
func itemCount() -> NSInteger {
return self.dataSource.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ADVERT_COLLECTION_CELL_ID, forIndexPath: indexPath) as! AdvertCollectionViewCell
cell.setImage(self.dataSource[indexPath.row])
return cell
}
// CycleViewDelegate
func itemDidSelected(indexPath: NSIndexPath) {
print("itemDidSelected:\(indexPath.section) \(indexPath.row)")
}
}
| mit | 10f5d2f4842247d941a112b797ee30a2 | 35.859504 | 153 | 0.648655 | 5.79974 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab2Search/SLV_200_SearchMainController.swift | 1 | 13987 | //
// SLV_200_SearchMainController.swift
// selluv-ios
//
// Created by 조백근 on 2016. 11. 8..
// Copyright © 2016년 BitBoy Labs. All rights reserved.
//
/*
탭2 검색뷰 컨트롤러
*/
import Foundation
import UIKit
import SnapKit
class SLV_200_SearchMainController: ButtonBarPagerTabStripViewController, NavgationTransitionable {
public weak var tr_pushTransition: TRNavgationTransitionDelegate?
var tr_presentTransition: TRViewControllerTransitionDelegate?
public weak var modalDelegate: ModalViewControllerDelegate?
@IBOutlet weak var hConstraint: NSLayoutConstraint!
var preTabIndex: Int = 0
let likePoint : UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.frame = CGRect(x:46, y:3, width:9, height: 9)
imageView.layer.masksToBounds = true
imageView.image = UIImage(named: "ic-badge.png")
imageView.layer.borderColor = UIColor.white.cgColor
imageView.layer.borderWidth = 2
imageView.layer.cornerRadius = 4.5
return imageView
}()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.resetupNavigationBar()
tabController.animationTabBarHidden(false)//탭바 보여준다.
tabController.hideFab()
self.preTabIndex = 1
self.binding()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidLoad() {
self.resetupNavigationBar()
self.setupButtonBar()
super.viewDidLoad()
self.navigationController?.navigationBar.tintColor = UIColor.white
self.navigationItem.hidesBackButton = true
self.extendedLayoutIncludesOpaqueBars = true
self.automaticallyAdjustsScrollViewInsets = false
self.setupNavigationButtons()
self.contentInsetY = 44
self.containerView.contentInset = UIEdgeInsets(top: contentInsetY, left: 0, bottom: 0, right: 0)
// let barFrame = self.buttonBarView.frame
// self.buttonBarView.frame = CGRect(x: barFrame.origin.x, y: barFrame.origin.y, width: 200, height: barFrame.size.height)
// self.buttonBarView.clipsToBounds = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override var prefersStatusBarHidden: Bool {
return false
}
func resetupNavigationBar() {
self.navigationBar?.isHidden = false
self.navigationBar?.barHeight = 44
_ = self.navigationBar?.sizeThatFits(.zero)
}
func setupButtonBar() {
// change selected bar color
settings.style.buttonBarBackgroundColor = .white
settings.style.buttonBarItemBackgroundColor = .white
settings.style.selectedBarBackgroundColor = text_color_bl51
settings.style.buttonBarItemFont = .systemFont(ofSize: 16, weight: UIFontWeightMedium)
settings.style.selectedBarHeight = 4.0 //스토리보드에서 높이만큼 컨테이너 뷰의 간격을 더 내려준다.(높이의 배수?)
settings.style.buttonBarMinimumLineSpacing = 0
settings.style.buttonBarItemTitleColor = text_color_bl51
settings.style.buttonBarItemsShouldFillAvailiableWidth = false
settings.style.buttonBarLeftContentInset = 40
settings.style.buttonBarRightContentInset = 40
settings.style.buttonBarHeight = 44
settings.style.buttonBarItemsLine = 2
changeCurrentIndexProgressive = { [weak self] (oldCell: ButtonBarViewCell?, newCell: ButtonBarViewCell?, progressPercentage: CGFloat, changeCurrentIndex: Bool, animated: Bool) -> Void in
guard changeCurrentIndex == true else { return }
oldCell?.label.textColor = text_color_g153
oldCell?.label.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightRegular)
newCell?.label.textColor = text_color_bl51
newCell?.label.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightSemibold)
if newCell != nil {
// let path = self?.buttonBarView.indexPath(for: newCell!)//TODO: 작업 중 nil 확인하고, 스크롤 관련 spliter 처리할 것...
// log.debug("pathInfo ---> \(path?.item)")
// if path != nil {
// }
}
self?.resetupNavigationBar()
}
}
func setupNavigationButtons() {
let search = UIButton()
search.setImage(UIImage(named:"Brand_header_search.png"), for: .normal)
// search.contentHorizontalAlignment = .left
search.frame = CGRect(x: 17, y: 0, width: 30+26, height: 30)
search.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 26)
search.addTarget(self, action: #selector(SLV_200_SearchMainController.search(sender:)), for: .touchUpInside)
let item1 = UIBarButtonItem(customView: search)
self.navigationItem.leftBarButtonItem = item1
let view = UIView(frame: CGRect(x:0, y:0, width:56, height: 30))
let iv = UIImageView()
iv.frame = CGRect(x:26, y:0, width:30, height: 30)
iv.image = UIImage(named:"actionbar-like.png")
view.addSubview(iv)
view.addSubview(self.likePoint)
let heart = UIButton()
heart.frame = CGRect(x:0, y:0, width:56, height: 30)
heart.addTarget(self, action: #selector(SLV_200_SearchMainController.like(sender:)), for: .touchUpInside)
view.addSubview(heart)
let item2 = UIBarButtonItem(customView: view)
self.navigationItem.rightBarButtonItem = item2
}
func binding() {
if self.preTabIndex != 0 {
// let board = UIStoryboard(name:"Search", bundle: nil)
// let controller1 = board.instantiateViewController(withIdentifier: "SLV_204_SearchStyle") as! SLV_204_SearchStyle
// controller1.linkDelegate(controller: self)
// let controller2 = board.instantiateViewController(withIdentifier:"SLV_201_SearchMale") as! SLV_201_SearchMale
// controller2.linkDelegate(controller: self)
// let controller3 = board.instantiateViewController(withIdentifier: "SLV_202_SearchFemale") as! SLV_202_SearchFemale
// controller3.linkDelegate(controller: self)
// let controller4 = board.instantiateViewController(withIdentifier:"SLV_203_SearchKids") as! SLV_203_SearchKids
// controller4.linkDelegate(controller: self)
// self.moveToViewController(at: self.preTabIndex, animated: false)
let controller = self.viewControllers[self.preTabIndex]
self.moveTo(viewController: controller, animated: false)
self.reloadPagerTabStripView()
}
}
// MARK: - PagerTabStripDataSource
override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
let board = UIStoryboard(name:"Search", bundle: nil)
let controller1 = board.instantiateViewController(withIdentifier: "SLV_204_SearchStyle") as! SLV_204_SearchStyle
controller1.linkDelegate(controller: self)
let controller2 = board.instantiateViewController(withIdentifier:"SLV_201_SearchMale") as! SLV_201_SearchMale
controller2.linkDelegate(controller: self)
let controller3 = board.instantiateViewController(withIdentifier: "SLV_202_SearchFemale") as! SLV_202_SearchFemale
controller3.linkDelegate(controller: self)
let controller4 = board.instantiateViewController(withIdentifier:"SLV_203_SearchKids") as! SLV_203_SearchKids
controller4.linkDelegate(controller: self)
return [controller1, controller2, controller3, controller4]
}
func moveUserPage(userId: String) {
let board = UIStoryboard(name:"Me", bundle: nil)
let controller = board.instantiateViewController(withIdentifier: "SLV_800_UserPageController") as! SLV_800_UserPageController
controller.sellerId = userId
self.navigationController?.tr_pushViewController(controller, method: TRPushTransitionMethod.fade, statusBarStyle: .default) {
}
}
// func moveSearchNext() {
// let board = UIStoryboard(name:"Search", bundle: nil)
// if 1 == 1 {
// let controller = board.instantiateViewController(withIdentifier: "SLV_206_SearchCategoryController") as! SLV_206_SearchCategoryController
//// controller.sellerId = userId
// self.tr_presentViewController(controller, method: TRPresentTransitionMethod.twitter, statusBarStyle: .default) {
// }
// } else {
// let controller = board.instantiateViewController(withIdentifier: "SLV_210_SearchBarController") as! SLV_210_SearchBarController
//// controller.sellerId = userId
// self.navigationController?.tr_pushViewController(controller, method: TRPushTransitionMethod.fade, statusBarStyle: .default) {
// }
// }
// }
//MARK: EVENT
func dismiss(callBack: AnyObject? = nil) {
// _ = self.navigationController?.tr_popViewController()
modalDelegate?.modalViewControllerDismiss(callbackData: callBack)
}
func back(sender: UIButton?) {
}
func search(sender: UIButton?) {
let board = UIStoryboard(name:"Search", bundle: nil)
let controller = board.instantiateViewController(withIdentifier: "SLV_210_SearchBarController") as! SLV_210_SearchBarController
controller.modalDelegate = self
self.tr_presentViewController(controller, method: TRPresentTransitionMethod.twitter) {
print("Present finished.")
}
}
func like(sender: UIButton?) {
}
func moveCategory(gender: String) {
let board = UIStoryboard(name:"Search", bundle: nil)
let controller = board.instantiateViewController(withIdentifier: "SLV_206_SearchCategoryController") as! SLV_206_SearchCategoryController
controller.setupCategory(gender: gender)
controller.modalDelegate = self
self.tr_presentViewController(controller, method: TRPresentTransitionMethod.twitter) {
print("Present finished.")
}
}
func moveSearchCategory(key: String, gender: String) {
let board = UIStoryboard(name:"Search", bundle: nil)
let controller = board.instantiateViewController(withIdentifier: "SLV_220_SearchCategoryController") as! SLV_220_SearchCategoryController
self.navigationController?.tr_pushViewController(controller, method: TRPushTransitionMethod.fade, statusBarStyle: .default) {
}
}
func moveBrandDetail(brand: Brand) {
let brandId = brand.id.copy() as! String
let board = UIStoryboard(name:"Brand", bundle: nil)
let controller = board.instantiateViewController(withIdentifier: "SLV_441_BrandPageController") as! SLV_441_BrandPageController
controller.brandId = brandId
self.navigationController?.tr_pushViewController(controller, method: TRPushTransitionMethod.fade, statusBarStyle: .default) {
}
}
}
extension SLV_200_SearchMainController: SLVButtonBarDelegate {
func showByScroll() {//down scroll
if self.hConstraint.constant > 0 {
return
}
tabController.hideFab()
tabController.animationTabBarHidden(false)
tabController.tabBar.needsUpdateConstraints()
self.hConstraint.constant = 44
self.buttonBarView.needsUpdateConstraints()
self.contentInsetY = 44
self.containerView.contentInset = UIEdgeInsets(top: contentInsetY, left: 0, bottom: 64, right: 0)
self.containerView.needsUpdateConstraints()
UIView.animate(withDuration: 0.2, animations: {
self.buttonBarView.layoutIfNeeded()
self.containerView.layoutIfNeeded()
}, completion: {
completed in
})
}
func hideByScroll() {// up scroll
//top
if self.hConstraint.constant == 0 {
return
}
tabController.showFab()
tabController.animationTabBarHidden(true)
tabController.tabBar.needsUpdateConstraints()
self.hConstraint.constant = 0
self.buttonBarView.needsUpdateConstraints()
self.contentInsetY = 0
self.containerView.contentInset = UIEdgeInsets(top: contentInsetY, left: 0, bottom: 20, right: 0)
self.containerView.needsUpdateConstraints()
UIView.animate(withDuration: 0.5, animations: {
self.buttonBarView.layoutIfNeeded()
self.containerView.layoutIfNeeded()
}, completion: {
completed in
})
}
}
extension SLV_200_SearchMainController: SLVNavigationControllerDelegate {
func linkMyNavigationForTransition() -> UINavigationController? {
return self.navigationController
}
// 현재의 탭정보를 반환하다.
func currentTabIndex() -> Int! {
return self.currentIndex
}
}
extension SLV_200_SearchMainController: ModalTransitionDelegate {
func modalViewControllerDismiss(callbackData data:AnyObject?) {
log.debug("SLV_200_SearchMainController(callbackData:)")
tr_dismissViewController(completion: {
if let back = data {
let cb = back as! [String: String]
let keys = cb.keys
if keys.contains("from") == true {
let key = cb["from"]
if key != nil {
if key == "category" {
let selectedCategory = cb["selection"]
}
}
}
}
})
}
}
| mit | 5c5f8dc8475329365cd4ec133d678c03 | 40.674699 | 194 | 0.654524 | 4.904644 | false | false | false | false |
CosmicMind/Samples | Projects/Programmatic/Search/Search/SampleData.swift | 1 | 4835 | /*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import Material
import Graph
extension UIImage {
public class func load(contentsOfFile name: String, ofType type: String) -> UIImage? {
return UIImage(contentsOfFile: Bundle.main.path(forResource: name, ofType: type)!)
}
}
struct SampleData {
public static func createSampleData() {
let graph = Graph()
let u1 = Entity(type: "User")
u1["name"] = "Daniel Dahan"
u1["status"] = "Making the world a better place, one line of code at a time."
u1["photo"] = UIImage.load(contentsOfFile: "daniel", ofType: "jpg")?.crop(toWidth: 60, toHeight: 60)
let u2 = Entity(type: "User")
u2["name"] = "Deepali Parhar"
u2["status"] = "I haven’t come this far, only to come this far."
u2["photo"] = UIImage.load(contentsOfFile: "deepali", ofType: "jpg")?.crop(toWidth: 60, toHeight: 60)
let u3 = Entity(type: "User")
u3["name"] = "Eve"
u3["status"] = "Life is beautiful, so reflect it."
u3["photo"] = UIImage.load(contentsOfFile: "eve", ofType: "jpg")?.crop(toWidth: 60, toHeight: 60)
let u4 = Entity(type: "User")
u4["name"] = "Kendall Johnson"
u4["status"] = "It’s all about perspective"
u4["photo"] = UIImage.load(contentsOfFile: "kendall", ofType: "jpg")?.crop(toWidth: 60, toHeight: 60)
let u5 = Entity(type: "User")
u5["name"] = "Ashton McGregor"
u5["status"] = "So much to say, so few words."
u5["photo"] = UIImage.load(contentsOfFile: "ashton", ofType: "png")?.crop(toWidth: 60, toHeight: 60)
let u7 = Entity(type: "User")
u7["name"] = "Laura Graham"
u7["status"] = "Eyes are the mirror to your soul."
u7["photo"] = UIImage.load(contentsOfFile: "laura", ofType: "jpg")?.crop(toWidth: 60, toHeight: 60)
let u8 = Entity(type: "User")
u8["name"] = "Karen Si"
u8["status"] = "Letting go to move forward."
u8["photo"] = UIImage.load(contentsOfFile: "karen", ofType: "jpg")?.crop(toWidth: 60, toHeight: 60)
let u9 = Entity(type: "User")
u9["name"] = "Jonathan Kuran"
u9["status"] = "Calculating the distance from here to there."
u9["photo"] = UIImage.load(contentsOfFile: "jonathan", ofType: "jpg")?.crop(toWidth: 60, toHeight: 60)
let u10 = Entity(type: "User")
u10["name"] = "Thomas Wallace"
u10["status"] = "I’m in it to win it. Long game."
u10["photo"] = UIImage.load(contentsOfFile: "thomas", ofType: "jpg")?.crop(toWidth: 60, toHeight: 60)
let u11 = Entity(type: "User")
u11["name"] = "Charles St. Louis"
u11["status"] = "Double Major in Mathematics and Philosophy. Modern Day Renaissance Man."
u11["photo"] = UIImage.load(contentsOfFile: "charles", ofType: "jpg")?.crop(toWidth: 60, toHeight: 60)
let u12 = Entity(type: "User")
u12["name"] = "Kelly Martin"
u12["status"] = "The world is mine."
u12["photo"] = UIImage.load(contentsOfFile: "kelly", ofType: "jpeg")?.crop(toWidth: 60, toHeight: 60)
graph.sync()
}
}
| bsd-3-clause | 04761018b52d6cdb9e1208f8a7b18d3a | 46.343137 | 110 | 0.640091 | 3.8632 | false | false | false | false |
ello/ello-ios | Specs/Controllers/Stream/Calculators/StreamTextCellSizeCalculatorSpec.swift | 1 | 1608 | ////
/// StreamTextCellSizeCalculatorSpec.swift
//
@testable import Ello
import Quick
import Nimble
class StreamTextCellSizeCalculatorSpec: QuickSpec {
override func spec() {
var webView: MockUIWebView!
let mockHeight: CGFloat = 50
beforeEach {
webView = MockUIWebView()
webView.mockHeight = mockHeight
}
describe("StreamTextCellSizeCalculator") {
it("assigns cell height to all cell items") {
let post = Post.stub([:])
let items = [
StreamCellItem(jsonable: post, type: .text(data: TextRegion(content: ""))),
StreamCellItem(jsonable: post, type: .text(data: TextRegion(content: ""))),
StreamCellItem(jsonable: post, type: .text(data: TextRegion(content: ""))),
StreamCellItem(jsonable: post, type: .text(data: TextRegion(content: ""))),
]
for item in items {
let calculator = StreamTextCellSizeCalculator(
streamKind: .following,
item: item,
width: 320,
columnCount: 1
)
calculator.webView = webView
var completed = false
calculator.begin {
completed = true
}
expect(completed) == true
expect(item.calculatedCellHeights.oneColumn) == mockHeight
}
}
}
}
}
| mit | b5f621598cc6415ca225aad1611f2013 | 31.816327 | 95 | 0.493781 | 5.72242 | false | false | false | false |
TONEY-XZW/douyu | ZW_Swift/Common/JQProgressHUD/JQOvalIndicatorView.swift | 1 | 2258 | //
// JQOvalIndicatorView.swift
// JQProgressHUD
//
// Created by HJQ on 2017/7/5.
// Copyright © 2017年 HJQ. All rights reserved.
//
import UIKit
public class JQOvalIndicatorView: UIView {
public var color: UIColor? = UIColor.white {
didSet{
commonInit()
}
}
public var lineWidth: CGFloat = 3.0 {
didSet{
commonInit()
}
}
//private let radius: CGFloat = 10
override public init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - private methods
private func setupUI() {
layer.addSublayer(ovalShapeLayer)
commonInit()
startAnimation()
}
private func commonInit() {
ovalShapeLayer.strokeColor = color!.cgColor
ovalShapeLayer.fillColor = UIColor.clear.cgColor
ovalShapeLayer.lineWidth = lineWidth
let anotherOvalRadius = frame.size.height/2 * 0.85
ovalShapeLayer.path = UIBezierPath(ovalIn: CGRect(x: frame.size.width/2 - anotherOvalRadius, y: frame.size.height/2 - anotherOvalRadius, width: anotherOvalRadius * 2, height: anotherOvalRadius * 2)).cgPath
ovalShapeLayer.lineCap = kCALineCapRound
}
// MARK: - lazy load
fileprivate lazy var ovalShapeLayer: CAShapeLayer = {
let indicatorLayer = CAShapeLayer()
return indicatorLayer
}()
fileprivate func startAnimation() {
let strokeStartAnimate = CABasicAnimation(keyPath: "strokeStart")
strokeStartAnimate.fromValue = -0.5
strokeStartAnimate.toValue = 1
let strokeEndAnimate = CABasicAnimation(keyPath: "strokeEnd")
strokeEndAnimate.fromValue = 0.0
strokeEndAnimate.toValue = 1
let strokeAnimateGroup = CAAnimationGroup()
strokeAnimateGroup.duration = 1.5
strokeAnimateGroup.repeatCount = HUGE
strokeAnimateGroup.animations = [strokeStartAnimate, strokeEndAnimate]
ovalShapeLayer.add(strokeAnimateGroup, forKey: nil)
}
}
| mit | da2a4db20cb884bc893f8aad9b416968 | 26.168675 | 213 | 0.619512 | 5.125 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.