repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Jubilant-Appstudio/Scuba | refs/heads/master | ScubaCalendar/Resource/Shared/CommonMethods.swift | mit | 1 | //
// CommonMethods.swift
// CredDirectory
//
// Created by Mahipal on 13/4/17.
// Copyright © 2017 Mahipal. All rights reserved.
//
import UIKit
import MBProgressHUD
import SkyFloatingLabelTextField
class CommonMethods: NSObject {
//Declare enum
enum AnimationType {
case ANIMATERIGHT
case ANIMATELEFT
case ANIMATEUP
case ANIMATEDOWN
}
struct SetFont {
static let MontserratSemiBold = UIFont(name: "Montserrat-SemiBold", size: 15.0)
static let MontserratMedium = UIFont(name: "Montserrat-Medium", size: 15.0)
static let MontserratBold = UIFont(name: "Montserrat-Bold", size: 15.0)
static let RalewayRegular = UIFont(name: "Raleway-Regular", size: 15.0)
static let RalewaySemiBold = UIFont(name: "Raleway-SemiBold", size: 15.0)
}
struct SetFontSize {
static let S10 = 10.0
static let S12 = 12.0
static let S15 = 15.0
static let S17 = 17.0
static let S20 = 20.0
}
struct SetColor {
static let clearColor = UIColor.clear
static let whiteColor = UIColor.white
static let themeColor = UIColor(red: 63/255.0, green: 81/255.0, blue: 114/255.0, alpha: 1.0)
static let darkGrayColor = UIColor(red: 104/255.0, green: 104/255.0, blue: 104/255.0, alpha: 1.0)
static let searchbarBGColor = UIColor(red: 15/255.0, green: 19/255.0, blue: 30/255.0, alpha: 1.0)
static let pickerBorderColor = UIColor(red: 0.0/255.0, green: 81.0/255.0, blue: 114.0/255.0, alpha: 1.0)
}
/*
static var setTextColor = UIColor.white
static var setLineColor = UIColor.white
static var setTopPlaceHolderColor = UIColor(red: 63/255.0, green: 81/255.0, blue: 114/255.0, alpha: 1.0)
*/
static var hud: MBProgressHUD = MBProgressHUD()
static var navControl: UINavigationController?
static var alert: UIAlertController?
static var sharedObj: Shared?
class func navigateTo(_ destinationVC: UIViewController, inNavigationViewController navigationController: UINavigationController, animated: Bool ) {
//Assign to global value
navControl = navigationController
var VCFound: Bool = false
let viewControllers: NSArray = navigationController.viewControllers as NSArray
var indexofVC: NSInteger = 0
for vc in navigationController.viewControllers {
if vc.nibName == (destinationVC.nibName) {
VCFound = true
break
} else {
indexofVC += 1
}
}
DispatchQueue.main.async(execute: {
if VCFound == true {
// navigationController .popToViewController(viewControllers.object(at: indexofVC) as! UIViewController, animated: animated)
if let navigationObj: UIViewController = viewControllers.object(at: indexofVC) as? UIViewController {
navigationController.popToViewController(navigationObj, animated: animated)
}
} else {
navigationController .pushViewController(destinationVC, animated: animated)
}
})
}
class func findViewControllerRefInStack(_ destinationVC: UIViewController, inNavigationViewController navigationController: UINavigationController) -> UIViewController {
var VCFound = false
var viewControllers = navigationController.viewControllers
var indexofVC = 0
for vc: UIViewController in viewControllers {
if vc.nibName == (destinationVC.nibName) {
VCFound = true
break
} else {
indexofVC += 1
}
}
if VCFound == true {
return viewControllers[indexofVC]
} else {
return destinationVC
}
}
// MARK: UIAlertView
class func showAlert(_ title: NSString, Description message: NSString) {
if alert != nil {
self.dismissAlertView()
}
DispatchQueue.main.async {
// alert = UIAlertView(title: title as String, message: message as String, delegate: nil, cancelButtonTitle: "Okay")
// alert!.show()
alert = UIAlertController(title: title as String, message: message as String, preferredStyle: .alert)
alert?.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
getTopViewController().present(alert!, animated: true, completion: nil)
}
}
class func dismissAlertView() {
alert?.dismiss(animated: true, completion: nil)
}
class func getTopViewController() -> UIViewController {
var viewController = UIViewController()
if let vc = UIApplication.shared.delegate?.window??.rootViewController {
viewController = vc
var presented = vc
while let top = presented.presentedViewController {
presented = top
viewController = top
}
}
print(viewController)
return viewController
}
class func showMBProgressHudView(_ view: UIView) {
DispatchQueue.main.async(execute: {
self.hud = MBProgressHUD.showAdded(to: view, animated: true)
})
}
class func showPercentageMBProgressHudView(_ view: UIView) {
DispatchQueue.main.async(execute: {
self.hud = MBProgressHUD.showAdded(to: view, animated: true)
hud.mode = .determinateHorizontalBar
})
}
class func hideMBProgressHud() {
DispatchQueue.main.async(execute: {
self.hud.hide(animated: true)
})
}
class func convertDateFormat(fullDate: String) -> String {
if fullDate != "" {
let dateFormatter = DateFormatter()
let tempLocale = dateFormatter.locale
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let date = dateFormatter.date(from: fullDate)!
dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.locale = tempLocale
let dateString = dateFormatter.string(from: date)
return dateString
} else {
return ""
}
}
class func setCommonLayer(getButton: UIButton) -> UIButton {
getButton.layer.borderColor = UIColor.white.cgColor
getButton.layer.borderWidth = 0.5
getButton.layer.cornerRadius = 5.0
return getButton
}
class func setCommonTextfield(getTextfield: SkyFloatingLabelTextField) -> SkyFloatingLabelTextField {
getTextfield.textColor = CommonMethods.SetColor.whiteColor
getTextfield.selectedLineColor = CommonMethods.SetColor.whiteColor
getTextfield.placeholderColor = CommonMethods.SetColor.themeColor
getTextfield.titleColor = CommonMethods.SetColor.themeColor
getTextfield.lineColor = CommonMethods.SetColor.themeColor
getTextfield.selectedTitleColor = CommonMethods.SetColor.themeColor
return getTextfield
}
class func setCommonSearchField(getSearchBar: UISearchBar) -> UISearchBar {
getSearchBar.borderColor = CommonMethods.SetColor.darkGrayColor
getSearchBar.borderWidth = 0.5
getSearchBar.cornerRadius = 5
getSearchBar.shadowOffset = CGSize(width: 0, height: 1)
getSearchBar.barTintColor = CommonMethods.SetColor.clearColor
getSearchBar.barStyle = .black
getSearchBar.barTintColor = CommonMethods.SetColor.clearColor
getSearchBar.tintColor = CommonMethods.SetColor.clearColor
getSearchBar.textField?.textColor = CommonMethods.SetColor.whiteColor
return getSearchBar
}
class func showViewControllerWith(storyboard: String , newViewController: UIViewController, usingAnimation animationType: AnimationType) {
let currentViewController = UIApplication.shared.delegate?.window??.rootViewController
let width = currentViewController?.view.frame.size.width
let height = currentViewController?.view.frame.size.height
var previousFrame: CGRect?
var nextFrame: CGRect?
switch animationType {
case .ANIMATELEFT:
previousFrame = CGRect(x: (width!) - 1, y: 0.0, width: width!, height: height!)
nextFrame = CGRect(x: -(width!), y: 0.0, width: width!, height: height!)
case .ANIMATERIGHT:
previousFrame = CGRect(x: -(width!) + 1, y: 0.0, width: width!, height: height!)
nextFrame = CGRect(x: (width!), y: 0.0, width: width!, height: height!)
case .ANIMATEUP:
previousFrame = CGRect(x: 0.0, y: (height!) - 1, width: width!, height: height!)
nextFrame = CGRect(x: 0.0, y: -(height!) + 1, width: width!, height: height!)
case .ANIMATEDOWN:
previousFrame = CGRect(x: 0.0, y: -(height!) + 1, width: width!, height: height!)
nextFrame = CGRect(x: 0.0, y: (height!) + 1, width: width!, height: height!)
}
newViewController.view.frame = previousFrame!
UIApplication.shared.delegate?.window??.addSubview(newViewController.view)
UIView.animate(withDuration: 0.3,
animations: { () -> Void in
newViewController.view.frame = (currentViewController?.view.frame)!
currentViewController?.view.frame = nextFrame!
}) { (_: Bool) -> Void in
UIApplication.shared.delegate?.window??.removeSubviews()
if storyboard == "Home" {
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Home", bundle: nil)
UIApplication.shared.delegate?.window??.rootViewController = mainStoryboard.instantiateInitialViewController()
} else {
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
guard let loginVC = mainStoryboard.instantiateViewController(withIdentifier: "LoginVC") as? LoginVC else {
return
}
let nav = UINavigationController(rootViewController: loginVC)
nav.setNavigationBarHidden(true, animated: false)
UIApplication.shared.delegate?.window??.rootViewController = nav
}
}
}
}
| e9ec4bd38994602c24811ee645c411f4 | 35.923588 | 173 | 0.592676 | false | false | false | false |
kfarst/alarm | refs/heads/master | alarm/TimePickerViewController.swift | mit | 1 | //
// TimePickerViewController.swift
// alarm
//
// Created by Michael Lewis on 3/8/15.
// Copyright (c) 2015 Kevin Farst. All rights reserved.
//
import UIKit
protocol TimePickerDelegate {
func timeSelected(time: TimePresenter)
}
class TimePickerViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var timePicker: UIPickerView!
// We're turning a linear picker into a circular one by
// massively duplicating the number of rows, and starting
// off in the middle.
let circularPickerExplosionFactor = 50
let pickerNaturalWidth = CGFloat(160.0)
let pickerNaturalHeight = CGFloat(216.0)
var pickerWidthScaleRatio = CGFloat(1.0)
var pickerHeightScaleRatio = CGFloat(1.0)
// Vertically stretch up the picker element text
let pickerElementHeightScaleRatio = CGFloat(1.3)
var pickerData: Array<TimePresenter>?
var startingTimePresenter: TimePresenter?
var delegate: TimePickerDelegate!
override func viewDidLoad() {
super.viewDidLoad()
// Set up our visual elements
self.view.backgroundColor = UIColor.clearColor()
timePicker.backgroundColor = UIColor.clearColor()
timePicker.alpha = 1.0
// Do any additional setup after loading the view.
timePicker.dataSource = self
timePicker.delegate = self
// Generate our picker data
pickerData = TimePresenter.generateAllElements()
// If we were given a TimePresenter to start with,
// try to select it.
if let timePresenter = startingTimePresenter {
selectTimePresenterRow(timePresenter)
}
}
override func viewWillAppear(animated: Bool) {
fixTimePickerDimensions()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
// Run up the number by a factor of 100 in order to provide fake
// circular selection. This has been profiled and does not materially
// hurt memory usage.
return (pickerData?.count ?? 0) * circularPickerExplosionFactor * 2
}
// For each picker element, set up the view
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView {
var timeView = UIView()
timeView.frame = CGRectMake(0, 0, pickerView.rowSizeForComponent(component).width, pickerView.rowSizeForComponent(component).height)
var timeLabel = UILabel()
var amPmLabel = UILabel()
if let activeElement = getTimePickerAtRow(row) {
let displayString = activeElement.stringForWheelDisplay()
var amPmString: String
if contains(["noon", "midnight"], displayString) {
amPmString = ""
} else {
amPmString = activeElement.stringForAmPm()
}
let transformation = CGAffineTransformMakeScale(
1.0 / pickerWidthScaleRatio,
pickerElementHeightScaleRatio / pickerHeightScaleRatio
)
// Create the labels with our attributed text
timeLabel.attributedText = NSAttributedString(
string: displayString,
attributes: [
NSFontAttributeName: UIFont(name: "Avenir-Light", size: 32.0)!,
NSForegroundColorAttributeName: UIColor(white: 0.8, alpha: 1.0),
]
)
timeLabel.textAlignment = .Center
amPmLabel.attributedText = NSAttributedString(
string: amPmString,
attributes: [
NSFontAttributeName: UIFont(name: "Avenir-Light", size: 18.0)!,
NSForegroundColorAttributeName: UIColor(white: 0.8, alpha: 1.0),
]
)
amPmLabel.textAlignment = .Center
// Finally, transform the text. This essentially performs two transforms.
// The first one is an inverse of the transform run on the picker
// as a whole. This makes sure that while the picker itself is
// stretched, the individual elements themselves are not.
// The second one is an individual scale of the element for
// aesthetics.
timeLabel.transform = transformation
amPmLabel.transform = transformation
}
timeLabel.sizeToFit()
timeLabel.center = timeView.center
amPmLabel.sizeToFit()
amPmLabel.center = CGPoint(x: (timeLabel.center.x + timeLabel.frame.width / 2) + (amPmLabel.frame.width / 2) + 10, y: timeLabel.center.y + amPmLabel.frame.height / 6)
timeView.addSubview(timeLabel)
timeView.addSubview(amPmLabel)
return timeView
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// pickerData[row]
}
func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 20.0
}
// The accept button was selected
@IBAction func acceptTapped(sender: UITapGestureRecognizer) {
let selectedRow = timePicker.selectedRowInComponent(0)
if let activeElement = getTimePickerAtRow(selectedRow) {
delegate?.timeSelected(activeElement)
}
}
/* Private */
// Given a time presenter, select the row in the picker view
// that is equal.
private func selectTimePresenterRow(timePresenter: TimePresenter, animated: Bool = false) {
if let data = pickerData {
if let index = find(data, timePresenter) {
let newRowIndex = data.count * circularPickerExplosionFactor + index
timePicker.selectRow(newRowIndex, inComponent: 0, animated: animated)
}
}
}
// Get the element at a given row
// This is helpful because of our circular data
private func getTimePickerAtRow(row: Int) -> TimePresenter? {
if let data = pickerData {
// Because we're duplicating elements in order to simulate
// a circular effect, we need to use modulus when accessing
// the data by row number.
let numRows = data.count
return data[row % numRows]
} else {
NSLog("Should never nil here")
return nil
}
}
// Horizontally stretch the time picker to the full height of the
// surrounding view. This introduces some weird stretching effects that
// need to be dealt with, but it's the only way to get a picker to display
// with a height greater than 216.
private func fixTimePickerDimensions() {
pickerWidthScaleRatio = (self.view.frame.width / 2.0) / pickerNaturalWidth
pickerHeightScaleRatio = self.view.frame.height / pickerNaturalHeight
timePicker.transform = CGAffineTransformMakeScale(pickerWidthScaleRatio, pickerHeightScaleRatio)
}
}
| a669c6a6136f12835254dca2f567d1e0 | 32.913265 | 170 | 0.705431 | false | false | false | false |
ibari/ios-yelp | refs/heads/master | Yelp/CheckMarkCell.swift | gpl-2.0 | 1 | //
// CheckMarkCell.swift
// Yelp
//
// Created by Ian on 5/17/15.
// Copyright (c) 2015 Ian Bari. All rights reserved.
//
import UIKit
@objc protocol CheckMarkCellDelegate {
optional func checkMarkCell(checkMarkCell: CheckMarkCell, toggleIdenfifier: AnyObject, didChangeValue value:Bool)
}
class CheckMarkCell: UITableViewCell {
@IBOutlet weak var descriptionLabel: UILabel!
var checkIdentifier: AnyObject = ""
var isChecked: Bool = false {
didSet {
if isChecked {
self.accessoryType = .Checkmark
} else {
self.accessoryType = .None
}
}
}
weak var delegate: CheckMarkCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
if selected && !self.selected {
super.setSelected(true, animated: true)
isChecked = !isChecked
delegate?.checkMarkCell?(self, toggleIdenfifier: checkIdentifier, didChangeValue: isChecked)
super.setSelected(false, animated: true)
}
}
} | 6ea04f6b88c091a0e3b66111f9f0644e | 23.27907 | 115 | 0.68744 | false | false | false | false |
AlmostDoneGames/BrickBreaker-iOS | refs/heads/master | Sprong/Bullet.swift | apache-2.0 | 2 | //
// Bullet.swift
// MathBreaker
//
// Created by Cameron Bardell on 2015-12-26.
// Copyright © 2015 Jared McGrath. All rights reserved.
//
import SpriteKit
class Bullet: SKSpriteNode {
var fromTop:Bool
// MARK: Initializers
init (position: CGPoint, fromTop: Bool) {
let texture = SKTexture(imageNamed: "Bullet")
//Changes where the score should be added
self.fromTop = fromTop
super.init(texture: texture, color: SKColor.clearColor(), size: texture.size())
self.physicsBody = SKPhysicsBody(circleOfRadius: texture.size().width/2)
self.physicsBody!.dynamic = true
self.physicsBody!.friction = 0
self.physicsBody!.collisionBitMask = 0x0
self.physicsBody!.linearDamping = 0
self.position = position
self.name = "bullet"
}
required init?(coder aDecoder: NSCoder) {
self.fromTop = false
super.init(coder: aDecoder)
}
} | 1a266093509d2eef33d65af93962db78 | 26.685714 | 87 | 0.637397 | false | false | false | false |
CRAnimation/CRAnimation | refs/heads/master | Example/CRAnimation/Demo/WidgetDemo/S0004_WCLLoadingView/WCLLoadingViewDemoVC.swift | mit | 1 | //
// WCLLoadingViewDemoVC.swift
// CRAnimation
//
// **************************************************
// * _____ *
// * __ _ __ ___ \ / *
// * \ \/ \/ / / __\ / / *
// * \ _ / | (__ / / *
// * \/ \/ \___/ / /__ *
// * /_____/ *
// * *
// **************************************************
// Github :https://github.com/631106979
// HomePage:https://imwcl.com
// CSDN :http://blog.csdn.net/wang631106979
//
// Created by 王崇磊 on 16/9/14.
// Copyright © 2016年 王崇磊. All rights reserved.
//
// @class WCLLoadingViewDemoVC
// @abstract WCLLoadingView的DemoVC
// @discussion WCLLoadingView的DemoVC
//
import UIKit
public let SWIFT_WIDTH = UIScreen.main.bounds.size.width
public let SWIFT_HEIGHT = UIScreen.main.bounds.size.height
public let color_0a090e = UIColor.init(rgba: "#0a090e")
class WCLLoadingViewDemoVC: CRProductionBaseVC {
@IBOutlet weak var loadingView: WCLLoadingView!
let controlViewHeight = 40
let offY: CGFloat = 30
let gapX: CGFloat = 10
//MARK: Public Methods
//MARK: Override
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
loadingView.startAnimation()
view.backgroundColor = color_0a090e
addTopBar(withTitle: "WCLLoadingView")
createSizeControlView()
createDurationControlView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: Target Methods
@IBAction func tapLoadingView(_ sender: UITapGestureRecognizer) {
switch loadingView.status {
case .animating:
loadingView.pauseAnimation()
case .pause:
loadingView.resumeAnimation()
case .normal:
loadingView.startAnimation()
}
}
@IBAction func sizeSliderValueChange(_ sender: UISlider) {
loadingView.transform = CGAffineTransform.identity.scaledBy(x: CGFloat(sender.value) , y: CGFloat(sender.value))
}
@IBAction func durationSliderValueChange(_ sender: UISlider) {
loadingView.duration = Double(sender.value)
}
func createControlView() -> Void {
createSizeControlView()
createDurationControlView()
}
func createSizeControlView() {
let sizeControlView = UIView.init(frame: CGRect.init(x: Int(CR_OFF_STARTX), y: 0, width: Int(SWIFT_WIDTH) - Int(CR_OFF_STARTX + CR_OFF_ENDX), height: controlViewHeight))
view.addSubview(sizeControlView)
let sizeLabel = UILabel.init()
sizeLabel.text = "Size"
sizeLabel.textColor = UIColor.white
sizeLabel.sizeToFit()
sizeControlView.addSubview(sizeLabel)
sizeLabel.bearSetRelativeLayout(with: .DIR_LEFT, destinationView: nil, parentRelation: true, distance: 0, center: true)
let sizeControlSlider = CRSlider.init(frame: CGRect.init(x: sizeLabel.maxX() + gapX, y: 0, width: sizeControlView.width() - sizeLabel.maxX() - gapX, height: sizeControlView.height()))
sizeControlSlider.sliderType = kCRSliderType_Normal
sizeControlSlider.minimumValue = 1
sizeControlSlider.maximumValue = 2
sizeControlSlider.value = 1
sizeControlSlider.addTarget(self, action: #selector(WCLLoadingViewDemoVC.sizeSliderValueChange(_:)), for: UIControlEvents.valueChanged)
sizeControlView.addSubview(sizeControlSlider)
sizeControlView.setMaxY(SWIFT_HEIGHT - CGFloat(controlViewHeight) - offY)
}
func createDurationControlView() {
let durationControlView = UIView.init(frame: CGRect.init(x: Int(CR_OFF_STARTX), y: 0, width: Int(SWIFT_WIDTH) - Int(CR_OFF_STARTX + CR_OFF_ENDX), height: controlViewHeight))
view.addSubview(durationControlView)
let durationLabel = UILabel.init()
durationLabel.text = "Duration"
durationLabel.textColor = UIColor.white
durationLabel.sizeToFit()
durationControlView.addSubview(durationLabel)
durationLabel.bearSetRelativeLayout(with: .DIR_LEFT, destinationView: nil, parentRelation: true, distance: 0, center: true)
let durationControlSlider = CRSlider.init(frame: CGRect.init(x: durationLabel.maxX() + gapX, y: 0, width: durationControlView.width() - durationLabel.maxX() - gapX, height: durationControlView.height()))
durationControlSlider.sliderType = kCRSliderType_Normal
durationControlSlider.minimumValue = 1
durationControlSlider.maximumValue = 2
durationControlSlider.value = 1
durationControlSlider.addTarget(self, action: #selector(WCLLoadingViewDemoVC.durationSliderValueChange(_:)), for: UIControlEvents.valueChanged)
durationControlView.addSubview(durationControlSlider)
durationControlView.setMaxY(SWIFT_HEIGHT - offY)
}
}
| b6c01f36eaf828716dda7b7c086fabb7 | 39.920635 | 211 | 0.623157 | false | false | false | false |
kingcos/Swift-3-Design-Patterns | refs/heads/master | 20-Command_Pattern.playground/Contents.swift | apache-2.0 | 1 | //: Playground - noun: a place where people can play
// Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Design-Patterns
import UIKit
// 烧烤
struct Barbecuer {
enum BBQ: String {
case mutton = "烤羊肉串"
case chickenWing = "烤鸡翅"
}
var state: BBQ = .mutton
mutating func bakeMutton() {
state = .mutton
print("\(state.rawValue)")
}
mutating func backChickenWing() {
state = .chickenWing
print("\(state.rawValue)")
}
}
// 命令
class Command: Hashable {
var bbq: Barbecuer
init(_ bbq: Barbecuer) {
self.bbq = bbq
}
var hashValue: Int {
return bbq.state.hashValue
}
static func ==(l: Command, r: Command) -> Bool {
return l.hashValue == r.hashValue
}
func executeCommand() {}
}
// 烤羊肉串命令
class BakeMuttonCommand: Command {
override init(_ bbq: Barbecuer) {
super.init(bbq)
self.bbq.state = .mutton
}
override func executeCommand() {
bbq.bakeMutton()
}
}
// 烤鸡翅命令
class BakeChickenWingCommand: Command {
override init(_ bbq: Barbecuer) {
super.init(bbq)
self.bbq.state = .chickenWing
}
override func executeCommand() {
bbq.backChickenWing()
}
}
// 服务员
struct Waiter {
var cmdSet = Set<Command>()
mutating func setOrder(_ command: Command) {
if command.bbq.state == .chickenWing {
print("没有鸡翅了,请点别的烧烤")
} else {
cmdSet.insert(command)
print("增加订单:\(command.bbq.state.rawValue)")
}
}
mutating func removeOrder(_ command: Command) {
cmdSet.remove(command)
print("取消订单:\(command.bbq.state.rawValue)")
}
func notify() {
for command in cmdSet {
command.executeCommand()
}
}
}
let bbq = Barbecuer()
let muttonA = BakeMuttonCommand(bbq)
let muttonB = BakeMuttonCommand(bbq)
let chickenWingA = BakeChickenWingCommand(bbq)
var waiter = Waiter()
waiter.setOrder(muttonA)
waiter.setOrder(muttonB)
waiter.setOrder(chickenWingA)
| ee30d78e9b4b37d89b9904ca4d619f21 | 19.757282 | 90 | 0.587933 | false | false | false | false |
brentsimmons/Evergreen | refs/heads/ios-candidate | Shared/Exporters/OPMLExporter.swift | mit | 1 | //
// OPMLExporter.swift
// NetNewsWire
//
// Created by Brent Simmons on 12/22/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import Account
import RSCore
struct OPMLExporter {
static func OPMLString(with account: Account, title: String) -> String {
let escapedTitle = title.escapingSpecialXMLCharacters
let openingText =
"""
<?xml version="1.0" encoding="UTF-8"?>
<!-- OPML generated by NetNewsWire -->
<opml version="1.1">
<head>
<title>\(escapedTitle)</title>
</head>
<body>
"""
let middleText = account.OPMLString(indentLevel: 0)
let closingText =
"""
</body>
</opml>
"""
let opml = openingText + middleText + closingText
return opml
}
}
| e0c222cedc7986967700b53998b17e51 | 17.390244 | 73 | 0.648541 | false | false | false | false |
burnsra/SquidBar | refs/heads/master | SquidBar/PreferencesController.swift | mit | 1 | //
// PreferencesController.swift
// SquidBar
//
// Created by Robert Burns on 2/11/16.
// Copyright © 2016 Robert Burns. All rights reserved.
//
import Foundation
private let squidExecutableKey = "squidExecutable"
private let squidConfigurationKey = "squidConfiguration"
private let squidLaunchKey = "squidStartOnLaunch"
private let squidWatchNetworkKey = "squidWatchNetwork"
class PreferenceController {
private let userDefaults = NSUserDefaults.standardUserDefaults()
func registerDefaultPreferences() {
let defaults = [ squidExecutableKey : "/usr/local/opt/squid/sbin/squid", squidConfigurationKey : "/usr/local/etc/squid.conf", squidLaunchKey : false, squidWatchNetworkKey : true ]
userDefaults.registerDefaults(defaults)
}
func resetDefaultPreferences() {
userDefaults.removeObjectForKey(squidExecutableKey)
userDefaults.removeObjectForKey(squidConfigurationKey)
userDefaults.removeObjectForKey(squidLaunchKey)
userDefaults.removeObjectForKey(squidWatchNetworkKey)
registerDefaultPreferences()
}
func synchronizePreferences() {
userDefaults.synchronize()
}
init() {
registerDefaultPreferences()
}
var squidExecutable: String? {
set (newSquidExecutable) {
userDefaults.setObject(newSquidExecutable, forKey: squidExecutableKey)
}
get {
return userDefaults.objectForKey(squidExecutableKey) as? String
}
}
var squidConfiguration: String? {
set (newSquidConfiguration) {
userDefaults.setObject(newSquidConfiguration, forKey: squidConfigurationKey)
}
get {
return userDefaults.objectForKey(squidConfigurationKey) as? String
}
}
var squidStartOnLaunch: Bool? {
set (newSquidStartOnLaunch) {
userDefaults.setObject(newSquidStartOnLaunch, forKey: squidLaunchKey)
}
get {
return userDefaults.objectForKey(squidLaunchKey) as? Bool
}
}
var squidWatchNetwork: Bool? {
set (newSquidWatchNetwork) {
userDefaults.setObject(newSquidWatchNetwork, forKey: squidWatchNetworkKey)
}
get {
return userDefaults.objectForKey(squidWatchNetworkKey) as? Bool
}
}
} | c0e895f69e1432214abe1eff2dd848e1 | 29.194805 | 188 | 0.686317 | false | true | false | false |
alblue/swift | refs/heads/master | validation-test/Sema/type_checker_perf/fast/rdar17170728.swift | apache-2.0 | 2 | // RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 -swift-version 5 -solver-disable-shrink -disable-constraint-solver-performance-hacks -solver-enable-operator-designated-types
// REQUIRES: tools-release,no_asserts
let i: Int? = 1
let j: Int?
let k: Int? = 2
let _ = [i, j, k].reduce(0 as Int?) {
$0 != nil && $1 != nil ? $0! + $1! : ($0 != nil ? $0! : ($1 != nil ? $1! : nil))
}
| ec83cbf50d54ad075beb09cd42f7a059 | 39.8 | 200 | 0.632353 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | stdlib/public/core/ArrayType.swift | apache-2.0 | 13 | //===--- ArrayType.swift - Protocol for Array-like types ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_versioned
internal protocol _ArrayProtocol
: RangeReplaceableCollection,
ExpressibleByArrayLiteral
{
//===--- public interface -----------------------------------------------===//
/// The number of elements the Array stores.
var count: Int { get }
/// The number of elements the Array can store without reallocation.
var capacity: Int { get }
/// `true` if and only if the Array is empty.
var isEmpty: Bool { get }
/// An object that guarantees the lifetime of this array's elements.
var _owner: AnyObject? { get }
/// If the elements are stored contiguously, a pointer to the first
/// element. Otherwise, `nil`.
var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? { get }
subscript(index: Int) -> Element { get set }
//===--- basic mutations ------------------------------------------------===//
/// Reserve enough space to store minimumCapacity elements.
///
/// - Postcondition: `capacity >= minimumCapacity` and the array has
/// mutable contiguous storage.
///
/// - Complexity: O(`self.count`).
mutating func reserveCapacity(_ minimumCapacity: Int)
/// Insert `newElement` at index `i`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count`).
///
/// - Precondition: `startIndex <= i`, `i <= endIndex`.
mutating func insert(_ newElement: Element, at i: Int)
/// Remove and return the element at the given index.
///
/// - returns: The removed element.
///
/// - Complexity: Worst case O(*n*).
///
/// - Precondition: `count > index`.
@discardableResult
mutating func remove(at index: Int) -> Element
//===--- implementation detail -----------------------------------------===//
associatedtype _Buffer : _ArrayBufferProtocol
init(_ buffer: _Buffer)
// For testing.
var _buffer: _Buffer { get }
}
extension _ArrayProtocol {
// Since RangeReplaceableCollection now has a version of filter that is less
// efficient, we should make the default implementation coming from Sequence
// preferred.
@_inlineable
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {
return try _filter(isIncluded)
}
}
| 3a268499a8d5149198ed49ff36b76825 | 31.117647 | 80 | 0.612454 | false | false | false | false |
rizumita/CTFeedbackSwift | refs/heads/main | CTFeedbackSwift/FeedbackConfiguration.swift | mit | 1 | //
// Created by 和泉田 領一 on 2017/09/07.
// Copyright (c) 2017 CAPH TECH. All rights reserved.
//
import Foundation
public class FeedbackConfiguration {
public var subject: String?
public var additionalDiagnosticContent: String?
public var toRecipients: [String]
public var ccRecipients: [String]
public var bccRecipients: [String]
public var usesHTML: Bool
public var dataSource: FeedbackItemsDataSource
/*
If topics array contains no topics, topics cell is hidden.
*/
public init(subject: String? = .none,
additionalDiagnosticContent: String? = .none,
topics: [TopicProtocol] = TopicItem.defaultTopics,
toRecipients: [String],
ccRecipients: [String] = [],
bccRecipients: [String] = [],
hidesUserEmailCell: Bool = true,
hidesAttachmentCell: Bool = false,
hidesAppInfoSection: Bool = false,
usesHTML: Bool = false,
appName: String? = nil) {
self.subject = subject
self.additionalDiagnosticContent = additionalDiagnosticContent
self.toRecipients = toRecipients
self.ccRecipients = ccRecipients
self.bccRecipients = bccRecipients
self.usesHTML = usesHTML
self.dataSource = FeedbackItemsDataSource(topics: topics,
hidesUserEmailCell: hidesUserEmailCell,
hidesAttachmentCell: hidesAttachmentCell,
hidesAppInfoSection: hidesAppInfoSection,
appName: appName)
}
}
| 67c2dd6c87e614e41f336739a58258b5 | 41.372093 | 91 | 0.548299 | false | false | false | false |
superk589/CGSSGuide | refs/heads/master | DereGuide/Toolbox/Gacha/Detail/View/GachaCardView.swift | mit | 2 | //
// GachaCardView.swift
// DereGuide
//
// Created by zzk on 2017/7/17.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
class GachaCardView: UIView {
var icon: CGSSCardIconView
var oddsLabel: UILabel
override init(frame: CGRect) {
icon = CGSSCardIconView()
oddsLabel = UILabel()
oddsLabel.adjustsFontSizeToFitWidth = true
oddsLabel.font = UIFont.systemFont(ofSize: 12)
oddsLabel.textColor = .vocal
super.init(frame: frame)
addSubview(oddsLabel)
addSubview(icon)
oddsLabel.snp.makeConstraints { (make) in
make.centerX.bottom.equalToSuperview()
make.left.greaterThanOrEqualToSuperview()
make.right.lessThanOrEqualToSuperview()
make.bottom.equalToSuperview()
}
icon.snp.makeConstraints { (make) in
make.right.left.top.equalToSuperview()
make.height.equalTo(snp.width)
make.bottom.equalTo(oddsLabel.snp.top)
}
}
func setupWith(card: CGSSCard, odds: Int?) {
icon.cardID = card.id
if let odds = odds, odds != 0 {
oddsLabel.text = String(format: "%.3f%%", Double(odds / 10) / 1000)
} else {
oddsLabel.text = "n/a"
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| a68db6465197e642f500129f46e66ea1 | 26.415094 | 79 | 0.58362 | false | false | false | false |
Hansoft/meteor | refs/heads/fav-96944 | cordova-build-release/platforms/ios/Timelines/Plugins/cordova-plugin-meteor-webapp/Utility.swift | agpl-3.0 | 5 | extension Collection {
func find(_ predicate: (Self.Iterator.Element) throws -> Bool) rethrows -> Self.Iterator.Element? {
return try index(where: predicate).map({self[$0]})
}
}
typealias JSONObject = [String:AnyObject]
// Regex that matches the query string part of a URL
let queryStringRegEx = try! NSRegularExpression(pattern: "(/[^?]+).*", options: [])
func URLPathByRemovingQueryString(_ URLString: String) -> String {
guard let match = queryStringRegEx.firstMatchInString(URLString) else {
return URLString
}
return (URLString as NSString).substring(with: match.range(at: 1))
}
// Regex that matches a SHA1 hash
let sha1HashRegEx = try! NSRegularExpression(pattern: "[0-9a-f]{40}", options: [])
// Regex that matches an ETag with a SHA1 hash
let ETagWithSha1HashRegEx = try! NSRegularExpression(pattern: "\"([0-9a-f]{40})\"", options: [])
func SHA1HashFromETag(_ ETag: String) -> String? {
guard let match = ETagWithSha1HashRegEx.firstMatchInString(ETag) else {
return nil
}
return (ETag as NSString).substring(with: match.range(at: 1))
}
extension NSRegularExpression {
func firstMatchInString(_ string: String) -> NSTextCheckingResult? {
return firstMatch(in: string, options: [],
range: NSRange(location: 0, length: string.utf16.count))
}
func matches(_ string: String) -> Bool {
return firstMatchInString(string) != nil
}
}
extension URL {
var isDirectory: Bool? {
let values = try? self.resourceValues(forKeys: [.isDirectoryKey])
return values?.isDirectory
}
var isRegularFile: Bool? {
let values = try? self.resourceValues(forKeys: [.isRegularFileKey])
return values?.isRegularFile
}
}
extension HTTPURLResponse {
var isSuccessful: Bool {
return (200..<300).contains(statusCode)
}
}
| c396d5aec3cbdcb93284430d1c2260f7 | 28.85 | 101 | 0.704634 | false | false | false | false |
csontosgabor/Twitter_Post | refs/heads/master | Twitter_Post/ModalAnimatorPhoto.swift | mit | 1 | //
// ModalAnimatorPhoto.swift
// Transition
//
// Created by Gabor Csontos on 12/22/16.
// Copyright © 2016 GaborMajorszki. All rights reserved.
//
import UIKit
public class ModalAnimatorPhoto {
public class func present(_ toView: UIView, fromView: UIView, completion: @escaping () -> Void) {
let statusBarHeight = UIApplication.shared.statusBarFrame.height
var toViewFrame = fromView.bounds.offsetBy(dx: 0, dy: statusBarHeight + fromView.bounds.size.height)
toViewFrame.size.height = toViewFrame.size.height
toView.frame = toViewFrame
toView.alpha = 0.0
fromView.addSubview(toView)
UIView.animate(
withDuration: 0.2,
animations: { () -> Void in
let statusBarHeight = UIApplication.shared.statusBarFrame.height
let toViewFrame = fromView.bounds.offsetBy(dx: 0, dy: statusBarHeight + fromView.bounds.size.height / 2.0 + 4)
toView.frame = toViewFrame
toView.alpha = 1.0
}) { (result) -> Void in
completion()
}
}
public class func dismiss(_ toView: UIView, fromView: UIView, completion: @escaping () -> Void) {
//Checking PhotoAutorizationStatus
if PhotoAutorizationStatusCheck() {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
let statusBarHeight = UIApplication.shared.statusBarFrame.height
let toViewFrame = fromView.bounds.offsetBy(dx: 0, dy: statusBarHeight + fromView.bounds.size.height / 2.0 + 4)
toView.frame = toViewFrame
}) { (result) -> Void in
completion()
}
} else {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
let toViewFrame = fromView.bounds.offsetBy(dx: 0, dy: fromView.bounds.size.height - 44)
toView.frame = toViewFrame
}) { (result) -> Void in
completion()
}
}
}
public class func dismissOnBottom(_ toView: UIView, fromView: UIView, completion: @escaping () -> Void) {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
let toViewFrame = fromView.bounds.offsetBy(dx: 0, dy: fromView.bounds.size.height - 44)
toView.frame = toViewFrame
}) { (result) -> Void in
completion()
}
}
public class func showOnfullScreen(_ toView: UIView, fromView: UIView, completion: @escaping () -> Void) {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
let statusBarHeight = UIApplication.shared.statusBarFrame.height
let toViewFrame = fromView.bounds.offsetBy(dx: 0, dy: statusBarHeight)
toView.frame = toViewFrame
}) { (result) -> Void in
completion()
}
}
}
| 0d3fc072ea90840cd59420e323e50709 | 29.008929 | 126 | 0.51205 | false | false | false | false |
bsmith11/ScoreReporter | refs/heads/master | ScoreReporterCore/ScoreReporterCore/Extensions/String+Extensions.swift | mit | 1 | //
// String+Extensions.swift
// ScoreReporter
//
// Created by Bradley Smith on 7/19/16.
// Copyright © 2016 Brad Smith. All rights reserved.
//
import Foundation
public extension String {
func matching(regexPattern: String) -> String? {
var strings = [String]()
do {
let regex = try NSRegularExpression(pattern: regexPattern, options: .caseInsensitive)
let options: NSRegularExpression.MatchingOptions = .reportProgress
let range = NSRange(location: 0, length: (self as NSString).length)
regex.enumerateMatches(in: self, options: options, range: range) { (result: NSTextCheckingResult?, _, _) in
if let result = result {
let match = (self as NSString).substring(with: result.range)
strings.append(match)
}
}
return strings.first
}
catch let error {
print("Failed to create regular expression with pattern: \(regexPattern) error: \(error)")
return nil
}
}
}
| 57c280d2324c5c77df216d84a141e707 | 30 | 119 | 0.589862 | false | false | false | false |
lfaoro/Cast | refs/heads/master | Cast/MenuSendersAction.swift | mit | 1 | //
// Created by Leonardo on 18/07/2015.
// Copyright © 2015 Leonardo Faoro. All rights reserved.
//
import Cocoa
import RxSwift
final class MenuSendersAction: NSObject {
let shortenClient = ShortenClient()
func shareClipboardContentsAction(sender: NSMenuItem) {
let _ = PasteboardClient.getPasteboardItems()
.debug("getPasteboardItems")
.subscribe(next: { value in
switch value {
case .Text(let item):
app.gistClient.setGist(content: item, isPublic: app.prefs.gistIsPublic!)
.debug("setGist")
.retry(3)
.flatMap { self.shortenClient.shorten(URL: $0) }
.subscribe { event in
switch event {
case .Next(let URL):
if let URL = URL {
PasteboardClient.putInPasteboard(items: [URL])
app.userNotification.pushNotification(openURL: URL)
} else {
app.userNotification.pushNotification(error: "Unable to Shorten URL")
}
case .Completed:
app.statusBarItem.menu = createMenu(self)
case .Error(let error):
app.userNotification.pushNotification(error: String(error))
}
}
case .File(let file):
print(file.path!)
default: break
}
})
}
func updateGistAction(sender: NSMenuItem) {
let _ = PasteboardClient.getPasteboardItems()
.debug("getPasteboardItems")
.subscribe(next: { value in
switch value {
case .Text(let item):
app.gistClient.setGist(content: item,
updateGist: true,
isPublic: app.prefs.gistIsPublic!)
.debug("setGist")
.retry(3)
.flatMap { self.shortenClient.shorten(URL: $0) }
.subscribe { event in
switch event {
case .Next(let URL):
if let URL = URL {
PasteboardClient.putInPasteboard(items: [URL])
app.userNotification.pushNotification(openURL: URL)
} else {
app.userNotification.pushNotification(error: "Unable to Shorten URL")
}
case .Completed:
app.statusBarItem.menu = createMenu(self)
case .Error(let error):
app.userNotification.pushNotification(error: String(error))
}
}
case .File(let file):
print(file.path!)
default: break
}
})
}
func shortenURLAction(sender: NSMenuItem) {
let _ = PasteboardClient.getPasteboardItems()
.debug("getPasteboardItems")
.subscribe(next: { value in
switch value {
case .Text(let item):
guard let url = NSURL(string: item) else { fallthrough }
self.shortenClient.shorten(URL: url)
.subscribe { event in
switch event {
case .Next(let shortenedURL):
guard let URL = shortenedURL else { fallthrough }
PasteboardClient.putInPasteboard(items: [URL])
app.userNotification.pushNotification(openURL: URL,
title: "Shortened with \(app.prefs.shortenService!)")
case .Completed:
print("completed")
case .Error(let error):
print("\(error)")
}
}
default:
app.userNotification.pushNotification(error: "Not a valid URL")
}
})
}
func loginToGithub(sender: NSMenuItem) {
app.oauth.authorize()
}
func logoutFromGithub(sender: NSMenuItem) {
if let error = OAuthClient.revoke() {
app.userNotification.pushNotification(error: error.localizedDescription)
} else {
app.statusBarItem.menu = createMenu(app.menuSendersAction)
app.userNotification.pushNotification(error: "GitHub Authentication",
description: "API key revoked internally")
}
}
func recentUploadsAction(sender: NSMenuItem) {
if let url = sender.representedObject as? NSURL {
NSWorkspace.sharedWorkspace().openURL(url)
} else {
fatalError("No link in recent uploads")
}
}
func clearItemsAction(sender: NSMenuItem) {
if app.prefs.recentActions!.count > 0 {
app.prefs.recentActions!.removeAll()
Swift.print(app.prefs.recentActions!)
app.statusBarItem.menu = createMenu(app.menuSendersAction)
}
}
func startAtLoginAction(sender: NSMenuItem) {
if sender.state == 0 {
sender.state = 1
} else {
sender.state = 0
}
}
func optionsAction(sender: NSMenuItem) {
NSApp.activateIgnoringOtherApps(true)
app.optionsWindowController.showWindow(nil)
}
}
| 94f6f96b8325131a14d44ced949d8dbe | 23.410405 | 78 | 0.656405 | false | false | false | false |
BBBInc/AlzPrevent-ios | refs/heads/master | researchline/LoginViewController.swift | bsd-3-clause | 1 | //
// LoginViewController.swift
// researchline
//
// Created by riverleo on 2015. 11. 8..
// Copyright © 2015년 bbb. All rights reserved.
//
import UIKit
import Alamofire
class LoginViewController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var doneBarButtonItem: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBarHidden = false
}
// MARK: IBAction Methods
@IBAction func editChangedTextField(sender: UITextField) {
doneBarButtonItem.enabled = !emailTextField.text!.isEmpty && !passwordTextField.text!.isEmpty
}
@IBAction func passwordChanged(sender: AnyObject) {
doneBarButtonItem.enabled = !emailTextField.text!.isEmpty && !passwordTextField.text!.isEmpty
}
@IBAction func touchUpInsideDoneBarButtonItem(sender: UIBarButtonItem) {
sender.enabled = false
Alamofire.request(.POST, Constants.login,
parameters: [
"email": emailTextField.text ?? "",
"password": passwordTextField.text ?? ""
],
headers: [
"deviceKey": Constants.deviceKey,
"deviceType": Constants.deviceType
])
.responseJSON { (response: Response) -> Void in
debugPrint(response)
sender.enabled = true
switch response.result {
case .Success:
switch response.response!.statusCode {
case 200:
// save the sign key
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(response.result.value!["signKey"]!, forKey: "signKey")
userDefaults.setObject(self.emailTextField.text, forKey: "email")
Constants.userDefaults.setObject(Constants.STEP_FINISHED, forKey: "registerStep")
// shows tab bar
let storyboard = UIStoryboard(name: "TabBar", bundle: nil)
let controller = storyboard.instantiateInitialViewController()!
self.presentViewController(controller, animated: true, completion: nil)
break
default:
let alertView = UIAlertView(title: nil, message: response.result.value!["message"] as? String, delegate: nil, cancelButtonTitle: "Okay")
alertView.show()
break
}
break
case .Failure:
let alertView = UIAlertView(title: "Server Error", message: nil, delegate: nil, cancelButtonTitle: "Okay")
alertView.show()
break
}
}
}
} | 244d4b506935abd56288f152c5a2e4de | 37.556962 | 160 | 0.552709 | false | false | false | false |
brentdax/swift | refs/heads/master | test/SILGen/protocol_class_refinement.swift | apache-2.0 | 1 | // RUN: %target-swift-emit-silgen -enable-sil-ownership %s | %FileCheck %s
protocol UID {
func uid() -> Int
var clsid: Int { get set }
var iid: Int { get }
}
extension UID {
var nextCLSID: Int {
get { return clsid + 1 }
set { clsid = newValue - 1 }
}
}
protocol ObjectUID : class, UID {}
extension ObjectUID {
var secondNextCLSID: Int {
get { return clsid + 2 }
set { }
}
}
class Base {}
// CHECK-LABEL: sil hidden @$s25protocol_class_refinement12getObjectUID{{[_0-9a-zA-Z]*}}F
func getObjectUID<T: ObjectUID>(x: T) -> (Int, Int, Int, Int) {
var x = x
// CHECK: [[XBOX:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : ObjectUID> { var τ_0_0 } <T>
// CHECK: [[PB:%.*]] = project_box [[XBOX]]
// -- call x.uid()
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: destroy_addr [[X_TMP]]
// -- call set x.clsid
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T
// CHECK: [[SET_CLSID:%.*]] = witness_method $T, #UID.clsid!setter.1
// CHECK: apply [[SET_CLSID]]<T>([[UID]], [[WRITE]])
x.clsid = x.uid()
// -- call x.uid()
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: destroy_addr [[X_TMP]]
// -- call nextCLSID from protocol ext
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T
// CHECK: [[SET_NEXTCLSID:%.*]] = function_ref @$s25protocol_class_refinement3UIDPAAE9nextCLSIDSivs
// CHECK: apply [[SET_NEXTCLSID]]<T>([[UID]], [[WRITE]])
x.nextCLSID = x.uid()
// -- call x.uid()
// CHECK: [[READ1:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X1:%.*]] = load [copy] [[READ1]]
// CHECK: [[BORROWED_X1:%.*]] = begin_borrow [[X1]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: destroy_addr [[X_TMP]]
// -- call secondNextCLSID from class-constrained protocol ext
// CHECK: [[SET_SECONDNEXT:%.*]] = function_ref @$s25protocol_class_refinement9ObjectUIDPAAE15secondNextCLSIDSivs
// CHECK: apply [[SET_SECONDNEXT]]<T>([[UID]], [[BORROWED_X1]])
// CHECK: end_borrow [[BORROWED_X1]]
// CHECK: destroy_value [[X1]]
x.secondNextCLSID = x.uid()
return (x.iid, x.clsid, x.nextCLSID, x.secondNextCLSID)
// CHECK: return
}
// CHECK-LABEL: sil hidden @$s25protocol_class_refinement16getBaseObjectUID{{[_0-9a-zA-Z]*}}F
func getBaseObjectUID<T: UID>(x: T) -> (Int, Int, Int) where T: Base {
var x = x
// CHECK: [[XBOX:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : Base, τ_0_0 : UID> { var τ_0_0 } <T>
// CHECK: [[PB:%.*]] = project_box [[XBOX]]
// -- call x.uid()
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: destroy_addr [[X_TMP]]
// -- call set x.clsid
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T
// CHECK: [[SET_CLSID:%.*]] = witness_method $T, #UID.clsid!setter.1
// CHECK: apply [[SET_CLSID]]<T>([[UID]], [[WRITE]])
x.clsid = x.uid()
// -- call x.uid()
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: destroy_addr [[X_TMP]]
// -- call nextCLSID from protocol ext
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T
// CHECK: [[SET_NEXTCLSID:%.*]] = function_ref @$s25protocol_class_refinement3UIDPAAE9nextCLSIDSivs
// CHECK: apply [[SET_NEXTCLSID]]<T>([[UID]], [[WRITE]])
x.nextCLSID = x.uid()
return (x.iid, x.clsid, x.nextCLSID)
// CHECK: return
}
| f393c040b95678f4aaaa136faa70eab4 | 38.361345 | 115 | 0.541845 | false | false | false | false |
hanwanjie853710069/iMessageTest | refs/heads/master | SmilLoveTwo/MessagesExtension/MessagesViewController.swift | apache-2.0 | 1 | //
// MessagesViewController.swift
// MessagesExtension
//
// Created by Mr.H on 2017/7/31.
// Copyright © 2017年 Mr.H. All rights reserved.
//
import UIKit
import Messages
class MessagesViewController: MSMessagesAppViewController {
override func viewDidLoad() {
super.viewDidLoad()
creatMessageBtn()
}
/// 创建
func creatMessageBtn() {
let creatBtn = UIButton(frame: CGRect(x: 100, y: 30, width: 200, height: 200))
creatBtn.addTarget(self, action: #selector(touchBtn), for: .touchUpInside)
creatBtn.backgroundColor = UIColor.brown
creatBtn.setTitle("创建Message按钮", for: .normal)
view.addSubview(creatBtn)
}
/// 创建表情点击事件
func touchBtn() {
if let image = creatImage(), let conversation = activeConversation {
let layout = MSMessageTemplateLayout()
layout.image = image
layout.caption = "Stepper Value"
layout.subcaption = "subcaption"
layout.trailingCaption = "trailingCaption"
layout.trailingSubcaption = "trailingSubcaption"
let message = MSMessage()
message.layout = layout
message.url = URL(string: "emptyURL")
conversation.insert(message, completionHandler: { (error: NSError?) in
} as? (Error?) -> Void)
}
}
func creatImage() -> UIImage? {
let background = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
background.backgroundColor = UIColor.red
let label = UILabel(frame: CGRect(x: 75, y: 75, width: 150, height: 150))
label.font = UIFont.systemFont(ofSize: 56.0)
label.backgroundColor = UIColor.brown
label.textColor = UIColor.white
label.text = "Message"
label.textAlignment = .center
label.layer.cornerRadius = label.frame.size.width/2.0
label.clipsToBounds = true
background.addSubview(label)
background.frame.origin = CGPoint(x: view.frame.size.width, y: view.frame.size.height)
view.addSubview(background)
UIGraphicsBeginImageContextWithOptions(background.frame.size, false, UIScreen.main.scale)
background.drawHierarchy(in: background.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
background.removeFromSuperview()
return image
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Conversation Handling
override func willBecomeActive(with conversation: MSConversation) {
// Called when the extension is about to move from the inactive to active state.
// This will happen when the extension is about to present UI.
// Use this method to configure the extension and restore previously stored state.
}
override func didResignActive(with conversation: MSConversation) {
// Called when the extension is about to move from the active to inactive state.
// This will happen when the user dissmises the extension, changes to a different
// conversation or quits Messages.
// Use this method to release shared resources, save user data, invalidate timers,
// and store enough state information to restore your extension to its current state
// in case it is terminated later.
}
override func didReceive(_ message: MSMessage, conversation: MSConversation) {
// Called when a message arrives that was generated by another instance of this
// extension on a remote device.
// Use this method to trigger UI updates in response to the message.
}
override func didStartSending(_ message: MSMessage, conversation: MSConversation) {
// Called when the user taps the send button.
}
override func didCancelSending(_ message: MSMessage, conversation: MSConversation) {
// Called when the user deletes the message without sending it.
// Use this to clean up state related to the deleted message.
}
override func willTransition(to presentationStyle: MSMessagesAppPresentationStyle) {
// Called before the extension transitions to a new presentation style.
// Use this method to prepare for the change in presentation style.
}
override func didTransition(to presentationStyle: MSMessagesAppPresentationStyle) {
// Called after the extension transitions to a new presentation style.
// Use this method to finalize any behaviors associated with the change in presentation style.
}
}
| db358add7f4ca83d619257a6c5bc9035 | 34.21831 | 102 | 0.633473 | false | false | false | false |
GuiminChu/HishowZone-iOS | refs/heads/master | HiShow/Features/Topics/TopicModel.swift | mit | 1 | //
// TopicModel.swift
// HiShow
//
// Created by Chu Guimin on 16/9/6.
// Copyright © 2016年 Chu Guimin. All rights reserved.
//
import Foundation
import SwiftyJSON
enum RefreshStatus {
case none
case pullSucess(hasMoreData: Bool)
case loadSucess(hasMoreData: Bool)
case error(message: String?)
}
let activityInfoStoreDidChangedNotification = "com.mst.MyRunning.ActivityInfoStoreDidChangedNotification"
class TopicItemStore {
static let shared = TopicItemStore()
private var topics = [Topic]()
private init() {}
private var refreshStatus = RefreshStatus.none {
didSet {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: activityInfoStoreDidChangedNotification), object: self, userInfo: [activityInfoStoreDidChangedNotification: refreshStatus])
}
}
var count: Int {
return topics.count
}
var start = 0 {
didSet {
request(start: start)
}
}
func topic(at index: Int) -> Topic {
return topics[index]
}
func request(start: Int) {
HiShowAPI.sharedInstance.getTopics(start: start, completion: { topicModel in
let hasMoreData = topicModel.topics.count < 20
if start == 0 {
self.topics = topicModel.topics
self.refreshStatus = RefreshStatus.pullSucess(hasMoreData: hasMoreData)
} else {
self.topics += topicModel.topics
self.refreshStatus = RefreshStatus.loadSucess(hasMoreData: hasMoreData)
}
}, failureHandler: { (reason, errorMessage) in
self.refreshStatus = RefreshStatus.error(message: errorMessage)
})
}
}
struct TopicModel {
var count: Int!
var start: Int!
var topics: [Topic]!
var total: Int!
init(fromJson json: JSON) {
if json == JSON.null {
return
}
count = json["count"].intValue
start = json["start"].intValue
total = json["total"].intValue
topics = [Topic]()
let topicsArray = json["topics"].arrayValue
for topicsJson in topicsArray {
let value = Topic(fromJson: topicsJson)
// 只展现有照片的话题
if value.photos.count > 0 {
// 过滤掉某些没有营养的广告贴
if value.id != "97583616" && value.id != "79786668" && value.id != "96555462" && value.id != "95243968" && value.id != "91716032" {
topics.append(value)
}
}
}
}
}
struct Topic {
var id: String!
var alt: String!
var author: Author!
var commentsCount: Int!
var content: String!
var created: String!
var likeCount: Int!
var photos: [Photo]!
var title: String!
var updated: String!
init(fromJson json: JSON) {
if json == JSON.null {
return
}
id = json["id"].stringValue
alt = json["alt"].stringValue
title = json["title"].stringValue
content = json["content"].stringValue
created = json["created"].stringValue
updated = json["updated"].stringValue
likeCount = json["like_count"].intValue
commentsCount = json["comments_count"].intValue
let authorJson = json["author"]
if authorJson != JSON.null {
author = Author(fromJson: authorJson)
}
photos = [Photo]()
let photosArray = json["photos"].arrayValue
for photosJson in photosArray {
let value = Photo(fromJson: photosJson)
photos.append(value)
}
}
}
struct Photo {
var id: String?
var alt: String?
var authorId: String?
var creationDate: String?
var seqId: String?
var title: String?
var topicId: String?
var size: PhotoSize!
init(fromJson json: JSON) {
if json == JSON.null {
return
}
id = json["id"].stringValue
alt = json["alt"].stringValue
seqId = json["seq_id"].stringValue
title = json["title"].stringValue
topicId = json["topic_id"].stringValue
authorId = json["author_id"].stringValue
creationDate = json["creation_date"].stringValue
let sizeJson = json["size"]
if !sizeJson.isEmpty {
size = PhotoSize(fromJson: sizeJson)
}
}
}
struct PhotoSize {
var height: Int = 1
var width: Int = 1
init(fromJson json: JSON) {
if json.isEmpty {
return
}
height = json["height"].intValue
width = json["width"].intValue
}
}
/**
* 作者
*/
struct Author {
var id: String?
var avatar: String?
var largeAvatar: String?
var isSuicide: Bool?
/// 主页地址
var alt: String?
/// 昵称
var name: String?
init(fromJson json: JSON) {
if json == JSON.null {
return
}
id = json["id"].stringValue
alt = json["alt"].stringValue
name = json["name"].stringValue
avatar = json["avatar"].stringValue
isSuicide = json["is_suicide"].boolValue
largeAvatar = json["large_avatar"].stringValue
}
}
| af30122bb2ff77d243a302512fb979c1 | 24.990476 | 203 | 0.546354 | false | false | false | false |
nodes-ios/NStackSDK | refs/heads/master | LocalizationsGenerator/Classes/Other/HTTPMethod.swift | mit | 2 | //
// HTTPMethod.swift
// NStackSDK
//
// Created by Dominik Hadl on 25/09/2018.
// Copyright © 2018 Nodes ApS. All rights reserved.
//
import Foundation
public enum HTTPMethod: String {
case get = "GET"
case patch = "PATCH"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
}
| 329d1e303e6e65bdcf1c26c776ca8f09 | 17.352941 | 52 | 0.628205 | false | false | false | false |
Feyluu/DouYuZB | refs/heads/master | DouYuZB/DouYuZB/Classes/Tools/NetworkTools.swift | mit | 1 | //
// 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)
}
}
}
| 36849d0c69b3bd1163c0cb0fc2297031 | 26.46875 | 151 | 0.61661 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new | refs/heads/master | Source/CourseCatalogViewController.swift | apache-2.0 | 2 | //
// CourseCatalogViewController.swift
// edX
//
// Created by Akiva Leffert on 11/30/15.
// Copyright © 2015 edX. All rights reserved.
//
import UIKit
class CourseCatalogViewController: UIViewController, CoursesTableViewControllerDelegate {
typealias Environment = protocol<NetworkManagerProvider, OEXRouterProvider, OEXSessionProvider, OEXConfigProvider, OEXAnalyticsProvider>
private let environment : Environment
private let tableController : CoursesTableViewController
private let loadController = LoadStateViewController()
private let insetsController = ContentInsetsController()
init(environment : Environment) {
self.environment = environment
self.tableController = CoursesTableViewController(environment: environment, context: .CourseCatalog)
super.init(nibName: nil, bundle: nil)
self.navigationItem.title = Strings.findCourses
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var paginationController : PaginationController<OEXCourse> = {
let username = self.environment.session.currentUser?.username ?? ""
precondition(username != "", "Shouldn't be showing course catalog without a logged in user")
let organizationCode = self.environment.config.organizationCode()
let paginator = WrappedPaginator(networkManager: self.environment.networkManager) { page in
return CourseCatalogAPI.getCourseCatalog(username, page: page, organizationCode: organizationCode)
}
return PaginationController(paginator: paginator, tableView: self.tableController.tableView)
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.accessibilityIdentifier = "course-catalog-screen";
addChildViewController(tableController)
tableController.didMoveToParentViewController(self)
self.loadController.setupInController(self, contentView: tableController.view)
self.view.addSubview(tableController.view)
tableController.view.snp_makeConstraints {make in
make.edges.equalTo(self.view)
}
self.view.backgroundColor = OEXStyles.sharedStyles().standardBackgroundColor()
tableController.delegate = self
paginationController.stream.listen(self, success:
{[weak self] courses in
self?.loadController.state = .Loaded
self?.tableController.courses = courses
self?.tableController.tableView.reloadData()
}, failure: {[weak self] error in
self?.loadController.state = LoadState.failed(error)
}
)
paginationController.loadMore()
insetsController.setupInController(self, scrollView: tableController.tableView)
insetsController.addSource(
// add a little padding to the bottom since we have a big space between
// each course card
ConstantInsetsSource(insets: UIEdgeInsets(top: 0, left: 0, bottom: StandardVerticalMargin, right: 0), affectsScrollIndicators: false)
)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
environment.analytics.trackScreenWithName(OEXAnalyticsScreenFindCourses)
}
func coursesTableChoseCourse(course: OEXCourse) {
guard let courseID = course.course_id else {
return
}
self.environment.router?.showCourseCatalogDetail(courseID, fromController:self)
}
}
// Testing only
extension CourseCatalogViewController {
var t_loaded : Stream<()> {
return self.paginationController.stream.map {_ in
return
}
}
}
| bd2f4c71c6b5b2dbf879fac8a0dc9d11 | 38.727273 | 145 | 0.687007 | false | false | false | false |
Killectro/RxGrailed | refs/heads/master | RxGrailed/RxGrailedTests/ViewModels/ListingsViewModelSpec.swift | mit | 1 | //
// ListingsViewModelSpec.swift
// RxGrailed
//
// Created by DJ Mitchell on 2/28/17.
// Copyright © 2017 Killectro. All rights reserved.
//
import Foundation
import Quick
import Nimble
import Mapper
import RxSwift
@testable
import RxGrailed
func testListingJSON() -> [String : Any] {
return [
"id" : 12345,
"retina_cover_photo" : [
"url" : "https://static.highsnobiety.com/wp-content/uploads/2016/10/02112116/cost-of-house-with-supreme-bricks-0.jpg"
],
"price_i" : 300,
"designer_names" : "Supreme",
"title" : "Supreme Brick",
"description" : "Literally just a brick",
"size" : "one size",
"user" : [
"username" : "not_YMBAPE"
]
]
}
class ListingsViewModelSpec: QuickSpec {
override func spec() {
var viewModel: ListingsViewModel!
var paginate: PublishSubject<Void>!
var disposeBag: DisposeBag!
beforeEach {
viewModel = ListingsViewModel(networkModel: MockGrailedNetworkModel())
paginate = PublishSubject()
disposeBag = DisposeBag()
}
it("loads a first page") {
viewModel.setupObservables(paginate: paginate.asObservable())
waitUntil { done in
viewModel.listings
.subscribe(onNext: { listings in
expect(listings).toNot(beEmpty())
expect(listings.count) == 5
done()
})
.disposed(by: disposeBag)
}
}
it("loads a second page when pagination occurs") {
viewModel.setupObservables(paginate: paginate.asObservable())
waitUntil { done in
viewModel.listings
.mapWithIndex { ($0, $1) }
.subscribe(onNext: { listings, index in
expect(listings).toNot(beEmpty())
expect(listings.count) == 5 * (index + 1)
if index == 1 {
done()
}
})
.disposed(by: disposeBag)
paginate.onNext(())
}
}
}
}
private class MockGrailedNetworkModel: GrailedNetworkModelable {
fileprivate func getListings(paginate: Observable<Void>, loadedSoFar: [Listing]) -> Observable<[Listing]> {
let listings = (0..<5).map { _ in
try! Listing(
map: Mapper(JSON: testListingJSON() as NSDictionary)
)
}
return Observable.of(listings).flatMap { listings -> Observable<[Listing]> in
let newListings = loadedSoFar + listings
let obs = [
// Return our current list of Listings
Observable.just(newListings),
// Wait until we are told to paginate
Observable.never().takeUntil(paginate),
// Retrieve the next list of listings
self.getListings(paginate: paginate, loadedSoFar: newListings)
]
return Observable.concat(obs)
}
}
}
| 7d502f10d25de39a552575ae94bbb0e7 | 28.495413 | 129 | 0.523173 | false | false | false | false |
nicadre/SwiftyProtein | refs/heads/master | SwiftyProtein/Controllers/PopOverViewController.swift | gpl-3.0 | 1 | //
// PopOverController.swift
// SwiftyProtein
//
// Created by Leo LAPILLONNE on 7/20/16.
// Copyright © 2016 Nicolas CHEVALIER. All rights reserved.
//
import UIKit
class PopOverViewController: UIViewController {
@IBOutlet weak var chemicalIdLabel: UILabel!
@IBOutlet weak var typeLabel: UILabel!
@IBOutlet weak var weightLabel: UILabel!
@IBOutlet weak var chemicalNameLabel: UILabel!
@IBOutlet weak var formulaLabel: UILabel!
var chemicalId: String = ""
var type: String = ""
var weight: String = ""
var chemicalName: String = ""
var formula: String = ""
override func viewDidLoad() {
super.viewDidLoad()
self.chemicalIdLabel.text = "\(chemicalId)"
self.typeLabel.text = "\(type)"
self.weightLabel.text = "\(weight)"
self.chemicalNameLabel.text = "\(chemicalName)"
self.formulaLabel.text = "\(formula)"
}
}
| eb832fe4d6fef47cea0066d6864cacdd | 25.277778 | 60 | 0.637421 | false | false | false | false |
edx/edx-app-ios | refs/heads/master | Source/AuthenticatedWebViewController.swift | apache-2.0 | 1 | //
// AuthenticatedWebViewController.swift
// edX
//
// Created by Akiva Leffert on 5/26/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
import WebKit
class HeaderViewInsets : ContentInsetsSource {
weak var insetsDelegate : ContentInsetsSourceDelegate?
var view : UIView?
var currentInsets : UIEdgeInsets {
return UIEdgeInsets(top : view?.frame.size.height ?? 0, left : 0, bottom : 0, right : 0)
}
var affectsScrollIndicators : Bool {
return true
}
}
private protocol WebContentController {
var view : UIView {get}
var scrollView : UIScrollView {get}
var isLoading: Bool {get}
var alwaysRequiresOAuthUpdate : Bool { get}
var initialContentState : AuthenticatedWebViewController.State { get }
func loadURLRequest(request : NSURLRequest)
func resetState()
}
@objc protocol WebViewNavigationDelegate: AnyObject {
func webView(_ webView: WKWebView, shouldLoad request: URLRequest) -> Bool
func webViewContainingController() -> UIViewController
}
// A class should implement AlwaysRequireAuthenticationOverriding protocol if it always require authentication.
protocol AuthenticatedWebViewControllerRequireAuthentication {
func alwaysRequireAuth() -> Bool
}
protocol AuthenticatedWebViewControllerDelegate: AnyObject {
func authenticatedWebViewController(authenticatedController: AuthenticatedWebViewController, didFinishLoading webview: WKWebView)
}
@objc protocol AJAXCompletionCallbackDelegate: AnyObject {
func didCompletionCalled(completion: Bool)
}
protocol WebViewNavigationResponseDelegate: AnyObject {
func handleHttpStatusCode(statusCode: OEXHTTPStatusCode) -> Bool
}
private class WKWebViewContentController : WebContentController {
fileprivate let webView: WKWebView
var view : UIView {
return webView
}
var scrollView : UIScrollView {
return webView.scrollView
}
init(configuration: WKWebViewConfiguration) {
webView = WKWebView(frame: .zero, configuration: configuration)
}
func loadURLRequest(request: NSURLRequest) {
webView.load(request as URLRequest)
}
func resetState() {
webView.stopLoading()
webView.loadHTMLString("", baseURL: nil)
}
var alwaysRequiresOAuthUpdate : Bool {
return false
}
var initialContentState : AuthenticatedWebViewController.State {
return AuthenticatedWebViewController.State.LoadingContent
}
var isLoading: Bool {
return webView.isLoading
}
}
private let OAuthExchangePath = "/oauth2/login/"
fileprivate let AJAXCallBackHandler = "ajaxCallbackHandler"
fileprivate let ajaxScriptFile = "ajaxHandler"
// Allows access to course content that requires authentication.
// Forwarding our oauth token to the server so we can get a web based cookie
public class AuthenticatedWebViewController: UIViewController, WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler {
fileprivate enum xBlockCompletionCallbackType: String {
case html = "publish_completion"
case problem = "problem_check"
case dragAndDrop = "do_attempt"
case ora = "render_grade"
}
fileprivate enum State {
case CreatingSession
case LoadingContent
case NeedingSession
}
public typealias Environment = OEXAnalyticsProvider & OEXConfigProvider & OEXSessionProvider & ReachabilityProvider
weak var delegate: AuthenticatedWebViewControllerDelegate?
internal let environment : Environment
private let loadController : LoadStateViewController
private let insetsController : ContentInsetsController
private let headerInsets : HeaderViewInsets
weak var webViewDelegate: WebViewNavigationDelegate?
weak var ajaxCallbackDelegate: AJAXCompletionCallbackDelegate?
weak var webViewNavigationResponseDelegate: WebViewNavigationResponseDelegate?
private lazy var configurations = environment.config.webViewConfiguration()
private var shouldListenForAjaxCallbacks = false
private lazy var webController: WebContentController = {
let controller = WKWebViewContentController(configuration: configurations)
if shouldListenForAjaxCallbacks {
addAjaxCallbackScript(in: configurations.userContentController)
}
controller.webView.navigationDelegate = self
controller.webView.uiDelegate = self
return controller
}()
var scrollView: UIScrollView {
return webController.scrollView
}
private var state = State.CreatingSession
private var contentRequest : NSURLRequest? = nil
var currentUrl: NSURL? {
return contentRequest?.url as NSURL?
}
public func setLoadControllerState(withState state: LoadState) {
loadController.state = state
}
public init(environment : Environment, shouldListenForAjaxCallbacks: Bool = false) {
self.environment = environment
self.shouldListenForAjaxCallbacks = shouldListenForAjaxCallbacks
loadController = LoadStateViewController()
insetsController = ContentInsetsController()
headerInsets = HeaderViewInsets()
insetsController.addSource(source: headerInsets)
super.init(nibName: nil, bundle: nil)
scrollView.contentInsetAdjustmentBehavior = .automatic
webController.view.accessibilityIdentifier = "AuthenticatedWebViewController:authenticated-web-view"
addObservers()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
// Prevent crash due to stale back pointer, since WKWebView's UIScrollView apparently doesn't
// use weak for its delegate
webController.scrollView.delegate = nil
NotificationCenter.default.removeObserver(self)
}
override public func viewDidLoad() {
super.viewDidLoad()
state = webController.initialContentState
view.addSubview(webController.view)
webController.view.snp.makeConstraints { make in
make.edges.equalTo(safeEdges)
}
loadController.setupInController(controller: self, contentView: webController.view)
webController.view.backgroundColor = OEXStyles.shared().standardBackgroundColor()
webController.scrollView.backgroundColor = OEXStyles.shared().standardBackgroundColor()
insetsController.setupInController(owner: self, scrollView: webController.scrollView)
if let request = contentRequest {
loadRequest(request: request)
}
}
private func addObservers() {
NotificationCenter.default.oex_addObserver(observer: self, name: NOTIFICATION_DYNAMIC_TEXT_TYPE_UPDATE) { (_, observer, _) in
observer.reload()
}
}
private func addAjaxCallbackScript(in contentController: WKUserContentController) {
guard let url = Bundle.main.url(forResource: ajaxScriptFile, withExtension: "js"),
let handler = try? String(contentsOf: url, encoding: .utf8) else { return }
let script = WKUserScript(source: handler, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
contentController.add(self, name: AJAXCallBackHandler)
contentController.addUserScript(script)
}
public func reload() {
guard let request = contentRequest, !webController.isLoading else { return }
state = .LoadingContent
loadRequest(request: request)
}
private func resetState() {
loadController.state = .Initial
state = .CreatingSession
}
public override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
if view.window == nil {
webController.resetState()
}
resetState()
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if headerView != nil {
insetsController.updateInsets()
}
}
public func showError(error : NSError?, icon : Icon? = nil, message : String? = nil) {
let buttonInfo = MessageButtonInfo(title: Strings.reload) {[weak self] in
if let request = self?.contentRequest, self?.environment.reachability.isReachable() ?? false {
self?.loadController.state = .Initial
self?.webController.loadURLRequest(request: request)
}
}
loadController.state = LoadState.failed(error: error, icon: icon, message: message, buttonInfo: buttonInfo)
refreshAccessibility()
}
public func showError(with state: LoadState) {
loadController.state = state
refreshAccessibility()
}
// MARK: Header View
var headerView : UIView? {
get {
return headerInsets.view
}
set {
headerInsets.view?.removeFromSuperview()
headerInsets.view = newValue
if let headerView = newValue {
webController.view.addSubview(headerView)
headerView.snp.makeConstraints { make in
make.top.equalTo(safeTop)
make.leading.equalTo(webController.view)
make.trailing.equalTo(webController.view)
}
webController.view.setNeedsLayout()
webController.view.layoutIfNeeded()
}
}
}
private func loadOAuthRefreshRequest() {
if let hostURL = environment.config.apiHostURL() {
let URL = hostURL.appendingPathComponent(OAuthExchangePath)
let exchangeRequest = NSMutableURLRequest(url: URL)
exchangeRequest.httpMethod = HTTPMethod.POST.rawValue
for (key, value) in self.environment.session.authorizationHeaders {
exchangeRequest.addValue(value, forHTTPHeaderField: key)
}
self.webController.loadURLRequest(request: exchangeRequest)
}
}
private func refreshAccessibility() {
DispatchQueue.main.async {
UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: nil)
}
}
// MARK: Request Loading
public func loadRequest(request : NSURLRequest) {
contentRequest = request
loadController.state = .Initial
state = webController.initialContentState
var isAuthRequestRequired = webController.alwaysRequiresOAuthUpdate
if let parent = parent as? AuthenticatedWebViewControllerRequireAuthentication {
isAuthRequestRequired = parent.alwaysRequireAuth()
}
if isAuthRequestRequired {
state = State.CreatingSession
loadOAuthRefreshRequest()
}
else {
webController.loadURLRequest(request: request)
}
}
// MARK: WKWebView delegate
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let isWebViewDelegateHandled = !(webViewDelegate?.webView(webView, shouldLoad: navigationAction.request) ?? true)
if isWebViewDelegateHandled {
decisionHandler(.cancel)
} else {
switch navigationAction.navigationType {
case .linkActivated:
if let url = navigationAction.request.url, UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
decisionHandler(.cancel)
default:
decisionHandler(.allow)
}
}
}
public func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
if let httpResponse = navigationResponse.response as? HTTPURLResponse, let statusCode = OEXHTTPStatusCode(rawValue: httpResponse.statusCode), let errorGroup = statusCode.errorGroup, state == .LoadingContent {
if webViewNavigationResponseDelegate?.handleHttpStatusCode(statusCode: statusCode) ?? false {
decisionHandler(.cancel)
return
}
switch errorGroup {
case .http4xx:
state = .NeedingSession
break
case .http5xx:
loadController.state = LoadState.failed()
decisionHandler(.cancel)
return
}
}
decisionHandler(.allow)
}
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
switch state {
case .CreatingSession:
if let request = contentRequest {
state = .LoadingContent
webController.loadURLRequest(request: request)
}
else {
loadController.state = LoadState.failed()
}
case .LoadingContent:
//The class which will implement this protocol method will be responsible to set the loadController state as Loaded
if delegate?.authenticatedWebViewController(authenticatedController: self, didFinishLoading: webView) == nil {
loadController.state = .Loaded
}
case .NeedingSession:
state = .CreatingSession
loadOAuthRefreshRequest()
}
refreshAccessibility()
}
/* Completion callbacks in case of different xBlocks
HTML /publish_completion
Video /publish_completion
Problem problem_check
DragAndDrop handler/do_attempt
ORABlock responseText contains class 'is--complete'
*/
private func isCompletionCallback(with data: Dictionary<AnyHashable, Any>) -> Bool {
let callback = AJAXCallbackData(data: data)
let requestURL = callback.url
if callback.statusCode != OEXHTTPStatusCode.code200OK.rawValue {
return false
}
if isBlockOf(type: .ora, with: requestURL) {
return callback.responseText.contains("is--complete")
} else {
return isBlockOf(type: .html, with: requestURL)
|| isBlockOf(type: .problem, with: requestURL)
|| isBlockOf(type: .dragAndDrop, with: requestURL)
}
}
private func isBlockOf(type: xBlockCompletionCallbackType, with requestURL: String) -> Bool {
return requestURL.contains(type.rawValue)
}
public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == AJAXCallBackHandler {
guard let data = message.body as? Dictionary<AnyHashable, Any> else { return }
if isCompletionCallback(with: data) {
ajaxCallbackDelegate?.didCompletionCalled(completion: true)
}
}
}
public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
showError(error: error as NSError?)
}
public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
guard !loadController.state.isError else { return }
showError(error: error as NSError?)
}
public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
// Don't use basic auth on exchange endpoint. That is explicitly non protected
// and it screws up the authorization headers
if let URL = webView.url, ((URL.absoluteString.hasSuffix(OAuthExchangePath)) != false) {
completionHandler(.performDefaultHandling, nil)
}
else if let credential = environment.config.URLCredentialForHost(challenge.protectionSpace.host as NSString) {
completionHandler(.useCredential, credential)
}
else {
completionHandler(.performDefaultHandling, nil)
}
}
public func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: Strings.ok, style: .default, handler: { action in
completionHandler(true)
}))
alertController.addAction(UIAlertAction(title: Strings.cancel, style: .cancel, handler: { action in
completionHandler(false)
}))
if let presenter = alertController.popoverPresentationController {
presenter.sourceView = view
presenter.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
}
if isViewVisible {
present(alertController, animated: true, completion: nil)
} else {
completionHandler(false)
}
}
}
private struct AJAXCallbackData {
private enum Keys: String {
case url = "url"
case statusCode = "status"
case responseText = "response_text"
}
let url: String
let statusCode: Int
let responseText: String
init(data: Dictionary<AnyHashable, Any>) {
url = data[Keys.url.rawValue] as? String ?? ""
statusCode = data[Keys.statusCode.rawValue] as? Int ?? 0
responseText = data[Keys.responseText.rawValue] as? String ?? ""
}
}
| 27264ff2cc8d70f9cadf50a2eaf71b69 | 35.627291 | 216 | 0.659753 | false | false | false | false |
adjusting/MemeMe | refs/heads/master | MemeMe/MemeEditorVC.swift | mit | 1 | //
// ViewController.swift
// MemeMe
//
// Created by Justin Gareau on 6/3/17.
// Copyright © 2017 Justin Gareau. All rights reserved.
//
import UIKit
class MemeEditorVC: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var cameraButton: UIBarButtonItem!
@IBOutlet weak var shareButton: UIBarButtonItem!
@IBOutlet weak var topTextField: UITextField!
@IBOutlet weak var bottomTextField: UITextField!
@IBOutlet weak var navbar: UIToolbar!
@IBOutlet weak var toolbar: UIToolbar!
let topDelegate = TopTextFieldDelegate()
let bottomDelegate = BottomTextFieldDelegate()
let memeTextAttributes:[String:Any] = [
NSStrokeColorAttributeName: UIColor.black,
NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSStrokeWidthAttributeName: -5]
override func viewDidLoad() {
super.viewDidLoad()
setupTextfield(topTextField, with: "TOP")
topTextField.delegate = topDelegate
setupTextfield(bottomTextField, with: "BOTTOM")
bottomTextField.delegate = bottomDelegate
shareButton.isEnabled = false
}
func setupTextfield(_ textField: UITextField, with text:String) {
textField.defaultTextAttributes = memeTextAttributes
textField.text = text
textField.textAlignment = .center
}
override func viewWillAppear(_ animated: Bool) {
cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera)
subscribeToKeyboardNotifications()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeFromKeyboardNotifications()
}
override var prefersStatusBarHidden: Bool { return true }
func subscribeToKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)
}
func unsubscribeFromKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}
@IBAction func pickAnImageFromAlbum(_ sender: Any) {
pickAnImage(sourceType:.photoLibrary)
}
@IBAction func pickAnImageFromCamera(_ sender: Any) {
pickAnImage(sourceType:.camera)
}
func pickAnImage(sourceType: UIImagePickerControllerSourceType) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = sourceType
present(imagePicker, animated: true, completion: nil)
}
@IBAction func shareMeme(_ sender: Any) {
let controller = UIActivityViewController(activityItems: [generateMemedImage()], applicationActivities: nil)
present(controller, animated: true, completion: {self.save()})
controller.completionWithItemsHandler = { (activityType: UIActivityType?, completed: Bool, returnedItems: [Any]?, error: Error?) -> Void in
if completed == true {
self.dismiss(animated: true, completion: nil)
}
}
}
@IBAction func cancel(_ sender: Any) {
imageView.image = nil
topTextField.text = "TOP"
bottomTextField.text = "BOTTOM"
shareButton.isEnabled = false
dismiss(animated: true, completion: nil)
}
func keyboardWillShow(_ notification:Notification) {
if bottomTextField.isEditing {
view.frame.origin.y = -getKeyboardHeight(notification)
}
}
func keyboardWillHide(_ notification:Notification) {
if bottomTextField.isEditing {
view.frame.origin.y = 0
}
}
func getKeyboardHeight(_ notification:Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue // of CGRect
return keyboardSize.cgRectValue.height
}
func generateMemedImage() -> UIImage {
hideToolbars(true)
// Render view to an image
UIGraphicsBeginImageContext(view.frame.size)
view.drawHierarchy(in: view.frame, afterScreenUpdates: true)
let memedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
hideToolbars(false)
return memedImage
}
func hideToolbars(_ flag:Bool) {
navbar.isHidden = flag
toolbar.isHidden = flag
}
func save() {
// Create the meme
let meme = Meme(topText: topTextField.text!, bottomText: bottomTextField.text!, originalImage: imageView.image!, memedImage: generateMemedImage())
// Add it to the memes array in the Application Delegate
let object = UIApplication.shared.delegate
let appDelegate = object as! AppDelegate
appDelegate.memes.append(meme)
}
}
extension MemeEditorVC: UIImagePickerControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: false, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageView.image = image
}
picker.dismiss(animated: false, completion: nil)
shareButton.isEnabled = true
}
}
extension MemeEditorVC: UINavigationControllerDelegate {
}
| 2ed6c7b46bc1e77879c3ce36025d00c4 | 33.561404 | 154 | 0.675635 | false | false | false | false |
pennlabs/penn-mobile-ios | refs/heads/main | PennMobile/Setup + Navigation/SplashViewController.swift | mit | 1 | //
// SplashViewController.swift
// PennMobile
//
// Created by Josh Doman on 2/25/19.
// Copyright © 2019 PennLabs. All rights reserved.
//
import Foundation
import UIKit
import FirebaseCore
class SplashViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
var imageView: UIImageView
imageView = UIImageView()
imageView.image = UIImage(named: "LaunchIcon")
imageView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(imageView)
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
imageView.widthAnchor.constraint(equalToConstant: view.frame.width/5*2).isActive = true
imageView.heightAnchor.constraint(equalToConstant: view.frame.width/5*2).isActive = true
}
}
| 0c8434205f7d64bd05c9fb255943fef8 | 33.321429 | 96 | 0.726327 | false | false | false | false |
gribozavr/swift | refs/heads/master | test/Constraints/keyword_arguments.swift | apache-2.0 | 3 | // RUN: %target-typecheck-verify-swift
// Single extraneous keyword argument (tuple-to-scalar)
func f1(_ a: Int) { }
f1(a: 5) // expected-error{{extraneous argument label 'a:' in call}}{{4-7=}}
struct X1 {
init(_ a: Int) { }
func f1(_ a: Int) {}
}
X1(a: 5).f1(b: 5)
// expected-error@-1 {{extraneous argument label 'a:' in call}} {{4-7=}}
// expected-error@-2 {{extraneous argument label 'b:' in call}} {{13-16=}}
// <rdar://problem/16801056>
enum Policy {
case Head(Int)
}
func extra2(x: Int, y: Int) { }
func testExtra2(_ policy : Policy) {
switch (policy)
{
case .Head(let count):
extra2(x: 0, y: count)
}
}
// Single missing keyword argument (scalar-to-tuple)
func f2(a: Int) { }
f2(5) // expected-error{{missing argument label 'a:' in call}}{{4-4=a: }}
struct X2 {
init(a: Int) { }
func f2(b: Int) { }
}
X2(5).f2(5)
// expected-error@-1 {{missing argument label 'a:' in call}} {{4-4=a: }}
// expected-error@-2 {{missing argument label 'b:' in call}} {{10-10=b: }}
// -------------------------------------------
// Missing keywords
// -------------------------------------------
func allkeywords1(x: Int, y: Int) { }
// Missing keywords.
allkeywords1(1, 2) // expected-error{{missing argument labels}} {{14-14=x: }} {{17-17=y: }}
allkeywords1(x: 1, 2) // expected-error{{missing argument label 'y:' in call}} {{20-20=y: }}
allkeywords1(1, y: 2) // expected-error{{missing argument label 'x:' in call}} {{14-14=x: }}
// If keyword is reserved, make sure to quote it. rdar://problem/21392294
func reservedLabel(_ x: Int, `repeat`: Bool) {}
reservedLabel(1, true) // expected-error{{missing argument label 'repeat:' in call}}{{18-18=repeat: }}
// Insert missing keyword before initial backtick. rdar://problem/21392294 part 2
func reservedExpr(_ x: Int, y: Int) {}
let `do` = 2
reservedExpr(1, `do`) // expected-error{{missing argument label 'y:' in call}}{{17-17=y: }}
reservedExpr(1, y: `do`)
class GenericCtor<U> {
init<T>(t : T) {} // expected-note {{'init(t:)' declared here}}
}
GenericCtor<Int>() // expected-error{{missing argument for parameter 't' in call}}
// -------------------------------------------
// Extraneous keywords
// -------------------------------------------
func nokeywords1(_ x: Int, _ y: Int) { }
nokeywords1(x: 1, y: 1) // expected-error{{extraneous argument labels 'x:y:' in call}}{{13-16=}}{{19-22=}}
// -------------------------------------------
// Some missing, some extraneous keywords
// -------------------------------------------
func somekeywords1(_ x: Int, y: Int, z: Int) { }
somekeywords1(x: 1, y: 2, z: 3) // expected-error{{extraneous argument label 'x:' in call}}{{15-18=}}
somekeywords1(1, 2, 3) // expected-error{{missing argument labels 'y:z:' in call}}{{18-18=y: }}{{21-21=z: }}
somekeywords1(x: 1, 2, z: 3) // expected-error{{incorrect argument labels in call (have 'x:_:z:', expected '_:y:z:')}}{{15-18=}}{{21-21=y: }}
// -------------------------------------------
// Out-of-order keywords
// -------------------------------------------
allkeywords1(y: 1, x: 2) // expected-error{{argument 'x' must precede argument 'y'}} {{14-14=x: 2, }} {{18-24=}}
// -------------------------------------------
// Default arguments
// -------------------------------------------
func defargs1(x: Int = 1, y: Int = 2, z: Int = 3) {}
// Using defaults (in-order)
defargs1()
defargs1(x: 1)
defargs1(x: 1, y: 2)
// Using defaults (in-order, some missing)
defargs1(y: 2)
defargs1(y: 2, z: 3)
defargs1(z: 3)
defargs1(x: 1, z: 3)
// Using defaults (out-of-order, error by SE-0060)
defargs1(z: 3, y: 2, x: 1) // expected-error{{argument 'x' must precede argument 'z'}} {{10-10=x: 1, }} {{20-26=}}
defargs1(x: 1, z: 3, y: 2) // expected-error{{argument 'y' must precede argument 'z'}} {{16-16=y: 2, }} {{20-26=}}
defargs1(y: 2, x: 1) // expected-error{{argument 'x' must precede argument 'y'}} {{10-10=x: 1, }} {{14-20=}}
// Default arguments "boxed in".
func defargs2(first: Int, x: Int = 1, y: Int = 2, z: Int = 3, last: Int) { }
// Using defaults in the middle (in-order, some missing)
defargs2(first: 1, x: 1, z: 3, last: 4)
defargs2(first: 1, x: 1, last: 4)
defargs2(first: 1, y: 2, z: 3, last: 4)
defargs2(first: 1, last: 4)
// Using defaults in the middle (out-of-order, error by SE-0060)
defargs2(first: 1, z: 3, x: 1, last: 4) // expected-error{{argument 'x' must precede argument 'z'}} {{20-20=x: 1, }} {{24-30=}}
defargs2(first: 1, z: 3, y: 2, last: 4) // expected-error{{argument 'y' must precede argument 'z'}} {{20-20=y: 2, }} {{24-30=}}
// Using defaults that have moved past a non-defaulted parameter
defargs2(x: 1, first: 1, last: 4) // expected-error{{argument 'first' must precede argument 'x'}} {{10-10=first: 1, }} {{14-24=}}
defargs2(first: 1, last: 4, x: 1) // expected-error{{argument 'x' must precede argument 'last'}} {{20-20=x: 1, }} {{27-33=}}
// -------------------------------------------
// Variadics
// -------------------------------------------
func variadics1(x: Int, y: Int, _ z: Int...) { }
// Using variadics (in-order, complete)
variadics1(x: 1, y: 2)
variadics1(x: 1, y: 2, 1)
variadics1(x: 1, y: 2, 1, 2)
variadics1(x: 1, y: 2, 1, 2, 3)
// Using various (out-of-order)
variadics1(1, 2, 3, 4, 5, x: 6, y: 7) // expected-error {{incorrect argument labels in call (have '_:_:_:_:_:x:y:', expected 'x:y:_:')}} {{12-12=x: }} {{15-15=y: }} {{27-30=}} {{33-36=}}
func variadics2(x: Int, y: Int = 2, z: Int...) { } // expected-note {{'variadics2(x:y:z:)' declared here}}
// Using variadics (in-order, complete)
variadics2(x: 1, y: 2, z: 1)
variadics2(x: 1, y: 2, z: 1, 2)
variadics2(x: 1, y: 2, z: 1, 2, 3)
// Using variadics (in-order, some missing)
variadics2(x: 1, z: 1, 2, 3)
variadics2(x: 1)
// Using variadics (out-of-order)
variadics2(z: 1, 2, 3, y: 2) // expected-error{{missing argument for parameter 'x' in call}}
variadics2(z: 1, 2, 3, x: 1) // expected-error{{argument 'x' must precede argument 'z'}} {{12-12=x: 1, }} {{22-28=}}
func variadics3(_ x: Int..., y: Int = 2, z: Int = 3) { }
// Using variadics (in-order, complete)
variadics3(1, 2, 3, y: 0, z: 1)
variadics3(1, y: 0, z: 1)
variadics3(y: 0, z: 1)
// Using variadics (in-order, some missing)
variadics3(1, 2, 3, y: 0)
variadics3(1, z: 1)
variadics3(z: 1)
variadics3(1, 2, 3, z: 1)
variadics3(1, z: 1)
variadics3(z: 1)
variadics3(1, 2, 3)
variadics3(1)
variadics3()
// Using variadics (out-of-order)
variadics3(y: 0, 1, 2, 3) // expected-error{{unnamed argument #2 must precede argument 'y'}} {{12-12=1, 2, 3, }} {{16-25=}}
variadics3(z: 1, 1) // expected-error{{unnamed argument #2 must precede argument 'z'}} {{12-12=1, }} {{16-19=}}
func variadics4(x: Int..., y: Int = 2, z: Int = 3) { }
// Using variadics (in-order, complete)
variadics4(x: 1, 2, 3, y: 0, z: 1)
variadics4(x: 1, y: 0, z: 1)
variadics4(y: 0, z: 1)
// Using variadics (in-order, some missing)
variadics4(x: 1, 2, 3, y: 0)
variadics4(x: 1, z: 1)
variadics4(z: 1)
variadics4(x: 1, 2, 3, z: 1)
variadics4(x: 1, z: 1)
variadics4(z: 1)
variadics4(x: 1, 2, 3)
variadics4(x: 1)
variadics4()
// Using variadics (in-order, some missing)
variadics4(y: 0, x: 1, 2, 3) // expected-error{{argument 'x' must precede argument 'y'}} {{12-12=x: 1, 2, 3, }} {{16-28=}}
variadics4(z: 1, x: 1) // expected-error{{argument 'x' must precede argument 'z'}} {{12-12=x: 1, }} {{16-22=}}
func variadics5(_ x: Int, y: Int, _ z: Int...) { } // expected-note {{declared here}}
// Using variadics (in-order, complete)
variadics5(1, y: 2)
variadics5(1, y: 2, 1)
variadics5(1, y: 2, 1, 2)
variadics5(1, y: 2, 1, 2, 3)
// Using various (out-of-order)
variadics5(1, 2, 3, 4, 5, 6, y: 7) // expected-error{{argument 'y' must precede unnamed argument #2}} {{15-15=y: 7, }} {{28-34=}}
variadics5(y: 1, 2, 3, 4, 5, 6, 7) // expected-error{{missing argument for parameter #1 in call}}
func variadics6(x: Int..., y: Int = 2, z: Int) { } // expected-note 4 {{'variadics6(x:y:z:)' declared here}}
// Using variadics (in-order, complete)
variadics6(x: 1, 2, 3, y: 0, z: 1)
variadics6(x: 1, y: 0, z: 1)
variadics6(y: 0, z: 1)
// Using variadics (in-order, some missing)
variadics6(x: 1, 2, 3, y: 0) // expected-error{{missing argument for parameter 'z' in call}}
variadics6(x: 1, z: 1)
variadics6(z: 1)
variadics6(x: 1, 2, 3, z: 1)
variadics6(x: 1, z: 1)
variadics6(z: 1)
variadics6(x: 1, 2, 3) // expected-error{{missing argument for parameter 'z' in call}}
variadics6(x: 1) // expected-error{{missing argument for parameter 'z' in call}}
variadics6() // expected-error{{missing argument for parameter 'z' in call}}
func outOfOrder(_ a : Int, b: Int) {
outOfOrder(b: 42, 52) // expected-error {{unnamed argument #2 must precede argument 'b'}} {{14-14=52, }} {{19-23=}}
}
// -------------------------------------------
// Missing arguments
// -------------------------------------------
// FIXME: Diagnostics could be improved with all missing names, or
// simply # of arguments required.
func missingargs1(x: Int, y: Int, z: Int) {} // expected-note {{'missingargs1(x:y:z:)' declared here}}
missingargs1(x: 1, y: 2) // expected-error{{missing argument for parameter 'z' in call}}
func missingargs2(x: Int, y: Int, _ z: Int) {} // expected-note {{'missingargs2(x:y:_:)' declared here}}
missingargs2(x: 1, y: 2) // expected-error{{missing argument for parameter #3 in call}}
// -------------------------------------------
// Extra arguments
// -------------------------------------------
func extraargs1(x: Int) {} // expected-note {{'extraargs1(x:)' declared here}}
extraargs1(x: 1, y: 2) // expected-error{{extra argument 'y' in call}}
extraargs1(x: 1, 2, 3) // expected-error{{extra arguments at positions #2, #3 in call}}
// -------------------------------------------
// Argument name mismatch
// -------------------------------------------
func mismatch1(thisFoo: Int = 0, bar: Int = 0, wibble: Int = 0) { } // expected-note {{'mismatch1(thisFoo:bar:wibble:)' declared here}}
mismatch1(foo: 5) // expected-error {{extra argument 'foo' in call}}
mismatch1(baz: 1, wobble: 2) // expected-error{{incorrect argument labels in call (have 'baz:wobble:', expected 'bar:wibble:')}} {{11-14=bar}} {{19-25=wibble}}
mismatch1(food: 1, zap: 2) // expected-error{{extra arguments at positions #1, #2 in call}}
// -------------------------------------------
// Subscript keyword arguments
// -------------------------------------------
struct Sub1 {
subscript (i: Int) -> Int {
get { return i }
}
}
var sub1 = Sub1()
var i: Int = 0
i = sub1[i]
i = sub1[i: i] // expected-error{{extraneous argument label 'i:' in subscript}} {{10-13=}}
struct Sub2 {
subscript (d d: Double) -> Double {
get { return d }
}
}
var sub2 = Sub2()
var d: Double = 0.0
d = sub2[d] // expected-error{{missing argument label 'd:' in subscript}} {{10-10=d: }}
d = sub2[d: d]
d = sub2[f: d] // expected-error{{incorrect argument label in subscript (have 'f:', expected 'd:')}} {{10-11=d}}
// -------------------------------------------
// Closures
// -------------------------------------------
func intToInt(_ i: Int) -> Int { return i }
func testClosures() {
let c0 = { (x: Int, y: Int) in x + y }
_ = c0(1, 2)
let c1 = { x, y in intToInt(x + y) }
_ = c1(1, 2)
let c2 = { intToInt($0 + $1) }
_ = c2(1, 2)
}
func acceptAutoclosure(f: @autoclosure () -> Int) { }
func produceInt() -> Int { }
acceptAutoclosure(f: produceInt) // expected-error{{add () to forward @autoclosure parameter}} {{32-32=()}}
// -------------------------------------------
// Trailing closures
// -------------------------------------------
func trailingclosure1(x: Int, f: () -> Int) {}
trailingclosure1(x: 1) { return 5 }
trailingclosure1(1) { return 5 } // expected-error{{missing argument label 'x:' in call}}{{18-18=x: }}
trailingclosure1(x: 1, { return 5 }) // expected-error{{missing argument label 'f:' in call}} {{24-24=f: }}
func trailingclosure2(x: Int, f: (() -> Int)?...) {}
trailingclosure2(x: 5) { return 5 }
func trailingclosure3(x: Int, f: (() -> Int)!) {
var f = f
f = nil
_ = f
}
trailingclosure3(x: 5) { return 5 }
func trailingclosure4(f: () -> Int) {}
trailingclosure4 { 5 }
func trailingClosure5<T>(_ file: String = #file, line: UInt = #line, expression: () -> T?) { }
// expected-note@-1 {{in call to function 'trailingClosure5(_:line:expression:)'}}
func trailingClosure6<T>(value: Int, expression: () -> T?) { }
// expected-note@-1 {{in call to function 'trailingClosure6(value:expression:)'}}
trailingClosure5(file: "hello", line: 17) { // expected-error{{extraneous argument label 'file:' in call}}{{18-24=}}
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
return Optional.Some(5)
// expected-error@-1 {{enum type 'Optional<Wrapped>' has no case 'Some'; did you mean 'some'?}} {{19-23=some}}
// expected-error@-2 {{generic parameter 'Wrapped' could not be inferred}}
// expected-note@-3 {{explicitly specify the generic arguments to fix this issue}}
}
trailingClosure6(5) { // expected-error{{missing argument label 'value:' in call}}{{18-18=value: }}
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
return Optional.Some(5)
// expected-error@-1 {{enum type 'Optional<Wrapped>' has no case 'Some'; did you mean 'some'?}} {{19-23=some}}
// expected-error@-2 {{generic parameter 'Wrapped' could not be inferred}}
// expected-note@-3 {{explicitly specify the generic arguments to fix this issue}}
}
class MismatchOverloaded1 {
func method1(_ x: Int!, arg: ((Int) -> Int)!) { }
func method1(_ x: Int!, secondArg: ((Int) -> Int)!) { }
@available(*, unavailable)
func method2(_ x: Int!, arg: ((Int) -> Int)!) { }
func method2(_ x: Int!, secondArg: ((Int) -> Int)!) { }
}
var mismatchOverloaded1 = MismatchOverloaded1()
mismatchOverloaded1.method1(5, arg: nil)
mismatchOverloaded1.method1(5, secondArg: nil)
// Prefer available to unavailable declaration, if it comes up.
mismatchOverloaded1.method2(5) { $0 }
// -------------------------------------------
// Values of function type
// -------------------------------------------
func testValuesOfFunctionType(_ f1: (_: Int, _ arg: Int) -> () ) {
f1(3, arg: 5) // expected-error{{extraneous argument label 'arg:' in call}}{{9-14=}}
f1(x: 3, 5) // expected-error{{extraneous argument label 'x:' in call}} {{6-9=}}
f1(3, 5)
}
// -------------------------------------------
// Literals
// -------------------------------------------
func string_literals1(x: String) { }
string_literals1(x: "hello")
func int_literals1(x: Int) { }
int_literals1(x: 1)
func float_literals1(x: Double) { }
float_literals1(x: 5)
// -------------------------------------------
// Tuples as arguments
// -------------------------------------------
func produceTuple1() -> (Int, Bool) { return (1, true) }
func acceptTuple1<T>(_ x: (T, Bool)) { }
acceptTuple1(produceTuple1())
acceptTuple1((1, false))
acceptTuple1(1, false) // expected-error {{global function 'acceptTuple1' expects a single parameter of type '(T, Bool)' [with T = Int]}} {{14-14=(}} {{22-22=)}}
func acceptTuple2<T>(_ input : T) -> T { return input }
var tuple1 = (1, "hello")
_ = acceptTuple2(tuple1)
_ = acceptTuple2((1, "hello", 3.14159))
func generic_and_missing_label(x: Int) {}
func generic_and_missing_label<T>(x: T) {}
generic_and_missing_label(42)
// expected-error@-1 {{missing argument label 'x:' in call}} {{27-27=x: }}
| 69fc995e340d7401da167e7f6729a3dd | 35.283019 | 186 | 0.576118 | false | false | false | false |
Alexiuce/Tip-for-day | refs/heads/master | TextKitDemo/TextKitDemo/ViewController.swift | mit | 1 | //
// ViewController.swift
// TextKitDemo
//
// Created by caijinzhu on 2018/3/20.
// Copyright © 2018年 alexiuce.github.io. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var titleLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let stringStorage = textView.textStorage
let lineHeight = textView.font!.lineHeight
guard let textPath = Bundle.main.path(forResource: "abc", ofType: ".txt") else { return }
guard let text = try? String(contentsOf: URL(fileURLWithPath: textPath), encoding: String.Encoding.utf8) else{return}
stringStorage.replaceCharacters(in: NSMakeRange(0, 0), with: text)
let layoutManager = NSLayoutManager()
stringStorage.addLayoutManager(layoutManager)
let textContainer = NSTextContainer(size: CGSize(width: 100, height: 100))
textContainer.lineBreakMode = .byTruncatingTail
layoutManager.addTextContainer(textContainer)
let exclucePath = UIBezierPath(rect: CGRect(x: 70, y: 100 - lineHeight, width: 30, height: lineHeight))
textContainer.exclusionPaths = [exclucePath]
let textRect = CGRect(x: 100, y: 400, width: 100, height: 100)
let textView2 = UITextView(frame:textRect , textContainer: textContainer)
textView2.isEditable = false
textView2.isScrollEnabled = false
textView2.backgroundColor = UIColor.yellow
view.addSubview(textView2)
let textContainer2 = NSTextContainer(size: CGSize(width: 100, height: 150))
layoutManager.addTextContainer(textContainer2)
let rect2 = CGRect(x: 210, y: 400, width: 100, height: 150)
let textView3 = UITextView(frame: rect2, textContainer: textContainer2)
textView3.backgroundColor = UIColor.gray
view.addSubview(textView3)
}
}
extension ViewController{
fileprivate func labelTest(){
var test = "http:www.joinf.com:3333"
titleLabel.text = test
test = "www.jionf.com"
}
}
| dedc8d2642ea99407381441515cd3620 | 28.051948 | 125 | 0.644613 | false | true | false | false |
mbeloded/discountsPublic | refs/heads/master | discounts/Classes/UI/DiscountView/DiscountView.swift | gpl-3.0 | 1 | //
// DiscountView.swift
// discounts
//
// Created by Michael Bielodied on 9/10/14.
// Copyright (c) 2014 Michael Bielodied. All rights reserved.
//
import Foundation
import UIKit
import RSBarcodes_Swift
import AVFoundation
class DiscountView: UIView {
@IBOutlet weak private var codeImageView: UIImageView!
@IBOutlet weak private var productImageLogoView: UIImageView!
@IBOutlet weak private var productNameLabel: UILabel!
func generateCode(_ productIndex:Int)
{
let companyObject:CompanyObject = DiscountsManager.sharedInstance.discountsCategoryArrayData[productIndex]
productNameLabel.text = companyObject.companyName
productImageLogoView.image = UIImage(named: companyObject.imageName)
let codeImage:UIImage = RSCode128Generator(codeTable: .a).generateCode(companyObject.discountCode, machineReadableCodeObjectType: AVMetadataObjectTypeCode128Code)!
codeImageView.image = codeImage
codeImageView.center = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
codeImageView.frame = CGRect(x: codeImageView.frame.origin.x, y: codeImageView.frame.origin.y, width: codeImage.size.width, height: codeImage.size.height)
}
}
| 179722bea9c772cdb7174f0d52cdc563 | 36.727273 | 171 | 0.747791 | false | false | false | false |
faimin/ZDOpenSourceDemo | refs/heads/master | Sources/LayoutArrangement.swift | apache-2.0 | 2 | // Copyright 2016 LinkedIn 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.
import CoreGraphics
/**
The frame of a layout and the frames of its sublayouts.
*/
public struct LayoutArrangement {
public let layout: Layout
public let frame: CGRect
public let sublayouts: [LayoutArrangement]
public init(layout: Layout, frame: CGRect, sublayouts: [LayoutArrangement]) {
self.layout = layout
self.frame = frame
self.sublayouts = sublayouts
}
/**
Creates the views for the layout and adds them as subviews to the provided view.
Existing subviews of the provided view will be removed.
If no view is provided, then a new one is created and returned.
MUST be run on the main thread.
- parameter view: The layout's views will be added as subviews to this view, if provided.
- parameter direction: The natural direction of the layout (default: .LeftToRight).
If it does not match the user's language direction, then the layout's views will be flipped horizontally.
Only provide this parameter if you want to test the flipped version of your layout,
or if your layouts are declared for right-to-left languages and you want them to get flipped for left-to-right languages.
- returns: The root view. If a view was provided, then the same view will be returned, otherwise, a new one will be created.
*/
@discardableResult
public func makeViews(in view: View? = nil, direction: UserInterfaceLayoutDirection = .leftToRight) -> View {
return makeViews(in: view, direction: direction, prepareAnimation: false)
}
/**
Prepares the view to be animated to this arrangement.
Call `prepareAnimation(for:direction)` before the animation block.
Call the returned animation's `apply()` method inside the animation block.
```
let animation = nextLayout.arrangement().prepareAnimation(for: rootView, direction: .RightToLeft)
View.animateWithDuration(5.0, animations: {
animation.apply()
})
```
Subviews are reparented for the new arrangement, if necessary, but frames are adjusted so locations don't change.
No frames or configurations of the new arrangement are applied until `apply()` is called on the returned animation object.
MUST be run on the main thread.
*/
public func prepareAnimation(for view: View, direction: UserInterfaceLayoutDirection = .leftToRight) -> Animation {
makeViews(in: view, direction: direction, prepareAnimation: true)
return Animation(arrangement: self, rootView: view, direction: direction)
}
/**
Helper function for `makeViews(in:direction:)` and `prepareAnimation(for:direction:)`.
See the documentation for those two functions.
*/
@discardableResult
private func makeViews(in view: View? = nil, direction: UserInterfaceLayoutDirection, prepareAnimation: Bool) -> View {
let recycler = ViewRecycler(rootView: view)
let views = makeSubviews(from: recycler, prepareAnimation: prepareAnimation)
let rootView: View
if let view = view {
for subview in views {
view.addSubview(subview, maintainCoordinates: prepareAnimation)
}
rootView = view
// In this case, the `rootView` is the view that was passed in. It is not created for this layout arrangement
// but merely hosts it. Therefore, the subview(s) that are being added to it are the root-most views from
// the LayoutKit view recycling perspective.
recycler.markViewsAsRoot(views)
} else if let view = views.first, views.count == 1 {
// We have a single view so it is our root view.
rootView = view
recycler.markViewsAsRoot(views)
} else {
// We have multiple views so create a root view.
rootView = View(frame: frame)
for subview in views {
if !prepareAnimation {
// Unapply the offset that was applied in makeSubviews()
subview.frame = subview.frame.offsetBy(dx: -frame.origin.x, dy: -frame.origin.y)
}
rootView.addSubview(subview)
}
// The generated root view that's being returned is the root-most one that is created by LayoutKit,
// so it is the one that should be marked as the root by the recycler.
recycler.markViewsAsRoot([rootView])
}
recycler.purgeViews()
if !prepareAnimation {
// Horizontally flip the view frames if direction does not match the root view's language direction.
if rootView.userInterfaceLayoutDirection != direction {
flipSubviewsHorizontally(rootView)
}
}
return rootView
}
/// Flips the right and left edges of the view's subviews.
private func flipSubviewsHorizontally(_ view: View) {
for subview in view.subviews {
subview.frame.origin.x = view.frame.width - subview.frame.maxX
flipSubviewsHorizontally(subview)
}
}
/// Returns the views for the layout and all of its sublayouts.
private func makeSubviews(from recycler: ViewRecycler, prepareAnimation: Bool) -> [View] {
let subviews = sublayouts.flatMap({ (sublayout: LayoutArrangement) -> [View] in
return sublayout.makeSubviews(from: recycler, prepareAnimation: prepareAnimation)
})
// If we are preparing an animation, then we don't want to update frames or configure views.
if layout.needsView, let view = recycler.makeOrRecycleView(havingViewReuseId: layout.viewReuseId, viewProvider: layout.makeView) {
if !prepareAnimation {
view.frame = frame
layout.configure(baseTypeView: view)
}
for subview in subviews {
// If a view gets reparented and we are preparing an animation, then
// make sure that its absolute position on the screen does not change.
view.addSubview(subview, maintainCoordinates: prepareAnimation)
}
return [view]
} else {
if !prepareAnimation {
for subview in subviews {
subview.frame = subview.frame.offsetBy(dx: frame.origin.x, dy: frame.origin.y)
}
}
return subviews
}
}
}
extension LayoutArrangement: CustomDebugStringConvertible {
public var debugDescription: String {
return _debugDescription(0)
}
private func _debugDescription(_ indent: Int) -> String {
let t = String(repeatElement(" ", count: indent * 2))
let sublayoutsString = sublayouts.map { $0._debugDescription(indent + 1) }.joined()
let layoutName = String(describing: layout).components(separatedBy: ".").last!
return"\(t)\(layoutName): \(frame)\n\(sublayoutsString)"
}
}
extension View {
/**
Similar to `addSubview()` except if `maintainCoordinates` is true, then the view's frame
will be adjusted so that its absolute position on the screen does not change.
*/
fileprivate func addSubview(_ view: View, maintainCoordinates: Bool) {
if maintainCoordinates {
let frame = view.convertToAbsoluteCoordinates(view.frame)
addSubview(view)
view.frame = view.convertFromAbsoluteCoordinates(frame)
} else {
addSubview(view)
}
}
}
| f140b1a3f59d8f730db8626f35c0dc84 | 42.661202 | 138 | 0.654068 | false | false | false | false |
BrunoMazzo/CocoaHeadsApp | refs/heads/master | CocoaHeadsApp/Classes/Events/Controllers/EventsListDataSource.swift | mit | 3 | import UIKit
class EventsListTableDataSource: NSObject, UITableViewDataSource {
let viewModel :EventsListViewModel
init(viewModel : EventsListViewModel) {
self.viewModel = viewModel
super.init()
}
// MARK: - Table view data source
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.viewModel.items.value.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let reuseIdentifier = R.nib.eventsListTableViewCell.name
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath)
guard let eventsCell = cell as? EventsListTableViewCell else {
return cell
}
//eventsCell.events.value = viewModel.items.value[indexPath.item]
return eventsCell
}
}
| f0d9d2cd3f768bc70d0e34ea5522b4b6 | 29.580645 | 109 | 0.67616 | false | false | false | false |
PorridgeBear/imvs | refs/heads/master | IMVS/Residue.swift | mit | 1 | //
// Residue.swift
// IMVS
//
// Created by Allistair Crossley on 13/07/2014.
// Copyright (c) 2014 Allistair Crossley. All rights reserved.
//
import Foundation
/**
* Amino Acid Residue
*
* A protein chain will have somewhere in the range of 50 to 2000 amino acid residues.
* You have to use this term because strictly speaking a peptide chain isn't made up of amino acids.
* When the amino acids combine together, a water molecule is lost. The peptide chain is made up
* from what is left after the water is lost - in other words, is made up of amino acid residues.
* http://www.chemguide.co.uk/organicprops/aminoacids/proteinstruct.html
* C and N terminus
*/
class Residue {
var name: String = ""
var atoms: [Atom] = []
convenience init() {
self.init(name: "NONE")
}
init(name: String) {
self.name = name
}
func addAtom(atom: Atom) {
atoms.append(atom)
}
func getAlphaCarbon() -> Atom? {
for atom in atoms {
if atom.element == "C" && atom.remoteness == "A" {
return atom
}
}
return nil
}
/** TODO - Might not be 100% right grabbing the first O - check */
func getCarbonylOxygen() -> Atom? {
for atom in atoms {
if atom.element == "O" {
return atom
}
}
return nil
}
}
| cf459bc4fc63165338b01a15234992d0 | 22.693548 | 101 | 0.560926 | false | false | false | false |
FuckBoilerplate/RxCache | refs/heads/master | Carthage/Checkouts/RxSwift/RxSwift/Observables/Implementations/ToArray.swift | mit | 6 | //
// ToArray.swift
// Rx
//
// Created by Junior B. on 20/10/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class ToArraySink<SourceType, O: ObserverType> : Sink<O>, ObserverType where O.E == [SourceType] {
typealias Parent = ToArray<SourceType>
let _parent: Parent
var _list = Array<SourceType>()
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<SourceType>) {
switch event {
case .next(let value):
self._list.append(value)
case .error(let e):
forwardOn(.error(e))
self.dispose()
case .completed:
forwardOn(.next(_list))
forwardOn(.completed)
self.dispose()
}
}
}
class ToArray<SourceType> : Producer<[SourceType]> {
let _source: Observable<SourceType>
init(source: Observable<SourceType>) {
_source = source
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == [SourceType] {
let sink = ToArraySink(parent: self, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
| 5e82d9a3cc0742e93e48ddf0a3f317cd | 27.08 | 149 | 0.601852 | false | false | false | false |
crspybits/SMSyncServer | refs/heads/master | iOS/iOSFramework/SMSyncServer/Classes/Internal/SMServerConstants.swift | gpl-3.0 | 1 | //
// SMServerConstants.swift
// NetDb
//
// Created by Christopher Prince on 11/26/15.
// Copyright © 2015 Christopher Prince. All rights reserved.
//
// Constants used in communication between the remote Node.js server and the iOS SMSyncServer framework.
import Foundation
public class SMServerConstants {
// Don't change the following constant. I'm using it to extract constants and use them in the Node.js
// Each line in the following is assumed (by the processing script) to either be a comment (starts with "//"), or have the structure: public static let X = Y (with *NO* possible following comments; The value of Y is taken as the remaining text up to the end of the line).
//SERVER-CONSTANTS-START
// -------- Information sent to the server --------
// MARK: REST API entry points on the server.
// Append '/' and one these values to the serverURL to create the specific operation URL:
public static let operationCreateNewUser = "CreateNewUser"
public static let operationCheckForExistingUser = "CheckForExistingUser"
// TODO: This will remove user credentials and all FileIndex entries from the SyncServer.
public static let operationRemoveUser = "RemoveUser"
public static let operationCreateSharingInvitation = "CreateSharingInvitation"
public static let operationLookupSharingInvitation = "LookupSharingInvitation"
public static let operationRedeemSharingInvitation = "RedeemSharingInvitation"
public static let operationGetLinkedAccountsForSharingUser = "GetLinkedAccountsForSharingUser"
public static let operationLock = "Lock"
public static let operationUploadFile = "UploadFile"
public static let operationDeleteFiles = "DeleteFiles"
// Holding the lock is optional for this operation (but the lock cannot already be held by another user of the same cloud storage account).
public static let operationGetFileIndex = "GetFileIndex"
public static let operationSetupInboundTransfers = "SetupInboundTransfers"
// Both of these implicitly do an Unlock after the cloud storage transfer.
// operationStartOutboundTransfer is also known as the "commit" operation.
public static let operationStartOutboundTransfer = "StartOutboundTransfer"
public static let operationStartInboundTransfer = "StartInboundTransfer"
// Provided to deal with the case of checking for downloads, but no downloads need to be carried out. Don't use if an operationId has been generated.
public static let operationUnlock = "Unlock"
public static let operationGetOperationId = "GetOperationId"
// Both of the following are carried out in an unlocked state.
public static let operationDownloadFile = "DownloadFile"
// Remove the downloaded file from the server.
public static let operationRemoveDownloadFile = "RemoveDownloadFile"
public static let operationCheckOperationStatus = "CheckOperationStatus"
public static let operationRemoveOperationId = "RemoveOperationId"
// Recover from errors that occur after starting to transfer files from cloud storage.
public static let operationInboundTransferRecovery = "InboundTransferRecovery"
// For development/debugging only. Removes lock. Removes all outbound file changes. Intended for use with automated testing to cleanup between tests that cause rcServerAPIError.
public static let operationCleanup = "Cleanup"
// MARK: Custom HTTP headers sent back from server
// For custom header naming conventions, see http://stackoverflow.com/questions/3561381/custom-http-headers-naming-conventions
// Used for operationDownloadFile only.
public static let httpDownloadParamHeader = "SMSyncServer-Download-Parameters"
// MARK: Credential parameters sent to the server.
// Key:
public static let userCredentialsDataKey = "CredentialsData"
// Each user account type has four common keys in the user credentials data nested structure:
// SubKey:
public static let mobileDeviceUUIDKey = "MobileDeviceUUID"
// Value: A UUID assigned by the app that uniquely represents the users device.
// SubKey:
public static let cloudFolderPath = "CloudFolderPath"
// Value: The path into the cloud storage system where the files will be stored. *All* files are stored in a single folder in the cloud storage system. Currently, this *must* be a folder immediately off of the root. E.g., /Petunia. Subfolders (e.g., /Petunia/subfolder) are not allowable currently.
// SubKey: (optional)
public static let accountUserName = "UserName"
// Value: String
// SubKey:
public static let userType = "UserType"
// Values
public static let userTypeOwning = "OwningUser"
public static let userTypeSharing = "SharingUser"
// SubKey: (for userTypeSharing only)
public static let linkedOwningUserId = "LinkedOwningUserId"
// Values: A string giving a server internal id referencing the owning user's data being shared. This is particularly important when a sharing user can access data from more than one owning user.
// SubKey:
public static let accountType = "AccountType"
// Values:
public static let accountTypeGoogle = "Google"
public static let accountTypeFacebook = "Facebook"
// And each specific storage system has its own specific keys in the credentials data for the specific user.
// MARK: For Google, there are the following additional keys:
// SubKey:
public static let googleUserIdToken = "IdToken"
// Value is an id token representing the user
// SubKey:
public static let googleUserAuthCode = "AuthCode"
// Value is a one-time authentication code
// MARK: For Facebook, there are the following additional keys:
// SubKey:
public static let facebookUserId = "userId"
// Value: String
// SubKey:
public static let facebookUserAccessToken = "accessToken"
// Value: String
// MARK: Other parameters sent to the server.
// Used with GetFileIndex operation
// Key:
public static let requirePreviouslyHeldLockKey = "RequirePreviouslyHeldLock"
// Value: Boolean
// When one or more files are being deleted (operationDeleteFiles), use the following
// Key:
public static let filesToDeleteKey = "FilesToDelete"
// Value: an array of JSON objects with keys: fileUUIDKey, fileVersionKey, cloudFileNameKey, fileMIMEtypeKey.
// When one or more files are being transferred from cloud storage (operationTransferFromCloudStorage), use the following
// Key:
public static let filesToTransferFromCloudStorageKey = "FilesToTransferFromCloudStorage"
// Value: an array of JSON objects with keys: fileUUIDKey
// Only the UUID key is needed because no change is being made to the file index-- the transfer operation consists of copying the current version of the file from cloud storage to the server temporary storage.
// When a file is being downloaded (operationDownloadFile, or operationRemoveDownloadFile), use the following key.
public static let downloadFileAttributes = "DownloadFileAttr"
// Value: a JSON object with key: fileUUIDKey.
// Like above, no change is being made to the file index, thus only the UUID is needed.
// The following keys are required for file uploads (and some for deletions and downloads, see above).
// Key:
public static let fileUUIDKey = "FileUUID"
// Value: A UUID assigned by the app that uniquely represents this file.
// Key:
public static let fileVersionKey = "FileVersion"
// Value: A integer value, > 0, indicating the version number of the file. The version number is application specific, but provides a way of indicating progressive changes or updates to the file. It is an error for the version number to be reduced. E.g., if version number N is stored currently in the cloud, then after some changes, version N+1 should be next to be stored.
// Key:
public static let cloudFileNameKey = "CloudFileName"
// Value: The name of the file on the cloud system.
// Key:
public static let fileMIMEtypeKey = "FileMIMEType"
// Value: The MIME type of the file in the cloud/app.
// TODO: Give a list of allowable MIME types. We have to restrict this because otherwise, there could be some injection error of the REST interface user creating a Google Drive folder or other special GD object.
// Key:
public static let appMetaDataKey = "AppMetaData"
// Value: Optional app-dependent meta data for the file.
// Optional key that can be given with operationUploadFile-- used to resolve conflicts where file has been deleted on the server, but where the local app wants to override that with an update.
// Key:
public static let undeleteFileKey = "UndeleteFile"
// Value: true
// TODO: I'm not yet using this.
public static let appGroupIdKey = "AppGroupId"
// Value: A UUID string that (optionally) indicates an app-specific logical group that the file belongs to.
// Used with operationCheckOperationStatus and operationRemoveOperationId
// Key:
public static let operationIdKey = "OperationId"
// Value: An operationId that resulted from operationCommitChanges, or from operationTransferFromCloudStorage
// Only used in development, not in production.
// Key:
public static let debugTestCaseKey = "DebugTestCase"
// Value: An integer number (values given next) indicating a particular test case.
// Values for debugTestCaseKey. These trigger simulated failures on the server at various points-- for testing.
// Simulated failure when marking all files for user/device in PSOutboundFileChange's as committed. This applies only to file uploads (and upload deletions).
public static let dbTcCommitChanges = 1
// Simulated failure when updating the file index on the server. Occurs when finishing sending a file to cloud storage. And when checking the log for consistency when doing outbound transfer recovery. Applies only to uploads (and upload deletions).
public static let dbTcSendFilesUpdate = 2
// Simulated failure when changing the operation id status to "in progress" when transferring files to/from cloud storage. Applies to both uploads and downloads.
public static let dbTcInProgress = 3
// Simulated failure when setting up for transferring files to/from cloud storage. This occurrs after changing the operation id status to "in progress" and before the actual transferring of files. Applies to both uploads and downloads.
public static let dbTcSetup = 4
// Simulated failure when transferring files to/from cloud storage. Occurs after dbTcSetup. Applies to both uploads and downloads.
public static let dbTcTransferFiles = 5
// Simulated failure when removing the lock after doing cloud storage transfer. Applies to both uploads and downloads.
public static let dbTcRemoveLockAfterCloudStorageTransfer = 6
public static let dbTcGetLockForDownload = 7
// Simulated failure in a file download, when getting download file info. Applies to download only.
public static let dbTcGetDownloadFileInfo = 8
// MARK: Parameters sent in sharing operations
// Key:
public static let sharingType = "SharingType"
// Values: String, one of the following:
public static let sharingDownloader = "Downloader"
public static let sharingUploader = "Uploader"
public static let sharingAdmin = "Admin"
// MARK Keys both sent to the server and received back from the server.
// This is returned on a successful call to operationCreateSharingInvitation, and sent to the server on an operationLookupSharingInvitation call.
// Key:
public static let sharingInvitationCode = "SharingInvitationCode"
// Value: A code uniquely identifying the sharing invitation.
// MARK: Parameter for lock operation
public static let forceLock = "ForceLock"
// Value: Bool, true or false. Default (don't give the parameter) is false.
// MARK: Responses from server
// Key:
public static let internalUserId = "InternalUserId"
// Values: See documentation on internalUserId in SMSyncServerUser
// Key:
public static let resultCodeKey = "ServerResult"
// Values: Integer values, defined below.
// This is returned on a successful call to operationStartFileChanges.
// Key:
public static let resultOperationIdKey = "ServerOperationId"
// Values: A unique string identifying the operation on the server. Valid until the operation completes on the server, and the client checks the state of the operation using operationCheckOpStatus.
// If there was an error, the value of this key may have textual details.
public static let errorDetailsKey = "ServerErrorDetails"
// This is returned on a successful call to operationGetFileIndex
// Key:
public static let resultFileIndexKey = "ServerFileIndex"
// Values: An JSON array of JSON objects describing the files for the user.
// The keys/values within the elements of that file index array are as follows:
// (Server side implementation note: Just changing these string constants below is not sufficient to change the names on the server. See PSFileIndex.sjs on the server).
// Value: UUID String; Client identifier for the file.
public static let fileIndexFileId = "fileId"
// Value: String; name of file in cloud storage.
public static let fileIndexCloudFileName = "cloudFileName"
// Value: String; A valid MIME type
public static let fileIndexMimeType = "mimeType"
// Value: JSON structure; app-specific meta data
public static let fileIndexAppMetaData = "appMetaData"
// Value: Boolean; Has file been deleted?
public static let fileIndexDeleted = "deleted"
// Value: Integer; version of file
public static let fileIndexFileVersion = "fileVersion"
// Value: String; a Javascript date.
public static let fileIndexLastModified = "lastModified"
// Value: Integer; The size of the file in cloud storage.
public static let fileSizeBytes = "fileSizeBytes"
// These are returned on a successful call to operationCheckOperationStatus. Note that "successful" doesn't mean the server operation being checked completed successfully.
// Key:
public static let resultOperationStatusCodeKey = "ServerOperationStatusCode"
// Values: Numeric values as indicated in rc's for OperationStatus below.
// Key:
public static let resultOperationStatusErrorKey = "ServerOperationStatusError"
// Values: Will be empty if no error occurred, and otherwise has a string describing the error.
// Key:
public static let resultInvitationContentsKey = "InvitationContents"
// Value: A JSON structure with the following keys:
// SubKey:
public static let invitationExpiryDate = "ExpiryDate"
// Value: A string giving a date
// SubKey:
public static let invitationOwningUser = "OwningUser"
// Value: A unique id for the owning user.
// SubKey:
public static let invitationSharingType = "SharingType"
// Value: A string. See SMSharingType.
// Key:
public static let resultOperationStatusCountKey = "ServerOperationStatusCount"
// Values: The numer of cloud storage operations attempted.
// The result from operationGetLinkedAccountsForSharingUser
// Key:
public static let resultLinkedAccountsKey = "LinkedAccounts"
// Values: An array with JSON objects with the following keys:
// SubKey:
// public static let internalUserId = "InternalUserId" // already defined
// SubKey:
// public static let accountUserName = "UserName" // already defined
// SubKey:
public static let accountSharingType = "SharingType"
// Value: A string. See SMSharingType.
// MARK: Results from lock operation
public static let resultLockHeldPreviously = "LockHeldPreviously"
// Values: A Bool.
// MARK: Server result codes (rc's)
// Common result codes
// Generic success! Some of the other result codes below also can indicate success.
public static let rcOK = 0
public static let rcUndefinedOperation = 1
public static let rcOperationFailed = 2
// The IdToken was stale and needs to be refreshed.
public static let rcStaleUserSecurityInfo = 3
// An error due to the way the server API was used. This error is *not* recoverable in the sense that the server API caller should not try to use operationFileChangesRecovery or other such recovery operations to just repeat the request because without changes the operation will just fail again.
public static let rcServerAPIError = 4
public static let rcNetworkFailure = 5
// Used only by client side: To indicate that a return code could not be obtained.
public static let rcInternalError = 6
public static let rcUserOnSystem = 51
public static let rcUserNotOnSystem = 52
// 2/13/16; This is not necessarily an API error. E.g., I just ran into a situation where a lock wasn't obtained (because it was held by another app/device), and this resulted in an attempted upload recovery. And the upload recovery failed because the lock wasn't held.
public static let rcLockNotHeld = 53
public static let rcNoOperationId = 54
// This will be because the invitation didn't exist, because it expired, or because it already had been redeemed.
public static let rcCouldNotRedeemSharingInvitation = 60
// rc's for serverOperationCheckForExistingUser
// rcUserOnSystem
// rcUserNotOnSystem
// rcOperationFailed: error
// rc's for operationCreateNewUser
// rcOK (new user was created).
// rcUserOnSystem: Informational response; could be an error in app, depending on context.
// rcOperationFailed: error
// operationStartUploads
public static let rcLockAlreadyHeld = 100
// rc's for OperationStatus
// The operation hasn't started asynchronous operation yet.
public static let rcOperationStatusNotStarted = 200
// Operation is in asynchronous operation. It is running after operationCommitChanges returned success to the REST/API caller.
public static let rcOperationStatusInProgress = 201
// These three can occur after the commit returns success to the client/app. For purposes of recovering from failure, the following three statuses should be taken to be the same-- just indicating failure. Use the resultOperationStatusCountKey to determine what kind of recovery to perform.
public static let rcOperationStatusFailedBeforeTransfer = 202
public static let rcOperationStatusFailedDuringTransfer = 203
public static let rcOperationStatusFailedAfterTransfer = 204
public static let rcOperationStatusSuccessfulCompletion = 210
// rc's for operationFileChangesRecovery
// Really the same as rcOperationStatusInProgress, but making this a different different value because of the Swift -> Javascript conversion.
public static let rcOperationInProgress = 300
// -------- Other constants --------
// Used in the file upload form. This is not a key specifically, but has to correspond to that used on the server.
public static let fileUploadFieldName = "file"
// Also used in file upload. Gives JSON parameters that must be parsed on server.
public static let serverParametersForFileUpload = "serverParams"
//SERVER-CONSTANTS-END
// Don't change the preceding constant. I'm using it to extract constants and use them in Node.js
} | c013ea20f6155ece1ba7d1900a6a8fc2 | 49.269802 | 378 | 0.717845 | false | false | false | false |
tbointeractive/TBODeveloperOverlay | refs/heads/develop | TBODeveloperOverlay/TBODeveloperOverlay/SectionDatasource.swift | mit | 1 | //
// SectionDatasource.swift
// TBODeveloperOverlay
//
// Created by Cornelius Horstmann on 28.07.17.
// Copyright © 2017 TBO Interactive GmbH & CO KG. All rights reserved.
//
import Foundation
public final class Datasource: NSObject, UITableViewDataSource {
let sections: [Section]
public init(sections: [Section]) {
self.sections = sections
}
public func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].items.count
}
public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section].title
}
public func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return sections[section].footer
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = self.item(at: indexPath)
let cell = tableView.dequeueReusableCell(withIdentifier: item.reuseIdentifier) ??
UITableViewCell(style: .subtitle, reuseIdentifier: item.reuseIdentifier)
switch item {
case .info(let title, let detail):
cell.textLabel?.text = title
cell.textLabel?.numberOfLines = 0
cell.detailTextLabel?.text = detail
cell.detailTextLabel?.numberOfLines = 0
cell.selectionStyle = .none
case .segue(let title, let detail, _, _):
cell.textLabel?.text = title
cell.detailTextLabel?.text = detail
cell.accessoryType = .disclosureIndicator
case .action(let title, let detail, _, _):
cell.textLabel?.text = title
cell.detailTextLabel?.text = detail
}
return cell
}
public func item(at indexPath: IndexPath) -> Section.Item {
guard indexPath.section < sections.count else { fatalError("indexPath.section out of bounds")}
guard indexPath.row < sections[indexPath.section].items.count else { fatalError("indexPath.row out of bounds")}
return sections[indexPath.section].items[indexPath.row]
}
}
| 1b1a71520188e75fe2b92fd3b4a22068 | 35.296875 | 119 | 0.649591 | false | false | false | false |
antonio081014/LeetCode-CodeBase | refs/heads/main | Swift/3sum-with-multiplicity.swift | mit | 1 | class Solution {
/// - Complexity:
/// - Time: O(nlogn + m * m), where n = arr.count, m is the number of unique keys in arr.
/// - Space: O(m), m is the number of unique keys in arr.
func threeSumMulti(_ arr: [Int], _ target: Int) -> Int {
let MOD = 1_000_000_007
var count = [Int : Int]()
for c in arr {
count[c, default: 0] += 1
}
let keys = count.keys.sorted()
var result = 0
let n = keys.count
for index in 0 ..< n {
var left = index + 1
var right = n - 1
let sum = target - keys[index]
/// Case: x < y <= z
while left <= right {
if keys[left] + keys[right] < sum {
left += 1
} else if keys[left] + keys[right] > sum {
right -= 1
} else {
if left != right {
result += (count[keys[index], default: 0] * count[keys[left], default: 0] * count[keys[right], default: 0]) % MOD
result %= MOD
} else {
let c = count[keys[left], default: 0]
result += (count[keys[index], default: 0] * (c) * (c - 1) / 2) % MOD
result %= MOD
}
left += 1
right -= 1
}
}
let leftover = target - keys[index] - keys[index]
/// Case: first two elements are the same, 3rd element is a larger number.
if leftover > keys[index] {
let c = count[keys[index], default: 0]
result += (count[leftover, default: 0] * (c) * (c - 1) / 2) % MOD
result %= MOD
}
/// Case: all 3 number are identical.
if leftover == keys[index] {
let c = count[keys[index], default: 0]
result += ((c) * (c - 1) * (c - 2) / 6) % MOD
result %= MOD
}
// print(keys[index], sum, result)
}
return result
}
}
| b3a6a265a8d7a17c5fea5e7a3a1ff902 | 37.298246 | 137 | 0.400366 | false | false | false | false |
cyrilwei/TCCalendar | refs/heads/master | Sources/TCCalendarViewWeekdayCell.swift | mit | 1 | //
// TCCalendarViewWeekdayCell.swift
// TCCalendar
//
// Copyright (c) 2015 Cyril Wei
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
class TCCalendarViewWeekdayCell: UICollectionViewCell {
var weekdayLabel: UILabel!
override func prepareForReuse() {
super.prepareForReuse()
reset()
}
private func reset() {
backgroundView = nil
weekdayLabel.text = ""
}
private func addDayLabel() {
weekdayLabel = UILabel(frame: self.bounds)
weekdayLabel.textAlignment = .Center
weekdayLabel.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(weekdayLabel)
let views = ["dayLabel": weekdayLabel]
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[dayLabel]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[dayLabel]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
}
func initialize() {
addDayLabel()
reset()
}
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
}
extension TCCalendarViewWeekdayCell {
dynamic func setFont(font: UIFont) {
self.weekdayLabel?.font = font
}
dynamic func setTextColor(color: UIColor) {
self.weekdayLabel?.textColor = color
}
} | 819375884391d29b02c2379f3f6b6979 | 32.4875 | 166 | 0.68596 | false | false | false | false |
Mclarenyang/medicine_aid | refs/heads/master | medicine aid/QRCodeViewController.swift | apache-2.0 | 1 | //
// QRCodeViewController.swift
// CodeScanner
//
// Created by zhuxuhong on 2017/4/19.
// Copyright © 2017年 zhuxuhong. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import RealmSwift
class QRCodeViewController: UIViewController {
static var QRResult = ""
fileprivate lazy var topBar: UINavigationBar = {
let bar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 64))
bar.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
let item = UINavigationItem(title: "扫一扫")
let leftBtn = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(QRCodeViewController.actionForBarButtonItemClicked(_:)))
let rightBtn = UIBarButtonItem(title: "相册", style: .plain, target: self, action: #selector(QRCodeViewController.actionForBarButtonItemClicked(_:)))
item.leftBarButtonItem = leftBtn
item.rightBarButtonItem = rightBtn
bar.items = [item]
return bar
}()
fileprivate lazy var readerView: QRCodeReaderView = {
let h = self.topBar.bounds.height
let frame = CGRect(x: 0, y: h, width: self.view.bounds.width, height: self.view.bounds.height-h)
let v = QRCodeReaderView(frame: frame)
v.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return v
}()
public var completion: QRCodeReaderCompletion?
convenience init(completion: QRCodeReaderCompletion?) {
self.init()
self.completion = completion
}
}
extension QRCodeViewController{
override func viewDidLoad() {
super.viewDidLoad()
let rightBtn = UIBarButtonItem(title: "相册", style: .plain, target: self, action: #selector(QRCodeViewController.actionForBarButtonItemClicked(_:)))
self.navigationItem.rightBarButtonItem = rightBtn
//view.addSubview(topBar)
if QRCodeReader.isDeviceAvailable() && !QRCodeReader.isCameraUseDenied(){
setupReader()
}
}
override func viewWillAppear(_ animated: Bool){
super.viewWillAppear(animated)
guard QRCodeReader.isDeviceAvailable() else{
let alert = UIAlertController(title: "Error", message: "相机无法使用", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "好", style: .cancel, handler: {
_ in
self.dismiss(animated: true, completion: nil)
}))
present(alert, animated: true, completion: nil)
return
}
if QRCodeReader.isCameraUseDenied(){
hanldeAlertForAuthorization(isCamera: true)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if QRCodeReader.isCameraUseAuthorized(){
readerView.updateRectOfOutput()
}
}
// MARK: - action & IBOutletAction
@IBAction func actionForBarButtonItemClicked(_ sender: UIBarButtonItem){
guard let item = topBar.items!.first else {
return
}
if sender == item.leftBarButtonItem! {
completionFor(result: nil, isCancel: true)
}
else if sender == self.navigationItem.rightBarButtonItem! {
handleActionForImagePicker()
}
}
fileprivate func completionFor(result: String?, isCancel: Bool){
readerView.reader.stopScanning()
dismiss(animated: true, completion: {
isCancel ? nil : self.completion?(result ?? "没有发现任何信息")
})
}
}
extension QRCodeViewController{
fileprivate func handleActionForImagePicker(){
if QRCodeReader.isAlbumUseDenied() {
hanldeAlertForAuthorization(isCamera: false)
return
}
readerView.reader.stopScanning()
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .savedPhotosAlbum
picker.allowsEditing = false
present(picker, animated: true, completion: nil)
}
fileprivate func setupReader(){
view.addSubview(readerView)
readerView.setup(completion: {[unowned self]
(result) in
self.completionFor(result: result, isCancel: false)
})
}
fileprivate func openSystemSettings(){
let url = URL(string: UIApplicationOpenSettingsURLString)!
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
fileprivate func hanldeAlertForAuthorization(isCamera: Bool){
let str = isCamera ? "相机" : "相册"
let alert = UIAlertController(title: "\(str)没有授权", message: "在[设置]中找到应用,开启[允许访问\(str)]", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "去设置", style: .cancel, handler: { _ in
self.openSystemSettings()
}))
present(alert, animated: true, completion: nil)
}
fileprivate func handleQRCodeScanningFor(image: UIImage){
let ciimage = CIImage(cgImage: image.cgImage!)
let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])
if let features = detector?.features(in: ciimage),
let first = features.first as? CIQRCodeFeature{
self.completionFor(result: first.messageString, isCancel: false)
///相册扫描结果
NSLog(first.messageString!)
QRCodeViewController.QRResult = first.messageString!
//ID
let defaults = UserDefaults.standard
let UserID = defaults.value(forKey: "UserID")!
//直接链接
//提示
let alert = UIAlertController(title: "提示", message: "确定挂号排队?", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
let doneAction = UIAlertAction(title: "好", style: .default, handler: {
action in
let url = AESEncoding.myURL + "igds/app/link"
let parameters: Parameters = [
"doctorId":first.messageString!,
"patientId":UserID
]
Alamofire.request(url, method: .post, parameters: parameters).responseJSON{
classValue in
if let value = classValue.result.value{
let json = JSON(value)
let code = json["code"]
print("患者挂号code:\(code)")
if code == 201{
//挂号信息本地化
saveRegister(doctorID: first.messageString!)
let queueView = queueViewController()
queueView.doctorID = first.messageString!
self.navigationController?.pushViewController(queueView, animated: true)
//储存挂号医生的ID,用于已挂查询
let defaults = UserDefaults.standard
defaults.set(first.messageString!, forKey: "doctorID")
//更新挂号状态
defaults.set("yes", forKey: "status")
}else if code == 403{
let alert = UIAlertController(title: "提示", message: "您已经挂号,请勿重复提交", preferredStyle: .alert)
let doneAction = UIAlertAction(title: "好", style: .default, handler:{
action in
let queueView = queueViewController()
queueView.doctorID = first.messageString!
self.navigationController?.pushViewController(queueView, animated: true)
})
alert.addAction(doneAction)
self.present(alert, animated: true, completion: nil)
}else{
let alert = UIAlertController(title: "链接错误", message: "你可能扫了一个假的二维码", preferredStyle: .alert)
let doneAction = UIAlertAction(title: "好", style: .default, handler:{
action in
_ = self.navigationController?.popViewController(animated: true)
})
alert.addAction(doneAction)
self.present(alert, animated: true, completion: nil)
}
}
}
})
alert.addAction(cancelAction)
alert.addAction(doneAction)
self.present(alert, animated: true, completion: nil)
}
}
}
//挂号本地化
func saveRegister(doctorID: String){
//读取储存信息
//ID
let defaults = UserDefaults.standard
let UserID = String(describing: defaults.value(forKey: "UserID")!)
//读Type
let realm = try! Realm()
let patientNickname = realm.objects(UserText.self).filter("UserID = '\(UserID)'")[0].UserNickname
//时间
let now = Date()
let dformatter = DateFormatter()
dformatter.dateFormat = "yyyy年MM月dd日 HH:mm:ss"
print("当前日期时间:\(dformatter.string(from: now))")
let time = dformatter.string(from: now)
//存储
let dprlist = DPRList()
dprlist.DoctorID = doctorID
dprlist.PatientID = UserID
//dprlist.DocrorNickname = doctorNickname
dprlist.PatientNickname = patientNickname
dprlist.Time = time
//dprlist.MedicalList = medicalStr
try! realm.write {
realm.add(dprlist)
}
}
extension QRCodeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
readerView.reader.startScanning(completion: completion)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
picker.dismiss(animated: true, completion: {
self.handleQRCodeScanningFor(image: image)
})
}
}
}
extension QRCodeViewController{
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
if QRCodeReader.isDeviceAvailable() && QRCodeReader.isCameraUseAuthorized() {
readerView.updateRectOfOutput()
}
}
}
| 4c705fc5dfe9f9234902492856216466 | 34.901899 | 155 | 0.55152 | false | false | false | false |
skylib/SnapImagePicker | refs/heads/master | SnapImagePicker/SnapImagePickerTransition.swift | bsd-3-clause | 1 | import Foundation
import UIKit
class VerticalSlideTransitionManager : NSObject, UIViewControllerAnimatedTransitioning {
let animationDuration = 0.3
let action: Action
enum Action {
case push
case pop
}
init(action: Action) {
self.action = action
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return animationDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if action == .push {
push(transitionContext)
} else {
pop(transitionContext)
}
}
func push(_ transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
if let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) {
containerView.addSubview(toView)
let size = containerView.bounds.size
let initalFrame = CGRect(x: CGFloat(0.0), y: -size.height, width: size.width, height: size.height)
let finalFrame = containerView.bounds
toView.frame = initalFrame
UIView.animate(withDuration: animationDuration,
animations: { toView.frame = finalFrame },
completion: { _ in transitionContext.completeTransition(true) })
}
}
func pop(_ transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView
if let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from),
let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) {
let size = containerView.bounds.size
let finalFrame = CGRect(x: CGFloat(0.0), y: -size.height, width: size.width, height: size.height)
toView.frame = CGRect(x: CGFloat(0.0), y: 0, width: size.width, height: size.height)
containerView.addSubview(toView)
containerView.sendSubview(toBack: toView)
UIView.animate(withDuration: animationDuration,
animations: {fromView.frame = finalFrame},
completion: { _ in transitionContext.completeTransition(true)})
}
}
}
open class SnapImagePickerNavigationControllerDelegate: NSObject, UINavigationControllerDelegate, UIViewControllerTransitioningDelegate {
public override init() {
super.init()
}
open func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch operation {
case .none: return nil
case .push: return VerticalSlideTransitionManager(action: .push)
case .pop: return VerticalSlideTransitionManager(action: .pop)
}
}
}
| ae5147d366336f1b4766bf06f146b1e9 | 40.76 | 251 | 0.648787 | false | false | false | false |
Ansem717/PictureFeed | refs/heads/master | PictureFeed/Post.swift | mit | 1 | //
// Post.swift
// PictureFeed
//
// Created by Andy Malik on 2/16/16.
// Copyright © 2016 Andy Malik. All rights reserved.
//
import UIKit
import CloudKit
enum PostError: ErrorType {
case WritingImage
case CreatingCKRecord
}
class Post {
let image: UIImage
let status: String?
init(image: UIImage, status: String? = "") {
self.image = image
self.status = status
}
}
extension Post {
class func recordWith(post: Post) throws -> CKRecord? {
let imageURL = NSURL.imageURL()
guard let imgData = UIImageJPEGRepresentation(post.image, 0.7) else { throw PostError.WritingImage }
let saved = imgData.writeToURL(imageURL, atomically: true)
if saved {
let asset = CKAsset(fileURL: imageURL)
let record = CKRecord(recordType: "Post")
record.setObject(asset, forKey: "image")
return record
} else { throw PostError.CreatingCKRecord }
}
} | c42d32f4b18f6e791e8374d8f2e1b8fb | 21.148936 | 108 | 0.591346 | false | false | false | false |
AckeeCZ/ACKReactiveExtensions | refs/heads/master | ACKReactiveExtensions/Realm/RealmExtensions.swift | mit | 1 | //
// RealmExtensions.swift
// Realm
//
// Created by Tomáš Kohout on 01/12/15.
// Copyright © 2015 Ackee s.r.o. All rights reserved.
//
import UIKit
import RealmSwift
import ReactiveCocoa
import ReactiveSwift
#if !COCOAPODS
import ACKReactiveExtensionsCore
#endif
/// Error return in case of Realm operation failure
public struct RealmError: Error {
public let underlyingError: NSError
public init(underlyingError: NSError){
self.underlyingError = underlyingError
}
}
/// Enum which represents RealmCollectionChange
public enum Change<T> {
typealias Element = T
/// Initial value
case initial(T)
/// RealmCollection was updated
case update(T, deletions: [Int], insertions: [Int], modifications: [Int])
}
public extension Reactive where Base: RealmCollection {
/// SignalProducer that sends changes as they happen
var changes: SignalProducer<Change<Base>, RealmError> {
var notificationToken: NotificationToken? = nil
let producer: SignalProducer<Change<Base>, RealmError> = SignalProducer { sink, d in
guard let realm = self.base.realm else {
print("Cannot observe object without Realm")
return
}
func observe() -> NotificationToken? {
return self.base.observe(on: OperationQueue.current?.underlyingQueue) { changes in
switch changes {
case .initial(let initial):
sink.send(value: Change.initial(initial))
case .update(let updates, let deletions, let insertions, let modifications):
sink.send(value: Change.update(updates, deletions: deletions, insertions: insertions, modifications: modifications))
case .error(let e):
sink.send(error: RealmError(underlyingError: e as NSError))
}
}
}
let registerObserverIfPossible: () -> (Bool, NotificationToken?) = {
if !realm.isInWriteTransaction { return (true, observe()) }
return (false, nil)
}
var counter = 0
let maxRetries = 10
func registerWhileNotSuccessful(queue: DispatchQueue) {
let (registered, token) = registerObserverIfPossible()
guard !registered, counter < maxRetries else { notificationToken = token; return }
counter += 1
queue.async { registerWhileNotSuccessful(queue: queue) }
}
if let opQueue = OperationQueue.current, let dispatchQueue = opQueue.underlyingQueue {
registerWhileNotSuccessful(queue: dispatchQueue)
} else {
notificationToken = observe()
}
}.on(terminated: {
notificationToken?.invalidate()
notificationToken = nil
}, disposed: {
notificationToken?.invalidate()
notificationToken = nil
})
return producer
}
/// SignalProducer that sends the latest value
var values: SignalProducer<Base, RealmError> {
return self.changes.map { changes -> Base in
switch changes {
case .initial(let initial):
return initial
case .update(let updates, _, _, _):
return updates
}
}
}
/// Property which represents the latest value
var property: ReactiveSwift.Property<Base> {
return ReactiveSwift.Property(initial: base, then: values.ignoreError() )
}
}
//MARK: Saving
public extension Reactive where Base: Object {
/**
* Reactive save Realm object
*
* - parameter update: Realm should find existing object using primaryKey() and update it if it exists otherwise create new object
* - parameter writeBlock: Closure which allows custom Realm operation instead of default add
*/
func save(update: Realm.UpdatePolicy = .all, writeBlock: ((Realm)->Void)? = nil) -> SignalProducer<Base, RealmError>{
return SignalProducer<Base, RealmError> { sink, d in
do {
let realm = try Realm()
realm.refresh()
try realm.write {
if let writeBlock = writeBlock {
writeBlock(realm)
} else {
realm.add(self.base, update: update)
}
}
sink.send(value: self.base)
sink.sendCompleted()
} catch (let e) {
sink.send(error: RealmError(underlyingError: e as NSError) )
}
}
}
/**
* Reactively delete object
*/
func delete() -> SignalProducer<(), RealmError> {
return SignalProducer { sink, d in
do {
let realm = try Realm()
realm.refresh()
try realm.write {
realm.delete(self.base)
}
sink.send(value: ())
sink.sendCompleted()
} catch (let e) {
sink.send(error: RealmError(underlyingError: e as NSError) )
}
}
}
var changes: SignalProducer<ObjectChange<ObjectBase>, RealmError> {
var notificationToken: NotificationToken? = nil
let producer: SignalProducer<ObjectChange<ObjectBase>, RealmError> = SignalProducer { sink, d in
guard let realm = self.base.realm else {
print("Cannot observe object without Realm")
return
}
func observe() -> NotificationToken? {
return self.base.observe { change in
switch change {
case .error(let e):
sink.send(error: RealmError(underlyingError: e))
default:
sink.send(value: change)
}
}
}
let registerObserverIfPossible: () -> (Bool, NotificationToken?) = {
if !realm.isInWriteTransaction { return (true, observe()) }
return (false, nil)
}
var counter = 0
let maxRetries = 10
func registerWhileNotSuccessful(queue: DispatchQueue) {
let (registered, token) = registerObserverIfPossible()
guard !registered, counter < maxRetries else { notificationToken = token; return }
counter += 1
queue.async { registerWhileNotSuccessful(queue: queue) }
}
if let opQueue = OperationQueue.current, let dispatchQueue = opQueue.underlyingQueue {
registerWhileNotSuccessful(queue: dispatchQueue)
} else {
notificationToken = observe()
}
}.on(terminated: {
notificationToken?.invalidate()
notificationToken = nil
}, disposed: {
notificationToken?.invalidate()
notificationToken = nil
})
return producer
}
var values: SignalProducer<Base, RealmError> {
return self.changes
.filter { if case .deleted = $0 { return false }; return true }
.map { _ in
return self.base
}
}
var property: ReactiveSwift.Property<Base> {
return ReactiveSwift.Property(initial: base, then: values.ignoreError() )
}
}
//MARK: Table view
/// Protocol which allows UITableView to be reloaded automatically when database changes happen
public protocol RealmTableViewReloading {
associatedtype Element: Object
var tableView: UITableView! { get set }
}
public extension Reactive where Base: UIViewController, Base: RealmTableViewReloading {
/// Binding target which updates tableView according to received changes
var changes: BindingTarget<Change<Results<Base.Element>>> {
return makeBindingTarget { vc, changes in
guard let tableView = vc.tableView else { return }
switch changes {
case .initial:
tableView.reloadData()
break
case .update(_, let deletions, let insertions, let modifications):
tableView.beginUpdates()
tableView.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0) }),
with: .automatic)
tableView.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0)}),
with: .automatic)
tableView.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0) }),
with: .automatic)
tableView.endUpdates()
break
}
}
}
}
//MARK: PrimaryKeyEquatable
protocol PrimaryKeyEquatable: AnyObject {
static func primaryKey() -> String?
subscript(key: String) -> Any? { get set }
}
extension Object: PrimaryKeyEquatable {}
precedencegroup PrimaryKeyEquative {
associativity: left
}
infix operator ~== : PrimaryKeyEquative
func ~==(lhs: PrimaryKeyEquatable, rhs: PrimaryKeyEquatable) -> Bool {
//Super ugly but can't find nicer way to assert same types
guard "\(type(of: lhs))" == "\(type(of: rhs))" else {
assertionFailure("Trying to compare different types \(type(of: lhs)) and \(type(of: rhs))")
return false
}
guard let primaryKey = type(of: lhs).primaryKey(), let lValue = lhs[primaryKey],
let rValue = rhs[primaryKey] else {
assertionFailure("Trying to compare object that has no primary key")
return false
}
if let l = lValue as? String, let r = rValue as? String {
return l == r
} else if let l = lValue as? Int, let r = rValue as? Int {
return l == r
} else if let l = lValue as? Int8, let r = rValue as? Int8 {
return l == r
} else if let l = lValue as? Int16, let r = rValue as? Int16 {
return l == r
} else if let l = lValue as? Int32, let r = rValue as? Int32 {
return l == r
} else if let l = lValue as? Int64, let r = rValue as? Int64 {
return l == r
} else {
assertionFailure("Unsupported primary key")
return false
}
}
//MARK: Orphaned Object
extension Realm {
/// Add objects and delete non-present objects from the orphan query
public func add<S: Sequence>(_ objects: S, update: Realm.UpdatePolicy = .all, deleteOrphanedQuery: Results<S.Iterator.Element>) where S.Iterator.Element: Object {
let allObjects = deleteOrphanedQuery.map { $0 }
//This could be faster with set, but we can't redefine hashable
let objectsToDelete = allObjects.filter { old in
!objects.contains(where: {
old ~== $0
})
}
self.delete(objectsToDelete)
self.add(objects, update: update)
}
}
| 55e825c9cda321f9c40709cdcf7a5f27 | 33.04908 | 166 | 0.568919 | false | false | false | false |
couchbaselabs/mini-hacks | refs/heads/master | google-sign-in/SimpleLogin/SimpleLogin/CreateSyncGatewaySession.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
import XCPlayground
// Let asynchronous code run
XCPSetExecutionShouldContinueIndefinitely()
let userId = "4567891023456789012340000000000000000000000000"
// 1
let loginURL = NSURL(string: "http://localhost:8000/google_signin")!
// 2
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: loginURL)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
// 3
var properties = [
"user_id": userId,
"auth_provider": "google"
]
let data = try! NSJSONSerialization.dataWithJSONObject(properties, options: NSJSONWritingOptions.PrettyPrinted)
// 4
let uploadTask = session.uploadTaskWithRequest(request, fromData: data, completionHandler: { (data, response, error) -> Void in
// 5
let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! Dictionary<String, AnyObject>
print("\(json)")
// TODO: pull/push replications with authenticated user
})
uploadTask.resume()
| 240587d207c7667db3e0020cc7804c12 | 28.675676 | 145 | 0.752051 | false | false | false | false |
halonsoluis/ViewControllerHideButtonExample | refs/heads/master | ChangeValueViewControllerExample/SecondViewController.swift | gpl-2.0 | 1 | //
// SecondViewController.swift
// ChangeValueViewControllerExample
//
// Created by Hugo on 12/1/15.
// Copyright © 2015 halonso. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 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.
}
func initFirstViewController() -> FirstViewController {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let firstViewController = storyboard.instantiateViewControllerWithIdentifier("FirstViewController") as! FirstViewController
return firstViewController
}
@IBAction func ShowNextViewWithButton(sender: AnyObject) {
let firstViewController = initFirstViewController()
self.presentViewController(firstViewController, animated: true, completion: {
//This lines will be called after the view is loaded so the code will run
firstViewController.firstButton.alpha = 1
})
}
@IBAction func ShowNextViewWithoutButton(sender: AnyObject) {
let firstViewController = initFirstViewController()
self.presentViewController(firstViewController, animated: true, completion: {
//This lines will be called after the view is loaded so the code will run
firstViewController.firstButton.alpha = 0
})
}
@IBAction func ShowNextViewWithButtonInit(sender: AnyObject) {
let firstViewController = initFirstViewController()
firstViewController.showButton = true
self.presentViewController(firstViewController, animated: true, completion: nil)
}
@IBAction func ShowNextViewWithoutButtonInit(sender: AnyObject) {
let firstViewController = initFirstViewController()
firstViewController.showButton = false
self.presentViewController(firstViewController, animated: true, completion: nil)
}
} | 304af60b95bff2d7301198d6a0ce8a9c | 34.193548 | 131 | 0.687758 | false | false | false | false |
leonereveel/Moya | refs/heads/master | Source/Moya+Internal.swift | mit | 1 | import Foundation
import Result
/// Internal extension to keep the inner-workings outside the main Moya.swift file.
internal extension MoyaProvider {
// Yup, we're disabling these. The function is complicated, but breaking it apart requires a large effort.
// swiftlint:disable cyclomatic_complexity
// swiftlint:disable function_body_length
/// Performs normal requests.
func requestNormal(target: Target, queue: dispatch_queue_t?, progress: Moya.ProgressBlock?, completion: Moya.Completion) -> Cancellable {
let endpoint = self.endpoint(target)
let stubBehavior = self.stubClosure(target)
let cancellableToken = CancellableWrapper()
if trackInflights {
objc_sync_enter(self)
var inflightCompletionBlocks = self.inflightRequests[endpoint]
inflightCompletionBlocks?.append(completion)
self.inflightRequests[endpoint] = inflightCompletionBlocks
objc_sync_exit(self)
if inflightCompletionBlocks != nil {
return cancellableToken
} else {
objc_sync_enter(self)
self.inflightRequests[endpoint] = [completion]
objc_sync_exit(self)
}
}
let performNetworking = { (requestResult: Result<NSURLRequest, Moya.Error>) in
if cancellableToken.cancelled {
self.cancelCompletion(completion, target: target)
return
}
var request: NSURLRequest!
switch requestResult {
case .Success(let urlRequest):
request = urlRequest
case .Failure(let error):
completion(result: .Failure(error))
return
}
switch stubBehavior {
case .Never:
let networkCompletion: Moya.Completion = { result in
if self.trackInflights {
self.inflightRequests[endpoint]?.forEach({ $0(result: result) })
objc_sync_enter(self)
self.inflightRequests.removeValueForKey(endpoint)
objc_sync_exit(self)
} else {
completion(result: result)
}
}
switch target.task {
case .Request:
cancellableToken.innerCancellable = self.sendRequest(target, request: request, queue: queue, progress: progress, completion: networkCompletion)
case .Upload(.File(let file)):
cancellableToken.innerCancellable = self.sendUploadFile(target, request: request, queue: queue, file: file, progress: progress, completion: networkCompletion)
case .Upload(.Multipart(let multipartBody)):
guard !multipartBody.isEmpty && target.method.supportsMultipart else {
fatalError("\(target) is not a multipart upload target.")
}
cancellableToken.innerCancellable = self.sendUploadMultipart(target, request: request, queue: queue, multipartBody: multipartBody, progress: progress, completion: networkCompletion)
case .Download(.Request(let destination)):
cancellableToken.innerCancellable = self.sendDownloadRequest(target, request: request, queue: queue, destination: destination, progress: progress, completion: networkCompletion)
}
default:
cancellableToken.innerCancellable = self.stubRequest(target, request: request, completion: { result in
if self.trackInflights {
self.inflightRequests[endpoint]?.forEach({ $0(result: result) })
objc_sync_enter(self)
self.inflightRequests.removeValueForKey(endpoint)
objc_sync_exit(self)
} else {
completion(result: result)
}
}, endpoint: endpoint, stubBehavior: stubBehavior)
}
}
requestClosure(endpoint, performNetworking)
return cancellableToken
}
// swiftlint:enable cyclomatic_complexity
// swiftlint:enable function_body_length
func cancelCompletion(completion: Moya.Completion, target: Target) {
let error = Moya.Error.Underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil))
plugins.forEach { $0.didReceiveResponse(.Failure(error), target: target) }
completion(result: .Failure(error))
}
/// Creates a function which, when called, executes the appropriate stubbing behavior for the given parameters.
final func createStubFunction(token: CancellableToken, forTarget target: Target, withCompletion completion: Moya.Completion, endpoint: Endpoint<Target>, plugins: [PluginType]) -> (() -> ()) {
return {
if token.cancelled {
self.cancelCompletion(completion, target: target)
return
}
switch endpoint.sampleResponseClosure() {
case .NetworkResponse(let statusCode, let data):
let response = Moya.Response(statusCode: statusCode, data: data, response: nil)
plugins.forEach { $0.didReceiveResponse(.Success(response), target: target) }
completion(result: .Success(response))
case .NetworkError(let error):
let error = Moya.Error.Underlying(error)
plugins.forEach { $0.didReceiveResponse(.Failure(error), target: target) }
completion(result: .Failure(error))
}
}
}
/// Notify all plugins that a stub is about to be performed. You must call this if overriding `stubRequest`.
final func notifyPluginsOfImpendingStub(request: NSURLRequest, target: Target) {
let alamoRequest = manager.request(request)
plugins.forEach { $0.willSendRequest(alamoRequest, target: target) }
}
}
private extension MoyaProvider {
private func sendUploadMultipart(target: Target, request: NSURLRequest, queue: dispatch_queue_t?, multipartBody: [MultipartFormData], progress: Moya.ProgressBlock? = nil, completion: Moya.Completion) -> CancellableWrapper {
let cancellable = CancellableWrapper()
let multipartFormData = { (form: RequestMultipartFormData) -> Void in
for bodyPart in multipartBody {
switch bodyPart.provider {
case .Data(let data):
self.append(data: data, bodyPart: bodyPart, to: form)
case .File(let url):
self.append(fileURL: url, bodyPart: bodyPart, to: form)
case .Stream(let stream, let length):
self.append(stream: stream, length: length, bodyPart: bodyPart, to: form)
}
}
if let parameters = target.parameters {
parameters
.flatMap { (key, value) in multipartQueryComponents(key, value) }
.forEach { (key, value) in
if let data = value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
form.appendBodyPart(data: data, name: key)
}
}
}
}
manager.upload(request, multipartFormData: multipartFormData) { (result: MultipartFormDataEncodingResult) in
switch result {
case .Success(let alamoRequest, _, _):
if cancellable.cancelled {
self.cancelCompletion(completion, target: target)
return
}
cancellable.innerCancellable = self.sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion)
case .Failure(let error):
completion(result: .Failure(Moya.Error.Underlying(error as NSError)))
}
}
return cancellable
}
private func sendUploadFile(target: Target, request: NSURLRequest, queue: dispatch_queue_t?, file: NSURL, progress: ProgressBlock? = nil, completion: Completion) -> CancellableToken {
let alamoRequest = manager.upload(request, file: file)
return self.sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion)
}
private func sendDownloadRequest(target: Target, request: NSURLRequest, queue: dispatch_queue_t?, destination: DownloadDestination, progress: ProgressBlock? = nil, completion: Completion) -> CancellableToken {
let alamoRequest = manager.download(request, destination: destination)
return self.sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion)
}
private func sendRequest(target: Target, request: NSURLRequest, queue: dispatch_queue_t?, progress: Moya.ProgressBlock?, completion: Moya.Completion) -> CancellableToken {
let alamoRequest = manager.request(request)
return sendAlamofireRequest(alamoRequest, target: target, queue: queue, progress: progress, completion: completion)
}
private func sendAlamofireRequest(alamoRequest: Request, target: Target, queue: dispatch_queue_t?, progress: Moya.ProgressBlock?, completion: Moya.Completion) -> CancellableToken {
// Give plugins the chance to alter the outgoing request
let plugins = self.plugins
plugins.forEach { $0.willSendRequest(alamoRequest, target: target) }
// Perform the actual request
if let progress = progress {
alamoRequest
.progress { (bytesWritten, totalBytesWritten, totalBytesExpected) in
let sendProgress: () -> () = {
progress(progress: ProgressResponse(totalBytes: totalBytesWritten, bytesExpected: totalBytesExpected))
}
if let queue = queue {
dispatch_async(queue, sendProgress)
} else {
sendProgress()
}
}
}
alamoRequest
.response(queue: queue) { (_, response: NSHTTPURLResponse?, data: NSData?, error: NSError?) -> () in
let result = convertResponseToResult(response, data: data, error: error)
// Inform all plugins about the response
plugins.forEach { $0.didReceiveResponse(result, target: target) }
completion(result: result)
}
alamoRequest.resume()
return CancellableToken(request: alamoRequest)
}
}
// MARK: - RequestMultipartFormData appending
private extension MoyaProvider {
private func append(data data: NSData, bodyPart: MultipartFormData, to form: RequestMultipartFormData) {
if let mimeType = bodyPart.mimeType {
if let fileName = bodyPart.fileName {
form.appendBodyPart(data: data, name: bodyPart.name, fileName: fileName, mimeType: mimeType)
} else {
form.appendBodyPart(data: data, name: bodyPart.name, mimeType: mimeType)
}
} else {
form.appendBodyPart(data: data, name: bodyPart.name)
}
}
private func append(fileURL url: NSURL, bodyPart: MultipartFormData, to form: RequestMultipartFormData) {
if let fileName = bodyPart.fileName, mimeType = bodyPart.mimeType {
form.appendBodyPart(fileURL: url, name: bodyPart.name, fileName: fileName, mimeType: mimeType)
} else {
form.appendBodyPart(fileURL: url, name: bodyPart.name)
}
}
private func append(stream stream: NSInputStream, length: UInt64, bodyPart: MultipartFormData, to form: RequestMultipartFormData) {
form.appendBodyPart(stream: stream, length: length, name: bodyPart.name, fileName: bodyPart.fileName ?? "", mimeType: bodyPart.mimeType ?? "")
}
}
/// Encode parameters for multipart/form-data
private func multipartQueryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += multipartQueryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += multipartQueryComponents("\(key)[]", value)
}
} else {
components.append((key, "\(value)"))
}
return components
}
| 4e43fbec51216d2dd23428eb1597341c | 46.842105 | 227 | 0.61614 | false | false | false | false |
marcosjvivar/WWE-iOS-Code-Test | refs/heads/development | WWEMobile/Model/Application/Video/WWEVideoTag.swift | mit | 1 | //
// WWEVideoTag.swift
// WWEMobile
//
// Created by Marcos Jesús Vivar on 8/25/17.
// Copyright © 2017 Spark Digital. All rights reserved.
//
import UIKit
import SwiftyJSON
import RealmSwift
class WWEVideoTag: Object {
dynamic var tagID: Int = 0
dynamic var tagType: String = ""
dynamic var tagTitle: String = ""
static func create(json: JSON) -> WWEVideoTag {
let tag = WWEVideoTag()
tag.tagID = json[attributes.id.rawValue].intValue
tag.tagTitle = json[attributes.title.rawValue].stringValue
tag.tagType = json[attributes.type.rawValue].stringValue
return tag
}
}
| f8aa6f01aa05d4b4edbfabd4853aac5c | 22.137931 | 66 | 0.636364 | false | false | false | false |
KamilSwojak/TagListView | refs/heads/master | TagListView/TagView.swift | mit | 1 | //
// TagView.swift
// TagListViewDemo
//
// Created by Dongyuan Liu on 2015-05-09.
// Copyright (c) 2015 Ela. All rights reserved.
//
import UIKit
@IBDesignable
open class TagView: UIButton {
@IBInspectable open var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable open var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable open var borderColor: UIColor? {
didSet {
reloadStyles()
}
}
@IBInspectable open var textColor: UIColor = UIColor.white {
didSet {
reloadStyles()
}
}
@IBInspectable open var selectedTextColor: UIColor = UIColor.white {
didSet {
reloadStyles()
}
}
@IBInspectable open var paddingY: CGFloat = 2 {
didSet {
titleEdgeInsets.top = paddingY
titleEdgeInsets.bottom = paddingY
}
}
@IBInspectable open var paddingX: CGFloat = 5 {
didSet {
titleEdgeInsets.left = paddingX
updateRightInsets()
}
}
@IBInspectable open var tagBackgroundColor: UIColor = UIColor.gray {
didSet {
reloadStyles()
}
}
@IBInspectable open var highlightedBackgroundColor: UIColor? {
didSet {
reloadStyles()
}
}
@IBInspectable open var selectedBorderColor: UIColor? {
didSet {
reloadStyles()
}
}
@IBInspectable open var selectedBackgroundColor: UIColor? {
didSet {
reloadStyles()
}
}
var textFont: UIFont = UIFont.systemFont(ofSize: 12) {
didSet {
titleLabel?.font = textFont
}
}
private func reloadStyles() {
if isHighlighted {
if let highlightedBackgroundColor = highlightedBackgroundColor {
// For highlighted, if it's nil, we should not fallback to backgroundColor.
// Instead, we keep the current color.
backgroundColor = highlightedBackgroundColor
}
}
else if isSelected {
backgroundColor = selectedBackgroundColor ?? tagBackgroundColor
layer.borderColor = selectedBorderColor?.cgColor ?? borderColor?.cgColor
setTitleColor(selectedTextColor, for: UIControlState())
}
else {
backgroundColor = tagBackgroundColor
layer.borderColor = borderColor?.cgColor
setTitleColor(textColor, for: UIControlState())
}
}
override open var isHighlighted: Bool {
didSet {
reloadStyles()
}
}
override open var isSelected: Bool {
didSet {
reloadStyles()
}
}
// MARK: remove button
let removeButton = CloseButton()
@IBInspectable open var enableRemoveButton: Bool = false {
didSet {
removeButton.isHidden = !enableRemoveButton
updateRightInsets()
}
}
@IBInspectable open var removeButtonIconSize: CGFloat = 12 {
didSet {
removeButton.iconSize = removeButtonIconSize
updateRightInsets()
}
}
@IBInspectable open var removeIconLineWidth: CGFloat = 3 {
didSet {
removeButton.lineWidth = removeIconLineWidth
}
}
@IBInspectable open var removeIconLineColor: UIColor = UIColor.white.withAlphaComponent(0.54) {
didSet {
removeButton.lineColor = removeIconLineColor
}
}
/// Handles Tap (TouchUpInside)
open var onTap: ((TagView) -> Void)?
open var onLongPress: ((TagView) -> Void)?
// MARK: - init
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
public init(title: String) {
super.init(frame: CGRect.zero)
setTitle(title, for: UIControlState())
setupView()
}
private func setupView() {
frame.size = intrinsicContentSize
addSubview(removeButton)
removeButton.tagView = self
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(self.longPress))
self.addGestureRecognizer(longPress)
}
@objc func longPress() {
onLongPress?(self)
}
// MARK: - layout
override open var intrinsicContentSize: CGSize {
var size = titleLabel?.text?.size(withAttributes: [NSAttributedStringKey.font: textFont]) ?? CGSize.zero
size.height = textFont.pointSize + paddingY * 2
size.width += paddingX * 2
if size.width < size.height {
size.width = size.height
}
if enableRemoveButton {
size.width += removeButtonIconSize + paddingX
}
return size
}
private func updateRightInsets() {
if enableRemoveButton {
titleEdgeInsets.right = paddingX + removeButtonIconSize + paddingX
}
else {
titleEdgeInsets.right = paddingX
}
}
open override func layoutSubviews() {
super.layoutSubviews()
if enableRemoveButton {
removeButton.frame.size.width = paddingX + removeButtonIconSize + paddingX
removeButton.frame.origin.x = self.frame.width - removeButton.frame.width
removeButton.frame.size.height = self.frame.height
removeButton.frame.origin.y = 0
}
}
}
| 590b85b5ce784c03c057fd57ef884139 | 26.052133 | 112 | 0.576209 | false | false | false | false |
tectijuana/iOS | refs/heads/master | PáramoAimeé/Practicas Libro/9 Ejercicio.swift | mit | 2 | import Foundation
func input() ->NSString {
var keyboard = NSFileHandle.fileHandleWithStandardInput()
var inputData = keyboard.availableData
return NSString(data: inputData, encoding:NSUTF8StringEncoding)!
}
print("Convertir ºC a ºF")
print("Ingresa grados centigrados")
var c, f: Double
var a = input().integerValue
var c = var a = input().integerValue
var f=(c*9/5)+32
print(c+"ºC equivale a "+f+"ºF") | 903f1ff3a1c348842a3225de062f0f8d | 25.3125 | 68 | 0.72619 | false | false | false | false |
JGiola/swift | refs/heads/main | test/SourceKit/CodeComplete/complete_sequence_builderfunc.swift | apache-2.0 | 14 | protocol Entity {}
struct Empty: Entity {
var value: Void = ()
}
@resultBuilder
struct Builder {
static func buildBlock() -> { Empty() }
static func buildBlock<T: Entity>(_ t: T) -> T { t }
}
struct MyValue {
var id: Int
var title: String
}
func build(_ arg: (MyValue) -> String) -> Empty { Empty() }
struct MyStruct {
@Builder var body: some Entity {
build { value in
value./*HERE * 2*/
} /*HERE*/
}
}
// RUN: %sourcekitd-test \
// RUN: -req=complete -pos=22:13 %s -- %s == \
// RUN: -req=complete -pos=22:13 %s -- %s == \
// RUN: -req=complete -pos=23:7 %s -- %s \
// RUN: | tee %t.result | %FileCheck %s
// CHECK-LABEL: key.results: [
// CHECK-DAG: key.description: "id"
// CHECK-DAG: key.description: "title"
// CHECK-DAG: key.description: "self"
// CHECK: ]
// CHECK-NOT: key.reusingastcontext: 1
// CHECK-LABEL: key.results: [
// CHECK-DAG: key.description: "id"
// CHECK-DAG: key.description: "title"
// CHECK-DAG: key.description: "self"
// CHECK: ]
// CHECK: key.reusingastcontext: 1
// CHECK-LABEL: key.results: [
// CHECK-DAG: key.description: "value"
// CHECK: ]
// CHECK: key.reusingastcontext: 1
| a44447c2a91b5fa97e101fe20f20dde8 | 21.803922 | 59 | 0.605331 | false | false | false | false |
jakespracher/Snapchat-Swipe-View | refs/heads/master | SnapchatSwipeView/VerticalScrollViewController.swift | mit | 1 | //
// MiddleScrollViewController.swift
// SnapchatSwipeView
//
// Created by Jake Spracher on 12/14/15.
// Copyright © 2015 Jake Spracher. All rights reserved.
//
import UIKit
class VerticalScrollViewController: UIViewController, SnapContainerViewControllerDelegate {
var topVc: UIViewController!
var middleVc: UIViewController!
var bottomVc: UIViewController!
var scrollView: UIScrollView!
class func verticalScrollVcWith(middleVc: UIViewController,
topVc: UIViewController?=nil,
bottomVc: UIViewController?=nil) -> VerticalScrollViewController {
let middleScrollVc = VerticalScrollViewController()
middleScrollVc.topVc = topVc
middleScrollVc.middleVc = middleVc
middleScrollVc.bottomVc = bottomVc
return middleScrollVc
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view:
setupScrollView()
}
func setupScrollView() {
scrollView = UIScrollView()
scrollView.isPagingEnabled = true
scrollView.showsVerticalScrollIndicator = false
scrollView.bounces = false
let view = (
x: self.view.bounds.origin.x,
y: self.view.bounds.origin.y,
width: self.view.bounds.width,
height: self.view.bounds.height
)
scrollView.frame = CGRect(x: view.x, y: view.y, width: view.width, height: view.height)
self.view.addSubview(scrollView)
let scrollWidth: CGFloat = view.width
var scrollHeight: CGFloat
switch (topVc, bottomVc) {
case (nil, nil):
scrollHeight = view.height
middleVc.view.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
addChildViewController(middleVc)
scrollView.addSubview(middleVc.view)
middleVc.didMove(toParentViewController: self)
case (_?, nil):
scrollHeight = 2 * view.height
topVc.view.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
middleVc.view.frame = CGRect(x: 0, y: view.height, width: view.width, height: view.height)
addChildViewController(topVc)
addChildViewController(middleVc)
scrollView.addSubview(topVc.view)
scrollView.addSubview(middleVc.view)
topVc.didMove(toParentViewController: self)
middleVc.didMove(toParentViewController: self)
scrollView.contentOffset.y = middleVc.view.frame.origin.y
case (nil, _?):
scrollHeight = 2 * view.height
middleVc.view.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
bottomVc.view.frame = CGRect(x: 0, y: view.height, width: view.width, height: view.height)
addChildViewController(middleVc)
addChildViewController(bottomVc)
scrollView.addSubview(middleVc.view)
scrollView.addSubview(bottomVc.view)
middleVc.didMove(toParentViewController: self)
bottomVc.didMove(toParentViewController: self)
scrollView.contentOffset.y = 0
default:
scrollHeight = 3 * view.height
topVc.view.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
middleVc.view.frame = CGRect(x: 0, y: view.height, width: view.width, height: view.height)
bottomVc.view.frame = CGRect(x: 0, y: 2 * view.height, width: view.width, height: view.height)
addChildViewController(topVc)
addChildViewController(middleVc)
addChildViewController(bottomVc)
scrollView.addSubview(topVc.view)
scrollView.addSubview(middleVc.view)
scrollView.addSubview(bottomVc.view)
topVc.didMove(toParentViewController: self)
middleVc.didMove(toParentViewController: self)
bottomVc.didMove(toParentViewController: self)
scrollView.contentOffset.y = middleVc.view.frame.origin.y
}
scrollView.contentSize = CGSize(width: scrollWidth, height: scrollHeight)
}
// MARK: - SnapContainerViewControllerDelegate Methods
func outerScrollViewShouldScroll() -> Bool {
if scrollView.contentOffset.y < middleVc.view.frame.origin.y || scrollView.contentOffset.y > 2*middleVc.view.frame.origin.y {
return false
} else {
return true
}
}
}
| 1706447570a8adefc2e01b14420b6b1e | 36.984127 | 133 | 0.604053 | false | false | false | false |
AfricanSwift/TUIKit | refs/heads/master | TUIKit/Source/Ansi/Ansi+Character.swift | mit | 1 | //
// File: Ansi+Character.swift
// Created by: African Swift
import Darwin
// MARK: -
// MARK: Character: Insert, Delete, ... -
public extension Ansi
{
/// Character
public enum Character
{
/// Insert Character(s) (ICH)
///
/// - parameters:
/// - quantity: Insert quantity (default = 1) of blank characters at current position
/// - returns: Ansi
public static func insert(quantity: Int = 1) -> Ansi
{
return Ansi("\(Ansi.C1.CSI)\(quantity)@")
}
/// Delete Character(s) (DCH)
///
/// - parameters:
/// - quantity: Delete quantity (default = 1) characters, current position to field end
/// - returns: Ansi
public static func delete(quantity: Int = 1) -> Ansi
{
return Ansi("\(Ansi.C1.CSI)\(quantity)P")
}
/// Erase Character(s) (ECH)
///
/// - parameters:
/// - quantity: Erase quantity (default = 1) characters
/// - returns: Ansi
public static func erase(quantity: Int = 1) -> Ansi
{
return Ansi("\(Ansi.C1.CSI)\(quantity)X")
}
/// Repeat the preceding graphic character (REP)
///
/// - parameters:
/// - quantity: Repeat previous displayable character a specified number of times (default = 1)
/// - returns: Ansi
public static func repeatLast(quantity: Int = 1) -> Ansi
{
return Ansi("\(Ansi.C1.CSI)\(quantity)b")
}
}
}
| e2407913fc2d9b437ce9d0665b3fd9e8 | 25.5 | 102 | 0.569532 | false | false | false | false |
jkingyens/sports-stream | refs/heads/master | SportsStreamClient/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// SportsStreamClient
//
// Created by Jeff Kingyens on 10/11/15.
// Copyright © 2015 SportsStream. All rights reserved.
//
import UIKit
import KeychainAccess
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// properties?
var window: UIWindow?
var preferredServerRegion: String?
var apiKey: String?
var loggedIn: Bool?
var sessionToken: String?
var currentEndpoint: String?
var username: String?
var password: String?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
let mainBundle = NSBundle.mainBundle()
let path = mainBundle.pathForResource("AppConfig", ofType: "plist")
let configurations = NSDictionary(contentsOfFile: path!)
let api = configurations!.objectForKey("ServerAPIKey")
NSLog("config = %@", configurations!)
NSLog("API Key = %@", api as! String)
self.apiKey = api as? String
self.preferredServerRegion = "North America - West";
self.loggedIn = false
// try to login automatically if we have credentials on file
let defaults = NSUserDefaults.standardUserDefaults()
let endpoint = defaults.objectForKey("endpoint") as? NSString
if (endpoint == nil) {
return true
}
let username = defaults.objectForKey("username")
if (username == nil) {
return true
}
let keychain = Keychain(server: endpoint as! String, protocolType: ProtocolType.HTTPS)
.label("com.sportsstream.sportsstreamclient")
.synchronizable(true)
if (keychain[username as! String] == nil) {
return true
}
// attempt login
let loginURL = NSURL(string:String(format: "%@/Login", endpoint!))
NSLog("connecting to endpoint: %@", loginURL!)
let request = NSMutableURLRequest(URL: loginURL!) as NSMutableURLRequest
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let postData = NSString(format: "username=%@&password=%@&key=%@", username as! NSString, keychain[username as! String]! as NSString, self.apiKey!) .dataUsingEncoding(NSUTF8StringEncoding)
NSLog("postdata = %@", NSString(data: postData!, encoding: NSUTF8StringEncoding)!)
request.HTTPMethod = "POST"
request.HTTPBody = postData
let defaultConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
let urlSession = NSURLSession(configuration: defaultConfiguration)
let dataTask = urlSession.dataTaskWithRequest(request, completionHandler: { (data, response, error) in
if (error != nil) {
// ask user to check address or internet connection
NSLog("error connecting to endpoint: %@", error!)
return
}
let httpResponse = response as! NSHTTPURLResponse
if (httpResponse.statusCode != 200) {
NSLog("error authenticating with server: %d", httpResponse.statusCode)
// remove from keychain here?
return
}
do {
let userInfo = try NSJSONSerialization .JSONObjectWithData(data!, options:NSJSONReadingOptions()) as! NSDictionary
NSLog("User info = %@", userInfo)
let membership = userInfo.objectForKey("membership")
if (membership == nil) {
NSLog("Membership is not defined")
return
}
if (membership?.isEqualToString("Premium") == false) {
NSLog("Not a premium member: %@", membership as! NSString)
return
}
// load in meory account
self.currentEndpoint = endpoint as? String
self.username = username as? String
self.password = keychain[username as! String]! as String
self.sessionToken = userInfo.objectForKey("token") as? String
self.loggedIn = true
// switch to game list and reload games view
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
let ctrl = self.window?.rootViewController as! UITabBarController
ctrl.selectedIndex = 1
let gameList = ctrl.selectedViewController as! LiveGamesViewController
gameList.refreshTable()
let loginCtrl = ctrl.viewControllers![0] as! LoginViewController
loginCtrl.refreshView()
}
} catch {
NSLog("Error parsing JSON response, got body = %@", data!)
}
});
dataTask.resume()
return true
}
}
| d4c8980290b9158f503501d5e7d992ed | 38.067164 | 195 | 0.575931 | false | true | false | false |
Jnosh/swift | refs/heads/master | stdlib/public/core/StringUTF16.swift | apache-2.0 | 4 | //===--- StringUTF16.swift ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// FIXME(ABI)#71 : The UTF-16 string view should have a custom iterator type to
// allow performance optimizations of linear traversals.
extension String {
/// A view of a string's contents as a collection of UTF-16 code units.
///
/// You can access a string's view of UTF-16 code units by using its `utf16`
/// property. A string's UTF-16 view encodes the string's Unicode scalar
/// values as 16-bit integers.
///
/// let flowers = "Flowers 💐"
/// for v in flowers.utf16 {
/// print(v)
/// }
/// // 70
/// // 108
/// // 111
/// // 119
/// // 101
/// // 114
/// // 115
/// // 32
/// // 55357
/// // 56464
///
/// Unicode scalar values that make up a string's contents can be up to 21
/// bits long. The longer scalar values may need two `UInt16` values for
/// storage. Those "pairs" of code units are called *surrogate pairs*.
///
/// let flowermoji = "💐"
/// for v in flowermoji.unicodeScalars {
/// print(v, v.value)
/// }
/// // 💐 128144
///
/// for v in flowermoji.utf16 {
/// print(v)
/// }
/// // 55357
/// // 56464
///
/// To convert a `String.UTF16View` instance back into a string, use the
/// `String` type's `init(_:)` initializer.
///
/// let favemoji = "My favorite emoji is 🎉"
/// if let i = favemoji.utf16.index(where: { $0 >= 128 }) {
/// let asciiPrefix = String(favemoji.utf16[..<i])
/// print(asciiPrefix)
/// }
/// // Prints "My favorite emoji is "
///
/// UTF16View Elements Match NSString Characters
/// ============================================
///
/// The UTF-16 code units of a string's `utf16` view match the elements
/// accessed through indexed `NSString` APIs.
///
/// print(flowers.utf16.count)
/// // Prints "10"
///
/// let nsflowers = flowers as NSString
/// print(nsflowers.length)
/// // Prints "10"
///
/// Unlike `NSString`, however, `String.UTF16View` does not use integer
/// indices. If you need to access a specific position in a UTF-16 view, use
/// Swift's index manipulation methods. The following example accesses the
/// fourth code unit in both the `flowers` and `nsflowers` strings:
///
/// print(nsflowers.character(at: 3))
/// // Prints "119"
///
/// let i = flowers.utf16.index(flowers.utf16.startIndex, offsetBy: 3)
/// print(flowers.utf16[i])
/// // Prints "119"
///
/// Although the Swift overlay updates many Objective-C methods to return
/// native Swift indices and index ranges, some still return instances of
/// `NSRange`. To convert an `NSRange` instance to a range of
/// `String.UTF16View.Index`, follow these steps:
///
/// 1. Use the `NSRange` type's `toRange` method to convert the instance to
/// an optional range of `Int` values.
/// 2. Use your string's `utf16` view's index manipulation methods to convert
/// the integer bounds to `String.UTF16View.Index` values.
/// 3. Create a new `Range` instance from the new index values.
///
/// Here's an implementation of those steps, showing how to retrieve a
/// substring described by an `NSRange` instance from the middle of a
/// string.
///
/// let snowy = "❄️ Let it snow! ☃️"
/// let nsrange = NSRange(location: 3, length: 12)
/// if let r = nsrange.toRange() {
/// let start = snowy.utf16.index(snowy.utf16.startIndex, offsetBy: r.lowerBound)
/// let end = snowy.utf16.index(snowy.utf16.startIndex, offsetBy: r.upperBound)
/// let substringRange = start..<end
/// print(snowy.utf16[substringRange])
/// }
/// // Prints "Let it snow!"
public struct UTF16View
: BidirectionalCollection,
CustomStringConvertible,
CustomDebugStringConvertible {
/// A position in a string's collection of UTF-16 code units.
///
/// You can convert between indices of the different string views by using
/// conversion initializers and the `samePosition(in:)` method overloads.
/// For example, the following code sample finds the index of the first
/// space in a string and then converts that to the same
/// position in the UTF-16 view.
///
/// let hearts = "Hearts <3 ♥︎ 💘"
/// if let i = hearts.index(of: " ") {
/// let j = i.samePosition(in: hearts.utf16)
/// print(Array(hearts.utf16[j...]))
/// print(hearts.utf16[j...])
/// }
/// // Prints "[32, 60, 51, 32, 9829, 65038, 32, 55357, 56472]"
/// // Prints " <3 ♥︎ 💘"
public struct Index {
// Foundation needs access to these fields so it can expose
// random access
public // SPI(Foundation)
init(_offset: Int) { self._offset = _offset }
public let _offset: Int
}
public typealias IndexDistance = Int
/// The position of the first code unit if the `String` is
/// nonempty; identical to `endIndex` otherwise.
public var startIndex: Index {
return Index(_offset: _offset)
}
/// The "past the end" position---that is, the position one greater than
/// the last valid subscript argument.
///
/// In an empty UTF-16 view, `endIndex` is equal to `startIndex`.
public var endIndex: Index {
return Index(_offset: _offset + _length)
}
public struct Indices {
internal var _elements: String.UTF16View
internal var _startIndex: Index
internal var _endIndex: Index
}
public var indices: Indices {
return Indices(
_elements: self, startIndex: startIndex, endIndex: endIndex)
}
// TODO: swift-3-indexing-model - add docs
public func index(after i: Index) -> Index {
// FIXME: swift-3-indexing-model: range check i?
return Index(_offset: _unsafePlus(i._offset, 1))
}
// TODO: swift-3-indexing-model - add docs
public func index(before i: Index) -> Index {
// FIXME: swift-3-indexing-model: range check i?
return Index(_offset: _unsafeMinus(i._offset, 1))
}
// TODO: swift-3-indexing-model - add docs
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
// FIXME: swift-3-indexing-model: range check i?
return Index(_offset: i._offset.advanced(by: n))
}
// TODO: swift-3-indexing-model - add docs
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
// FIXME: swift-3-indexing-model: range check i?
let d = i._offset.distance(to: limit._offset)
if (d > 0) ? (d < n) : (d > n) {
return nil
}
return Index(_offset: i._offset.advanced(by: n))
}
// TODO: swift-3-indexing-model - add docs
public func distance(from start: Index, to end: Index) -> IndexDistance {
// FIXME: swift-3-indexing-model: range check start and end?
return start._offset.distance(to: end._offset)
}
func _internalIndex(at i: Int) -> Int {
return _core.startIndex + i
}
/// Accesses the code unit at the given position.
///
/// The following example uses the subscript to print the value of a
/// string's first UTF-16 code unit.
///
/// let greeting = "Hello, friend!"
/// let i = greeting.utf16.startIndex
/// print("First character's UTF-16 code unit: \(greeting.utf16[i])")
/// // Prints "First character's UTF-16 code unit: 72"
///
/// - Parameter position: A valid index of the view. `position` must be
/// less than the view's end index.
public subscript(i: Index) -> UTF16.CodeUnit {
_precondition(i >= startIndex && i < endIndex,
"out-of-range access on a UTF16View")
let index = _internalIndex(at: i._offset)
let u = _core[index]
if _fastPath((u &>> 11) != 0b1101_1) {
// Neither high-surrogate, nor low-surrogate -- well-formed sequence
// of 1 code unit.
return u
}
if (u &>> 10) == 0b1101_10 {
// `u` is a high-surrogate. Sequence is well-formed if it
// is followed by a low-surrogate.
if _fastPath(
index + 1 < _core.count &&
(_core[index + 1] &>> 10) == 0b1101_11) {
return u
}
return 0xfffd
}
// `u` is a low-surrogate. Sequence is well-formed if
// previous code unit is a high-surrogate.
if _fastPath(index != 0 && (_core[index - 1] &>> 10) == 0b1101_10) {
return u
}
return 0xfffd
}
#if _runtime(_ObjC)
// These may become less important once <rdar://problem/19255291> is addressed.
@available(
*, unavailable,
message: "Indexing a String's UTF16View requires a String.UTF16View.Index, which can be constructed from Int when Foundation is imported")
public subscript(i: Int) -> UTF16.CodeUnit {
Builtin.unreachable()
}
@available(
*, unavailable,
message: "Slicing a String's UTF16View requires a Range<String.UTF16View.Index>, String.UTF16View.Index can be constructed from Int when Foundation is imported")
public subscript(bounds: Range<Int>) -> UTF16View {
Builtin.unreachable()
}
#endif
/// Accesses the contiguous subrange of elements enclosed by the specified
/// range.
///
/// - Complexity: O(*n*) if the underlying string is bridged from
/// Objective-C, where *n* is the length of the string; otherwise, O(1).
public subscript(bounds: Range<Index>) -> UTF16View {
return UTF16View(
_core,
offset: _internalIndex(at: bounds.lowerBound._offset),
length: bounds.upperBound._offset - bounds.lowerBound._offset)
}
internal init(_ _core: _StringCore) {
self.init(_core, offset: 0, length: _core.count)
}
internal init(_ _core: _StringCore, offset: Int, length: Int) {
self._offset = offset
self._length = length
self._core = _core
}
public var description: String {
let start = _internalIndex(at: _offset)
let end = _internalIndex(at: _offset + _length)
return String(_core[start..<end])
}
public var debugDescription: String {
return "StringUTF16(\(self.description.debugDescription))"
}
internal var _offset: Int
internal var _length: Int
internal let _core: _StringCore
}
/// A UTF-16 encoding of `self`.
public var utf16: UTF16View {
get {
return UTF16View(_core)
}
set {
self = String(describing: newValue)
}
}
/// Creates a string corresponding to the given sequence of UTF-16 code units.
///
/// If `utf16` contains unpaired UTF-16 surrogates, the result is `nil`.
///
/// You can use this initializer to create a new string from a slice of
/// another string's `utf16` view.
///
/// let picnicGuest = "Deserving porcupine"
/// if let i = picnicGuest.utf16.index(of: 32) {
/// let adjective = String(picnicGuest.utf16[..<i])
/// print(adjective)
/// }
/// // Prints "Optional(Deserving)"
///
/// The `adjective` constant is created by calling this initializer with a
/// slice of the `picnicGuest.utf16` view.
///
/// - Parameter utf16: A UTF-16 code sequence.
public init?(_ utf16: UTF16View) {
let wholeString = String(utf16._core)
guard
let start = UTF16Index(_offset: utf16._offset)
.samePosition(in: wholeString),
let end = UTF16Index(_offset: utf16._offset + utf16._length)
.samePosition(in: wholeString)
else
{
return nil
}
self = wholeString[start..<end]
}
/// The index type for subscripting a string's `utf16` view.
public typealias UTF16Index = UTF16View.Index
}
extension String.UTF16View : _SwiftStringView {
var _ephemeralContent : String { return _persistentContent }
var _persistentContent : String { return String(self._core) }
}
extension String.UTF16View.Index : Comparable {
// FIXME: swift-3-indexing-model: add complete set of forwards for Comparable
// assuming String.UTF8View.Index continues to exist
public static func == (
lhs: String.UTF16View.Index,
rhs: String.UTF16View.Index
) -> Bool {
return lhs._offset == rhs._offset
}
public static func < (
lhs: String.UTF16View.Index,
rhs: String.UTF16View.Index
) -> Bool {
return lhs._offset < rhs._offset
}
}
// Index conversions
extension String.UTF16View.Index {
/// Creates an index in the given UTF-16 view that corresponds exactly to the
/// specified `UTF8View` position.
///
/// The following example finds the position of a space in a string's `utf8`
/// view and then converts that position to an index in the string's
/// `utf16` view.
///
/// let cafe = "Café 🍵"
///
/// let utf8Index = cafe.utf8.index(of: 32)!
/// let utf16Index = String.UTF16View.Index(utf8Index, within: cafe.utf16)!
///
/// print(cafe.utf16[..<utf16Index])
/// // Prints "Café"
///
/// If the position passed as `utf8Index` doesn't have an exact corresponding
/// position in `utf16`, the result of the initializer is `nil`. For
/// example, because UTF-8 and UTF-16 represent high Unicode code points
/// differently, an attempt to convert the position of a UTF-8 continuation
/// byte fails.
///
/// - Parameters:
/// - utf8Index: A position in a `UTF8View` instance. `utf8Index` must be
/// an element in `String(utf16).utf8.indices`.
/// - utf16: The `UTF16View` in which to find the new position.
public init?(
_ utf8Index: String.UTF8Index, within utf16: String.UTF16View
) {
let core = utf16._core
_precondition(
utf8Index._coreIndex >= 0 && utf8Index._coreIndex <= core.endIndex,
"Invalid String.UTF8Index for this UTF-16 view")
// Detect positions that have no corresponding index.
if !utf8Index._isOnUnicodeScalarBoundary(in: core) {
return nil
}
_offset = utf8Index._coreIndex
}
/// Creates an index in the given UTF-16 view that corresponds exactly to the
/// specified `UnicodeScalarView` position.
///
/// The following example finds the position of a space in a string's `utf8`
/// view and then converts that position to an index in the string's
/// `utf16` view.
///
/// let cafe = "Café 🍵"
///
/// let scalarIndex = cafe.unicodeScalars.index(of: "é")!
/// let utf16Index = String.UTF16View.Index(scalarIndex, within: cafe.utf16)
///
/// print(cafe.utf16[...utf16Index])
/// // Prints "Café"
///
/// - Parameters:
/// - unicodeScalarIndex: A position in a `UnicodeScalarView` instance.
/// `unicodeScalarIndex` must be an element in
/// `String(utf16).unicodeScalarIndex.indices`.
/// - utf16: The `UTF16View` in which to find the new position.
public init(
_ unicodeScalarIndex: String.UnicodeScalarIndex,
within utf16: String.UTF16View) {
_offset = unicodeScalarIndex._position
}
/// Creates an index in the given UTF-16 view that corresponds exactly to the
/// specified string position.
///
/// The following example finds the position of a space in a string and then
/// converts that position to an index in the string's `utf16` view.
///
/// let cafe = "Café 🍵"
///
/// let stringIndex = cafe.index(of: "é")!
/// let utf16Index = String.UTF16View.Index(stringIndex, within: cafe.utf16)
///
/// print(cafe.utf16[...utf16Index])
/// // Prints "Café"
///
/// - Parameters:
/// - index: A position in a string. `index` must be an element in
/// `String(utf16).indices`.
/// - utf16: The `UTF16View` in which to find the new position.
public init(_ index: String.Index, within utf16: String.UTF16View) {
_offset = index._utf16Index
}
/// Returns the position in the given UTF-8 view that corresponds exactly to
/// this index.
///
/// The index must be a valid index of `String(utf8).utf16`.
///
/// This example first finds the position of a space (UTF-16 code point `32`)
/// in a string's `utf16` view and then uses this method to find the same
/// position in the string's `utf8` view.
///
/// let cafe = "Café 🍵"
/// let i = cafe.utf16.index(of: 32)!
/// let j = i.samePosition(in: cafe.utf8)!
/// print(Array(cafe.utf8[..<j]))
/// // Prints "[67, 97, 102, 195, 169]"
///
/// - Parameter utf8: The view to use for the index conversion.
/// - Returns: The position in `utf8` that corresponds exactly to this index.
/// If this index does not have an exact corresponding position in `utf8`,
/// this method returns `nil`. For example, an attempt to convert the
/// position of a UTF-16 trailing surrogate returns `nil`.
public func samePosition(
in utf8: String.UTF8View
) -> String.UTF8View.Index? {
return String.UTF8View.Index(self, within: utf8)
}
/// Returns the position in the given view of Unicode scalars that
/// corresponds exactly to this index.
///
/// This index must be a valid index of `String(unicodeScalars).utf16`.
///
/// This example first finds the position of a space (UTF-16 code point `32`)
/// in a string's `utf16` view and then uses this method to find the same
/// position in the string's `unicodeScalars` view.
///
/// let cafe = "Café 🍵"
/// let i = cafe.utf16.index(of: 32)!
/// let j = i.samePosition(in: cafe.unicodeScalars)!
/// print(cafe.unicodeScalars[..<j])
/// // Prints "Café"
///
/// - Parameter unicodeScalars: The view to use for the index conversion.
/// - Returns: The position in `unicodeScalars` that corresponds exactly to
/// this index. If this index does not have an exact corresponding
/// position in `unicodeScalars`, this method returns `nil`. For example,
/// an attempt to convert the position of a UTF-16 trailing surrogate
/// returns `nil`.
public func samePosition(
in unicodeScalars: String.UnicodeScalarView
) -> String.UnicodeScalarIndex? {
return String.UnicodeScalarIndex(self, within: unicodeScalars)
}
/// Returns the position in the given string that corresponds exactly to this
/// index.
///
/// This index must be a valid index of `characters.utf16`.
///
/// This example first finds the position of a space (UTF-16 code point `32`)
/// in a string's `utf16` view and then uses this method find the same position
/// in the string.
///
/// let cafe = "Café 🍵"
/// let i = cafe.utf16.index(of: 32)!
/// let j = i.samePosition(in: cafe)!
/// print(cafe[..<j])
/// // Prints "Café"
///
/// - Parameter characters: The string to use for the index conversion.
/// - Returns: The position in `characters` that corresponds exactly to this
/// index. If this index does not have an exact corresponding position in
/// `characters`, this method returns `nil`. For example, an attempt to
/// convert the position of a UTF-16 trailing surrogate returns `nil`.
public func samePosition(
in characters: String
) -> String.Index? {
return String.Index(self, within: characters)
}
}
// Reflection
extension String.UTF16View : CustomReflectable {
/// Returns a mirror that reflects the UTF-16 view of a string.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: self)
}
}
extension String.UTF16View : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text(description)
}
}
extension String.UTF16View.Indices : BidirectionalCollection {
public typealias Index = String.UTF16View.Index
public typealias IndexDistance = String.UTF16View.IndexDistance
public typealias Indices = String.UTF16View.Indices
public typealias SubSequence = String.UTF16View.Indices
internal init(
_elements: String.UTF16View,
startIndex: Index,
endIndex: Index
) {
self._elements = _elements
self._startIndex = startIndex
self._endIndex = endIndex
}
public var startIndex: Index {
return _startIndex
}
public var endIndex: Index {
return _endIndex
}
public var indices: Indices {
return self
}
public subscript(i: Index) -> Index {
// FIXME: swift-3-indexing-model: range check.
return i
}
public subscript(bounds: Range<Index>) -> String.UTF16View.Indices {
// FIXME: swift-3-indexing-model: range check.
return String.UTF16View.Indices(
_elements: _elements,
startIndex: bounds.lowerBound,
endIndex: bounds.upperBound)
}
public func index(after i: Index) -> Index {
// FIXME: swift-3-indexing-model: range check.
return _elements.index(after: i)
}
public func formIndex(after i: inout Index) {
// FIXME: swift-3-indexing-model: range check.
_elements.formIndex(after: &i)
}
public func index(before i: Index) -> Index {
// FIXME: swift-3-indexing-model: range check.
return _elements.index(before: i)
}
public func formIndex(before i: inout Index) {
// FIXME: swift-3-indexing-model: range check.
_elements.formIndex(before: &i)
}
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
// FIXME: swift-3-indexing-model: range check i?
return _elements.index(i, offsetBy: n)
}
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
// FIXME: swift-3-indexing-model: range check i?
return _elements.index(i, offsetBy: n, limitedBy: limit)
}
// TODO: swift-3-indexing-model - add docs
public func distance(from start: Index, to end: Index) -> IndexDistance {
// FIXME: swift-3-indexing-model: range check start and end?
return _elements.distance(from: start, to: end)
}
}
| 1a4ea78e32911143889cc0d745aaa6d3 | 33.919003 | 167 | 0.624186 | false | false | false | false |
MHaubenstock/Endless-Dungeon | refs/heads/master | EndlessDungeon/EndlessDungeon/Tile.swift | mit | 1 | //
// Tile.swift
// EndlessDungeon
//
// Created by Michael Haubenstock on 9/21/14.
// Copyright (c) 2014 Michael Haubenstock. All rights reserved.
//
import Foundation
import SpriteKit
class Tile
{
var enemies : [NPCharacter] = []
var lootables : [Container] = []
var cells : [[Cell]]
var entranceCell : Cell
var exitCells : [Cell]
var containers : [Container] = []
var tileSprite : SKSpriteNode = SKSpriteNode()
var roomGenerated : Bool = false
var numXCells : Int!
var numYCells : Int!
//Create Entrance Tile
init(nXCells : Int, nYCells : Int)
{
numXCells = nXCells
numYCells = nYCells
//Fill all cells with walls
cells = Array(count: numYCells, repeatedValue: Array(count: numXCells, repeatedValue: Cell()))
exitCells = Array(count: 0, repeatedValue: Cell(type: .Exit))
entranceCell = Cell()
}
init(nXCells : Int, nYCells : Int, gridLeft : CGFloat, gridBottom : CGFloat, cellSize : Int)
{
numXCells = nXCells
numYCells = nYCells
//Fill all cells with walls
cells = Array(count: numYCells, repeatedValue: Array(count: numXCells, repeatedValue: Cell()))
exitCells = Array(count: 0, repeatedValue: Cell(type: .Exit))
//Initialize each cell's position and index
for x in 0...(numXCells! - 1)
{
for y in 0...(numYCells! - 1)
{
cells[y][x] = Cell(theIndex: (x, y), type: .Wall, thePosition: CGPoint(x: gridLeft + CGFloat(cellSize * x), y: gridBottom + CGFloat(cellSize * y)))
}
}
entranceCell = Cell()
}
func draw(gridLeft : CGFloat, gridBottom : CGFloat, cellSize : CGFloat) -> SKSpriteNode
{
for x in 0...(numXCells! - 1)
{
for y in 0...(numYCells! - 1)
{
tileSprite.addChild(createCell(cells[y][x], cellSize: cellSize))
}
}
return tileSprite
}
func createCell(cell : Cell, cellSize : CGFloat) -> SKSpriteNode
{
var sprite = SKSpriteNode(imageNamed: cell.cellImage)
sprite.name = cell.cellImage.stringByReplacingOccurrencesOfString(".png", withString: "", options: nil, range: nil)
if(sprite.name == "Column")
{
sprite.shadowCastBitMask = 1
sprite.lightingBitMask = 1
}
sprite.anchorPoint = CGPoint(x: 0, y: 0)
sprite.size = CGSizeMake(cellSize, cellSize)
sprite.position = cell.position
return sprite
}
func getCellsOfType(type : Cell.CellType) -> [Cell]
{
var theCells : [Cell] = [Cell]()
for x in 0...(numXCells! - 1)
{
for y in 0...(numYCells! - 1)
{
if(cells[y][x].cellType == type)
{
theCells.append(cells[y][x])
}
}
}
return theCells
}
func getNeighboringCells(cell : Cell, getDiagonals : Bool) -> Dictionary<Dungeon.Direction, Cell>
{
var neighborDictionary : Dictionary<Dungeon.Direction, Cell> = Dictionary<Dungeon.Direction, Cell>()
//North
var neighborCellIndex : (Int, Int) = Dungeon.getNeighborCellindex(cell.index, exitDirection: .North)
if(isValidIndex(neighborCellIndex))
{
neighborDictionary.updateValue(cells[neighborCellIndex.1][neighborCellIndex.0], forKey: .North)
}
//South
neighborCellIndex = Dungeon.getNeighborCellindex(cell.index, exitDirection: .South)
if(isValidIndex(neighborCellIndex))
{
neighborDictionary.updateValue(cells[neighborCellIndex.1][neighborCellIndex.0], forKey: .South)
}
//East
neighborCellIndex = Dungeon.getNeighborCellindex(cell.index, exitDirection: .East)
if(isValidIndex(neighborCellIndex))
{
neighborDictionary.updateValue(cells[neighborCellIndex.1][neighborCellIndex.0], forKey: .East)
}
//West
neighborCellIndex = Dungeon.getNeighborCellindex(cell.index, exitDirection: .West)
if(isValidIndex(neighborCellIndex))
{
neighborDictionary.updateValue(cells[neighborCellIndex.1][neighborCellIndex.0], forKey: .West)
}
if getDiagonals
{
//Northeast
neighborCellIndex = Dungeon.getNeighborCellindex(cell.index, exitDirection: .Northeast)
if(isValidIndex(neighborCellIndex))
{
neighborDictionary.updateValue(cells[neighborCellIndex.1][neighborCellIndex.0], forKey: .Northeast)
}
//Northwest
neighborCellIndex = Dungeon.getNeighborCellindex(cell.index, exitDirection: .Northwest)
if(isValidIndex(neighborCellIndex))
{
neighborDictionary.updateValue(cells[neighborCellIndex.1][neighborCellIndex.0], forKey: .Northwest)
}
//Southeast
neighborCellIndex = Dungeon.getNeighborCellindex(cell.index, exitDirection: .Southeast)
if(isValidIndex(neighborCellIndex))
{
neighborDictionary.updateValue(cells[neighborCellIndex.1][neighborCellIndex.0], forKey: .Southeast)
}
//Southwest
neighborCellIndex = Dungeon.getNeighborCellindex(cell.index, exitDirection: .Southwest)
if(isValidIndex(neighborCellIndex))
{
neighborDictionary.updateValue(cells[neighborCellIndex.1][neighborCellIndex.0], forKey: .Southwest)
}
}
return neighborDictionary
}
func isValidIndex(theIndex : (Int, Int)) -> Bool
{
return (theIndex.0 >= 0 && theIndex.0 < numXCells && theIndex.1 >= 0 && theIndex.1 < numYCells)
}
//For state searches and such
func getSimplifiedTileState() -> [[Int]]
{
var simplifiedTileState : [[Int]] = Array(count: numYCells, repeatedValue: Array(count: numXCells, repeatedValue: 0))
for x in 0...(numXCells! - 1)
{
for y in 0...(numYCells! - 1)
{
if(cells[y][x].cellType == .Wall)
{
simplifiedTileState[y][x] = 0
}
else if(cells[y][x].characterInCell != nil)
{
if(cells[y][x].characterInCell is Player)
{
simplifiedTileState[y][x] = 1
}
else if(cells[y][x].characterInCell is NPCharacter)
{
simplifiedTileState[y][x] = 2
}
}
else
{
simplifiedTileState[y][x] = 3
}
}
}
return simplifiedTileState
}
}
| 32d7c8f7ef86753b71a6de078d641fe7 | 31.633484 | 163 | 0.544786 | false | false | false | false |
RevenueCat/purchases-ios | refs/heads/main | Tests/TestingApps/PurchaseTester/PurchaseTester/InitialViewController.swift | mit | 1 | //
// InitialViewController.swift
// PurchaseTester
//
// Created by Ryan Kotzebue on 1/9/19.
// Copyright © 2019 RevenueCat. All rights reserved.
//
import UIKit
import RevenueCat
class InitialViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Get the latest customerInfo to see if we have a pro cat user or not
Purchases.shared.getCustomerInfo { (customerInfo, error) in
if let e = error {
print(e.localizedDescription)
}
// Route the view depending if we have a premium cat user or not
if customerInfo?.entitlements["pro_cat"]?.isActive == true {
// if we have a pro_cat subscriber, send them to the cat screen
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "cats")
controller.modalPresentationStyle = .fullScreen
self.present(controller, animated: true, completion: nil)
} else {
// if we don't have a pro subscriber, send them to the upsell screen
let controller = SwiftPaywall(
termsOfServiceUrlString: "https://www.revenuecat.com/terms",
privacyPolicyUrlString: "https://www.revenuecat.com/terms")
controller.titleLabel.text = "Upsell Screen"
controller.subtitleLabel.text = "New cats, unlimited cats, personal cat insights and more!"
controller.modalPresentationStyle = .fullScreen
self.present(controller, animated: true, completion: nil)
}
}
}
}
| da13aff0a76ff27ba326ac1dcc7dafbf | 37.980392 | 107 | 0.59507 | false | false | false | false |
rambler-digital-solutions/rambler-it-ios | refs/heads/develop | Carthage/Checkouts/rides-ios-sdk/examples/Swift SDK/Swift SDK/AuthorizationCodeGrantExampleViewController.swift | mit | 1 | //
// AuthorizationCodeGrantExampleViewController.swift
// Swift SDK
//
// Copyright © 2015 Uber Technologies, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UberRides
import CoreLocation
/// This class demonstrates how do use the LoginManager to complete Authorization Code Grant Authorization
/// and how to use some of the request endpoints
/// Make sure to replace instances of "YOUR_URL" with the path for your backend service
class AuthorizationCodeGrantExampleViewController: AuthorizationBaseViewController {
fileprivate let states = ["accepted", "arriving", "in_progress", "completed"]
/// The LoginManager to use for login
/// Specify authorization code grant as the loginType to use privileged scopes
let loginManager = LoginManager(loginType: .authorizationCode)
/// The RidesClient to use for endpoints
let ridesClient = RidesClient()
@IBOutlet weak var driverImageView: UIImageView!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var loginButton: UIBarButtonItem!
@IBOutlet weak var carLabel: UILabel!
@IBOutlet weak var carImageView: UIImageView!
@IBOutlet weak var driverLabel: UILabel!
@IBOutlet weak var requestButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
loginButton.isEnabled = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let loggedIn = TokenManager.fetchToken() != nil
loginButton.isEnabled = !loggedIn
requestButton.isEnabled = loggedIn
reset()
}
override func reset() {
statusLabel.text = ""
carLabel.text = ""
driverLabel.text = ""
carImageView.image = nil
driverImageView.image = nil
}
@IBAction func login(_ sender: AnyObject) {
// Can define a state variable to prevent tampering
loginManager.state = UUID().uuidString
// Define which scopes we're requesting
// Need to be authorized on your developer dashboard at developer.uber.com
// Privileged scopes can be used by anyone in sandbox for your own account but must be approved for production
let requestedScopes = [RidesScope.request, RidesScope.allTrips]
// Use your loginManager to login with the requested scopes, viewcontroller to present over, and completion block
loginManager.login(requestedScopes: requestedScopes, presentingViewController: self) { (accessToken, error) -> () in
// Error
if let error = error {
self.showMessage(error.localizedDescription)
return
}
// Poll backend for access token
// Replace "YOUR_URL" with the path for your backend service
if let url = URL(string: "YOUR_URL") {
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
guard let data = data,
let jsonString = String(data: data, encoding: String.Encoding.utf8) else {
self.showMessage("Unable to retrieve access token")
return
}
let token = AccessToken(tokenString: jsonString)
// Do any additional work to verify the state passed in earlier
if !TokenManager.save(accessToken: token) {
self.showMessage("Unable to save access token")
} else {
self.showMessage("Saved an AccessToken!")
self.loginButton.isEnabled = false
self.requestButton.isEnabled = true
}
}
}.resume()
}
}
}
@IBAction func requestRide(_ sender: AnyObject) {
// Create ride parameters
self.requestButton.isEnabled = false
let pickupLocation = CLLocation(latitude: 37.770, longitude: -122.466)
let dropoffLocation = CLLocation(latitude: 37.791, longitude: -122.405)
let builder = RideParametersBuilder()
builder.pickupLocation = pickupLocation
builder.pickupNickname = "California Academy of Sciences"
builder.dropoffLocation = dropoffLocation
builder.dropoffNickname = "Pier 39"
builder.productID = "a1111c8c-c720-46c3-8534-2fcdd730040d"
// Use the POST /v1/requests endpoint to make a ride request (in sandbox)
ridesClient.requestRide(parameters: builder.build(), completion: { ride, response in
DispatchQueue.main.async(execute: {
self.checkError(response)
if let ride = ride {
self.statusLabel.text = "Processing"
self.updateRideStatus(ride.requestID, index: 0)
} else {
self.requestButton.isEnabled = true
}
})
})
}
// Uses the the GET /v1/requests/{request_id} endpoint to get information about a ride request
func getRideData(_ requestID: String) {
ridesClient.fetchRideDetails(requestID: requestID) { ride, response in
self.checkError(response)
// Unwrap some optionals for data we want to use
guard let ride = ride,
let driverName = ride.driver?.name,
let driverNumber = ride.driver?.phoneNumber,
let licensePlate = ride.vehicle?.licensePlate,
let make = ride.vehicle?.make,
let model = ride.vehicle?.model,
let driverImage = ride.driver?.pictureURL,
let carImage = ride.vehicle?.pictureURL else {
return
}
// Update the UI on the main thread
DispatchQueue.main.async {
self.driverLabel.text = "\(driverName)\n\(driverNumber)"
self.carLabel.text = "\(make) \(model)\n(\(licensePlate)"
// Asynchronously fetch images
URLSession.shared.dataTask(with: driverImage) {
(data, response, error) in
DispatchQueue.main.async {
guard let data = data else {
return
}
self.driverImageView.image = UIImage(data: data)
}
}.resume()
URLSession.shared.dataTask(with: carImage) {
(data, response, error) in
DispatchQueue.main.async {
guard let data = data else {
return
}
self.carImageView.image = UIImage(data: data)
}
}.resume()
self.updateRideStatus(requestID, index: 1)
}
}
}
// Simulates stepping through ride statuses recursively
func updateRideStatus(_ requestID: String, index: Int) {
guard index < states.count,
let token = TokenManager.fetchToken() else {
return
}
let status = states[index]
// Use the PUT /v1/sandbox/requests/{request_id} to update the ride status
let updateStatusEndpoint = URL(string: "https://sandbox-api.uber.com/v1/sandbox/requests/\(requestID)")!
var request = URLRequest(url: updateStatusEndpoint)
request.httpMethod = "PUT"
request.setValue("Bearer \(token.tokenString!)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
do {
let data = try JSONSerialization.data(withJSONObject: ["status":status], options: .prettyPrinted)
request.httpBody = data
} catch { }
URLSession.shared.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
if let response = response as? HTTPURLResponse, response.statusCode != 204 {
return
}
self.statusLabel.text = status.capitalized
// Get ride data when in the Accepted state
if status == "accepted" {
self.getRideData(requestID)
return
}
self.delay(2) {
self.updateRideStatus(requestID, index: index+1)
}
}
}.resume()
}
}
| 00262ba6e9b08677f3eeeb6ed094a158 | 41.611111 | 124 | 0.583191 | false | false | false | false |
HabitRPG/habitrpg-ios | refs/heads/develop | HabitRPG/TableviewCells/CustomRewardCell.swift | gpl-3.0 | 1 | //
// CustomRewrdCell.swift
// Habitica
//
// Created by Phillip on 21.08.17.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import UIKit
import Habitica_Models
import Down
class CustomRewardCell: UICollectionViewCell {
@IBOutlet weak var mainRewardWrapper: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var notesLabel: UILabel!
@IBOutlet weak var currencyImageView: UIImageView!
@IBOutlet weak var amountLabel: AbbreviatedNumberLabel!
@IBOutlet weak var buyButton: UIView!
var onBuyButtonTapped: (() -> Void)?
public var canAfford: Bool = false {
didSet {
if canAfford {
currencyImageView.alpha = 1.0
buyButton.backgroundColor = UIColor.yellow500.withAlphaComponent(0.3)
if ThemeService.shared.theme.isDark {
amountLabel.textColor = UIColor.yellow50
} else {
amountLabel.textColor = UIColor.yellow1.withAlphaComponent(0.85)
}
} else {
currencyImageView.alpha = 0.6
buyButton.backgroundColor = ThemeService.shared.theme.offsetBackgroundColor.withAlphaComponent(0.5)
amountLabel.textColor = ThemeService.shared.theme.dimmedTextColor
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
currencyImageView.image = HabiticaIcons.imageOfGold
buyButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(buyButtonTapped)))
}
func configure(reward: TaskProtocol) {
let theme = ThemeService.shared.theme
titleLabel.font = CustomFontMetrics.scaledSystemFont(ofSize: 15)
if let text = reward.text {
titleLabel.attributedText = try? Down(markdownString: text.unicodeEmoji).toHabiticaAttributedString(baseSize: 15, textColor: theme.primaryTextColor)
} else {
titleLabel.text = ""
}
notesLabel.font = CustomFontMetrics.scaledSystemFont(ofSize: 11)
if let trimmedNotes = reward.notes?.trimmingCharacters(in: .whitespacesAndNewlines), trimmedNotes.isEmpty == false {
notesLabel.attributedText = try? Down(markdownString: trimmedNotes.unicodeEmoji).toHabiticaAttributedString(baseSize: 11, textColor: theme.secondaryTextColor)
notesLabel.isHidden = false
} else {
notesLabel.isHidden = true
}
amountLabel.text = String(reward.value)
backgroundColor = theme.contentBackgroundColor
mainRewardWrapper.backgroundColor = theme.windowBackgroundColor
titleLabel.textColor = theme.primaryTextColor
notesLabel.textColor = theme.ternaryTextColor
}
@objc
func buyButtonTapped() {
if let action = onBuyButtonTapped {
action()
}
}
}
| 2bc1dd48db01d8724633d651e67f7e7a | 36.435897 | 170 | 0.654452 | false | false | false | false |
liujinlongxa/AnimationTransition | refs/heads/master | testTransitioning/NormalFirstViewController.swift | mit | 1 | //
// NormalFirstViewController.swift
// AnimationTransition
//
// Created by Liujinlong on 8/12/15.
// Copyright © 2015 Jaylon. All rights reserved.
//
import UIKit
class NormalFirstViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// 设置模态的过场动画类型
if segue.identifier == "normalSegue1" {
segue.destination.modalTransitionStyle = UIModalTransitionStyle.flipHorizontal
}
else if segue.identifier == "normalSegue2" {
segue.destination.modalTransitionStyle = UIModalTransitionStyle.partialCurl
}
}
@IBAction func clickFirstButton(_ sender: AnyObject) {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "normalSecondVC")
//设置过场动画
let transiton = CATransition()
transiton.type = "cube"
transiton.subtype = kCATransitionFromRight
self.navigationController!.view.layer.add(transiton, forKey: "transitionAnimation")
vc.view.backgroundColor = UIColor.orange
self.navigationController?.pushViewController(vc
, animated: false)
}
@IBAction func clickSecondButton(_ sender: AnyObject) {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "normalSecondVC")
//设置过场动画
let transiton = CATransition()
transiton.type = "pageCurl"
self.navigationController!.view.layer.add(transiton, forKey: "transitionAnimation")
vc.view.backgroundColor = UIColor.orange
self.navigationController?.pushViewController(vc
, animated: false)
}
@IBAction func unwindForSegue(_ unwindSegue:UIStoryboardSegue) {
}
}
| f98c38800052df6bdaa74df9a8ceea00 | 29.571429 | 116 | 0.648598 | false | false | false | false |
mas-cli/mas | refs/heads/main | Tests/MasKitTests/Commands/SearchCommandSpec.swift | mit | 1 | //
// SearchCommandSpec.swift
// MasKitTests
//
// Created by Ben Chatelain on 2018-12-28.
// Copyright © 2018 mas-cli. All rights reserved.
//
import Nimble
import Quick
@testable import MasKit
public class SearchCommandSpec: QuickSpec {
override public func spec() {
let result = SearchResult(
trackId: 1111,
trackName: "slack",
trackViewUrl: "mas preview url",
version: "0.0"
)
let storeSearch = StoreSearchMock()
beforeSuite {
MasKit.initialize()
}
describe("search command") {
beforeEach {
storeSearch.reset()
}
it("can find slack") {
storeSearch.apps[result.trackId] = result
let search = SearchCommand(storeSearch: storeSearch)
let searchOptions = SearchOptions(appName: "slack", price: false)
let result = search.run(searchOptions)
expect(result).to(beSuccess())
}
it("fails when searching for nonexistent app") {
let search = SearchCommand(storeSearch: storeSearch)
let searchOptions = SearchOptions(appName: "nonexistent", price: false)
let result = search.run(searchOptions)
expect(result)
.to(
beFailure { error in
expect(error) == .noSearchResultsFound
})
}
}
}
}
| 319e9deb271f408ef4ae79feea6f50a6 | 29.156863 | 87 | 0.527958 | false | false | false | false |
superk589/CGSSGuide | refs/heads/master | DereGuide/Controller/TransitionableNavigationController.swift | mit | 2 | //
// TransitionableNavigationController.swift
// DereGuide
//
// Created by zzk on 2017/6/13.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
class TransitionableNavigationController: BaseNavigationController {
var customGesture: UIScreenEdgePanGestureRecognizer!
var interactiveAnimator: UIPercentDrivenInteractiveTransition!
override func viewDidLoad() {
super.viewDidLoad()
customGesture = UIScreenEdgePanGestureRecognizer()
view.addGestureRecognizer(customGesture)
customGesture.edges = .left
customGesture.addTarget(self, action: #selector(self.handleCustomGesture(gesture:)))
customGesture.isEnabled = false
}
override func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let type = TransitionTypes.init(operation: operation)
if let from = fromVC as? Transitionable, let to = toVC as? Transitionable {
if from.transitionTypes.contains(type) && to.transitionTypes.contains(type) {
return TransitionAnimatorController(transitionTypes: type)
}
}
return nil
}
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
if let transitionable = viewController as? Transitionable, transitionable.transitionTypes.contains(.interactive) {
customGesture.isEnabled = true
interactivePopGestureRecognizer?.isEnabled = false
} else {
customGesture.isEnabled = false
interactivePopGestureRecognizer?.isEnabled = true
}
}
func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactiveAnimator
}
@objc func handleCustomGesture(gesture: UIScreenEdgePanGestureRecognizer) {
var progress = gesture.translation(in: self.view).x / self.view.bounds.size.width
progress = min(1.0, max(0.0, progress))
switch gesture.state {
case .began:
interactiveAnimator = UIPercentDrivenInteractiveTransition()
self.popViewController(animated: true)
case .changed:
interactiveAnimator?.update(progress)
case .ended, .cancelled:
if progress > 0.5 {
interactiveAnimator?.finish()
} else {
interactiveAnimator?.cancel()
}
interactiveAnimator = nil
default:
break
}
}
}
| 8b9a6119ba3b95f846fe3610c3584ad8 | 38.972222 | 256 | 0.683808 | false | false | false | false |
AckeeCZ/ACKategories | refs/heads/master | ACKategoriesExample/Screens/VC composition/TitleViewController.swift | mit | 1 | //
// TitleViewController.swift
// ACKategories
//
// Created by Jakub Olejník on 12/09/2018.
// Copyright © 2018 Ackee, s.r.o. All rights reserved.
//
import UIKit
import ACKategories
class TitleViewController: BaseViewControllerNoVM {
private(set) weak var nameLabel: UILabel!
private let name: String
private let color: UIColor
// MARK: Initializers
init(name: String, color: UIColor) {
self.name = name
self.color = color
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View life cycle
override func loadView() {
super.loadView()
view.backgroundColor = color
let nameLabel = UILabel()
nameLabel.textAlignment = .center
nameLabel.text = name
view.addSubview(nameLabel)
nameLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
nameLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
nameLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20),
nameLabel.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20)
])
self.nameLabel = nameLabel
}
}
| e3c8a60967e15b0afcc64aebc63dd587 | 26.857143 | 112 | 0.671795 | false | false | false | false |
Paulinechi/Swift-Pauline | refs/heads/master | day3/day3HW.playground/section-1.swift | mit | 1 | // Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
//Q0
func printNumber(N: Int){
print(N)
if N > 0{
printNumber(N)
}
}
//Q1
class Recursion {
func printNumber(N: Int){
print(N)
if N > 1 {
printNumber(N - 1)
}
println(N)
}
}
//Q2
void; reverseWords( char * , str);_ = {
Int; i = 0;
char*; subStrStart;
char*; subStrEnd;
char*; currentPos;
currentPos = str;
while(*currentPos!=\0)
{
subStrStart = currentPos;
while(*currentPos!= "", &&*currentPos!=\0)
currentPos++;
subStrEnd = currentPos - 1;
reverseStr(str, (int)(subStrStart - str), (int)(subStrEnd - str));
currentPos++;
}
return;
}
Int(); main()
{
char; Str[20] = "I am a student.";
reverseStr(str, 0, strlen(str)-1 );
reverseWords(str);
printf("%s\n", str);
return 0;
}
//Q3
for (i) 1-n
push (ai)
pop (an)
min = an
for (i = n - 1 to n)
pop (ai)
if(ai < min){
min = ai
}
//Q4
/*void HeapAdjust(Int array[], Int i , Int , Length){
Int child , temp;
for(temp=array[i];2*i+1<Length;i=child)
{
child = 2*i+1;
if(child<Length-1 && array[child+1]<array[child]){
}
child++;
if (temp>array[child]){
}
array[i]=array[child];
} else{
break;
array[child]=temp;
}
}
void; Swap(int*, a,Int* b )
_ = {
*a=*a^*b;
*b=*a^*b;
*a=*a^*b;
}
Int GetMin( Int array[], Int Length, Int k)
{
int min=array[0];
Swap(&array[0],&array[Length-1]);
int child,temp;
int i=0,j=k-1;
for (temp=array[0]; j>0 && 2*i+1<Length; --j,i=child)
{
child = 2*i+1;
if(child<Length-1 && array[child+1]<array[child])
child++;
if (temp>array[child])
array[i]=array[child];
else
break;
array[child]=temp;
}
return min;
}
void Kmin(int array[] , int Length , int k)
{
for(int i=Length/2-1;i>=0;--i)
//初始建堆,时间复杂度为O(n)
HeapAdjust(array,i,Length);
int j=Length;
for(i=k;i>0;--i,--j)
//k次循环,每次循环的复杂度最多为k次交换,复杂度为o(k^2)
{
int min=GetMin(array,j,i);
printf("%d,", min);
}
}
Int main()
{
int array[MAXLEN];
for(int i=MAXLEN;i>0;--i)
array[MAXLEN-i] = i;
Kmin(array,MAXLEN,K);
return 0;
}
*/
//Q5
/*
6架
三架从一个方向起飞,到1/8路程时第一架将2 3加满油返回,到1/4时,2将3加满返回,3到1/2时,456从另一方向起飞,456飞行过程与123一致,3与6将在3/4相遇,6这时是满油,分一半给3就可以了。所以是6架。
//Q6
//Q7
//intergration
| 2b265e480dbdc50dd7b76c21c58bd411 | 14.152542 | 110 | 0.494407 | false | false | false | false |
Andgfaria/MiniGitClient-iOS | refs/heads/master | Brejas/Pods/Nimble/Sources/Nimble/ExpectationMessage.swift | apache-2.0 | 28 | import Foundation
public indirect enum ExpectationMessage {
// --- Primary Expectations ---
/// includes actual value in output ("expected to <message>, got <actual>")
case expectedActualValueTo(/* message: */ String)
/// uses a custom actual value string in output ("expected to <message>, got <actual>")
case expectedCustomValueTo(/* message: */ String, /* actual: */ String)
/// excludes actual value in output ("expected to <message>")
case expectedTo(/* message: */ String)
/// allows any free-form message ("<message>")
case fail(/* message: */ String)
// --- Composite Expectations ---
// Generally, you'll want the methods, appended(message:) and appended(details:) instead.
/// Not Fully Implemented Yet.
case prepends(/* Prepended Message */ String, ExpectationMessage)
/// appends after an existing message ("<expectation> (use beNil() to match nils)")
case appends(ExpectationMessage, /* Appended Message */ String)
/// provides long-form multi-line explainations ("<expectation>\n\n<string>")
case details(ExpectationMessage, String)
internal var sampleMessage: String {
let asStr = toString(actual: "<ACTUAL>", expected: "expected", to: "to")
let asFailureMessage = FailureMessage()
update(failureMessage: asFailureMessage)
return "(toString(actual:expected:to:) -> \(asStr) || update(failureMessage:) -> \(asFailureMessage.stringValue))"
}
/// Returns the smallest message after the "expected to" string that summarizes the error.
///
/// Returns the message part from ExpectationMessage, ignoring all .appends and .details.
public var expectedMessage: String {
switch self {
case let .fail(msg):
return msg
case let .expectedTo(msg):
return msg
case let .expectedActualValueTo(msg):
return msg
case let .expectedCustomValueTo(msg, _):
return msg
case let .prepends(_, expectation):
return expectation.expectedMessage
case let .appends(expectation, msg):
return "\(expectation.expectedMessage)\(msg)"
case let .details(expectation, _):
return expectation.expectedMessage
}
}
/// Appends a message after the primary expectation message
public func appended(message: String) -> ExpectationMessage {
switch self {
case .fail, .expectedTo, .expectedActualValueTo, .expectedCustomValueTo, .appends, .prepends:
return .appends(self, message)
case let .details(expectation, msg):
return .details(expectation.appended(message: message), msg)
}
}
/// Appends a message hinting to use beNil() for when the actual value given was nil.
public func appendedBeNilHint() -> ExpectationMessage {
return appended(message: " (use beNil() to match nils)")
}
/// Appends a detailed (aka - multiline) message after the primary expectation message
/// Detailed messages will be placed after .appended(message:) calls.
public func appended(details: String) -> ExpectationMessage {
return .details(self, details)
}
internal func visitLeafs(_ f: (ExpectationMessage) -> ExpectationMessage) -> ExpectationMessage {
switch self {
case .fail, .expectedTo, .expectedActualValueTo, .expectedCustomValueTo:
return f(self)
case let .prepends(msg, expectation):
return .prepends(msg, expectation.visitLeafs(f))
case let .appends(expectation, msg):
return .appends(expectation.visitLeafs(f), msg)
case let .details(expectation, msg):
return .details(expectation.visitLeafs(f), msg)
}
}
/// Replaces a primary expectation with one returned by f. Preserves all composite expectations
/// that were built upon it (aka - all appended(message:) and appended(details:).
public func replacedExpectation(_ f: @escaping (ExpectationMessage) -> ExpectationMessage) -> ExpectationMessage {
func walk(_ msg: ExpectationMessage) -> ExpectationMessage {
switch msg {
case .fail, .expectedTo, .expectedActualValueTo, .expectedCustomValueTo:
return f(msg)
default:
return msg
}
}
return visitLeafs(walk)
}
/// Wraps a primary expectation with text before and after it.
/// Alias to prepended(message: before).appended(message: after)
public func wrappedExpectation(before: String, after: String) -> ExpectationMessage {
return prepended(expectation: before).appended(message: after)
}
/// Prepends a message by modifying the primary expectation
public func prepended(expectation message: String) -> ExpectationMessage {
func walk(_ msg: ExpectationMessage) -> ExpectationMessage {
switch msg {
case let .expectedTo(msg):
return .expectedTo(message + msg)
case let .expectedActualValueTo(msg):
return .expectedActualValueTo(message + msg)
case let .expectedCustomValueTo(msg, actual):
return .expectedCustomValueTo(message + msg, actual)
default:
return msg.visitLeafs(walk)
}
}
return visitLeafs(walk)
}
// TODO: test & verify correct behavior
internal func prepended(message: String) -> ExpectationMessage {
return .prepends(message, self)
}
/// Converts the tree of ExpectationMessages into a final built string.
public func toString(actual: String, expected: String = "expected", to: String = "to") -> String {
switch self {
case let .fail(msg):
return msg
case let .expectedTo(msg):
return "\(expected) \(to) \(msg)"
case let .expectedActualValueTo(msg):
return "\(expected) \(to) \(msg), got \(actual)"
case let .expectedCustomValueTo(msg, actual):
return "\(expected) \(to) \(msg), got \(actual)"
case let .prepends(msg, expectation):
return "\(msg)\(expectation.toString(actual: actual, expected: expected, to: to))"
case let .appends(expectation, msg):
return "\(expectation.toString(actual: actual, expected: expected, to: to))\(msg)"
case let .details(expectation, msg):
return "\(expectation.toString(actual: actual, expected: expected, to: to))\n\n\(msg)"
}
}
// Backwards compatibility: converts ExpectationMessage tree to FailureMessage
internal func update(failureMessage: FailureMessage) {
switch self {
case let .fail(msg):
failureMessage.stringValue = msg
case let .expectedTo(msg):
failureMessage.actualValue = nil
failureMessage.postfixMessage = msg
case let .expectedActualValueTo(msg):
failureMessage.postfixMessage = msg
case let .expectedCustomValueTo(msg, actual):
failureMessage.postfixMessage = msg
failureMessage.actualValue = actual
case let .prepends(msg, expectation):
expectation.update(failureMessage: failureMessage)
if let desc = failureMessage.userDescription {
failureMessage.userDescription = "\(msg)\(desc)"
} else {
failureMessage.userDescription = msg
}
case let .appends(expectation, msg):
expectation.update(failureMessage: failureMessage)
failureMessage.appendMessage(msg)
case let .details(expectation, msg):
expectation.update(failureMessage: failureMessage)
failureMessage.appendDetails(msg)
}
}
}
extension FailureMessage {
internal func toExpectationMessage() -> ExpectationMessage {
let defaultMsg = FailureMessage()
if expected != defaultMsg.expected || _stringValueOverride != nil {
return .fail(stringValue)
}
var msg: ExpectationMessage = .fail(userDescription ?? "")
if actualValue != "" && actualValue != nil {
msg = .expectedCustomValueTo(postfixMessage, actualValue ?? "")
} else if postfixMessage != defaultMsg.postfixMessage {
if actualValue == nil {
msg = .expectedTo(postfixMessage)
} else {
msg = .expectedActualValueTo(postfixMessage)
}
}
if postfixActual != defaultMsg.postfixActual {
msg = .appends(msg, postfixActual)
}
if let m = extendedMessage {
msg = .details(msg, m)
}
return msg
}
}
#if _runtime(_ObjC)
public class NMBExpectationMessage: NSObject {
private let msg: ExpectationMessage
internal init(swift msg: ExpectationMessage) {
self.msg = msg
}
public init(expectedTo message: String) {
self.msg = .expectedTo(message)
}
public init(expectedActualValueTo message: String) {
self.msg = .expectedActualValueTo(message)
}
public init(expectedActualValueTo message: String, customActualValue actual: String) {
self.msg = .expectedCustomValueTo(message, actual)
}
public init(fail message: String) {
self.msg = .fail(message)
}
public init(prepend message: String, child: NMBExpectationMessage) {
self.msg = .prepends(message, child.msg)
}
public init(appendedMessage message: String, child: NMBExpectationMessage) {
self.msg = .appends(child.msg, message)
}
public init(prependedMessage message: String, child: NMBExpectationMessage) {
self.msg = .prepends(message, child.msg)
}
public init(details message: String, child: NMBExpectationMessage) {
self.msg = .details(child.msg, message)
}
public func appendedBeNilHint() -> NMBExpectationMessage {
return NMBExpectationMessage(swift: msg.appendedBeNilHint())
}
public func toSwift() -> ExpectationMessage { return self.msg }
}
extension ExpectationMessage {
func toObjectiveC() -> NMBExpectationMessage {
return NMBExpectationMessage(swift: self)
}
}
#endif
| dd3fff02ba7033d69f7c26b2565adf5c | 38.360153 | 122 | 0.636523 | false | false | false | false |
MangoMade/MMNavigationController | refs/heads/master | Source/UIViewControllerExtension.swift | mit | 1 | //
// UIViewControllerExtension.swift
// MMNavigationController
//
// Created by Mango on 2017/4/9.
// Copyright © 2017年 MangoMade. All rights reserved.
//
import UIKit
extension UIViewController: NamespaceWrappable { }
private extension TypeWrapper {
var viewController: T {
return wrapperObject
}
}
fileprivate struct AssociatedKey {
static var viewWillAppearInjectBlock = 0
static var navigationBarHidden = 0
static var popGestrueEnable = 0
static var navigationBarBackgroundColor = 0
static var popGestrueEnableWidth = 0
static var navigationBarTitleColor = 0
static var gestureDelegate = 0
}
public extension TypeWrapper where T: UIViewController {
/// 在AppDelegate中调用此方法
public static func load() {
UIViewController.methodsSwizzling
}
/// navigationBar 是否隐藏
public var navigationBarHidden: Bool {
get {
var hidden = objc_getAssociatedObject(self.viewController, &AssociatedKey.navigationBarHidden) as? NSNumber
if hidden == nil {
hidden = NSNumber(booleanLiteral: false)
objc_setAssociatedObject(self.viewController,
&AssociatedKey.navigationBarHidden,
hidden,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return hidden!.boolValue
}
set {
objc_setAssociatedObject(self.viewController,
&AssociatedKey.navigationBarHidden,
NSNumber(booleanLiteral: newValue),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// pop 手势是否可用
public var popGestrueEnable: Bool {
get {
var enable = objc_getAssociatedObject(self.viewController, &AssociatedKey.popGestrueEnable) as? NSNumber
if enable == nil {
enable = NSNumber(booleanLiteral: true)
objc_setAssociatedObject(self.viewController,
&AssociatedKey.popGestrueEnable,
enable,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return enable!.boolValue
}
set {
objc_setAssociatedObject(self.viewController,
&AssociatedKey.popGestrueEnable,
NSNumber(booleanLiteral: newValue),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// pop手势可用宽度,从左开始计算
public var popGestrueEnableWidth: CGFloat {
get {
var width = objc_getAssociatedObject(self.viewController, &AssociatedKey.popGestrueEnableWidth) as? NSNumber
if width == nil {
width = NSNumber(floatLiteral: 0)
objc_setAssociatedObject(self.viewController,
&AssociatedKey.popGestrueEnableWidth,
width,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return CGFloat(width!.floatValue)
}
set {
objc_setAssociatedObject(self.viewController,
&AssociatedKey.popGestrueEnableWidth,
NSNumber(floatLiteral: Double(newValue)),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// navigationBar 背景颜色
public var navigationBarBackgroundColor: UIColor? {
get {
return objc_getAssociatedObject(self.viewController, &AssociatedKey.navigationBarBackgroundColor) as? UIColor
}
set {
objc_setAssociatedObject(self.viewController, &AssociatedKey.navigationBarBackgroundColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// navigationBar 标题字体颜色
public var navigationBarTitleColor: UIColor? {
get {
return objc_getAssociatedObject(self.viewController, &AssociatedKey.navigationBarTitleColor) as? UIColor
}
set {
objc_setAssociatedObject(self.viewController, &AssociatedKey.navigationBarTitleColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// gesture delegate
/// 可以通过设置这个代理,实现代理方法,解决手势冲突等问题
public weak var gestureDelegate: UIGestureRecognizerDelegate? {
get {
return gestureDelegateWrapper.instance
}
set {
gestureDelegateWrapper.instance = newValue
}
}
private var gestureDelegateWrapper: WeakReferenceWrapper<UIGestureRecognizerDelegate> {
var wrapper = objc_getAssociatedObject(self.viewController, &AssociatedKey.gestureDelegate) as? WeakReferenceWrapper<UIGestureRecognizerDelegate>
if wrapper == nil {
wrapper = WeakReferenceWrapper<UIGestureRecognizerDelegate>()
objc_setAssociatedObject(self.viewController, &AssociatedKey.gestureDelegate, wrapper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return wrapper!
}
internal var viewWillAppearInjectBlock: ViewControllerInjectBlockWrapper? {
get {
return objc_getAssociatedObject(self.viewController, &AssociatedKey.viewWillAppearInjectBlock) as? ViewControllerInjectBlockWrapper
}
set {
objc_setAssociatedObject(self.viewController, &AssociatedKey.viewWillAppearInjectBlock, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
extension UIViewController {
fileprivate static let methodsSwizzling: () = {
guard let originalViewWillAppearSelector = class_getInstanceMethod(UIViewController.self, #selector(viewWillAppear(_:))),
let swizzledViewWillAppearSelector = class_getInstanceMethod(UIViewController.self, #selector(mm_viewWillAppear(_:))) else {
return
}
method_exchangeImplementations(originalViewWillAppearSelector, swizzledViewWillAppearSelector)
}()
// MARK - private methods
@objc fileprivate func mm_viewWillAppear(_ animated: Bool) {
mm_viewWillAppear(animated)
mm.viewWillAppearInjectBlock?.block?(self, animated)
}
}
| e6b56ed6ee773d9722a846f0aebb3d97 | 37.939394 | 153 | 0.602957 | false | false | false | false |
wangyuanou/Coastline | refs/heads/master | Coastline/Paint/AttributeString+Doc.swift | mit | 1 | //
// AttributeString+Html.swift
// Coastline
//
// Created by 王渊鸥 on 2016/9/25.
// Copyright © 2016年 王渊鸥. All rights reserved.
//
import UIKit
public extension NSAttributedString {
public convenience init?(html:String) {
let options = [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue] as [String : Any]
if let data = html.data(using: .utf8, allowLossyConversion: true) {
try? self.init(data: data, options: options, documentAttributes: nil)
} else {
return nil
}
}
@available(iOS 9.0, *)
public convenience init?(rtfUrl:String) {
let options = [NSDocumentTypeDocumentAttribute : NSRTFTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue] as [String : Any]
guard let url = rtfUrl.url else { return nil }
try? self.init(url: url, options: options, documentAttributes: nil)
}
@available(iOS 9.0, *)
public convenience init?(rtfdUrl:String) {
let options = [NSDocumentTypeDocumentAttribute : NSRTFDTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue] as [String : Any]
guard let url = rtfdUrl.url else { return nil }
try? self.init(url: url, options: options, documentAttributes: nil)
}
}
| d48431822eb56665bc19678458cf4f2c | 34.945946 | 104 | 0.716541 | false | false | false | false |
tdquang/CarlWrite | refs/heads/master | CVCalendar/CVCalendarMonthContentViewController.swift | mit | 1 | //
// CVCalendarMonthContentViewController.swift
// CVCalendar Demo
//
// Created by Eugene Mozharovsky on 12/04/15.
// Copyright (c) 2015 GameApp. All rights reserved.
//
import UIKit
class CVCalendarMonthContentViewController: CVCalendarContentViewController {
private var monthViews: [Identifier : MonthView]
override init(calendarView: CalendarView, frame: CGRect) {
monthViews = [Identifier : MonthView]()
super.init(calendarView: calendarView, frame: frame)
initialLoad(presentedMonthView.date)
}
init(calendarView: CalendarView, frame: CGRect, presentedDate: NSDate) {
monthViews = [Identifier : MonthView]()
super.init(calendarView: calendarView, frame: frame)
presentedMonthView = MonthView(calendarView: calendarView, date: presentedDate)
presentedMonthView.updateAppearance(scrollView.bounds)
initialLoad(presentedDate)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Load & Reload
func initialLoad(date: NSDate) {
insertMonthView(getPreviousMonth(date), withIdentifier: Previous)
insertMonthView(presentedMonthView, withIdentifier: Presented)
insertMonthView(getFollowingMonth(date), withIdentifier: Following)
presentedMonthView.mapDayViews { dayView in
if self.matchedDays(dayView.date, Date(date: date)) {
self.calendarView.coordinator.flush()
self.calendarView.touchController.receiveTouchOnDayView(dayView)
dayView.circleView?.removeFromSuperview()
}
}
calendarView.presentedDate = CVDate(date: presentedMonthView.date)
}
func reloadMonthViews() {
for (identifier, monthView) in monthViews {
monthView.frame.origin.x = CGFloat(indexOfIdentifier(identifier)) * scrollView.frame.width
monthView.removeFromSuperview()
scrollView.addSubview(monthView)
}
}
// MARK: - Insertion
func insertMonthView(monthView: MonthView, withIdentifier identifier: Identifier) {
let index = CGFloat(indexOfIdentifier(identifier))
monthView.frame.origin = CGPointMake(scrollView.bounds.width * index, 0)
monthViews[identifier] = monthView
scrollView.addSubview(monthView)
}
func replaceMonthView(monthView: MonthView, withIdentifier identifier: Identifier, animatable: Bool) {
var monthViewFrame = monthView.frame
monthViewFrame.origin.x = monthViewFrame.width * CGFloat(indexOfIdentifier(identifier))
monthView.frame = monthViewFrame
monthViews[identifier] = monthView
if animatable {
scrollView.scrollRectToVisible(monthViewFrame, animated: false)
}
}
// MARK: - Load management
func scrolledLeft() {
if let presented = monthViews[Presented], let following = monthViews[Following] {
if pageLoadingEnabled {
pageLoadingEnabled = false
monthViews[Previous]?.removeFromSuperview()
replaceMonthView(presented, withIdentifier: Previous, animatable: false)
replaceMonthView(following, withIdentifier: Presented, animatable: true)
insertMonthView(getFollowingMonth(following.date), withIdentifier: Following)
}
}
}
func scrolledRight() {
if let previous = monthViews[Previous], let presented = monthViews[Presented] {
if pageLoadingEnabled {
pageLoadingEnabled = false
monthViews[Following]?.removeFromSuperview()
replaceMonthView(previous, withIdentifier: Presented, animatable: true)
replaceMonthView(presented, withIdentifier: Following, animatable: false)
insertMonthView(getPreviousMonth(previous.date), withIdentifier: Previous)
}
}
}
// MARK: - Override methods
override func updateFrames(rect: CGRect) {
super.updateFrames(rect)
for monthView in monthViews.values {
monthView.reloadViewsWithRect(rect != CGRectZero ? rect : scrollView.bounds)
}
reloadMonthViews()
if let presented = monthViews[Presented] {
if scrollView.frame.height != presented.potentialSize.height {
updateHeight(presented.potentialSize.height, animated: false)
}
scrollView.scrollRectToVisible(presented.frame, animated: false)
}
}
override func performedDayViewSelection(dayView: DayView) {
if dayView.isOut {
if dayView.date.day > 20 {
let presentedDate = dayView.monthView.date
calendarView.presentedDate = Date(date: self.dateBeforeDate(presentedDate))
presentPreviousView(dayView)
} else {
let presentedDate = dayView.monthView.date
calendarView.presentedDate = Date(date: self.dateAfterDate(presentedDate))
presentNextView(dayView)
}
}
}
override func presentPreviousView(view: UIView?) {
if presentationEnabled {
presentationEnabled = false
if let extra = monthViews[Following], let presented = monthViews[Presented], let previous = monthViews[Previous] {
UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.prepareTopMarkersOnMonthView(presented, hidden: true)
extra.frame.origin.x += self.scrollView.frame.width
presented.frame.origin.x += self.scrollView.frame.width
previous.frame.origin.x += self.scrollView.frame.width
self.replaceMonthView(presented, withIdentifier: self.Following, animatable: false)
self.replaceMonthView(previous, withIdentifier: self.Presented, animatable: false)
self.presentedMonthView = previous
self.updateLayoutIfNeeded()
}) { _ in
extra.removeFromSuperview()
self.insertMonthView(self.getPreviousMonth(previous.date), withIdentifier: self.Previous)
self.updateSelection()
self.presentationEnabled = true
for monthView in self.monthViews.values {
self.prepareTopMarkersOnMonthView(monthView, hidden: false)
}
}
}
}
}
override func presentNextView(view: UIView?) {
if presentationEnabled {
presentationEnabled = false
if let extra = monthViews[Previous], let presented = monthViews[Presented], let following = monthViews[Following] {
UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.prepareTopMarkersOnMonthView(presented, hidden: true)
extra.frame.origin.x -= self.scrollView.frame.width
presented.frame.origin.x -= self.scrollView.frame.width
following.frame.origin.x -= self.scrollView.frame.width
self.replaceMonthView(presented, withIdentifier: self.Previous, animatable: false)
self.replaceMonthView(following, withIdentifier: self.Presented, animatable: false)
self.presentedMonthView = following
self.updateLayoutIfNeeded()
}) { _ in
extra.removeFromSuperview()
self.insertMonthView(self.getFollowingMonth(following.date), withIdentifier: self.Following)
self.updateSelection()
self.presentationEnabled = true
for monthView in self.monthViews.values {
self.prepareTopMarkersOnMonthView(monthView, hidden: false)
}
}
}
}
}
override func updateDayViews(hidden: Bool) {
setDayOutViewsVisible(hidden)
}
private var togglingBlocked = false
override func togglePresentedDate(date: NSDate) {
let presentedDate = Date(date: date)
if let presented = monthViews[Presented], let selectedDate = calendarView.coordinator.selectedDayView?.date {
if !matchedDays(selectedDate, presentedDate) && !togglingBlocked {
if !matchedMonths(presentedDate, selectedDate) {
togglingBlocked = true
monthViews[Previous]?.removeFromSuperview()
monthViews[Following]?.removeFromSuperview()
insertMonthView(getPreviousMonth(date), withIdentifier: Previous)
insertMonthView(getFollowingMonth(date), withIdentifier: Following)
let currentMonthView = MonthView(calendarView: calendarView, date: date)
currentMonthView.updateAppearance(scrollView.bounds)
currentMonthView.alpha = 0
insertMonthView(currentMonthView, withIdentifier: Presented)
presentedMonthView = currentMonthView
calendarView.presentedDate = Date(date: date)
UIView.animateWithDuration(0.8, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
presented.alpha = 0
currentMonthView.alpha = 1
}) { _ in
presented.removeFromSuperview()
self.selectDayViewWithDay(presentedDate.day, inMonthView: currentMonthView)
self.togglingBlocked = false
self.updateLayoutIfNeeded()
}
} else {
if let currentMonthView = monthViews[Presented] {
selectDayViewWithDay(presentedDate.day, inMonthView: currentMonthView)
}
}
}
}
}
}
// MARK: - Month management
extension CVCalendarMonthContentViewController {
func getFollowingMonth(date: NSDate) -> MonthView {
let firstDate = calendarView.manager.monthDateRange(date).monthStartDate
let components = Manager.componentsForDate(firstDate)
components.month += 1
let newDate = NSCalendar.currentCalendar().dateFromComponents(components)!
let frame = scrollView.bounds
let monthView = MonthView(calendarView: calendarView, date: newDate)
monthView.updateAppearance(frame)
return monthView
}
func getPreviousMonth(date: NSDate) -> MonthView {
let firstDate = calendarView.manager.monthDateRange(date).monthStartDate
let components = Manager.componentsForDate(firstDate)
components.month -= 1
let newDate = NSCalendar.currentCalendar().dateFromComponents(components)!
let frame = scrollView.bounds
let monthView = MonthView(calendarView: calendarView, date: newDate)
monthView.updateAppearance(frame)
return monthView
}
}
// MARK: - Visual preparation
extension CVCalendarMonthContentViewController {
func prepareTopMarkersOnMonthView(monthView: MonthView, hidden: Bool) {
monthView.mapDayViews { dayView in
dayView.topMarker?.hidden = hidden
}
}
func setDayOutViewsVisible(visible: Bool) {
for monthView in monthViews.values {
monthView.mapDayViews { dayView in
if dayView.isOut {
if !visible {
dayView.alpha = 0
dayView.hidden = false
}
UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
dayView.alpha = visible ? 0 : 1
}) { _ in
if visible {
dayView.alpha = 1
dayView.hidden = true
dayView.userInteractionEnabled = false
} else {
dayView.userInteractionEnabled = true
}
}
}
}
}
}
func updateSelection() {
let coordinator = calendarView.coordinator
if let selected = coordinator.selectedDayView {
for (index, monthView) in monthViews {
if indexOfIdentifier(index) != 1 {
monthView.mapDayViews {
dayView in
if dayView == selected {
dayView.setDeselectedWithClearing(true)
coordinator.dequeueDayView(dayView)
}
}
}
}
}
if let presentedMonthView = monthViews[Presented] {
self.presentedMonthView = presentedMonthView
calendarView.presentedDate = Date(date: presentedMonthView.date)
if let selected = coordinator.selectedDayView, let selectedMonthView = selected.monthView where !matchedMonths(Date(date: selectedMonthView.date), Date(date: presentedMonthView.date)) {
let current = Date(date: NSDate())
let presented = Date(date: presentedMonthView.date)
if matchedMonths(current, presented) {
selectDayViewWithDay(current.day, inMonthView: presentedMonthView)
} else {
selectDayViewWithDay(Date(date: calendarView.manager.monthDateRange(presentedMonthView.date).monthStartDate).day, inMonthView: presentedMonthView)
}
}
}
}
func selectDayViewWithDay(day: Int, inMonthView monthView: CVCalendarMonthView) {
let coordinator = calendarView.coordinator
monthView.mapDayViews { dayView in
if dayView.date.day == day && !dayView.isOut {
if let selected = coordinator.selectedDayView where selected != dayView {
self.calendarView.didSelectDayView(dayView)
}
coordinator.performDayViewSingleSelection(dayView)
}
}
}
}
// MARK: - UIScrollViewDelegate
extension CVCalendarMonthContentViewController {
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView.contentOffset.y != 0 {
scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, 0)
}
let page = Int(floor((scrollView.contentOffset.x - scrollView.frame.width / 2) / scrollView.frame.width) + 1)
if currentPage != page {
currentPage = page
}
lastContentOffset = scrollView.contentOffset.x
}
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
if let presented = monthViews[Presented] {
prepareTopMarkersOnMonthView(presented, hidden: true)
}
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if pageChanged {
switch direction {
case .Left: scrolledLeft()
case .Right: scrolledRight()
default: break
}
}
updateSelection()
updateLayoutIfNeeded()
pageLoadingEnabled = true
direction = .None
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if decelerate {
let rightBorder = scrollView.frame.width
if scrollView.contentOffset.x <= rightBorder {
direction = .Right
} else {
direction = .Left
}
}
for monthView in monthViews.values {
prepareTopMarkersOnMonthView(monthView, hidden: false)
}
}
} | 4f4a1a4d4fa7db5f4cd592fe2adf760f | 39.102625 | 197 | 0.580705 | false | false | false | false |
ji3g4m6zo6/bookmark | refs/heads/master | Pods/BarcodeScanner/Sources/Config.swift | mit | 1 | import UIKit
import AVFoundation
// MARK: - Configurations
public struct Title {
public static var text = NSLocalizedString("Scan barcode", comment: "")
public static var font = UIFont.boldSystemFont(ofSize: 17)
public static var color = UIColor.black
}
public struct CloseButton {
public static var text = NSLocalizedString("Close", comment: "")
public static var font = UIFont.boldSystemFont(ofSize: 17)
public static var color = UIColor.black
}
public struct SettingsButton {
public static var text = NSLocalizedString("Settings", comment: "")
public static var font = UIFont.boldSystemFont(ofSize: 17)
public static var color = UIColor.white
}
public struct Info {
public static var text = NSLocalizedString(
"Place the barcode within the window to scan. The search will start automatically.", comment: "")
public static var loadingText = NSLocalizedString(
"Looking for your product...", comment: "")
public static var notFoundText = NSLocalizedString(
"No product found.", comment: "")
public static var settingsText = NSLocalizedString(
"In order to scan barcodes you have to allow camera under your settings.", comment: "")
public static var font = UIFont.boldSystemFont(ofSize: 14)
public static var textColor = UIColor.black
public static var tint = UIColor.black
public static var loadingFont = UIFont.boldSystemFont(ofSize: 16)
public static var loadingTint = UIColor.black
public static var notFoundTint = UIColor.red
}
/**
Returns image with a given name from the resource bundle.
- Parameter name: Image name.
- Returns: An image.
*/
func imageNamed(_ name: String) -> UIImage {
let cls = BarcodeScannerController.self
var bundle = Bundle(for: cls)
let traitCollection = UITraitCollection(displayScale: 3)
if let path = bundle.resourcePath,
let resourceBundle = Bundle(path: path + "/BarcodeScanner.bundle") {
bundle = resourceBundle
}
guard let image = UIImage(named: name, in: bundle,
compatibleWith: traitCollection)
else { return UIImage() }
return image
}
/**
`AVCaptureMetadataOutput` metadata object types.
*/
public var metadata = [
AVMetadataObjectTypeUPCECode,
AVMetadataObjectTypeCode39Code,
AVMetadataObjectTypeCode39Mod43Code,
AVMetadataObjectTypeEAN13Code,
AVMetadataObjectTypeEAN8Code,
AVMetadataObjectTypeCode93Code,
AVMetadataObjectTypeCode128Code,
AVMetadataObjectTypePDF417Code,
AVMetadataObjectTypeQRCode,
AVMetadataObjectTypeAztecCode
]
| 006f1a546c52ebd71a8206a34f18fbf9 | 29.851852 | 101 | 0.752701 | false | false | false | false |
ACChe/eidolon | refs/heads/master | Kiosk/Bid Fulfillment/RegistrationPasswordViewModel.swift | mit | 1 | import Foundation
import ReactiveCocoa
import Moya
class RegistrationPasswordViewModel {
private class PasswordHolder: NSObject {
dynamic var password: String = ""
}
var emailExistsSignal: RACSignal
let command: RACCommand
let email: String
init(passwordSignal: RACSignal, manualInvocationSignal: RACSignal, finishedSubject: RACSubject, email: String) {
let endpoint: ArtsyAPI = ArtsyAPI.FindExistingEmailRegistration(email: email)
let emailExistsSignal = Provider.sharedProvider.request(endpoint).map(responseIsOK).replayLast()
let passwordHolder = PasswordHolder()
RAC(passwordHolder, "password") <~ passwordSignal
command = RACCommand(enabled: passwordSignal.map(isStringLengthAtLeast(6))) { _ -> RACSignal! in
return emailExistsSignal.map { (object) -> AnyObject! in
let emailExists = object as! Bool
if emailExists {
let endpoint: ArtsyAPI = ArtsyAPI.XAuth(email: email, password: passwordHolder.password)
return Provider.sharedProvider.request(endpoint).filterSuccessfulStatusCodes().mapJSON()
} else {
return RACSignal.empty()
}
}.switchToLatest().doCompleted { () -> Void in
finishedSubject.sendCompleted()
}
}
self.emailExistsSignal = emailExistsSignal
self.email = email
manualInvocationSignal.subscribeNext { [weak self] _ -> Void in
self?.command.execute(nil)
return
}
}
func userForgotPasswordSignal() -> RACSignal {
let endpoint: ArtsyAPI = ArtsyAPI.LostPasswordNotification(email: email)
return XAppRequest(endpoint).filterSuccessfulStatusCodes().doNext { (json) -> Void in
logger.log("Sent forgot password request")
}
}
} | 14a1889031190ef8d764e10546caccf0 | 36.470588 | 116 | 0.642932 | false | false | false | false |
nhojb/SyncthingBar | refs/heads/master | SyncthingBar/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// SyncthingBar
//
// Created by John on 11/11/2016.
// Copyright © 2016 Olive Toast Software Ltd. All rights reserved.
//
import Cocoa
let kSyncthingURLDefaultsKey = "SyncthingURL"
let kSyncthingAPIKeyDefaultsKey = "SyncthingAPIKey"
let kSyncthingPathDefaultsKey = "SyncthingPath"
let kSyncthingLaunchDefaultsKey = "LaunchAtStartup"
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
@IBOutlet weak var statusMenu: NSMenu!
@IBOutlet weak var connectedMenuItem: NSMenuItem!
var connected: Bool = false {
didSet {
if let client = self.client, connected {
self.statusItem.button?.image = NSImage(named: "SyncthingEnabled")
self.connectedMenuItem.title = "Connected - \(client.url)"
} else {
self.statusItem.button?.image = NSImage(named: "SyncthingDisabled")
self.connectedMenuItem.title = "Not Connected"
}
}
}
private lazy var webViewWindowController: WebViewWindowController = WebViewWindowController(windowNibName: "WebViewWindow")
private lazy var preferencesWindowController: PreferencesWindowController = PreferencesWindowController(windowNibName: "PreferencesWindow")
private let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
private var client: SyncthingClient?
private var syncthing: Process?
private var syncthingPath: String?
private var launchSyncthing = true
func registerDefaults() {
UserDefaults.standard.register(defaults: [kSyncthingURLDefaultsKey: "http://127.0.0.1:8384",
kSyncthingPathDefaultsKey: "/usr/local/bin/syncthing",
kSyncthingLaunchDefaultsKey: true])
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
self.registerDefaults()
self.statusItem.menu = self.statusMenu
self.statusItem.button?.image = NSImage(named: "SyncthingDisabled")
self.launchSyncthing = UserDefaults.standard.bool(forKey: kSyncthingLaunchDefaultsKey)
self.syncthingPath = UserDefaults.standard.string(forKey: kSyncthingPathDefaultsKey)
self.updateClient()
self.updateSyncthing()
if self.client == nil {
self.openPreferences(self)
}
_ = NotificationCenter.default.addObserver(forName: PreferencesWindowController.preferencesDidCloseNotification,
object: nil,
queue: nil) { [weak self] notification in
self?.updateClient()
self?.updateSyncthing()
}
}
func applicationWillTerminate(_ aNotification: Notification) {
self.syncthing?.terminate()
}
func updateClient() {
guard let url = UserDefaults.standard.url(forKey: kSyncthingURLDefaultsKey) else {
return
}
// TODO: Store in keychain?
guard let apiKey = UserDefaults.standard.object(forKey: kSyncthingAPIKeyDefaultsKey) as? String else {
return
}
self.client = SyncthingClient(url: url, apiKey: apiKey)
self.client?.ping { [weak self] ok, error in
assert(Thread.isMainThread)
self?.connected = ok
}
}
func updateSyncthing() {
let launchSyncthing = UserDefaults.standard.bool(forKey: kSyncthingLaunchDefaultsKey)
let syncthingPath = UserDefaults.standard.string(forKey: kSyncthingPathDefaultsKey)
if launchSyncthing != self.launchSyncthing || syncthingPath != self.syncthingPath {
self.stopSyncthing()
}
self.launchSyncthing = launchSyncthing
self.syncthingPath = syncthingPath
if launchSyncthing {
self.startSyncthing()
}
}
func startSyncthing() {
guard self.syncthing == nil else {
return
}
guard let syncthingPath = self.syncthingPath else {
return
}
// syncthing -no-browser
if Processes.find(processName: "syncthing") == nil {
self.syncthing = Process.launchedProcess(launchPath: syncthingPath, arguments: ["-no-browser"])
} else {
print("syncthing already running!")
}
// Poll until the server is launched:
self.client?.checkConnection(repeating: 5) { [weak self] ok, error in
assert(Thread.isMainThread)
self?.connected = ok
}
}
func stopSyncthing() {
guard self.syncthing != nil else {
return
}
self.syncthing?.terminate()
self.syncthing?.waitUntilExit()
self.syncthing = nil
self.client?.ping { [weak self] ok, error in
assert(Thread.isMainThread)
self?.connected = ok
}
}
@IBAction func openPreferences(_ sender: Any) {
NSApplication.shared.activate(ignoringOtherApps: true)
self.preferencesWindowController.showWindow(self)
}
@IBAction func openSyncthing(_ sender: Any) {
// User UserDefaults url in case the API key has not yet been set (user can still connect via browser).
if let url = UserDefaults.standard.url(forKey: kSyncthingURLDefaultsKey) {
NSApplication.shared.activate(ignoringOtherApps: true)
self.webViewWindowController.showWindow(self)
let request = URLRequest(url: url)
self.webViewWindowController.webView?.load(request)
}
}
// NSMenuDelegate
func menuWillOpen(_ menu: NSMenu) {
self.client?.ping { [weak self] ok, error in
assert(Thread.isMainThread)
self?.connected = ok
}
}
}
| ca5c4ba9c74f67dea51a25f517f7ee32 | 31.519337 | 143 | 0.631668 | false | false | false | false |
exchangegroup/paged-scroll-view-with-images | refs/heads/master | paged-scroll-view-with-images/TegColors.swift | mit | 2 | import UIKit
enum TegColor: String {
case Bag = "#2bb999"
case Heart = "#ea3160"
case Shade10 = "#000000"
case Shade20 = "#1C1C1C"
case Shade30 = "#383838"
case Shade40 = "#545454"
case Shade50 = "#707070"
case Shade60 = "#8C8C8C"
case Shade70 = "#A8A8A8"
case Shade80 = "#C4C4C4"
case Shade90 = "#E0E0E0"
case Shade95 = "#F0F0F0"
case Shade100 = "#FFFFFF"
var uiColor: UIColor {
return TegUIColor.fromHexString(rawValue)
}
}
| d09c4e90a4fb87672a6c12dea01bd391 | 20.318182 | 45 | 0.637527 | false | false | false | false |
sonsongithub/reddift | refs/heads/master | test/CAPTCHATest.swift | mit | 1 | //
// CAPTCHATest.swift
// reddift
//
// Created by sonson on 2015/05/07.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
import XCTest
#if os(iOS)
import UIKit
#endif
class CAPTCHATest: SessionTestSpec {
// now, CAPTCHA API does not work.....?
// func testCheckWhetherCAPTCHAIsNeededOrNot() {
// let msg = "is true or false as Bool"
// print(msg)
// var check_result: Bool? = nil
// let documentOpenExpectation = self.expectation(description: msg)
// do {
// try self.session?.checkNeedsCAPTCHA({(result) -> Void in
// switch result {
// case .failure(let error):
// print(error)
// case .success(let check):
// check_result = check
// }
// XCTAssert(check_result != nil, msg)
// documentOpenExpectation.fulfill()
// })
// } catch { XCTFail((error as NSError).description) }
// self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
// }
// now, CAPTCHA API does not work.....?
// func testGetIdenForNewCAPTCHA() {
// let msg = "is String"
// print(msg)
// var iden: String? = nil
// let documentOpenExpectation = self.expectation(description: msg)
// do {
// try self.session?.getIdenForNewCAPTCHA({ (result) -> Void in
// switch result {
// case .failure(let error):
// print(error.description)
// case .success(let identifier):
// iden = identifier
// }
// XCTAssert(iden != nil, msg)
// documentOpenExpectation.fulfill()
// })
// } catch { XCTFail((error as NSError).description) }
// self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
// }
// now, CAPTCHA API does not work.....?
// func testSizeOfNewImageGeneratedUsingIden() {
// let msg = "is 120x50"
// print(msg)
//#if os(iOS) || os(tvOS)
// var size: CGSize? = nil
//#elseif os(macOS)
// var size: NSSize? = nil
//#endif
// let documentOpenExpectation = self.expectation(description: msg)
// do {
// try self.session?.getIdenForNewCAPTCHA({ (result) -> Void in
// switch result {
// case .failure(let error):
// print(error.description)
// case .success(let string):
// try! self.session?.getCAPTCHA(string, completion: { (result) -> Void in
// switch result {
// case .failure(let error):
// print(error.description)
// case .success(let image):
// size = image.size
// }
// documentOpenExpectation.fulfill()
// })
// }
// })
// } catch { XCTFail((error as NSError).description) }
// self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
//
// if let size = size {
//#if os(iOS)
// XCTAssert(size == CGSize(width: 120, height: 50), msg)
//#elseif os(macOS)
// XCTAssert(size == NSSize(width: 120, height: 50), msg)
//#endif
// } else {
// XCTFail(msg)
// }
// }
}
| a691831e836b4094ed944c1221e09226 | 33.49505 | 93 | 0.504018 | false | true | false | false |
SSU-CS-Department/ssumobile-ios | refs/heads/master | SSUMobile/Modules/Resources/Views/SSUResourcesViewController.swift | apache-2.0 | 1 | //
// SSUResourcesViewController.swift
// SSUMobile
//
// Created by Eric Amorde on 10/5/14.
// Copyright (c) 2014 Sonoma State University Department of Computer Science. All rights reserved.
//
import Foundation
class SSUResourcesViewController: SSUCoreDataTableViewController<SSUResourcesEntry> {
var context: NSManagedObjectContext {
return SSUResourcesModule.instance.context
}
var selectedIndexPath: IndexPath?
override func viewDidLoad() {
super.viewDidLoad()
tableView.separatorColor = .ssuBlue
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension;
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: #selector(self.refresh), for: .valueChanged)
// Remove search button
navigationItem.rightBarButtonItem = nil
setupCoreData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.reloadData()
}
@objc func refresh() {
SSUResourcesModule.instance.updateData { [weak self] in
DispatchQueue.main.async {
self?.refreshControl?.endRefreshing()
}
}
}
func setupCoreData() {
let sortDescriptors: [NSSortDescriptor] = [
NSSortDescriptor(key: "section.position", ascending: true),
NSSortDescriptor(key: "id", ascending: true)
]
let request: NSFetchRequest<SSUResourcesEntry> = SSUResourcesEntry.fetchRequest()
request.sortDescriptors = sortDescriptors
fetchedResultsController = NSFetchedResultsController<SSUResourcesEntry>(fetchRequest: request,
managedObjectContext: context,
sectionNameKeyPath: "section.position",
cacheName: nil)
}
// MARK: UITableView
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let info = fetchedResultsController?.sections?[section]
if let firstResource = info?.objects?.first as? SSUResourcesEntry {
return firstResource.section?.name
}
return nil
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SSUResourcesCell
let resource = object(atIndex: indexPath)
cell.titleLabel.text = resource.name
cell.phoneLabel.textColor = .ssuBlue
cell.phoneLabel.text = resource.phone
cell.urlLabel.text = resource.url?.replacingOccurrences(of: "http://", with: "").replacingOccurrences(of: "www.", with: "")
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let resource = object(atIndex: indexPath)
if resource.phone == nil && resource.url == nil {
SSULogging.logError("Resource selected but missing phone and url: \(resource)")
return
}
selectedIndexPath = indexPath
let controller = UIAlertController(title: resource.name, message: nil, preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
if let phone = resource.phone, !phone.isEmpty {
let title = "Call \(phone)"
controller.addAction(UIAlertAction(title: title, style: .default, handler: { (_) in
self.callPhoneNumber(phone)
}))
}
if let urlString = resource.url, let url = URL(string: urlString) {
let title = "Open in Safari"
controller.addAction(UIAlertAction(title: title, style: .default, handler: { (_) in
self.openURL(url)
}))
}
present(controller, animated: true, completion: nil)
}
func callPhoneNumber(_ phone: String) {
if let url = URL(string: "tel://\(phone))"), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
} else {
SSULogging.logError("Unable to call phone number \(phone)")
}
}
func openURL(_ url: URL) {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
} else {
SSULogging.logError("Unable to open url \(url)")
}
}
}
| 3f26b6d939004a16d6fcdbfbc3993ecf | 36.141732 | 131 | 0.614374 | false | false | false | false |
february29/Learning | refs/heads/master | swift/Fch_Contact/Fch_Contact/AppClasses/ViewController/FontViewController.swift | mit | 1 | //
// FontViewController.swift
// Fch_Contact
//
// Created by bai on 2018/1/15.
// Copyright © 2018年 北京仙指信息技术有限公司. All rights reserved.
//
import UIKit
import SnapKit
class FontViewController: BBaseViewController ,UITableViewDelegate,UITableViewDataSource{
let dataArray = [FontSize.small,FontSize.middle,FontSize.large]
lazy var tableView:UITableView = {
let table = UITableView.init(frame: CGRect.zero, style: .grouped);
table.showsVerticalScrollIndicator = false;
table.showsHorizontalScrollIndicator = false;
// table.estimatedRowHeight = 30;
table.delegate = self;
table.dataSource = self;
table.setBackgroundColor(.tableBackground);
table.setSeparatorColor(.primary);
table.register(FontTableViewCell.self, forCellReuseIdentifier: "cell")
table.rowHeight = UITableViewAutomaticDimension;
// table.separatorStyle = .none;
table.tableFooterView = UIView();
return table;
}();
override func viewDidLoad() {
super.viewDidLoad()
self.title = BLocalizedString(key: "Font Size");
self.view.addSubview(self.tableView);
self.tableView.snp.makeConstraints { (make) in
make.left.right.top.bottom.equalToSuperview();
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = FontTableViewCell.init(style: .default, reuseIdentifier: "cell");
cell.coloumLable1?.text = dataArray[indexPath.row].displayName;
if indexPath.row == 0 {
cell.coloumLable1?.font = UIFont.systemFont(ofSize: 11);
}else if indexPath.row == 1{
cell.coloumLable1?.font = UIFont.systemFont(ofSize: 13);
}else{
cell.coloumLable1?.font = UIFont.systemFont(ofSize: 15);
}
// cell.setSelected(true, animated: false);
return cell;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
FontCenter.shared.fontSize = dataArray[indexPath.row] ;
let setting = UserDefaults.standard.getUserSettingModel()
setting.fontSize = dataArray[indexPath.row];
UserDefaults.standard.setUserSettingModel(model: setting);
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 1;
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 45;
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return UIView();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| d880373f673751e27d09c9de2812fea5 | 27.95283 | 100 | 0.622353 | false | false | false | false |
yunzixun/V2ex-Swift | refs/heads/master | Common/AnalyzeURLHelper.swift | mit | 1 | //
// AnalyzeURLHelper.swift
// V2ex-Swift
//
// Created by huangfeng on 2/18/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
class AnalyzeURLHelper {
/**
分析URL 进行相应的操作
- parameter url: 各种URL 例如https://baidu.com 、/member/finab 、/t/100000
*/
@discardableResult
class func Analyze(_ url:String) -> Bool {
let result = AnalyzURLResultType(url: url)
switch result {
case .url(let url):
url.run()
case .member(let member):
member.run()
case .topic(let topic):
topic.run()
case .undefined :
return false
}
return true
}
}
enum AnalyzURLResultType {
/// 普通URL链接
case url(UrlActionModel)
/// 用户
case member(MemberActionModel)
/// 帖子链接
case topic(TopicActionModel)
/// 未定义
case undefined
private enum `Type` : Int {
case url, member, topic , undefined
}
private static let patterns = [
"^(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?",
"^(http:\\/\\/|https:\\/\\/)?(www\\.)?(v2ex.com)?/member/[a-zA-Z0-9_]+$",
"^(http:\\/\\/|https:\\/\\/)?(www\\.)?(v2ex.com)?/t/[0-9]+",
]
init(url:String) {
var resultType:AnalyzURLResultType = .undefined
var type = Type.undefined
for pattern in AnalyzURLResultType.patterns {
let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
regex.enumerateMatches(in: url, options: .withoutAnchoringBounds, range: NSMakeRange(0, url.Lenght), using: { (result, _, _) -> Void in
if let result = result {
let range = result.range
if range.location == NSNotFound || range.length <= 0 {
return ;
}
type = Type(rawValue: AnalyzURLResultType.patterns.index(of: pattern)!)!
switch type {
case .url:
if let action = UrlActionModel(url: url) {
resultType = .url(action)
}
case .member :
if let action = MemberActionModel(url: url) {
resultType = .member(action)
}
case .topic:
if let action = TopicActionModel(url: url) {
resultType = .topic(action)
}
default:break
}
}
})
}
self = resultType
}
}
protocol AnalyzeURLActionProtocol {
init?(url:String)
func run()
}
struct UrlActionModel: AnalyzeURLActionProtocol{
var url:String
init?(url:String) {
self.url = url;
}
func run() {
let controller = V2WebViewViewController(url: url)
V2Client.sharedInstance.topNavigationController.pushViewController(controller, animated: true)
}
}
struct MemberActionModel: AnalyzeURLActionProtocol {
var username:String
init?(url:String) {
if let range = url.range(of: "/member/") {
self.username = String(url[range.upperBound...])
}
else{
return nil
}
}
func run() {
let memberViewController = MemberViewController()
memberViewController.username = username
V2Client.sharedInstance.topNavigationController.pushViewController(memberViewController, animated: true)
}
}
struct TopicActionModel: AnalyzeURLActionProtocol {
var topicID:String
init?(url:String) {
if let range = url.range(of: "/t/") {
var topicID = url[range.upperBound...]
if let range = topicID.range(of: "?"){
topicID = topicID[..<range.lowerBound]
}
if let range = topicID.range(of: "#"){
topicID = topicID[..<range.lowerBound]
}
self.topicID = String(topicID)
}
else{
return nil;
}
}
func run() {
let controller = TopicDetailViewController()
controller.topicId = topicID
V2Client.sharedInstance.topNavigationController.pushViewController(controller, animated: true)
}
}
extension AnalyzeURLHelper {
/**
测试
*/
class func test() -> Void {
var urls = [
"http://v2ex.com/member/finab",
"https://v2ex.com/member/finab",
"http://www.v2ex.com/member/finab",
"https://www.v2ex.com/member/finab",
"v2ex.com/member/finab",
"www.v2ex.com/member/finab",
"/member/finab",
"/MEMBER/finab"
]
urls.forEach { (url) in
let result = AnalyzURLResultType(url: url)
if case AnalyzURLResultType.member(let member) = result {
print(member.username)
}
else{
assert(false, "不能解析member : " + url )
}
}
urls = [
"member/finab",
"www.baidu.com/member/finab",
"com/member/finab",
"www.baidu.com",
"http://www.baidu.com"
]
urls.forEach { (url) in
let result = AnalyzURLResultType(url: url)
if case AnalyzURLResultType.member(_) = result {
assert(true, "解析了不是member的URL : " + url )
}
}
}
}
| 9355d3b9043c01639c2fca53c2b4ecc4 | 28.115 | 147 | 0.488752 | false | false | false | false |
ianyh/Amethyst | refs/heads/development | Amethyst/Layout/Layouts/BinarySpacePartitioningLayout.swift | mit | 1 | //
// BinarySpacePartitioningLayout.swift
// Amethyst
//
// Created by Ian Ynda-Hummel on 5/29/16.
// Copyright © 2016 Ian Ynda-Hummel. All rights reserved.
//
import Silica
class TreeNode<Window: WindowType>: Codable {
typealias WindowID = Window.WindowID
private enum CodingKeys: String, CodingKey {
case left
case right
case windowID
}
weak var parent: TreeNode?
var left: TreeNode?
var right: TreeNode?
var windowID: WindowID?
init() {}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.left = try values.decodeIfPresent(TreeNode.self, forKey: .left)
self.right = try values.decodeIfPresent(TreeNode.self, forKey: .right)
self.windowID = try values.decodeIfPresent(WindowID.self, forKey: .windowID)
self.left?.parent = self
self.right?.parent = self
guard valid else {
throw LayoutDecodingError.invalidLayout
}
}
var valid: Bool {
return (left != nil && right != nil && windowID == nil) || (left == nil && right == nil && windowID != nil)
}
func findWindowID(_ windowID: WindowID) -> TreeNode? {
guard self.windowID == windowID else {
return left?.findWindowID(windowID) ?? right?.findWindowID(windowID)
}
return self
}
func orderedWindowIDs() -> [WindowID] {
guard let windowID = windowID else {
let leftWindowIDs = left?.orderedWindowIDs() ?? []
let rightWindowIDs = right?.orderedWindowIDs() ?? []
return leftWindowIDs + rightWindowIDs
}
return [windowID]
}
func insertWindowIDAtEnd(_ windowID: WindowID) {
guard left == nil && right == nil else {
right?.insertWindowIDAtEnd(windowID)
return
}
insertWindowID(windowID)
}
func insertWindowID(_ windowID: WindowID, atPoint insertionPoint: WindowID) {
guard self.windowID == insertionPoint else {
left?.insertWindowID(windowID, atPoint: insertionPoint)
right?.insertWindowID(windowID, atPoint: insertionPoint)
return
}
insertWindowID(windowID)
}
func removeWindowID(_ windowID: WindowID) {
guard let node = findWindowID(windowID) else {
log.error("Trying to remove window not in tree")
return
}
guard let parent = node.parent else {
return
}
guard let grandparent = parent.parent else {
if node == parent.left {
parent.windowID = parent.right?.windowID
} else {
parent.windowID = parent.left?.windowID
}
parent.left = nil
parent.right = nil
return
}
if parent == grandparent.left {
if node == parent.left {
grandparent.left = parent.right
} else {
grandparent.left = parent.left
}
grandparent.left?.parent = grandparent
} else {
if node == parent.left {
grandparent.right = parent.right
} else {
grandparent.right = parent.left
}
grandparent.right?.parent = grandparent
}
}
func insertWindowID(_ windowID: WindowID) {
guard parent != nil || self.windowID != nil else {
self.windowID = windowID
return
}
if let parent = parent {
let newParent = TreeNode()
let newNode = TreeNode()
newNode.parent = newParent
newNode.windowID = windowID
newParent.left = self
newParent.right = newNode
newParent.parent = parent
if self == parent.left {
parent.left = newParent
} else {
parent.right = newParent
}
self.parent = newParent
} else {
let newSelf = TreeNode()
let newNode = TreeNode()
newSelf.windowID = self.windowID
self.windowID = nil
newNode.windowID = windowID
left = newSelf
left?.parent = self
right = newNode
right?.parent = self
}
}
}
extension TreeNode: Equatable {
static func == (lhs: TreeNode, rhs: TreeNode) -> Bool {
return lhs.windowID == rhs.windowID && lhs.left == rhs.left && lhs.right == rhs.right
}
}
class BinarySpacePartitioningLayout<Window: WindowType>: StatefulLayout<Window> {
typealias WindowID = Window.WindowID
private typealias TraversalNode = (node: TreeNode<Window>, frame: CGRect)
private enum CodingKeys: String, CodingKey {
case rootNode
}
override static var layoutName: String { return "Binary Space Partitioning" }
override static var layoutKey: String { return "bsp" }
override var layoutDescription: String { return "\(lastKnownFocusedWindowID.debugDescription)" }
private var rootNode = TreeNode<Window>()
private var lastKnownFocusedWindowID: WindowID?
required init() {
super.init()
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.rootNode = try container.decode(TreeNode<Window>.self, forKey: .rootNode)
super.init()
}
override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(rootNode, forKey: .rootNode)
}
private func constructInitialTreeWithWindows(_ windows: [LayoutWindow<Window>]) {
for window in windows {
guard rootNode.findWindowID(window.id) == nil else {
continue
}
rootNode.insertWindowIDAtEnd(window.id)
if window.isFocused {
lastKnownFocusedWindowID = window.id
}
}
}
override func updateWithChange(_ windowChange: Change<Window>) {
switch windowChange {
case let .add(window):
guard rootNode.findWindowID(window.id()) == nil else {
log.warning("Trying to add a window already in the tree")
return
}
if let insertionPoint = lastKnownFocusedWindowID, window.id() != insertionPoint {
log.info("insert \(window) - \(window.id()) at point: \(insertionPoint)")
rootNode.insertWindowID(window.id(), atPoint: insertionPoint)
} else {
log.info("insert \(window) - \(window.id()) at end")
rootNode.insertWindowIDAtEnd(window.id())
}
if window.isFocused() {
lastKnownFocusedWindowID = window.id()
}
case let .remove(window):
log.info("remove: \(window) - \(window.id())")
rootNode.removeWindowID(window.id())
case let .focusChanged(window):
lastKnownFocusedWindowID = window.id()
case let .windowSwap(window, otherWindow):
let windowID = window.id()
let otherWindowID = otherWindow.id()
guard let windowNode = rootNode.findWindowID(windowID), let otherWindowNode = rootNode.findWindowID(otherWindowID) else {
log.error("Tried to perform an unbalanced window swap: \(windowID) <-> \(otherWindowID)")
return
}
windowNode.windowID = otherWindowID
otherWindowNode.windowID = windowID
case .applicationDeactivate, .applicationActivate, .spaceChange, .layoutChange, .unknown:
break
}
}
override func nextWindowIDCounterClockwise() -> WindowID? {
guard let focusedWindow = Window.currentlyFocused() else {
return nil
}
let orderedIDs = rootNode.orderedWindowIDs()
guard let focusedWindowIndex = orderedIDs.index(of: focusedWindow.id()) else {
return nil
}
let nextWindowIndex = (focusedWindowIndex == 0 ? orderedIDs.count - 1 : focusedWindowIndex - 1)
return orderedIDs[nextWindowIndex]
}
override func nextWindowIDClockwise() -> WindowID? {
guard let focusedWindow = Window.currentlyFocused() else {
return nil
}
let orderedIDs = rootNode.orderedWindowIDs()
guard let focusedWindowIndex = orderedIDs.index(of: focusedWindow.id()) else {
return nil
}
let nextWindowIndex = (focusedWindowIndex == orderedIDs.count - 1 ? 0 : focusedWindowIndex + 1)
return orderedIDs[nextWindowIndex]
}
override func frameAssignments(_ windowSet: WindowSet<Window>, on screen: Screen) -> [FrameAssignmentOperation<Window>]? {
let windows = windowSet.windows
guard !windows.isEmpty else {
return []
}
if rootNode.left == nil && rootNode.right == nil {
constructInitialTreeWithWindows(windows)
}
let windowIDMap: [WindowID: LayoutWindow<Window>] = windows.reduce([:]) { (windowMap, window) -> [WindowID: LayoutWindow<Window>] in
var mutableWindowMap = windowMap
mutableWindowMap[window.id] = window
return mutableWindowMap
}
let baseFrame = screen.adjustedFrame()
var ret: [FrameAssignmentOperation<Window>] = []
var traversalNodes: [TraversalNode] = [(node: rootNode, frame: baseFrame)]
while !traversalNodes.isEmpty {
let traversalNode = traversalNodes[0]
traversalNodes = [TraversalNode](traversalNodes.dropFirst(1))
if let windowID = traversalNode.node.windowID {
guard let window = windowIDMap[windowID] else {
log.warning("Could not find window for ID: \(windowID)")
continue
}
let resizeRules = ResizeRules(isMain: true, unconstrainedDimension: .horizontal, scaleFactor: 1)
let frameAssignment = FrameAssignment<Window>(
frame: traversalNode.frame,
window: window,
screenFrame: baseFrame,
resizeRules: resizeRules
)
ret.append(FrameAssignmentOperation(frameAssignment: frameAssignment, windowSet: windowSet))
} else {
guard let left = traversalNode.node.left, let right = traversalNode.node.right else {
log.error("Encountered an invalid node")
continue
}
let frame = traversalNode.frame
if frame.width > frame.height {
let leftFrame = CGRect(
x: frame.origin.x,
y: frame.origin.y,
width: frame.width / 2.0,
height: frame.height
)
let rightFrame = CGRect(
x: frame.origin.x + frame.width / 2.0,
y: frame.origin.y,
width: frame.width / 2.0,
height: frame.height
)
traversalNodes.append((node: left, frame: leftFrame))
traversalNodes.append((node: right, frame: rightFrame))
} else {
let topFrame = CGRect(
x: frame.origin.x,
y: frame.origin.y,
width: frame.width,
height: frame.height / 2.0
)
let bottomFrame = CGRect(
x: frame.origin.x,
y: frame.origin.y + frame.height / 2.0,
width: frame.width,
height: frame.height / 2.0
)
traversalNodes.append((node: left, frame: topFrame))
traversalNodes.append((node: right, frame: bottomFrame))
}
}
}
return ret
}
}
extension BinarySpacePartitioningLayout: Equatable {
static func == (lhs: BinarySpacePartitioningLayout<Window>, rhs: BinarySpacePartitioningLayout<Window>) -> Bool {
return lhs.rootNode == rhs.rootNode
}
}
| 86912a532f0381c1456f8d8747571bf6 | 32.32 | 140 | 0.562225 | false | false | false | false |
MiezelKat/AWSense | refs/heads/master | AWSenseConnect/AWSenseConnectWatch/SensingDataBuffer.swift | mit | 1 | //
// SensingDataBuffer.swift
// AWSenseConnect
//
// Created by Katrin Hansel on 05/03/2017.
// Copyright © 2017 Katrin Haensel. All rights reserved.
//
import Foundation
import AWSenseShared
internal class SensingDataBuffer{
private let bufferLimit = 1024
private let bufferLimitHR = 10
// MARK: - properties
var sensingSession : SensingSession
var sensingBuffers : [AWSSensorType : [AWSSensorData]]
var sensingBufferBatchNo : [AWSSensorType : Int]
var sensingBufferEvent : SensingBufferEvent = SensingBufferEvent()
// MARK: - init
init(withSession session : SensingSession){
sensingSession = session
sensingBuffers = [AWSSensorType : [AWSSensorData]]()
sensingBufferBatchNo = [AWSSensorType : Int]()
for s : AWSSensorType in sensingSession.sensorConfig.enabledSensors{
sensingBuffers[s] = [AWSSensorData]()
sensingBufferBatchNo[s] = 1
}
}
// MARK: - methods
func append(sensingData data: AWSSensorData, forType type: AWSSensorType){
let count = sensingBuffers[type]!.count
sensingBuffers[type]!.append(data)
if(type != .heart_rate && count > bufferLimit){
if(type == .device_motion){
print("devide motion")
}
sensingBufferEvent.raiseEvent(withType: .bufferLimitReached, forSensor: type)
}else if (type == .heart_rate && count > bufferLimitHR){
sensingBufferEvent.raiseEvent(withType: .bufferLimitReached, forSensor: type)
}
}
func prepareDataToSend(forType type: AWSSensorType) -> (Int, [AWSSensorData]){
let batchNo = sensingBufferBatchNo[type]!
let data = sensingBuffers[type]!
// reset the buffer
sensingBuffers[type]!.removeAll(keepingCapacity: true)
return (batchNo, data)
}
public func subscribe(handler: SensingBufferEventHandler){
sensingBufferEvent.add(handler: handler)
}
public func unsubscribe(handler: SensingBufferEventHandler){
sensingBufferEvent.remove(handler: handler)
}
}
class SensingBufferEvent{
private var eventHandlers = [SensingBufferEventHandler]()
public func raiseEvent(withType type: SensingBufferEventType, forSensor stype : AWSSensorType) {
for handler in self.eventHandlers {
handler.handle(withType: type, forSensor: stype)
}
}
public func add(handler: SensingBufferEventHandler){
eventHandlers.append(handler)
}
public func remove(handler: SensingBufferEventHandler){
eventHandlers = eventHandlers.filter { $0 !== handler }
}
}
protocol SensingBufferEventHandler : class {
func handle(withType type: SensingBufferEventType, forSensor stype: AWSSensorType)
}
enum SensingBufferEventType{
case bufferLimitReached
}
| c5053f0653119d618d467609124148f3 | 28.277228 | 100 | 0.655394 | false | false | false | false |
kickstarter/ios-oss | refs/heads/main | Library/TestHelpers/MockOptimizelyClient.swift | apache-2.0 | 1 | import Library
import XCTest
internal enum MockOptimizelyError: Error {
case generic
var localizedDescription: String {
return "Optimizely Error"
}
}
internal class MockOptimizelyClient: OptimizelyClientType {
// MARK: - Experiment Activation Test Properties
var activatePathCalled: Bool = false
var allKnownExperiments: [String] = []
var experiments: [String: String] = [:]
var error: MockOptimizelyError?
var features: [String: Bool] = [:]
var getVariantPathCalled: Bool = false
var userAttributes: [String: Any?]?
// MARK: - Event Tracking Test Properties
var trackedAttributes: [String: Any?]?
var trackedEventKey: String?
var trackedUserId: String?
internal func activate(experimentKey: String, userId: String, attributes: [String: Any?]?) throws
-> String {
self.activatePathCalled = true
return try self.experiment(forKey: experimentKey, userId: userId, attributes: attributes)
}
internal func getVariationKey(experimentKey: String, userId: String, attributes: [String: Any?]?) throws
-> String {
self.getVariantPathCalled = true
return try self.experiment(forKey: experimentKey, userId: userId, attributes: attributes)
}
func isFeatureEnabled(featureKey: String, userId _: String, attributes _: [String: Any?]?) -> Bool {
return self.features[featureKey] == true
}
private func experiment(forKey key: String, userId _: String, attributes: [String: Any?]?) throws
-> String {
self.userAttributes = attributes
if let error = self.error {
throw error
}
guard let experimentVariant = self.experiments[key] else {
throw MockOptimizelyError.generic
}
return experimentVariant
}
func track(
eventKey: String,
userId: String,
attributes: [String: Any?]?,
eventTags _: [String: Any]?
) throws {
self.trackedEventKey = eventKey
self.trackedAttributes = attributes
self.trackedUserId = userId
}
func allExperiments() -> [String] {
return self.allKnownExperiments
}
}
| ac8dc3d626203c950e67b80687dec33a | 26.6 | 106 | 0.692754 | false | false | false | false |
jjatie/Charts | refs/heads/master | Source/Charts/Charts/BarChartView.swift | apache-2.0 | 1 | //
// BarChartView.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import CoreGraphics
import Foundation
/// Chart that draws bars.
open class BarChartView: BarLineChartViewBase, BarChartDataProvider {
// MARK: - BarChartDataProvider
open var barData: BarChartData? { return data as? BarChartData }
/// if set to true, all values are drawn above their bars, instead of below their top
public var isDrawValueAboveBarEnabled = true {
didSet { setNeedsDisplay() }
}
/// if set to true, a grey area is drawn behind each bar that indicates the maximum value
public var isDrawBarShadowEnabled = false {
didSet { setNeedsDisplay() }
}
// MARK: Style
/// Adds half of the bar width to each side of the x-axis range in order to allow the bars of the barchart to be fully displayed.
/// **default**: false
public var fitBars = false
/// Set this to `true` to make the highlight operation full-bar oriented, `false` to make it highlight single values (relevant only for stacked).
/// If enabled, highlighting operations will highlight the whole bar, even if only a single stack entry was tapped.
public var isHighlightFullBarEnabled: Bool = false
// MARK: -
override internal func initialize() {
super.initialize()
renderer = BarChartRenderer(dataProvider: self, animator: chartAnimator, viewPortHandler: viewPortHandler)
highlighter = BarHighlighter(chart: self)
xAxis.spaceMin = 0.5
xAxis.spaceMax = 0.5
}
override internal func calcMinMax() {
guard let data = self.data as? BarChartData
else { return }
if fitBars {
xAxis.calculate(
min: data.xRange.min - data.barWidth / 2.0,
max: data.xRange.max + data.barWidth / 2.0
)
} else {
xAxis.calculate(min: data.xRange.min, max: data.xRange.max)
}
// calculate axis range (min / max) according to provided data
leftAxis.calculate(
min: data.getYMin(axis: .left),
max: data.getYMax(axis: .left)
)
rightAxis.calculate(
min: data.getYMin(axis: .right),
max: data.getYMax(axis: .right)
)
}
/// - Returns: The Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the BarChart.
override open func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight? {
if data === nil {
Swift.print("Can't select by touch. No data set.")
return nil
}
guard let h = highlighter?.getHighlight(x: pt.x, y: pt.y)
else { return nil }
if !isHighlightFullBarEnabled { return h }
// For isHighlightFullBarEnabled, remove stackIndex
return Highlight(
x: h.x, y: h.y,
xPx: h.xPx, yPx: h.yPx,
dataIndex: h.dataIndex,
dataSetIndex: h.dataSetIndex,
stackIndex: -1,
axis: h.axis
)
}
/// - Returns: The bounding box of the specified Entry in the specified DataSet. Returns null if the Entry could not be found in the charts data.
open func getBarBounds(entry e: BarChartDataEntry) -> CGRect {
guard let
data = data as? BarChartData,
let set = data.getDataSetForEntry(e) as? BarChartDataSet
else { return .null }
let y = e.y
let x = e.x
let barWidth = data.barWidth
let left = x - barWidth / 2.0
let right = x + barWidth / 2.0
let top = y >= 0.0 ? y : 0.0
let bottom = y <= 0.0 ? y : 0.0
var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top)
getTransformer(forAxis: set.axisDependency).rectValueToPixel(&bounds)
return bounds
}
/// Groups all BarDataSet objects this data object holds together by modifying the x-value of their entries.
/// Previously set x-values of entries will be overwritten. Leaves space between bars and groups as specified by the parameters.
/// Calls `notifyDataSetChanged()` afterwards.
///
/// - Parameters:
/// - fromX: the starting point on the x-axis where the grouping should begin
/// - groupSpace: the space between groups of bars in values (not pixels) e.g. 0.8f for bar width 1f
/// - barSpace: the space between individual bars in values (not pixels) e.g. 0.1f for bar width 1f
open func groupBars(fromX: Double, groupSpace: Double, barSpace: Double) {
guard let barData = self.barData
else {
Swift.print("You need to set data for the chart before grouping bars.", terminator: "\n")
return
}
barData.groupBars(fromX: fromX, groupSpace: groupSpace, barSpace: barSpace)
notifyDataSetChanged()
}
/// Highlights the value at the given x-value in the given DataSet. Provide -1 as the dataSetIndex to undo all highlighting.
///
/// - Parameters:
/// - x:
/// - dataSetIndex:
/// - stackIndex: the index inside the stack - only relevant for stacked entries
open func highlightValue(x: Double, dataSetIndex: Int, stackIndex: Int) {
highlightValue(Highlight(x: x, dataSetIndex: dataSetIndex, stackIndex: stackIndex))
}
}
| b318ce7e1faa1364579d0b94ea97cedd | 34.954248 | 149 | 0.630249 | false | false | false | false |
ZeeQL/ZeeQL3 | refs/heads/develop | Sources/ZeeQL/Access/AccessDataSource.swift | apache-2.0 | 1 | //
// AccessDataSource.swift
// ZeeQL
//
// Created by Helge Hess on 24/02/17.
// Copyright © 2017-2020 ZeeZide GmbH. All rights reserved.
//
/**
* This class has a set of operations targetted at SQL based applications. It
* has three major subclasses with specific characteristics:
*
* - `DatabaseDataSource`
* - `ActiveDataSource`
* - `AdaptorDataSource`
*
* All of those datasources are very similiar in the operations they provide,
* but they differ in the feature set and overhead.
*
* `DatabaseDataSource` works on top of an `EditingContext`. It has the biggest
* overhead but provides features like object uniquing/registry. Eg if you need
* to fetch a bunch of objects and then perform subsequent processing on them
* (for example permission checks), it is convenient because the context
* remembers the fetched objects. This datasource returns DatabaseObject's as
* specified in the associated Model.
*
* `ActiveDataSource` is similiar to `DatabaseDataSource`, but it directly works
* on a channel. It has a reasonably small overhead and still provides a good
* feature set, like object mapping or prefetching.
*
* Finally `AdaptorDataSource`. This datasource does not perform object mapping,
* that is, it returns `AdaptorRecord` objects and works directly on top of an
* `AdaptorChannel`.
*/
open class AccessDataSource<Object: SwiftObject> : DataSource<Object> {
open var log : ZeeQLLogger = globalZeeQLLogger
var _fsname : String?
override open var fetchSpecification : FetchSpecification? {
set {
super.fetchSpecification = newValue
_fsname = nil
}
get {
if let fs = super.fetchSpecification { return fs }
if let name = _fsname, let entity = entity {
return entity[fetchSpecification: name]
}
return nil
}
}
open var fetchSpecificationName : String? {
set {
_fsname = newValue
if let name = _fsname, let entity = entity {
super.fetchSpecification = entity[fetchSpecification: name]
}
else {
super.fetchSpecification = nil
}
}
get { return _fsname }
}
var _entityName : String? = nil
open var entityName : String? {
set { _entityName = newValue }
get {
if let entityName = _entityName { return entityName }
if let entity = entity { return entity.name }
if let fs = fetchSpecification, let ename = fs.entityName { return ename }
return nil
}
}
open var auxiliaryQualifier : Qualifier?
open var isFetchEnabled = true
open var qualifierBindings : Any? = nil
// MARK: - Abstract Base Class
open var entity : Entity? {
fatalError("implement in subclass: \(#function)")
}
open func _primaryFetchObjects(_ fs: FetchSpecification,
yield: ( Object ) throws -> Void) throws
{
fatalError("implement in subclass: \(#function)")
}
open func _primaryFetchCount(_ fs: FetchSpecification) throws -> Int {
fatalError("implement in subclass: \(#function)")
}
open func _primaryFetchGlobalIDs(_ fs: FetchSpecification,
yield: ( GlobalID ) throws -> Void) throws {
fatalError("implement in subclass: \(#function)")
}
override open func fetchObjects(cb yield: ( Object ) -> Void) throws {
try _primaryFetchObjects(try fetchSpecificationForFetch(), yield: yield)
}
override open func fetchCount() throws -> Int {
return try _primaryFetchCount(try fetchSpecificationForFetch())
}
open func fetchGlobalIDs(yield: ( GlobalID ) throws -> Void) throws {
try _primaryFetchGlobalIDs(try fetchSpecificationForFetch(), yield: yield)
}
// MARK: - Bindings
var qualifierBindingKeys : [ String ] {
let q = fetchSpecification?.qualifier
let aux = auxiliaryQualifier
guard q != nil || aux != nil else { return [] }
var keys = Set<String>()
q?.addBindingKeys(to: &keys)
aux?.addBindingKeys(to: &keys)
return Array(keys)
}
// MARK: - Fetch Specification
func fetchSpecificationForFetch() throws -> FetchSpecification {
/* copy fetchspec */
var fs : FetchSpecification
if let ofs = fetchSpecification {
fs = ofs // a copy, it is a struct
}
else if let e = entity {
fs = ModelFetchSpecification(entity: e)
}
else if let entityName = entityName {
fs = ModelFetchSpecification(entityName: entityName)
}
else {
throw AccessDataSourceError
.CannotConstructFetchSpecification(.missingEntity)
}
let qb = qualifierBindings
let aux = auxiliaryQualifier
if qb == nil && aux == nil { return fs }
/* merge in aux qualifier */
if let aux = aux {
let combined = and(aux, fs.qualifier)
fs.qualifier = combined
}
/* apply bindings */
if let qb = qb {
guard let fs = try fs.fetchSpecificiationWith(bindings: qb) else {
throw AccessDataSourceError
.CannotConstructFetchSpecification(.bindingFailed)
}
return fs
}
else { return fs }
}
}
| fc58b09f0ed3c1dd90d169f86d3f92cf | 29.766467 | 80 | 0.655313 | false | false | false | false |
XCEssentials/UniFlow | refs/heads/master | Sources/5_MutationDecriptors/4-DeinitializationOf.swift | mit | 1 | /*
MIT License
Copyright (c) 2016 Maxim Khatskevich ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation /// for access to `Date` type
//---
public
struct DeinitializationOf<F: SomeFeature>: SomeMutationDecriptor
{
public
let oldState: SomeStateBase
public
let timestamp: Date
public
init?(
from report: Storage.HistoryElement
) {
guard
report.feature == F.self,
let deinitialization = Deinitialization(from: report)
else
{
return nil
}
//---
self.oldState = deinitialization.oldState
self.timestamp = report.timestamp
}
}
| 0ca66ae8bfcc46ce22ff03515ce1baac | 28.844828 | 79 | 0.70364 | false | false | false | false |
TLOpenSpring/TLTabBarSpring | refs/heads/master | Example/TLTabBarSpring/CustomController1.swift | mit | 1 | //
// CustomController1.swift
// TLTabBarSpring
//
// Created by Andrew on 16/5/30.
// Copyright © 2016年 CocoaPods. All rights reserved.
//
import UIKit
class CustomController1: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
initView()
}
func initView() -> Void {
let rect = CGRect(x: 100, y: 100, width: 200, height: 40)
let btn = UIButton(frame: rect)
btn.center=self.view.center
btn.setTitle("首页", for: UIControlState())
btn.setTitleColor(UIColor.red, for: UIControlState())
btn.titleLabel?.font=UIFont.boldSystemFont(ofSize: 28)
self.view.addSubview(btn)
}
}
| 0ee80d56a90378d900a7341d4bbcd7ba | 24.1 | 65 | 0.620186 | false | false | false | false |
IamAlchemist/DemoDynamicCollectionView | refs/heads/master | DemoDynamicCollectionView/NewtownianLayoutAttributes.swift | mit | 1 | //
// NewtownianLayoutAttributes.swift
// DemoDynamicCollectionView
//
// Created by Wizard Li on 1/12/16.
// Copyright © 2016 morgenworks. All rights reserved.
//
import UIKit
class NewtownianLayoutAttributes : UICollectionViewLayoutAttributes {
var id : Int = 0
override func copyWithZone(zone: NSZone) -> AnyObject {
let newValue = super.copyWithZone(zone) as! NewtownianLayoutAttributes
newValue.id = id
return newValue
}
override func isEqual(object: AnyObject?) -> Bool {
if super.isEqual(object) {
if let attributeObject = object as? NewtownianLayoutAttributes {
if attributeObject.id == id {
return true
}
}
}
return false
}
}
| 898cb2051c7cf1775af3b846a6f16edd | 24.935484 | 78 | 0.605721 | false | false | false | false |
ctarda/Turnstile | refs/heads/trunk | Sources/TurnstileTests/EventTests.swift | mit | 1 | //
// EventTests.swift
// Turnstile
//
// Created by Cesar Tardaguila on 09/05/15.
//
import XCTest
import Turnstile
class EventTests: XCTestCase {
private struct Constants {
static let eventName = "Event under test"
static let sourceStates = [State(value: "State 1"), State(value: "State 2")]
static let destinationState = State(value: "State3")
static let stringDiff = "💩"
}
var event: Event<String>?
override func setUp() {
super.setUp()
event = Event(name: Constants.eventName, sourceStates: Constants.sourceStates, destinationState: Constants.destinationState)
}
override func tearDown() {
event = nil
super.tearDown()
}
func testEventCanBeConstructed() {
XCTAssertNotNil(event, "Event must not be nil")
}
func testEventNameIsSetProperly() {
XCTAssertNotNil(event?.name, "Event name must not be nil")
}
func testEqualEventsAreEqual() {
let secondEvent = Event(name: Constants.eventName, sourceStates: Constants.sourceStates, destinationState: Constants.destinationState)
XCTAssertTrue( event == secondEvent, "A event must be equal to itself")
}
func testEventsWithDifferentNamesAreDifferent() {
let secondEvent = Event(name: Constants.eventName + Constants.stringDiff, sourceStates: Constants.sourceStates, destinationState: Constants.destinationState)
XCTAssertFalse( event == secondEvent, "Events with different name are different")
}
func testEventsWithDiffrentSourceStatesAndSameNameAreDifferent() {
let secondEvent = Event(name: Constants.eventName, sourceStates: [State(value: "State 3")], destinationState: Constants.destinationState)
XCTAssertFalse( event == secondEvent, "Events with different source states are different")
}
func testEventsWithSameNameAndSourceEventsAndDifferentDestinationEventsAreDifferent() {
let secondEvent = Event(name: Constants.eventName, sourceStates: Constants.sourceStates , destinationState: State(value: "State 3"))
XCTAssertFalse( event == secondEvent, "Events with different destination states are different")
}
func testSourceStatesCanBeSet() {
XCTAssertTrue((event!.sourceStates == Constants.sourceStates), "Source states must be set properly")
}
}
| 2710fb99451f01747b7a60dd1fd82587 | 35.69697 | 165 | 0.687861 | false | true | false | false |
robpearson/BlueRing | refs/heads/master | BlueRing/OctopusClient.swift | apache-2.0 | 1 | //
// OctopusService.swift
// BlueRing
//
// Created by Robert Pearson on 11/2/17.
// Copyright © 2017 Rob Pearson. All rights reserved.
//
import Cocoa
import RxSwift
import Foundation
class OctopusClient: NSObject {
public func getAllProjects() -> Observable<String> {
let session = URLSession.shared
let url = URL(string: "http://192.168.8.107/api/projects/all?apiKey=API-GUEST") // hard coded for now
let observable = Observable<String>.create { observer in
let task = session.dataTask(with: url!) { data, response, err in
if let error = err {
// TODO: Handle errors nicely
print("octopus api error: \(error)")
}
// then check the response code
if let httpResponse = response as? HTTPURLResponse {
switch httpResponse.statusCode {
case 200: // all good!
let dataString = String(data: data!, encoding: String.Encoding.utf8)
observer.onNext(dataString!)
observer.onCompleted()
case 401: // unauthorized
print("octopus api returned an 'unauthorized' response. Did you forget to set your API key?")
default:
print("octopus api returned response: %d %@", httpResponse.statusCode, HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode))
}
}
}
task.resume()
return Disposables.create {
task.cancel()
}
}
return observable
}
}
| 2e28dcf460c38998a1fea7748081af12 | 32.272727 | 167 | 0.508743 | false | false | false | false |
harenbrs/swix | refs/heads/master | swix/swix/swix/matrix/m-matrix.swift | mit | 1 | //
// matrix2d.swift
// swix
//
// Created by Scott Sievert on 7/9/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
import Accelerate
struct matrix {
let n: Int
var rows: Int
var columns: Int
var count: Int
var shape: (Int, Int)
var flat:ndarray
var T:matrix {return transpose(self)}
var I:matrix {return inv(self)}
var pI:matrix {return pinv(self)}
init(columns: Int, rows: Int) {
self.n = rows * columns
self.rows = rows
self.columns = columns
self.shape = (rows, columns)
self.count = n
self.flat = zeros(rows * columns)
}
func copy()->matrix{
var y = zeros_like(self)
y.flat = self.flat.copy()
return y
}
subscript(i: String) -> ndarray {
get {
assert(i == "diag", "Currently the only support x[string] is x[\"diag\"]")
let size = rows < columns ? rows : columns
let i = arange(size)
return self[i*columns.double + i]
}
set {
assert(i == "diag", "Currently the only support x[string] is x[\"diag\"]")
let m = shape.0
let n = shape.1
let min_mn = m < n ? m : n
let j = n.double * arange(min_mn)
self[j + j/n.double] = newValue
}
}
func indexIsValidForRow(r: Int, c: Int) -> Bool {
return r >= 0 && r < rows && c>=0 && c < columns
}
func dot(y: matrix) -> matrix{
return self *! y
}
subscript(i: Int, j: Int) -> Double {
// x[0,0]
get {
var nI = i
var nJ = j
if nI < 0 {nI = rows + i}
if nJ < 0 {nJ = rows + j}
assert(indexIsValidForRow(nI, c:nJ), "Index out of range")
return flat[nI * columns + nJ]
}
set {
var nI = i
var nJ = j
if nI < 0 {nI = rows + i}
if nJ < 0 {nJ = rows + j}
assert(indexIsValidForRow(nI, c:nJ), "Index out of range")
flat[nI * columns + nJ] = newValue
}
}
subscript(i: Range<Int>, k: Int) -> ndarray {
// x[0..<2, 0]
get {
let idx = asarray(i)
return self[idx, k]
}
set {
let idx = asarray(i)
self[idx, k] = newValue
}
}
subscript(r: Range<Int>, c: Range<Int>) -> matrix {
// x[0..<2, 0..<2]
get {
let rr = asarray(r)
let cc = asarray(c)
return self[rr, cc]
}
set {
let rr = asarray(r)
let cc = asarray(c)
self[rr, cc] = newValue
}
}
subscript(i: Int, k: Range<Int>) -> ndarray {
// x[0, 0..<2]
get {
let idx = asarray(k)
return self[i, idx]
}
set {
let idx = asarray(k)
self[i, idx] = newValue
}
}
subscript(or: ndarray, oc: ndarray) -> matrix {
// the main method.
// x[array(1,2), array(3,4)]
get {
var r = or.copy()
var c = oc.copy()
if r.max() < 0.0 {r += 1.0 * rows.double}
if c.max() < 0.0 {c += 1.0 * columns.double}
let (j, i) = meshgrid(r, y: c)
let idx = (j.flat*columns.double + i.flat)
let z = flat[idx]
let zz = reshape(z, shape: (r.n, c.n))
return zz
}
set {
var r = or.copy()
var c = oc.copy()
if r.max() < 0.0 {r += 1.0 * rows.double}
if c.max() < 0.0 {c += 1.0 * columns.double}
if r.n > 0 && c.n > 0{
let (j, i) = meshgrid(r, y: c)
let idx = j.flat*columns.double + i.flat
flat[idx] = newValue.flat
}
}
}
subscript(r: ndarray) -> ndarray {
// flat indexing
get {return self.flat[r]}
set {self.flat[r] = newValue }
}
subscript(i: String, k:Int) -> ndarray {
// x["all", 0]
get {
let idx = arange(shape.0)
let x:ndarray = self.flat[idx * self.columns.double + k.double]
return x
}
set {
let idx = arange(shape.0)
self.flat[idx * self.columns.double + k.double] = newValue
}
}
subscript(i: Int, k: String) -> ndarray {
// x[0, "all"]
get {
assert(k == "all", "Only 'all' supported")
let idx = arange(shape.1)
let x:ndarray = self.flat[i.double * self.columns.double + idx]
return x
}
set {
assert(k == "all", "Only 'all' supported")
let idx = arange(shape.1)
self.flat[i.double * self.columns.double + idx] = newValue
}
}
subscript(i: ndarray, k: Int) -> ndarray {
// x[array(1,2), 0]
get {
let idx = i.copy()
let x:ndarray = self.flat[idx * self.columns.double + k.double]
return x
}
set {
let idx = i.copy()
self.flat[idx * self.columns.double + k.double] = newValue
}
}
subscript(i: matrix) -> ndarray {
// x[x < 5]
get {
return self.flat[i.flat]
}
set {
self.flat[i.flat] = newValue
}
}
subscript(i: Int, k: ndarray) -> ndarray {
// x[0, array(1,2)]
get {
let x:ndarray = self.flat[i.double * self.columns.double + k]
return x
}
set {
self.flat[i.double * self.columns.double + k] = newValue
}
}
}
| c527eb02f09d1866fb23467c87371cc7 | 25.539171 | 86 | 0.442785 | false | false | false | false |
naveengthoppan/NGTRefreshControl | refs/heads/master | NGTProgressView/NGTProgressView.swift | mit | 1 | //
// NGTProgressView.swift
// PullRefresh
//
// Created by Naveen George Thoppan on 28/12/16.
// Copyright © 2016 Appcoda. All rights reserved.
//
import UIKit
@IBDesignable
public class NGTProgressView: UIView {
@IBOutlet weak var view: UIView!
@IBOutlet weak var cityImageView: UIImageView!
@IBOutlet weak var sunImageView: UIImageView!
@IBOutlet weak var signBoardImageView: UIImageView!
@IBOutlet weak var carImageView: UIImageView!
@IBOutlet weak var carLeadingConstraint: NSLayoutConstraint!
@IBOutlet weak var cityLeadingConstriant: NSLayoutConstraint!
var isCompleted: Bool!
override public init(frame: CGRect) {
super.init(frame: frame)
nibSetup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
nibSetup()
}
private func nibSetup() {
backgroundColor = .clear
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.translatesAutoresizingMaskIntoConstraints = true
addSubview(view)
}
private func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let nibView = nib.instantiate(withOwner: self, options: nil).first as! UIView
return nibView
}
public func startAnimation(completion: @escaping (_ isCompleted: Bool)->()) {
isCompleted = false
rotateView(targetView: sunImageView)
animateRefreshStep2() { (isCompleted) -> () in
if isCompleted == true {
completion(isCompleted)
}
}
}
public func animateRefreshStep2(completion: @escaping (_ isCompleted: Bool)->()) {
self.carLeadingConstraint.constant = self.view.bounds.width/2 - 30
self.cityLeadingConstriant.constant -= 15
UIView.animate(withDuration: 4, animations: {
self.view.layoutIfNeeded()
self.startCarShakeAnimation()
}) { finished in
completion(true)
}
}
public func stopAnimation (completion: @escaping (_ isCompleted: Bool)->()) {
if (self.isCompleted == false) {
self.carLeadingConstraint.constant = self.view.bounds.width + 30
self.cityLeadingConstriant.constant -= 15
UIView.animate(withDuration: 2, delay:0.8, animations: {
self.view.layoutIfNeeded()
}) { finished in
self.isCompleted = true
self.stopCarShakeAnimation()
completion(self.isCompleted)
self.carLeadingConstraint.constant = -90
self.cityLeadingConstriant.constant = -37
}
}
}
private func rotateView(targetView: UIView, duration: Double = 2) {
UIView.animate(withDuration: duration, delay: 0.0, options: [.repeat, .curveLinear], animations: {
targetView.transform = targetView.transform.rotated(by: CGFloat(M_PI))
})
}
public func startCarShakeAnimation () {
let carShakeAnimation = CABasicAnimation(keyPath: "transform.rotation")
carShakeAnimation.duration = 0.1
carShakeAnimation.beginTime = CACurrentMediaTime() + 1
carShakeAnimation.autoreverses = true
carShakeAnimation.repeatDuration = 20
carShakeAnimation.fromValue = -0.1;
carShakeAnimation.toValue = 0.1
self.carImageView.layer.add(carShakeAnimation, forKey: "carAnimation")
}
public func stopCarShakeAnimation () {
self.carImageView.layer.removeAnimation(forKey: "carAnimation")
}
}
| 52b536582224a16260f932825418e84c | 33.540541 | 106 | 0.622848 | false | false | false | false |
russbishop/swift | refs/heads/master | test/SILGen/vtable_thunks.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -sdk %S/Inputs -emit-silgen -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module | FileCheck %s
protocol AddrOnly {}
@objc class B {
// We only allow B! -> B overrides for @objc methods.
// The IUO force-unwrap requires a thunk.
@objc func iuo(x: B, y: B!, z: B) -> B? {}
// f* don't require thunks, since the parameters and returns are object
// references.
func f(x: B, y: B) -> B? {}
func f2(x: B, y: B) -> B? {}
func f3(x: B, y: B) -> B {}
func f4(x: B, y: B) -> B {}
// Thunking monomorphic address-only params and returns
func g(x: AddrOnly, y: AddrOnly) -> AddrOnly? {}
func g2(x: AddrOnly, y: AddrOnly) -> AddrOnly? {}
func g3(x: AddrOnly, y: AddrOnly) -> AddrOnly {}
func g4(x: AddrOnly, y: AddrOnly) -> AddrOnly {}
// Thunking polymorphic address-only params and returns
func h<T>(x: T, y: T) -> T? {}
func h2<T>(x: T, y: T) -> T? {}
func h3<T>(x: T, y: T) -> T {}
func h4<T>(x: T, y: T) -> T {}
// Thunking value params and returns
func i(x: Int, y: Int) -> Int? {}
func i2(x: Int, y: Int) -> Int? {}
func i3(x: Int, y: Int) -> Int {}
func i4(x: Int, y: Int) -> Int {}
// Note: i3, i4 are implicitly @objc
}
class D: B {
override func iuo(x: B?, y: B, z: B) -> B {}
override func f(x: B?, y: B) -> B {}
override func f2(x: B, y: B) -> B {}
override func f3(x: B?, y: B) -> B {}
override func f4(x: B, y: B) -> B {}
override func g(x: AddrOnly?, y: AddrOnly) -> AddrOnly {}
override func g2(x: AddrOnly, y: AddrOnly) -> AddrOnly {}
override func g3(x: AddrOnly?, y: AddrOnly) -> AddrOnly {}
override func g4(x: AddrOnly, y: AddrOnly) -> AddrOnly {}
override func h<U>(x: U?, y: U) -> U {}
override func h2<U>(x: U, y: U) -> U {}
override func h3<U>(x: U?, y: U) -> U {}
override func h4<U>(x: U, y: U) -> U {}
override func i(x: Int?, y: Int) -> Int {}
override func i2(x: Int, y: Int) -> Int {}
// Int? cannot be represented in ObjC so the override has to be
// explicitly @nonobjc
@nonobjc override func i3(x: Int?, y: Int) -> Int {}
override func i4(x: Int, y: Int) -> Int {}
}
// Inherits the thunked impls from D
class E: D { }
// Overrides w/ its own thunked impls
class F: D {
override func f(x: B?, y: B) -> B {}
override func f2(x: B, y: B) -> B {}
override func f3(x: B?, y: B) -> B {}
override func f4(x: B, y: B) -> B {}
override func g(x: AddrOnly?, y: AddrOnly) -> AddrOnly {}
override func g2(x: AddrOnly, y: AddrOnly) -> AddrOnly {}
override func g3(x: AddrOnly?, y: AddrOnly) -> AddrOnly {}
override func g4(x: AddrOnly, y: AddrOnly) -> AddrOnly {}
override func h<U>(x: U?, y: U) -> U {}
override func h2<U>(x: U, y: U) -> U {}
override func h3<U>(x: U?, y: U) -> U {}
override func h4<U>(x: U, y: U) -> U {}
override func i(x: Int?, y: Int) -> Int {}
override func i2(x: Int, y: Int) -> Int {}
// Int? cannot be represented in ObjC so the override has to be
// explicitly @nonobjc
@nonobjc override func i3(x: Int?, y: Int) -> Int {}
override func i4(x: Int, y: Int) -> Int {}
}
// CHECK-LABEL: sil private @_TTVFC13vtable_thunks1D3iuo
// CHECK: [[WRAP_X:%.*]] = enum $Optional<B>
// CHECK: [[UNWRAP_Y:%.*]] = unchecked_enum_data
// CHECK: [[RES:%.*]] = apply {{%.*}}([[WRAP_X]], [[UNWRAP_Y]], %2, %3)
// CHECK: [[WRAP_RES:%.*]] = enum $Optional<B>, {{.*}} [[RES]]
// CHECK: return [[WRAP_RES]]
// CHECK-LABEL: sil private @_TTVFC13vtable_thunks1D1g
// TODO: extra copies here
// CHECK: [[WRAPPED_X_ADDR:%.*]] = init_enum_data_addr [[WRAP_X_ADDR:%.*]] :
// CHECK: copy_addr [take] {{%.*}} to [initialization] [[WRAPPED_X_ADDR]]
// CHECK: inject_enum_addr [[WRAP_X_ADDR]]
// CHECK: [[RES_ADDR:%.*]] = alloc_stack
// CHECK: apply {{%.*}}([[RES_ADDR]], [[WRAP_X_ADDR]], %2, %3)
// CHECK: [[DEST_ADDR:%.*]] = init_enum_data_addr %0
// CHECK: copy_addr [take] [[RES_ADDR]] to [initialization] [[DEST_ADDR]]
// CHECK: inject_enum_addr %0
class ThrowVariance {
func mightThrow() throws {}
}
class NoThrowVariance: ThrowVariance {
override func mightThrow() {}
}
// rdar://problem/20657811
class X<T: B> {
func foo(x: T) { }
}
class Y: X<D> {
override func foo(x: D) { }
}
// rdar://problem/21154055
// Ensure reabstraction happens when necessary to get a value in or out of an
// optional.
class Foo {
func foo(x: (Int) -> Int) -> ((Int) -> Int)? {}
}
class Bar: Foo {
override func foo(x: ((Int) -> Int)?) -> (Int) -> Int {}
}
// rdar://problem/21364764
// Ensure we can override an optional with an IUO or vice-versa.
struct S {}
class Aap {
func cat(b: B?) -> B? {}
func dog(b: B!) -> B! {}
func catFast(s: S?) -> S? {}
func dogFast(s: S!) -> S! {}
func flip() -> (() -> S?) {}
func map() -> (S) -> () -> Aap? {}
}
class Noot : Aap {
override func cat(b: B!) -> B! {}
override func dog(b: B?) -> B? {}
override func catFast(s: S!) -> S! {}
override func dogFast(s: S?) -> S? {}
override func flip() -> (() -> S) {}
override func map() -> (S?) -> () -> Noot {}
}
// CHECK-LABEL: sil private @_TTVFC13vtable_thunks3Bar3foo{{.*}} : $@convention(method) (@owned @callee_owned (Int) -> Int, @guaranteed Bar) -> @owned Optional<(Int) -> Int>
// CHECK: function_ref @_TTRXFo_dSi_dSi_XFo_iSi_iSi_
// CHECK: [[IMPL:%.*]] = function_ref @_TFC13vtable_thunks3Bar3foo{{.*}}
// CHECK: apply [[IMPL]]
// CHECK: function_ref @_TTRXFo_dSi_dSi_XFo_iSi_iSi_
// CHECK-LABEL: sil private @_TTVFC13vtable_thunks4Noot4flip{{.*}}
// CHECK: [[IMPL:%.*]] = function_ref @_TFC13vtable_thunks4Noot4flip{{.*}}
// CHECK: [[INNER:%.*]] = apply %1(%0)
// CHECK: [[THUNK:%.*]] = function_ref @_TTRXFo__dV13vtable_thunks1S_XFo__dGSqS0___
// CHECK: [[OUTER:%.*]] = partial_apply [[THUNK]]([[INNER]])
// CHECK: return [[OUTER]]
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__dV13vtable_thunks1S_XFo__dGSqS0___
// CHECK: [[INNER:%.*]] = apply %0()
// CHECK: [[OUTER:%.*]] = enum $Optional<S>, #Optional.some!enumelt.1, %1 : $S
// CHECK: return [[OUTER]] : $Optional<S>
// CHECK-LABEL: sil private @_TTVFC13vtable_thunks4Noot3map{{.*}}
// CHECK: [[IMPL:%.*]] = function_ref @_TFC13vtable_thunks4Noot3map{{.*}}
// CHECK: [[INNER:%.*]] = apply %1(%0)
// CHECK: [[THUNK:%.*]] = function_ref @_TTRXFo_dGSqV13vtable_thunks1S__oXFo__oCS_4Noot__XFo_dS0__oXFo__oGSqCS_3Aap___
// CHECK: [[OUTER:%.*]] = partial_apply [[THUNK]]([[INNER]])
// CHECK: return [[OUTER]]
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dGSqV13vtable_thunks1S__oXFo__oCS_4Noot__XFo_dS0__oXFo__oGSqCS_3Aap___
// CHECK: [[ARG:%.*]] = enum $Optional<S>, #Optional.some!enumelt.1, %0
// CHECK: [[INNER:%.*]] = apply %1(%2)
// CHECK: [[OUTER:%.*]] = convert_function [[INNER]] : $@callee_owned () -> @owned Noot to $@callee_owned () -> @owned Optional<Aap>
// CHECK: return [[OUTER]]
// CHECK-LABEL: sil_vtable D {
// CHECK: #B.iuo!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.f!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.f2!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.f3!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.f4!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.g!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.g2!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.g3!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.g4!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.h!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.h2!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.h3!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.h4!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.i!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.i2!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.i3!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.i4!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK-LABEL: sil_vtable E {
// CHECK: #B.iuo!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.f!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.f2!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.f3!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.f4!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.g!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.g2!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.g3!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.g4!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.h!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.h2!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.h3!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.h4!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.i!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.i2!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.i3!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.i4!1: _TF{{[A-Z0-9a-z_]*}}1D
// CHECK-LABEL: sil_vtable F {
// CHECK: #B.iuo!1: _TTVF{{[A-Z0-9a-z_]*}}1D
// CHECK: #B.f!1: _TF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.f2!1: _TF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.f3!1: _TF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.f4!1: _TF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.g!1: _TTVF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.g2!1: _TTVF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.g3!1: _TTVF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.g4!1: _TF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.h!1: _TTVF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.h2!1: _TTVF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.h3!1: _TTVF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.h4!1: _TF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.i!1: _TTVF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.i2!1: _TTVF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.i3!1: _TTVF{{[A-Z0-9a-z_]*}}1F
// CHECK: #B.i4!1: _TF{{[A-Z0-9a-z_]*}}1F
// CHECK-LABEL: sil_vtable NoThrowVariance {
// CHECK: #ThrowVariance.mightThrow!1: _TF
| 8c1cc494fbd4416eac5d94e76a8203a2 | 37.71875 | 173 | 0.519774 | false | false | false | false |
EasySwift/EasySwift | refs/heads/master | Carthage/Checkouts/IQKeyboardManager/Demo/Swift_Demo/ViewController/NavigationBarViewController.swift | apache-2.0 | 4 | //
// NavigationBarViewController.swift
// IQKeyboard
//
// Created by Iftekhar on 23/09/14.
// Copyright (c) 2014 Iftekhar. All rights reserved.
//
import UIKit
import IQKeyboardManagerSwift
class NavigationBarViewController: UIViewController, UIPopoverPresentationControllerDelegate {
fileprivate var returnKeyHandler : IQKeyboardReturnKeyHandler!
@IBOutlet fileprivate var textField2 : UITextField!
@IBOutlet fileprivate var textField3 : UITextField!
@IBOutlet fileprivate var scrollView : UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
textField3.placeholderText = "This is the customised placeholder title for displaying as toolbar title"
returnKeyHandler = IQKeyboardReturnKeyHandler(controller: self)
returnKeyHandler.lastTextFieldReturnKeyType = UIReturnKeyType.done
}
@IBAction func textFieldClicked(_ sender : UITextField!) {
}
@IBAction func enableScrollAction(_ sender : UISwitch!) {
scrollView.isScrollEnabled = sender.isOn;
}
@IBAction func shouldHideTitle(_ sender : UISwitch!) {
textField2.shouldHidePlaceholderText = !textField2.shouldHidePlaceholderText;
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
if identifier == "SettingsNavigationController" {
let controller = segue.destination
controller.modalPresentationStyle = .popover
controller.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem
let heightWidth = max(UIScreen.main.bounds.width, UIScreen.main.bounds.height);
controller.preferredContentSize = CGSize(width: heightWidth, height: heightWidth)
controller.popoverPresentationController?.delegate = self
}
}
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
func prepareForPopoverPresentation(_ popoverPresentationController: UIPopoverPresentationController) {
self.view.endEditing(true)
}
override var shouldAutorotate : Bool {
return true
}
}
| c36872d6514669f578abe527ee4e5e86 | 32.671429 | 111 | 0.679678 | false | false | false | false |
DarrenKong/firefox-ios | refs/heads/master | SyncTests/HistorySynchronizerTests.swift | mpl-2.0 | 5 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Shared
import Storage
@testable import Sync
import XCGLogger
import Deferred
import XCTest
import SwiftyJSON
private let log = Logger.syncLogger
class MockSyncDelegate: SyncDelegate {
func displaySentTab(for url: URL, title: String, from deviceName: String?) {
}
}
class DBPlace: Place {
var isDeleted = false
var shouldUpload = false
var serverModified: Timestamp?
var localModified: Timestamp?
}
class MockSyncableHistory {
var wasReset: Bool = false
var places = [GUID: DBPlace]()
var remoteVisits = [GUID: Set<Visit>]()
var localVisits = [GUID: Set<Visit>]()
init() {
}
fileprivate func placeForURL(url: String) -> DBPlace? {
return findOneValue(places) { $0.url == url }
}
}
extension MockSyncableHistory: ResettableSyncStorage {
func resetClient() -> Success {
self.wasReset = true
return succeed()
}
}
extension MockSyncableHistory: SyncableHistory {
// TODO: consider comparing the timestamp to local visits, perhaps opting to
// not delete the local place (and instead to give it a new GUID) if the visits
// are newer than the deletion.
// Obviously this'll behave badly during reconciling on other devices:
// they might apply our new record first, renaming their local copy of
// the old record with that URL, and thus bring all the old visits back to life.
// Desktop just finds by GUID then deletes by URL.
func deleteByGUID(_ guid: GUID, deletedAt: Timestamp) -> Deferred<Maybe<()>> {
self.remoteVisits.removeValue(forKey: guid)
self.localVisits.removeValue(forKey: guid)
self.places.removeValue(forKey: guid)
return succeed()
}
func hasSyncedHistory() -> Deferred<Maybe<Bool>> {
let has = self.places.values.contains(where: { $0.serverModified != nil })
return deferMaybe(has)
}
/**
* This assumes that the provided GUID doesn't already map to a different URL!
*/
func ensurePlaceWithURL(_ url: String, hasGUID guid: GUID) -> Success {
// Find by URL.
if let existing = self.placeForURL(url: url) {
let p = DBPlace(guid: guid, url: url, title: existing.title)
p.isDeleted = existing.isDeleted
p.serverModified = existing.serverModified
p.localModified = existing.localModified
self.places.removeValue(forKey: existing.guid)
self.places[guid] = p
}
return succeed()
}
func storeRemoteVisits(_ visits: [Visit], forGUID guid: GUID) -> Success {
// Strip out existing local visits.
// We trust that an identical timestamp and type implies an identical visit.
var remote = Set<Visit>(visits)
if let local = self.localVisits[guid] {
remote.subtract(local)
}
// Visits are only ever added.
if var r = self.remoteVisits[guid] {
r.formUnion(remote)
} else {
self.remoteVisits[guid] = remote
}
return succeed()
}
func insertOrUpdatePlace(_ place: Place, modified: Timestamp) -> Deferred<Maybe<GUID>> {
// See if we've already applied this one.
if let existingModified = self.places[place.guid]?.serverModified {
if existingModified == modified {
log.debug("Already seen unchanged record \(place.guid).")
return deferMaybe(place.guid)
}
}
// Make sure that we collide with any matching URLs -- whether locally
// modified or not. Then overwrite the upstream and merge any local changes.
return self.ensurePlaceWithURL(place.url, hasGUID: place.guid)
>>> {
if let existingLocal = self.places[place.guid] {
if existingLocal.shouldUpload {
log.debug("Record \(existingLocal.guid) modified locally and remotely.")
log.debug("Local modified: \(existingLocal.localModified ??? "nil"); remote: \(modified).")
// Should always be a value if marked as changed.
if let localModified = existingLocal.localModified, localModified > modified {
// Nothing to do: it's marked as changed.
log.debug("Discarding remote non-visit changes!")
self.places[place.guid]?.serverModified = modified
return deferMaybe(place.guid)
} else {
log.debug("Discarding local non-visit changes!")
self.places[place.guid]?.shouldUpload = false
}
} else {
log.debug("Remote record exists, but has no local changes.")
}
} else {
log.debug("Remote record doesn't exist locally.")
}
// Apply the new remote record.
let p = DBPlace(guid: place.guid, url: place.url, title: place.title)
p.localModified = Date.now()
p.serverModified = modified
p.isDeleted = false
self.places[place.guid] = p
return deferMaybe(place.guid)
}
}
func getModifiedHistoryToUpload() -> Deferred<Maybe<[(Place, [Visit])]>> {
// TODO.
return deferMaybe([])
}
func getDeletedHistoryToUpload() -> Deferred<Maybe<[GUID]>> {
// TODO.
return deferMaybe([])
}
func markAsSynchronized(_: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> {
// TODO
return deferMaybe(0)
}
func markAsDeleted(_: [GUID]) -> Success {
// TODO
return succeed()
}
func onRemovedAccount() -> Success {
// TODO
return succeed()
}
func doneApplyingRecordsAfterDownload() -> Success {
return succeed()
}
func doneUpdatingMetadataAfterUpload() -> Success {
return succeed()
}
}
class HistorySynchronizerTests: XCTestCase {
private func applyRecords(records: [Record<HistoryPayload>], toStorage storage: SyncableHistory & ResettableSyncStorage) -> (synchronizer: HistorySynchronizer, prefs: Prefs, scratchpad: Scratchpad) {
let delegate = MockSyncDelegate()
// We can use these useless values because we're directly injecting decrypted
// payloads; no need for real keys etc.
let prefs = MockProfilePrefs()
let scratchpad = Scratchpad(b: KeyBundle.random(), persistingTo: prefs)
let synchronizer = HistorySynchronizer(scratchpad: scratchpad, delegate: delegate, basePrefs: prefs, why: .scheduled)
let expectation = self.expectation(description: "Waiting for application.")
var succeeded = false
synchronizer.applyIncomingToStorage(storage, records: records)
.upon({ result in
succeeded = result.isSuccess
expectation.fulfill()
})
waitForExpectations(timeout: 10, handler: nil)
XCTAssertTrue(succeeded, "Application succeeded.")
return (synchronizer, prefs, scratchpad)
}
func testRecordSerialization() {
let id = "abcdefghi"
let modified: Timestamp = 0 // Ignored in upload serialization.
let sortindex = 1
let ttl = 12345
let json: JSON = JSON([
"id": id,
"visits": [],
"histUri": "http://www.slideshare.net/swadpasc/bpm-edu-netseminarscepwithreactionrulemlprova",
"title": "Semantic Complex Event Processing with \(Character(UnicodeScalar(11)))Reaction RuleML 1.0 and Prova",
])
let payload = HistoryPayload(json)
let record = Record<HistoryPayload>(id: id, payload: payload, modified: modified, sortindex: sortindex, ttl: ttl)
let k = KeyBundle.random()
let s = k.serializer({ (x: HistoryPayload) -> JSON in x.json })
let converter = { (x: JSON) -> HistoryPayload in HistoryPayload(x) }
let f = k.factory(converter)
let serialized = s(record)!
let envelope = EnvelopeJSON(serialized)
// With a badly serialized payload, we get null JSON!
let p = f(envelope.payload)
XCTAssertFalse(p!.json.isNull())
// When we round-trip, the payload should be valid, and we'll get a record here.
let roundtripped = Record<HistoryPayload>.fromEnvelope(envelope, payloadFactory: f)
XCTAssertNotNil(roundtripped)
}
func testApplyRecords() {
let earliest = Date.now()
let empty = MockSyncableHistory()
let noRecords = [Record<HistoryPayload>]()
// Apply no records.
let _ = self.applyRecords(records: noRecords, toStorage: empty)
// Hey look! Nothing changed.
XCTAssertTrue(empty.places.isEmpty)
XCTAssertTrue(empty.remoteVisits.isEmpty)
XCTAssertTrue(empty.localVisits.isEmpty)
// Apply one remote record.
let jA = "{\"id\":\"aaaaaa\",\"histUri\":\"http://foo.com/\",\"title\": \"ñ\",\"visits\":[{\"date\":1222222222222222,\"type\":1}]}"
let pA = HistoryPayload.fromJSON(JSON(parseJSON: jA))!
let rA = Record<HistoryPayload>(id: "aaaaaa", payload: pA, modified: earliest + 10000, sortindex: 123, ttl: 1000000)
let (_, prefs, _) = self.applyRecords(records: [rA], toStorage: empty)
// The record was stored. This is checking our mock implementation, but real storage should work, too!
XCTAssertEqual(1, empty.places.count)
XCTAssertEqual(1, empty.remoteVisits.count)
XCTAssertEqual(1, empty.remoteVisits["aaaaaa"]!.count)
XCTAssertTrue(empty.localVisits.isEmpty)
// Test resetting now that we have a timestamp.
XCTAssertFalse(empty.wasReset)
XCTAssertTrue(HistorySynchronizer.resetSynchronizerWithStorage(empty, basePrefs: prefs, collection: "history").value.isSuccess)
XCTAssertTrue(empty.wasReset)
}
}
| 49473bf5880985569411508cf5911c45 | 37.345725 | 203 | 0.614736 | false | false | false | false |
ingresse/ios-sdk | refs/heads/dev | IngresseSDKTests/Model/UserTests.swift | mit | 1 | //
// Copyright © 2018 Ingresse. All rights reserved.
//
import XCTest
@testable import IngresseSDK
class UserTests: XCTestCase {
func testDecode() {
// Given
var json = [String: Any]()
json["id"] = 1
json["name"] = "name"
json["email"] = "email"
json["type"] = "type"
json["username"] = "username"
json["phone"] = "phone"
json["cellphone"] = "cellphone"
json["pictures"] = [:]
json["social"] = [
[
"network": "facebook",
"id": "facebookId"
], [
"network": "twitter",
"id": "twitterId"
]
]
// When
let obj = JSONDecoder().decodeDict(of: User.self, from: json)
// Then
XCTAssertNotNil(obj)
XCTAssertEqual(obj?.id, 1)
XCTAssertEqual(obj?.name, "name")
XCTAssertEqual(obj?.email, "email")
XCTAssertEqual(obj?.type, "type")
XCTAssertEqual(obj?.username, "username")
XCTAssertEqual(obj?.phone, "phone")
XCTAssertEqual(obj?.cellphone, "cellphone")
XCTAssertEqual(obj?.pictures, [:])
let social = obj!.social
XCTAssertEqual(social[0].network, "facebook")
XCTAssertEqual(social[1].network, "twitter")
XCTAssertEqual(social[0].id, "facebookId")
XCTAssertEqual(social[1].id, "twitterId")
}
func testEmptyInit() {
// When
let obj = User()
// Then
XCTAssertEqual(obj.id, 0)
XCTAssertEqual(obj.name, "")
XCTAssertEqual(obj.email, "")
XCTAssertEqual(obj.type, "")
XCTAssertEqual(obj.username, "")
XCTAssertEqual(obj.phone, "")
XCTAssertEqual(obj.cellphone, "")
XCTAssertEqual(obj.pictures, [:])
XCTAssertEqual(obj.social, [])
}
}
| b0de5ca9065483165ee5bf8d9ae5a7ce | 27.014925 | 69 | 0.52797 | false | true | false | false |
soffes/valio | refs/heads/master | Valio/ItemTableViewCell.swift | mit | 1 | //
// ItemTableViewCell.swift
// Valio
//
// Created by Sam Soffes on 6/6/14.
// Copyright (c) 2014 Sam Soffes. All rights reserved.
//
import UIKit
import QuartzCore
class ItemTableViewCell: UITableViewCell {
// MARK: - Properties
lazy var titleLabel: UILabel = {
let label = UILabel()
label.setTranslatesAutoresizingMaskIntoConstraints(false)
label.font = UIFont(name: "Avenir", size: 12)
return label
}()
lazy var timeLabel: UILabel = {
let label = UILabel()
label.setTranslatesAutoresizingMaskIntoConstraints(false)
label.font = UIFont(name: "Avenir-Light", size: 12)
label.textColor = UIColor(red: 0.631, green: 0.651, blue: 0.678, alpha: 1)
label.textAlignment = .Right
return label
}()
lazy var lineView: UIView = {
let view = UIView()
view.setTranslatesAutoresizingMaskIntoConstraints(false)
view.backgroundColor = UIColor(red: 0.906, green: 0.914, blue: 0.918, alpha: 1)
return view
}()
lazy var circleView: UIView = {
let view = UIView()
view.setTranslatesAutoresizingMaskIntoConstraints(false)
view.backgroundColor = UIColor.whiteColor()
view.layer.borderWidth = 1
view.layer.cornerRadius = 7
return view
}()
var minor: Bool = false {
didSet {
titleLabel.textColor = minor ? timeLabel.textColor : UIColor(red: 0.227, green: 0.227, blue: 0.278, alpha: 1)
circleView.layer.borderColor = minor ? UIColor(red: 0.839, green: 0.847, blue: 0.851, alpha: 1).CGColor : UIColor(red: 0.329, green: 0.831, blue: 0.690, alpha: 1).CGColor
}
}
// MARK: - Initializers
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .None
contentView.addSubview(titleLabel)
contentView.addSubview(timeLabel)
contentView.addSubview(lineView)
contentView.addSubview(circleView)
let views = [
"timeLabel": timeLabel,
"titleLabel": titleLabel,
"lineView": lineView,
"circleView": circleView
]
let metrics = [
"margin": 12,
"leftMargin": 16,
"lineMargin": 14
]
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-(leftMargin)-[timeLabel(80)]-(lineMargin)-[lineView(2)]-(lineMargin)-[titleLabel]-|", options: nil, metrics: metrics, views: views))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(margin)-[titleLabel]-(margin)-|", options: nil, metrics: metrics, views: views))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[lineView]|", options: nil, metrics: metrics, views: views))
contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: timeLabel, attribute: .CenterY, multiplier: 1, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: circleView, attribute: .CenterX, relatedBy: .Equal, toItem: lineView, attribute: .CenterX, multiplier: 1, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: circleView, attribute: .CenterY, relatedBy: .Equal, toItem: titleLabel, attribute: .CenterY, multiplier: 1, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: circleView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 14))
contentView.addConstraint(NSLayoutConstraint(item: circleView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 14))
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| 55772923c1876197e8d0deba4045b840 | 36.723404 | 211 | 0.732939 | false | false | false | false |
Pluto-Y/SwiftyEcharts | refs/heads/master | DemoOptions/GaugeOptions.swift | mit | 1 | //
// GaugeOptions.swift
// SwiftyEcharts
//
// Created by Pluto-Y on 16/01/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
import SwiftyEcharts
public final class GaugeOptions {
// MARK: Gauge Car Dark
/// 地址: http://echarts.baidu.com/demo.html#gauge-car-dark
static func gaugeCarDarkOption() -> Option {
// TODO: 添加实现
return Option(
)
}
// MARK: Gauge Car
/// 地址: http://echarts.baidu.com/demo.html#gauge-car
static func gaugeCarOption() -> Option {
let serieData1: [Jsonable] = [["value": 40, "name": "km/h"]]
let serieData2: [Jsonable] = [["value": 1.5, "name": "x1000 r/min"]]
let serieData3: [Jsonable] = [["value": 0.5, "name": "gas"]]
let serieData4: [Jsonable] = [["value": 0.5, "name": "gas"]]
let serie1: GaugeSerie = GaugeSerie(
.name("速度"), // 缺少z
.min(0),
.max(220),
.splitNumber(11),
.radius(50%),
.axisLine(AxisLine(
.lineStyle(LineStyle(
.width(10)
))
)),
.axisTick(AxisTick(
.length(15),
.lineStyle(LineStyle(
.color(Color.auto)
))
)),
.splitLine(SplitLine(
.length(20),
.lineStyle(LineStyle(
.color(Color.auto)
))
)),
.title(GaugeSerie.Title(
.textStyle(TextStyle(
.fontWeight(.bolder),
.fontSize(20),
.fontStyle(.italic)
))
)),
.detail(GaugeSerie.Detail(
.textStyle(TextStyle(
.fontWeight(.bolder)
))
)),
.data(serieData1)
)
let serie2: GaugeSerie = GaugeSerie(
.name("转速"),
.center([20%, 55%]),
.radius(35%),
.min(0),
.max(7),
.endAngle(45),
.splitNumber(7),
.axisLine(AxisLine(
.lineStyle(LineStyle(
.width(8)
))
)),
.axisTick(AxisTick(
.length(12),
.lineStyle(LineStyle(
.color(Color.auto)
))
)),
.splitLine(SplitLine(
.length(20),
.lineStyle(LineStyle(
.color(Color.auto)
))
)),
.pointer(GaugeSerie.Pointer(
.width(5)
)),
.title(GaugeSerie.Title(
.offsetCenter([0, (-30)%])
)),
.detail(GaugeSerie.Detail(
.textStyle(TextStyle(
.fontWeight(.bolder)
))
)),
.data(serieData2)
)
let serie3: GaugeSerie = GaugeSerie(
.name("油表"),
.center([77%, 50%]),
.radius(25%),
.min(0),
.max(2),
.startAngle(135),
.endAngle(45),
.splitNumber(2),
.axisLine(AxisLine(
.lineStyle(LineStyle(
.width(8)
))
)),
.axisTick(AxisTick(
.splitNumber(5),
.length(10),
.lineStyle(LineStyle(
.color(Color.auto)
))
)),
.axisLabel(AxisLabel(
.formatter(.function("function axisLabelFormattter(v){ switch (v + '') { case '0' : return 'E'; case '1' : return 'Gas'; case '2' : return 'F'; }}"))
)),
.splitLine(SplitLine(
.length(15),
.lineStyle(LineStyle(
.color(Color.auto)
))
)),
.pointer(GaugeSerie.Pointer(
.width(2)
)),
.title(GaugeSerie.Title(
.show(false)
)),
.detail(GaugeSerie.Detail(
.show(false)
)),
.data(serieData3)
)
let serie4 = GaugeSerie(
.name("水表"),
.center([77%, 50%]),
.radius(25%),
.min(0),
.max(2),
.startAngle(315),
.endAngle(225),
.splitNumber(2),
.axisLine(AxisLine(
.lineStyle(LineStyle(
.width(8)
))
)),
.axisLabel(AxisLabel(
.formatter(.function("function axisLabelFomatter2(v){ switch (v + '') { case '0' : return 'H'; case '1' : return 'Water'; case '2' : return 'C'; } }"))
)),
.splitLine(SplitLine(
.length(15),
.lineStyle(LineStyle(
.color(Color.auto)
))
)),
.pointer(GaugeSerie.Pointer(
.width(2)
)),
.title(GaugeSerie.Title(
.show(false)
)),
.detail(GaugeSerie.Detail(
.show(false)
)),
.data(serieData4)
)
let series: [Serie] = [
serie1,
serie2,
serie3,
serie4
]
return Option(
.tooltip(Tooltip(
.formatter(.string("{a}<br/>{c} {b}"))
)),
.toolbox(Toolbox(
.show(true),
.feature(ToolboxFeature(
.restore(ToolboxFeatureRestore(.show(true))),
.saveAsImage(ToolboxFeatureSaveAsImage(.show(true)))
))
)),
.series(series)
)
}
// MARK: Gauge
/// 地址: http://echarts.baidu.com/demo.html#gauge
static func gaugeOption() -> Option {
return Option(
.tooltip(Tooltip(
.formatter(.string("{a} <br/>{b} : {c}%"))
)),
.toolbox(Toolbox(
.feature(ToolboxFeature(
.restore(ToolboxFeatureRestore()),
.saveAsImage(ToolboxFeatureSaveAsImage())
))
)),
.series([
GaugeSerie(
.name("业务指标"),
.detail(GaugeSerieDetail(
.formatter(.string("{value}%"))
)),
.data([["name":"完成率", "value": 50]]) // FIXIM: 封装Data类型?
)
])
)
}
}
| 6fddb285aac919e22697722dd3e166c3 | 29.75 | 167 | 0.381098 | false | false | false | false |
iamyuiwong/swift-common | refs/heads/master | demos/AlertDEMO/AlertDEMO/AppDelegate.swift | lgpl-3.0 | 1 | //
// AppDelegate.swift
// AlertDEMO
//
// Created by 黄锐 on 15/10/16.
// Copyright © 2015年 yuiwong. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "yuiwong.AlertDEMO" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("AlertDEMO", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| bd8024696c391ad9f65fb1f36ccfd931 | 51.324324 | 288 | 0.752755 | false | false | false | false |
huangboju/QMUI.swift | refs/heads/master | QMUI.swift/Demo/Modules/Demos/UIKit/QDTextFieldViewController.swift | mit | 1 | //
// QDTextFieldViewController.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/4/17.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
import UIKit
class QDTextFieldViewController: QDCommonViewController {
private lazy var textField: QMUITextField = {
let textField = QMUITextField()
textField.delegate = self
textField.maximumTextLength = 10
textField.placeholder = "请输入文字"
textField.font = UIFontMake(16)
textField.layer.cornerRadius = 2
textField.layer.borderColor = UIColorSeparator.cgColor
textField.layer.borderWidth = PixelOne
textField.textInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
textField.clearButtonMode = .always
return textField
}()
private lazy var tipsLabel: UILabel = {
let label = UILabel()
let attributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: UIFontMake(12), NSAttributedString.Key.foregroundColor: UIColorGray6, NSAttributedString.Key.paragraphStyle: NSMutableParagraphStyle(lineHeight: 16)]
label.attributedText = NSAttributedString(string: "支持自定义 placeholder 颜色,支持调整输入框与文字之间的间距,支持限制最大可输入的文字长度(可试试输入 emoji、从中文输入法候选词输入等)。", attributes: attributes)
label.numberOfLines = 0
return label
}()
override func didInitialized() {
super.didInitialized()
automaticallyAdjustsScrollViewInsets = false
}
override func initSubviews() {
super.initSubviews()
view.addSubview(textField)
view.addSubview(tipsLabel)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let padding = UIEdgeInsets(top: qmui_navigationBarMaxYInViewCoordinator + 16, left: 16, bottom: 16, right: 16)
let contentWidth = view.bounds.width - padding.horizontalValue
textField.frame = CGRect(x: padding.left, y: padding.top, width: contentWidth, height: 40)
let tipsLabelHeight = tipsLabel.sizeThatFits(CGSize(width: contentWidth, height: CGFloat.greatestFiniteMagnitude)).height
tipsLabel.frame = CGRectFlat(padding.left, textField.frame.maxY + 8, contentWidth, tipsLabelHeight)
}
}
extension QDTextFieldViewController: QMUITextFieldDelegate {
func textField(_ textField: QMUITextField, didPreventTextChangeInRange range: NSRange, replacementString: String?) {
QMUITips.showSucceed(text: "文字不能超过 \(textField.maximumTextLength)个字符", in: view, hideAfterDelay: 2)
}
}
| 433abc76341d861ad20bfc77e39de687 | 38.71875 | 235 | 0.700236 | false | false | false | false |
RameshRM/Background-Fetch | refs/heads/master | Background-Fetch/Background-Fetch/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// Background-Fetch
//
// Created by Mahadevan, Ramesh on 10/29/14.
// Copyright (c) 2014 GoliaMania. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var helloLabel: UILabel!
var messageId: NSString!;
let _MESSAGE_FROM = "background.poll";
let _MESSAGE_POSTBOX = "pobox"
let _MESSAGE_PROCESSING_API = "http://citypageapp.com/messages.retrieve?to=";
override func viewDidLoad() {
super.viewDidLoad()
self.send();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func onMessageReceived(messageArgs: NSString){
println(messageArgs);
self.helloLabel.text = messageArgs;
processMessage(messageArgs);
}
func processMessage(messageArgs: NSString){
var encodedMessageArgs = messageArgs.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) as NSString!;
var url = "\(self._MESSAGE_PROCESSING_API)\(self.messageId)";
var request = NSURLRequest(URL: NSURL(string: url)!);
NSURLConnection.sendAsynchronousRequest(request,queue: NSOperationQueue.mainQueue()) {
(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
self.send();
var receivedMessage = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as NSDictionary;
self.helloLabel.text = receivedMessage["body"] as NSString!;
}
}
func getNow() -> NSTimeInterval{
return NSDate().timeIntervalSince1970 * 1000;
}
func sendMessage(from: NSString, to: NSString, body: NSString) -> Void{
var url = "http://citypageapp.com/messages.send?from=\(from)&to=\(to)&body=\(body)";
var request = NSURLRequest(URL: NSURL(string: url)!);
NSURLConnection.sendAsynchronousRequest(request,queue: NSOperationQueue.mainQueue()) {
(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
}
}
func getAndSetMessageId() -> NSString{
return "\(_MESSAGE_POSTBOX).\(self.getNow())";
}
func messageBody() -> NSString{
var message = "Hello, Current Time in Milli Seconds is : \(getNow())";
return message.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) as NSString!;
}
func send() -> Void{
self.messageId = self.getAndSetMessageId();
self.sendMessage(_MESSAGE_FROM, to: self.messageId, body: self.messageBody())
}
}
| ca44af5330c436fb4e25d9f8667806b3 | 32.4375 | 122 | 0.643738 | false | false | false | false |
theabovo/Extend | refs/heads/master | Tests/HelpersTests/ThrottlerTests.swift | apache-2.0 | 1 | //
// Copyright (c) 2016-present, Menly ApS
// All rights reserved.
//
// This source code is licensed under the Apache License 2.0 found in the
// LICENSE file in the root directory of this source tree.
//
@testable import Extend
import XCTest
class ThrottlerTests: XCTestCase {
// MARK: - Tests
func testStringThrottler() {
let interval: TimeInterval = 0.1
let firstText = "Hello World!"
let finalText = "Hello you world self"
let expectation = XCTestExpectation(description: "Throttling")
let stringThrottler = Throttler<String>(interval: interval) { text in
XCTAssertEqual(text, finalText)
expectation.fulfill()
}
stringThrottler.handle(firstText)
stringThrottler.handle(finalText)
wait(for: [expectation], timeout: 1)
}
}
| 9938eeaee46c276f2d8b1d2f2e94e812 | 23.548387 | 73 | 0.729304 | false | true | false | false |
sora0077/QiitaKit | refs/heads/master | QiitaKit/src/Endpoint/ExpandedTemplate/CreateExpandedTemplate.swift | mit | 1 | //
// CreateExpandedTemplate.swift
// QiitaKit
//
// Created on 2015/06/08.
// Copyright (c) 2015年 林達也. All rights reserved.
//
import Foundation
import APIKit
/**
* 受け取ったテンプレート用文字列の変数を展開して返します。
*/
public struct CreateExpandedTemplate {
/// テンプレートの本文
/// example: Weekly MTG on %{Year}/%{month}/%{day}
///
public let body: String
/// タグ一覧
/// example: [{"name"=>"MTG/%{Year}/%{month}/%{day}", "versions"=>["0.0.1"]}]
///
public let tags: Array<Tagging>
/// 生成される投稿のタイトルの雛形
/// example: Weekly MTG on %{Year}/%{month}/%{day}
///
public let title: String
public init(body: String, tags: Array<Tagging>, title: String) {
self.body = body
self.tags = tags
self.title = title
}
}
extension CreateExpandedTemplate: QiitaRequestToken {
public typealias Response = ExpandedTemplate
public typealias SerializedObject = [String: AnyObject]
public var method: HTTPMethod {
return .POST
}
public var path: String {
return "/api/v2/expanded_templates"
}
public var parameters: [String: AnyObject]? {
return [
"body": body,
"tags": tags.map({ ["name": $0.name, "versions": $0.versions] }),
"title": title
]
}
public var encoding: RequestEncoding {
return .JSON
}
}
public extension CreateExpandedTemplate {
func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response {
return _ExpandedTemplate(object)
}
}
| 5768751a422b8439840742dcd06587d3 | 21.8 | 119 | 0.601504 | false | false | false | false |
EZ-NET/CodePiece | refs/heads/Rev2 | ESTwitter/Character.swift | gpl-3.0 | 1 | //
// Character.swift
// ESTwitter
//
// Created by Tomohiro Kumagai on 2020/02/02.
// Copyright © 2020 Tomohiro Kumagai. All rights reserved.
//
import Foundation
extension String {
public var twitterCharacterView: [TwitterCharacter] {
return map(TwitterCharacter.init)
}
}
public struct TwitterCharacter {
private(set) var units: [UTF16Character]
public init(_ character: Character) {
units = character.utf16.map(UTF16Character.init)
}
}
extension TwitterCharacter {
public var rawString: String {
return units
.map { $0.rawValue }
.withUnsafeBufferPointer { buffer in
guard let address = buffer.baseAddress else {
return ""
}
return String(utf16CodeUnits: address, count: buffer.count)
}
}
public var utf8: String.UTF8View {
return rawString.utf8
}
public var unitCount: Int {
return units.count
}
public func contains(_ element: UTF16Character) -> Bool {
return units.contains(element)
}
public var wordCountForPost: Double {
if isEnglish {
return 0.5
}
else if contains(.tpvs) {
return 2
}
else {
return 1
}
}
public var wordCountForIndices: Int {
return utf8.map(UTF8Character.init).utf8LeadingByteCount
}
public var isEnglish: Bool {
guard units.count == 1 else {
return false
}
switch units.first!.rawValue {
case 0x0000 ... 0x10FF,
0x2000 ... 0x200D,
0x2010 ... 0x201F,
0x2032 ... 0x2037:
return true
default:
return false
}
}
public var isSurrogatePair: Bool {
guard units.count == 2 else {
return false
}
return units[0].isSurrogateHight && units[1].isSurrogateLow
}
}
extension Sequence where Element == TwitterCharacter {
public var wordCountForPost: Double {
return reduce(0) { $0 + $1.wordCountForPost }
}
}
| 398d79cd4591e526c39d6ef8a0ead2f5 | 14.521008 | 62 | 0.659989 | false | false | false | false |
loudnate/LoopKit | refs/heads/master | LoopKit/GlucoseKit/StoredGlucoseSample.swift | mit | 1 | //
// StoredGlucoseSample.swift
// LoopKit
//
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import HealthKit
public struct StoredGlucoseSample: GlucoseSampleValue {
public let sampleUUID: UUID
// MARK: - HealthKit Sync Support
public let syncIdentifier: String
public let syncVersion: Int
// MARK: - SampleValue
public let startDate: Date
public let quantity: HKQuantity
// MARK: - GlucoseSampleValue
public let isDisplayOnly: Bool
public let provenanceIdentifier: String
init(sample: HKQuantitySample) {
self.init(
sampleUUID: sample.uuid,
syncIdentifier: sample.metadata?[HKMetadataKeySyncIdentifier] as? String,
syncVersion: sample.metadata?[HKMetadataKeySyncVersion] as? Int ?? 1,
startDate: sample.startDate,
quantity: sample.quantity,
isDisplayOnly: sample.isDisplayOnly,
provenanceIdentifier: sample.provenanceIdentifier
)
}
public init(
sampleUUID: UUID,
syncIdentifier: String?,
syncVersion: Int,
startDate: Date,
quantity: HKQuantity,
isDisplayOnly: Bool,
provenanceIdentifier: String
) {
self.sampleUUID = sampleUUID
self.syncIdentifier = syncIdentifier ?? sampleUUID.uuidString
self.syncVersion = syncVersion
self.startDate = startDate
self.quantity = quantity
self.isDisplayOnly = isDisplayOnly
self.provenanceIdentifier = provenanceIdentifier
}
}
extension StoredGlucoseSample: Equatable, Hashable, Comparable {
public static func <(lhs: StoredGlucoseSample, rhs: StoredGlucoseSample) -> Bool {
return lhs.startDate < rhs.startDate
}
public static func ==(lhs: StoredGlucoseSample, rhs: StoredGlucoseSample) -> Bool {
return lhs.sampleUUID == rhs.sampleUUID
}
public func hash(into hasher: inout Hasher) {
hasher.combine(sampleUUID)
}
}
extension StoredGlucoseSample {
init(managedObject: CachedGlucoseObject) {
self.init(
sampleUUID: managedObject.uuid!,
syncIdentifier: managedObject.syncIdentifier,
syncVersion: Int(managedObject.syncVersion),
startDate: managedObject.startDate,
quantity: HKQuantity(unit: HKUnit(from: managedObject.unitString!), doubleValue: managedObject.value),
isDisplayOnly: managedObject.isDisplayOnly,
provenanceIdentifier: managedObject.provenanceIdentifier!
)
}
}
| e663e3185d89438064055eecc73b74b8 | 28.215909 | 114 | 0.668611 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.