repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
chihaodong/RMCollectionViewLayout | RMCollectionViewLayout/RMCollectionViewCell.swift | 1 | 1182 | //
// RMCollectionViewCell.swift
// RMCollectionViewLayout
//
// Created by 迟浩东 on 2017/4/6.
// Copyright © 2017年 迟浩东. All rights reserved.
//
import UIKit
import YYWebImage
class RMCollectionViewCell: UICollectionViewCell {
var model :RMData? {
didSet {
let url = URL(string:(model?.gif?.images.preview_gif?.url)!)! as URL
imageView.yy_setImage(with: url, options: .progressive)
}
}
let imageView :UIImageView = YYAnimatedImageView()
override init(frame:CGRect) {
super.init(frame: frame)
self.imageView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
imageView.backgroundColor = UIColor.gray
self.addSubview(self.imageView)
}
required init?(coder aDecoder:NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//重新布局,否则二次刷新时由于单元格重用导致错位
override func layoutSubviews() {
super.layoutSubviews()
self.imageView.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
}
}
| gpl-3.0 | e9ac883de512cdba33bb9e78a3ea9a73 | 26.341463 | 111 | 0.636039 | 3.812925 | false | false | false | false |
gribozavr/swift | test/IRGen/objc_class_export.swift | 1 | 6030 | // RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend -sdk %S/Inputs -I %t -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
// CHECK-DAG: %swift.refcounted = type
// CHECK-DAG: [[HOOZIT:%T17objc_class_export6HoozitC]] = type <{ [[REF:%swift.refcounted]] }>
// CHECK-DAG: [[FOO:%T17objc_class_export3FooC]] = type <{ [[REF]], %TSi }>
// CHECK-DAG: [[INT:%TSi]] = type <{ i64 }>
// CHECK-DAG: [[DOUBLE:%TSd]] = type <{ double }>
// CHECK-DAG: [[NSRECT:%TSo6NSRectV]] = type <{ %TSo7NSPointV, %TSo6NSSizeV }>
// CHECK-DAG: [[NSPOINT:%TSo7NSPointV]] = type <{ %TSd, %TSd }>
// CHECK-DAG: [[NSSIZE:%TSo6NSSizeV]] = type <{ %TSd, %TSd }>
// CHECK: @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" = hidden global %objc_class {
// CHECK-SAME: %objc_class* @"OBJC_METACLASS_$_{{(_TtCs12_)?}}SwiftObject",
// CHECK-SAME: %objc_class* @"OBJC_METACLASS_$_{{(_TtCs12_)?}}SwiftObject",
// CHECK-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-SAME: %swift.opaque* null,
// CHECK-SAME: i64 ptrtoint ({{.*}}* @_METACLASS_DATA__TtC17objc_class_export3Foo to i64)
// CHECK-SAME: }
// CHECK: [[FOO_NAME:@.*]] = private unnamed_addr constant [28 x i8] c"_TtC17objc_class_export3Foo\00"
// CHECK: @_METACLASS_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } {
// CHECK-SAME: i32 129,
// CHECK-SAME: i32 40,
// CHECK-SAME: i32 40,
// CHECK-SAME: i32 0,
// CHECK-SAME: i8* null,
// CHECK-SAME: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0),
// CHECK-SAME: @_CLASS_METHODS__TtC17objc_class_export3Foo,
// CHECK-SAME: i8* null,
// CHECK-SAME: i8* null,
// CHECK-SAME: i8* null,
// CHECK-SAME: i8* null
// CHECK-SAME: }, section "__DATA, __objc_const", align 8
// CHECK: @_DATA__TtC17objc_class_export3Foo = private constant {{.*\*}} } {
// CHECK-SAME: i32 128,
// CHECK-SAME: i32 16,
// CHECK-SAME: i32 24,
// CHECK-SAME: i32 0,
// CHECK-SAME: i8* null,
// CHECK-SAME: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0),
// CHECK-SAME: { i32, i32, [6 x { i8*, i8*, i8* }] }* @_INSTANCE_METHODS__TtC17objc_class_export3Foo,
// CHECK-SAME: i8* null,
// CHECK-SAME: @_IVARS__TtC17objc_class_export3Foo,
// CHECK-SAME: i8* null,
// CHECK-SAME: _PROPERTIES__TtC17objc_class_export3Foo
// CHECK-SAME: }, section "__DATA, __objc_const", align 8
// CHECK: @"$s17objc_class_export3FooCMf" = internal global <{{.*}} }> <{
// CHECK-SAME: void ([[FOO]]*)* @"$s17objc_class_export3FooCfD",
// CHECK-SAME: i8** @"$sBOWV",
// CHECK-SAME: i64 ptrtoint (%objc_class* @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" to i64),
// CHECK-SAME: %objc_class* @"OBJC_CLASS_$_{{(_TtCs12_)?}}SwiftObject",
// CHECK-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-SAME: %swift.opaque* null,
// CHECK-SAME: i64 add (i64 ptrtoint ({{.*}}* @_DATA__TtC17objc_class_export3Foo to i64), i64 {{1|2}}),
// CHECK-SAME: [[FOO]]* (%swift.type*)* @"$s17objc_class_export3FooC6createACyFZ",
// CHECK-SAME: void (double, double, double, double, [[FOO]]*)* @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tF"
// CHECK-SAME: }>, section "__DATA,__objc_data, regular"
// -- TODO: The OBJC_CLASS symbol should reflect the qualified runtime name of
// Foo.
// CHECK: @"$s17objc_class_export3FooCN" = hidden alias %swift.type, bitcast (i64* getelementptr inbounds ({{.*}} @"$s17objc_class_export3FooCMf", i32 0, i32 2) to %swift.type*)
// CHECK: @"OBJC_CLASS_$__TtC17objc_class_export3Foo" = hidden alias %swift.type, %swift.type* @"$s17objc_class_export3FooCN"
import gizmo
class Hoozit {}
struct BigStructWithNativeObjects {
var x, y, w : Double
var h : Hoozit
}
@objc class Foo {
@objc var x = 0
@objc class func create() -> Foo {
return Foo()
}
@objc func drawInRect(dirty dirty: NSRect) {
}
// CHECK: define internal void @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tFTo"([[OPAQUE:%.*]]*, i8*, [[NSRECT]]* byval align 8) {{[#0-9]*}} {
// CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE]]* %0 to [[FOO]]*
// CHECK: call swiftcc void @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tF"(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]])
// CHECK: }
@objc func bounds() -> NSRect {
return NSRect(origin: NSPoint(x: 0, y: 0),
size: NSSize(width: 0, height: 0))
}
// CHECK: define internal void @"$s17objc_class_export3FooC6boundsSo6NSRectVyFTo"([[NSRECT]]* noalias nocapture sret, [[OPAQUE4:%.*]]*, i8*) {{[#0-9]*}} {
// CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE4]]* %1 to [[FOO]]*
// CHECK: call swiftcc { double, double, double, double } @"$s17objc_class_export3FooC6boundsSo6NSRectVyF"([[FOO]]* swiftself [[CAST]])
@objc func convertRectToBacking(r r: NSRect) -> NSRect {
return r
}
// CHECK: define internal void @"$s17objc_class_export3FooC20convertRectToBacking1rSo6NSRectVAG_tFTo"([[NSRECT]]* noalias nocapture sret, [[OPAQUE5:%.*]]*, i8*, [[NSRECT]]* byval align 8) {{[#0-9]*}} {
// CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE5]]* %1 to [[FOO]]*
// CHECK: call swiftcc { double, double, double, double } @"$s17objc_class_export3FooC20convertRectToBacking1rSo6NSRectVAG_tF"(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]])
func doStuffToSwiftSlice(f f: [Int]) {
}
// This function is not representable in Objective-C, so don't emit the objc entry point.
// CHECK-NOT: @"$s17objc_class_export3FooC19doStuffToSwiftSlice1fySaySiG_tcAAFTo"
func doStuffToBigSwiftStruct(f f: BigStructWithNativeObjects) {
}
// This function is not representable in Objective-C, so don't emit the objc entry point.
// CHECK-NOT: @_TToFC17objc_class_export3Foo23doStuffToBigSwiftStruct1ffS_FTV17objc_class_export27BigStructWithNativeObjects_T_
@objc init() { }
}
| apache-2.0 | 70e70cd7940cbfeffc1505323f5879fc | 50.982759 | 219 | 0.639469 | 3.076531 | false | false | false | false |
RoverPlatform/rover-ios-beta | Sources/Models/Color.swift | 2 | 1320 | //
// Color.swift
// Rover
//
// Created by Sean Rucker on 2017-10-19.
// Copyright © 2017 Rover Labs Inc. All rights reserved.
//
import UIKit
public struct Color: Decodable {
public var red: Int
public var green: Int
public var blue: Int
public var alpha: Double
public init(red: Int, green: Int, blue: Int, alpha: Double) {
self.red = red
self.green = green
self.blue = blue
self.alpha = alpha
}
}
// MARK: Convenience Initializers
extension Color {
var uiColor: UIColor {
let red = CGFloat(self.red) / 255.0
let green = CGFloat(self.green) / 255.0
let blue = CGFloat(self.blue) / 255.0
let alpha = CGFloat(self.alpha)
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
func uiColor(dimmedBy: Double) -> UIColor {
let red = CGFloat(self.red) / 255.0
let green = CGFloat(self.green) / 255.0
let blue = CGFloat(self.blue) / 255.0
let alpha = CGFloat(self.alpha) * CGFloat(dimmedBy)
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
static var white: Color { return Color(red: 255, green: 255, blue: 255, alpha: 1) }
static var transparent: Color { return Color(red: 0, green: 0, blue: 0, alpha: 0) }
}
| mit | db55c14336e93c18a2fc4b829a90af12 | 27.673913 | 87 | 0.60652 | 3.555256 | false | false | false | false |
storix/bulls-eye | BullsEye/ViewController.swift | 1 | 3816 | //
// ViewController.swift
// BullsEye
//
// Created by admin on 11/20/15.
// Copyright © 2015 admin. All rights reserved.
//
import QuartzCore
import UIKit
class ViewController: UIViewController {
var currentValue = 0
var targetValue = 0
var score = 0
var round = 0
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var targetLable: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var roundLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
startNewGame()
updateLablels()
// Do any additional setup after loading the view, typically from a nib.
let thumbImageNormal = UIImage(named: "SliderThumb-Normal")
slider.setThumbImage(thumbImageNormal, forState: .Normal)
let thumbImageHighlighted = UIImage(named: "SliderThumb-Highlighted")
slider.setThumbImage(thumbImageHighlighted, forState: .Highlighted)
let insets = UIEdgeInsets(top: 0, left: 14, bottom: 0, right: 14)
if let trackLeftImage = UIImage(named: "SliderTrackLeft") {
let trackLeftResizable = trackLeftImage.resizableImageWithCapInsets(insets)
slider.setMinimumTrackImage(trackLeftResizable, forState: .Normal)
}
if let trackRightImage = UIImage(named: "SliderTrackRight"){
let trackRightResizable = trackRightImage.resizableImageWithCapInsets(insets)
slider.setMaximumTrackImage(trackRightResizable, forState: .Normal)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func startNewRound() {
++round
currentValue = 50
targetValue = 1 + Int(arc4random_uniform(100))
slider.value = Float(currentValue)
}
func updateLablels() {
targetLable.text = String(targetValue)
scoreLabel.text = String(score)
roundLabel.text = String(round)
}
func startNewGame() {
score = 0
round = 0
startNewRound()
}
@IBAction func startOver() {
startNewGame()
updateLablels()
let transition = CATransition()
transition.type = kCATransitionFade
transition.duration = 1
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
view.layer.addAnimation(transition, forKey: nil)
}
@IBAction func showAlert() {
let difference = abs(currentValue - targetValue)
var points = 100 - difference
score += points
let title: String
switch difference {
case 0:
title = "Perfect!"
points += 100
case 1..<5:
title = "You almost did it!"
case 5..<10:
title = "Pretty good!"
default:
title = "Not even close!"
}
let message = "The value of the slider is \(currentValue)" +
"\nThe target value is \(targetValue)" +
"\nThe difference is \(difference)" +
"\nYour score is \(points)"
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default, handler: {
action in
self.startNewRound()
self.updateLablels()
})
alert.addAction(action)
presentViewController(alert, animated: true, completion: nil)
}
@IBAction func sliderMoved(slider: UISlider) {
currentValue = lroundf(slider.value)
}
}
| gpl-2.0 | 808597204056eccf5f5c5d9d28238a59 | 27.684211 | 94 | 0.592398 | 5.093458 | false | false | false | false |
WholePunk/photodrop | Photo Drop/ViewController.swift | 1 | 7818 | //
// ViewController.swift
// Photo Drop
//
// Created by Bob Warwick on 2015-05-05.
// Copyright (c) 2015 Whole Punk Creators. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIAlertViewDelegate {
// MARK: - Setup
let locationManager = CLLocationManager()
let imagePicker = UIImagePickerController()
var firebase: Firebase?
var geofire: GeoFire?
var regionQuery: GFRegionQuery?
var foundQuery: GFCircleQuery?
var annotations: Dictionary<String, Pin> = Dictionary(minimumCapacity: 8)
var lastExchangeKeyFound: String?
var lastExchangeLocationFound: CLLocation?
var inExchange = false
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var foundImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.sourceType = .PhotoLibrary
imagePicker.delegate = self
firebase = Firebase(url: "https://sizzling-inferno-971.firebaseio.com/")
geofire = GeoFire(firebaseRef: firebase!.childByAppendingPath("geo"))
let gestureRecongnizer = UITapGestureRecognizer(target: self, action: Selector("hideImageView:"))
foundImage.addGestureRecognizer(gestureRecongnizer)
}
// MARK: - Map Tracking
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
locationManager.requestWhenInUseAuthorization()
self.mapView.userLocation.addObserver(self, forKeyPath: "location", options: NSKeyValueObservingOptions(), context: nil)
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if (self.mapView.showsUserLocation && self.mapView.userLocation.location != nil) {
let span = MKCoordinateSpanMake(0.0125, 0.0125)
let region = MKCoordinateRegion(center: self.mapView.userLocation.location.coordinate, span: span)
self.mapView.setRegion(region, animated: true)
if regionQuery == nil {
regionQuery = geofire?.queryWithRegion(region)
regionQuery!.observeEventType(GFEventTypeKeyEntered, withBlock: { (key: String!, location: CLLocation!) in
let annotation = Pin(key: key)
annotation.coordinate = location.coordinate
self.mapView.addAnnotation(annotation)
self.annotations[key] = annotation
})
regionQuery!.observeEventType(GFEventTypeKeyExited, withBlock: { (key: String!, location: CLLocation!) -> Void in
self.mapView.removeAnnotation(self.annotations[key])
self.annotations[key] = nil
})
}
// We also want a query with an extremely limited span. When a photo enters that region, we want to notify the user they can exchange.
if foundQuery == nil {
foundQuery = geofire?.queryAtLocation(self.mapView.userLocation.location, withRadius: 0.05)
foundQuery!.observeEventType(GFEventTypeKeyEntered, withBlock: { (key: String!, location: CLLocation!) -> Void in
self.lastExchangeKeyFound = key
self.lastExchangeLocationFound = location
let foundAPhoto = UIAlertView(title: "You Found a Drop!", message: "You can view the photo by tapping exchange and providing a new photo.", delegate: self, cancelButtonTitle: "Not Here", otherButtonTitles: "Exchange")
foundAPhoto.show()
})
} else {
foundQuery?.center = self.mapView.userLocation.location
}
}
}
// MARK: - Drop a Photo
@IBAction func dropPhoto(sender: AnyObject) {
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
self.dismissViewControllerAnimated(true, completion: nil)
// Save the photo to Firebase
let thumbnail = image.resizedImageWithContentMode(UIViewContentMode.ScaleAspectFit, bounds: CGSizeMake(400, 400), interpolationQuality:kCGInterpolationHigh)
let imgData = UIImagePNGRepresentation(thumbnail)
let base64EncodedImage = imgData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros)
if inExchange {
// Download the existing photo and show it
firebase?.childByAppendingPath(lastExchangeKeyFound).observeEventType(.Value, withBlock: { (snapshot) -> Void in
self.firebase?.childByAppendingPath(self.lastExchangeKeyFound).removeAllObservers()
let existingImageInBase64 = snapshot.value as! String
let existingImageData = NSData(base64EncodedString: existingImageInBase64, options: NSDataBase64DecodingOptions.allZeros)
let image = UIImage(data: existingImageData!)
self.foundImage.image = image
self.foundImage.hidden = false
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.foundImage.alpha = 1.0
var layer = self.foundImage.layer
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowRadius = 10.0
layer.shadowOffset = CGSizeMake(10.0, 5.0)
layer.shadowOpacity = 0.8
})
// Overwrite the existing photo
let existingReference = self.firebase?.childByAppendingPath(self.lastExchangeKeyFound)
existingReference?.setValue(base64EncodedImage)
// Go back to the non-exchange flow
self.inExchange = false
})
} else {
let uniqueReference = firebase?.childByAutoId()
uniqueReference!.setValue(base64EncodedImage)
let key = uniqueReference?.key
let location = mapView.userLocation.location
geofire!.setLocation(mapView.userLocation.location, forKey: key)
}
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
self.dismissViewControllerAnimated(true, completion: nil)
inExchange = false
}
func hideImageView(sender: AnyObject?) {
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.foundImage.alpha = 0.0
var layer = self.foundImage.layer
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowRadius = 0.0
layer.shadowOffset = CGSizeMake(0.0, 0.0)
layer.shadowOpacity = 0.0
}) { (bool) -> Void in
self.foundImage.image = nil
self.foundImage.hidden = true
}
}
// MARK: - Exchange Dialog Delegate
func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) {
if buttonIndex == 1 {
inExchange = true
self.dropPhoto(self)
}
}
}
| mit | 3ec230051acf03071a0bdff65389e543 | 38.484848 | 237 | 0.603095 | 5.774003 | false | false | false | false |
UncleJoke/JKPinTu-Swift | JKPinTu-Swift/Util/AppConstants.swift | 1 | 813 | //
// AppConstants.swift
// PingTu-swift
//
// Created by bingjie-macbookpro on 15/12/8.
// Copyright © 2015年 Bingjie. All rights reserved.
//
import Foundation
import UIKit
import SwiftyBeaver
let jk_log = SwiftyBeaver.self
let SCREEN_BOUNDS = UIScreen.mainScreen().bounds
let SCREEN_WIDTH = UIScreen.mainScreen().bounds.width
let SCREEN_HEIGHT = UIScreen.mainScreen().bounds.height
let STATUSBARHEIGHT = CGFloat(20)
let TOPBARHEIGHT = CGFloat(44)
let BOTTOMHEIGHT = CGFloat(49)
/*!
生成随机数 x , start <= x < end
- parameter start: start
- parameter end: end
- returns: arc4random
*/
func arc4randomInRange(start:Int ,to end:Int)->Int{
let count = UInt32(end - start)
return Int(arc4random_uniform(count)) + start
}
public func JKLog(items: Any...){
print(items)
} | mit | 9aca41e7715b255eedd22dd04c4d1957 | 18.536585 | 55 | 0.70875 | 3.265306 | false | false | false | false |
robertofrontado/OkDataSources | Library/RxSwift/OkRxTableViewDelegate.swift | 2 | 3862 | //
// OkRxTableViewDelegate.swift
// OkDataSources
//
// Created by Roberto Frontado on 4/22/16.
// Copyright © 2016 Roberto Frontado. All rights reserved.
//
import UIKit
import RxSwift
public class OkRxTableViewDelegate<T: OkViewDataSource>: OkRxViewDelegate<T>, UITableViewDelegate {
private var tableView: UITableView!
public override init(dataSource: T, onItemClicked: @escaping (_ item: T.ItemType, _ position: Int) -> Void) {
super.init(dataSource: dataSource, onItemClicked: onItemClicked)
}
// MARK: - Public methods
// MARK: Pull to refresh
public func setOnPullToRefresh(_ tableView: UITableView, onRefreshed: @escaping () -> Observable<[T.ItemType]>) {
setOnPullToRefresh(tableView, onRefreshed: onRefreshed, refreshControl: nil)
}
public func setOnPullToRefresh(_ tableView: UITableView, onRefreshed: @escaping () -> Observable<[T.ItemType]>, refreshControl: UIRefreshControl?) {
var refreshControl = refreshControl
self.tableView = tableView
configureRefreshControl(&refreshControl, onRefreshed: onRefreshed)
tableView.addSubview(refreshControl!)
}
override func refreshControlValueChanged(_ refreshControl: UIRefreshControl) {
super.refreshControlValueChanged(refreshControl)
onRefreshed?()
.observeOn(MainScheduler.instance)
.subscribe(onNext: { items in
self.dataSource.items.removeAll()
self.dataSource.items.append(contentsOf: items)
self.tableView.reloadData()
})
}
// MARK: UITableViewDelegate
public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// Ask for nextPage every time the user is getting close to the trigger treshold
if dataSource.reverseItemsOrder {
if reverseTriggerTreshold == indexPath.row
&& tableView.visibleCells.count > reverseTriggerTreshold {
let reverseIndex = dataSource.items.count - indexPath.row - 1
let item = dataSource.itemAtIndexPath(IndexPath(item: reverseIndex, section: 0))
onPagination?(item)
.observeOn(MainScheduler.instance)
.subscribe(onNext: { items in
if items.isEmpty { return }
self.dataSource.items.append(contentsOf: items)
let beforeHeight = tableView.contentSize.height
let beforeOffsetY = tableView.contentOffset.y
tableView.reloadData()
tableView.contentOffset = CGPoint(x: 0, y: (tableView.contentSize.height - beforeHeight + beforeOffsetY))
})
}
} else {
if (dataSource.items.count - triggerTreshold) == indexPath.row
&& indexPath.row > triggerTreshold {
onPagination?(dataSource.items[indexPath.row])
.observeOn(MainScheduler.instance)
.subscribe(onNext: { items in
if items.isEmpty { return }
self.dataSource.items.append(contentsOf: items)
tableView.reloadData()
})
}
}
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var item = dataSource.itemAtIndexPath(indexPath as IndexPath)
if dataSource.reverseItemsOrder {
let inverseIndex = dataSource.items.count - indexPath.row - 1
item = dataSource.itemAtIndexPath(IndexPath(item: inverseIndex, section: 0))
onItemClicked(item, inverseIndex)
} else {
onItemClicked(item, indexPath.row)
}
}
}
| apache-2.0 | 4a112e8185be2c855f350786b5a8c2eb | 42.875 | 152 | 0.619788 | 5.392458 | false | false | false | false |
DerryZhao/SwiftExtension | SwiftExtension/String+Extension.swift | 1 | 1045 | //
// String+HtmlToString.swift
// SwiftExtension
//
// Created by zhaoheqiang on 16/6/4.
// Copyright © 2016年 zhaoheqiang. All rights reserved.
//
import UIKit
extension String {
//MARK: html to format string
public func htmlFormatString() -> String{
let str = self.dataUsingEncoding(NSUTF8StringEncoding)
let attributedStr = try? NSAttributedString(data: str!, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)
return (attributedStr?.string.stringByReplacingOccurrencesOfString("%", withString: " "))!
}
public func toDate() -> String {
let index = self.startIndex.advancedBy(10)
let str = self.substringToIndex(index)
let timeSta:NSTimeInterval = Double(str)!
let dfmatter = NSDateFormatter()
dfmatter.dateFormat="yyyy-MM-dd hh:mm"
let date = NSDate(timeIntervalSince1970: timeSta)
return dfmatter.stringFromDate(date)
}
}
| mit | 779833c0a0c2e4be8584193c68dae031 | 34.931034 | 213 | 0.703455 | 4.510823 | false | false | false | false |
webim/webim-client-sdk-ios | Example/WebimClientLibrary/GeneralViews/SpinningIndicator.swift | 1 | 4827 | //
// SpinningIndicator.swift
// WebimClientLibrary_Example
//
// Created by Eugene Ilyin on 14.10.2019.
// Copyright © 2019 Webim. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import UIKit
class SpinningIndicator: UIView {
// MARK: - Properties
var animating: Bool = true {
didSet {
updateAnimation()
}
}
var lineWidth: CGFloat = 2 {
didSet {
circleLayer.lineWidth = lineWidth
setNeedsLayout()
}
}
var strokeColor: CGColor = UIColor.red.cgColor {
didSet {
circleLayer.strokeColor = strokeColor
setNeedsLayout()
}
}
// MARK: - Private properties
private let circleLayer = CAShapeLayer()
private let strokeEndAnimation: CAAnimation = {
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = 0
animation.toValue = 1
animation.duration = 2
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
let group = CAAnimationGroup()
group.duration = 2.5
group.repeatCount = .infinity
group.animations = [animation]
return group
}()
private let strokeStartAnimation: CAAnimation = {
let animation = CABasicAnimation(keyPath: "strokeStart")
animation.beginTime = 0.5
animation.fromValue = 0
animation.toValue = 1
animation.duration = 2
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
let group = CAAnimationGroup()
group.duration = 2.5
group.repeatCount = .infinity
group.animations = [animation]
return group
}()
private let rotationAnimation: CAAnimation = {
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
animation.fromValue = 0
animation.toValue = Double.pi * 2
animation.duration = 4
animation.repeatCount = .infinity
return animation
}()
// MARK: - Methods
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
override func layoutSubviews() {
super.layoutSubviews()
let center = CGPoint(x: bounds.midX, y: bounds.midY)
let radius = min(bounds.width, bounds.height) / 2 - circleLayer.lineWidth / 2
let startAngle = CGFloat(-Double.pi / 2) // -90°
let endAngle = startAngle + CGFloat(Double.pi * 2)
let path = UIBezierPath(
arcCenter: CGPoint.zero,
radius: radius,
startAngle: startAngle,
endAngle: endAngle,
clockwise: true
)
circleLayer.position = center
circleLayer.path = path.cgPath
}
// MARK: - Private methods
private func setup() {
circleLayer.lineWidth = lineWidth
circleLayer.fillColor = nil
circleLayer.strokeColor = strokeColor
layer.addSublayer(circleLayer)
updateAnimation()
}
private func updateAnimation() {
if animating {
circleLayer.isHidden = false
circleLayer.add(strokeEndAnimation, forKey: "strokeEnd")
circleLayer.add(strokeStartAnimation, forKey: "strokeStart")
circleLayer.add(rotationAnimation, forKey: "rotation")
} else {
circleLayer.isHidden = true
circleLayer.removeAnimation(forKey: "strokeEnd")
circleLayer.removeAnimation(forKey: "strokeStart")
circleLayer.removeAnimation(forKey: "rotation")
}
}
}
| mit | 7c83c70a145af120882a1b819f81b9b2 | 32.275862 | 85 | 0.632953 | 5.062959 | false | false | false | false |
zhuyunfeng1224/XiheMtxx | XiheMtxx/VC/Photo/PhotoAlbumTableViewCell.swift | 1 | 5321 | //
// PhotoAlbumTableViewCell.swift
// EasyCard
//
// Created by echo on 2017/2/21.
// Copyright © 2017年 羲和. All rights reserved.
//
import UIKit
import Photos
class PhotoAlbumTableViewCell: UITableViewCell {
lazy var mImageView: UIImageView = {
let _imageView = UIImageView()
_imageView.contentMode = .scaleAspectFill
_imageView.clipsToBounds = true
_imageView.translatesAutoresizingMaskIntoConstraints = false
return _imageView
}()
lazy var titleLabel: UILabel = {
let _titleLabel = UILabel()
_titleLabel.translatesAutoresizingMaskIntoConstraints = false
_titleLabel.textColor = UIColor.gray
return _titleLabel
}()
lazy var detailLabel: UILabel = {
let _detailLabel = UILabel()
_detailLabel.translatesAutoresizingMaskIntoConstraints = false
_detailLabel.textColor = UIColor.lightGray
return _detailLabel
}()
lazy var arrowView: UIImageView = {
let _arrowView = UIImageView()
_arrowView.contentMode = .center
_arrowView.clipsToBounds = true
_arrowView.translatesAutoresizingMaskIntoConstraints = false
_arrowView.image = UIImage(named: "icon_settings_arrowNext_7x13_")
return _arrowView
}()
var asset: PHAsset? {
willSet(newValue) {
let option = PHImageRequestOptions()
option.resizeMode = .fast
option.isNetworkAccessAllowed = true
PHCachingImageManager.default().requestImage(for: newValue!, targetSize: CGSize(width: 180, height: 180), contentMode: .aspectFill, options: option, resultHandler: { (image, info) in
self.mImageView.image = image
})
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
self.backgroundColor = UIColor.clear
self.contentView.addSubview(self.mImageView)
self.contentView.addSubview(self.titleLabel)
self.contentView.addSubview(self.detailLabel)
self.contentView.addSubview(self.arrowView)
self.setNeedsUpdateConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateConstraints() {
super.updateConstraints()
let imageHContraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[imageView]", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["imageView": self.mImageView])
let imageVContraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-10-[imageView]-10-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["imageView": self.mImageView])
let imageWidthEHeightConstraint = NSLayoutConstraint(item: self.mImageView, attribute: .width, relatedBy: .equal, toItem: self.mImageView, attribute: .height, multiplier: 1, constant: 0)
self.contentView.addConstraints(imageHContraints)
self.contentView.addConstraints(imageVContraints)
self.contentView.addConstraint(imageWidthEHeightConstraint)
let titleLabelHContraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-10-[titleLabel]-15-[arrowView]", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["titleLabel": self.titleLabel, "imageView": self.mImageView, "arrowView": self.arrowView])
let titleLabelVContraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-15-[titleLabel(==20)]", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["titleLabel": self.titleLabel])
self.contentView.addConstraints(titleLabelHContraints)
self.contentView.addConstraints(titleLabelVContraints)
let detailLabelHContraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-10-[detailLabel]-15-[arrowView]", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["detailLabel": self.detailLabel, "imageView": self.mImageView, "arrowView": self.arrowView])
let detailLabelVContraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[titleLabel]-10-[detailLabel(==20)]", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["titleLabel": self.titleLabel, "detailLabel": self.detailLabel])
self.contentView.addConstraints(detailLabelHContraints)
self.contentView.addConstraints(detailLabelVContraints)
let arrowViewHContraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[arrowView(==20)]-10-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["arrowView": self.arrowView])
let arrowViewVContraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[arrowView]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["arrowView": self.arrowView])
self.contentView.addConstraints(arrowViewHContraints)
self.contentView.addConstraints(arrowViewVContraints)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| mit | 0aa365f8bcc34424de1343bc152a4024 | 50.592233 | 293 | 0.706436 | 5.094919 | false | false | false | false |
lenglengiOS/BuDeJie | 百思不得姐/Pods/Charts/Charts/Classes/Utils/ChartTransformer.swift | 19 | 10215 | //
// ChartTransformer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 6/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
/// Transformer class that contains all matrices and is responsible for transforming values into pixels on the screen and backwards.
public class ChartTransformer: NSObject
{
/// matrix to map the values to the screen pixels
internal var _matrixValueToPx = CGAffineTransformIdentity
/// matrix for handling the different offsets of the chart
internal var _matrixOffset = CGAffineTransformIdentity
internal var _viewPortHandler: ChartViewPortHandler
public init(viewPortHandler: ChartViewPortHandler)
{
_viewPortHandler = viewPortHandler
}
/// Prepares the matrix that transforms values to pixels. Calculates the scale factors from the charts size and offsets.
public func prepareMatrixValuePx(chartXMin chartXMin: Double, deltaX: CGFloat, deltaY: CGFloat, chartYMin: Double)
{
let scaleX = (_viewPortHandler.contentWidth / deltaX)
let scaleY = (_viewPortHandler.contentHeight / deltaY)
// setup all matrices
_matrixValueToPx = CGAffineTransformIdentity
_matrixValueToPx = CGAffineTransformScale(_matrixValueToPx, scaleX, -scaleY)
_matrixValueToPx = CGAffineTransformTranslate(_matrixValueToPx, CGFloat(-chartXMin), CGFloat(-chartYMin))
}
/// Prepares the matrix that contains all offsets.
public func prepareMatrixOffset(inverted: Bool)
{
if (!inverted)
{
_matrixOffset = CGAffineTransformMakeTranslation(_viewPortHandler.offsetLeft, _viewPortHandler.chartHeight - _viewPortHandler.offsetBottom)
}
else
{
_matrixOffset = CGAffineTransformMakeScale(1.0, -1.0)
_matrixOffset = CGAffineTransformTranslate(_matrixOffset, _viewPortHandler.offsetLeft, -_viewPortHandler.offsetTop)
}
}
/// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the SCATTERCHART.
public func generateTransformedValuesScatter(entries: [ChartDataEntry], phaseY: CGFloat) -> [CGPoint]
{
var valuePoints = [CGPoint]()
valuePoints.reserveCapacity(entries.count)
for (var j = 0; j < entries.count; j++)
{
let e = entries[j]
valuePoints.append(CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value) * phaseY))
}
pointValuesToPixel(&valuePoints)
return valuePoints
}
/// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the BUBBLECHART.
public func generateTransformedValuesBubble(entries: [ChartDataEntry], phaseX: CGFloat, phaseY: CGFloat, from: Int, to: Int) -> [CGPoint]
{
let count = to - from
var valuePoints = [CGPoint]()
valuePoints.reserveCapacity(count)
for (var j = 0; j < count; j++)
{
let e = entries[j + from]
valuePoints.append(CGPoint(x: CGFloat(e.xIndex - from) * phaseX + CGFloat(from), y: CGFloat(e.value) * phaseY))
}
pointValuesToPixel(&valuePoints)
return valuePoints
}
/// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the LINECHART.
public func generateTransformedValuesLine(entries: [ChartDataEntry], phaseX: CGFloat, phaseY: CGFloat, from: Int, to: Int) -> [CGPoint]
{
let count = Int(ceil(CGFloat(to - from) * phaseX))
var valuePoints = [CGPoint]()
valuePoints.reserveCapacity(count)
for (var j = 0; j < count; j++)
{
let e = entries[j + from]
valuePoints.append(CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value) * phaseY))
}
pointValuesToPixel(&valuePoints)
return valuePoints
}
/// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the CANDLESTICKCHART.
public func generateTransformedValuesCandle(entries: [CandleChartDataEntry], phaseY: CGFloat) -> [CGPoint]
{
var valuePoints = [CGPoint]()
valuePoints.reserveCapacity(entries.count)
for (var j = 0; j < entries.count; j++)
{
let e = entries[j]
valuePoints.append(CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.high) * phaseY))
}
pointValuesToPixel(&valuePoints)
return valuePoints
}
/// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the BARCHART.
public func generateTransformedValuesBarChart(entries: [BarChartDataEntry], dataSet: Int, barData: BarChartData, phaseY: CGFloat) -> [CGPoint]
{
var valuePoints = [CGPoint]()
valuePoints.reserveCapacity(entries.count)
let setCount = barData.dataSetCount
let space = barData.groupSpace
for (var j = 0; j < entries.count; j++)
{
let e = entries[j]
// calculate the x-position, depending on datasetcount
let x = CGFloat(e.xIndex + (e.xIndex * (setCount - 1)) + dataSet) + space * CGFloat(e.xIndex) + space / 2.0
let y = e.value
valuePoints.append(CGPoint(x: x, y: CGFloat(y) * phaseY))
}
pointValuesToPixel(&valuePoints)
return valuePoints
}
/// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the BARCHART.
public func generateTransformedValuesHorizontalBarChart(entries: [ChartDataEntry], dataSet: Int, barData: BarChartData, phaseY: CGFloat) -> [CGPoint]
{
var valuePoints = [CGPoint]()
valuePoints.reserveCapacity(entries.count)
let setCount = barData.dataSetCount
let space = barData.groupSpace
for (var j = 0; j < entries.count; j++)
{
let e = entries[j]
let i = e.xIndex
// calculate the x-position, depending on datasetcount
let x = CGFloat(i + (i * (setCount - 1)) + dataSet) + space * CGFloat(i) + space / 2.0
let y = e.value
valuePoints.append(CGPoint(x: CGFloat(y) * phaseY, y: x))
}
pointValuesToPixel(&valuePoints)
return valuePoints
}
/// Transform an array of points with all matrices.
// VERY IMPORTANT: Keep matrix order "value-touch-offset" when transforming.
public func pointValuesToPixel(inout pts: [CGPoint])
{
let trans = valueToPixelMatrix
for (var i = 0, count = pts.count; i < count; i++)
{
pts[i] = CGPointApplyAffineTransform(pts[i], trans)
}
}
public func pointValueToPixel(inout point: CGPoint)
{
point = CGPointApplyAffineTransform(point, valueToPixelMatrix)
}
/// Transform a rectangle with all matrices.
public func rectValueToPixel(inout r: CGRect)
{
r = CGRectApplyAffineTransform(r, valueToPixelMatrix)
}
/// Transform a rectangle with all matrices with potential animation phases.
public func rectValueToPixel(inout r: CGRect, phaseY: CGFloat)
{
// multiply the height of the rect with the phase
var bottom = r.origin.y + r.size.height
bottom *= phaseY
let top = r.origin.y * phaseY
r.size.height = bottom - top
r.origin.y = top
r = CGRectApplyAffineTransform(r, valueToPixelMatrix)
}
/// Transform a rectangle with all matrices.
public func rectValueToPixelHorizontal(inout r: CGRect)
{
r = CGRectApplyAffineTransform(r, valueToPixelMatrix)
}
/// Transform a rectangle with all matrices with potential animation phases.
public func rectValueToPixelHorizontal(inout r: CGRect, phaseY: CGFloat)
{
// multiply the height of the rect with the phase
var right = r.origin.x + r.size.width
right *= phaseY
let left = r.origin.x * phaseY
r.size.width = right - left
r.origin.x = left
r = CGRectApplyAffineTransform(r, valueToPixelMatrix)
}
/// transforms multiple rects with all matrices
public func rectValuesToPixel(inout rects: [CGRect])
{
let trans = valueToPixelMatrix
for (var i = 0; i < rects.count; i++)
{
rects[i] = CGRectApplyAffineTransform(rects[i], trans)
}
}
/// Transforms the given array of touch points (pixels) into values on the chart.
public func pixelsToValue(inout pixels: [CGPoint])
{
let trans = pixelToValueMatrix
for (var i = 0; i < pixels.count; i++)
{
pixels[i] = CGPointApplyAffineTransform(pixels[i], trans)
}
}
/// Transforms the given touch point (pixels) into a value on the chart.
public func pixelToValue(inout pixel: CGPoint)
{
pixel = CGPointApplyAffineTransform(pixel, pixelToValueMatrix)
}
/// - returns: the x and y values in the chart at the given touch point
/// (encapsulated in a PointD). This method transforms pixel coordinates to
/// coordinates / values in the chart.
public func getValueByTouchPoint(point: CGPoint) -> CGPoint
{
return CGPointApplyAffineTransform(point, pixelToValueMatrix)
}
public var valueToPixelMatrix: CGAffineTransform
{
return
CGAffineTransformConcat(
CGAffineTransformConcat(
_matrixValueToPx,
_viewPortHandler.touchMatrix
),
_matrixOffset
)
}
public var pixelToValueMatrix: CGAffineTransform
{
return CGAffineTransformInvert(valueToPixelMatrix)
}
} | apache-2.0 | f0ec590f534f14dd92ebeb6c7d64442a | 34.472222 | 153 | 0.636711 | 5.054429 | false | false | false | false |
vuchau/iRemind | iRemind/ReminderInfoTableVC.swift | 2 | 2034 | //
// ReminderInfoTableVC.swift
// iRemind
//
// Created by Vijay Subrahmanian on 03/06/15.
// Copyright (c) 2015 Vijay Subrahmanian. All rights reserved.
//
import UIKit
class ReminderInfoTableVC: UITableViewController, UITableViewDataSource, UITableViewDelegate {
let reminderList = (UIApplication.sharedApplication().delegate as! AppDelegate).reminderList
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1 // First section contains Add Reminder Cell.
}
return reminderList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("AddReminder") as! UITableViewCell
cell.textLabel?.text = "Create New Reminder"
return cell
}
let cell = tableView.dequeueReusableCellWithIdentifier("ReminderInfo") as! UITableViewCell
let reminderInfo = self.reminderList[indexPath.row] as ReminderInfoModel
cell.textLabel?.text = reminderInfo.name
let dateFormat = NSDateFormatter()
dateFormat.dateStyle = NSDateFormatterStyle.ShortStyle
dateFormat.timeStyle = NSDateFormatterStyle.ShortStyle
cell.detailTextLabel?.text = dateFormat.stringFromDate(reminderInfo.time)
return cell
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "New Reminder"
}
return "Reminders"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 1cd3a05e53a9045ac7c1f07f33afdff6 | 32.344262 | 118 | 0.666175 | 5.65 | false | false | false | false |
khizkhiz/swift | stdlib/public/core/Index.swift | 1 | 13131 | //===--- Index.swift - A position in a Collection -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// ForwardIndex, BidirectionalIndex, and RandomAccessIndex
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//===--- ForwardIndex -----------------------------------------------------===//
/// This protocol is an implementation detail of `ForwardIndex`; do
/// not use it directly.
///
/// Its requirements are inherited by `ForwardIndex` and thus must
/// be satisfied by types conforming to that protocol.
public protocol _Incrementable : Equatable {
/// Returns the next consecutive value in a discrete sequence of
/// `Self` values.
///
/// - Precondition: `self` has a well-defined successor.
@warn_unused_result
func successor() -> Self
mutating func _successorInPlace()
}
extension _Incrementable {
@inline(__always)
public mutating func _successorInPlace() { self = self.successor() }
}
//===----------------------------------------------------------------------===//
// A dummy type that we can use when we /don't/ want to create an
// ambiguity indexing Range<T> outside a generic context. See the
// implementation of Range for details.
public struct _DisabledRangeIndex_ {
init() {
_sanityCheckFailure("Nobody should ever create one.")
}
}
//===----------------------------------------------------------------------===//
/// Replace `i` with its `successor()` and return the updated value of
/// `i`.
@_transparent
@available(*, deprecated, message="it will be removed in Swift 3")
public prefix func ++ <T : _Incrementable> (i: inout T) -> T {
i._successorInPlace()
return i
}
/// Replace `i` with its `successor()` and return the original
/// value of `i`.
@_transparent
@available(*, deprecated, message="it will be removed in Swift 3")
public postfix func ++ <T : _Incrementable> (i: inout T) -> T {
let ret = i
i._successorInPlace()
return ret
}
/// Represents a discrete value in a series, where a value's
/// successor, if any, is reachable by applying the value's
/// `successor()` method.
public protocol ForwardIndex : _Incrementable {
/// A type that can represent the number of steps between pairs of
/// `Self` values where one value is reachable from the other.
///
/// Reachability is defined by the ability to produce one value from
/// the other via zero or more applications of `successor`.
associatedtype Distance : _SignedInteger = Int
// See the implementation of Range for an explanation of this
// associated type
associatedtype _DisabledRangeIndex = _DisabledRangeIndex_
/// Performs a range check in O(1), or a no-op when a range check is not
/// implementable in O(1).
///
/// The range check, if performed, is equivalent to:
///
/// precondition(bounds.contains(index))
///
/// Use this function to perform a cheap range check for QoI purposes when
/// memory safety is not a concern. Do not rely on this range check for
/// memory safety.
///
/// The default implementation for forward and bidirectional indices is a
/// no-op. The default implementation for random access indices performs a
/// range check.
///
/// - Complexity: O(1).
static func _failEarlyRangeCheck(index: Self, bounds: Range<Self>)
/// Performs a range check in O(1), or a no-op when a range check is not
/// implementable in O(1).
///
/// The range check, if performed, is equivalent to:
///
/// precondition(
/// bounds.contains(range.startIndex) ||
/// range.startIndex == bounds.endIndex)
/// precondition(
/// bounds.contains(range.endIndex) ||
/// range.endIndex == bounds.endIndex)
///
/// Use this function to perform a cheap range check for QoI purposes when
/// memory safety is not a concern. Do not rely on this range check for
/// memory safety.
///
/// The default implementation for forward and bidirectional indices is a
/// no-op. The default implementation for random access indices performs a
/// range check.
///
/// - Complexity: O(1).
static func _failEarlyRangeCheck2(
rangeStart rangeStart: Self,
rangeEnd: Self,
boundsStart: Self,
boundsEnd: Self)
// FIXME: the suffix `2` in the name, and passing `startIndex` and `endIndex`
// separately (rather than as a range) are workarounds for a compiler defect.
// <rdar://problem/21855350> Rejects-valid: rejects code that has two Self
// types in non-direct-argument-type position
/// Returns the result of advancing `self` by `n` positions.
///
/// - Returns:
/// - If `n > 0`, the result of applying `successor` to `self` `n` times.
/// - If `n < 0`, the result of applying `predecessor` to `self` `-n` times.
/// - Otherwise, `self`.
///
/// - Precondition: `n >= 0` if only conforming to `ForwardIndex`
/// - Complexity:
/// - O(1) if conforming to `RandomAccessIndex`
/// - O(`abs(n)`) otherwise
@warn_unused_result
func advanced(by n: Distance) -> Self
/// Returns the result of advancing `self` by `n` positions, or until it
/// equals `limit`.
///
/// - Returns:
/// - If `n > 0`, the result of applying `successor` to `self` `n` times
/// but not past `limit`.
/// - If `n < 0`, the result of applying `predecessor` to `self` `-n` times
/// but not past `limit`.
/// - Otherwise, `self`.
///
/// - Precondition: `n >= 0` if only conforming to `ForwardIndex`.
///
/// - Complexity:
/// - O(1) if conforming to `RandomAccessIndex`
/// - O(`abs(n)`) otherwise
@warn_unused_result
func advanced(by n: Distance, limit: Self) -> Self
/// Measure the distance between `self` and `end`.
///
/// - Precondition:
/// - `start` and `end` are part of the same sequence when conforming to
/// `RandomAccessIndex`.
/// - `end` is reachable from `self` by incrementation otherwise.
///
/// - Complexity:
/// - O(1) if conforming to `RandomAccessIndex`
/// - O(`n`) otherwise, where `n` is the function's result.
@warn_unused_result
func distance(to end: Self) -> Distance
}
// advance and distance implementations
extension ForwardIndex {
public static func _failEarlyRangeCheck(index: Self, bounds: Range<Self>) {
// Can't perform range checks in O(1) on forward indices.
}
public static func _failEarlyRangeCheck2(
rangeStart rangeStart: Self,
rangeEnd: Self,
boundsStart: Self,
boundsEnd: Self
) {
// Can't perform range checks in O(1) on forward indices.
}
/// Do not use this method directly; call advanced(by: n) instead.
@_transparent
@warn_unused_result
internal func _advanceForward(n: Distance) -> Self {
_precondition(n >= 0,
"Only BidirectionalIndex can be advanced by a negative amount")
var p = self
var i : Distance = 0
while i != n {
p._successorInPlace()
i += 1
}
return p
}
/// Do not use this method directly; call advanced(by: n, limit) instead.
@_transparent
@warn_unused_result
internal func _advanceForward(n: Distance, _ limit: Self) -> Self {
_precondition(n >= 0,
"Only BidirectionalIndex can be advanced by a negative amount")
var p = self
var i : Distance = 0
while i != n {
if p == limit { break }
p._successorInPlace()
i += 1
}
return p
}
@warn_unused_result
public func advanced(by n: Distance) -> Self {
return self._advanceForward(n)
}
@warn_unused_result
public func advanced(by n: Distance, limit: Self) -> Self {
return self._advanceForward(n, limit)
}
@warn_unused_result
public func distance(to end: Self) -> Distance {
var p = self
var count: Distance = 0
while p != end {
count += 1
p._successorInPlace()
}
return count
}
}
//===----------------------------------------------------------------------===//
//===--- BidirectionalIndex -----------------------------------------------===//
/// An index that can step backwards via application of its
/// `predecessor()` method.
public protocol BidirectionalIndex : ForwardIndex {
/// Returns the previous consecutive value in a discrete sequence.
///
/// If `self` has a well-defined successor,
/// `self.successor().predecessor() == self`. If `self` has a
/// well-defined predecessor, `self.predecessor().successor() ==
/// self`.
///
/// - Precondition: `self` has a well-defined predecessor.
@warn_unused_result
func predecessor() -> Self
mutating func _predecessorInPlace()
}
extension BidirectionalIndex {
@inline(__always)
public mutating func _predecessorInPlace() {
self = self.predecessor()
}
@warn_unused_result
public func advanced(by n: Distance) -> Self {
if n >= 0 {
return _advanceForward(n)
}
var p = self
var i: Distance = n
while i != 0 {
p._predecessorInPlace()
i._successorInPlace()
}
return p
}
@warn_unused_result
public func advanced(by n: Distance, limit: Self) -> Self {
if n >= 0 {
return _advanceForward(n, limit)
}
var p = self
var i: Distance = n
while i != 0 && p != limit {
p._predecessorInPlace()
i._successorInPlace()
}
return p
}
}
/// Replace `i` with its `predecessor()` and return the updated value
/// of `i`.
@_transparent
@available(*, deprecated, message="it will be removed in Swift 3")
public prefix func -- <T : BidirectionalIndex> (i: inout T) -> T {
i._predecessorInPlace()
return i
}
/// Replace `i` with its `predecessor()` and return the original
/// value of `i`.
@_transparent
@available(*, deprecated, message="it will be removed in Swift 3")
public postfix func -- <T : BidirectionalIndex> (i: inout T) -> T {
let ret = i
i._predecessorInPlace()
return ret
}
//===----------------------------------------------------------------------===//
//===--- RandomAccessIndex ------------------------------------------------===//
/// Used to force conformers of RandomAccessIndex to implement
/// `advanced(by:)` methods and `distance(to:)`.
public protocol _RandomAccessAmbiguity {
associatedtype Distance : _SignedInteger = Int
}
extension _RandomAccessAmbiguity {
@warn_unused_result
public func advanced(by n: Distance) -> Self {
fatalError("advanced(by:) not implemented")
}
}
/// An index that can be offset by an arbitrary number of positions,
/// and can measure the distance to any reachable value, in O(1).
public protocol RandomAccessIndex : BidirectionalIndex, Strideable,
_RandomAccessAmbiguity {
@warn_unused_result
func distance(to other: Self) -> Distance
@warn_unused_result
func advanced(by n: Distance) -> Self
@warn_unused_result
func advanced(by n: Distance, limit: Self) -> Self
}
extension RandomAccessIndex {
public static func _failEarlyRangeCheck(index: Self, bounds: Range<Self>) {
_precondition(
bounds.startIndex <= index,
"index is out of bounds: index designates a position before bounds.startIndex")
_precondition(
index < bounds.endIndex,
"index is out of bounds: index designates the bounds.endIndex position or a position after it")
}
public static func _failEarlyRangeCheck2(
rangeStart rangeStart: Self,
rangeEnd: Self,
boundsStart: Self,
boundsEnd: Self
) {
let range = rangeStart..<rangeEnd
let bounds = boundsStart..<boundsEnd
_precondition(
bounds.startIndex <= range.startIndex,
"range.startIndex is out of bounds: index designates a position before bounds.startIndex")
_precondition(
bounds.startIndex <= range.endIndex,
"range.endIndex is out of bounds: index designates a position before bounds.startIndex")
_precondition(
range.startIndex <= bounds.endIndex,
"range.startIndex is out of bounds: index designates a position after bounds.endIndex")
_precondition(
range.endIndex <= bounds.endIndex,
"range.startIndex is out of bounds: index designates a position after bounds.endIndex")
}
@_transparent
@warn_unused_result
public func advanced(by n: Distance, limit: Self) -> Self {
let d = self.distance(to: limit)
if d == 0 || (d > 0 ? d <= n : d >= n) {
return limit
}
return self.advanced(by: n)
}
}
@available(*, unavailable, renamed="ForwardIndex")
public typealias ForwardIndexType = ForwardIndex
@available(*, unavailable, renamed="BidirectionalIndex")
public typealias BidirectionalIndexType = BidirectionalIndex
@available(*, unavailable, renamed="RandomAccessIndex")
public typealias RandomAccessIndexType = RandomAccessIndex
| apache-2.0 | 7c51d41e9d69a62308dc20e5d118da04 | 31.105134 | 101 | 0.626152 | 4.275806 | false | false | false | false |
orlandoamorim/FamilyKey | Pods/ImageSlideshow/ImageSlideshow/Classes/Core/ZoomAnimatedTransitioning.swift | 1 | 14593 | //
// ZoomAnimatedTransitioning.swift
// ImageSlideshow
//
// Created by Petr Zvoníček on 31.08.15.
//
//
import UIKit
open class ZoomAnimatedTransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate {
/// parent image view used for animated transition
open var referenceImageView: UIImageView?
/// parent slideshow view used for animated transition
open var referenceSlideshowView: ImageSlideshow?
// must be weak because FullScreenSlideshowViewController has strong reference to its transitioning delegate
weak var referenceSlideshowController: FullScreenSlideshowViewController?
var referenceSlideshowViewFrame: CGRect?
var gestureRecognizer: UIPanGestureRecognizer!
fileprivate var interactionController: UIPercentDrivenInteractiveTransition?
/// Enables or disables swipe-to-dismiss interactive transition
open var slideToDismissEnabled: Bool = true
/**
Init the transitioning delegate with a source ImageSlideshow
- parameter slideshowView: ImageSlideshow instance to animate the transition from
- parameter slideshowController: FullScreenViewController instance to animate the transition to
*/
public init(slideshowView: ImageSlideshow, slideshowController: FullScreenSlideshowViewController) {
self.referenceSlideshowView = slideshowView
self.referenceSlideshowController = slideshowController
super.init()
initialize()
}
/**
Init the transitioning delegate with a source ImageView
- parameter imageView: UIImageView instance to animate the transition from
- parameter slideshowController: FullScreenViewController instance to animate the transition to
*/
public init(imageView: UIImageView, slideshowController: FullScreenSlideshowViewController) {
self.referenceImageView = imageView
self.referenceSlideshowController = slideshowController
super.init()
initialize()
}
func initialize() {
// Pan gesture recognizer for interactive dismiss
gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(ZoomAnimatedTransitioningDelegate.handleSwipe(_:)))
gestureRecognizer.delegate = self
// Append it to a window otherwise it will be canceled during the transition
UIApplication.shared.keyWindow?.addGestureRecognizer(gestureRecognizer)
}
@objc func handleSwipe(_ gesture: UIPanGestureRecognizer) {
guard let referenceSlideshowController = referenceSlideshowController else {
return
}
let percent = min(max(fabs(gesture.translation(in: gesture.view!).y) / 200.0, 0.0), 1.0)
if gesture.state == .began {
interactionController = UIPercentDrivenInteractiveTransition()
referenceSlideshowController.dismiss(animated: true, completion: nil)
} else if gesture.state == .changed {
interactionController?.update(percent)
} else if gesture.state == .ended || gesture.state == .cancelled || gesture.state == .failed {
let velocity = gesture.velocity(in: referenceSlideshowView)
if fabs(velocity.y) > 500 {
if let pageSelected = referenceSlideshowController.pageSelected {
pageSelected(referenceSlideshowController.slideshow.currentPage)
}
interactionController?.finish()
} else if percent > 0.5 {
if let pageSelected = referenceSlideshowController.pageSelected {
pageSelected(referenceSlideshowController.slideshow.currentPage)
}
interactionController?.finish()
} else {
interactionController?.cancel()
}
interactionController = nil
}
}
open func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if let reference = referenceSlideshowView {
return ZoomInAnimator(referenceSlideshowView: reference, parent: self)
} else if let reference = referenceImageView {
return ZoomInAnimator(referenceImageView: reference, parent: self)
} else {
return nil
}
}
open func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if let reference = referenceSlideshowView {
return ZoomOutAnimator(referenceSlideshowView: reference, parent: self)
} else if let reference = referenceImageView {
return ZoomOutAnimator(referenceImageView: reference, parent: self)
} else {
return nil
}
}
open func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactionController
}
open func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactionController
}
}
extension ZoomAnimatedTransitioningDelegate: UIGestureRecognizerDelegate {
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard let _ = gestureRecognizer as? UIPanGestureRecognizer else {
return false
}
if !slideToDismissEnabled {
return false
}
if let currentItem = referenceSlideshowController?.slideshow.currentSlideshowItem, currentItem.isZoomed() {
return false
}
return true
}
}
class ZoomAnimator: NSObject {
var referenceImageView: UIImageView?
var referenceSlideshowView: ImageSlideshow?
var parent: ZoomAnimatedTransitioningDelegate
init(referenceSlideshowView: ImageSlideshow, parent: ZoomAnimatedTransitioningDelegate) {
self.referenceSlideshowView = referenceSlideshowView
self.referenceImageView = referenceSlideshowView.currentSlideshowItem?.imageView
self.parent = parent
super.init()
}
init(referenceImageView: UIImageView, parent: ZoomAnimatedTransitioningDelegate) {
self.referenceImageView = referenceImageView
self.parent = parent
super.init()
}
}
class ZoomInAnimator: ZoomAnimator { }
extension ZoomInAnimator: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
// Pauses slideshow
self.referenceSlideshowView?.pauseTimer()
let containerView = transitionContext.containerView
let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!
guard let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? FullScreenSlideshowViewController else {
return
}
toViewController.view.frame = transitionContext.finalFrame(for: toViewController)
let transitionBackgroundView = UIView(frame: containerView.frame)
transitionBackgroundView.backgroundColor = toViewController.backgroundColor
containerView.addSubview(transitionBackgroundView)
containerView.sendSubview(toBack: transitionBackgroundView)
let finalFrame = toViewController.view.frame
var transitionView: UIImageView?
var transitionViewFinalFrame = finalFrame
if let referenceImageView = referenceImageView {
transitionView = UIImageView(image: referenceImageView.image)
transitionView!.contentMode = UIViewContentMode.scaleAspectFill
transitionView!.clipsToBounds = true
transitionView!.frame = containerView.convert(referenceImageView.bounds, from: referenceImageView)
containerView.addSubview(transitionView!)
self.parent.referenceSlideshowViewFrame = transitionView!.frame
referenceImageView.alpha = 0
if let image = referenceImageView.image {
transitionViewFinalFrame = image.tgr_aspectFitRectForSize(finalFrame.size)
}
}
if let item = toViewController.slideshow.currentSlideshowItem, item.zoomInInitially {
transitionViewFinalFrame.size = CGSize(width: transitionViewFinalFrame.size.width * item.maximumZoomScale, height: transitionViewFinalFrame.size.height * item.maximumZoomScale)
}
let duration: TimeInterval = transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration, delay:0, usingSpringWithDamping:0.7, initialSpringVelocity:0, options: UIViewAnimationOptions.curveLinear, animations: {
fromViewController.view.alpha = 0
transitionView?.frame = transitionViewFinalFrame
transitionView?.center = CGPoint(x: finalFrame.midX, y: finalFrame.midY)
}, completion: {(_) in
fromViewController.view.alpha = 1
self.referenceImageView?.alpha = 1
transitionView?.removeFromSuperview()
transitionBackgroundView.removeFromSuperview()
containerView.addSubview(toViewController.view)
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
class ZoomOutAnimator: ZoomAnimator { }
extension ZoomOutAnimator: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.25
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let toViewController: UIViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!
guard let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? FullScreenSlideshowViewController else {
return
}
let containerView = transitionContext.containerView
toViewController.view.frame = transitionContext.finalFrame(for: toViewController)
toViewController.view.alpha = 0
containerView.addSubview(toViewController.view)
containerView.sendSubview(toBack: toViewController.view)
var transitionViewInitialFrame: CGRect
if let currentSlideshowItem = fromViewController.slideshow.currentSlideshowItem {
if let image = currentSlideshowItem.imageView.image {
transitionViewInitialFrame = image.tgr_aspectFitRectForSize(currentSlideshowItem.imageView.frame.size)
} else {
transitionViewInitialFrame = currentSlideshowItem.imageView.frame
}
transitionViewInitialFrame = containerView.convert(transitionViewInitialFrame, from: currentSlideshowItem)
} else {
transitionViewInitialFrame = fromViewController.slideshow.frame
}
var transitionViewFinalFrame: CGRect
if let referenceImageView = referenceImageView {
referenceImageView.alpha = 0
let referenceSlideshowViewFrame = containerView.convert(referenceImageView.bounds, from: referenceImageView)
transitionViewFinalFrame = referenceSlideshowViewFrame
// do a frame scaling when AspectFit content mode enabled
if fromViewController.slideshow.currentSlideshowItem?.imageView.image != nil && referenceImageView.contentMode == UIViewContentMode.scaleAspectFit {
transitionViewFinalFrame = containerView.convert(referenceImageView.aspectToFitFrame(), from: referenceImageView)
}
// fixes the problem when the referenceSlideshowViewFrame was shifted during change of the status bar hidden state
if UIApplication.shared.isStatusBarHidden && !toViewController.prefersStatusBarHidden && referenceSlideshowViewFrame.origin.y != parent.referenceSlideshowViewFrame?.origin.y {
transitionViewFinalFrame = transitionViewFinalFrame.offsetBy(dx: 0, dy: 20)
}
} else {
transitionViewFinalFrame = referenceSlideshowView?.frame ?? CGRect.zero
}
let transitionBackgroundView = UIView(frame: containerView.frame)
transitionBackgroundView.backgroundColor = fromViewController.backgroundColor
containerView.addSubview(transitionBackgroundView)
containerView.sendSubview(toBack: transitionBackgroundView)
let transitionView: UIImageView = UIImageView(image: fromViewController.slideshow.currentSlideshowItem?.imageView.image)
transitionView.contentMode = UIViewContentMode.scaleAspectFill
transitionView.clipsToBounds = true
transitionView.frame = transitionViewInitialFrame
containerView.addSubview(transitionView)
fromViewController.view.isHidden = true
let duration: TimeInterval = transitionDuration(using: transitionContext)
let animations = {
toViewController.view.alpha = 1
transitionView.frame = transitionViewFinalFrame
}
let completion = { (_: Any) in
let completed = !transitionContext.transitionWasCancelled
self.referenceImageView?.alpha = 1
if completed {
fromViewController.view.removeFromSuperview()
UIApplication.shared.keyWindow?.removeGestureRecognizer(self.parent.gestureRecognizer)
// Unpauses slideshow
self.referenceSlideshowView?.unpauseTimer()
} else {
fromViewController.view.isHidden = false
}
transitionView.removeFromSuperview()
transitionBackgroundView.removeFromSuperview()
transitionContext.completeTransition(completed)
}
// Working around iOS 10 bug in UIView.animate causing a glitch in interrupted interactive transition
if #available(iOS 10.0, *) {
UIViewPropertyAnimator.runningPropertyAnimator(withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: animations, completion: completion)
} else {
UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: animations, completion: completion)
}
}
}
| mit | 2c4d4b4c1dd04bb218781708744bb5b6 | 43.215152 | 188 | 0.715372 | 6.278399 | false | false | false | false |
foresterre/mal | swift3/Sources/step0_repl/main.swift | 15 | 201 | import Foundation
while true {
print("user> ", terminator: "")
let line = readLine(strippingNewline: true)
if line == nil { break }
if line == "" { continue }
print("\(line!)")
}
| mpl-2.0 | 65a22b2fb466efb96be112256df72991 | 19.1 | 47 | 0.577114 | 4.02 | false | false | false | false |
lojals/DoorsConcept | DoorConcept/Controllers/History/HistoryTableViewController.swift | 1 | 1442 | //
// HistoryTableViewController.swift
// DoorConcept
//
// Created by Jorge Raul Ovalle Zuleta on 3/20/16.
// Copyright © 2016 jorgeovalle. All rights reserved.
//
import UIKit
class HistoryTableViewController: UITableViewController {
var historyInteractor:HistoryInteractor = HistoryInteractor()
var history:[History] = [History]()
override func viewDidLoad() {
super.viewDidLoad()
}
/**
After View loaded, historyInteractor retrieve the history for User
- parameter animated: default
*/
override func viewWillAppear(animated: Bool) {
historyInteractor.getHistory { (data, error) -> Void in
if error == nil{
self.history = data as! [History]
self.tableView.reloadData()
}
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return history.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("HistoryCell", forIndexPath: indexPath) as! HistoryTableViewCell
cell.configureCellWithHistory(history[indexPath.row])
return cell
}
}
| mit | 05cdf768d3aef01c3ef4ea9b2a341d12 | 28.408163 | 127 | 0.666204 | 5.109929 | false | false | false | false |
zhxnlai/DongerListKeyboard | DongerListKeyboard/DongerListKeyboard/DLEmoticonManager.swift | 1 | 2699 | //
// DLEmoticonManager.swift
// DongerListKeyboard
//
// Created by Zhixuan Lai on 11/12/14.
// Copyright (c) 2014 Zhixuan Lai. All rights reserved.
//
import Foundation
import SwiftyJSON
let appGroupId = "group.dongerListKeyboard"
private let _singletonInstance = DLEmoticonManager()
let kJSONCategoryKey = "category"
let kJSONValueKey = "value"
class DLEmoticonManager: NSObject {
class var sharedInstance: DLEmoticonManager {
return _singletonInstance
}
var emoticons:Dictionary<String,Array<String>> = Dictionary<String,Array<String>>()
func initialize(data:NSData) {
let json = JSON(data:data)
let jsonColumns = json["columns"] //array
let jsonRows = json["data"].arrayValue; //array
// println("jsonColumns: \(jsonColumns)")
// jsonRows.reduce(emoticons, combine: { (acc:Dictionary<String,Array<String>>, json:JSON) -> Dictionary<String,Array<String>> in
// let category = json[kJSONCategoryKey].arrayValue[0].stringValue
// let value = json[kJSONValueKey].arrayValue[0].stringValue
// if var array = acc[category] {
// array.append(value)
// } else {
// acc.updateValue(value: [value], forKey: category)
// }
// })
for row in jsonRows {
let category = formatCategory(row[kJSONCategoryKey].arrayValue[0].stringValue)
let value = row[kJSONValueKey].arrayValue[0].stringValue
// println("value \(value)")
// if var array = emoticons[category] {
if var array = emoticons[category] {
array.append(value)
emoticons.updateValue(array, forKey: category)
} else {
emoticons.updateValue([value], forKey: category)
}
}
// println("dictionary: \(emoticons)")
let sharedDefaults = NSUserDefaults(suiteName: appGroupId)!
// sharedDefaults?.setObject(emoticons, forKey: "emoticons")
sharedDefaults.setInteger(1, forKey: "test")
sharedDefaults.setObject(NSKeyedArchiver.archivedDataWithRootObject(emoticons), forKey: "emoticons")
if sharedDefaults.synchronize() {
println("synchronized")
println("share defaults: \(sharedDefaults.dictionaryRepresentation())")
}
// NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(object), forKey: key)
}
func formatCategory(name:String) -> String {
let nameArray = name.componentsSeparatedByString(" ")
return nameArray[1]
}
}
| mit | eb33aa5f804a6c1854c26f3aaf22bdda | 33.164557 | 136 | 0.621341 | 4.597956 | false | false | false | false |
yoshiz3-onishi/YZTagView | source/TagView.swift | 1 | 15424 | // ------------------------------------------------------------------------------------------------
import UIKit
// ------------------------------------------------------------------------------------------------
public enum TagViewOptions
{
case OuterMergine ( CGFloat )
case InnerMergine ( CGFloat )
case BackgroundColor ( UIColor )
case AutoGlowHeight ( Bool )
case Font ( UIFont )
case TagBackgroundColor ( UIColor )
case TagSelectedColor ( UIColor )
case TagTextColor ( UIColor )
case TagPrefix ( String )
case TagMaxCharactors ( Int )
case AddButtonBackgroundColor ( UIColor )
case AddButtonTextColor ( UIColor )
case EnableEdit ( Bool )
case MaxTagCount ( Int )
}
// ------------------------------------------------------------------------------------------------
@objc public protocol TagViewDelegate
{
@objc optional func onChangedLayoutTag( sender: UIView )
@objc optional func onDidEndEditingTag( sender: UIView )
@objc optional func onTapTag( name: String, userData: Any? )
}
// ------------------------------------------------------------------------------------------------
class TagView: UIView, UITextFieldDelegate
{
var _scrollView : UIScrollView!
var _tagIndex : Int = 0
var _touchTagIndex : Int = -1
var _tagFields : [Int: UITextField]! = [:]
var _userDatum : [Int: Any]! = [:]
var _tagFieldMaxX : CGFloat = 0.0
var _tagFieldMinY : CGFloat = 0.0
var _basePosition : CGPoint!
var _baseSize : CGSize!
var _addButton : UIButton!
var _outerMergine : CGFloat = 5.0
var _innerMergine : CGFloat = 2.5
var _autoGlowHeight : Bool = true
var _font : UIFont!
var _tagBackgroundColor : UIColor = UIColor.white
var _tagSelectedColor : UIColor = UIColor.white
var _tagTextColor : UIColor = UIColor.black
var _tagPrefix : String = "#"
var _tagMaxCharactors : Int = 30
var _tagCharCountLabel : UILabel!
var _addButtonBackgroundColor : UIColor = UIColor.white
var _addButtonTextColor : UIColor = UIColor.black
var _enableEdit : Bool = true
var _maxTagCount : Int = 1000
var _tagCount : Int = 0
var _targetTextField : UITextField!
weak var delegate : TagViewDelegate?
// --------------------------------------------------------------------------------------------
required init( coder aDecoder: NSCoder )
{
super.init( coder: aDecoder )!
}
// --------------------------------------------------------------------------------------------
override init( frame: CGRect )
{
super.init( frame: frame )
}
// --------------------------------------------------------------------------------------------
convenience init( position: CGPoint, size: CGSize, options: [TagViewOptions]? = nil )
{
self.init( frame: CGRect( x: position.x, y: position.y, width: size.width, height: size.height ) )
self.isUserInteractionEnabled = true
self.addGestureRecognizer( UITapGestureRecognizer( target: self, action: #selector( onTapBackground ) ) )
_basePosition = position
_baseSize = size
if let _options = options
{
for option in _options
{
switch option
{
case let .OuterMergine ( value ): _outerMergine = value
case let .InnerMergine ( value ): _innerMergine = value
case let .AutoGlowHeight ( value ): _autoGlowHeight = value
case let .BackgroundColor ( value ): backgroundColor = value
case let .Font ( value ): _font = value
case let .TagBackgroundColor ( value ): _tagBackgroundColor = value
case let .TagSelectedColor ( value ): _tagSelectedColor = value
case let .TagTextColor ( value ): _tagTextColor = value
case let .TagPrefix ( value ): _tagPrefix = value
case let .TagMaxCharactors ( value ): _tagMaxCharactors = value
case let .AddButtonBackgroundColor ( value ): _addButtonBackgroundColor = value
case let .AddButtonTextColor ( value ): _addButtonTextColor = value
case let .EnableEdit ( value ): enableEdit = value
case let .MaxTagCount ( value ): _maxTagCount = value
}
}
}
_scrollView = UIScrollView( frame: frame )
_scrollView.isPagingEnabled = false
_scrollView.frame = CGRect( x: 0, y: 0, width: frame.width, height: frame.height )
_scrollView.contentSize = CGSize( width: frame.width, height: frame.height )
_scrollView.layer.position = CGPoint( x: frame.width / 2, y: frame.height / 2 )
_scrollView.showsVerticalScrollIndicator = false
_scrollView.isUserInteractionEnabled = true
self.addSubview( _scrollView )
_addButton = UIButton( frame: CGRect( x: 0, y: 0, width: 30, height: 30 ) )
_addButton.layer.anchorPoint = CGPoint( x: 0.0, y: 0.5 )
_addButton.layer.position = CGPoint( x: _outerMergine, y: _outerMergine + _addButton.frame.height / 2 )
_addButton.isHidden = !_enableEdit
_addButton.titleLabel?.font = _font
_addButton.layer.masksToBounds = true
_addButton.isUserInteractionEnabled = true
_addButton.layer.cornerRadius = _addButton.frame.height / 2
_addButton.layer.borderColor = _addButtonTextColor.cgColor
_addButton.layer.borderWidth = 1.5
_addButton.backgroundColor = _addButtonBackgroundColor
_addButton.setTitle( "+", for: UIControlState.normal )
_addButton.setTitleColor( _addButtonTextColor, for: UIControlState.normal )
_addButton.setTitle( "+", for: UIControlState.highlighted )
_addButton.setTitleColor( _addButtonTextColor, for: UIControlState.highlighted )
_addButton.setBackgroundImage( UIImage.createImageFromColor( color: UIColor.white ), for: .highlighted )
_addButton.addTarget( self, action: #selector( onTapAddButton ), for: .touchUpInside )
self.addSubview( _addButton )
_tagCharCountLabel = UILabel( frame: CGRect( x: 0, y: 0, width: 51, height: 20 ) )
_tagCharCountLabel.layer.anchorPoint = CGPoint( x: 1.0, y: 0.5 )
_tagCharCountLabel.font = Utility.getSystemFont( size: 10 )
_tagCharCountLabel.textColor = _addButtonTextColor
_tagCharCountLabel.textAlignment = NSTextAlignment.center
_tagCharCountLabel.layer.zPosition = 5000
_tagCharCountLabel.backgroundColor = UIColor.white
_tagCharCountLabel.layer.masksToBounds = true
_tagCharCountLabel.layer.cornerRadius = 20 / 2
_tagCharCountLabel.layer.borderColor = _addButtonTextColor.cgColor
_tagCharCountLabel.layer.borderWidth = 1.5
_tagCharCountLabel.isHidden = true
self.addSubview( _tagCharCountLabel )
}
// --------------------------------------------------------------------------------------------
var enableEdit: Bool
{
get
{
return _enableEdit
}
set( newFlag )
{
if _addButton != nil
{
_addButton.isHidden = !newFlag
}
for index in 0 ..< _tagFields.count
{
_tagFields[ index ]?.isEnabled = newFlag
}
_enableEdit = newFlag
}
}
// --------------------------------------------------------------------------------------------
func getTags( withPrefix: Bool ) -> [String]
{
var tags: [String] = []
for ( _, value ) in _tagFields.sorted( by: { $0.0 < $1.0 } )
{
if withPrefix == true
{
if value.text!.range( of: _tagPrefix ) != nil
{
tags.append( value.text! )
}
else
{
tags.append( _tagPrefix + value.text! )
}
}
else
{
if value.text!.range( of: _tagPrefix ) != nil
{
tags.append( value.text!.replacingOccurrences( of: _tagPrefix, with: "" ) )
}
else
{
tags.append( value.text! )
}
}
}
return tags
}
// --------------------------------------------------------------------------------------------
// layout functions
// --------------------------------------------------------------------------------------------
func addTag( tagString: String, userData: Any? = nil )
{
let tagField = UITextField( frame: CGRect( x: 0, y: 0, width: 60, height: 30 ) )
tagField.layer.anchorPoint = CGPoint( x: 0.0, y: 0.0 )
tagField.layer.position = CGPoint( x: _outerMergine + _tagFieldMaxX, y: _outerMergine + _tagFieldMinY )
tagField.backgroundColor = _tagBackgroundColor
tagField.textColor = _tagTextColor
tagField.text = tagString
tagField.tintColor = _addButtonTextColor
tagField.font = _font
tagField.textAlignment = NSTextAlignment.center
tagField.delegate = self
tagField.borderStyle = UITextBorderStyle.roundedRect
tagField.returnKeyType = UIReturnKeyType.done
tagField.tag = _tagIndex
tagField.isEnabled = _enableEdit
tagField.becomeFirstResponder()
tagField.sizeToFit()
_scrollView.addSubview( tagField )
_tagFields[ _tagIndex ] = tagField
_userDatum[ _tagIndex ] = userData
fitTag( tagField: tagField )
updateLayout()
_tagIndex += 1
hideCharactorCount()
}
// --------------------------------------------------------------------------------------------
func removeTag( tagField: UITextField )
{
_tagFields.removeValue( forKey: tagField.tag )
_userDatum.removeValue( forKey: tagField.tag )
tagField.removeFromSuperview()
}
// --------------------------------------------------------------------------------------------
func fitTag( tagField: UITextField )
{
if 0 < tagField.text!.characters.count
{
if ( tagField.text! as NSString ).substring( to: _tagPrefix.characters.count ) != _tagPrefix
{
tagField.text = _tagPrefix + tagField.text!
}
}
tagField.sizeToFit()
tagField.frame = CGRect( x: tagField.layer.position.x, y: tagField.layer.position.y, width: tagField.frame.width + _innerMergine * 2, height: tagField.frame.height + _innerMergine * 2 )
}
// --------------------------------------------------------------------------------------------
func updateLayout()
{
_tagFieldMaxX = 0.0
_tagFieldMinY = _outerMergine
var tagFieldMaxY = CGFloat( 0.0 )
for ( _, value ) in _tagFields.sorted( by: { $0.0 < $1.0 } )
{
value.frame = CGRect( x: _tagFieldMaxX + _outerMergine, y: _tagFieldMinY, width: value.frame.width, height: value.frame.height )
if frame.width - _outerMergine * 2 < value.frame.width
{
value.frame = CGRect( x: _outerMergine, y: value.frame.maxY + _outerMergine, width: frame.width - _outerMergine * 2, height: value.frame.height )
}
else if frame.width - _outerMergine < value.frame.maxX
{
value.layer.position = CGPoint( x: _outerMergine, y: value.frame.maxY + _outerMergine )
}
_tagFieldMaxX = value.frame.maxX
_tagFieldMinY = value.frame.minY
if tagFieldMaxY < value.frame.maxY
{
tagFieldMaxY = value.frame.maxY
}
}
if _tagFields.count == 0
{
_addButton.layer.position = CGPoint( x: _outerMergine, y: _outerMergine + _addButton.frame.height / 2 )
}
else
{
_addButton.layer.position = CGPoint( x: _tagFieldMaxX + _outerMergine, y: _tagFieldMinY + ( tagFieldMaxY - _tagFieldMinY ) / 2 )
}
if frame.width - _outerMergine < _addButton.frame.maxX
{
_addButton.layer.position = CGPoint( x: _outerMergine, y: tagFieldMaxY + _outerMergine + _addButton.frame.height / 2 )
if tagFieldMaxY < _addButton.frame.maxY
{
tagFieldMaxY = _addButton.frame.maxY
}
}
_scrollView.contentSize = CGSize( width: frame.width, height: tagFieldMaxY + _outerMergine )
if _autoGlowHeight == true
{
frame = CGRect( x: _basePosition.x, y: _basePosition.y, width: _baseSize.width, height: max( _baseSize.height, _scrollView.contentSize.height ) )
_scrollView.frame = CGRect( x: 0, y: 0, width: frame.width, height: frame.height )
delegate?.onChangedLayoutTag!( sender: self )
}
}
// --------------------------------------------------------------------------------------------
func updateCharactorCount()
{
_tagCharCountLabel.isHidden = false
_tagCharCountLabel.text = _targetTextField.text!.characters.count.description + " / " + _tagMaxCharactors.description
_tagCharCountLabel.layer.position = CGPoint( x: _targetTextField.frame.maxX, y: _targetTextField.frame.maxY + 5 )
_tagCharCountLabel.text = _targetTextField.text!.characters.count.description + " / " + _tagMaxCharactors.description
}
// --------------------------------------------------------------------------------------------
func hideCharactorCount()
{
_tagCharCountLabel.isHidden = true
}
// --------------------------------------------------------------------------------------------
// event functions
// --------------------------------------------------------------------------------------------
func onTapAddButton( sender: UIButton )
{
if 0 < _maxTagCount - _tagCount
{
addTag( tagString: _tagPrefix )
_tagCount += 1
_addButton.isHidden = ( _maxTagCount - _tagCount ) == 0
}
}
// --------------------------------------------------------------------------------------------
func textFieldShouldBeginEditing( _ textField: UITextField ) -> Bool
{
_targetTextField = textField
updateCharactorCount()
return true
}
// --------------------------------------------------------------------------------------------
func textField( _ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String ) -> Bool
{
Timer.scheduledTimer( timeInterval: 0.05, target: self, selector: #selector( onTimerTextField ), userInfo: _tagFields[ textField.tag ]!, repeats: false )
return true
}
// --------------------------------------------------------------------------------------------
func onTimerTextField( timer: Timer )
{
if _tagMaxCharactors < _targetTextField.text!.characters.count
{
_targetTextField.text = ( _targetTextField.text! as NSString ).substring( to: _tagMaxCharactors )
}
updateCharactorCount()
fitTag( tagField: timer.userInfo as! UITextField )
updateLayout()
}
// --------------------------------------------------------------------------------------------
func textFieldDidEndEditing( _ textField: UITextField )
{
if textField.text == "" || textField.text == _tagPrefix
{
removeTag( tagField: _tagFields[ textField.tag ]! )
_tagCount -= 1
_addButton.isHidden = ( _maxTagCount - _tagCount ) == 0
}
else
{
fitTag( tagField: _tagFields[ textField.tag ]! )
}
updateLayout()
}
// --------------------------------------------------------------------------------------------
func textFieldShouldReturn( _ textField: UITextField ) -> Bool
{
textField.resignFirstResponder()
hideCharactorCount()
endEditing( true )
delegate?.onDidEndEditingTag!( sender: self )
return true
}
// --------------------------------------------------------------------------------------------
func onTapBackground( sender: UITapGestureRecognizer )
{
let point = sender.location( in: self )
for index in 0 ..< _tagFields.count
{
if _tagFields[ index ]?.frame.contains( point ) == true
{
_tagFields[ index ]!.backgroundColor = _tagSelectedColor
Timer.scheduledTimer( timeInterval: 0.05, target: self, selector: #selector( self.onTouchEnd ), userInfo: index, repeats: false )
_touchTagIndex = index
return
}
}
}
// --------------------------------------------------------------------------------------------
func onTouchEnd( timer: Timer )
{
_tagFields[ _touchTagIndex ]!.backgroundColor = _tagBackgroundColor
delegate?.onTapTag!( name: ( _tagFields[ _touchTagIndex ]?.text )!, userData: _userDatum[ _touchTagIndex ] )
}
}
| mit | 9e20dedfe9639ecfea2bfd490ed0dbd6 | 38.147208 | 187 | 0.57229 | 3.731914 | false | false | false | false |
Spacerat/HexKeyboard | HexKeyboard/HexViewController.swift | 1 | 1767 | //
// ViewController.swift
// HexKeyboard
//
// Created by Joseph Atkins-Turkish on 02/09/2014.
// Copyright (c) 2014 Joseph Atkins-Turkish. All rights reserved.
//
import UIKit
import Foundation
import CoreAudio
import AVFoundation
class HexViewController: UIViewController, HexViewDelegate {
var player : NotePlayer!
override func viewDidLoad() {
super.viewDidLoad()
println(view.frame)
//println(view)
let k = AVAudioEngine()
println("viewDidLoad")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func loadView() {
let hexes = HexView()
self.view = hexes
hexes.delegate = self
}
override func viewWillAppear(animated: Bool) {
if let hexes = self.view as? HexView {
hexes.refreshLabels()
}
if let instrument = InstrumentSpec.currentInstrument {
player = instrument
}
else {
player = InstrumentSpec.defaultInstrumentSpec.getInstrument()
}
}
func hexPressed(row: Int, column: Int) {
let note = Note(hexRow: row, column: column)
//println("\(note.index) : \(note.name)")
player.play(note)
}
func hexReleased(row: Int, column: Int) {
let note = Note(hexRow: row, column: column)
player.release(note)
}
func hexNameForRow(row: Int, column: Int) -> String {
let name = Note(hexRow: row, column: column).name
return "\(name)"
}
func shouldHoldKeys() -> Bool {
return player.currentInstrument.transient == false
}
}
| gpl-2.0 | c112742298726c83e9013753b4ffe422 | 23.541667 | 73 | 0.593096 | 4.439698 | false | false | false | false |
ylovesy/CodeFun | wuzhentao/SortList.swift | 1 | 1973 | public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}
public class Solution {
func sortList(_ head: ListNode?) -> ListNode? {
var node = head
var ary = [Int]()
while node != nil {
ary.append((node?.val)!)
node = node?.next
}
ary = ary.sorted()
var node1 = head
for num in ary {
node1?.val = num
node1 = node1?.next
}
return head
}
}
class Solution {
func sortList(_ head: ListNode?) -> ListNode? {
if head == nil {
return nil
}
if head?.next == nil {
return head
}
var prev = head, slow = head, fast = head
while fast != nil, fast?.next != nil {
prev = slow
slow = slow?.next
fast = fast?.next?.next
}
prev?.next = nil
let firstHalf = sortList(head)
let secondHalf = sortList(slow)
return mergeTwoLists(firstHalf, secondHalf)
}
private func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
let result = ListNode(0)
var head = result
var l1 = l1
var l2 = l2
while l1 != nil, l2 != nil {
if l1!.val < l2!.val {
head.next = l1
l1 = l1?.next
} else {
head.next = l2
l2 = l2?.next
}
head = head.next!
}
head.next = l1 != nil ? l1 : l2
return result.next
}
}
let l1 = ListNode(10)
let l2 = ListNode(8)
let l3 = ListNode(14)
let l4 = ListNode(2)
let l5 = ListNode(9)
let l6 = ListNode(15)
let l7 = ListNode(4)
let l8 = ListNode(6)
l1.next=l2
l2.next=l3
l3.next=l4
l4.next=l5
l5.next=l6
l6.next=l7
l7.next=l8
let s = Solution()
let ll = s.sortList(l1)
print(ll as Any)
| apache-2.0 | e10f33f48dd1960008df0b8f746d5f5e | 21.168539 | 79 | 0.488089 | 3.516934 | false | false | false | false |
sleekbyte/tailor | src/test/swift/com/sleekbyte/tailor/functional/MaxNameLengthTest.swift | 1 | 1251 | class CheckSuperLongClassName {
}
let checkElementNameLength: (ename: Int, veryLongElementName: Int) = (1, 2)
enum PrettyLongExampleEnum: Int {
case A, BIsAVeryLongEnumCaseName, C = 5, D
}
func myFunctionNameIsTooLong(longExternalParameterName aLongLocalParameterName: Int) -> Bool {
return true
}
let myStr = "hello"
mySwitchLabel: switch myStr {
case "hello":
print("yes")
case "hi":
print("no")
default:
print("both")
}
protocol TooLongProtocolHere {
}
struct RectIsAPrettyLongName {
var mid: Int {
get {
return 1
}
set(newCenterTooLong) {
mid = newCenterTooLong
}
}
}
typealias LongNameMusicalNote = String
struct Rect { // test enterVariableName
var thisIsALongVariable: Point {
get {
return Point(12, 144)
}
}
}
func myFunctionNameIsAlsoLong(longExternalParameterName aLongLocalParameterName: Int) -> Bool {
return true
}
let thisIsALongConstantName = 1
var thisIsALongVariableName = 0
enum SomeEnum: Int {
case SomeLongEnumCaseName
init (value: NSNumber) {
switch value.integerValue {
case SomeLongEnumCaseName:
self = Some_Enum_Case
}
}
}
| mit | afba7ca9824de7b15312e9f387c6d733 | 18.857143 | 95 | 0.645883 | 3.837423 | false | false | false | false |
akosma/SwiftMoment | SwiftMoment/SwiftMoment/TimeUnit.swift | 1 | 713 | //
// TimeUnit.swift
// SwiftMoment
//
// Created by Adrian on 19/01/15.
// Copyright (c) 2015 Adrian Kosmaczewski. All rights reserved.
//
/// Represents different time units.
///
/// - years: Represents year units.
/// - quarters: Represents quarter units.
/// - months: Represents month units.
/// - weeks: Represents week units.
/// - days: Represents day units.
/// - hours: Represents hour units.
/// - minutes: Represents minute units.
/// - seconds: Represents second units.
public enum TimeUnit: String {
case years = "y"
case quarters = "Q"
case months = "M"
case weeks = "w"
case days = "d"
case hours = "H"
case minutes = "m"
case seconds = "s"
}
| bsd-2-clause | 310ee0a69097e1677c5ac3a5d42e8d14 | 24.464286 | 64 | 0.618513 | 3.582915 | false | false | false | false |
SpriteKitAlliance/SKAControlSprite | Example/SKAControlExample/SKAControlExample/Controllers/GameViewController.swift | 1 | 851 | //
// GameViewController.swift
// SKAControlExample
//
// Created by Marc Vandehey on 4/20/17.
// Copyright © 2017 SpriteKit Alliance. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
let scene = MenuScene()
scene.size = view.bounds.size
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
view.ignoresSiblingOrder = true
}
}
override var shouldAutorotate: Bool {
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| mit | 054f477c6a32e0c5b0aeee9a10538da9 | 19.238095 | 63 | 0.684706 | 4.473684 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/SharedViews/LoadingBarButtonItemView.swift | 1 | 2444 | import Library
import Prelude
import UIKit
final class LoadingBarButtonItemView: UIView, NibLoading {
@IBOutlet fileprivate var activityIndicator: UIActivityIndicatorView!
@IBOutlet fileprivate var titleButton: UIButton!
private let viewModel: LoadingBarButtonItemViewModelType = LoadingBarButtonItemViewModel()
public static func instantiate() -> LoadingBarButtonItemView {
guard let saveButtonView = LoadingBarButtonItemView.fromNib(nib: Nib.LoadingBarButtonItemView) else {
fatalError("failed to load LoadingBarButtonItemView from Nib")
}
saveButtonView.translatesAutoresizingMaskIntoConstraints = false
return saveButtonView
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func bindStyles() {
super.bindStyles()
_ = self.titleButton
|> UIButton.lens.titleLabel.font .~ UIFont.systemFont(ofSize: 17)
|> UIButton.lens.titleColor(for: .normal) .~ .ksr_create_700
|> UIButton.lens.titleColor(for: .disabled) .~ .ksr_support_300
_ = self.activityIndicator
|> baseActivityIndicatorStyle
}
override func bindViewModel() {
super.bindViewModel()
self.titleButton.rac.hidden = self.viewModel.outputs.titleButtonIsHidden
self.titleButton.rac.enabled = self.viewModel.outputs.titleButtonIsEnabled
self.titleButton.rac.title = self.viewModel.outputs.titleButtonText
self.viewModel.outputs.activityIndicatorIsLoading
.observeForUI()
.observeValues { [weak self] isLoading in
self?.animateActivityIndicator(isLoading)
}
}
// MARK: - Public Functions
func setIsEnabled(isEnabled: Bool) {
self.viewModel.inputs.setIsEnabled(isEnabled: isEnabled)
}
func setTitle(title: String) {
self.viewModel.inputs.setTitle(title: title)
}
func startAnimating() {
self.viewModel.inputs.setAnimating(isAnimating: true)
}
func stopAnimating() {
self.viewModel.inputs.setAnimating(isAnimating: false)
}
func addTarget(_ target: Any?, action: Selector) {
self.titleButton.addTarget(target, action: action, for: .touchUpInside)
}
// MARK: - Functions
private func animateActivityIndicator(_ isAnimating: Bool) {
if isAnimating {
bringSubviewToFront(self.activityIndicator)
self.activityIndicator.startAnimating()
} else {
self.activityIndicator.stopAnimating()
bringSubviewToFront(self.titleButton)
}
}
}
| apache-2.0 | eb6a0572eece9fb0477361a82bf8b6a2 | 27.418605 | 105 | 0.733224 | 4.811024 | false | false | false | false |
shoheiyokoyama/SYBlinkAnimationKit | Source/SYTextField.swift | 2 | 4514 | //
// SYTextField.swift
// SYBlinkAnimationKit
//
// Created by Shohei Yokoyama on 12/13/2015.
// Copyright © 2015年 Shohei. All rights reserved.
//
import UIKit
@IBDesignable
public final class SYTextField: UITextField, AnimatableComponent {
public enum AnimationType: Int {
case border, borderWithShadow, background, ripple
}
@IBInspectable public var animationBorderColor = AnimationDefaultColor.border {
didSet {
syLayer.setBorderColor(animationBorderColor)
}
}
@IBInspectable public var animationBackgroundColor = AnimationDefaultColor.background {
didSet {
syLayer.setAnimationBackgroundColor(animationBackgroundColor)
}
}
@IBInspectable public var animationRippleColor = AnimationDefaultColor.ripple {
didSet {
syLayer.setRippleColor(animationRippleColor)
}
}
@IBInspectable public var animationTimingAdapter: Int {
get {
return animationTimingFunction.rawValue
}
set(index) {
animationTimingFunction = SYMediaTimingFunction(rawValue: index) ?? .linear
}
}
@IBInspectable public var animationDuration: CGFloat = 1.5 {
didSet {
syLayer.setAnimationDuration( CFTimeInterval(animationDuration) )
}
}
@IBInspectable public var animationAdapter: Int {
get {
return animationType.rawValue
}
set(index) {
animationType = AnimationType(rawValue: index) ?? .border
}
}
@IBInspectable public var stopAnimationWithTouch = true
override public var frame: CGRect {
didSet {
syLayer.resizeSuperLayer()
}
}
override public var bounds: CGRect {
didSet {
syLayer.resizeSuperLayer()
}
}
override public func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
if stopAnimationWithTouch && isAnimating {
stopAnimating()
}
return super.beginTracking(touch, with: event)
}
override public var borderStyle: UITextBorderStyle {
didSet {
self.layer.cornerRadius = {
switch borderStyle {
case .bezel, .line:
return CGFloat(0)
case .none, .roundedRect:
return CGFloat(5)
}
}()
}
}
override public var backgroundColor: UIColor? {
didSet {
if let backgroundColor = backgroundColor {
syLayer.setBackgroundColor(backgroundColor)
originalBackgroundColor = backgroundColor
}
}
}
public var isAnimating = false
public var animationTimingFunction: SYMediaTimingFunction = .linear {
didSet {
syLayer.setTimingFunction(animationTimingFunction)
}
}
public var animationType: AnimationType = .border {
didSet {
syLayer.animationType = {
switch animationType {
case .border:
return .border
case .borderWithShadow:
return .borderWithShadow
case .background:
return .background
case .ripple:
return .ripple
}
}()
}
}
fileprivate var originalBackgroundColor: UIColor = .white
fileprivate lazy var syLayer: SYLayer = .init(layer: self.layer)
// MARK: - initializer -
public override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
// MARK: - Public Methods -
public func startAnimating() {
isAnimating = true
if case (.background, .roundedRect) = (animationType, borderStyle) {
backgroundColor = .clear
}
syLayer.startAnimating()
}
public func stopAnimating() {
isAnimating = false
if case (.background, .roundedRect) = (animationType, borderStyle) {
backgroundColor = originalBackgroundColor
}
syLayer.stopAnimating()
}
// MARK: - Private Methods -
private func configure() {
syLayer.animationType = .border
borderStyle = .roundedRect
}
}
| mit | 717a13f01b206f37f8537ed828d27526 | 27.371069 | 91 | 0.576369 | 5.569136 | false | false | false | false |
stulevine/firefox-ios | Storage/SQL/SQLFavicons.swift | 1 | 2088 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
/**
* The sqlite-backed implementation of the favicons protocol.
*/
public class SQLiteFavicons : Favicons {
let files: FileAccessor
let db: BrowserDB
let table = JoinedFaviconsHistoryTable<(Site, Favicon)>()
lazy public var defaultIcon: UIImage = {
return UIImage(named: "defaultFavicon")!
}()
required public init(files: FileAccessor) {
self.files = files
self.db = BrowserDB(files: files)!
db.createOrUpdate(table)
}
public func clear(options: QueryOptions?, complete: ((success: Bool) -> Void)?) {
var err: NSError? = nil
let res = db.delete(&err) { (conn, inout err: NSError?) -> Int in
return self.table.delete(conn, item: nil, err: &err)
}
files.remove("favicons")
dispatch_async(dispatch_get_main_queue()) {
complete?(success: err == nil)
return
}
}
public func get(options: QueryOptions?, complete: (data: Cursor) -> Void) {
var err: NSError? = nil
let res = db.query(&err) { connection, err in
return self.table.query(connection, options: options)
}
dispatch_async(dispatch_get_main_queue()) {
complete(data: res)
}
}
public func add(icon: Favicon, site: Site, complete: ((success: Bool) -> Void)?) {
var err: NSError? = nil
let res = db.insert(&err) { (conn, inout err: NSError?) -> Int in
return self.table.insert(conn, item: (icon: icon, site: site), err: &err)
}
dispatch_async(dispatch_get_main_queue()) {
complete?(success: err == nil)
return
}
}
private let debug_enabled = false
private func debug(msg: String) {
if debug_enabled {
println("FaviconsSqlite: " + msg)
}
}
}
| mpl-2.0 | 9c78c466961c19a92f74c8ba6fee20a1 | 29.26087 | 86 | 0.588602 | 4.070175 | false | false | false | false |
UpWorks/stockprices | StockPrices/AppDelegate.swift | 1 | 6935 | //
// AppDelegate.swift
// StockPrices
//
// Created by Michael Updegraff on 1/30/15.
//
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.
self.setupAppAppearance()
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
var navigationController = UINavigationController()
var tabBarController = TabBarController()
navigationController.viewControllers = [tabBarController]
self.window!.rootViewController = navigationController
self.window!.makeKeyAndVisible()
return true
}
func setupAppAppearance()
{
UIApplication.sharedApplication().statusBarStyle = .LightContent
UINavigationBar.appearance().barTintColor = UIColor.blackColor()
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
UITabBar.appearance().barTintColor = UIColor.blackColor()
UITabBar.appearance().tintColor = UIColor.whiteColor()
UITabBar.appearance().selectionIndicatorImage = UIImage(named: "SelectedTabBackground")
}
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 "com.michaelupdegraff.StockPrices" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
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("StockPrices", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return 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
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("StockPrices.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as [NSObject : AnyObject])
// 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 \(error), \(error!.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
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// 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.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| mit | 6bd88bb9535b65397882d94c66972f79 | 50.37037 | 288 | 0.735689 | 5.740894 | false | false | false | false |
coderMONSTER/ioscelebrity | YStar/YStar/Scenes/Controller/MeetTypeDetailVC.swift | 1 | 2282 | //
// MeetTypeDetailVC.swift
// YStar
//
// Created by MONSTER on 2017/7/10.
// Copyright © 2017年 com.yundian. All rights reserved.
//
import UIKit
private let KMeetTypeDetailCellID = "MeetTypeDetailCell"
class MeetTypeDetailVC: BaseListTableViewController {
var items:[MeetTypeModel] = []
// MARK: - 初始化
override func viewDidLoad() {
super.viewDidLoad()
self.title = "约见类型管理"
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "地点", style: .done, target: self, action: #selector(rightItemButtonClick))
}
// 请求刷新数据
override func didRequest() {
didRequestComplete(items as AnyObject?)
}
// MARK: - UITableViewDataSource,UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let model = items[indexPath.row]
let param = ChangerMeetTypeRequest()
param.mid = model.mid
param.type = model.status == 0 ? 1 :0
AppAPIHelper.commen().changeOrderType(requestModel: param, complete: {[weak self] (result) in
if let response = result as? ResultModel{
if response.result == 1{
model.status = model.status == 0 ? 1 :0
self?.items[indexPath.row].status = model.status == 0 ? 1 :0
}
}
return nil
}, error: errorBlockFunc())
model.status = model.status == 0 ? 1 :0
tableView.reloadRows(at:[indexPath], with: .automatic)
tableView.deselectRow(at: indexPath, animated: true)
}
override func tableView(_ tableView: UITableView, cellIdentifierForRowAtIndexPath indexPath: IndexPath) -> String? {
return MeetTypeDetailCell.className()
}
// MARK: - 点击时间地点管理Action
func rightItemButtonClick() {
let timeAndPlaceVC = UIStoryboard.init(name:"Meet",bundle: nil).instantiateViewController(withIdentifier: "TimeAndPlaceVC") as! TimeAndPlaceVC
self.navigationController?.pushViewController(timeAndPlaceVC, animated: true)
}
@IBAction func completeButtonAction(_ sender: UIButton) {
}
}
| mit | 53e40356bff7efc953113b59d126209b | 30.394366 | 151 | 0.628982 | 4.672956 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/Extensions/NSLayoutConstraint-Extensions.swift | 1 | 1132 | //
// NSLayoutConstraint-Extensions.swift
// Habitica
//
// Created by Phillip Thelen on 21.02.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import UIKit
//https://stackoverflow.com/a/33003217
extension NSLayoutConstraint {
/**
Change multiplier constraint
- parameter multiplier: CGFloat
- returns: NSLayoutConstraint
*/
func setMultiplier(multiplier: CGFloat) -> NSLayoutConstraint? {
NSLayoutConstraint.deactivate([self])
guard let first = firstItem else {
return nil
}
let newConstraint = NSLayoutConstraint(
item: first,
attribute: firstAttribute,
relatedBy: relation,
toItem: secondItem,
attribute: secondAttribute,
multiplier: multiplier,
constant: constant)
newConstraint.priority = priority
newConstraint.shouldBeArchived = shouldBeArchived
newConstraint.identifier = identifier
NSLayoutConstraint.activate([newConstraint])
return newConstraint
}
}
| gpl-3.0 | 0941da12f84a1d1d7be80fe0d7e67ed0 | 25.302326 | 68 | 0.618921 | 5.8 | false | false | false | false |
kmalkic/LazyKit | LazyKit/Classes/LazyBaseOptions.swift | 1 | 9437 | //
// LazyBaseOptions.swift
// LazyKit
//
// Created by Kevin Malkic on 17/01/2016.
// Copyright © 2016 Kevin Malkic. All rights reserved.
//
import UIKit
//MARK: - Base options
///Structure for UIView base properties
public struct ViewBaseOptions {
/**
A string that identifies the element.
*/
public var accessibilityIdentifier: String?
/**
The view’s background color.
*/
public var backgroundColor: UIColor?
/**
The first nondefault tint color value in the view’s hierarchy, ascending from and starting with the view itself.
*/
public var tintColor: UIColor?
/**
The view’s alpha value.
*/
public var alpha: CGFloat?
/**
The width of the layer’s border.
*/
public var borderWidth: CGFloat?
/**
The color of the layer’s border.
*/
public var borderColor: UIColor?
/**
The radius of curvature for the plane’s corners.
*/
public var cornerRadius: CGFloat?
/**
A Boolean value that determines whether user events are ignored and removed from the event queue.
*/
public var userInteractionEnabled: Bool?
/**
A Boolean value that determines whether the view is hidden.
*/
public var hidden: Bool?
/**
Constructor
*/
public init(accessibilityIdentifier: String? = nil, backgroundColor: UIColor? = nil, tintColor: UIColor? = nil, alpha: CGFloat? = nil, borderWidth: CGFloat? = nil, borderColor: UIColor? = nil, cornerRadius: CGFloat? = nil, userInteractionEnabled: Bool? = nil, hidden: Bool? = nil) {
self.accessibilityIdentifier = accessibilityIdentifier
self.backgroundColor = backgroundColor
self.tintColor = tintColor
self.alpha = alpha
self.borderWidth = borderWidth
self.borderColor = borderColor
self.cornerRadius = cornerRadius
self.userInteractionEnabled = userInteractionEnabled
self.hidden = hidden
}
}
///Structure for UI elements that support UILabel base properties
public struct TextBaseOptions {
/**
The text displayed by the label.
*/
public var text: String?
/**
The font of the text.
*/
public var font: UIFont?
/**
The color of the text.
*/
public var textColor: UIColor?
/**
The technique to use for aligning the text.
*/
public var textAlignment: NSTextAlignment?
/**
The maximum number of lines to use for rendering text.
*/
public var numberOfLines: Int?
/**
A Boolean value indicating whether the font size should be reduced in order to fit the title string into the label’s bounding rectangle.
*/
public var adjustsFontSizeToFitWidth: Bool?
/**
The distance in points between the bottom of one line fragment and the top of the next.
*/
public var lineSpacing: CGFloat?
/**
The space after the end of the paragraph.
*/
public var paragraphSpacing: CGFloat?
/**
The indentation of the receiver’s lines other than the first.
*/
public var headIndent: CGFloat?
/**
The mode that should be used to break lines in the receiver.
*/
public var lineBreakMode: NSLineBreakMode?
/**
Constructor
*/
public init(text: String? = nil, font: UIFont? = nil, textColor: UIColor? = nil, textAlignment: NSTextAlignment? = nil, numberOfLines: Int? = nil, adjustsFontSizeToFitWidth: Bool? = nil, lineSpacing: CGFloat? = nil, paragraphSpacing: CGFloat? = nil, headIndent: CGFloat? = nil, lineBreakMode: NSLineBreakMode? = nil) {
self.text = text
self.font = font
self.textColor = textColor
self.textAlignment = textAlignment
self.numberOfLines = numberOfLines
self.adjustsFontSizeToFitWidth = adjustsFontSizeToFitWidth
self.lineSpacing = lineSpacing
self.paragraphSpacing = paragraphSpacing
self.headIndent = headIndent
self.lineBreakMode = lineBreakMode
}
}
///Structure for UI elements that support UIImageView base properties
public struct ImageBaseOptions {
/**
A flag used to determine how a view lays out its content when its bounds change.
*/
public var contentMode: UIViewContentMode?
/**
A color used to tint template images in the view hierarchy.
*/
public var tintColor: UIColor?
/**
The name of the file. If this is the first time the image is being loaded, the method looks for an image with the specified name in the application’s main bundle.
*/
public var imageNamed: String?
/**
Constructor
*/
public init(imageNamed: String? = nil, contentMode: UIViewContentMode? = nil, tintColor: UIColor? = nil) {
self.tintColor = tintColor
self.contentMode = contentMode
self.imageNamed = imageNamed
}
}
///Structure for UI elements that support Text inputs
public struct TextInputBaseOptions {
/**
The auto-capitalization style for the text object.
*/
public var autocapitalizationType: UITextAutocapitalizationType?
/**
The autocorrection style for the text object.
*/
public var autocorrectionType: UITextAutocorrectionType?
/**
The spell-checking style for the text object.
*/
public var spellCheckingType: UITextSpellCheckingType?
/**
The keyboard style associated with the text object.
*/
public var keyboardType: UIKeyboardType?
/**
The appearance style of the keyboard that is associated with the text object
*/
public var keyboardAppearance: UIKeyboardAppearance?
/**
The visible title of the Return key.
*/
public var returnKeyType: UIReturnKeyType?
/**
A Boolean value indicating whether the Return key is automatically enabled when the user is entering text.
*/
public var enablesReturnKeyAutomatically: Bool?
/**
Identifies whether the text object should hide the text being entered.
*/
public var secureTextEntry: Bool?
/**
Constructor
*/
public init(autocapitalizationType: UITextAutocapitalizationType? = nil, autocorrectionType: UITextAutocorrectionType? = nil, spellCheckingType: UITextSpellCheckingType? = nil, keyboardType: UIKeyboardType? = nil, keyboardAppearance: UIKeyboardAppearance? = nil, returnKeyType: UIReturnKeyType? = nil, enablesReturnKeyAutomatically: Bool? = nil, secureTextEntry: Bool? = nil) {
self.autocapitalizationType = autocapitalizationType
self.autocorrectionType = autocorrectionType
self.spellCheckingType = spellCheckingType
self.keyboardType = keyboardType
self.keyboardAppearance = keyboardAppearance
self.returnKeyType = returnKeyType
self.enablesReturnKeyAutomatically = enablesReturnKeyAutomatically
self.secureTextEntry = secureTextEntry
}
}
//MARK: - Operands
internal func + (left:ViewBaseOptions?, right:ViewBaseOptions? ) -> ViewBaseOptions? {
if left == nil && right == nil { return nil }
var object = ViewBaseOptions()
object.accessibilityIdentifier = right?.accessibilityIdentifier ?? left?.accessibilityIdentifier
object.backgroundColor = right?.backgroundColor ?? left?.backgroundColor
object.tintColor = right?.tintColor ?? left?.tintColor
object.alpha = right?.alpha ?? left?.alpha
object.borderWidth = right?.borderWidth ?? left?.borderWidth
object.borderColor = right?.borderColor ?? left?.borderColor
object.cornerRadius = right?.cornerRadius ?? left?.cornerRadius
object.userInteractionEnabled = right?.userInteractionEnabled ?? left?.userInteractionEnabled
object.hidden = right?.hidden ?? left?.hidden
return object
}
internal func + (left:TextBaseOptions?, right:TextBaseOptions? ) -> TextBaseOptions? {
if left == nil && right == nil { return nil }
var object = TextBaseOptions()
object.text = right?.text ?? left?.text
object.font = right?.font ?? left?.font
object.textColor = right?.textColor ?? left?.textColor
object.textAlignment = right?.textAlignment ?? left?.textAlignment
object.numberOfLines = right?.numberOfLines ?? left?.numberOfLines
object.adjustsFontSizeToFitWidth = right?.adjustsFontSizeToFitWidth ?? left?.adjustsFontSizeToFitWidth
object.lineSpacing = right?.lineSpacing ?? left?.lineSpacing
object.paragraphSpacing = right?.paragraphSpacing ?? left?.paragraphSpacing
object.headIndent = right?.headIndent ?? left?.headIndent
object.lineBreakMode = right?.lineBreakMode ?? left?.lineBreakMode
return object
}
internal func + (left:[LazyControlState: TextBaseOptions]?, right:[LazyControlState: TextBaseOptions]? ) -> [LazyControlState: TextBaseOptions]? {
return right ?? left
}
internal func + (left:[LazyControlState: ImageBaseOptions]?, right:[LazyControlState: ImageBaseOptions]? ) -> [LazyControlState: ImageBaseOptions]? {
return right ?? left
}
internal func + (left:ImageBaseOptions?, right:ImageBaseOptions? ) -> ImageBaseOptions? {
if left == nil && right == nil { return nil }
var object = ImageBaseOptions()
object.tintColor = right?.tintColor ?? left?.tintColor
object.contentMode = right?.contentMode ?? left?.contentMode
object.imageNamed = right?.imageNamed ?? left?.imageNamed
return object
}
| mit | 97495beeba2c2437e9f2ef214704f465 | 33.881481 | 381 | 0.68539 | 5.049866 | false | false | false | false |
slxl/ReactKit | ReactKit/Foundation/NSObject+Own.swift | 1 | 805 | //
// NSObject+Owner.swift
// ReactKit
//
// Created by Yasuhiro Inami on 2014/11/11.
// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//
import Foundation
private var owningStreamsKey: UInt8 = 0
internal extension NSObject {
internal typealias AnyStream = Any // NOTE: can't use Stream<Any?>
internal var _owningStreams: [AnyStream] {
get {
var owningStreams = objc_getAssociatedObject(self, &owningStreamsKey) as? [AnyStream]
if owningStreams == nil {
owningStreams = []
self._owningStreams = owningStreams!
}
return owningStreams!
}
set {
objc_setAssociatedObject(self, &owningStreamsKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
| mit | 17f8ed5cdca3b23c54df6620f0b8760e | 26.689655 | 107 | 0.616438 | 4.317204 | false | false | false | false |
Piwigo/Piwigo-Mobile | piwigoKit/Network/pwg.images/pwg.images.upload.swift | 1 | 5200 | //
// pwg.images.upload.swift
// piwigoKit
//
// Created by Eddy Lelièvre-Berna on 28/06/2020.
// Copyright © 2020 Piwigo.org. All rights reserved.
//
import Foundation
// MARK: - pwg.images.upload
public let kPiwigoImagesUpload = "format=json&method=pwg.images.upload"
public struct ImagesUploadJSON: Decodable {
public var status: String?
public var data = ImagesUpload(image_id: NSNotFound, square_src: "", src: "", name: "")
public var category = ImageCategory(catId: NSNotFound, catName: "", nbPhotos: NSNotFound)
public var errorCode = 0
public var errorMessage = ""
private enum RootCodingKeys: String, CodingKey {
case status = "stat"
case data = "result"
case errorCode = "err"
case errorMessage = "message"
}
private enum ResultCodingKeys: String, CodingKey {
case category
}
private enum CategoryCodingKeys: String, CodingKey {
case catId = "id"
case catName = "label"
case nbPhotos = "nb_photos"
}
private enum ErrorCodingKeys: String, CodingKey {
case code = "code"
case message = "msg"
}
public init(from decoder: Decoder) throws
{
do {
// Root container keyed by RootCodingKeys
guard let rootContainer = try? decoder.container(keyedBy: RootCodingKeys.self) else {
return
}
// dump(rootContainer)
// Status returned by Piwigo
status = try rootContainer.decodeIfPresent(String.self, forKey: .status)
if status == "ok"
{
// Decodes response from the data and store them in the array
data = try rootContainer.decodeIfPresent(ImagesUpload.self, forKey: .data) ?? ImagesUpload(image_id: NSNotFound, square_src: "", src: "", name: "")
// dump(data)
// Result container keyed by ResultCodingKeys
let resultContainer = try rootContainer.nestedContainer(keyedBy: ResultCodingKeys.self, forKey: .data)
// dump(resultContainer)
// Decodes derivatives
do {
try category = resultContainer.decode(ImageCategory.self, forKey: .category)
}
catch {
// Sometimes, nbPhotos is provided as String instead of Int!
var categoryStr = ImageCategoryStr(catId: NSNotFound, catName: "", nbPhotos: "")
try categoryStr = resultContainer.decode(ImageCategoryStr.self, forKey: .category)
if let nbPhotosStr = categoryStr.nbPhotos, let nbPhotos = Int(nbPhotosStr) {
category = ImageCategory(catId: categoryStr.catId,
catName: categoryStr.catName,
nbPhotos: nbPhotos)
}
}
}
else if status == "fail"
{
// Retrieve Piwigo server error
do {
// Retrieve Piwigo server error
errorCode = try rootContainer.decode(Int.self, forKey: .errorCode)
errorMessage = try rootContainer.decode(String.self, forKey: .errorMessage)
}
catch {
// Error container keyed by ErrorCodingKeys ("format=json" forgotten in call)
let errorContainer = try rootContainer.nestedContainer(keyedBy: ErrorCodingKeys.self, forKey: .errorCode)
errorCode = Int(try errorContainer.decode(String.self, forKey: .code)) ?? NSNotFound
errorMessage = try errorContainer.decode(String.self, forKey: .message)
}
}
else {
// Unexpected Piwigo server error
errorCode = -1
errorMessage = "Unexpected error encountered while calling server method with provided parameters."
}
} catch let error {
print(error.localizedDescription)
}
}
}
// MARK: - Result
public struct ImagesUpload: Decodable
{
public let image_id: Int? // 1042
public let square_src: String? // "https://…-sq.jpg"
public let src: String? // "https://…-th.jpg"
// The following data is not used yet
public let name: String? // "Delft - 01"
}
// MARK: - Category
public struct ImageCategory: Decodable {
public let catId: Int? // 140
public let catName: String? // "Essai"
public let nbPhotos: Int? // 7
public enum CodingKeys: String, CodingKey {
case catId = "id"
case catName = "label"
case nbPhotos = "nb_photos"
}
}
public struct ImageCategoryStr: Decodable {
public let catId: Int? // 140
public let catName: String? // "Essai"
public let nbPhotos: String? // "7"
public enum CodingKeys: String, CodingKey {
case catId = "id"
case catName = "label"
case nbPhotos = "nb_photos"
}
}
| mit | d0f4e0b9c42588fcd952bb89c583faad | 35.836879 | 163 | 0.559299 | 4.787097 | false | false | false | false |
AnthonyMDev/Nimble | Sources/Nimble/Utils/Await.swift | 1 | 13250 | import CoreFoundation
import Dispatch
import Foundation
#if canImport(CDispatch)
import CDispatch
#endif
private let timeoutLeeway = DispatchTimeInterval.milliseconds(1)
private let pollLeeway = DispatchTimeInterval.milliseconds(1)
/// Stores debugging information about callers
internal struct WaitingInfo: CustomStringConvertible {
let name: String
let file: FileString
let lineNumber: UInt
var description: String {
return "\(name) at \(file):\(lineNumber)"
}
}
internal protocol WaitLock {
func acquireWaitingLock(_ fnName: String, file: FileString, line: UInt)
func releaseWaitingLock()
func isWaitingLocked() -> Bool
}
internal class AssertionWaitLock: WaitLock {
private var currentWaiter: WaitingInfo?
init() { }
func acquireWaitingLock(_ fnName: String, file: FileString, line: UInt) {
let info = WaitingInfo(name: fnName, file: file, lineNumber: line)
let isMainThread = Thread.isMainThread
nimblePrecondition(
isMainThread,
"InvalidNimbleAPIUsage",
"\(fnName) can only run on the main thread."
)
nimblePrecondition(
currentWaiter == nil,
"InvalidNimbleAPIUsage",
"""
Nested async expectations are not allowed to avoid creating flaky tests.
The call to
\t\(info)
triggered this exception because
\t\(currentWaiter!)
is currently managing the main run loop.
"""
)
currentWaiter = info
}
func isWaitingLocked() -> Bool {
return currentWaiter != nil
}
func releaseWaitingLock() {
currentWaiter = nil
}
}
internal enum AwaitResult<T> {
/// Incomplete indicates None (aka - this value hasn't been fulfilled yet)
case incomplete
/// TimedOut indicates the result reached its defined timeout limit before returning
case timedOut
/// BlockedRunLoop indicates the main runloop is too busy processing other blocks to trigger
/// the timeout code.
///
/// This may also mean the async code waiting upon may have never actually ran within the
/// required time because other timers & sources are running on the main run loop.
case blockedRunLoop
/// The async block successfully executed and returned a given result
case completed(T)
/// When a Swift Error is thrown
case errorThrown(Error)
/// When an Objective-C Exception is raised
case raisedException(NSException)
func isIncomplete() -> Bool {
switch self {
case .incomplete: return true
default: return false
}
}
func isCompleted() -> Bool {
switch self {
case .completed: return true
default: return false
}
}
}
/// Holds the resulting value from an asynchronous expectation.
/// This class is thread-safe at receiving an "response" to this promise.
internal final class AwaitPromise<T> {
private(set) internal var asyncResult: AwaitResult<T> = .incomplete
private var signal: DispatchSemaphore
init() {
signal = DispatchSemaphore(value: 1)
}
deinit {
signal.signal()
}
/// Resolves the promise with the given result if it has not been resolved. Repeated calls to
/// this method will resolve in a no-op.
///
/// @returns a Bool that indicates if the async result was accepted or rejected because another
/// value was received first.
func resolveResult(_ result: AwaitResult<T>) -> Bool {
if signal.wait(timeout: .now()) == .success {
self.asyncResult = result
return true
} else {
return false
}
}
}
internal struct AwaitTrigger {
let timeoutSource: DispatchSourceTimer
let actionSource: DispatchSourceTimer?
let start: () throws -> Void
}
/// Factory for building fully configured AwaitPromises and waiting for their results.
///
/// This factory stores all the state for an async expectation so that Await doesn't
/// doesn't have to manage it.
internal class AwaitPromiseBuilder<T> {
let awaiter: Awaiter
let waitLock: WaitLock
let trigger: AwaitTrigger
let promise: AwaitPromise<T>
internal init(
awaiter: Awaiter,
waitLock: WaitLock,
promise: AwaitPromise<T>,
trigger: AwaitTrigger) {
self.awaiter = awaiter
self.waitLock = waitLock
self.promise = promise
self.trigger = trigger
}
func timeout(_ timeoutInterval: TimeInterval, forcefullyAbortTimeout: TimeInterval) -> Self {
// = Discussion =
//
// There's a lot of technical decisions here that is useful to elaborate on. This is
// definitely more lower-level than the previous NSRunLoop based implementation.
//
//
// Why Dispatch Source?
//
//
// We're using a dispatch source to have better control of the run loop behavior.
// A timer source gives us deferred-timing control without having to rely as much on
// a run loop's traditional dispatching machinery (eg - NSTimers, DefaultRunLoopMode, etc.)
// which is ripe for getting corrupted by application code.
//
// And unlike dispatch_async(), we can control how likely our code gets prioritized to
// executed (see leeway parameter) + DISPATCH_TIMER_STRICT.
//
// This timer is assumed to run on the HIGH priority queue to ensure it maintains the
// highest priority over normal application / test code when possible.
//
//
// Run Loop Management
//
// In order to properly interrupt the waiting behavior performed by this factory class,
// this timer stops the main run loop to tell the waiter code that the result should be
// checked.
//
// In addition, stopping the run loop is used to halt code executed on the main run loop.
trigger.timeoutSource.schedule(
deadline: DispatchTime.now() + timeoutInterval,
repeating: .never,
leeway: timeoutLeeway
)
trigger.timeoutSource.setEventHandler {
guard self.promise.asyncResult.isIncomplete() else { return }
let timedOutSem = DispatchSemaphore(value: 0)
let semTimedOutOrBlocked = DispatchSemaphore(value: 0)
semTimedOutOrBlocked.signal()
let runLoop = CFRunLoopGetMain()
#if canImport(Darwin)
let runLoopMode = CFRunLoopMode.defaultMode.rawValue
#else
let runLoopMode = kCFRunLoopDefaultMode
#endif
CFRunLoopPerformBlock(runLoop, runLoopMode) {
if semTimedOutOrBlocked.wait(timeout: .now()) == .success {
timedOutSem.signal()
semTimedOutOrBlocked.signal()
if self.promise.resolveResult(.timedOut) {
CFRunLoopStop(CFRunLoopGetMain())
}
}
}
// potentially interrupt blocking code on run loop to let timeout code run
CFRunLoopStop(runLoop)
let now = DispatchTime.now() + forcefullyAbortTimeout
let didNotTimeOut = timedOutSem.wait(timeout: now) != .success
let timeoutWasNotTriggered = semTimedOutOrBlocked.wait(timeout: .now()) == .success
if didNotTimeOut && timeoutWasNotTriggered {
if self.promise.resolveResult(.blockedRunLoop) {
CFRunLoopStop(CFRunLoopGetMain())
}
}
}
return self
}
/// Blocks for an asynchronous result.
///
/// @discussion
/// This function must be executed on the main thread and cannot be nested. This is because
/// this function (and it's related methods) coordinate through the main run loop. Tampering
/// with the run loop can cause undesirable behavior.
///
/// This method will return an AwaitResult in the following cases:
///
/// - The main run loop is blocked by other operations and the async expectation cannot be
/// be stopped.
/// - The async expectation timed out
/// - The async expectation succeeded
/// - The async expectation raised an unexpected exception (objc)
/// - The async expectation raised an unexpected error (swift)
///
/// The returned AwaitResult will NEVER be .incomplete.
func wait(_ fnName: String = #function, file: FileString = #file, line: UInt = #line) -> AwaitResult<T> {
waitLock.acquireWaitingLock(
fnName,
file: file,
line: line)
let capture = NMBExceptionCapture(handler: ({ exception in
_ = self.promise.resolveResult(.raisedException(exception))
}), finally: ({
self.waitLock.releaseWaitingLock()
}))
capture.tryBlock {
do {
try self.trigger.start()
} catch let error {
_ = self.promise.resolveResult(.errorThrown(error))
}
self.trigger.timeoutSource.resume()
while self.promise.asyncResult.isIncomplete() {
// Stopping the run loop does not work unless we run only 1 mode
_ = RunLoop.current.run(mode: .default, before: .distantFuture)
}
self.trigger.timeoutSource.cancel()
if let asyncSource = self.trigger.actionSource {
asyncSource.cancel()
}
}
return promise.asyncResult
}
}
internal class Awaiter {
let waitLock: WaitLock
let timeoutQueue: DispatchQueue
let asyncQueue: DispatchQueue
internal init(
waitLock: WaitLock,
asyncQueue: DispatchQueue,
timeoutQueue: DispatchQueue) {
self.waitLock = waitLock
self.asyncQueue = asyncQueue
self.timeoutQueue = timeoutQueue
}
private func createTimerSource(_ queue: DispatchQueue) -> DispatchSourceTimer {
return DispatchSource.makeTimerSource(flags: .strict, queue: queue)
}
func performBlock<T>(
file: FileString,
line: UInt,
_ closure: @escaping (@escaping (T) -> Void) throws -> Void
) -> AwaitPromiseBuilder<T> {
let promise = AwaitPromise<T>()
let timeoutSource = createTimerSource(timeoutQueue)
var completionCount = 0
let trigger = AwaitTrigger(timeoutSource: timeoutSource, actionSource: nil) {
try closure {
completionCount += 1
if completionCount < 2 {
if promise.resolveResult(.completed($0)) {
CFRunLoopStop(CFRunLoopGetMain())
}
} else {
fail("waitUntil(..) expects its completion closure to be only called once",
file: file, line: line)
}
}
}
return AwaitPromiseBuilder(
awaiter: self,
waitLock: waitLock,
promise: promise,
trigger: trigger)
}
func poll<T>(_ pollInterval: TimeInterval, closure: @escaping () throws -> T?) -> AwaitPromiseBuilder<T> {
let promise = AwaitPromise<T>()
let timeoutSource = createTimerSource(timeoutQueue)
let asyncSource = createTimerSource(asyncQueue)
let trigger = AwaitTrigger(timeoutSource: timeoutSource, actionSource: asyncSource) {
let interval = DispatchTimeInterval.nanoseconds(Int(pollInterval * TimeInterval(NSEC_PER_SEC)))
asyncSource.schedule(deadline: .now(), repeating: interval, leeway: pollLeeway)
asyncSource.setEventHandler {
do {
if let result = try closure() {
if promise.resolveResult(.completed(result)) {
CFRunLoopStop(CFRunLoopGetCurrent())
}
}
} catch let error {
if promise.resolveResult(.errorThrown(error)) {
CFRunLoopStop(CFRunLoopGetCurrent())
}
}
}
asyncSource.resume()
}
return AwaitPromiseBuilder(
awaiter: self,
waitLock: waitLock,
promise: promise,
trigger: trigger)
}
}
internal func pollBlock(
pollInterval: TimeInterval,
timeoutInterval: TimeInterval,
file: FileString,
line: UInt,
fnName: String = #function,
expression: @escaping () throws -> Bool) -> AwaitResult<Bool> {
let awaiter = NimbleEnvironment.activeInstance.awaiter
let result = awaiter.poll(pollInterval) { () throws -> Bool? in
if try expression() {
return true
}
return nil
}.timeout(timeoutInterval, forcefullyAbortTimeout: timeoutInterval / 2.0).wait(fnName, file: file, line: line)
return result
}
| apache-2.0 | 18a9a71380fcdc7202806a7b2dcc99da | 35.103542 | 118 | 0.603321 | 5.11583 | false | false | false | false |
blkbrds/intern09_final_project_tung_bien | MyApp/View/Controls/CustomCells/RecentTableViewCell/RecentTableViewCell.swift | 1 | 1088 | //
// RecentTableViewCell.swift
// MyApp
//
// Created by AST on 8/2/17.
// Copyright © 2017 Asian Tech Co., Ltd. All rights reserved.
//
import UIKit
import MVVM
class RecentTableViewCell: TableCell {
// MARK: - Properties
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var idLabel: UILabel!
@IBOutlet weak var statusOrderImageView: UIImageView!
@IBOutlet weak var statusOrderLabel: UILabel!
var viewModel: RecentCellViewModel? {
didSet {
updateView()
}
}
// MARK: - LifeCycle
override func awakeFromNib() {
super.awakeFromNib()
updateView()
}
// MARK: - Private
private func updateView() {
guard let viewModel = viewModel else { return }
if let date = viewModel.date?.toDate(format: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") {
dateLabel.text = date.toString(format: "HH:mm dd/MM/yyyy")
}
idLabel.text = "\(viewModel.id)"
statusOrderLabel.text = "\(viewModel.status)"
statusOrderImageView.image = viewModel.status.icon
}
}
| mit | 7b386787a12ea7ee770eba936cb35ed0 | 24.880952 | 86 | 0.624655 | 4.101887 | false | false | false | false |
hoffmanjon/SwiftyBones | Sources/SwiftyBones_Components/Sensors/SBTiltSensor.swift | 1 | 2946 | //
// SBTiltSensor.swift
// SwiftyBones Component Library
//
// Created by Jon Hoffman on 5/19/16.
//
/**
This type represents a tilt sensor connected to a Digital GPIO pin. The SBTiltSensor type is a value type
Initialize:
let tiltSensor = try SBTiltSensor(header: .P9, pin: 11, componentName: "Tilt Sensor")
or
let tileSensor = try SBTiltSensor(gpio: SBDigitalGPIO(id: "gpio30", direction: .IN), componentName: "Tilt Sensor")
Methods:
isTiltDetected() -> Bool?: true if the sensor is tilted.
*/
struct SBTiltSensor: SBComponentInProtocol {
let componentName: String
let gpio: SBDigitalGPIO
/**
Initlizes the SBTiltSensor type using a SBDigitalGPIO type and a name.
- Parameter gpio: An instances of a SBDigitalGPIO type
- Parameter componentName: A name for this instance that identifies it like "Tilt Sensor"
- Throws: ComponentErrors.InvalidGPIOType if the gpio parameter is not an instance of the SBDigitalGPIO type
*/
init(gpio: GPIO?,componentName: String) throws {
guard gpio != nil else {
throw ComponentErrors.GPIOCanNotBeNil
}
if let testGpio = gpio as? SBDigitalGPIO {
self.gpio = testGpio
self.componentName = componentName
} else {
throw ComponentErrors.InvalidGPIOType("/(componentName): Expecting SBDigitalGPIO Type")
}
}
/**
Initlizes the SBTiltSensor type using the pin defined by the header and pin parameters. The component name defines a name for the sensor.
- Parameter header: The header of the pin that the sensor is connected too
- Parameter pin: The pin that the sensor is connected too
- Parameter componentName: A name for this instance that identifies it like "Tilt Sensor"
- Throws: ComponentErrors.InvalidGPIOType if the gpio parameter is not an instance of the SBDigitalGPIO type
*/
init(header: BBExpansionHeader, pin: Int, componentName: String) throws {
if let gpio = SBDigitalGPIO(header: header, pin: pin, direction: .IN) {
self.gpio = gpio
self.componentName = componentName
} else {
throw ComponentErrors.GPIOCanNotBeNil
}
}
/**
The method retrieves the value of the GPIO pin that the sensor is connected to
Returns: a 1 for HIGH or a 0 for LOW
*/
func getRawValue() -> Int? {
if let value = gpio.getValue() {
return (value == DigitalGPIOValue.HIGH) ? 1 : 0
} else {
return nil
}
}
/**
Determines if the tilt sensor is tilted
Returns: a true value if the sensor is tilted or false if there isn't. Will return nil if there was an error reading the sensor.
*/
func isTiltDetected() -> Bool? {
if let value = getRawValue() {
return (value == 0) ? true : false
} else {
return nil
}
}
}
| mit | 2360153e09d18298d338a673c124e0c1 | 36.769231 | 143 | 0.649695 | 4.251082 | false | false | false | false |
JaSpa/swift | test/SILGen/guaranteed_self.swift | 2 | 25602 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module | %FileCheck %s
protocol Fooable {
init()
func foo(_ x: Int)
mutating func bar()
mutating func bas()
var prop1: Int { get set }
var prop2: Int { get set }
var prop3: Int { get nonmutating set }
}
protocol Barrable: class {
init()
func foo(_ x: Int)
func bar()
func bas()
var prop1: Int { get set }
var prop2: Int { get set }
var prop3: Int { get set }
}
struct S: Fooable {
var x: C? // Make the type nontrivial, so +0/+1 is observable.
// CHECK-LABEL: sil hidden @_T015guaranteed_self1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin S.Type) -> @owned S
init() {}
// TODO: Way too many redundant r/r pairs here. Should use +0 rvalues.
// CHECK-LABEL: sil hidden @_T015guaranteed_self1SV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed S) -> () {
// CHECK: bb0({{.*}} [[SELF:%.*]] : $S):
// CHECK-NOT: copy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
func foo(_ x: Int) {
self.foo(x)
}
func foooo(_ x: (Int, Bool)) {
self.foooo(x)
}
// CHECK-LABEL: sil hidden @_T015guaranteed_self1SV3bar{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout S) -> ()
// CHECK: bb0([[SELF:%.*]] : $*S):
// CHECK-NOT: destroy_addr [[SELF]]
mutating func bar() {
self.bar()
}
// CHECK-LABEL: sil hidden @_T015guaranteed_self1SV3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed S) -> ()
// CHECK: bb0([[SELF:%.*]] : $S):
// CHECK-NOT: copy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
func bas() {
self.bas()
}
var prop1: Int = 0
var prop2: Int {
// CHECK-LABEL: sil hidden @_T015guaranteed_self1SV5prop2Sifg : $@convention(method) (@guaranteed S) -> Int
// CHECK: bb0([[SELF:%.*]] : $S):
// CHECK-NOT: destroy_value [[SELF]]
get { return 0 }
// CHECK-LABEL: sil hidden @_T015guaranteed_self1SV5prop2Sifs : $@convention(method) (Int, @inout S) -> ()
// CHECK-LABEL: sil hidden [transparent] @_T015guaranteed_self1SV5prop2Sifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
set { }
}
var prop3: Int {
// CHECK-LABEL: sil hidden @_T015guaranteed_self1SV5prop3Sifg : $@convention(method) (@guaranteed S) -> Int
// CHECK: bb0([[SELF:%.*]] : $S):
// CHECK-NOT: destroy_value [[SELF]]
get { return 0 }
// CHECK-LABEL: sil hidden @_T015guaranteed_self1SV5prop3Sifs : $@convention(method) (Int, @guaranteed S) -> ()
// CHECK: bb0({{.*}} [[SELF:%.*]] : $S):
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-LABEL: sil hidden [transparent] @_T015guaranteed_self1SV5prop3Sifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: bb0({{.*}} [[SELF:%.*]] : $S):
// CHECK-NOT: destroy_value [[SELF]]
nonmutating set { }
}
// Getter for prop1
// CHECK-LABEL: sil hidden [transparent] @_T015guaranteed_self1SV5prop1Sifg : $@convention(method) (@guaranteed S) -> Int
// CHECK: bb0([[SELF:%.*]] : $S):
// CHECK-NOT: destroy_value [[SELF]]
// Setter for prop1
// CHECK-LABEL: sil hidden [transparent] @_T015guaranteed_self1SV5prop1Sifs : $@convention(method) (Int, @inout S) -> ()
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: load [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// materializeForSet for prop1
// CHECK-LABEL: sil hidden [transparent] @_T015guaranteed_self1SV5prop1Sifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: load [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
}
// Witness thunk for nonmutating 'foo'
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableAaaDP3foo{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (Int, @in_guaranteed S) -> () {
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF_COPY:%.*]] = alloc_stack $S
// CHECK: copy_addr [[SELF_ADDR]] to [initialization] [[SELF_COPY]]
// CHECK: [[SELF:%.*]] = load [take] [[SELF_COPY]]
// CHECK: destroy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_COPY]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for mutating 'bar'
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableAaaDP3bar{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@inout S) -> () {
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: load [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for 'bas', which is mutating in the protocol, but nonmutating
// in the implementation
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableAaaDP3bas{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@inout S) -> ()
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF:%.*]] = load [copy] [[SELF_ADDR]]
// CHECK: destroy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
// Witness thunk for prop1 getter
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableAaaDP5prop1SifgTW : $@convention(witness_method) (@in_guaranteed S) -> Int
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF_COPY:%.*]] = alloc_stack $S
// CHECK: copy_addr [[SELF_ADDR]] to [initialization] [[SELF_COPY]]
// CHECK: [[SELF:%.*]] = load [take] [[SELF_COPY]]
// CHECK: destroy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_COPY]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop1 setter
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableAaaDP5prop1SifsTW : $@convention(witness_method) (Int, @inout S) -> () {
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop1 materializeForSet
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableAaaDP5prop1SifmTW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop2 getter
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableAaaDP5prop2SifgTW : $@convention(witness_method) (@in_guaranteed S) -> Int
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF_COPY:%.*]] = alloc_stack $S
// CHECK: copy_addr [[SELF_ADDR]] to [initialization] [[SELF_COPY]]
// CHECK: [[SELF:%.*]] = load [take] [[SELF_COPY]]
// CHECK: destroy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_COPY]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop2 setter
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableAaaDP5prop2SifsTW : $@convention(witness_method) (Int, @inout S) -> () {
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop2 materializeForSet
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableAaaDP5prop2SifmTW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop3 getter
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableAaaDP5prop3SifgTW : $@convention(witness_method) (@in_guaranteed S) -> Int
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF_COPY:%.*]] = alloc_stack $S
// CHECK: copy_addr [[SELF_ADDR]] to [initialization] [[SELF_COPY]]
// CHECK: [[SELF:%.*]] = load [take] [[SELF_COPY]]
// CHECK: destroy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_COPY]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop3 nonmutating setter
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableAaaDP5prop3SifsTW : $@convention(witness_method) (Int, @in_guaranteed S) -> ()
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF_COPY:%.*]] = alloc_stack $S
// CHECK: copy_addr [[SELF_ADDR]] to [initialization] [[SELF_COPY]]
// CHECK: [[SELF:%.*]] = load [take] [[SELF_COPY]]
// CHECK: destroy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_COPY]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop3 nonmutating materializeForSet
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableAaaDP5prop3SifmTW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF:%.*]] = load [copy] [[SELF_ADDR]]
// CHECK: destroy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: }
//
// TODO: Expected output for the other cases
//
struct AO<T>: Fooable {
var x: T?
init() {}
// CHECK-LABEL: sil hidden @_T015guaranteed_self2AOV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) <T> (Int, @in_guaranteed AO<T>) -> ()
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*AO<T>):
// CHECK-NOT: copy_addr
// CHECK: apply {{.*}} [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// CHECK: }
func foo(_ x: Int) {
self.foo(x)
}
mutating func bar() {
self.bar()
}
// CHECK-LABEL: sil hidden @_T015guaranteed_self2AOV3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) <T> (@in_guaranteed AO<T>) -> ()
// CHECK: bb0([[SELF_ADDR:%.*]] : $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
func bas() {
self.bas()
}
var prop1: Int = 0
var prop2: Int {
// CHECK-LABEL: sil hidden @_T015guaranteed_self2AOV5prop2Sifg : $@convention(method) <T> (@in_guaranteed AO<T>) -> Int {
// CHECK: bb0([[SELF_ADDR:%.*]] : $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
get { return 0 }
set { }
}
var prop3: Int {
// CHECK-LABEL: sil hidden @_T015guaranteed_self2AOV5prop3Sifg : $@convention(method) <T> (@in_guaranteed AO<T>) -> Int
// CHECK: bb0([[SELF_ADDR:%.*]] : $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
get { return 0 }
// CHECK-LABEL: sil hidden @_T015guaranteed_self2AOV5prop3Sifs : $@convention(method) <T> (Int, @in_guaranteed AO<T>) -> ()
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// CHECK-LABEL: sil hidden [transparent] @_T015guaranteed_self2AOV5prop3Sifm : $@convention(method) <T> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed AO<T>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// CHECK: }
nonmutating set { }
}
}
// Witness for nonmutating 'foo'
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T015guaranteed_self2AOVyxGAA7FooableAAlAaDP3foo{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0> (Int, @in_guaranteed AO<τ_0_0>) -> ()
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*AO<τ_0_0>):
// TODO: This copy isn't necessary.
// CHECK: copy_addr [[SELF_ADDR]] to [initialization] [[SELF_COPY:%.*]] :
// CHECK: apply {{.*}} [[SELF_COPY]]
// CHECK: destroy_addr [[SELF_COPY]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness for 'bar', which is mutating in protocol but nonmutating in impl
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T015guaranteed_self2AOVyxGAA7FooableAAlAaDP3bar{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) <τ_0_0> (@inout AO<τ_0_0>) -> ()
// CHECK: bb0([[SELF_ADDR:%.*]] : $*AO<τ_0_0>):
// -- NB: This copy *is* necessary, unless we're willing to assume an inout
// parameter is not mutably aliased.
// CHECK: copy_addr [[SELF_ADDR]] to [initialization] [[SELF_COPY:%.*]] :
// CHECK: apply {{.*}} [[SELF_COPY]]
// CHECK: destroy_addr [[SELF_COPY]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
class C: Fooable, Barrable {
// Allocating initializer
// CHECK-LABEL: sil hidden @_T015guaranteed_self1CC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick C.Type) -> @owned C
// CHECK: [[SELF1:%.*]] = alloc_ref $C
// CHECK-NOT: [[SELF1]]
// CHECK: [[SELF2:%.*]] = apply {{.*}}([[SELF1]])
// CHECK-NOT: [[SELF2]]
// CHECK: return [[SELF2]]
// Initializing constructors still have the +1 in, +1 out convention.
// CHECK-LABEL: sil hidden @_T015guaranteed_self1CC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned C) -> @owned C {
// CHECK: bb0([[SELF:%.*]] : $C):
// CHECK: [[MARKED_SELF:%.*]] = mark_uninitialized [rootself] [[SELF]]
// CHECK: [[MARKED_SELF_RESULT:%.*]] = copy_value [[MARKED_SELF]]
// CHECK: destroy_value [[MARKED_SELF]]
// CHECK: return [[MARKED_SELF_RESULT]]
// CHECK: } // end sil function '_T015guaranteed_self1CC{{[_0-9a-zA-Z]*}}fc'
// @objc thunk for initializing constructor
// CHECK-LABEL: sil hidden [thunk] @_T015guaranteed_self1CC{{[_0-9a-zA-Z]*}}fcTo : $@convention(objc_method) (@owned C) -> @owned C
// CHECK: bb0([[SELF:%.*]] : $C):
// CHECK-NOT: copy_value [[SELF]]
// CHECK: [[SELF2:%.*]] = apply {{%.*}}([[SELF]])
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF2]]
// CHECK: return [[SELF2]]
// CHECK: } // end sil function '_T015guaranteed_self1CC{{[_0-9a-zA-Z]*}}fcTo'
@objc required init() {}
// CHECK-LABEL: sil hidden @_T015guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed C) -> ()
// CHECK: bb0({{.*}} [[SELF:%.*]] : $C):
// CHECK-NOT: copy_value
// CHECK-NOT: destroy_value
// CHECK: } // end sil function '_T015guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden [thunk] @_T015guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (Int, C) -> () {
// CHECK: bb0({{.*}} [[SELF:%.*]] : $C):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: apply {{.*}}({{.*}}, [[SELF_COPY]])
// CHECK: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: } // end sil function '_T015guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}FTo'
@objc func foo(_ x: Int) {
self.foo(x)
}
@objc func bar() {
self.bar()
}
@objc func bas() {
self.bas()
}
// CHECK-LABEL: sil hidden [thunk] @_T015guaranteed_self1CC5prop1SifgTo : $@convention(objc_method) (C) -> Int
// CHECK: bb0([[SELF:%.*]] : $C):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: apply {{.*}}([[SELF_COPY]])
// CHECK: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF_COPY]]
// CHECK-LABEL: sil hidden [thunk] @_T015guaranteed_self1CC5prop1SifsTo : $@convention(objc_method) (Int, C) -> ()
// CHECK: bb0({{.*}} [[SELF:%.*]] : $C):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: apply {{.*}} [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: }
@objc var prop1: Int = 0
@objc var prop2: Int {
get { return 0 }
set {}
}
@objc var prop3: Int {
get { return 0 }
set {}
}
}
class D: C {
// CHECK-LABEL: sil hidden @_T015guaranteed_self1DC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick D.Type) -> @owned D
// CHECK: [[SELF1:%.*]] = alloc_ref $D
// CHECK-NOT: [[SELF1]]
// CHECK: [[SELF2:%.*]] = apply {{.*}}([[SELF1]])
// CHECK-NOT: [[SELF1]]
// CHECK-NOT: [[SELF2]]
// CHECK: return [[SELF2]]
// CHECK-LABEL: sil hidden @_T015guaranteed_self1DC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned D) -> @owned D
// CHECK: bb0([[SELF:%.*]] : $D):
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var D }
// CHECK-NEXT: [[PB:%.*]] = project_box [[SELF_BOX]]
// CHECK-NEXT: [[SELF_ADDR:%.*]] = mark_uninitialized [derivedself] [[PB]]
// CHECK-NEXT: store [[SELF]] to [init] [[SELF_ADDR]]
// CHECK-NOT: [[SELF_ADDR]]
// CHECK: [[SELF1:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NEXT: [[SUPER1:%.*]] = upcast [[SELF1]]
// CHECK-NOT: [[SELF_ADDR]]
// CHECK: [[SUPER2:%.*]] = apply {{.*}}([[SUPER1]])
// CHECK-NEXT: [[SELF2:%.*]] = unchecked_ref_cast [[SUPER2]]
// CHECK-NEXT: store [[SELF2]] to [init] [[SELF_ADDR]]
// CHECK-NOT: [[SELF_ADDR]]
// CHECK-NOT: [[SELF1]]
// CHECK-NOT: [[SUPER1]]
// CHECK-NOT: [[SELF2]]
// CHECK-NOT: [[SUPER2]]
// CHECK: [[SELF_FINAL:%.*]] = load [copy] [[SELF_ADDR]]
// CHECK-NEXT: destroy_value [[SELF_BOX]]
// CHECK-NEXT: return [[SELF_FINAL]]
required init() {
super.init()
}
// CHECK-LABEL: sil shared [transparent] [thunk] @_T015guaranteed_self1DC3foo{{[_0-9a-zA-Z]*}}FTD : $@convention(method) (Int, @guaranteed D) -> ()
// CHECK: bb0({{.*}} [[SELF:%.*]]):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: }
dynamic override func foo(_ x: Int) {
self.foo(x)
}
}
func S_curryThunk(_ s: S) -> ((S) -> (Int) -> ()/*, Int -> ()*/) {
return (S.foo /*, s.foo*/)
}
func AO_curryThunk<T>(_ ao: AO<T>) -> ((AO<T>) -> (Int) -> ()/*, Int -> ()*/) {
return (AO.foo /*, ao.foo*/)
}
// ----------------------------------------------------------------------------
// Make sure that we properly translate in_guaranteed parameters
// correctly if we are asked to.
// ----------------------------------------------------------------------------
// CHECK-LABEL: sil [transparent] [thunk] @_T015guaranteed_self9FakeArrayVAA8SequenceAaaDP17_constrainElement{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method) (@in FakeElement, @in_guaranteed FakeArray) -> () {
// CHECK: bb0([[ARG0_PTR:%.*]] : $*FakeElement, [[ARG1_PTR:%.*]] : $*FakeArray):
// CHECK: [[GUARANTEED_COPY_STACK_SLOT:%.*]] = alloc_stack $FakeArray
// CHECK: copy_addr [[ARG1_PTR]] to [initialization] [[GUARANTEED_COPY_STACK_SLOT]]
// CHECK: [[ARG0:%.*]] = load [trivial] [[ARG0_PTR]]
// CHECK: function_ref (extension in guaranteed_self):guaranteed_self.SequenceDefaults._constrainElement
// CHECK: [[FUN:%.*]] = function_ref @_{{.*}}
// CHECK: apply [[FUN]]<FakeArray>([[ARG0]], [[GUARANTEED_COPY_STACK_SLOT]])
// CHECK: destroy_addr [[GUARANTEED_COPY_STACK_SLOT]]
class Z {}
public struct FakeGenerator {}
public struct FakeArray {
var z = Z()
}
public struct FakeElement {}
public protocol FakeGeneratorProtocol {
associatedtype Element
}
extension FakeGenerator : FakeGeneratorProtocol {
public typealias Element = FakeElement
}
public protocol SequenceDefaults {
associatedtype Element
associatedtype Generator : FakeGeneratorProtocol
}
extension SequenceDefaults {
public final func _constrainElement(_: FakeGenerator.Element) {}
}
public protocol Sequence : SequenceDefaults {
func _constrainElement(_: Element)
}
extension FakeArray : Sequence {
public typealias Element = FakeElement
public typealias Generator = FakeGenerator
func _containsElement(_: Element) {}
}
// -----------------------------------------------------------------------------
// Make sure that we do not emit extra copy_values when accessing let fields of
// guaranteed parameters.
// -----------------------------------------------------------------------------
class Kraken {
func enrage() {}
}
func destroyShip(_ k: Kraken) {}
class LetFieldClass {
let letk = Kraken()
var vark = Kraken()
// CHECK-LABEL: sil hidden @_T015guaranteed_self13LetFieldClassC10letkMethod{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed LetFieldClass) -> () {
// CHECK: bb0([[CLS:%.*]] : $LetFieldClass):
// CHECK: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk
// CHECK-NEXT: [[KRAKEN:%.*]] = load_borrow [[KRAKEN_ADDR]]
// CHECK-NEXT: [[KRAKEN_METH:%.*]] = class_method [[KRAKEN]]
// CHECK-NEXT: apply [[KRAKEN_METH]]([[KRAKEN]])
// CHECK-NEXT: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk
// CHECK-NEXT: [[KRAKEN:%.*]] = load [copy] [[KRAKEN_ADDR]]
// CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> ()
// CHECK-NEXT: [[KRAKEN_COPY:%.*]] = copy_value [[KRAKEN]]
// CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]])
// CHECK-NEXT: [[KRAKEN_BOX:%.*]] = alloc_box ${ var Kraken }
// CHECK-NEXT: [[PB:%.*]] = project_box [[KRAKEN_BOX]]
// CHECK-NEXT: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk
// CHECK-NEXT: [[KRAKEN2:%.*]] = load [copy] [[KRAKEN_ADDR]]
// CHECK-NEXT: store [[KRAKEN2]] to [init] [[PB]]
// CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> ()
// CHECK-NEXT: [[KRAKEN_COPY:%.*]] = load [copy] [[PB]]
// CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]])
// CHECK-NEXT: destroy_value [[KRAKEN_BOX]]
// CHECK-NEXT: destroy_value [[KRAKEN]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
func letkMethod() {
letk.enrage()
let ll = letk
destroyShip(ll)
var lv = letk
destroyShip(lv)
}
// CHECK-LABEL: sil hidden @_T015guaranteed_self13LetFieldClassC10varkMethod{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed LetFieldClass) -> () {
// CHECK: bb0([[CLS:%.*]] : $LetFieldClass):
// CHECK: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter.1 : (LetFieldClass) -> () -> Kraken , $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken
// CHECK-NEXT: [[KRAKEN:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]])
// CHECK-NEXT: [[KRAKEN_METH:%.*]] = class_method [[KRAKEN]]
// CHECK-NEXT: apply [[KRAKEN_METH]]([[KRAKEN]])
// CHECK-NEXT: destroy_value [[KRAKEN]]
// CHECK-NEXT: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter.1 : (LetFieldClass) -> () -> Kraken , $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken
// CHECK-NEXT: [[KRAKEN:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]])
// CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> ()
// CHECK-NEXT: [[KRAKEN_COPY:%.*]] = copy_value [[KRAKEN]]
// CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]])
// CHECK-NEXT: [[KRAKEN_BOX:%.*]] = alloc_box ${ var Kraken }
// CHECK-NEXT: [[PB:%.*]] = project_box [[KRAKEN_BOX]]
// CHECK-NEXT: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter.1 : (LetFieldClass) -> () -> Kraken , $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken
// CHECK-NEXT: [[KRAKEN2:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]])
// CHECK-NEXT: store [[KRAKEN2]] to [init] [[PB]]
// CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> ()
// CHECK-NEXT: [[KRAKEN_COPY:%.*]] = load [copy] [[PB]]
// CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]])
// CHECK-NEXT: destroy_value [[KRAKEN_BOX]]
// CHECK-NEXT: destroy_value [[KRAKEN]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
func varkMethod() {
vark.enrage()
let vl = vark
destroyShip(vl)
var vv = vark
destroyShip(vv)
}
}
// -----------------------------------------------------------------------------
// Make sure that in all of the following cases find has only one copy_value in it.
// -----------------------------------------------------------------------------
class ClassIntTreeNode {
let value : Int
let left, right : ClassIntTreeNode
init() {}
// CHECK-LABEL: sil hidden @_T015guaranteed_self16ClassIntTreeNodeC4find{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed ClassIntTreeNode) -> @owned ClassIntTreeNode {
// CHECK-NOT: destroy_value
// CHECK: copy_value
// CHECK-NOT: copy_value
// CHECK-NOT: destroy_value
// CHECK: return
func find(_ v : Int) -> ClassIntTreeNode {
if v == value { return self }
if v < value { return left.find(v) }
return right.find(v)
}
}
| apache-2.0 | 4238ff0c90f21292f9195399c04577d6 | 44.953321 | 252 | 0.585795 | 3.394695 | false | false | false | false |
lionheart/LionheartExtensions | Pod/Classes/File.swift | 1 | 2978 | //
// Copyright 2016 Lionheart Software LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
public final class File {
public var filename: String?
public init(_ filename: String) {
self.filename = filename
}
/// The file's full path contained with the documents directory, or `nil` if it does not exist.
lazy var documentsPath: String? = {
let paths: [NSString] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as [NSString]
guard let path = paths.first,
let filename = self.filename else {
return nil
}
return path.appendingPathComponent(filename)
}()
/// The file's full path contained within the bundle, or `nil` if `filename` is `nil`.
var bundlePath: String? {
let bundle = Bundle.main
guard let filename = filename else {
return nil
}
let components = filename.components(separatedBy: ".")
return bundle.path(forResource: components[0], ofType: components[1])
}
/// Returns the file's contents as a `String`.
func read() -> String? {
guard let path = documentsPath ?? bundlePath else {
return nil
}
return try? String(contentsOfFile: path, encoding: .utf8)
}
/// A boolean that indicates whether `self` is contained within the app bundle.
var existsInBundle: Bool {
guard let path = bundlePath else {
return false
}
return FileManager.default.fileExists(atPath: path)
}
/// A boolean that indicates whether `self` is contained within the documents directory.
var existsInDocuments: Bool {
guard let path = documentsPath else {
return false
}
return FileManager.default.fileExists(atPath: path)
}
}
extension File: ExpressibleByStringLiteral {
public typealias StringLiteralType = String
public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
public typealias UnicodeScalarLiteralType = StringLiteralType
public convenience init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
self.init(value)
}
public convenience init(stringLiteral value: StringLiteralType) {
self.init(value)
}
public convenience init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
self.init(value)
}
}
| apache-2.0 | c4fa7593635fbe7cd648f14f2f6d1a7f | 31.369565 | 124 | 0.674614 | 4.963333 | false | false | false | false |
sebastiangrail/Mars-Orbiter | MarsOrbiter/MultidimensionalUnits.swift | 1 | 1462 | //
// MultidimensionalUnits.swift
// MarsOrbiter
//
// Created by Sebastian Grail on 20/02/2016.
// Copyright © 2016 Sebastian Grail. All rights reserved.
//
public enum One {}
public enum Two {}
public enum Three {}
// MARK: - Converting Product<T,T> and 2-dimensional unit with same base as T
public extension Unit where Trait: ProductTraitType, Trait.Left == Trait.Right, Trait.Left.Dimension == One {
func to <U: UnitTrait where U.BaseTrait == Trait.Left.BaseTrait, U.Dimension == Two>
(type: Unit<U>.Type) -> Unit<U>
{
return Unit<U>(value * Trait.Left.toBaseUnit() * Trait.Left.toBaseUnit() / U.toBaseUnit())
}
}
public extension Unit where Trait.Dimension == Two {
func to <U: ProductTraitType where U.Left == U.Right, U.Left.Dimension == One, U.Left.BaseTrait == Trait.BaseTrait>
(type: Unit<U>.Type) -> Unit<U>
{
return Unit<U>(value * Trait.toBaseUnit() / (U.Left.toBaseUnit() * U.Right.toBaseUnit()))
}
}
public extension Unit
where Trait: ProductTraitType,
Trait.Left: ProductTraitType,
Trait.Left.Left == Trait.Left.Right,
Trait.Left.Right == Trait.Right,
Trait.Right.Dimension == One
{
func to <U: UnitTrait where U.BaseTrait == Trait.Right.BaseTrait, U.Dimension == Three> (type: Unit<U>.Type) -> Unit<U> {
return Unit<U>(value * Trait.Right.toBaseUnit() * Trait.Right.toBaseUnit() * Trait.Right.toBaseUnit() / U.toBaseUnit())
}
}
| mit | e3d98817369ec6bdb47509a99cd3be40 | 35.525 | 128 | 0.657084 | 3.397674 | false | false | false | false |
kevinzhow/PNChart-Swift | PNChartSwift/Source/PNLineChart.swift | 1 | 20975 | //
// PNLineChart.swift
// PNChartSwift
//
// Created by YiChen Zhou on 11/10/16.
// Copyright © 2016 YiChen Zhou. All rights reserved.
//
import UIKit
import QuartzCore
class PNLineChart: UIView{
public var xLabels: NSArray = []{
didSet {
if self.showLabel {
self.xLabelWidth = self.chartCavanWidth/CGFloat(self.xLabels.count)
for index in 0..<self.xLabels.count {
let labelText = self.xLabels[index] as! String
let labelX = 2 * self.chartMargin + (CGFloat(index) * self.xLabelWidth) - (self.xLabelWidth/2)
let label: PNChartLabel = PNChartLabel(frame: CGRect(x: CGFloat(labelX), y: CGFloat(self.chartMargin + self.chartCavanHeight), width: CGFloat(self.xLabelWidth), height: CGFloat(self.chartMargin)))
label.textAlignment = NSTextAlignment.center
label.text = labelText
self.addSubview(label)
}
} else {
self.xLabelWidth = frame.size.width / CGFloat(self.xLabels.count)
}
}
}
public var yLabels: NSArray = []{
didSet {
self.yLabelNum = CGFloat(self.yLabels.count)
let ySetp: CGFloat = (self.yValueMax - self.yValueMin) / CGFloat(self.yLabelNum)
let yStepHeight: CGFloat = self.chartCavanHeight / CGFloat(self.yLabelNum)
var index: CGFloat = 0
for _ in yLabels {
let labelY = self.chartCavanHeight - (index * yStepHeight)
let label: PNChartLabel = PNChartLabel(frame: CGRect(x: CGFloat(0), y: labelY, width: self.chartMargin + 5, height: CGFloat(yLabelHeight)))
label.textAlignment = .right
label.text = String(format: self.yLabelFormat, Double(self.yValueMin + (ySetp * index)))
index += 1
self.addSubview(label)
}
}
}
// Array of LineChartData objects, one for eacg line
public var chartData: NSArray = []{
didSet{
let yLabelsArray: NSMutableArray = NSMutableArray(capacity: self.chartData.count)
var yMax: CGFloat = 0
var yMin: CGFloat = CGFloat.infinity
var yValue: CGFloat!
// remove all shape layers before adding new ones
for layer in self.chartLineArray {
(layer as! CALayer).removeFromSuperlayer()
}
for layer in self.chartPointArray {
(layer as! CALayer).removeFromSuperlayer()
}
self.chartLineArray = NSMutableArray(capacity: self.chartData.count)
self.chartPointArray = NSMutableArray(capacity: self.chartData.count)
// Set for point stroken
let circleStrokeWidth: CGFloat = 2
let lineWidth: CGFloat = 3
for chart in self.chartData {
// Create as many chart line layers as number of data
let chartObj = chart as! PNLineChartData
let chartLine: CAShapeLayer = CAShapeLayer()
chartLine.lineCap = kCALineCapButt
chartLine.lineJoin = kCALineJoinMiter
chartLine.fillColor = UIColor.white.cgColor
chartLine.lineWidth = lineWidth
chartLine.strokeEnd = 0
layer.addSublayer(chartLine)
self.chartLineArray.add(chartLine)
// Create as many chart point layers as number of data
let pointLayer: CAShapeLayer = CAShapeLayer()
pointLayer.strokeColor = chartObj.color.cgColor
pointLayer.lineCap = kCALineCapRound
pointLayer.lineJoin = kCALineJoinBevel
pointLayer.fillColor = nil
pointLayer.lineWidth = circleStrokeWidth
layer.addSublayer(pointLayer)
self.chartPointArray.add(pointLayer)
for index in 0..<chartObj.itemCount {
yValue = CGFloat(chartObj.getData(index).y)
yLabelsArray.add(String(format: "%2f", yValue))
yMax = fmax(yMax, yValue)
yMin = fmin(yMin, yValue)
}
}
// Min value for Y label
if yMax < 5 {
yMax = 5.0
}
if yMin < 0 {
yMin = 0.0
}
self.yValueMin = yMin
self.yValueMax = yMax
if self.showLabel {
self.yLabels = yLabelsArray as NSArray
}
setNeedsDisplay()
}
}
var pathPoints: NSMutableArray = []
// X-Axis Info
public var xLabelWidth: CGFloat = 0
// Y-Axis Info
public var yValueMax: CGFloat = 10
public var yValueMin: CGFloat = 1
public var yLabelNum: CGFloat = 0
public var yLabelHeight: CGFloat = 12
// Chart Info
public var showLabel: Bool = true
public var showCoordinateAxis: Bool = true
public var chartCavanHeight: CGFloat = {
return CGFloat(0)
}()
public var chartCavanWidth: CGFloat = {
return CGFloat(0)
}()
public var chartMargin: CGFloat = 25
// For Axis
public var axisColor: UIColor = PNGrey
public var axisWidth: CGFloat = 1
public var xUnit: NSString!
public var yUnit: NSString!
// String Format for float values in y labels.
public var yLabelFormat = "%1.1f"
var chartLineArray: NSMutableArray = []
var chartPointArray: NSMutableArray = []
var chartPaths: NSMutableArray = []
var pointPaths: NSMutableArray = []
// Initialize Methods
override init(frame: CGRect) {
super.init(frame: frame)
setDefaultValues()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Functions
func setDefaultValues() {
self.backgroundColor = UIColor.white
self.clipsToBounds = true
self.chartLineArray = NSMutableArray()
self.showLabel = false
self.pathPoints = NSMutableArray()
self.isUserInteractionEnabled = true
self.chartCavanWidth = self.frame.size.width - (chartMargin * 2)
self.chartCavanHeight = self.frame.size.height - (chartMargin * 2)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.touchPoint(touches: touches as NSSet, withEvent: event!)
self.touchKeyPoint(touches: touches as NSSet, withEvent: event!)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
self.touchPoint(touches: touches as NSSet, withEvent: event!)
self.touchKeyPoint(touches: touches as NSSet, withEvent: event!)
}
func touchPoint(touches: NSSet, withEvent event: UIEvent) {
let touch: UITouch = touches.anyObject() as! UITouch
let touchPoint = touch.location(in: self)
for linePoints in self.pathPoints {
let linePointsArray = linePoints as! [PNValue]
for index in 0..<(linePointsArray.count - 1) {
let p1: CGPoint = (linePointsArray[index]).point
let p2: CGPoint = (linePointsArray[index + 1]).point
// The closest distance from point to value
var distance: CGFloat = fabs(((p2.x - p1.x) * (touchPoint.y - p1.y)) - ((p1.x - touchPoint.x) * (p1.y - p2.y)))
distance = distance / hypot(p2.x - p1.x, p1.y - p2.y)
if distance <= 5 {
for path in self.chartPaths {
if (path as AnyObject).contains(p1) {
self.userClickedOnLinePoint(point: touchPoint, lineIndex: self.chartPaths.index(of: path))
}
}
}
}
}
}
func touchKeyPoint(touches: NSSet, withEvent event: UIEvent) {
let touch: UITouch = touches.anyObject() as! UITouch
let touchPoint = touch.location(in: self)
for linePoints in pathPoints {
let linePointsArray = pathPoints as! [PNValue]
for index in 0..<(linePointsArray.count - 1) {
let p1: CGPoint = (linePointsArray[index]).point
let p2: CGPoint = (linePointsArray[index + 1]).point
let distanceToP1: CGFloat = fabs(CGFloat(hypot(touchPoint.x - p1.x , touchPoint.y - p1.y )))
let distanceToP2: CGFloat = hypot( touchPoint.x - p2.x, touchPoint.y - p2.y)
let distance: CGFloat = fmin(distanceToP1, distanceToP2)
if distance <= 10 {
self.userClickedOnLineKeyPoint(point: touchPoint, lineIndex: self.pathPoints.index(of: linePoints), keyPointIndex: (distance == distanceToP2 ? index + 1 : index))
}
}
}
}
// This method will be called and stroke the line in animation
func strokeChart() {
let chartPaths = NSMutableArray()
let pointPaths = NSMutableArray()
for lineIndex in 0..<chartData.count {
let chartData: PNLineChartData = self.chartData[lineIndex] as! PNLineChartData
let chartLine = chartLineArray[lineIndex] as! CAShapeLayer
let pointLayer = chartPointArray[lineIndex] as! CAShapeLayer
var yValue: CGFloat!
var innerGrade: CGFloat!
UIGraphicsBeginImageContext(self.frame.size)
let progressLine = UIBezierPath()
progressLine.lineWidth = chartData.lineWidth
progressLine.lineCapStyle = .round
progressLine.lineJoinStyle = .round
let pointPath = UIBezierPath()
pointPath.lineWidth = chartData.lineWidth
chartPaths.add(progressLine)
pointPaths.add(pointPath)
if !(self.showLabel) {
self.chartCavanHeight = self.frame.size.height - 2 * self.yLabelHeight
self.chartCavanWidth = self.frame.size.width
self.chartMargin = 0
self.xLabelWidth = (self.chartCavanWidth / CGFloat(self.xLabels.count - 1))
}
let linePointsArray = NSMutableArray()
var lastX: CGFloat = 0
var lastY: CGFloat = 0
let inflexionWidth = chartData.inflexionPointWidth
for index in 0..<chartData.itemCount {
yValue = CGFloat(chartData.getData(index).y)
innerGrade = (yValue - self.yValueMin) / (self.yValueMax - self.yValueMin)
let x: CGFloat = self.chartMargin * 2 + (CGFloat(index) * self.xLabelWidth)
let y: CGFloat = self.chartCavanHeight - (innerGrade * self.chartCavanHeight)
switch chartData.inflexPointStyle {
// Cycle Style Point
case .Cycle:
let circleRect = CGRect(x: x - inflexionWidth/2, y: y - inflexionWidth/2, width: inflexionWidth, height: inflexionWidth)
let circleCenter = CGPoint(x: circleRect.origin.x + circleRect.size.width/2, y: circleRect.origin.y + circleRect.size.height/2)
pointPath.move(to: CGPoint(x: circleCenter.x + inflexionWidth/2, y: circleCenter.y))
pointPath.addArc(withCenter: circleCenter, radius: CGFloat(inflexionWidth/2), startAngle: 0, endAngle: CGFloat(Double.pi * 2), clockwise: true)
if index != 0 {
// Calculate the point for line
let distance = CGFloat(sqrt(pow(Double(x - lastX), 2) + pow(Double(y - lastY), 2)))
let lastX1 = lastX + (inflexionWidth/2) / distance * (x - lastX)
let lastY1 = lastY + (inflexionWidth/2) / distance * (y - lastY)
let x1 = x - (inflexionWidth/2) / distance * (x - lastX)
let y1 = y - (inflexionWidth/2) / distance * (y - lastY)
progressLine.move(to: CGPoint(x: lastX1, y: lastY1))
progressLine.addLine(to: CGPoint(x: x1, y: y1))
}
lastX = x
lastY = y
// Square Style Point
case .Square:
let squareRect = CGRect(x: x - inflexionWidth/2, y: y - inflexionWidth/2, width: inflexionWidth, height: inflexionWidth)
let squareCenter = CGPoint(x: squareRect.origin.x + (squareRect.size.width/2), y: squareRect.origin.y + (squareRect.size.height/2))
pointPath.move(to: CGPoint(x: squareCenter.x - (inflexionWidth/2), y: squareCenter.y - (inflexionWidth/2)))
pointPath.addLine(to: CGPoint(x: squareCenter.x + (inflexionWidth/2), y: squareCenter.y - (inflexionWidth/2)))
pointPath.addLine(to: CGPoint(x: squareCenter.x + (inflexionWidth/2), y: squareCenter.y + (inflexionWidth/2)))
pointPath.addLine(to: CGPoint(x: squareCenter.x - (inflexionWidth/2), y: squareCenter.y + (inflexionWidth/2)))
pointPath.close()
if index != 0 {
// Calculate the point for line
let distance = CGFloat(sqrt(pow(x - lastX, 2) + pow(y - lastY, 2)))
let lastX1 = lastX + (inflexionWidth / 2)
let lastY1 = lastY + (inflexionWidth / 2) / distance * (y - lastY)
let x1 = x - (inflexionWidth / 2)
let y1 = y - (inflexionWidth / 2) / distance * (y - lastY)
progressLine.move(to: CGPoint(x: lastX1, y: lastY1))
progressLine.addLine(to: CGPoint(x: x1, y: y1))
}
lastX = x
lastY = y
// Triangle Style Point
case .Triangle:
if index != 0 {
progressLine.addLine(to: CGPoint(x: x, y: y))
}
progressLine.move(to: CGPoint(x: x, y: y))
default:
if index != 0 {
progressLine.addLine(to: CGPoint(x: x, y: y))
}
progressLine.move(to: CGPoint(x: x, y: y))
}
linePointsArray.add(PNValue(point: CGPoint(x: x, y: y)))
}
pathPoints.add(linePointsArray)
// Setup color for chart line
if chartData.color != UIColor.black {
chartLine.strokeColor = chartData.color.cgColor
pointLayer.strokeColor = chartData.color.cgColor
} else {
chartLine.strokeColor = PNGreen.cgColor
chartLine.strokeColor = PNGreen.cgColor
}
progressLine.stroke()
chartLine.path = progressLine.cgPath
pointLayer.path = pointPath.cgPath
CATransaction.begin()
let path = CABasicAnimation(keyPath: "strokeEnd")
path.duration = 1
path.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
path.fromValue = 0
path.toValue = 1
chartLine.add(path, forKey: "strokeEndAnimation")
chartLine.strokeEnd = 1
if chartData.inflexPointStyle != .None {
pointLayer.add(path, forKey: "strokeEndAnimation")
}
CATransaction.commit()
UIGraphicsEndImageContext()
}
}
override func draw(_ rect: CGRect) {
if self.showCoordinateAxis {
let yAxisOffset: CGFloat = 10
let ctx = UIGraphicsGetCurrentContext()
UIGraphicsPushContext(ctx!)
ctx?.setLineWidth(self.axisWidth)
ctx?.setStrokeColor(self.axisColor.cgColor)
let xAxisWidth: CGFloat = rect.width - self.chartMargin/2
let yAxisHeight: CGFloat = self.chartMargin + self.chartCavanHeight
// Draw coordinate axis
ctx?.move(to: CGPoint(x: self.chartMargin + yAxisOffset, y: 0))
ctx?.addLine(to: CGPoint(x: self.chartMargin + yAxisOffset, y: yAxisHeight))
ctx?.addLine(to: CGPoint(x: xAxisWidth, y: yAxisHeight))
ctx?.strokePath()
// Draw y axis arrow
ctx?.move(to: CGPoint(x: self.chartMargin + yAxisOffset - 3, y: 6))
ctx?.addLine(to: CGPoint(x: self.chartMargin + yAxisOffset, y: 0))
ctx?.addLine(to: CGPoint(x: self.chartMargin + yAxisOffset + 3, y: 6))
ctx?.strokePath()
// Draw x axis arrow
ctx?.move(to: CGPoint(x: xAxisWidth - 6, y: yAxisHeight - 3))
ctx?.addLine(to: CGPoint(x: xAxisWidth, y: yAxisHeight))
ctx?.addLine(to: CGPoint(x: xAxisWidth - 6, y: yAxisHeight + 3))
ctx?.strokePath()
if self.showLabel {
// Draw x axis separator
var point: CGPoint!
for index in 0..<self.xLabels.count {
point = CGPoint(x: 2 * self.chartMargin + CGFloat(index) * self.xLabelWidth, y: self.chartMargin + self.chartCavanHeight)
ctx?.move(to: CGPoint(x: point.x, y: point.y - 2))
ctx?.addLine(to: CGPoint(x: point.x, y: point.y))
ctx?.strokePath()
}
// Draw y axis separator
let yStepHeight = self.chartCavanHeight/self.yLabelNum
for index in 0..<self.xLabels.count {
point = CGPoint(x: self.chartMargin + yAxisOffset, y: (self.chartCavanHeight - CGFloat(index) * yStepHeight + self.yLabelHeight/2))
ctx?.move(to: CGPoint(x: point.x, y: point.y))
ctx?.addLine(to: CGPoint(x: point.x + 2, y: point.y))
ctx?.strokePath()
}
}
let font = UIFont(name: "Avenir-Medium", size: 11)
// Draw y unit
if self.yUnit != nil {
let height = self.heightOfString(text: self.yUnit, width: 30, font: font!)
let drawRect = CGRect(x: self.chartMargin + 15, y: 0, width: 30, height: height)
self.drawTextInContext(ctx: ctx!, text: self.yUnit, rect: drawRect, font: font!)
}
if self.xUnit != nil {
let height = self.heightOfString(text: self.xUnit, width: 30, font: font!)
let drawRect = CGRect(x: rect.width - self.chartMargin + 5, y: self.chartMargin + self.chartCavanHeight - height/2, width: 25, height: height)
self.drawTextInContext(ctx: ctx!, text: self.xUnit, rect: drawRect, font: font!)
}
}
super.draw(rect)
}
}
extension PNLineChart {
func heightOfString(text: NSString, width: CGFloat, font: UIFont) -> CGFloat {
let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let rect = text.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)
return rect.size.height
}
func drawTextInContext(ctx: CGContext, text: NSString, rect: CGRect, font: UIFont) {
let priceParagraphStyle: NSMutableParagraphStyle = NSParagraphStyle.default as! NSMutableParagraphStyle
priceParagraphStyle.lineBreakMode = .byTruncatingTail
priceParagraphStyle.alignment = .left
text.draw(in: rect, withAttributes: [NSAttributedStringKey.paragraphStyle: priceParagraphStyle])
}
func userClickedOnLineKeyPoint(point: CGPoint, lineIndex: Int, keyPointIndex: Int) {
print("Click Key on line \(point.x), \(point.y) line index is \(lineIndex) and point index is \(keyPointIndex)")
}
func userClickedOnLinePoint(point: CGPoint, lineIndex: Int) {
print("Click Key on line \(point.x), \(point.y) line index is \(lineIndex)")
}
}
| mit | 6cbc37aea20ebccaaf826f0d0d9da8f5 | 43.063025 | 216 | 0.543912 | 4.819393 | false | false | false | false |
StYaphet/firefox-ios | Client/Frontend/Theme/ThemedWidgets.swift | 6 | 5966 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class ThemedTableViewCell: UITableViewCell, Themeable {
var detailTextColor = UIColor.theme.tableView.disabledRowText
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
applyTheme()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func applyTheme() {
textLabel?.textColor = UIColor.theme.tableView.rowText
detailTextLabel?.textColor = detailTextColor
backgroundColor = UIColor.theme.tableView.rowBackground
tintColor = UIColor.theme.general.controlTint
}
}
class ThemedTableViewController: UITableViewController, Themeable {
override init(style: UITableView.Style = .grouped) {
super.init(style: style)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = ThemedTableViewCell(style: .subtitle, reuseIdentifier: nil)
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
applyTheme()
}
func applyTheme() {
tableView.separatorColor = UIColor.theme.tableView.separator
tableView.backgroundColor = UIColor.theme.tableView.headerBackground
tableView.reloadData()
(tableView.tableHeaderView as? Themeable)?.applyTheme()
}
}
class ThemedTableSectionHeaderFooterView: UITableViewHeaderFooterView, Themeable {
private struct UX {
static let titleHorizontalPadding: CGFloat = 15
static let titleVerticalPadding: CGFloat = 6
static let titleVerticalLongPadding: CGFloat = 20
}
enum TitleAlignment {
case top
case bottom
}
var titleAlignment: TitleAlignment = .bottom {
didSet {
remakeTitleAlignmentConstraints()
}
}
lazy var titleLabel: UILabel = {
var headerLabel = UILabel()
headerLabel.font = UIFont.systemFont(ofSize: 12.0, weight: UIFont.Weight.regular)
headerLabel.numberOfLines = 0
return headerLabel
}()
fileprivate lazy var bordersHelper = ThemedHeaderFooterViewBordersHelper()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
contentView.addSubview(titleLabel)
bordersHelper.initBorders(view: self)
setDefaultBordersValues()
setupInitialConstraints()
applyTheme()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func applyTheme() {
bordersHelper.applyTheme()
contentView.backgroundColor = UIColor.theme.tableView.headerBackground
titleLabel.textColor = UIColor.theme.tableView.headerTextLight
}
func setupInitialConstraints() {
remakeTitleAlignmentConstraints()
}
func showBorder(for location: ThemedHeaderFooterViewBordersHelper.BorderLocation, _ show: Bool) {
bordersHelper.showBorder(for: location, show)
}
func setDefaultBordersValues() {
bordersHelper.showBorder(for: .top, false)
bordersHelper.showBorder(for: .bottom, false)
}
override func prepareForReuse() {
super.prepareForReuse()
setDefaultBordersValues()
titleLabel.text = nil
titleAlignment = .bottom
applyTheme()
}
fileprivate func remakeTitleAlignmentConstraints() {
switch titleAlignment {
case .top:
titleLabel.snp.remakeConstraints { make in
make.left.right.equalTo(self.contentView).inset(UX.titleHorizontalPadding)
make.top.equalTo(self.contentView).offset(UX.titleVerticalPadding)
make.bottom.equalTo(self.contentView).offset(-UX.titleVerticalLongPadding)
}
case .bottom:
titleLabel.snp.remakeConstraints { make in
make.left.right.equalTo(self.contentView).inset(UX.titleHorizontalPadding)
make.bottom.equalTo(self.contentView).offset(-UX.titleVerticalPadding)
make.top.equalTo(self.contentView).offset(UX.titleVerticalLongPadding)
}
}
}
}
class ThemedHeaderFooterViewBordersHelper: Themeable {
enum BorderLocation {
case top
case bottom
}
fileprivate lazy var topBorder: UIView = {
let topBorder = UIView()
return topBorder
}()
fileprivate lazy var bottomBorder: UIView = {
let bottomBorder = UIView()
return bottomBorder
}()
func showBorder(for location: BorderLocation, _ show: Bool) {
switch location {
case .top:
topBorder.isHidden = !show
case .bottom:
bottomBorder.isHidden = !show
}
}
func initBorders(view: UITableViewHeaderFooterView) {
view.contentView.addSubview(topBorder)
view.contentView.addSubview(bottomBorder)
topBorder.snp.makeConstraints { make in
make.left.right.top.equalTo(view.contentView)
make.height.equalTo(0.25)
}
bottomBorder.snp.makeConstraints { make in
make.left.right.bottom.equalTo(view.contentView)
make.height.equalTo(0.5)
}
}
func applyTheme() {
topBorder.backgroundColor = UIColor.theme.tableView.separator
bottomBorder.backgroundColor = UIColor.theme.tableView.separator
}
}
class UISwitchThemed: UISwitch {
override func layoutSubviews() {
super.layoutSubviews()
onTintColor = UIColor.theme.general.controlTint
}
}
| mpl-2.0 | fdc9d871f78817b809c705f82e7003a3 | 30.235602 | 109 | 0.664935 | 5.094791 | false | false | false | false |
biohazardlover/ROer | DataImporter/DatabaseManager.swift | 1 | 8105 |
import Foundation
import CoreData
private let sharedManager = DatabaseManager()
class DatabaseManager: NSObject {
class var shared: DatabaseManager {
return sharedManager
}
func loadDatabase() {
guard let prerenewalManagedObjectContext = DatabaseManager.shared.prerenewalManagedObjectContext, let renewalManagedObjectContext = DatabaseManager.shared.renewalManagedObjectContext else { return }
let preImporter = Importer(managedObjectContext: prerenewalManagedObjectContext)
preImporter.importPrerenewal()
let reImporter = Importer(managedObjectContext: renewalManagedObjectContext)
reImporter.importRenewal()
}
// MARK: - Core Data Stack
lazy var desktopURL: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.studiopp.Roer" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask)
return urls.last!
}()
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 = Bundle(for: Item.self).url(forResource: "Roer", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var prerenewalPersistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return 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
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.desktopURL.appendingPathComponent("Pre-renewal.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error
error = 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 \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var renewalPersistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return 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
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.desktopURL.appendingPathComponent("Renewal.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error
error = 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 \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var prerenewalManagedObjectContext: 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.prerenewalPersistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
lazy var renewalManagedObjectContext: 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.renewalPersistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving Support
func saveContext () {
if let moc = self.prerenewalManagedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// 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.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
if let moc = self.renewalManagedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// 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.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
}
| mit | 6643e7291dbfefe7b0d80ff0880277d6 | 53.033333 | 290 | 0.667242 | 5.835133 | false | false | false | false |
RoverPlatform/rover-ios | Sources/Experiences/Extensions/URLRequest.swift | 1 | 2257 | //
// URLRequest.swift
// Rover
//
// Created by Andrew Clunis on 2019-05-31.
// Copyright © 2019 Rover Labs Inc. All rights reserved.
//
import Foundation
import UIKit
import RoverFoundation
extension URLRequest {
/// Replace the standard CFNetwork-created User Agent with a more useful one.
mutating func setRoverUserAgent() {
// we want to add the Rover SDK version to the User Agent. Sadly, we cannot get our hands on the default user agent sent by CFNetwork, so we have to start from scratch, including reproducing the fields in the stock user agent:
// AppName/$version. (a value exists for this by default, but this version is a bit better than the stock version of this value, which has the app build number rather than version)
let appBundleDict = Bundle.main.infoDictionary
let appName = appBundleDict?["CFBundleName"] as? String ?? "unknown"
let appVersion = appBundleDict?["CFBundleShortVersionString"] as? String ?? "unknown"
let appDescriptor = appName + "/" + appVersion
// CFNetwork/$version (reproducing it; it exists in the standard iOS user agent, and perhaps some ops tooling will benefit from it being stock)
let cfNetworkInfo = Bundle(identifier: "com.apple.CFNetwork")?.infoDictionary
let cfNetworkVersion = cfNetworkInfo?["CFBundleShortVersionString"] as? String ?? "unknown"
let cfNetworkDescriptor = "CFNetwork/\(cfNetworkVersion)"
// Darwin/$version (reproducing it; it exists in the standard iOS user agent, and perhaps some ops tooling will benefit from it being stock)
var sysinfo = utsname()
uname(&sysinfo)
let dv = String(bytes: Data(bytes: &sysinfo.release, count: Int(_SYS_NAMELEN)), encoding: .ascii)?.trimmingCharacters(in: .controlCharacters) ?? "unknown"
let darwinDescriptor = "Darwin/\(dv)"
// iOS/$ios-version
let osDescriptor = "iOS/" + UIDevice.current.systemVersion
// RoverSDK/$rover-sdk-version
let roverVersion = Meta.SDKVersion
self.setValue("\(appDescriptor) \(cfNetworkDescriptor) \(darwinDescriptor) \(osDescriptor) RoverSDK/\(roverVersion)", forHTTPHeaderField: "User-Agent")
}
}
| apache-2.0 | f34b3fa9326d6648613192299967a493 | 52.714286 | 234 | 0.692819 | 4.670807 | false | false | false | false |
JRG-Developer/BetterBaseClasses | BetterBaseClasses/Demo/SetViewControllerContainerViewController.swift | 1 | 1688 | //
// SetViewControllerContainerViewController.swift
// BetterBaseClasses
//
// Created by Joshua Greene on 8/25/16.
// Copyright © 2016 Joshua Greene. All rights reserved.
//
import UIKit
class SetViewControllerContainerViewController: BaseContainerViewController {
// MARK: - Actions
@IBAction func toggleTopViewControllerPressed(_ sender: AnyObject) {
guard topViewController == nil else {
setTop(nil, animated: true, completion: nil)
return
}
let viewController = UIViewController()
viewController.view.backgroundColor = UIColor.green
setTop(viewController, animated: true, completion: nil)
}
@IBAction func replaceTopViewControllerPressed(_ sender: AnyObject) {
let viewController = UIViewController()
viewController.view.backgroundColor = UIColor.blue
setTop(viewController, animated: true, completion: nil)
}
@IBAction func toggleBottomViewControllerPressed(_ sender: AnyObject) {
guard bottomViewController == nil else {
setBottom(nil, animated: true, completion: nil)
return
}
let viewController = UIViewController()
viewController.view.backgroundColor = UIColor.red
setBottom(viewController, animated: true, completion: nil)
}
@IBAction func replaceBottomViewControllerPressed(_ sender: AnyObject) {
let viewController = UIViewController()
viewController.view.backgroundColor = UIColor.blue
setBottom(viewController, animated: true, completion: nil)
}
@IBAction func toggleBothViewControllersPresed(_ sender: AnyObject) {
toggleTopViewControllerPressed(sender)
toggleBottomViewControllerPressed(sender)
}
}
| mit | 9f119f38d46f8021615d3b6b4eed026a | 28.596491 | 77 | 0.730883 | 5.066066 | false | false | false | false |
sungkipyung/CodeSample | SimpleCameraApp/SimpleCameraApp/RadioButton.swift | 1 | 1965 | //
// RadioButton.swift
// SimpleCameraApp
//
// Created by 성기평 on 2016. 4. 22..
// Copyright © 2016년 hothead. All rights reserved.
//
import UIKit
typealias RaioButtonOnChangeLocation = (_ view: RadioButton, _ originalPosition: CGPoint, _ incX: CGFloat, _ incY: CGFloat) -> (Void)
class RadioButton: UIButton {
fileprivate var originalPosition: CGPoint?
fileprivate var touchOffset: CGPoint?
var onChangeLocation:RaioButtonOnChangeLocation?
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.cornerRadius = min(frame.width, frame.height) / 2
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
originalPosition = self.center
if let position:CGPoint = touches.first?.location(in: self.superview) {
touchOffset = position
}
self.alpha = 0.8
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let loc:CGPoint = touches.first!.location(in: self.superview) {
let deltaX = loc.x - self.touchOffset!.x
let deltaY = loc.y - self.touchOffset!.y
self.onChangeLocation?(self, self.originalPosition!, deltaX, deltaY)
// self.onChangeLocation?(view: self, origin: CGPoint(x: self.originalPosition!.x + deltaX, y: self.originalPosition!.y + deltaY))
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.alpha = 1.0
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
}}
| apache-2.0 | 2e6e26d74be0722d58b60301ba6a3ae0 | 32.724138 | 153 | 0.635992 | 4.289474 | false | false | false | false |
omaralbeik/SwifterSwift | Sources/Extensions/SwiftStdlib/SequenceExtensions.swift | 1 | 8559 | //
// SequenceExtensions.swift
// SwifterSwift
//
// Created by Anton Novoselov on 04/04/2018.
// Copyright © 2018 SwifterSwift
//
#if canImport(Foundation)
import Foundation
#endif
public extension Sequence {
/// SwifterSwift: Check if all elements in collection match a conditon.
///
/// [2, 2, 4].all(matching: {$0 % 2 == 0}) -> true
/// [1,2, 2, 4].all(matching: {$0 % 2 == 0}) -> false
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: true when all elements in the array match the specified condition.
public func all(matching condition: (Element) throws -> Bool) rethrows -> Bool {
return try !contains { try !condition($0) }
}
/// SwifterSwift: Check if no elements in collection match a conditon.
///
/// [2, 2, 4].none(matching: {$0 % 2 == 0}) -> false
/// [1, 3, 5, 7].none(matching: {$0 % 2 == 0}) -> true
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: true when no elements in the array match the specified condition.
public func none(matching condition: (Element) throws -> Bool) rethrows -> Bool {
return try !contains { try condition($0) }
}
/// SwifterSwift: Check if any element in collection match a conditon.
///
/// [2, 2, 4].any(matching: {$0 % 2 == 0}) -> false
/// [1, 3, 5, 7].any(matching: {$0 % 2 == 0}) -> true
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: true when no elements in the array match the specified condition.
public func any(matching condition: (Element) throws -> Bool) rethrows -> Bool {
return try contains { try condition($0) }
}
/// SwifterSwift: Get last element that satisfies a conditon.
///
/// [2, 2, 4, 7].last(where: {$0 % 2 == 0}) -> 4
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: the last element in the array matching the specified condition. (optional)
public func last(where condition: (Element) throws -> Bool) rethrows -> Element? {
for element in reversed() {
if try condition(element) { return element }
}
return nil
}
/// SwifterSwift: Filter elements based on a rejection condition.
///
/// [2, 2, 4, 7].reject(where: {$0 % 2 == 0}) -> [7]
///
/// - Parameter condition: to evaluate the exclusion of an element from the array.
/// - Returns: the array with rejected values filtered from it.
public func reject(where condition: (Element) throws -> Bool) rethrows -> [Element] {
return try filter { return try !condition($0) }
}
/// SwifterSwift: Get element count based on condition.
///
/// [2, 2, 4, 7].count(where: {$0 % 2 == 0}) -> 3
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: number of times the condition evaluated to true.
public func count(where condition: (Element) throws -> Bool) rethrows -> Int {
var count = 0
for element in self where try condition(element) {
count += 1
}
return count
}
/// SwifterSwift: Iterate over a collection in reverse order. (right to left)
///
/// [0, 2, 4, 7].forEachReversed({ print($0)}) -> //Order of print: 7,4,2,0
///
/// - Parameter body: a closure that takes an element of the array as a parameter.
public func forEachReversed(_ body: (Element) throws -> Void) rethrows {
try reversed().forEach(body)
}
/// SwifterSwift: Calls the given closure with each element where condition is true.
///
/// [0, 2, 4, 7].forEach(where: {$0 % 2 == 0}, body: { print($0)}) -> //print: 0, 2, 4
///
/// - Parameters:
/// - condition: condition to evaluate each element against.
/// - body: a closure that takes an element of the array as a parameter.
public func forEach(where condition: (Element) throws -> Bool, body: (Element) throws -> Void) rethrows {
for element in self where try condition(element) {
try body(element)
}
}
/// SwifterSwift: Reduces an array while returning each interim combination.
///
/// [1, 2, 3].accumulate(initial: 0, next: +) -> [1, 3, 6]
///
/// - Parameters:
/// - initial: initial value.
/// - next: closure that combines the accumulating value and next element of the array.
/// - Returns: an array of the final accumulated value and each interim combination.
public func accumulate<U>(initial: U, next: (U, Element) throws -> U) rethrows -> [U] {
var runningTotal = initial
return try map { element in
runningTotal = try next(runningTotal, element)
return runningTotal
}
}
/// SwifterSwift: Filtered and map in a single operation.
///
/// [1,2,3,4,5].filtered({ $0 % 2 == 0 }, map: { $0.string }) -> ["2", "4"]
///
/// - Parameters:
/// - isIncluded: condition of inclusion to evaluate each element against.
/// - transform: transform element function to evaluate every element.
/// - Returns: Return an filtered and mapped array.
public func filtered<T>(_ isIncluded: (Element) throws -> Bool, map transform: (Element) throws -> T) rethrows -> [T] {
return try compactMap({
if try isIncluded($0) {
return try transform($0)
}
return nil
})
}
/// SwifterSwift: Get the only element based on a condition.
///
/// [].single(where: {_ in true}) -> nil
/// [4].single(where: {_ in true}) -> 4
/// [1, 4, 7].single(where: {$0 % 2 == 0}) -> 4
/// [2, 2, 4, 7].single(where: {$0 % 2 == 0}) -> nil
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: The only element in the array matching the specified condition. If there are more matching elements, nil is returned. (optional)
public func single(where condition: ((Element) throws -> Bool)) rethrows -> Element? {
var singleElement: Element?
for element in self where try condition(element) {
guard singleElement == nil else {
singleElement = nil
break
}
singleElement = element
}
return singleElement
}
}
public extension Sequence where Element: Equatable {
/// SwifterSwift: Check if array contains an array of elements.
///
/// [1, 2, 3, 4, 5].contains([1, 2]) -> true
/// [1.2, 2.3, 4.5, 3.4, 4.5].contains([2, 6]) -> false
/// ["h", "e", "l", "l", "o"].contains(["l", "o"]) -> true
///
/// - Parameter elements: array of elements to check.
/// - Returns: true if array contains all given items.
public func contains(_ elements: [Element]) -> Bool {
guard !elements.isEmpty else { return true }
for element in elements {
if !contains(element) {
return false
}
}
return true
}
}
public extension Sequence where Element: Hashable {
/// SwifterSwift: Check whether a sequence contains duplicates.
///
/// - Returns: true if the receiver contains duplicates.
public func containsDuplicates() -> Bool {
var set = Set<Element>()
for element in self {
if !set.insert(element).inserted {
return true
}
}
return false
}
/// SwifterSwift: Getting the duplicated elements in a sequence.
///
/// [1, 1, 2, 2, 3, 3, 3, 4, 5].duplicates().sorted() -> [1, 2, 3])
/// ["h", "e", "l", "l", "o"].duplicates().sorted() -> ["l"])
///
/// - Returns: An array of duplicated elements.
///
public func duplicates() -> [Element] {
var set = Set<Element>()
var duplicates = Set<Element>()
forEach {
if !set.insert($0).inserted {
duplicates.insert($0)
}
}
return Array(duplicates)
}
}
// MARK: - Methods (Numeric)
public extension Sequence where Element: Numeric {
/// SwifterSwift: Sum of all elements in array.
///
/// [1, 2, 3, 4, 5].sum() -> 15
///
/// - Returns: sum of the array's elements.
public func sum() -> Element {
return reduce(0, {$0 + $1})
}
}
| mit | 63f38c21e100a43bc2e4e5472ee46f3b | 36.047619 | 147 | 0.567539 | 4.136298 | false | false | false | false |
Performador/Pickery | iOSTests/SignalProducerTests.swift | 1 | 1427 | //
// SignalProducerTests.swift
// Pickery
//
// Created by Okan Arikan on 7/28/16.
//
//
import ReactiveSwift
import XCTest
@testable import iOS
class SignalProducerTests: XCTestCase {
/// This will test the parallel map extension
func testParallelMap() {
// We will swuare these
let values : [ Int ] = [ 1,2,3 ]
// Parallel map (signal producer version)
SignalProducer<Int, Error>(values: values)
.parallelFlatMap { (value: Int) -> SignalProducer<Int, Error> in
return SignalProducer<Int, Error> { sink, disposible in
sink.sendNext(value * value)
sink.sendCompleted()
}
}.collect()
.startWithNext { squaredValues in
XCTAssert(squaredValues.count == 3)
for v in values {
XCTAssert(squaredValues.contains(v * v))
}
}
// Parallel map (direct version)
SignalProducer<Int, Error>(values: values)
.parallelFlatMap { (value: Int) -> Int in
return value * value
}.collect()
.startWithNext { squaredValues in
XCTAssert(squaredValues.count == 3)
for v in values {
XCTAssert(squaredValues.contains(v * v))
}
}
}
}
| mit | 8a00abf795cd64c96ade440afc8722fe | 28.122449 | 76 | 0.516468 | 4.804714 | false | true | false | false |
silence0201/Swift-Study | Learn/13.类继承/重写属性观察者.playground/section-1.swift | 1 | 857 |
class Person {
var name: String
var age: Int
func description() -> String {
return "\(name) 年龄是: \(age)"
}
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
class Student: Person {
var school: String
override var age: Int {
willSet {
print("学生年龄新值:\(newValue)")
}
didSet {
print("学生年龄旧值:\(oldValue)")
}
}
convenience init() {
self.init(name: "Tony", age: 18, school: "清华大学")
}
init(name: String, age: Int, school: String) {
self.school = school
super.init(name: name, age: age)
}
}
let student1 = Student()
print("学生年龄:\(student1.age)")
student1.age = 6
print("学生年龄:\(student1.age)")
| mit | 5ba38bcdb415df7baa7b9e86e13919c2 | 17.488372 | 56 | 0.503145 | 3.613636 | false | false | false | false |
apptentive/apptentive-ios | Apptentive/ApptentiveTests/ApptentiveEngagementTests.swift | 1 | 7185 | //
// ApptentiveEngagementTests.swift
// ApptentiveTests
//
// Created by Frank Schmitt on 11/5/18.
// Copyright © 2018 Apptentive, Inc. All rights reserved.
//
import XCTest
class ApptentiveEngagementTests: XCTestCase {
func testEventLabelsContainingCodePointSeparatorCharacters() {
//Escape "%", "/", and "#".
var i = "testEventLabelSeparators";
var o = "testEventLabelSeparators";
XCTAssertTrue(ApptentiveBackend.stringByEscapingCodePointSeparatorCharacters(in: i) == o, "Test escaping code point separator characters from event labels.");
i = "test#Event#Label#Separators";
o = "test%23Event%23Label%23Separators";
XCTAssertTrue(ApptentiveBackend.stringByEscapingCodePointSeparatorCharacters(in: i) == o, "Test escaping code point separator characters from event labels.");
i = "test/Event/Label/Separators";
o = "test%2FEvent%2FLabel%2FSeparators";
XCTAssertTrue(ApptentiveBackend.stringByEscapingCodePointSeparatorCharacters(in: i) == o, "Test escaping code point separator characters from event labels.");
i = "test%Event/Label#Separators";
o = "test%25Event%2FLabel%23Separators";
XCTAssertTrue(ApptentiveBackend.stringByEscapingCodePointSeparatorCharacters(in: i) == o, "Test escaping code point separator characters from event labels.");
i = "test#Event/Label%Separators";
o = "test%23Event%2FLabel%25Separators";
XCTAssertTrue(ApptentiveBackend.stringByEscapingCodePointSeparatorCharacters(in: i) == o, "Test escaping code point separator characters from event labels.");
i = "test###Event///Label%%%Separators";
o = "test%23%23%23Event%2F%2F%2FLabel%25%25%25Separators";
XCTAssertTrue(ApptentiveBackend.stringByEscapingCodePointSeparatorCharacters(in: i) == o, "Test escaping code point separator characters from event labels.");
i = "test#%///#%//%%/#Event_!@#$%^&*(){}Label1234567890[]`~Separators";
o = "test%23%25%2F%2F%2F%23%25%2F%2F%25%25%2F%23Event_!@%23$%25^&*(){}Label1234567890[]`~Separators";
XCTAssertTrue(ApptentiveBackend.stringByEscapingCodePointSeparatorCharacters(in: i) == o, "Test escaping code point separator characters from event labels.");
i = "test%/#";
o = "test%25%2F%23";
XCTAssertTrue(ApptentiveBackend.stringByEscapingCodePointSeparatorCharacters(in: i) == o, "Test escaping code point separator characters from event labels.");
}
func testMergingCounts() {
let aLongTimeAgo = Date(timeIntervalSinceNow: -1000)
let aLittleWhileAgo = Date(timeIntervalSinceNow: -500)
let oldCount = ApptentiveCount(totalCount: 5, versionCount: 10, buildCount: 20, lastInvoked: aLongTimeAgo);
let newCount = ApptentiveCount(totalCount: 1, versionCount: 2, buildCount: 4, lastInvoked: aLittleWhileAgo);
let mergedCount = ApptentiveCount.mergeOldCount(oldCount, withNewCount: newCount);
XCTAssertEqual(mergedCount.totalCount, 6)
XCTAssertEqual(mergedCount.versionCount, 2)
XCTAssertEqual(mergedCount.buildCount, 4)
XCTAssertEqual(mergedCount.lastInvoked, aLittleWhileAgo)
let mergedCount2 = ApptentiveCount.mergeOldCount(nil, withNewCount: nil)
XCTAssertEqual(mergedCount2.totalCount, 0)
XCTAssertEqual(mergedCount2.versionCount, 0)
XCTAssertEqual(mergedCount2.buildCount, 0)
XCTAssertEqual(mergedCount2.lastInvoked, nil)
let mergedCount3 = ApptentiveCount.mergeOldCount(oldCount, withNewCount: nil)
XCTAssertEqual(mergedCount3.totalCount, 5)
XCTAssertEqual(mergedCount3.versionCount, 0)
XCTAssertEqual(mergedCount3.buildCount, 0)
XCTAssertEqual(mergedCount3.lastInvoked, aLongTimeAgo)
let mergedCount4 = ApptentiveCount.mergeOldCount(nil, withNewCount: newCount)
XCTAssertEqual(mergedCount4.totalCount, 1)
XCTAssertEqual(mergedCount4.versionCount, 2)
XCTAssertEqual(mergedCount4.buildCount, 4)
XCTAssertEqual(mergedCount4.lastInvoked, aLittleWhileAgo)
}
func testEscapedKeyForKey() {
XCTAssertEqual(ApptentiveEngagement.escapedKey(forKey: "local#app#go/daddy"), "local#app#go%2Fdaddy")
XCTAssertEqual(ApptentiveEngagement.escapedKey(forKey: "local#app#go#daddy"), "local#app#go%23daddy")
XCTAssertEqual(ApptentiveEngagement.escapedKey(forKey: "local#app#go%25daddy"), nil)
XCTAssertEqual(ApptentiveEngagement.escapedKey(forKey: "com.apptentive#app#launch"), nil)
}
func testMigration() {
Bundle(for: ApptentiveEngagementTests.self).url(forResource: "conversation-4", withExtension:"archive")
// Open a 4.0.0 archive with slash/pound/percent event names
guard let fourOhUrl = Bundle(for: ApptentiveEngagementTests.self).url(forResource: "conversation-4", withExtension:"archive"),
let fourOhData = try? Data(contentsOf: fourOhUrl) else {
return XCTFail("Can't open 4.0 conversation archive")
}
let maybeFourOhConversation: ApptentiveConversation?
if #available(iOS 11.0, *) {
maybeFourOhConversation = try? NSKeyedUnarchiver.unarchivedObject(ofClass: ApptentiveConversation.self, from: fourOhData)
} else {
maybeFourOhConversation = NSKeyedUnarchiver.unarchiveObject(with: fourOhData) as? ApptentiveConversation
}
guard let fourOhConversation = maybeFourOhConversation else {
return XCTFail("Can't unarchive 4.0 conversation archive")
}
let fourOhEngagement = fourOhConversation.engagement
XCTAssertEqual(fourOhEngagement.version, 2)
XCTAssertEqual(fourOhEngagement.codePoints["local#app#go%2Fdaddy"]?.totalCount, 1)
XCTAssertEqual(fourOhEngagement.codePoints["local#app#go%2Fdaddy"]?.buildCount, 1)
XCTAssertEqual(fourOhEngagement.codePoints["local#app#go%2Fdaddy"]?.versionCount, 1)
XCTAssertEqual(fourOhEngagement.codePoints["local#app#go%23daddy"]?.totalCount, 1)
XCTAssertEqual(fourOhEngagement.codePoints["local#app#go%25daddy"]?.totalCount, 1)
XCTAssertEqual(fourOhEngagement.codePoints["local#app#go%2520daddy"]?.totalCount, 1)
guard let fiveTwoUrl = Bundle(for: ApptentiveEngagementTests.self).url(forResource: "conversation-5", withExtension:"archive"),
let fiveTwoData = try? Data(contentsOf: fiveTwoUrl) else {
return XCTFail("Can't open 5.2 conversation archive")
}
let maybeFiveTwoConversation: ApptentiveConversation?
if #available(iOS 11.0, *) {
maybeFiveTwoConversation = try? NSKeyedUnarchiver.unarchivedObject(ofClass: ApptentiveConversation.self, from: fiveTwoData)
} else {
maybeFiveTwoConversation = NSKeyedUnarchiver.unarchiveObject(with: fiveTwoData) as? ApptentiveConversation
}
guard let fiveTwoConversation = maybeFiveTwoConversation else {
return XCTFail("Can't unarchive 5.2 conversation archive")
}
let fiveTwoEngagement = fiveTwoConversation.engagement
XCTAssertEqual(fiveTwoEngagement.version, 2)
XCTAssertEqual(fiveTwoEngagement.codePoints["local#app#go%2Fdaddy"]?.totalCount, 2)
XCTAssertEqual(fiveTwoEngagement.codePoints["local#app#go%2Fdaddy"]?.buildCount, 0)
XCTAssertEqual(fiveTwoEngagement.codePoints["local#app#go%2Fdaddy"]?.versionCount, 0)
XCTAssertEqual(fiveTwoEngagement.codePoints["local#app#go%23daddy"]?.totalCount, 2)
// No longer migrating these, as there aren't any in the wild.
// XCTAssertEqual(fiveTwoEngagement.codePoints["local#app#go%25daddy"]?.totalCount, 2)
// XCTAssertEqual(fiveTwoEngagement.codePoints["local#app#go%2520daddy"]?.totalCount, 2)
}
}
| bsd-3-clause | 5d0bf1767d77f4a5abb6719fea555e3c | 46.893333 | 160 | 0.779232 | 3.678443 | false | true | false | false |
FotiosTragopoulos/Core-Geometry | Core Geometry/Con1ViewHeight.swift | 1 | 1722 | //
// Con1ViewHeight.swift
// Core Geometry
//
// Created by Fotios Tragopoulos on 18/01/2017.
// Copyright © 2017 Fotios Tragopoulos. All rights reserved.
//
import UIKit
class Con1ViewHeight: UIView {
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
let myShadowOffset = CGSize (width: 10, height: 10)
context?.setShadow (offset: myShadowOffset, blur: 8)
context?.saveGState()
context?.setLineWidth(3.0)
context?.setStrokeColor(UIColor.init(red: 111.0/255.0, green: 110.0/255.0, blue: 1.0/255.0, alpha: 1.0).cgColor)
let xView = viewWithTag(33)?.alignmentRect(forFrame: rect).midX
let yView = viewWithTag(33)?.alignmentRect(forFrame: rect).midY
let width = self.viewWithTag(33)?.frame.size.width
let height = self.viewWithTag(33)?.frame.size.height
let size = CGSize(width: width! * 0.8, height: height! * 0.8)
let linePlacementY = CGFloat(size.height/3)
context?.move(to: CGPoint(x: (xView! * 1.02), y: (yView! - linePlacementY * 1.02)))
context?.addLine(to: CGPoint(x: (xView! * 1.02), y: (yView! + linePlacementY * 1.25)))
let dashArray:[CGFloat] = [10, 4]
context?.setLineDash(phase: 3, lengths: dashArray)
context?.strokePath()
context?.restoreGState()
self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.15, initialSpringVelocity: 6.0, options: .allowUserInteraction, animations: { self.transform = CGAffineTransform.identity } ,completion: nil)
}
}
| apache-2.0 | 75e150add18832c206e5582cfab02ef2 | 38.113636 | 219 | 0.627542 | 3.774123 | false | false | false | false |
bytedissident/BDTests | Example/BDTestsExample/Pods/Alamofire/Source/MultipartFormData.swift | 1 | 22100 | //
// MultipartFormData.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
#if os(iOS) || os(watchOS) || os(tvOS)
import MobileCoreServices
#elseif os(macOS)
import CoreServices
#endif
/// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
/// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
/// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
/// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
/// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.
///
/// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well
/// and the w3 form documentation.
///
/// - https://www.ietf.org/rfc/rfc2388.txt
/// - https://www.ietf.org/rfc/rfc2045.txt
/// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13
open class MultipartFormData {
// MARK: - Helper Types
enum EncodingCharacters {
static let crlf = "\r\n"
}
enum BoundaryGenerator {
enum BoundaryType {
case initial, encapsulated, final
}
static func randomBoundary() -> String {
let first = UInt32.random(in: UInt32.min...UInt32.max)
let second = UInt32.random(in: UInt32.min...UInt32.max)
return String(format: "alamofire.boundary.%08x%08x", first, second)
}
static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data {
let boundaryText: String
switch boundaryType {
case .initial:
boundaryText = "--\(boundary)\(EncodingCharacters.crlf)"
case .encapsulated:
boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)"
case .final:
boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)"
}
return Data(boundaryText.utf8)
}
}
class BodyPart {
let headers: HTTPHeaders
let bodyStream: InputStream
let bodyContentLength: UInt64
var hasInitialBoundary = false
var hasFinalBoundary = false
init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) {
self.headers = headers
self.bodyStream = bodyStream
self.bodyContentLength = bodyContentLength
}
}
// MARK: - Properties
/// Default memory threshold used when encoding `MultipartFormData`, in bytes.
public static let encodingMemoryThreshold: UInt64 = 10_000_000
/// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
open lazy var contentType: String = "multipart/form-data; boundary=\(self.boundary)"
/// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
public var contentLength: UInt64 { bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
/// The boundary used to separate the body parts in the encoded form data.
public let boundary: String
let fileManager: FileManager
private var bodyParts: [BodyPart]
private var bodyPartError: AFError?
private let streamBufferSize: Int
// MARK: - Lifecycle
/// Creates an instance.
///
/// - Parameters:
/// - fileManager: `FileManager` to use for file operations, if needed.
/// - boundary: Boundary `String` used to separate body parts.
public init(fileManager: FileManager = .default, boundary: String? = nil) {
self.fileManager = fileManager
self.boundary = boundary ?? BoundaryGenerator.randomBoundary()
bodyParts = []
//
// The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
// information, please refer to the following article:
// - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
//
streamBufferSize = 1024
}
// MARK: - Body Parts
/// Creates a body part from the data and appends it to the instance.
///
/// The body part data will be encoded using the following format:
///
/// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
/// - `Content-Type: #{mimeType}` (HTTP Header)
/// - Encoded file data
/// - Multipart form boundary
///
/// - Parameters:
/// - data: `Data` to encoding into the instance.
/// - name: Name to associate with the `Data` in the `Content-Disposition` HTTP header.
/// - fileName: Filename to associate with the `Data` in the `Content-Disposition` HTTP header.
/// - mimeType: MIME type to associate with the data in the `Content-Type` HTTP header.
public func append(_ data: Data, withName name: String, fileName: String? = nil, mimeType: String? = nil) {
let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType)
let stream = InputStream(data: data)
let length = UInt64(data.count)
append(stream, withLength: length, headers: headers)
}
/// Creates a body part from the file and appends it to the instance.
///
/// The body part data will be encoded using the following format:
///
/// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
/// - `Content-Type: #{generated mimeType}` (HTTP Header)
/// - Encoded file data
/// - Multipart form boundary
///
/// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
/// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
/// system associated MIME type.
///
/// - Parameters:
/// - fileURL: `URL` of the file whose content will be encoded into the instance.
/// - name: Name to associate with the file content in the `Content-Disposition` HTTP header.
public func append(_ fileURL: URL, withName name: String) {
let fileName = fileURL.lastPathComponent
let pathExtension = fileURL.pathExtension
if !fileName.isEmpty && !pathExtension.isEmpty {
let mime = mimeType(forPathExtension: pathExtension)
append(fileURL, withName: name, fileName: fileName, mimeType: mime)
} else {
setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL))
}
}
/// Creates a body part from the file and appends it to the instance.
///
/// The body part data will be encoded using the following format:
///
/// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
/// - Content-Type: #{mimeType} (HTTP Header)
/// - Encoded file data
/// - Multipart form boundary
///
/// - Parameters:
/// - fileURL: `URL` of the file whose content will be encoded into the instance.
/// - name: Name to associate with the file content in the `Content-Disposition` HTTP header.
/// - fileName: Filename to associate with the file content in the `Content-Disposition` HTTP header.
/// - mimeType: MIME type to associate with the file content in the `Content-Type` HTTP header.
public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) {
let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType)
//============================================================
// Check 1 - is file URL?
//============================================================
guard fileURL.isFileURL else {
setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL))
return
}
//============================================================
// Check 2 - is file URL reachable?
//============================================================
do {
let isReachable = try fileURL.checkPromisedItemIsReachable()
guard isReachable else {
setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL))
return
}
} catch {
setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error))
return
}
//============================================================
// Check 3 - is file URL a directory?
//============================================================
var isDirectory: ObjCBool = false
let path = fileURL.path
guard fileManager.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else {
setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL))
return
}
//============================================================
// Check 4 - can the file size be extracted?
//============================================================
let bodyContentLength: UInt64
do {
guard let fileSize = try fileManager.attributesOfItem(atPath: path)[.size] as? NSNumber else {
setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL))
return
}
bodyContentLength = fileSize.uint64Value
} catch {
setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error))
return
}
//============================================================
// Check 5 - can a stream be created from file URL?
//============================================================
guard let stream = InputStream(url: fileURL) else {
setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL))
return
}
append(stream, withLength: bodyContentLength, headers: headers)
}
/// Creates a body part from the stream and appends it to the instance.
///
/// The body part data will be encoded using the following format:
///
/// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
/// - `Content-Type: #{mimeType}` (HTTP Header)
/// - Encoded stream data
/// - Multipart form boundary
///
/// - Parameters:
/// - stream: `InputStream` to encode into the instance.
/// - length: Length, in bytes, of the stream.
/// - name: Name to associate with the stream content in the `Content-Disposition` HTTP header.
/// - fileName: Filename to associate with the stream content in the `Content-Disposition` HTTP header.
/// - mimeType: MIME type to associate with the stream content in the `Content-Type` HTTP header.
public func append(_ stream: InputStream,
withLength length: UInt64,
name: String,
fileName: String,
mimeType: String) {
let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType)
append(stream, withLength: length, headers: headers)
}
/// Creates a body part with the stream, length, and headers and appends it to the instance.
///
/// The body part data will be encoded using the following format:
///
/// - HTTP headers
/// - Encoded stream data
/// - Multipart form boundary
///
/// - Parameters:
/// - stream: `InputStream` to encode into the instance.
/// - length: Length, in bytes, of the stream.
/// - headers: `HTTPHeaders` for the body part.
public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) {
let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
bodyParts.append(bodyPart)
}
// MARK: - Data Encoding
/// Encodes all appended body parts into a single `Data` value.
///
/// - Note: This method will load all the appended body parts into memory all at the same time. This method should
/// only be used when the encoded data will have a small memory footprint. For large data cases, please use
/// the `writeEncodedData(to:))` method.
///
/// - Returns: The encoded `Data`, if encoding is successful.
/// - Throws: An `AFError` if encoding encounters an error.
public func encode() throws -> Data {
if let bodyPartError = bodyPartError {
throw bodyPartError
}
var encoded = Data()
bodyParts.first?.hasInitialBoundary = true
bodyParts.last?.hasFinalBoundary = true
for bodyPart in bodyParts {
let encodedData = try encode(bodyPart)
encoded.append(encodedData)
}
return encoded
}
/// Writes all appended body parts to the given file `URL`.
///
/// This process is facilitated by reading and writing with input and output streams, respectively. Thus,
/// this approach is very memory efficient and should be used for large body part data.
///
/// - Parameter fileURL: File `URL` to which to write the form data.
/// - Throws: An `AFError` if encoding encounters an error.
public func writeEncodedData(to fileURL: URL) throws {
if let bodyPartError = bodyPartError {
throw bodyPartError
}
if fileManager.fileExists(atPath: fileURL.path) {
throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL))
} else if !fileURL.isFileURL {
throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL))
}
guard let outputStream = OutputStream(url: fileURL, append: false) else {
throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL))
}
outputStream.open()
defer { outputStream.close() }
bodyParts.first?.hasInitialBoundary = true
bodyParts.last?.hasFinalBoundary = true
for bodyPart in bodyParts {
try write(bodyPart, to: outputStream)
}
}
// MARK: - Private - Body Part Encoding
private func encode(_ bodyPart: BodyPart) throws -> Data {
var encoded = Data()
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
encoded.append(initialData)
let headerData = encodeHeaders(for: bodyPart)
encoded.append(headerData)
let bodyStreamData = try encodeBodyStream(for: bodyPart)
encoded.append(bodyStreamData)
if bodyPart.hasFinalBoundary {
encoded.append(finalBoundaryData())
}
return encoded
}
private func encodeHeaders(for bodyPart: BodyPart) -> Data {
let headerText = bodyPart.headers.map { "\($0.name): \($0.value)\(EncodingCharacters.crlf)" }
.joined()
+ EncodingCharacters.crlf
return Data(headerText.utf8)
}
private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data {
let inputStream = bodyPart.bodyStream
inputStream.open()
defer { inputStream.close() }
var encoded = Data()
while inputStream.hasBytesAvailable {
var buffer = [UInt8](repeating: 0, count: streamBufferSize)
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
if let error = inputStream.streamError {
throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error))
}
if bytesRead > 0 {
encoded.append(buffer, count: bytesRead)
} else {
break
}
}
return encoded
}
// MARK: - Private - Writing Body Part to Output Stream
private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws {
try writeInitialBoundaryData(for: bodyPart, to: outputStream)
try writeHeaderData(for: bodyPart, to: outputStream)
try writeBodyStream(for: bodyPart, to: outputStream)
try writeFinalBoundaryData(for: bodyPart, to: outputStream)
}
private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
return try write(initialData, to: outputStream)
}
private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
let headerData = encodeHeaders(for: bodyPart)
return try write(headerData, to: outputStream)
}
private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
let inputStream = bodyPart.bodyStream
inputStream.open()
defer { inputStream.close() }
while inputStream.hasBytesAvailable {
var buffer = [UInt8](repeating: 0, count: streamBufferSize)
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
if let streamError = inputStream.streamError {
throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError))
}
if bytesRead > 0 {
if buffer.count != bytesRead {
buffer = Array(buffer[0..<bytesRead])
}
try write(&buffer, to: outputStream)
} else {
break
}
}
}
private func writeFinalBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
if bodyPart.hasFinalBoundary {
return try write(finalBoundaryData(), to: outputStream)
}
}
// MARK: - Private - Writing Buffered Data to Output Stream
private func write(_ data: Data, to outputStream: OutputStream) throws {
var buffer = [UInt8](repeating: 0, count: data.count)
data.copyBytes(to: &buffer, count: data.count)
return try write(&buffer, to: outputStream)
}
private func write(_ buffer: inout [UInt8], to outputStream: OutputStream) throws {
var bytesToWrite = buffer.count
while bytesToWrite > 0, outputStream.hasSpaceAvailable {
let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
if let error = outputStream.streamError {
throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error))
}
bytesToWrite -= bytesWritten
if bytesToWrite > 0 {
buffer = Array(buffer[bytesWritten..<buffer.count])
}
}
}
// MARK: - Private - Mime Type
private func mimeType(forPathExtension pathExtension: String) -> String {
if
let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(),
let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() {
return contentType as String
}
return "application/octet-stream"
}
// MARK: - Private - Content Headers
private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> HTTPHeaders {
var disposition = "form-data; name=\"\(name)\""
if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" }
var headers: HTTPHeaders = [.contentDisposition(disposition)]
if let mimeType = mimeType { headers.add(.contentType(mimeType)) }
return headers
}
// MARK: - Private - Boundary Encoding
private func initialBoundaryData() -> Data {
BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary)
}
private func encapsulatedBoundaryData() -> Data {
BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary)
}
private func finalBoundaryData() -> Data {
BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary)
}
// MARK: - Private - Errors
private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) {
guard bodyPartError == nil else { return }
bodyPartError = AFError.multipartEncodingFailed(reason: reason)
}
}
| mit | 36e81584a62129a039b54c317a17e8c0 | 39.402194 | 142 | 0.625882 | 4.94186 | false | false | false | false |
CatchChat/Yep | Yep/ViewControllers/VerifyChangedMobile/VerifyChangedMobileViewController.swift | 1 | 8014 | //
// VerifyChangedMobileViewController.swift
// Yep
//
// Created by NIX on 16/5/4.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
import YepNetworking
import Ruler
import RxSwift
import RxCocoa
final class VerifyChangedMobileViewController: UIViewController {
var mobile: String!
var areaCode: String!
private lazy var disposeBag = DisposeBag()
@IBOutlet private weak var verifyMobileNumberPromptLabel: UILabel!
@IBOutlet private weak var verifyMobileNumberPromptLabelTopConstraint: NSLayoutConstraint!
@IBOutlet private weak var phoneNumberLabel: UILabel!
@IBOutlet private weak var verifyCodeTextField: BorderTextField!
@IBOutlet private weak var verifyCodeTextFieldTopConstraint: NSLayoutConstraint!
@IBOutlet private weak var callMePromptLabel: UILabel!
@IBOutlet private weak var callMeButton: UIButton!
@IBOutlet private weak var callMeButtonTopConstraint: NSLayoutConstraint!
private lazy var nextButton: UIBarButtonItem = {
let button = UIBarButtonItem()
button.title = NSLocalizedString("Submit", comment: "")
button.rx_tap
.subscribeNext({ [weak self] in self?.confirmNewMobile() })
.addDisposableTo(self.disposeBag)
return button
}()
private lazy var callMeTimer: NSTimer = {
let timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(VerifyChangedMobileViewController.tryCallMe(_:)), userInfo: nil, repeats: true)
return timer
}()
private var haveAppropriateInput = false {
didSet {
nextButton.enabled = haveAppropriateInput
if (oldValue != haveAppropriateInput) && haveAppropriateInput {
confirmNewMobile()
}
}
}
private var callMeInSeconds = YepConfig.callMeInSeconds()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.yepViewBackgroundColor()
navigationItem.titleView = NavigationTitleLabel(title: String.trans_titleChangeMobile)
navigationItem.rightBarButtonItem = nextButton
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(VerifyChangedMobileViewController.activeAgain(_:)), name: AppDelegate.Notification.applicationDidBecomeActive, object: nil)
verifyMobileNumberPromptLabel.text = NSLocalizedString("Input verification code sent to", comment: "")
phoneNumberLabel.text = "+" + areaCode + " " + mobile
verifyCodeTextField.placeholder = " "
verifyCodeTextField.backgroundColor = UIColor.whiteColor()
verifyCodeTextField.textColor = UIColor.yepInputTextColor()
verifyCodeTextField.rx_text
.map({ $0.characters.count == YepConfig.verifyCodeLength() })
.subscribeNext({ [weak self] in self?.haveAppropriateInput = $0 })
.addDisposableTo(disposeBag)
callMePromptLabel.text = NSLocalizedString("Didn't get it?", comment: "")
callMeButton.setTitle(String.trans_buttonCallMe, forState: .Normal)
verifyMobileNumberPromptLabelTopConstraint.constant = Ruler.iPhoneVertical(30, 50, 60, 60).value
verifyCodeTextFieldTopConstraint.constant = Ruler.iPhoneVertical(30, 40, 50, 50).value
callMeButtonTopConstraint.constant = Ruler.iPhoneVertical(10, 20, 40, 40).value
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
nextButton.enabled = false
callMeButton.enabled = false
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
verifyCodeTextField.becomeFirstResponder()
callMeTimer.fire()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
view.endEditing(true)
}
// MARK: Actions
@objc private func activeAgain(notification: NSNotification) {
verifyCodeTextField.becomeFirstResponder()
}
@objc private func tryCallMe(timer: NSTimer) {
if !haveAppropriateInput {
if callMeInSeconds > 1 {
let callMeInSecondsString = String.trans_buttonCallMe + " (\(callMeInSeconds))"
UIView.performWithoutAnimation { [weak self] in
self?.callMeButton.setTitle(callMeInSecondsString, forState: .Normal)
self?.callMeButton.layoutIfNeeded()
}
} else {
UIView.performWithoutAnimation { [weak self] in
self?.callMeButton.setTitle(String.trans_buttonCallMe, forState: .Normal)
self?.callMeButton.layoutIfNeeded()
}
callMeButton.enabled = true
}
}
if (callMeInSeconds > 1) {
callMeInSeconds -= 1
}
}
@IBAction private func callMe(sender: UIButton) {
callMeTimer.invalidate()
UIView.performWithoutAnimation { [weak self] in
self?.callMeButton.setTitle(String.trans_buttonCalling, forState: .Normal)
self?.callMeButton.layoutIfNeeded()
self?.callMeButton.enabled = false
}
delay(10) {
UIView.performWithoutAnimation { [weak self] in
self?.callMeButton.setTitle(String.trans_buttonCallMe, forState: .Normal)
self?.callMeButton.layoutIfNeeded()
self?.callMeButton.enabled = true
}
}
sendVerifyCodeOfNewMobile(mobile, withAreaCode: areaCode, useMethod: .Call, failureHandler: { reason, errorMessage in
defaultFailureHandler(reason: reason, errorMessage: errorMessage)
let errorMessage = errorMessage ?? "Error: call for verify code"
YepAlert.alertSorry(message: errorMessage, inViewController: self)
SafeDispatch.async {
UIView.performWithoutAnimation { [weak self] in
self?.callMeButton.setTitle(String.trans_buttonCallMe, forState: .Normal)
self?.callMeButton.layoutIfNeeded()
}
}
}, completion: { success in
println("sendVerifyCodeOfNewMobile .Call \(success)")
})
}
private func confirmNewMobile() {
view.endEditing(true)
guard let verifyCode = verifyCodeTextField.text else {
return
}
YepHUD.showActivityIndicator()
comfirmNewMobile(mobile, withAreaCode: areaCode, verifyCode: verifyCode, failureHandler: { (reason, errorMessage) in
defaultFailureHandler(reason: reason, errorMessage: errorMessage)
YepHUD.hideActivityIndicator()
SafeDispatch.async { [weak self] in
self?.nextButton.enabled = false
}
let errorMessage = errorMessage ?? ""
YepAlert.alertSorry(message: errorMessage, inViewController: self, withDismissAction: {
SafeDispatch.async { [weak self] in
self?.verifyCodeTextField.text = nil
self?.verifyCodeTextField.becomeFirstResponder()
}
})
}, completion: {
YepHUD.hideActivityIndicator()
SafeDispatch.async { [weak self] in
if let strongSelf = self {
YepUserDefaults.areaCode.value = strongSelf.areaCode
YepUserDefaults.mobile.value = strongSelf.mobile
}
}
YepAlert.alert(title: NSLocalizedString("Success", comment: ""), message: NSLocalizedString("You have successfully updated your mobile for Yep! For now on, using the new number to login.", comment: ""), dismissTitle: NSLocalizedString("OK", comment: ""), inViewController: self, withDismissAction: { [weak self] in
self?.performSegueWithIdentifier("unwindToEditProfile", sender: nil)
})
})
}
}
| mit | 826379778f3201c787771fc4d5a69dd0 | 34.446903 | 326 | 0.648234 | 5.337109 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/BaseTest/BaseTest/Class_Struct_Enum/ExtensionSummany.swift | 1 | 2030 | //
// ExtensionSummany.swift
// BaseTest
//
// Created by wuyp on 2016/12/23.
// Copyright © 2016年 raymond. All rights reserved.
//
import Foundation
@objc protocol FoodsProtocol {
@objc optional func eatTaste() -> String
}
protocol ElectricProtocol {
func SoundsType() -> String
}
protocol clothesProtocol {
func colothersType() -> String
}
extension Double {
var km: Double { return self * 1_000.0 }
var m: Double { return self }
var cm: Double { return self / 100.0}
}
enum GoodsType {
case food, electric, clothes
}
class ExtensionBaseGoods: NSObject {
var price: Float = 0.0
var name: String = ""
var classify: GoodsType
init(price: Float, name: String, classify: GoodsType) {
self.price = price
self.name = name
self.classify = classify
}
override var description: String {
return "the \(name) price is \(price) and is belong to \(classify)"
}
}
class Orange: ExtensionBaseGoods {
override var description: String {
return "the \(name) is very nice."
}
}
extension Orange: FoodsProtocol {
func eatTaste() -> String {
self.name = "orange"
return "this have a litter sour."
}
}
extension Int {
subscript(digitIndex: Int) -> Int {
var decimalBase = 1
for _ in 0..<digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
@objc protocol CounterDataSource {
@objc optional func increment(forCount count: Int) -> Int
@objc optional var fixedIncrement: Int { get }
}
class Counter {
var count = 0
var dataSource: CounterDataSource?
func increment() {
if let amount = dataSource?.increment?(forCount: count) {
count += amount
} else if let amount = dataSource?.fixedIncrement {
count += amount
}
}
}
extension Collection where Iterator.Element: FoodsProtocol {
var textualDescription: String {
return "abc"
}
}
| apache-2.0 | c0d9d89228b683b236e58d648b778fb0 | 20.56383 | 75 | 0.614702 | 3.94358 | false | false | false | false |
brave/browser-ios | ClientTests/TestHistory.swift | 3 | 8154 | /* 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/. */
@testable import Client
import Foundation
import Storage
import XCTest
class TestHistory : ProfileTest {
private func addSite(history: BrowserHistory, url: String, title: String, s: Bool = true) {
let site = Site(url: url, title: title)
let visit = SiteVisit(site: site, date: NSDate.nowMicroseconds())
XCTAssertEqual(s, history.addLocalVisit(visit).value.isSuccess, "Site added: \(url).")
}
private func innerCheckSites(history: BrowserHistory, callback: (cursor: Cursor<Site>) -> Void) {
// Retrieve the entry
history.getSitesByLastVisit(100).upon {
XCTAssertTrue($0.isSuccess)
callback(cursor: $0.successValue!)
}
}
private func checkSites(history: BrowserHistory, urls: [String: String], s: Bool = true) {
// Retrieve the entry.
if let cursor = history.getSitesByLastVisit(100).value.successValue {
XCTAssertEqual(cursor.status, CursorStatus.Success, "Returned success \(cursor.statusMessage).")
XCTAssertEqual(cursor.count, urls.count, "Cursor has \(urls.count) entries.")
for index in 0..<cursor.count {
let s = cursor[index]!
XCTAssertNotNil(s, "Cursor has a site for entry.")
let title = urls[s.url]
XCTAssertNotNil(title, "Found right URL.")
XCTAssertEqual(s.title, title!, "Found right title.")
}
} else {
XCTFail("Couldn't get cursor.")
}
}
private func clear(history: BrowserHistory) {
XCTAssertTrue(history.clearHistory().value.isSuccess, "History cleared.")
}
private func checkVisits(history: BrowserHistory, url: String) {
let expectation = self.expectationWithDescription("Wait for history")
history.getSitesByLastVisit(100).upon { result in
XCTAssertTrue(result.isSuccess)
history.getSitesByFrecencyWithLimit(100, whereURLContains: url).upon { result in
XCTAssertTrue(result.isSuccess)
let cursor = result.successValue!
XCTAssertEqual(cursor.status, CursorStatus.Success, "returned success \(cursor.statusMessage)")
// XXX - We don't allow querying much info about visits here anymore, so there isn't a lot to do
expectation.fulfill()
}
}
self.waitForExpectationsWithTimeout(100, handler: nil)
}
// This is a very basic test. Adds an entry. Retrieves it, and then clears the database
func testHistory() {
withTestProfile { profile -> Void in
let h = profile.history
self.addSite(h, url: "http://url1/", title: "title")
self.addSite(h, url: "http://url1/", title: "title")
self.addSite(h, url: "http://url1/", title: "title 2")
self.addSite(h, url: "https://url2/", title: "title")
self.addSite(h, url: "https://url2/", title: "title")
self.checkSites(h, urls: ["http://url1/": "title 2", "https://url2/": "title"])
self.checkVisits(h, url: "http://url1/")
self.checkVisits(h, url: "https://url2/")
self.clear(h)
}
}
func testAboutUrls() {
withTestProfile { (profile) -> Void in
let h = profile.history
self.addSite(h, url: "about:home", title: "About Home", s: false)
self.clear(h)
}
}
let NumThreads = 5
let NumCmds = 10
func testInsertPerformance() {
withTestProfile { profile -> Void in
let h = profile.history
var j = 0
self.measureBlock({ () -> Void in
for _ in 0...self.NumCmds {
self.addSite(h, url: "https://someurl\(j).com/", title: "title \(j)")
j++
}
self.clear(h)
})
}
}
func testGetPerformance() {
withTestProfile { profile -> Void in
let h = profile.history
var j = 0
var urls = [String: String]()
self.clear(h)
for _ in 0...self.NumCmds {
self.addSite(h, url: "https://someurl\(j).com/", title: "title \(j)")
urls["https://someurl\(j).com/"] = "title \(j)"
j++
}
self.measureBlock({ () -> Void in
self.checkSites(h, urls: urls)
return
})
self.clear(h)
}
}
// Fuzzing tests. These fire random insert/query/clear commands into the history database from threads. The don't check
// the results. Just look for crashes.
func testRandomThreading() {
withTestProfile { profile -> Void in
let queue = dispatch_queue_create("My Queue", DISPATCH_QUEUE_CONCURRENT)
var counter = 0
let expectation = self.expectationWithDescription("Wait for history")
for _ in 0..<self.NumThreads {
var history = profile.history as BrowserHistory
self.runRandom(&history, queue: queue, cb: { () -> Void in
counter++
if counter == self.NumThreads {
expectation.fulfill()
}
})
}
self.waitForExpectationsWithTimeout(10, handler: nil)
}
}
// Same as testRandomThreading, but uses one history connection for all threads
func testRandomThreading2() {
withTestProfile { profile -> Void in
let queue = dispatch_queue_create("My Queue", DISPATCH_QUEUE_CONCURRENT)
var history = profile.history as BrowserHistory
var counter = 0
let expectation = self.expectationWithDescription("Wait for history")
for _ in 0..<self.NumThreads {
self.runRandom(&history, queue: queue, cb: { () -> Void in
counter++
if counter == self.NumThreads {
expectation.fulfill()
}
})
}
self.waitForExpectationsWithTimeout(10, handler: nil)
}
}
// Runs a random command on a database. Calls cb when finished.
private func runRandom(inout history: BrowserHistory, cmdIn: Int, cb: () -> Void) {
var cmd = cmdIn
if cmd < 0 {
cmd = Int(rand() % 5)
}
switch cmd {
case 0...1:
let url = "https://randomurl.com/\(rand() % 100)"
let title = "title \(rand() % 100)"
addSite(history, url: url, title: title)
cb()
case 2...3:
innerCheckSites(history) { cursor in
for site in cursor {
_ = site!
}
}
cb()
default:
history.clearHistory().upon() { success in cb() }
}
}
// Calls numCmds random methods on this database. val is a counter used by this interally (i.e. always pass zero for it).
// Calls cb when finished.
private func runMultiRandom(inout history: BrowserHistory, val: Int, numCmds: Int, cb: () -> Void) {
if val == numCmds {
cb()
return
} else {
runRandom(&history, cmdIn: -1) { _ in
self.runMultiRandom(&history, val: val+1, numCmds: numCmds, cb: cb)
}
}
}
// Helper for starting a new thread running NumCmds random methods on it. Calls cb when done.
private func runRandom(inout history: BrowserHistory, queue: dispatch_queue_t, cb: () -> Void) {
dispatch_async(queue) {
// Each thread creates its own history provider
self.runMultiRandom(&history, val: 0, numCmds: self.NumCmds) { _ in
dispatch_async(dispatch_get_main_queue(), cb)
}
}
}
} | mpl-2.0 | 1ea63e34118ce5fabdb2eac5a1a1a425 | 36.580645 | 125 | 0.551018 | 4.524972 | false | true | false | false |
roshkadev/Form | Form/Classes/LocationPicker/LocationPicker.swift | 1 | 1204 | //
// LocationPicker.swift
// Pods
//
// Created by Paul Von Schrottky on 6/18/17.
//
//
import UIKit
import MapKit
final public class LocationPicker: NSObject {
// #MARK - Field
public var form: Form!
public var row: Row!
public var view: FieldView
public var contentView: UIView
public var stackView: UIStackView
public var title: String?
public var label: FieldLabel?
public var key: String?
public var attachedTo: InputKey?
public var padding = Space.default
public var formBindings = [(event: FormEvent, field: Field, handler: ((Field) -> Void))]()
public var button: UIButton
@discardableResult
override public init() {
view = FieldView()
stackView = UIStackView()
label = FieldLabel()
button = UIButton()
button.setTitle("Select location", for: .normal)
contentView = button
super.init()
Utilities.constrain(field: self, withView: button)
}
}
extension LocationPicker: Field {
@discardableResult
public func style(_ style: ((LocationPicker) -> Void)) -> Self {
style(self)
return self
}
}
| mit | d5bb5f5030ded0368d29a296f5cbce7d | 21.296296 | 94 | 0.616279 | 4.442804 | false | false | false | false |
AutosoftDMS/SignalR-Swift | SignalR-Swift/Transports/WebSocketTransport.swift | 1 | 8162 | //
// WebSocketTransport.swift
// SignalR-Swift
//
//
// Copyright © 2017 Jordan Camara. All rights reserved.
//
import Foundation
import Starscream
import Alamofire
private typealias WebSocketStartClosure = (String?, Error?) -> ()
public class WebSocketTransport: HttpTransport, WebSocketDelegate {
var reconnectDelay = 2.0
private var connectionInfo: WebSocketConnectionInfo?
private var webSocket: WebSocket?
private var startClosure: WebSocketStartClosure?
private var connectTimeoutOperation: BlockOperation?
override public var name: String? {
return "webSockets"
}
override public var supportsKeepAlive: Bool {
return true
}
override public func negotiate(connection: ConnectionProtocol, connectionData: String?, completionHandler: ((NegotiationResponse?, Error?) -> ())?) {
super.negotiate(connection: connection, connectionData: connectionData, completionHandler: completionHandler)
}
override public func start(connection: ConnectionProtocol, connectionData: String?, completionHandler: ((Any?, Error?) -> ())?) {
self.connectionInfo = WebSocketConnectionInfo(connection: connection, data: connectionData)
// perform connection
self.performConnect(completionHandler: completionHandler)
}
override public func send(connection: ConnectionProtocol, data: Any, connectionData: String?, completionHandler: ((Any?, Error?) -> ())?) {
if let dataString = data as? String {
self.webSocket?.write(string: dataString)
} else if let dataDict = data as? [String: Any] {
self.webSocket?.write(string: dataDict.toJSONString()!)
}
completionHandler?(nil, nil)
}
override public func abort(connection: ConnectionProtocol, timeout: Double, connectionData: String?) {
self.stopWebSocket()
super.abort(connection: connection, timeout: timeout, connectionData: connectionData)
}
override public func lostConnection(connection: ConnectionProtocol) {
self.stopWebSocket()
if self.tryCompleteAbort() {
return
}
self.reconnect(connection: self.connectionInfo?.connection)
}
private func stopWebSocket() {
self.webSocket?.delegate = nil
self.webSocket?.disconnect()
self.webSocket = nil
}
// MARK: - WebSockets transport
func performConnect(completionHandler: ((_ response: String?, _ error: Error?) -> ())?) {
self.performConnect(reconnecting: false, completionHandler: completionHandler)
}
func performConnect(reconnecting: Bool, completionHandler: ((_ response: String?, _ error: Error?) -> ())?) {
let connection = self.connectionInfo?.connection
var parameters: [String: Any] = [
"transport": self.name!,
"connectionToken": connection?.connectionToken ?? "",
"messageId": connection?.messageId ?? "",
"groupsToken": connection?.groupsToken ?? "",
"connectionData": self.connectionInfo?.data ?? ""
]
if let queryString = self.connectionInfo?.connection?.queryString {
for (key, value) in queryString {
parameters[key] = value
}
}
var urlComponents = URLComponents(string: connection!.url)
if let urlScheme = urlComponents?.scheme {
if urlScheme.hasPrefix("https") {
urlComponents?.scheme = "wss"
} else if urlScheme.hasPrefix("http") {
urlComponents?.scheme = "ws"
}
}
do {
let baseUrl = try urlComponents?.asURL()
let url = reconnecting ? baseUrl!.absoluteString.appending("reconnect") : baseUrl!.absoluteString.appending("connect")
let request = connection?.getRequest(url: url, httpMethod: .get, encoding: URLEncoding.default, parameters: parameters, timeout: 30)
self.startClosure = completionHandler
if let startClosure = self.startClosure {
self.connectTimeoutOperation = BlockOperation(block: { [weak self] in
guard let strongSelf = self else { return }
let userInfo = [
NSLocalizedDescriptionKey: NSLocalizedString("Connection timed out.", comment: "timeout error description"),
NSLocalizedFailureReasonErrorKey: NSLocalizedString("Connection did not receive initialized message before the timeout.", comment: "timeout error reason"),
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString("Retry or switch transports.", comment: "timeout error retry suggestion")
]
let error = NSError(domain: "com.autosoftdms.SignalR-Swift.\(type(of: strongSelf))", code: NSURLErrorTimedOut, userInfo: userInfo)
strongSelf.stopWebSocket()
strongSelf.startClosure = nil
startClosure(nil, error)
})
self.connectTimeoutOperation?.perform(#selector(BlockOperation.start), with: nil, afterDelay: connection!.transportConnectTimeout)
}
if let encodedRequest = request?.request {
self.webSocket = WebSocket(request: encodedRequest)
self.webSocket!.disableSSLCertValidation = connection?.webSocketAllowsSelfSignedSSL ?? false
self.webSocket!.delegate = self
self.webSocket!.connect()
}
} catch {
}
}
func reconnect(connection: ConnectionProtocol?) {
_ = BlockOperation { [weak self] in
if let strongSelf = self, let connection = connection, Connection.ensureReconnecting(connection: connection) {
strongSelf.performConnect(reconnecting: true, completionHandler: nil)
}
}.perform(#selector(BlockOperation.start), with: nil, afterDelay: self.reconnectDelay)
}
// MARK: - WebSocketDelegate
public func websocketDidConnect(socket: WebSocketClient){
if let connection = self.connectionInfo?.connection, connection.changeState(oldState: .reconnecting, toState: .connected) {
connection.didReconnect()
}
}
public func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
if let error = error {
webSocketError(error)
}
else if !self.tryCompleteAbort() {
self.reconnect(connection: self.connectionInfo?.connection)
}
}
private func webSocketError(_ error: Error) {
if let startClosure = self.startClosure, let connectTimeoutOperation = self.connectTimeoutOperation {
NSObject.cancelPreviousPerformRequests(withTarget: connectTimeoutOperation, selector: #selector(BlockOperation.start), object: nil)
self.connectTimeoutOperation = nil
self.stopWebSocket()
self.startClosure = nil
startClosure(nil, error)
} else if !self.startedAbort {
self.reconnect(connection: self.connectionInfo?.connection)
}
}
public func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
var timedOut = false
var disconnected = false
if let connection = self.connectionInfo?.connection, let data = text.data(using: .utf8) {
connection.processResponse(response: data, shouldReconnect: &timedOut, disconnected: &disconnected)
}
if let startClosure = self.startClosure, let connectTimeoutOperation = self.connectTimeoutOperation {
NSObject.cancelPreviousPerformRequests(withTarget: connectTimeoutOperation, selector: #selector(BlockOperation.start), object: nil)
self.connectTimeoutOperation = nil
self.startClosure = nil
startClosure(nil, nil)
}
if disconnected {
self.connectionInfo?.connection?.disconnect()
self.stopWebSocket()
}
}
public func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
}
}
| mit | 6bfd4800d4da01a733a30678f591ded5 | 39.004902 | 179 | 0.645387 | 5.411804 | false | false | false | false |
schibsted/layout | EditorExtension/Extension/FormatXMLCommand.swift | 1 | 1873 | // Copyright © 2017 Schibsted. All rights reserved.
import Foundation
import XcodeKit
class FormatXMLCommand: NSObject, XCSourceEditorCommand {
func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void) {
guard ["public.xml"].contains(invocation.buffer.contentUTI) else {
return completionHandler(NSError(
domain: "Layout",
code: 0,
userInfo: [NSLocalizedDescriptionKey: "File is not XML"]
))
}
// Grab the selected source to format
let sourceToFormat = invocation.buffer.completeBuffer
do {
let output = try format(sourceToFormat)
if output == sourceToFormat {
// No changes needed
return completionHandler(nil)
}
// Remove all selections to avoid a crash when changing the contents of the buffer.
invocation.buffer.selections.removeAllObjects()
// Update buffer
invocation.buffer.completeBuffer = output
// For the time being, set the selection back to the last character of the buffer
guard let lastLine = invocation.buffer.lines.lastObject as? String else {
return completionHandler(nil)
}
let position = XCSourceTextPosition(line: invocation.buffer.lines.count - 1, column: lastLine.count)
let updatedSelectionRange = XCSourceTextRange(start: position, end: position)
invocation.buffer.selections.add(updatedSelectionRange)
return completionHandler(nil)
} catch {
return completionHandler(NSError(
domain: "Layout",
code: 0,
userInfo: [NSLocalizedDescriptionKey: "\(error)"]
))
}
}
}
| mit | 72b995e18932baf8750c2d8707fdbe3b | 38 | 115 | 0.610043 | 5.571429 | false | false | false | false |
xspyhack/FlashPicker | FlashPicker/ActionCell.swift | 1 | 2082 | //
// ActionCell.swift
// ImagePicker
//
// Created by k on 6/29/16.
// Copyright © 2016 egg. All rights reserved.
//
import UIKit
class ActionCell: UICollectionViewCell {
lazy var titleLabel: UILabel = {
let label = UILabel()
label.textAlignment = .Center
label.font = UIFont.systemFontOfSize(14.0)
label.numberOfLines = 0
return label
}()
lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .ScaleAspectFill
return imageView
}()
override func willMoveToSuperview(newSuperview: UIView?) {
super.willMoveToSuperview(newSuperview)
configure()
}
private func configure() {
layer.cornerRadius = 8.0
backgroundColor = UIColor.whiteColor()
addSubview(titleLabel)
addSubview(imageView)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
imageView.translatesAutoresizingMaskIntoConstraints = false
let titleLabelHeight = NSLayoutConstraint(item: titleLabel, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 0.5, constant: 0.0)
let titleLabelY = NSLayoutConstraint(item: titleLabel, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.5, constant: 0.0)
let titleLabelH = NSLayoutConstraint.constraintsWithVisualFormat("H:|-12-[titleLabel]-12-|", options: [], metrics: nil, views: ["titleLabel": titleLabel])
let imageViewX = NSLayoutConstraint(item: imageView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0.0)
let imageViewY = NSLayoutConstraint(item: imageView, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 0.0)
NSLayoutConstraint.activateConstraints([titleLabelHeight, titleLabelY, imageViewX, imageViewY])
NSLayoutConstraint.activateConstraints(titleLabelH)
}
}
| mit | ec2d38c12c92455f26a48d8d6817ccfa | 37.537037 | 172 | 0.675637 | 4.978469 | false | false | false | false |
cnbuff410/hn-notifier | HNNotifier/AppDelegate.swift | 1 | 7588 | //
// AppDelegate.swift
// HNNotifier
//
// Created by Kun Li on 8/11/14.
//
//
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
@IBOutlet var window: NSWindow!
@IBOutlet weak var updateIntervalInputField: NSTextField!
@IBOutlet weak var postCntInputField: NSTextField!
// User defaults keys
let keyUpdateInterval = "update_interval"
let keyPostCnt = "post_count"
let keyObjectId = "object_id"
let apiLink = "http://hn.algolia.com/api/v1/search_by_date?tags=story"
let hackerNewsPostLinkPrefix = "https://news.ycombinator.com/item?id="
let hackerNewsLink = "https://news.ycombinator.com/newest"
let noNewItemMsg = "Nothing new, Go back to WORK!"
let postCntLimit = 50 // It doesn't make sense to have more than 50 items in the menu
var preObjectId = 0
var statusBar = NSStatusBar.systemStatusBar()
var statusBarItem : NSStatusItem = NSStatusItem()
var menu: NSMenu = NSMenu()
var menuItem : NSMenuItem = NSMenuItem()
var unreadMenuItems = [NSMenuItem]()
var menuItemLinks = [String]()
var timer: NSTimer!
var menuOpenDate: NSDate!
var postCnt: Int = 0
var updateIntervalInMinute: Int = 0
override func awakeFromNib() {
// Add statusBarItem
statusBarItem = statusBar.statusItemWithLength(-1)
statusBarItem.menu = menu
menu.delegate = self
postCnt = NSUserDefaults.standardUserDefaults().integerForKey(keyPostCnt)
updateIntervalInMinute = NSUserDefaults.standardUserDefaults().integerForKey(keyUpdateInterval)
preObjectId = NSUserDefaults.standardUserDefaults().integerForKey(keyObjectId)
// Default value for first time use
if postCnt == 0 { postCnt = 20 }
if updateIntervalInMinute == 0 { updateIntervalInMinute = 1 }
updatePost()
updateStatusBar()
timer = NSTimer.scheduledTimerWithTimeInterval(
NSTimeInterval(updateIntervalInMinute) * 60, target: self, selector: "updatePost", userInfo: nil, repeats: true)
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
self.window.orderOut(self)
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
@IBAction func onPreferenceConfirm(sender: AnyObject) {
if updateIntervalInputField.integerValue > 0 {
updateIntervalInMinute = updateIntervalInputField.integerValue
NSUserDefaults.standardUserDefaults().setInteger(updateIntervalInMinute, forKey: keyUpdateInterval)
timer.invalidate()
timer = NSTimer.scheduledTimerWithTimeInterval(
NSTimeInterval(60 * updateIntervalInMinute), target: self, selector: "updatePost", userInfo: nil, repeats: true)
}
if postCntInputField.integerValue > 0 {
postCnt = postCntInputField.integerValue
if postCnt > postCntLimit {
postCnt = postCntLimit
}
NSUserDefaults.standardUserDefaults().setInteger(postCnt, forKey: keyPostCnt)
}
NSUserDefaults.standardUserDefaults().synchronize()
self.window.orderOut(sender)
}
@IBAction func onPreferenceCancel(sender: AnyObject) {
self.window.orderOut(sender)
}
func updateStatusBar() {
if unreadMenuItems.count > 0 {
statusBarItem.image = NSImage(named: "BarItemIconActive")
} else {
statusBarItem.image = NSImage(named: "BarItemIconInactive")
}
}
func updateMenu() {
menu.removeAllItems()
// Add menuItem to menu
menuItem.title = "Latest Hacker News Post"
//menuItem.action = Selector("setWindowVisible:")
menuItem.keyEquivalent = ""
menu.addItem(menuItem)
menu.addItem(NSMenuItem.separatorItem())
if unreadMenuItems.count == 0 {
menu.addItemWithTitle(noNewItemMsg, action: nil, keyEquivalent: "")
} else {
var endIndex = unreadMenuItems.count > postCnt ? postCnt : unreadMenuItems.count
for i in 0..<endIndex {
menu.addItem(unreadMenuItems[i])
}
}
menu.addItem(NSMenuItem.separatorItem())
menu.addItemWithTitle("Option", action: "openPreference:", keyEquivalent: "")
menu.addItem(NSMenuItem.separatorItem())
menu.addItemWithTitle("Quit", action: "exit:", keyEquivalent: "")
}
// MARK: - Selectors
func updatePost() {
let request:NSURLRequest = NSURLRequest(URL: NSURL(string: apiLink)!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
let json = JSON(data: data)
if let posts = json["hits"].array {
if posts.count <= 0 {
return
}
var endIndex = posts.count > self.postCnt ? self.postCnt : posts.count
var incomingStoryList = [NSMenuItem]()
var incomingLinkList = [String]()
for i in 0..<endIndex {
if let id = posts[i]["objectID"].string {
if let intId = id.toInt() {
if intId > self.preObjectId { // New post
let menuItem = NSMenuItem()
menuItem.title = posts[i]["title"].string!
menuItem.toolTip = "\(self.hackerNewsPostLinkPrefix)\(intId)"
menuItem.action = Selector("openLink:")
incomingStoryList.append(menuItem)
} else {
break
}
}
}
}
self.unreadMenuItems = incomingStoryList + self.unreadMenuItems
self.menuItemLinks = incomingLinkList + self.menuItemLinks
self.preObjectId = posts[0]["objectID"].string!.toInt()!
NSUserDefaults.standardUserDefaults().setInteger(self.preObjectId, forKey: self.keyObjectId)
NSUserDefaults.standardUserDefaults().synchronize()
if self.unreadMenuItems.count > 0 {
self.updateStatusBar()
self.updateMenu()
}
}
})
}
func openLink(sender: AnyObject) {
var item: NSMenuItem = sender as! NSMenuItem
if let toolTip = item.toolTip {
NSWorkspace.sharedWorkspace().openURL(NSURL(string: toolTip)!)
}
}
func openPreference(sender: AnyObject) {
println("open preference")
self.window.orderFrontRegardless()
}
func exit(sender: AnyObject) {
timer?.invalidate()
NSApplication.sharedApplication().terminate(nil)
}
// MARK: - Menu delegates
func menuWillOpen(menu: NSMenu) {
menuOpenDate = NSDate()
updateMenu()
}
func menuDidClose(menu: NSMenu) {
let duration = NSDate().timeIntervalSinceDate(menuOpenDate)
if duration > 1 {
// Assume user glanced over all items, clear
unreadMenuItems.removeAll(keepCapacity: false)
updateStatusBar()
}
}
}
| mit | b722694db9aa26ba20d93eeb52db6076 | 37.130653 | 173 | 0.596468 | 5.218707 | false | false | false | false |
xu6148152/binea_project_for_ios | CustomXib/CustomXib/ViewController.swift | 1 | 5261 | //
// ViewController.swift
// CustomXib
//
// Created by Binea Xu on 10/13/15.
// Copyright © 2015 Binea Xu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var mainViewTopSpaceLayoutConstraintValue: CGFloat!
var mainViewOriginY: CGFloat!
var hiddenTopViewDefaultPosition: CGFloat!
var xiaoyunOriginX: CGFloat!
var middleImageViewHasBeenEnlarged = true
@IBOutlet weak var mainView: UIView!
@IBOutlet weak var topLayoutConstraintOfMainView: NSLayoutConstraint!
@IBOutlet weak var panGesture: UIPanGestureRecognizer!
@IBOutlet weak var hiddenTopView: UIView!
@IBOutlet weak var topLayoutConstraintOfHiddenTopView: NSLayoutConstraint!
@IBOutlet weak var dayunView: UIView!
@IBOutlet weak var xiaoyunView: UIView!
@IBOutlet weak var hiddenBannerView: UIView!
@IBOutlet weak var leftDistanceOfDayun: NSLayoutConstraint!
@IBOutlet weak var rightDistanceOfXiaoyun: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
mainViewTopSpaceLayoutConstraintValue = topLayoutConstraintOfMainView.constant
mainViewOriginY = mainView.frame.origin.y
panGesture.addTarget(self, action: "pan:")
hiddenTopViewDefaultPosition = -(hiddenTopView.frame.height / 2)
// topLayoutConstraintOfHiddenTopView.constant = hiddenTopViewDefaultPosition
rightDistanceOfXiaoyun.constant = 60
xiaoyunOriginX = xiaoyunView.frame.origin.x
makeDayunRolling()
// Do any additional setup after loading the view, typically from a nib.
// let button = NSBundle.mainBundle().loadNibNamed("RoundButton", owner: self, options: nil).first as! UIButton
// button.center = self.view.center
// self.view.addSubview(button)
}
func makeDayunRolling() {
leftDistanceOfDayun.constant -= 30
UIView.animateWithDuration(0.8, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
self.dayunView.layoutIfNeeded()
}) { (success) -> Void in
if success {
self.leftDistanceOfDayun.constant += 30
UIView.animateWithDuration(0.8, delay: 0.5, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
self.dayunView.layoutIfNeeded()
}, completion: { (success) -> Void in
if success {
self.makeDayunRolling()
}
})
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func centerButtonBeTapped(sender: AnyObject) {
print("centerButtonBeTapped")
}
func pan(recongnizer: UIPanGestureRecognizer) {
if panGesture.state == UIGestureRecognizerState.Ended {
middleImageViewHasBeenEnlarged = true
UIView.animateWithDuration(0.4, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
recongnizer.view?.frame.origin.y = self.mainViewOriginY
//make animated views move
self.hiddenTopView.frame.origin.y = self.hiddenTopViewDefaultPosition
}, completion: { (success) -> Void in
if success {
self.topLayoutConstraintOfMainView.constant = self.mainViewTopSpaceLayoutConstraintValue
}
})
return
}
let y = panGesture.translationInView(self.view).y
topLayoutConstraintOfMainView.constant = mainViewTopSpaceLayoutConstraintValue + y
//move xiaoyun when pull
let xiaoyunDistance = 60 - y*0.5
if xiaoyunDistance > -48 {
rightDistanceOfXiaoyun.constant = xiaoyunDistance
}else {
//slow down xiaoyun's speed when it needs
rightDistanceOfXiaoyun.constant = -sqrt(-xiaoyunDistance - 47) - 47
}
//move HiddenTopView when pull
let distance = 0.3 * y + hiddenTopViewDefaultPosition
if distance < 1 {
topLayoutConstraintOfHiddenTopView.constant = distance
}else {
//slow down HiddenTopView's speed when it needs
topLayoutConstraintOfHiddenTopView.constant = sqrt(distance)
}
if mainViewTopSpaceLayoutConstraintValue + y > hiddenTopView.frame.height * 1.2 {
if middleImageViewHasBeenEnlarged {
enlargeMiddleImageView()
middleImageViewHasBeenEnlarged = false
}
}
}
//enlarge middle image
func enlargeMiddleImageView() {
UIView.animateWithDuration(0.5, delay: 0.2, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
self.hiddenBannerView.transform = CGAffineTransformMakeScale(1.1, 1.1)
}) { (success) -> Void in
if success {
return
}
}
}
}
| mit | 5751a7f05d1462722fc4e5c99c9193b8 | 36.841727 | 136 | 0.620722 | 5.213082 | false | false | false | false |
savelii/BSON | Sources/ExtractionSubscripts.swift | 1 | 7869 | import Foundation
extension Document {
public subscript(parts: SubscriptExpressionType...) -> String? {
get {
return self[raw: parts]?.string
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: SubscriptExpressionType...) -> Int? {
get {
return self[raw: parts]?.int
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: SubscriptExpressionType...) -> Int32? {
get {
return self[raw: parts]?.int32
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: SubscriptExpressionType...) -> Int64? {
get {
return self[raw: parts]?.int64
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: SubscriptExpressionType...) -> Bool? {
get {
return self[raw: parts]?.boolValue
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: SubscriptExpressionType...) -> Double? {
get {
return self[raw: parts]?.double
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: SubscriptExpressionType...) -> Date? {
get {
return self[raw: parts]?.dateValue
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: SubscriptExpressionType...) -> Document? {
get {
return self[raw: parts]?.documentValue
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: SubscriptExpressionType...) -> [String: ValueConvertible]? {
get {
return (self[parts] as Document?)?.dictionaryValue
}
set {
if let newValue = newValue {
self[raw: parts] = Document(dictionaryElements: newValue.map { ($0.0, $0.1) })
} else {
self[raw: parts] = nil
}
}
}
public subscript(parts: SubscriptExpressionType...) -> [ValueConvertible]? {
get {
return (self[parts] as Document?)?.arrayValue
}
set {
if let newValue = newValue {
self[raw: parts] = Document(array: newValue)
} else {
self[raw: parts] = nil
}
}
}
public subscript(parts: SubscriptExpressionType...) -> ObjectId? {
get {
return self[raw: parts]?.objectIdValue
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: SubscriptExpressionType...) -> Timestamp? {
get {
return self[raw: parts] as? Timestamp
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: SubscriptExpressionType...) -> Binary? {
get {
return self[raw: parts] as? Binary
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: SubscriptExpressionType...) -> Data? {
get {
return (self[raw: parts] as? Binary)?.data
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: SubscriptExpressionType...) -> Null? {
get {
return self[raw: parts] as? Null
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: SubscriptExpressionType...) -> JavascriptCode? {
get {
return self[raw: parts] as? JavascriptCode
}
set {
self[raw: parts] = newValue
}
}
#if swift(>=3.1)
public subscript(parts: SubscriptExpressionType...) -> NSRegularExpression? {
get {
return self[raw: parts] as? NSRegularExpression
}
set {
self[raw: parts] = newValue
}
}
#else
public subscript(parts: SubscriptExpressionType...) -> RegularExpression? {
get {
return self[raw: parts] as? RegularExpression
}
set {
self[raw: parts] = newValue
}
}
#endif
}
extension Document {
public subscript(parts: [SubscriptExpressionType]) -> String? {
get {
return self[raw: parts]?.string
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: [SubscriptExpressionType]) -> Int? {
get {
return self[raw: parts]?.int
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: [SubscriptExpressionType]) -> Int32? {
get {
return self[raw: parts]?.int32
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: [SubscriptExpressionType]) -> Int64? {
get {
return self[raw: parts]?.int64
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: [SubscriptExpressionType]) -> Bool? {
get {
return self[raw: parts]?.boolValue
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: [SubscriptExpressionType]) -> Double? {
get {
return self[raw: parts]?.double
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: [SubscriptExpressionType]) -> Date? {
get {
return self[raw: parts]?.dateValue
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: [SubscriptExpressionType]) -> Document? {
get {
return self[raw: parts]?.documentValue
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: [SubscriptExpressionType]) -> ObjectId? {
get {
return self[raw: parts]?.objectIdValue
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: [SubscriptExpressionType]) -> Timestamp? {
get {
return self[raw: parts] as? Timestamp
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: [SubscriptExpressionType]) -> Binary? {
get {
return self[raw: parts] as? Binary
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: [SubscriptExpressionType]) -> Data? {
get {
return (self[raw: parts] as? Binary)?.data
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: [SubscriptExpressionType]) -> Null? {
get {
return self[raw: parts] as? Null
}
set {
self[raw: parts] = newValue
}
}
public subscript(parts: [SubscriptExpressionType]) -> JavascriptCode? {
get {
return self[raw: parts] as? JavascriptCode
}
set {
self[raw: parts] = newValue
}
}
#if swift(>=3.1)
public subscript(parts: [SubscriptExpressionType]) -> NSRegularExpression? {
get {
return self[raw: parts] as? NSRegularExpression
}
set {
self[raw: parts] = newValue
}
}
#else
public subscript(parts: [SubscriptExpressionType]) -> RegularExpression? {
get {
return self[raw: parts] as? RegularExpression
}
set {
self[raw: parts] = newValue
}
}
#endif
}
| mit | 281be8498b4abcc81eedd8cb8ba7bffe | 23.514019 | 94 | 0.484814 | 4.757557 | false | false | false | false |
jzucker2/SwiftyKit | SwiftyKit/Classes/NSManagedObjectContext+Extensions.swift | 1 | 3232 | //
// NSManagedObjectContext+Extensions.swift
// PomodoroTurntableApp
//
// Created by Jordan Zucker on 7/23/17.
// Copyright © 2017 Stanera. All rights reserved.
//
import CoreData
extension NSManagedObjectContext {
private var store: NSPersistentStore {
guard let psc = persistentStoreCoordinator else { fatalError("PSC missing") }
guard let store = psc.persistentStores.first else { fatalError("No Store") }
return store
}
public var metaData: [String: Any] {
get {
guard let psc = persistentStoreCoordinator else { fatalError("must have PSC") }
return psc.metadata(for: store) as [String : Any]
}
set {
performChanges {
guard let psc = self.persistentStoreCoordinator else { fatalError("PSC missing") }
psc.setMetadata(newValue, for: self.store)
}
}
}
public func setMetaData(object: Any?, forKey key: String) {
var md = metaData
md[key] = object
metaData = md
}
public func insertObject<T: NSManagedObject>() -> T where T: Managed {
guard let obj = NSEntityDescription.insertNewObject(forEntityName: T.entityName, into: self) as? T else { fatalError("Wrong object type") }
return obj
}
public func saveOrRollback() -> Bool {
do {
try save()
return true
} catch {
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print("!!!!!!!!!!!!!!!! Caught for rollback: \(error.localizedDescription)")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
rollback()
return false
}
}
public func performSaveOrRollback() {
perform {
_ = self.saveOrRollback()
}
}
public func performChanges(block: @escaping () -> ()) {
perform {
block()
_ = self.saveOrRollback()
}
}
}
private let SingleObjectCacheKey = "SingleObjectCache"
private typealias SingleObjectCache = [String:NSManagedObject]
extension NSManagedObjectContext {
public func set(_ object: NSManagedObject?, forSingleObjectCacheKey key: String) {
var cache = userInfo[SingleObjectCacheKey] as? SingleObjectCache ?? [:]
cache[key] = object
userInfo[SingleObjectCacheKey] = cache
}
public func object(forSingleObjectCacheKey key: String) -> NSManagedObject? {
guard let cache = userInfo[SingleObjectCacheKey] as? [String:NSManagedObject] else { return nil }
return cache[key]
}
}
| mit | b8f6c32868793679a8d2fff4cdb0f57f | 33.741935 | 147 | 0.481585 | 5.296721 | false | false | false | false |
tutsplus/iOSFromScratch-ShoppingList-2 | Shopping List/EditItemViewController.swift | 1 | 1451 | //
// EditItemViewController.swift
// Shopping List
//
// Created by Bart Jacobs on 18/12/15.
// Copyright © 2015 Envato Tuts+. All rights reserved.
//
import UIKit
protocol EditItemViewControllerDelegate {
func controller(controller: EditItemViewController, didUpdateItem item: Item)
}
class EditItemViewController: UIViewController {
@IBOutlet var nameTextField: UITextField!
@IBOutlet var priceTextField: UITextField!
var item: Item!
var delegate: EditItemViewControllerDelegate?
// MARK: -
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Create Save Button
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Save, target: self, action: "save:")
// Populate Text Fields
nameTextField.text = item.name
priceTextField.text = "\(item.price)"
}
// MARK: -
// MARK: Actions
func save(sender: UIBarButtonItem) {
if let name = nameTextField.text, let priceAsString = priceTextField.text, let price = Float(priceAsString) {
// Update Item
item.name = name
item.price = price
// Notify Delegate
delegate?.controller(self, didUpdateItem: item)
// Pop View Controller
navigationController?.popViewControllerAnimated(true)
}
}
}
| bsd-2-clause | 101d75551248c11da641eccebac39b78 | 26.358491 | 118 | 0.626897 | 5.105634 | false | false | false | false |
Limon-O-O/Medusa | MED/Views/FocusOverlay.swift | 1 | 3036 | //
// FocusOverlay.swift
// VideoRecorderExample
//
// Created by Limon on 6/15/16.
// Copyright © 2016 VideoRecorder. All rights reserved.
//
import UIKit
class FocusOverlay: UIView {
var topLeftCornerLines = [UIView]()
var topRightCornerLines = [UIView]()
var bottomLeftCornerLines = [UIView]()
var bottomRightCornerLines = [UIView]()
let cornerDepth: CGFloat = 3
let cornerWidth: CGFloat = 20
let lineWidth: CGFloat = 1
init() {
super.init(frame: CGRect.zero)
createLines()
}
override init(frame: CGRect) {
super.init(frame: frame)
createLines()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
createLines()
}
override func layoutSubviews() {
let corners = [topLeftCornerLines, topRightCornerLines, bottomLeftCornerLines, bottomRightCornerLines]
for i in 0..<corners.count {
let corner = corners[i]
var horizontalFrame: CGRect
var verticalFrame: CGRect
switch (i) {
case 0:
verticalFrame = CGRect(x: -cornerDepth, y: -cornerDepth, width: cornerDepth, height: cornerWidth)
horizontalFrame = CGRect(x: -cornerDepth, y: -cornerDepth, width: cornerWidth, height: cornerDepth)
break
case 1:
verticalFrame = CGRect(x: bounds.width, y: -cornerDepth, width: cornerDepth, height: cornerWidth)
horizontalFrame = CGRect(x: bounds.width + cornerDepth - cornerWidth, y: -cornerDepth, width: cornerWidth, height: cornerDepth)
break
case 2:
verticalFrame = CGRect(x: -cornerDepth, y: bounds.height + cornerDepth - cornerWidth, width: cornerDepth, height: cornerWidth)
horizontalFrame = CGRect(x: -cornerDepth, y: bounds.height, width: cornerWidth, height: cornerDepth)
break
case 3:
verticalFrame = CGRect(x: bounds.width, y: bounds.height + cornerDepth - cornerWidth, width: cornerDepth, height: cornerWidth)
horizontalFrame = CGRect(x: bounds.width + cornerDepth - cornerWidth, y: bounds.height, width: cornerWidth, height: cornerDepth)
break
default:
verticalFrame = CGRect.zero
horizontalFrame = CGRect.zero
break
}
corner[0].frame = verticalFrame
corner[1].frame = horizontalFrame
}
}
func createLines() {
topLeftCornerLines = [createLine(), createLine()]
topRightCornerLines = [createLine(), createLine()]
bottomLeftCornerLines = [createLine(), createLine()]
bottomRightCornerLines = [createLine(), createLine()]
isUserInteractionEnabled = false
}
func createLine() -> UIView {
let line = UIView()
line.backgroundColor = UIColor.white
addSubview(line)
return line
}
}
| mit | 2abbbd6df89387ec1963f1f1495af560 | 32.351648 | 147 | 0.602965 | 4.450147 | false | false | false | false |
niunaruto/DeDaoAppSwift | testSwift/Pods/BSImagePicker/Sources/View/CameraCell.swift | 1 | 2839 | //
// CameraCell.swift
// Pods
//
// Created by Joakim Gyllström on 2015-09-26.
//
//
import UIKit
import AVFoundation
/**
*/
final class CameraCell: UICollectionViewCell {
static let cellIdentifier = "cameraCellIdentifier"
let imageView: UIImageView = UIImageView(frame: .zero)
let cameraBackground: UIView = UIView(frame: .zero)
var takePhotoIcon: UIImage? {
didSet {
imageView.image = takePhotoIcon
// Apply tint to image
imageView.image = imageView.image?.withRenderingMode(.alwaysTemplate)
}
}
var session: AVCaptureSession?
var captureLayer: AVCaptureVideoPreviewLayer?
let sessionQueue = DispatchQueue(label: "AVCaptureVideoPreviewLayer", attributes: [])
override init(frame: CGRect) {
super.init(frame: frame)
cameraBackground.frame = contentView.bounds
cameraBackground.autoresizingMask = [.flexibleWidth, .flexibleHeight]
contentView.addSubview(cameraBackground)
imageView.frame = contentView.bounds
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
imageView.contentMode = .center
contentView.addSubview(imageView)
setupCaptureLayer()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
captureLayer?.frame = bounds
}
func startLiveBackground() {
sessionQueue.async { () -> Void in
self.session?.startRunning()
}
}
func stopLiveBackground() {
sessionQueue.async { () -> Void in
self.session?.stopRunning()
}
}
private func setupCaptureLayer() {
// Don't trigger camera access for the background
guard AVCaptureDevice.authorizationStatus(for: AVMediaType.video) == .authorized else {
return
}
do {
// Prepare avcapture session
session = AVCaptureSession()
session?.sessionPreset = AVCaptureSession.Preset.medium
// Hook upp device
let device = AVCaptureDevice.default(for: AVMediaType.video)
let input = try AVCaptureDeviceInput(device: device!)
session?.addInput(input)
// Setup capture layer
guard session != nil else {
return
}
let captureLayer = AVCaptureVideoPreviewLayer(session: session!)
captureLayer.frame = bounds
captureLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
cameraBackground.layer.addSublayer(captureLayer)
self.captureLayer = captureLayer
} catch {
session = nil
}
}
}
| mit | 14403a23a39e6d2d5d8dab1f500d006f | 27.09901 | 95 | 0.618746 | 5.532164 | false | false | false | false |
al7/DashView | DashView/Source/DashView.swift | 1 | 2137 | /*
Copyright (c) 2015 - Alex Leite (al7dev)
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
@IBDesignable open class DashView: UIView {
@IBInspectable open var dashWidth: CGFloat = 3.0
@IBInspectable open var dashSpace: CGFloat = 1.0
@IBInspectable open var dashColor: UIColor = UIColor.darkGray
//MARK- Initializers
public override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = UIColor.clear
}
//MARK- Base Overrides
open override func draw(_ rect: CGRect) {
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(self.dashColor.cgColor)
var nextDashFrame = CGRect(x: 0.0, y: 0.0, width: self.dashWidth, height: rect.size.height)
while nextDashFrame.origin.x < rect.size.width {
context.fill(nextDashFrame)
nextDashFrame.origin.x += (self.dashWidth + self.dashSpace)
}
}
}
}
| mit | 394415964bae2b6cedc86052e73f2154 | 36.491228 | 103 | 0.708002 | 4.489496 | false | false | false | false |
hooman/swift | test/Concurrency/Runtime/async_taskgroup_cancel_from_inside_child.swift | 2 | 1395 | // RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library) | %FileCheck %s --dump-input always
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
import Dispatch
@available(SwiftStdlib 5.5, *)
func test_taskGroup_cancel_from_inside_child() async {
let one = try! await withTaskGroup(of: Int.self, returning: Int.self) { group in
await group.next()
return 0
}
let two = await withTaskGroup(of: Int.self, returning: Int.self) { group in
0
}
let result = await withTaskGroup(of: Int.self, returning: Int.self) { group in
let firstAdded = group.spawnUnlessCancelled { [group] in // must explicitly capture, as the task executes concurrently
group.cancelAll() // allowed
print("first")
return 1
}
print("firstAdded: \(firstAdded)") // CHECK: firstAdded: true
let one = await group.next()
let secondAdded = group.spawnUnlessCancelled {
print("second")
return 2
}
print("secondAdded: \(secondAdded)") // CHECK: secondAdded: false
return 1
}
print("result: \(result)") // CHECK: result: 1
}
@available(SwiftStdlib 5.5, *)
@main struct Main {
static func main() async {
await test_taskGroup_cancel_from_inside_child()
}
}
| apache-2.0 | 0a7a49848ce0caa6bc967d10fcb48979 | 25.320755 | 150 | 0.67957 | 3.842975 | false | true | false | false |
ru-kio/Hydra | FXHydra/FXDefaultMusicCell.swift | 3 | 4671 | //
// FXDefaultMusicCell.swift
// FXHydra
//
// Created by kioshimafx on 3/14/16.
// Copyright © 2016 FXSolutions. All rights reserved.
//
import UIKit
import ESTMusicIndicator
class FXDefaultMusicCell: UITableViewCell {
var audioAristLabel : AttributedLabel!
var audioTitleLabel : AttributedLabel!
var audioDurationTime : AttributedLabel!
var audioBitrate : AttributedLabel!
var audioTimeLabel : AttributedLabel!
var downloadButton : UIButton!
var downloadedImage : UIImageView!
var bitRateBackgroundImage : UIImageView!
weak var bindedAudioModel : FXAudioItemModel!
//var musicIndicator : ESTMusicIndicatorView!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
// self.musicIndicator = ESTMusicIndicatorView()
// self.musicIndicator.tintColor = UIColor (red: 0.0, green: 0.8408, blue: 1.0, alpha: 1.0)
// self.musicIndicator.hidesWhenStopped = true
super.init(style: UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier)
self.audioTitleLabel = AttributedLabel()
self.audioTitleLabel.font = UIFont(name: "Avenir-Heavy", size: 15)!
self.audioTitleLabel.textColor = UIColor ( red: 0.9508, green: 0.9508, blue: 0.9508, alpha: 1.0 )
self.audioTitleLabel.backgroundColor = UIColor.clearColor()
self.audioAristLabel = AttributedLabel()
self.audioAristLabel.font = UIFont(name: "HelveticaNeue-Light", size: 13)!
self.audioAristLabel.textColor = UIColor ( red: 0.7805, green: 0.7768, blue: 0.7843, alpha: 1.0 )
self.audioAristLabel.backgroundColor = UIColor.clearColor()
self.audioBitrate = AttributedLabel()
self.audioBitrate.font = UIFont(name: "Avenir-Medium", size: 12)!
self.audioBitrate.textColor = UIColor.whiteColor()
self.audioBitrate.backgroundColor = UIColor.clearColor()
self.audioBitrate.contentAlignment = .Center
self.audioTimeLabel = AttributedLabel()
self.audioTimeLabel.font = UIFont(name: "Avenir-Heavy", size: 13)!
self.audioTimeLabel.textColor = UIColor.whiteColor()
self.audioTimeLabel.backgroundColor = UIColor.clearColor()
self.audioTimeLabel.contentAlignment = .Center
self.bitRateBackgroundImage = UIImageView()
self.downloadButton = UIButton(type: UIButtonType.System)
self.downloadedImage = UIImageView()
self.contentView.addSubview(self.downloadButton)
self.contentView.addSubview(self.downloadedImage)
self.contentView.addSubview(self.audioAristLabel)
self.contentView.addSubview(self.audioTitleLabel)
self.contentView.addSubview(self.bitRateBackgroundImage)
self.contentView.addSubview(self.audioBitrate)
self.contentView.addSubview(self.audioTimeLabel)
//self.contentView.addSubview(self.musicIndicator)
self.contentView.backgroundColor = UIColor.clearColor()
self.backgroundColor = UIColor.clearColor()
let colorView = UIView()
colorView.backgroundColor = UIColor ( red: 0.6037, green: 0.6037, blue: 0.6037, alpha: 0.195258620689655 )
self.selectedBackgroundView = colorView
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
self.audioTitleLabel.frame = CGRectMake(self.separatorInset.left, 5, self.contentView.frame.width-100, 20)
self.audioAristLabel.frame = CGRectMake(self.separatorInset.left, 32.5, self.contentView.frame.width-100, 20)
self.audioTimeLabel.frame = CGRectMake(5, 5, 40, 20)
self.bitRateBackgroundImage.frame = CGRectMake(10, 32.5, 30, 20)
self.audioBitrate.frame = CGRectMake(10, 32.5, 30, 20)
self.downloadedImage.frame = CGRectMake(self.contentView.frame.width-40, 15, 30, 30)
self.downloadButton.frame = CGRectMake(self.contentView.frame.width-40, 15, 30, 30)
//self.musicIndicator.frame = CGRectMake(self.contentView.frame.width-40, 15, 30, 30)
}
override func prepareForReuse() {
super.prepareForReuse()
//self.musicIndicator.state = ESTMusicIndicatorViewState.ESTMusicIndicatorViewStateStopped
self.downloadButton.hidden = false
}
}
| mit | 59dc192b875ba8152fdb1bfd637bd640 | 38.91453 | 117 | 0.656745 | 4.582924 | false | false | false | false |
remobjects/Marzipan | CodeGen4/CGJavaCodeGenerator.swift | 1 | 32555 | public enum CGJavaCodeGeneratorDialect {
case Standard
case Iodine
}
public class CGJavaCodeGenerator : CGCStyleCodeGenerator {
public init() {
super.init()
// current as of Elements 8.1 and C# 6.0
keywords = ["__assembly", "__block", "__extension", "__get", "__module", "__out", "__partial", "__ref", "__selector", "__set", "__strong", "__struct", "__unretained", "__weak",
"abstract", "continue", "for", "new", "switch", "assert", "default", "goto", "package", "synchronized", "boolean", "do", "if",
"private", "this", "break", "double", "implements", "protected", "throw", "byte", "else", "import", "public", "throws", "case",
"enum", "instanceof", "return", "transient", "catch", "extends", "int", "short", "try", "char", "final", "interface", "static",
"void", "class", "finally", "long", "strictfp", "volatile", "const", "float", "native", "super", "while"].ToList() as! List<String>
}
public var Dialect: CGJavaCodeGeneratorDialect = .Standard
public var isElements: Boolean { return isIodine }
public var isIodine: Boolean { return Dialect == .Iodine }
public var isStandard: Boolean { return Dialect == .Standard }
public convenience init(dialect: CGJavaCodeGeneratorDialect) {
init()
Dialect = dialect
}
public override var defaultFileExtension: String { return "java" }
override func escapeIdentifier(_ name: String) -> String {
return name // todo
}
override func generateHeader() {
super.generateHeader()
if let namespace = currentUnit.Namespace {
Append("package ")
generateIdentifier(namespace.Name, alwaysEmitNamespace: true)
AppendLine(";")
AppendLine()
}
}
override func generateFooter() {
}
override func generateImport(_ imp: CGImport) {
if imp.StaticClass != nil {
Append("import ")
generateIdentifier(imp.StaticClass!.Name, alwaysEmitNamespace: true)
AppendLine(";")
} else {
Append("import ")
generateIdentifier(imp.Namespace!.Name, alwaysEmitNamespace: true)
AppendLine(".*;")
}
}
override func generateGlobals() {
if let globals = currentUnit.Globals, globals.Count > 0{
AppendLine("public static class __Globals")
AppendLine("{")
incIndent()
super.generateGlobals()
decIndent()
AppendLine("}")
AppendLine()
}
}
/*
override func generateInlineComment(_ comment: String) {
// handled in base
}
*/
//
// Statements
//
// in C-styleCG Base class
/*
override func generateBeginEndStatement(_ statement: CGBeginEndBlockStatement) {
// handled in base
}
*/
/*
override func generateIfElseStatement(_ statement: CGIfThenElseStatement) {
// handled in base
}
*/
/*
override func generateForToLoopStatement(_ statement: CGForToLoopStatement) {
// handled in base
}
*/
override func generateForEachLoopStatement(_ statement: CGForEachLoopStatement) {
Append("for (")
if let type = statement.LoopVariableType {
generateTypeReference(type)
Append(" ")
}
generateIdentifier(statement.LoopVariableName)
Append(": ")
generateExpression(statement.Collection)
AppendLine(")")
generateStatementIndentedUnlessItsABeginEndBlock(statement.NestedStatement)
}
/*
override func generateWhileDoLoopStatement(_ statement: CGWhileDoLoopStatement) {
// handled in base
}
*/
/*
override func generateDoWhileLoopStatement(_ statement: CGDoWhileLoopStatement) {
// handled in base
}
*/
/*
override func generateInfiniteLoopStatement(_ statement: CGInfiniteLoopStatement) {
// handled in base
}
*/
/*
override func generateSwitchStatement(_ statement: CGSwitchStatement) {
// handled in base
}
*/
override func generateLockingStatement(_ statement: CGLockingStatement) {
Append("lock (")
generateExpression(statement.Expression)
AppendLine(")")
generateStatementIndentedUnlessItsABeginEndBlock(statement.NestedStatement)
}
override func generateUsingStatement(_ statement: CGUsingStatement) {
Append("using (")
if let type = statement.`Type` {
generateTypeReference(type)
Append(" ")
} else {
Append("var ")
}
generateIdentifier(statement.Name)
Append(" = ")
generateExpression(statement.Value)
AppendLine(")")
generateStatementIndentedUnlessItsABeginEndBlock(statement.NestedStatement)
}
override func generateAutoReleasePoolStatement(_ statement: CGAutoReleasePoolStatement) {
assert(false, "generateAutoReleasePoolStatement is not supported in Java")
}
override func generateTryFinallyCatchStatement(_ statement: CGTryFinallyCatchStatement) {
AppendLine("try")
AppendLine("{")
incIndent()
generateStatements(statement.Statements)
decIndent()
AppendLine("}")
if let finallyStatements = statement.FinallyStatements, finallyStatements.Count > 0 {
AppendLine("finally")
AppendLine("{")
incIndent()
generateStatements(finallyStatements)
decIndent()
AppendLine("}")
}
if let catchBlocks = statement.CatchBlocks, catchBlocks.Count > 0 {
for b in catchBlocks {
if let name = b.Name, let type = b.`Type` {
Append("catch (")
generateTypeReference(type)
Append(" ")
generateIdentifier(name)
AppendLine(")")
AppendLine("{")
} else {
AppendLine("__catch ")
AppendLine("{")
}
incIndent()
generateStatements(b.Statements)
decIndent()
AppendLine("}")
}
}
}
/*
override func generateReturnStatement(_ statement: CGReturnStatement) {
// handled in base
}
*/
override func generateThrowStatement(_ statement: CGThrowStatement) {
if let value = statement.Exception {
Append("throw ")
generateExpression(value)
AppendLine()
} else {
AppendLine("throw")
}
AppendLine(";")
}
/*
override func generateBreakStatement(_ statement: CGBreakStatement) {
// handled in base
}
*/
/*
override func generateContinueStatement(_ statement: CGContinueStatement) {
// handled in base
}
*/
override func generateVariableDeclarationStatement(_ statement: CGVariableDeclarationStatement) {
if let type = statement.`Type` {
generateTypeReference(type)
Append(" ")
} else {
Append("var ")
}
generateIdentifier(statement.Name)
if let value = statement.Value {
Append(" = ")
generateExpression(value)
}
AppendLine(";")
}
override func generateAssignmentStatement(_ statement: CGAssignmentStatement) {
// Hack for Java not knwoing about properties
if Dialect != .Iodine, let property = statement.Target as? CGPropertyAccessExpression {
javaGenerateCallSiteForExpression(property)
generateIdentifier("set"+uppercaseFirstLetter(property.Name))
Append("(")
if let params = property.Parameters, params.Count > 0 {
javaGenerateCallParameters(property.Parameters)
Append(", ")
}
generateExpression(statement.Value)
Append(")")
} else {
super.generateAssignmentStatement(statement)
}
}
override func generateConstructorCallStatement(_ statement: CGConstructorCallStatement) {
if let callSite = statement.CallSite {
if callSite is CGInheritedExpression {
Append("super")
} else if callSite is CGSelfExpression {
Append("this")
} else {
assert(false, "Unsupported call site for constructor call.")
}
}
if let name = statement.ConstructorName {
Append(" ")
Append(name)
}
Append("(")
javaGenerateCallParameters(statement.Parameters)
AppendLine(");")
}
//
// Expressions
//
/*
override func generateNamedIdentifierExpression(_ expression: CGNamedIdentifierExpression) {
// handled in base
}
*/
/*
override func generateAssignedExpression(_ expression: CGAssignedExpression) {
// handled in base
}
*/
/*
override func generateSizeOfExpression(_ expression: CGSizeOfExpression) {
// handled in base
}
*/
override func generateTypeOfExpression(_ expression: CGTypeOfExpression) {
generateExpression(expression.Expression)
Append(".class")
}
override func generateDefaultExpression(_ expression: CGDefaultExpression) {
}
override func generateSelectorExpression(_ expression: CGSelectorExpression) {
assert(false, "generateSelectorExpression is not supported")
}
override func generateTypeCastExpression(_ cast: CGTypeCastExpression) {
Append("((")
generateTypeReference(cast.TargetType)
Append(")(")
generateExpression(cast.Expression)
Append("))")
if !cast.ThrowsException {
Append("/* exception-less casts not supported */")
}
}
override func generateInheritedExpression(_ expression: CGInheritedExpression) {
Append("super")
}
override func generateSelfExpression(_ expression: CGSelfExpression) {
Append("this")
}
override func generateNilExpression(_ expression: CGNilExpression) {
Append("null")
}
override func generatePropertyValueExpression(_ expression: CGPropertyValueExpression) {
Append("value")
}
override func generateAwaitExpression(_ expression: CGAwaitExpression) {
assert(false, "generateAwaitExpression is not supported in Java")
}
override func generateAnonymousMethodExpression(_ expression: CGAnonymousMethodExpression) {
}
override func generateAnonymousTypeExpression(_ expression: CGAnonymousTypeExpression) {
}
override func generatePointerDereferenceExpression(_ expression: CGPointerDereferenceExpression) {
}
/*
override func generateUnaryOperatorExpression(_ expression: CGUnaryOperatorExpression) {
// handled in base
}
*/
/*
override func generateBinaryOperatorExpression(_ expression: CGBinaryOperatorExpression) {
// handled in base
}
*/
/*
override func generateUnaryOperator(_ `operator`: CGUnaryOperatorKind) {
// handled in base
}
*/
override func generateBinaryOperator(_ `operator`: CGBinaryOperatorKind) {
switch (`operator`) {
case .Is: Append("instanceof")
case .AddEvent: Append("+=")
case .RemoveEvent: Append("-=")
default: super.generateBinaryOperator(`operator`)
}
}
/*
override func generateIfThenElseExpression(_ expression: CGIfThenElseExpression) {
// handled in base
}
*/
/*
override func generateArrayElementAccessExpression(_ expression: CGArrayElementAccessExpression) {
// handled in base
}
*/
internal func javaGenerateStorageModifierPrefixIfNeeded(_ storageModifier: CGStorageModifierKind) {
if Dialect != .Iodine {
switch storageModifier {
case .Strong: break
case .Weak: Append("__weak ")
case .Unretained: Append("__unretained ")
}
}
}
internal func javaGenerateCallSiteForExpression(_ expression: CGMemberAccessExpression) {
if let callSite = expression.CallSite {
generateExpression(callSite)
if (expression.Name != "") {
if expression.NilSafe {
Append("?.")
} else {
Append(".")
}
}
}
}
func javaGenerateCallParameters(_ parameters: List<CGCallParameter>) {
for p in 0 ..< parameters.Count {
let param = parameters[p]
if p > 0 {
if Dialect == .Iodine, let name = param.Name {
Append(") ")
generateIdentifier(name)
Append("(")
} else {
Append(", ")
}
}
if Dialect == .Iodine {
switch param.Modifier {
case .Var: self.Append("__ref ")
case .Out: self.Append("__out ")
default:
}
}
generateExpression(param.Value)
}
}
func javaGenerateAttributeParameters(_ parameters: List<CGCallParameter>) {
for p in 0 ..< parameters.Count {
let param = parameters[p]
if p > 0 {
Append(", ")
}
if let name = param.Name {
generateIdentifier(name)
Append(" = ")
}
generateExpression(param.Value)
}
}
override func generateParameterDefinition(_ param: CGParameterDefinition) {
if Dialect == .Iodine {
switch param.Modifier {
case .Var: Append("__ref ")
//case .Const: Append("const ") //todo: Oxygene ony?
case .Out: Append("__out ")
//case .Params: Append("params ")
default:
}
}
if let type = param.`Type` {
generateTypeReference(type)
}
Append(" ")
generateIdentifier(param.Name)
if let defaultValue = param.DefaultValue {
Append(" = ")
generateExpression(defaultValue)
}
}
func javaGenerateDefinitionParameters(_ parameters: List<CGParameterDefinition>) {
helpGenerateCommaSeparatedList(parameters) { param in
self.generateParameterDefinition(param)
}
}
func javaGenerateAncestorList(_ type: CGClassOrStructTypeDefinition) {
if type.Ancestors.Count > 0 {
Append(" extends ")
for a in 0 ..< type.Ancestors.Count {
if let ancestor = type.Ancestors[a] {
if a > 0 {
Append(", ")
}
generateTypeReference(ancestor)
}
}
}
if type.ImplementedInterfaces.Count > 0 {
Append(" implements ")
for a in 0 ..< type.ImplementedInterfaces.Count {
if let interface = type.ImplementedInterfaces[a] {
if a > 0 {
Append(", ")
}
generateTypeReference(interface)
}
}
}
}
override func generateFieldAccessExpression(_ expression: CGFieldAccessExpression) {
javaGenerateCallSiteForExpression(expression)
generateIdentifier(expression.Name)
}
override func generateMethodCallExpression(_ method: CGMethodCallExpression) {
javaGenerateCallSiteForExpression(method)
generateIdentifier(method.Name)
generateGenericArguments(method.GenericArguments)
Append("(")
javaGenerateCallParameters(method.Parameters)
Append(")")
}
override func generateNewInstanceExpression(_ expression: CGNewInstanceExpression) {
Append("new ")
generateExpression(expression.`Type`)
Append("(")
javaGenerateCallParameters(expression.Parameters)
Append(")")
if let propertyInitializers = expression.PropertyInitializers, propertyInitializers.Count > 0 {
Append(" /* Property Initializers : ")
helpGenerateCommaSeparatedList(propertyInitializers) { param in
self.Append(param.Name)
self.Append(" = ")
self.generateExpression(param.Value)
}
Append(" */")
}
}
override func generatePropertyAccessExpression(_ property: CGPropertyAccessExpression) {
javaGenerateCallSiteForExpression(property)
if Dialect == .Iodine {
generateIdentifier(property.Name)
if let params = property.Parameters, params.Count > 0 {
Append("[")
javaGenerateCallParameters(property.Parameters)
Append("]")
}
} else {
generateIdentifier("get"+uppercaseFirstLetter(property.Name))
Append("(")
if let params = property.Parameters, params.Count > 0 {
javaGenerateCallParameters(property.Parameters)
}
Append(")")
}
}
/*
override func generateStringLiteralExpression(_ expression: CGStringLiteralExpression) {
// handled in base
}
*/
/*
override func generateCharacterLiteralExpression(_ expression: CGCharacterLiteralExpression) {
// handled in base
}
*/
/*
override func generateIntegerLiteralExpression(_ expression: CGIntegerLiteralExpression) {
// handled in base
}
*/
/*
override func generateFloatLiteralExpression(_ literalExpression: CGFloatLiteralExpression) {
// handled in base
}
*/
override func generateArrayLiteralExpression(_ array: CGArrayLiteralExpression) {
Append("{")
for e in 0 ..< array.Elements.Count {
if e > 0 {
Append(", ")
}
generateExpression(array.Elements[e])
}
Append("}")
}
override func generateSetLiteralExpression(_ expression: CGSetLiteralExpression) {
assert(false, "Sets are not supported in Java")
}
override func generateDictionaryExpression(_ dictionary: CGDictionaryLiteralExpression) {
}
/*
override func generateTupleExpression(_ expression: CGTupleLiteralExpression) {
// default handled in base
}
*/
override func generateSetTypeReference(_ setType: CGSetTypeReference, ignoreNullability: Boolean = false) {
assert(false, "generateSetTypeReference is not supported in Java")
}
override func generateSequenceTypeReference(_ sequence: CGSequenceTypeReference, ignoreNullability: Boolean = false) {
assert(false, "generateSequenceTypeReference is not supported in Javar")
}
//
// Type Definitions
//
override func generateAttribute(_ attribute: CGAttribute, inline: Boolean) {
Append("@")
generateTypeReference(attribute.`Type`)
if let parameters = attribute.Parameters, parameters.Count > 0 {
Append("(")
javaGenerateAttributeParameters(parameters)
Append(")")
}
if let comment = attribute.Comment {
Append(" ")
generateSingleLineCommentStatement(comment)
} else {
if inline {
Append(" ")
} else {
AppendLine()
}
}
}
func javaGenerateTypeVisibilityPrefix(_ visibility: CGTypeVisibilityKind) {
switch visibility {
case .Unspecified: break /* no-op */
case .Unit: Append("internal ")
case .Assembly: Append("internal ")
case .Public: Append("public ")
}
}
func javaGenerateMemberTypeVisibilityPrefix(_ visibility: CGMemberVisibilityKind) {
switch visibility {
case .Unspecified: break /* no-op */
case .Private: Append("private ")
case .Unit: fallthrough
case .UnitOrProtected: fallthrough
case .UnitAndProtected: fallthrough
case .Assembly: fallthrough
case .AssemblyAndProtected: Append("internal ")
case .AssemblyOrProtected: fallthrough
case .Protected: Append("protected ")
case .Published: fallthrough
case .Public: Append("public ")
}
}
func javaGenerateStaticPrefix(_ isStatic: Boolean) {
if isStatic {
Append("static ")
}
}
func javaGenerateAbstractPrefix(_ isAbstract: Boolean) {
if isAbstract {
Append("abstract ")
}
}
func javaGeneratePartialPrefix(_ isPartial: Boolean) {
if isPartial && Dialect == .Iodine {
Append("__partial ")
}
}
func javaGenerateSealedPrefix(_ isSealed: Boolean) {
if isSealed {
Append("final ")
}
}
func javaGenerateVirtualityPrefix(_ member: CGMemberDefinition) {
switch member.Virtuality {
//case .None
//case .Virtual:
//case .Override:
//case .Reintroduced:
case .Abstract: Append("abstract ")
case .Final: Append("final ")
default:
}
}
override func generateAliasType(_ type: CGTypeAliasDefinition) {
}
override func generateBlockType(_ block: CGBlockTypeDefinition) {
if Dialect != .Iodine {
assert(false, "generateBlockType is not supported in Java, except in Iodine")
}
if block.IsPlainFunctionPointer {
Append("@FunctionPointer ")
}
javaGenerateTypeVisibilityPrefix(block.Visibility)
Append("__block ")
if let returnType = block.ReturnType {
generateTypeReference(returnType)
} else {
Append("void")
}
Append(" ")
generateIdentifier(block.Name)
Append(" (")
if let parameters = block.Parameters, parameters.Count > 0 {
javaGenerateDefinitionParameters(parameters)
}
AppendLine(");")
}
override func generateEnumType(_ type: CGEnumTypeDefinition) {
javaGenerateTypeVisibilityPrefix(type.Visibility)
Append("enum ")
generateIdentifier(type.Name)
//ToDo: generic constraints
if let baseType = type.BaseType {
Append(" : ")
generateTypeReference(baseType)
}
AppendLine()
AppendLine("{")
incIndent()
helpGenerateCommaSeparatedList(type.Members) { m in
if let member = m as? CGEnumValueDefinition {
self.generateAttributes(member.Attributes, inline: true)
self.generateIdentifier(member.Name)
if let value = member.Value {
self.Append(" = ")
self.generateExpression(value)
}
}
}
AppendLine()
decIndent()
AppendLine("}")
AppendLine()
}
override func generateClassTypeStart(_ type: CGClassTypeDefinition) {
javaGenerateTypeVisibilityPrefix(type.Visibility)
javaGenerateStaticPrefix(type.Static)
javaGenerateAbstractPrefix(type.Abstract)
javaGeneratePartialPrefix(type.Partial)
javaGenerateSealedPrefix(type.Sealed)
Append("class ")
generateIdentifier(type.Name)
//ToDo: generic constraints
javaGenerateAncestorList(type)
AppendLine()
AppendLine("{")
incIndent()
}
override func generateClassTypeEnd(_ type: CGClassTypeDefinition) {
decIndent()
AppendLine("}")
}
override func generateStructTypeStart(_ type: CGStructTypeDefinition) {
javaGenerateTypeVisibilityPrefix(type.Visibility)
javaGenerateStaticPrefix(type.Static)
javaGenerateAbstractPrefix(type.Abstract)
javaGeneratePartialPrefix(type.Partial)
javaGenerateSealedPrefix(type.Sealed)
Append("struct ")
generateIdentifier(type.Name)
//ToDo: generic constraints
javaGenerateAncestorList(type)
AppendLine()
AppendLine("{")
incIndent()
}
override func generateStructTypeEnd(_ type: CGStructTypeDefinition) {
decIndent()
AppendLine("}")
}
override func generateInterfaceTypeStart(_ type: CGInterfaceTypeDefinition) {
javaGenerateTypeVisibilityPrefix(type.Visibility)
javaGenerateSealedPrefix(type.Sealed)
Append("interface ")
generateIdentifier(type.Name)
//ToDo: generic constraints
javaGenerateAncestorList(type)
AppendLine()
AppendLine("{")
incIndent()
}
override func generateInterfaceTypeEnd(_ type: CGInterfaceTypeDefinition) {
decIndent()
AppendLine("}")
}
override func generateExtensionTypeStart(_ type: CGExtensionTypeDefinition) {
AppendLine("[Category]")
javaGenerateTypeVisibilityPrefix(type.Visibility)
javaGenerateStaticPrefix(type.Static)
Append("class ")
generateIdentifier(type.Name)
javaGenerateAncestorList(type)
AppendLine()
AppendLine("{")
incIndent()
}
override func generateExtensionTypeEnd(_ type: CGExtensionTypeDefinition) {
decIndent()
AppendLine("}")
}
//
// Type Members
//
override func generateMethodDefinition(_ method: CGMethodDefinition, type: CGTypeDefinition) {
if type is CGInterfaceTypeDefinition {
if method.Optional {
generateAttribute(CGAttribute("Optional".AsTypeReference()));
}
javaGenerateStaticPrefix(method.Static && !type.Static)
} else {
if method.Virtuality == CGMemberVirtualityKind.Override {
generateAttribute(CGAttribute("Override".AsTypeReference()));
}
javaGenerateMemberTypeVisibilityPrefix(method.Visibility)
javaGenerateStaticPrefix(method.Static && !type.Static)
if method.External {
Append("extern ")
}
javaGenerateVirtualityPrefix(method)
}
if let returnType = method.ReturnType {
generateTypeReference(returnType)
Append(" ")
} else {
Append("void ")
}
generateIdentifier(method.Name)
// todo: generics
Append("(")
javaGenerateDefinitionParameters(method.Parameters)
Append(")")
if let `throws` = method.ThrownExceptions, `throws`.Count > 0 {
Append(" throws ")
helpGenerateCommaSeparatedList(`throws`) { t in
self.generateTypeReference(t, ignoreNullability: true)
}
}
if type is CGInterfaceTypeDefinition || method.Virtuality == CGMemberVirtualityKind.Abstract || method.External || definitionOnly {
AppendLine(";")
return
}
AppendLine()
AppendLine("{")
incIndent()
generateStatements(variables: method.LocalVariables)
generateStatements(method.Statements)
decIndent()
AppendLine("}")
}
override func generateConstructorDefinition(_ ctor: CGConstructorDefinition, type: CGTypeDefinition) {
if type is CGInterfaceTypeDefinition {
} else {
javaGenerateMemberTypeVisibilityPrefix(ctor.Visibility)
}
generateIdentifier(type.Name)
Append("(")
if ctor.Parameters.Count > 0 {
javaGenerateDefinitionParameters(ctor.Parameters)
}
AppendLine(")")
if definitionOnly {
AppendLine(";")
return
}
AppendLine("{")
incIndent()
generateStatements(variables: ctor.LocalVariables)
generateStatements(ctor.Statements)
decIndent()
AppendLine("}")
}
override func generateDestructorDefinition(_ dtor: CGDestructorDefinition, type: CGTypeDefinition) {
}
override func generateFinalizerDefinition(_ finalizer: CGFinalizerDefinition, type: CGTypeDefinition) {
}
override func generateFieldDefinition(_ field: CGFieldDefinition, type: CGTypeDefinition) {
javaGenerateMemberTypeVisibilityPrefix(field.Visibility)
javaGenerateStaticPrefix(field.Static && !type.Static)
if field.Constant {
Append("final ")
}
javaGenerateStorageModifierPrefixIfNeeded(field.StorageModifier)
if let type = field.`Type` {
generateTypeReference(type)
Append(" ")
} else {
Append("var ")
}
generateIdentifier(field.Name)
if let value = field.Initializer {
Append(" = ")
generateExpression(value)
}
AppendLine(";")
}
override func generatePropertyDefinition(_ property: CGPropertyDefinition, type: CGTypeDefinition) {
if Dialect != .Iodine {
assert(false, "generatePropertyDefinition is not supported in Java, except in Iodine")
}
javaGenerateMemberTypeVisibilityPrefix(property.Visibility)
javaGenerateStaticPrefix(property.Static && !type.Static)
javaGenerateVirtualityPrefix(property)
javaGenerateStorageModifierPrefixIfNeeded(property.StorageModifier)
if let type = property.`Type` {
generateTypeReference(type)
Append(" ")
} else {
Append("var ")
}
if property.Default {
Append("this")
} else {
generateIdentifier(property.Name)
}
if let params = property.Parameters, params.Count > 0 {
Append("[")
javaGenerateDefinitionParameters(params)
Append("]")
}
func appendGet() {
if let v = property.GetterVisibility {
self.javaGenerateMemberTypeVisibilityPrefix(v)
}
self.Append("__get")
}
func appendSet() {
if let v = property.SetterVisibility {
self.javaGenerateMemberTypeVisibilityPrefix(v)
}
self.Append("__set")
}
if property.GetStatements == nil && property.SetStatements == nil && property.GetExpression == nil && property.SetExpression == nil {
if property.ReadOnly {
Append(" { ")
appendGet()
Append("; }")
} else if property.WriteOnly {
Append(" { ")
appendSet()
Append("; }")
} else {
Append(" { ")
appendGet()
Append("; ")
appendSet()
Append("; }")
}
if let value = property.Initializer {
Append(" = ")
generateExpression(value)
Append(";")
}
AppendLine()
} else {
if definitionOnly {
Append("{ ")
if property.GetStatements != nil || property.GetExpression != nil {
appendGet()
Append("; ")
}
if property.SetStatements != nil || property.SetExpression != nil {
appendSet()
Append("; ")
}
Append("}")
AppendLine()
return
}
AppendLine()
AppendLine("{")
incIndent()
if let getStatements = property.GetStatements {
appendGet()
AppendLine()
AppendLine("{")
incIndent()
generateStatementsSkippingOuterBeginEndBlock(getStatements)
decIndent()
AppendLine("}")
} else if let getExpresssion = property.GetExpression {
appendGet()
AppendLine()
AppendLine("{")
incIndent()
generateStatement(CGReturnStatement(getExpresssion))
decIndent()
AppendLine("}")
}
if let setStatements = property.SetStatements {
appendSet()
AppendLine()
AppendLine("{")
incIndent()
generateStatementsSkippingOuterBeginEndBlock(setStatements)
decIndent()
AppendLine("}")
} else if let setExpression = property.SetExpression {
appendSet()
AppendLine()
AppendLine("{")
incIndent()
generateStatement(CGAssignmentStatement(setExpression, CGPropertyValueExpression.PropertyValue))
decIndent()
AppendLine("}")
}
decIndent()
Append("}")
if let value = property.Initializer {
Append(" = ")
generateExpression(value)
Append(";")
}
AppendLine()
}
}
override func generateEventDefinition(_ event: CGEventDefinition, type: CGTypeDefinition) {
if Dialect != .Iodine {
assert(false, "generateEventDefinition is not supported in Java, except in Iodine")
}
javaGenerateMemberTypeVisibilityPrefix(event.Visibility)
javaGenerateStaticPrefix(event.Static && !type.Static)
javaGenerateVirtualityPrefix(event)
Append("__event ")
if let type = event.`Type` {
generateTypeReference(type)
Append(" ")
}
generateIdentifier(event.Name)
AppendLine(";")
}
override func generateCustomOperatorDefinition(_ customOperator: CGCustomOperatorDefinition, type: CGTypeDefinition) {
generateCommentStatement(CGCommentStatement("Custom Operator \(customOperator.Name)"))
}
//
// Type References
//
override func generatePredefinedTypeReference(_ type: CGPredefinedTypeReference, ignoreNullability: Boolean = false) {
if (!ignoreNullability) && (((type.Nullability == CGTypeNullabilityKind.NullableUnwrapped) && (type.DefaultNullability == CGTypeNullabilityKind.NotNullable)) || (type.Nullability == CGTypeNullabilityKind.NullableNotUnwrapped)) {
switch (type.Kind) {
case .Int: Append("Integer")
case .Int8: Append("Byte")
case .UInt8: if isIodine { Append("UInt8") } else { Append("/* Unsupported type: UInt8 */") }
case .Int16: Append("Short")
case .UInt16: if isIodine { Append("UInt16") } else { Append("/* Unsupported type: UInt16 */") }
case .Int32: Append("Integer")
case .UInt32: if isIodine { Append("UInt32") } else { Append("/* Unsupported type: UInt32 */") }
case .Int64: Append("Long")
case .UInt64: if isIodine { Append("UInt64") } else { Append("/* Unsupported type: UInt64 */") }
case .IntPtr: if isIodine { Append("IntPtr") } else { Append("/* Unsupported type: IntPtr */") }
case .UIntPtr: if isIodine { Append("UIntPtr") } else { Append("/* Unsupported type: UIntPtr */") }
case .Single: Append("Float")
case .Double: Append("Double")
case .Boolean: Append("Boolean")
case .String: Append("String")
case .AnsiChar: Append("AnsiChar")
case .UTF16Char: Append("Char")
case .UTF32Char: if isIodine { Append("UTF32Char") } else { Append("/* Unsupported type: UTF32Char */") }
case .Dynamic: if isIodine { Append("dynamic") } else { Append("/* Unsupported type: Dynamic */") }
case .InstanceType: if isIodine { Append("InstanceType") } else { Append("/* Unsupported type: InstanceType */") }
case .Void: Append("Void")
case .Object: Append("Object")
case .Class: Append("Class") // todo: make platform-specific
default: Append("/*Unsupported type*/")
}
} else {
switch (type.Kind) {
case .Int: Append("int")
case .Int8: Append("byte")
case .UInt8: if isIodine { Append("UInt8") } else { Append("/* Unsupported type: UInt8 */") }
case .Int16: Append("short")
case .UInt16: if isIodine { Append("UInt16") } else { Append("/* Unsupported type: UInt16 */") }
case .Int32: Append("int")
case .UInt32: if isIodine { Append("UInt32") } else { Append("/* Unsupported type: UInt32 */") }
case .Int64: Append("long")
case .UInt64: if isIodine { Append("UInt64") } else { Append("/* Unsupported type: UInt64 */") }
case .IntPtr: if isIodine { Append("IntPtr") } else { Append("/* Unsupported type: IntPtr */") }
case .UIntPtr: if isIodine { Append("UIntPtr") } else { Append("/* Unsupported type: UIntPtr */") }
case .Single: Append("float")
case .Double: Append("double")
case .Boolean: Append("boolean")
case .String: Append("String")
case .AnsiChar: Append("AnsiChar")
case .UTF16Char: Append("Char")
case .UTF32Char: if isIodine { Append("UTF32Char") } else { Append("/* Unsupported type: UTF32Char */") }
case .Dynamic: if isIodine { Append("dynamic") } else { Append("/* Unsupported type: Dynamic */") }
case .InstanceType: if isIodine { Append("InstanceType") } else { Append("/* Unsupported type: InstanceType */") }
case .Void: Append("void")
case .Object: Append("Object")
case .Class: Append("Class") // todo: make platform-specific
default: Append("/*Unsupported type*/")
}
}
}
override func generateInlineBlockTypeReference(_ type: CGInlineBlockTypeReference, ignoreNullability: Boolean = false) {
if Dialect != .Iodine {
assert(false, "generateInlineBlockTypeReference is not supported in Java, except in Iodine")
}
if type.Block.IsPlainFunctionPointer {
Append("[FunctionPointer] ")
}
Append("__block ")
if let returnType = type.Block.ReturnType {
Append(" ")
generateTypeReference(returnType)
} else {
Append("void ")
}
Append("(")
if let parameters = type.Block.Parameters, parameters.Count > 0 {
javaGenerateDefinitionParameters(parameters)
}
Append(")")
}
override func generatePointerTypeReference(_ type: CGPointerTypeReference) {
}
override func generateTupleTypeReference(_ type: CGTupleTypeReference, ignoreNullability: Boolean = false) {
}
override func generateArrayTypeReference(_ type: CGArrayTypeReference, ignoreNullability: Boolean = false) {
generateTypeReference(type.`Type`)
Append("[]")
}
override func generateDictionaryTypeReference(_ type: CGDictionaryTypeReference, ignoreNullability: Boolean = false) {
}
} | bsd-3-clause | c1b1fce3f9e473453d253e2ac7d5d5ba | 25.993367 | 230 | 0.702485 | 3.691653 | false | false | false | false |
firemuzzy/slugg | mobile/Slug/Slug/views/LabledButton.swift | 1 | 2564 | //
// LabledButton.swift
// Slug
//
// Created by Andrew Charkin on 3/21/15.
// Copyright (c) 2015 Slug. All rights reserved.
//
import UIKit
@IBDesignable public class LabledButton: UIButton {
var textLabel: UILabel!
var iconView: UIView!
@IBInspectable public var title: String? {
didSet {
self.textLabel.text = title
}
}
@IBInspectable public var icon: UIImage? {
didSet {
// self.iconView.image = icon
}
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureView()
}
init() {
super.init(frame: CGRectZero)
configureView()
}
override init(frame: CGRect) {
super.init(frame: frame)
configureView()
}
func configureView() {
self.textLabel = UILabel()
self.textLabel.textAlignment = .Center
self.textLabel.adjustsFontSizeToFitWidth = true
self.textLabel.font = UIFont.boldSystemFontOfSize(40)
self.textLabel.numberOfLines = 0
self.textLabel.minimumScaleFactor = 0.01
self.textLabel.textColor = UIColor.whiteColor()
self.textLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
self.textLabel.setContentHuggingPriority(750, forAxis: UILayoutConstraintAxis.Vertical)
self.textLabel.backgroundColor = UIColor.blueColor()
self.addSubview(self.textLabel)
self.iconView = UIView()
self.iconView.backgroundColor = UIColor.yellowColor()
self.addSubview(self.iconView)
self.addConstraint(NSLayoutConstraint(item: self.iconView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: self.iconView, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: self.iconView, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: self.iconView, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1, constant: 0))
self.constrain(.Bottom, relation: .Equal, otherView: self.textLabel, otherAttribute: .Bottom, multiplier: 1, constant: 0)
.constrain(.CenterX, relation: .Equal, otherView: self.textLabel, otherAttribute: .CenterX, multiplier: 1, constant: 0)
.constrain(.Width, relation: .Equal, otherView: self.textLabel, otherAttribute: .Width, multiplier: 1, constant: 0)
self.backgroundColor = UIColor.blackColor()
}
}
| mit | aa39b529371d84d7704e4d4cc3d0bb9b | 33.186667 | 164 | 0.709438 | 4.252073 | false | true | false | false |
tismart/TSMLib | TSMLib/Utils/Macros.swift | 1 | 1324 | //
// Macros.swift
// TSMLib
//
// Created by Franco Castellano on 3/14/16.
// Copyright © 2016 Tismart. All rights reserved.
//
import UIKit
enum UIUserInterfaceIdiom : Int {
case Unspecified
case Phone
case Pad
}
struct ScreenSize {
static let SCREEN_WIDTH = UIScreen.mainScreen().bounds.size.width
static let SCREEN_HEIGHT = UIScreen.mainScreen().bounds.size.height
static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}
struct DeviceType {
static let IS_IPHONE_4_OR_LESS = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0
static let IS_IPHONE_5 = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0
static let IS_IPHONE_6 = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0
static let IS_IPHONE_6P = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0
static let IS_IPAD = UIDevice.currentDevice().userInterfaceIdiom == .Pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0
}
class Macros: NSObject {
}
| mit | 93844dba98265eb2fd23e909edcd5ea7 | 36.8 | 132 | 0.689342 | 3.972973 | false | false | false | false |
exevil/Keys-For-Sketch | Source/Support/NSAlert+Additions.swift | 1 | 4017 | //
// NSAlert+additions.swift
// KeysForSketch
//
// Created by Vyacheslav Dubovitsky on 09/09/2017.
// Copyright © 2017 Vyacheslav Dubovitsky. All rights reserved.
//
extension NSAlert {
/**
Display an alert sheet with given parameters and execute closure associated with pressed button. Buttons will shown on `NSAlert` in the same order in order that provides orderedButtonTitles array
- parameters:
- window: An NSWindow instance new sheet should be attached to. While nil value is passed method will firstly try to attach alert to NSApplication's mainWindow but if it's nil too alert will be shown separately using `runModal()` method.
- style: 'NSAlert''s alertSytle.
- icon: 'NSAlert''s icon.
- messageText: `NSAlert's` messageText.
- informativeText: `NSAlert's` informativeText.
- orderedButtonTitles: Titles of alert buttons ordered from first to last one.
- completionHandler: Closure with pressed button number as a parameter. Button number should correspond the button order in `orderedButtonTitles` parameter's array.
*/
class func showAlert(over window: NSWindow? = nil,
style: NSAlert.Style = .informational,
icon: NSImage? = image(Const.Image.keysIcon),
messageText: String,
informativeText: String,
orderedButtonTitles: [String],
completionHandler: ((_ pressedButtonNumber: Int) -> Void)?
) {
// Make alert
let alert = NSAlert()
alert.alertStyle = style
alert.icon = icon ?? alert.icon
alert.messageText = messageText
alert.informativeText = informativeText
orderedButtonTitles.forEach {
alert.addButton(withTitle: $0)
}
// Handle completion handler
let alertCompletionHandler: (NSApplication.ModalResponse) -> () = { response in
// Responeded buttons have incremental (by 1) indexes started from 1000
let buttonNumber = response.rawValue - 1000
completionHandler?(buttonNumber)
}
// Attach to window if possible and needed
if let win = window {
alert.beginSheetModal(for: win, completionHandler: alertCompletionHandler)
} else {
alertCompletionHandler(alert.runModal())
}
}
/**
`showAlert` method shorthand for quick presentation of error `localizedDescription` as part of message text.
- important: Descriptions of other parameters can be found in `showAlert` method.
- parameters:
- error: Error instance which `localizedDescription` should be used in alert.
- underErrorText: Additional text that should be placed right after an error message.
*/
class func showKeysErrorAlert(over window: NSWindow? = nil,
style: NSAlert.Style = NSAlert.Style.critical,
icon: NSImage? = image(Const.Image.keysIcon),
messageText: String = "Keys For Sketch Error Occurred",
error: Error,
underErrorText: String = "Make sure you running latest versions of Keys and Sketch and contact developer if problem still occurs.",
orderedButtonTitles: [String] = ["OK"],
completionHandler: ((_ pressedButtonNumber: Int) -> Void)? = nil) {
showAlert(over: window,
style: style,
icon: icon,
messageText: messageText,
informativeText: "\(error.localizedDescription)\n· · ·\n\(underErrorText)",
orderedButtonTitles: orderedButtonTitles,
completionHandler: completionHandler)
}
}
| mit | b926b4a61f141da63c5c6f38b21df579 | 47.939024 | 246 | 0.595066 | 5.581363 | false | false | false | false |
cozkurt/coframework | COFramework/COFramework/Swift/Components/Helpers/ImageViewWithMask.swift | 1 | 738 | //
// ImageViewWithMask.swift
// FuzFuz
//
// Created by Cenker Ozkurt on 11/13/19.
// Copyright © 2019 FuzFuz. All rights reserved.
//
import UIKit
@IBDesignable
class UIImageViewWithMask: UIImageView {
var maskImageView = UIImageView()
@IBInspectable
var maskImage: UIImage? {
didSet {
maskImageView.image = maskImage
updateView()
}
}
// This updates mask size when changing device orientation (portrait/landscape)
override func layoutSubviews() {
super.layoutSubviews()
updateView()
}
func updateView() {
if maskImageView.image != nil {
maskImageView.frame = bounds
mask = maskImageView
}
}
}
| gpl-3.0 | 33f35e09a5a07ef9759c00d4cb495c67 | 20.057143 | 83 | 0.61194 | 4.816993 | false | false | false | false |
huangboju/Moots | Examples/UIScrollViewDemo/UIScrollViewDemo/Extensions.swift | 1 | 7823 | //
// Extensions.swift
// UIScrollViewDemo
//
// Created by 黄伯驹 on 2017/11/3.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import UIKit
public class NotificationNames {
fileprivate init() {}
}
/// Base class for static user defaults keys. Specialize with value type
/// and pass key name to the initializer to create a key.
public class NotificationName: NotificationNames {
// TODO: Can we use protocols to ensure ValueType is a compatible type?
public let _key: String
public init(_ key: String) {
self._key = key
super.init()
}
public init(name: NSNotification.Name) {
self._key = name.rawValue
super.init()
}
}
extension NotificationCenter {
static func postNotification(name: NotificationName, object: Any? = nil) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: name._key), object: object)
}
}
extension UIViewController {
func addObserver(with selector: Selector, name: NSNotification.Name, object: Any? = nil) {
NotificationCenter.default.addObserver(self, selector: selector, name: name, object: object)
}
func addObserver(with selector: Selector, name: NotificationName, object: Any? = nil) {
addObserver(with: selector, name: NSNotification.Name(rawValue: name._key), object: object)
}
func postNotification(name: NSNotification.Name, object: Any? = nil) {
NotificationCenter.default.post(name: name, object: object)
}
func postNotification(name: NotificationName, object: Any? = nil) {
postNotification(name: NSNotification.Name(rawValue: name._key), object: object)
}
func removeNotification() {
NotificationCenter.default.removeObserver(self)
}
@discardableResult
func showAlert(actionTitle: String = "确定", title: String? = nil, message: String?, style: UIAlertController.Style = .alert, handle: ((UIAlertAction) -> Void)? = nil) -> UIAlertController {
let alert = UIAlertController(title: title, message: message, preferredStyle: style)
present(alert, animated: true, completion: nil)
return alert.action(actionTitle, handle)
}
}
extension UIAlertController {
@discardableResult
func action(_ title: String, style: UIAlertAction.Style = .`default`, _ handle: ((UIAlertAction) -> Void)? = nil) -> UIAlertController {
let action = UIAlertAction(title: title, style: style, handler: handle)
addAction(action)
return self
}
}
extension UIColor {
// 纯色图片
public func image(size: CGSize, cornerRadius: CGFloat) -> UIImage {
// let size = size.flatted
let opaque = (cornerRadius == 0.0)
UIGraphicsBeginImageContextWithOptions(size, opaque, 0)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(cgColor)
if cornerRadius > 0 {
let path = UIBezierPath(roundedRect: size.rect, cornerRadius: cornerRadius)
path.addClip()
path.fill()
} else {
context?.fill(size.rect)
}
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resultImage!
}
static var random: UIColor {
return UIColor(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1), alpha: 1.0)
}
}
extension UITableView {
/** Resize a tableView header to according to the auto layout of its contents.
- This method can resize a headerView according to changes in a dynamically set text label. Simply place this method inside viewDidLayoutSubviews.
- To animate constrainsts, wrap a tableview.beginUpdates and .endUpdates, followed by a UIView.animateWithDuration block around constraint changes.
*/
func sizeHeaderToFit() {
guard let headerView = tableHeaderView else {
return
}
let oldHeight = headerView.frame.height
let height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
headerView.frame.size.height = height
contentSize.height += (height - oldHeight)
headerView.layoutIfNeeded()
}
func sizeFooterToFit() {
guard let footerView = tableFooterView else {
return
}
let oldHeight = footerView.frame.height
let height = footerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
footerView.frame.size.height = height
contentSize.height += (height - oldHeight)
footerView.layoutIfNeeded()
}
}
extension UICollectionViewFlowLayout {
/// 修正collection布局有缝隙
func fixSlit(rect: inout CGRect, colCount: CGFloat, space: CGFloat = 0) -> CGFloat {
let totalSpace = (colCount - 1) * space
let itemWidth = (rect.width - totalSpace) / colCount
let fixValue = 1 / UIScreen.main.scale
var realItemWidth = floor(itemWidth) + fixValue
if realItemWidth < itemWidth {
realItemWidth += fixValue
}
let realWidth = colCount * realItemWidth + totalSpace
let pointX = (realWidth - rect.width) / 2
rect.origin.x = -pointX
rect.size.width = realWidth
return (rect.width - totalSpace) / colCount
}
}
extension UICollectionView {
func fixSlit(cols: Int, space: CGFloat = 0) -> CGFloat {
let colCount = CGFloat(cols)
let totalSpace = (colCount - 1) * space
let itemWidth = (frame.width - totalSpace) / colCount
let fixValue = 1 / UIScreen.main.scale
var realItemWidth = floor(itemWidth) + fixValue
if realItemWidth < itemWidth {
realItemWidth += fixValue
}
let realWidth = colCount * realItemWidth + totalSpace
let pointX = (realWidth - frame.width) / 2
frame.origin.x = -pointX
frame.size.width = realWidth
return (frame.width - totalSpace) / colCount
}
}
extension UIViewController {
var visibleViewControllerIfExist: UIViewController? {
if let presentedViewController = presentedViewController {
return presentedViewController.visibleViewControllerIfExist
}
if let nav = self as? UINavigationController {
return nav.topViewController?.visibleViewControllerIfExist
}
if let tabbar = self as? UITabBarController {
return tabbar.selectedViewController?.visibleViewControllerIfExist
}
if isViewLoaded && view.window != nil {
return self
} else {
print("qmui_visibleViewControllerIfExist:,找不到可见的viewController。self = \(self), view.window = \(String(describing: view.window))")
return nil
}
}
}
extension UIImage {
func blurred(radius: CGFloat) -> UIImage {
let ciContext = CIContext(options: nil)
guard let cgImage = cgImage else { return self }
let inputImage = CIImage(cgImage: cgImage)
guard let ciFilter = CIFilter(name: "CIGaussianBlur") else { return self }
ciFilter.setValue(inputImage, forKey: kCIInputImageKey)
ciFilter.setValue(radius, forKey: "inputRadius")
guard let resultImage = ciFilter.value(forKey: kCIOutputImageKey) as? CIImage else { return self }
guard let cgImage2 = ciContext.createCGImage(resultImage, from: inputImage.extent) else { return self }
return UIImage(cgImage: cgImage2)
}
}
extension UIResponder {
var responderChain: String {
guard let next = next else {
return String(describing: self)
}
return String(describing: self) + " -> " + next.responderChain
}
}
| mit | 28c5e39ca88a4e2c68b6415c1a13569b | 34.461187 | 192 | 0.652975 | 4.779077 | false | false | false | false |
ReactiveCocoa/ReactiveSwift | Tests/ReactiveSwiftTests/SignalProducerNimbleMatchers.swift | 3 | 2081 | //
// SignalProducerNimbleMatchers.swift
// ReactiveSwift
//
// Created by Javier Soto on 1/25/15.
// Copyright (c) 2015 GitHub. All rights reserved.
//
import Foundation
import ReactiveSwift
import Nimble
public func sendValue<T: Equatable, E: Equatable>(_ value: T?, sendError: E?, complete: Bool) -> Predicate<SignalProducer<T, E>> {
return sendValues(value.map { [$0] } ?? [], sendError: sendError, complete: complete)
}
public func sendValues<T: Equatable, E: Equatable>(_ values: [T], sendError maybeSendError: E?, complete: Bool) -> Predicate<SignalProducer<T, E>> {
return Predicate<SignalProducer<T, E>> { actualExpression in
precondition(maybeSendError == nil || !complete, "Signals can't both send an error and complete")
guard let signalProducer = try actualExpression.evaluate() else {
let message = ExpectationMessage.fail("The SignalProducer was not created.")
.appendedBeNilHint()
return PredicateResult(status: .fail, message: message)
}
var sentValues: [T] = []
var sentError: E?
var signalCompleted = false
signalProducer.start { event in
switch event {
case let .value(value):
sentValues.append(value)
case .completed:
signalCompleted = true
case let .failed(error):
sentError = error
default:
break
}
}
if sentValues != values {
let message = ExpectationMessage.expectedCustomValueTo(
"send values <\(values)>",
actual: "<\(sentValues)>"
)
return PredicateResult(status: .doesNotMatch, message: message)
}
if sentError != maybeSendError {
let message = ExpectationMessage.expectedCustomValueTo(
"send error <\(String(describing: maybeSendError))>",
actual: "<\(String(describing: sentError))>"
)
return PredicateResult(status: .doesNotMatch, message: message)
}
let completeMessage = complete ?
"complete, but the producer did not complete" :
"not to complete, but the producer completed"
let message = ExpectationMessage.expectedTo(completeMessage)
return PredicateResult(bool: signalCompleted == complete, message: message)
}
}
| mit | 605b84a28bccf020a17d3a005e46e7ce | 30.530303 | 148 | 0.710235 | 3.96381 | false | false | false | false |
auth0/Auth0.swift | Auth0Tests/CredentialsManagerSpec.swift | 1 | 57730 | import Combine
import Quick
import Nimble
import SimpleKeychain
import OHHTTPStubs
#if SWIFT_PACKAGE
import OHHTTPStubsSwift
#endif
#if WEB_AUTH_PLATFORM
import LocalAuthentication
#endif
@testable import Auth0
private let AccessToken = UUID().uuidString.replacingOccurrences(of: "-", with: "")
private let NewAccessToken = UUID().uuidString.replacingOccurrences(of: "-", with: "")
private let TokenType = "bearer"
private let IdToken = UUID().uuidString.replacingOccurrences(of: "-", with: "")
private let NewIdToken = UUID().uuidString.replacingOccurrences(of: "-", with: "")
private let RefreshToken = UUID().uuidString.replacingOccurrences(of: "-", with: "")
private let NewRefreshToken = UUID().uuidString.replacingOccurrences(of: "-", with: "")
private let ExpiresIn: TimeInterval = 3600
private let ValidTTL = Int(ExpiresIn - 1000)
private let InvalidTTL = Int(ExpiresIn + 1000)
private let Timeout: DispatchTimeInterval = .seconds(2)
private let ClientId = "CLIENT_ID"
private let Domain = "samples.auth0.com"
private let ExpiredToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIiLCJpYXQiOjE1NzE4NTI0NjMsImV4cCI6MTU0MDIzMDA2MywiYXVkIjoiYXVkaWVuY2UiLCJzdWIiOiIxMjM0NSJ9.Lcz79P1AFAZDI4Yr1teFapFVAmBbdfhGBGbj9dQVeRM"
private let ValidToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ0ZXN0IiwiaWF0IjoxNTcxOTExNTkyLCJleHAiOjE5MTg5ODAzOTIsImF1ZCI6ImF1ZGllbmNlIiwic3ViIjoic3VifDEyMyJ9.uLNF8IpY6cJTY-RyO3CcqLpCaKGaVekR-DTDoQTlnPk" // Token is valid until 2030
class CredentialsManagerSpec: QuickSpec {
override func spec() {
let authentication = Auth0.authentication(clientId: ClientId, domain: Domain)
var credentialsManager: CredentialsManager!
var credentials: Credentials!
beforeEach {
credentialsManager = CredentialsManager(authentication: authentication)
credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: ExpiresIn))
stub(condition: isHost(Domain)) { _ in catchAllResponse() }.name = "YOU SHALL NOT PASS!"
}
afterEach {
HTTPStubs.removeAllStubs()
}
describe("storage") {
afterEach {
_ = credentialsManager.clear()
}
it("should store credentials in keychain") {
expect(credentialsManager.store(credentials: credentials)).to(beTrue())
}
it("should clear credentials in keychain") {
expect(credentialsManager.store(credentials: credentials)).to(beTrue())
expect(credentialsManager.clear()).to(beTrue())
}
it("should fail to clear credentials") {
expect(credentialsManager.clear()).to(beFalse())
}
}
describe("custom storage") {
class CustomStore: CredentialsStorage {
var store: [String: Data] = [:]
func getEntry(forKey: String) -> Data? {
return store[forKey]
}
func setEntry(_ data: Data, forKey: String) -> Bool {
store[forKey] = data
return true
}
func deleteEntry(forKey: String) -> Bool {
store[forKey] = nil
return true
}
}
beforeEach {
credentialsManager = CredentialsManager(authentication: authentication, storage: CustomStore());
}
afterEach {
_ = credentialsManager.clear()
}
it("should store credentials in custom store") {
expect(credentialsManager.store(credentials: credentials)).to(beTrue())
expect(credentialsManager.hasValid()).to(beTrue())
}
it("should clear credentials from custom store") {
expect(credentialsManager.store(credentials: credentials)).to(beTrue())
expect(credentialsManager.clear()).to(beTrue())
expect(credentialsManager.hasValid()).to(beFalse())
}
}
describe("clearing and revoking refresh token") {
beforeEach {
_ = credentialsManager.store(credentials: credentials)
stub(condition: isRevokeToken(Domain) && hasAtLeast(["token": RefreshToken])) { _ in return revokeTokenResponse() }.name = "revoke success"
}
afterEach {
_ = credentialsManager.clear()
}
it("should clear credentials and revoke the refresh token") {
waitUntil(timeout: Timeout) { done in
credentialsManager.revoke { result in
expect(result).to(beSuccessful())
expect(credentialsManager.hasValid()).to(beFalse())
done()
}
}
}
it("should not return an error if there were no credentials stored") {
_ = credentialsManager.clear()
waitUntil(timeout: Timeout) { done in
credentialsManager.revoke { result in
expect(result).to(beSuccessful())
expect(credentialsManager.hasValid()).to(beFalse())
done()
}
}
}
it("should not return an error if there is no refresh token, and clear credentials anyway") {
let credentials = Credentials(accessToken: AccessToken,
idToken: IdToken,
expiresIn: Date(timeIntervalSinceNow: ExpiresIn))
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager.revoke { result in
expect(result).to(beSuccessful())
expect(credentialsManager.hasValid()).to(beFalse())
done()
}
}
}
it("should return the failure if the token could not be revoked, and not clear credentials") {
let cause = AuthenticationError(description: "Revoke failed", statusCode: 400)
let expectedError = CredentialsManagerError(code: .revokeFailed, cause: cause)
stub(condition: isRevokeToken(Domain) && hasAtLeast(["token": RefreshToken])) { _ in
return authFailure(code: "400", description: "Revoke failed")
}
waitUntil(timeout: Timeout) { done in
credentialsManager.revoke { result in
expect(result).to(haveCredentialsManagerError(expectedError))
expect(credentialsManager.hasValid()).to(beTrue())
done()
}
}
}
it("should include custom headers") {
let key = "foo"
let value = "bar"
stub(condition: hasHeader(key, value: value)) { _ in return revokeTokenResponse() }.name = "revoke success"
waitUntil(timeout: Timeout) { done in
credentialsManager.revoke(headers: [key: value], { result in
expect(result).to(beSuccessful())
done()
})
}
}
}
describe("multi instances of credentials manager") {
var secondaryCredentialsManager: CredentialsManager!
var secondaryCredentials: Credentials!
beforeEach {
secondaryCredentialsManager = CredentialsManager(authentication: authentication, storeKey: "secondary_store")
secondaryCredentials = Credentials(accessToken: "SecondaryAccessToken", tokenType: TokenType, idToken: "SecondaryIdToken", refreshToken: "SecondaryRefreshToken", expiresIn: Date(timeIntervalSinceNow: ExpiresIn))
}
it("should store credentials into distinct locations") {
expect(credentialsManager.store(credentials: credentials)).to(beTrue())
expect(secondaryCredentialsManager.store(credentials: secondaryCredentials)).to(beTrue())
waitUntil(timeout: .seconds(200)) { done in
credentialsManager.credentials { result in
expect(result).to(haveCredentials(AccessToken, IdToken, RefreshToken))
done()
}
}
waitUntil(timeout: Timeout) { done in
secondaryCredentialsManager.credentials { result in
expect(result).to(haveCredentials("SecondaryAccessToken", "SecondaryIdToken", "SecondaryRefreshToken"))
done()
}
}
}
it("should store new credentials") {
credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: ExpiresIn))
_ = credentialsManager.store(credentials: credentials)
}
it("should share a space in the keychain if using the same store key") {
credentialsManager = CredentialsManager(authentication: authentication, storeKey: "secondary_store")
expect(credentialsManager.store(credentials: credentials)).to(beTrue())
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials { result in
expect(result).to(haveCredentials(AccessToken, IdToken, RefreshToken))
done()
}
}
waitUntil(timeout: Timeout) { done in
secondaryCredentialsManager.credentials { result in
expect(result).to(haveCredentials(AccessToken, IdToken, RefreshToken))
done()
}
}
}
afterEach {
_ = credentialsManager.clear()
_ = secondaryCredentialsManager.clear()
}
}
describe("user") {
afterEach {
_ = credentialsManager.clear()
}
it("should retrieve the user profile when there is an id token stored") {
let credentials = Credentials(idToken: ValidToken, expiresIn: Date(timeIntervalSinceNow: ExpiresIn))
expect(credentialsManager.store(credentials: credentials)).to(beTrue())
expect(credentialsManager.user).toNot(beNil())
}
it("should not retrieve the user profile when there are no credentials stored") {
expect(credentialsManager.user).to(beNil())
}
it("should not retrieve the user profile when the id token is not a jwt") {
let credentials = Credentials(accessToken: AccessToken, idToken: "not a jwt", expiresIn: Date(timeIntervalSinceNow: ExpiresIn))
expect(credentialsManager.store(credentials: credentials)).to(beTrue())
expect(credentialsManager.user).to(beNil())
}
}
describe("validity") {
afterEach {
_ = credentialsManager.clear()
}
it("should have valid credentials when stored and not expired") {
expect(credentialsManager.store(credentials: credentials)).to(beTrue())
expect(credentialsManager.hasValid()).to(beTrue())
}
it("should not have valid credentials when keychain is empty") {
expect(credentialsManager.hasValid()).to(beFalse())
}
it("should have valid credentials when token valid") {
let credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: nil, expiresIn: Date(timeIntervalSinceNow: ExpiresIn))
expect(credentialsManager.store(credentials: credentials)).to(beTrue())
expect(credentialsManager.hasValid()).to(beTrue())
}
it("should not have valid credentials when token expired") {
let credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: nil, expiresIn: Date(timeIntervalSinceNow: -ExpiresIn))
expect(credentialsManager.store(credentials: credentials)).to(beTrue())
expect(credentialsManager.hasValid()).to(beFalse())
}
it("should have valid credentials when the ttl is less than the token lifetime") {
let credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: ExpiresIn))
expect(credentialsManager.store(credentials: credentials)).to(beTrue())
expect(credentialsManager.hasValid(minTTL: ValidTTL)).to(beTrue())
}
it("should not have valid credentials when the ttl is greater than the token lifetime") {
let credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: nil, expiresIn: Date(timeIntervalSinceNow: ExpiresIn))
expect(credentialsManager.store(credentials: credentials)).to(beTrue())
expect(credentialsManager.hasValid(minTTL: InvalidTTL)).to(beFalse())
}
}
describe("expiry") {
it("should not expire soon when the min ttl is less than the at expiry") {
let credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: nil, expiresIn: Date(timeIntervalSinceNow: ExpiresIn))
expect(credentialsManager.willExpire(credentials, within: ValidTTL)).to(beFalse())
}
it("should expire soon when the min ttl is greater than the at expiry") {
let credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: nil, expiresIn: Date(timeIntervalSinceNow: ExpiresIn))
expect(credentialsManager.willExpire(credentials, within: InvalidTTL)).to(beTrue())
}
it("should not be expired when expiry of at is + 1 hour") {
let credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: nil, expiresIn: Date(timeIntervalSinceNow: ExpiresIn))
expect(credentialsManager.hasExpired(credentials)).to(beFalse())
}
it("should be expired when expiry of at is - 1 hour") {
let credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: nil, expiresIn: Date(timeIntervalSinceNow: -ExpiresIn))
expect(credentialsManager.hasExpired(credentials)).to(beTrue())
}
}
describe("renewability") {
afterEach {
_ = credentialsManager.clear()
}
it("should have renewable credentials when stored and have a refresh token") {
expect(credentialsManager.store(credentials: credentials)).to(beTrue())
expect(credentialsManager.canRenew()).to(beTrue())
}
it("should not have renewable credentials when keychain is empty") {
expect(credentialsManager.canRenew()).to(beFalse())
}
it("should not have renewable credentials without a refresh token") {
let credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: nil)
expect(credentialsManager.store(credentials: credentials)).to(beTrue())
expect(credentialsManager.canRenew()).to(beFalse())
}
}
describe("scope") {
it("should return true when the scope has changed") {
let credentials = Credentials(scope: "openid email profile")
expect(credentialsManager.hasScopeChanged(credentials, from: "openid email")).to(beTrue())
}
it("should return false when the scope has not changed") {
let credentials = Credentials(scope: "openid email")
expect(credentialsManager.hasScopeChanged(credentials, from: "openid email")).to(beFalse())
expect(credentialsManager.hasScopeChanged(credentials, from: "email openid")).to(beFalse())
}
}
describe("id token") {
afterEach {
_ = credentialsManager.clear()
}
it("should be valid when at valid and id token expired") {
let credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: ExpiredToken, refreshToken: nil, expiresIn: Date(timeIntervalSinceNow: ExpiresIn))
expect(credentialsManager.store(credentials: credentials)).to(beTrue())
expect(credentialsManager.hasValid()).to(beTrue())
}
}
describe("retrieval") {
beforeEach {
stub(condition: isToken(Domain) && hasAtLeast(["refresh_token": RefreshToken])) {
_ in return authResponse(accessToken: NewAccessToken, idToken: NewIdToken, refreshToken: nil, expiresIn: ExpiresIn * 2)
}.name = "renew success"
}
afterEach {
_ = credentialsManager.clear()
}
it("should error when no credentials stored") {
_ = credentialsManager.clear()
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials { result in
expect(result).to(haveCredentialsManagerError(CredentialsManagerError(code: .noCredentials)))
done()
}
}
}
it("should error when no refresh token") {
credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: nil, expiresIn: Date(timeIntervalSinceNow: -ExpiresIn))
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials { result in
expect(result).to(haveCredentialsManagerError(CredentialsManagerError(code: .noRefreshToken)))
done()
}
}
}
it("should return original credentials as not expired") {
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials { result in
expect(result).to(haveCredentials())
done()
}
}
}
#if os(iOS)
context("require biometrics") {
it("should error when biometrics are unavailable") {
let expectedError = CredentialsManagerError(code: .biometricsFailed, cause: LAError(LAError.biometryNotAvailable))
credentialsManager.enableBiometrics(withTitle: "Auth Title", cancelTitle: "Cancel Title", fallbackTitle: "Fallback Title")
credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: -ExpiresIn))
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials { result in
expect(result).to(haveCredentialsManagerError(expectedError))
done()
}
}
}
it("should error when biometric validation fails") {
let laContext = MockLAContext()
let bioAuth = BioAuthentication(authContext: laContext, evaluationPolicy: .deviceOwnerAuthenticationWithBiometrics, title: "Auth Title")
let cause = LAError(.appCancel)
let expectedError = CredentialsManagerError(code: .biometricsFailed, cause: cause)
laContext.replyError = cause
credentialsManager.bioAuth = bioAuth
credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: -ExpiresIn))
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials { result in
expect(result).to(haveCredentialsManagerError(expectedError))
done()
}
}
}
it("should yield new credentials when biometric validation succeeds") {
let laContext = MockLAContext()
let bioAuth = BioAuthentication(authContext: laContext, evaluationPolicy: .deviceOwnerAuthenticationWithBiometrics, title: "Biometric Auth")
credentialsManager.bioAuth = bioAuth
credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: -ExpiresIn))
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials { result in
expect(result).to(haveCredentials(NewAccessToken, NewIdToken, RefreshToken))
done()
}
}
}
}
#endif
context("renew") {
it("should yield new credentials without refresh token rotation") {
credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: -ExpiresIn))
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials { result in
expect(result).to(haveCredentials(NewAccessToken, NewIdToken, RefreshToken))
done()
}
}
}
it("should yield new credentials with refresh token rotation") {
stub(condition: isToken(Domain) && hasAtLeast(["refresh_token": RefreshToken])) {
_ in return authResponse(accessToken: NewAccessToken, idToken: NewIdToken, refreshToken: NewRefreshToken, expiresIn: ExpiresIn)
}
credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: -ExpiresIn))
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials { result in
expect(result).to(haveCredentials(NewAccessToken, NewIdToken, NewRefreshToken))
done()
}
}
}
it("should store new credentials") {
credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: -ExpiresIn))
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials { result in
expect(result).to(beSuccessful())
credentialsManager.credentials { result in
expect(result).to(haveCredentials(NewAccessToken, NewIdToken, RefreshToken))
done()
}
}
}
}
it("should yield error on failed renew") {
let cause = AuthenticationError(info: ["error": "invalid_request", "error_description": "missing_params"])
let expectedError = CredentialsManagerError(code: .renewFailed, cause: cause)
stub(condition: isToken(Domain) && hasAtLeast(["refresh_token": RefreshToken])) { _ in return authFailure(code: "invalid_request", description: "missing_params") }.name = "renew failed"
credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: -ExpiresIn))
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials { result in
expect(result).to(haveCredentialsManagerError(expectedError))
done()
}
}
}
it("should yield error on failed store") {
class MockStore: CredentialsStorage {
func getEntry(forKey: String) -> Data? {
let credentials = Credentials(accessToken: AccessToken,
tokenType: TokenType,
idToken: IdToken,
refreshToken: RefreshToken,
expiresIn: Date(timeIntervalSinceNow: -ExpiresIn))
let data = try? NSKeyedArchiver.archivedData(withRootObject: credentials,
requiringSecureCoding: true)
return data
}
func setEntry(_ data: Data, forKey: String) -> Bool {
return false
}
func deleteEntry(forKey: String) -> Bool {
return true
}
}
credentialsManager = CredentialsManager(authentication: authentication, storage: MockStore())
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials { result in
expect(result).to(haveCredentialsManagerError(.storeFailed))
done()
}
}
}
it("renew request should include custom parameters") {
let someId = UUID().uuidString
stub(condition: isToken(Domain) && hasAtLeast(["refresh_token": RefreshToken, "some_id": someId])) {
_ in return authResponse(accessToken: NewAccessToken, idToken: NewIdToken, refreshToken: NewRefreshToken, expiresIn: ExpiresIn)
}
credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: -ExpiresIn))
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials(parameters: ["some_id": someId]) { result in
expect(result).to(haveCredentials(NewAccessToken, NewIdToken, NewRefreshToken))
done()
}
}
}
it("renew request should include custom headers") {
let key = "foo"
let value = "bar"
stub(condition: hasHeader(key, value: value)) {
_ in return authResponse(accessToken: NewAccessToken, idToken: NewIdToken, refreshToken: NewRefreshToken, expiresIn: ExpiresIn)
}
credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: -ExpiresIn))
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials(headers: [key: value]) { result in
expect(result).to(beSuccessful())
done()
}
}
}
}
context("forced renew") {
beforeEach {
_ = credentialsManager.store(credentials: credentials)
}
it("should not yield a new access token by default") {
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials { result in
expect(result).to(haveCredentials(AccessToken))
done()
}
}
}
it("should not yield a new access token without a new scope") {
credentials = Credentials(accessToken: AccessToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: ExpiresIn), scope: "openid profile")
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials(withScope: nil) { result in
expect(result).to(haveCredentials(AccessToken))
done()
}
}
}
it("should not yield a new access token with the same scope") {
credentials = Credentials(accessToken: AccessToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: ExpiresIn), scope: "openid profile")
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials(withScope: "openid profile") { result in
expect(result).to(haveCredentials(AccessToken))
done()
}
}
}
it("should yield a new access token with a new scope") {
credentials = Credentials(accessToken: AccessToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: ExpiresIn), scope: "openid profile")
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials(withScope: "openid profile offline_access") { result in
expect(result).to(haveCredentials(NewAccessToken))
done()
}
}
}
it("should not yield a new access token with a min ttl less than its expiry") {
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials(minTTL: ValidTTL) { result in
expect(result).to(haveCredentials(AccessToken))
done()
}
}
}
it("should yield a new access token with a min ttl greater than its expiry") {
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials(minTTL: InvalidTTL) { result in
expect(result).to(haveCredentials(NewAccessToken))
done()
}
}
}
it("should fail to yield a renewed access token with a min ttl greater than its expiry") {
let minTTL = 100_000
// The dates are not mocked, so they won't match exactly
let expectedError = CredentialsManagerError(code: .largeMinTTL(minTTL: minTTL, lifetime: Int(ExpiresIn - 1)))
stub(condition: isToken(Domain) && hasAtLeast(["refresh_token": RefreshToken])) {
_ in return authResponse(accessToken: NewAccessToken, idToken: NewIdToken, refreshToken: nil, expiresIn: ExpiresIn)
}
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials(withScope: nil, minTTL: minTTL) { result in
expect(result).to(haveCredentialsManagerError(expectedError))
done()
}
}
}
}
context("serial renew from same thread") {
it("should yield the stored credentials after the previous renewal operation succeeded") {
credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: -ExpiresIn))
_ = credentialsManager.store(credentials: credentials)
stub(condition: isToken(Domain) && hasAtLeast(["refresh_token": RefreshToken])) { _ in
return authResponse(accessToken: NewAccessToken, idToken: NewIdToken, refreshToken: NewRefreshToken, expiresIn: ExpiresIn)
}
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials { result in
expect(result).to(haveCredentials(NewAccessToken, NewIdToken, NewRefreshToken))
}
credentialsManager.credentials { result in
expect(result).to(haveCredentials(NewAccessToken, NewIdToken, NewRefreshToken))
done()
}
}
}
it("should renew the credentials after the previous renewal operation failed") {
credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: -ExpiresIn))
_ = credentialsManager.store(credentials: credentials)
stub(condition: isToken(Domain) && hasAtLeast(["refresh_token": RefreshToken])) { _ in return apiFailureResponse() }
waitUntil(timeout: Timeout) { done in
credentialsManager.credentials { result in
expect(result).to(beUnsuccessful())
stub(condition: isToken(Domain) && hasAtLeast(["refresh_token": RefreshToken])) { _ in
return authResponse(accessToken: NewAccessToken, idToken: NewIdToken, refreshToken: NewRefreshToken, expiresIn: ExpiresIn)
}
}
credentialsManager.credentials { result in
expect(result).to(haveCredentials())
done()
}
}
}
}
context("serial renew from different threads") {
it("should yield the stored credentials after the previous renewal operation succeeded") {
credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: -ExpiresIn))
_ = credentialsManager.store(credentials: credentials)
stub(condition: isToken(Domain) && hasAtLeast(["refresh_token": RefreshToken, "request": "first"])) { request in
return authResponse(accessToken: NewAccessToken, idToken: NewIdToken, refreshToken: NewRefreshToken, expiresIn: ExpiresIn)
}
waitUntil(timeout: Timeout) { done in
DispatchQueue.global(qos: .utility).sync {
credentialsManager.credentials(parameters: ["request": "first"]) { result in
expect(result).to(haveCredentials(NewAccessToken, NewIdToken, NewRefreshToken))
}
}
DispatchQueue.global(qos: .background).sync {
credentialsManager.credentials { result in
expect(result).to(haveCredentials(NewAccessToken, NewIdToken, NewRefreshToken))
done()
}
}
}
}
it("should renew the credentials after the previous renewal operation failed") {
credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: -ExpiresIn))
_ = credentialsManager.store(credentials: credentials)
stub(condition: isToken(Domain) && hasAtLeast(["refresh_token": RefreshToken, "request": "first"])) { request in
return apiFailureResponse()
}
stub(condition: isToken(Domain) && hasAtLeast(["refresh_token": RefreshToken, "request": "second"])) { request in
return authResponse(accessToken: NewAccessToken, idToken: NewIdToken, refreshToken: NewRefreshToken, expiresIn: ExpiresIn)
}
waitUntil(timeout: Timeout) { done in
DispatchQueue.global(qos: .utility).sync {
credentialsManager.credentials(parameters: ["request": "first"]) { result in
expect(result).to(beUnsuccessful())
}
}
DispatchQueue.global(qos: .background).sync {
credentialsManager.credentials(parameters: ["request": "second"]) { result in
expect(result).to(haveCredentials())
done()
}
}
}
}
}
context("custom keychain") {
let storage = SimpleKeychain(service: "test_service")
beforeEach {
credentialsManager = CredentialsManager(authentication: authentication,
storage: storage)
}
it("custom keychain should successfully set and clear credentials") {
_ = credentialsManager.store(credentials: credentials)
expect { try storage.data(forKey: "credentials") }.toNot(beNil())
_ = credentialsManager.clear()
expect { try storage.data(forKey: "credentials") }.to(throwError(SimpleKeychainError.itemNotFound))
}
}
}
if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) {
describe("combine") {
var cancellables: Set<AnyCancellable> = []
afterEach {
_ = credentialsManager.clear()
cancellables.removeAll()
}
context("credentials") {
it("should emit only one value") {
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager
.credentials()
.assertNoFailure()
.count()
.sink(receiveValue: { count in
expect(count) == 1
done()
})
.store(in: &cancellables)
}
}
it("should complete using the default parameter values") {
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager
.credentials()
.sink(receiveCompletion: { completion in
guard case .finished = completion else { return }
done()
}, receiveValue: { _ in })
.store(in: &cancellables)
}
}
it("should complete using custom parameter values") {
let key = "foo"
let value = "bar"
stub(condition: isToken(Domain) && hasAtLeast(["refresh_token": RefreshToken, key: value]) && hasHeader(key, value: value)) { _ in
return authResponse(accessToken: NewAccessToken, idToken: NewIdToken, refreshToken: NewRefreshToken, expiresIn: ExpiresIn)
}
credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: -ExpiresIn), scope: "openid profile")
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager
.credentials(withScope: "openid profile offline_access",
minTTL: ValidTTL,
parameters: [key: value],
headers: [key: value])
.sink(receiveCompletion: { completion in
guard case .finished = completion else { return }
done()
}, receiveValue: { _ in })
.store(in: &cancellables)
}
}
it("should complete with an error") {
waitUntil(timeout: Timeout) { done in
credentialsManager
.credentials()
.ignoreOutput()
.sink(receiveCompletion: { completion in
guard case .failure = completion else { return }
done()
}, receiveValue: { _ in })
.store(in: &cancellables)
}
}
}
context("revoke") {
it("should emit only one value") {
stub(condition: isRevokeToken(Domain) && hasAtLeast(["token": RefreshToken])) { _ in
return revokeTokenResponse()
}
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager
.revoke()
.assertNoFailure()
.count()
.sink(receiveValue: { count in
expect(count) == 1
done()
})
.store(in: &cancellables)
}
}
it("should complete using the default parameter values") {
stub(condition: isRevokeToken(Domain) && hasAtLeast(["token": RefreshToken])) { _ in
return revokeTokenResponse()
}
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager
.revoke()
.sink(receiveCompletion: { completion in
guard case .finished = completion else { return }
done()
}, receiveValue: { _ in })
.store(in: &cancellables)
}
}
it("should complete using custom parameter values") {
let key = "foo"
let value = "bar"
stub(condition: isRevokeToken(Domain) && hasAtLeast(["token": RefreshToken]) && hasHeader(key, value: value)) { _ in
return revokeTokenResponse()
}
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager
.revoke(headers: [key: value])
.sink(receiveCompletion: { completion in
guard case .finished = completion else { return }
done()
}, receiveValue: { _ in })
.store(in: &cancellables)
}
}
it("should complete with an error") {
stub(condition: isRevokeToken(Domain) && hasAtLeast(["token": RefreshToken])) { _ in
return apiFailureResponse()
}
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
credentialsManager
.revoke()
.ignoreOutput()
.sink(receiveCompletion: { completion in
guard case .failure = completion else { return }
done()
}, receiveValue: { _ in })
.store(in: &cancellables)
}
}
}
}
}
#if compiler(>=5.5) && canImport(_Concurrency)
describe("async await") {
afterEach {
_ = credentialsManager.clear()
}
context("credentials") {
it("should return the credentials using the default parameter values") {
let credentialsManager = credentialsManager!
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
#if compiler(>=5.5.2)
if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) {
Task.init {
_ = try await credentialsManager.credentials()
done()
}
}
#else
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
Task.init {
_ = try await credentialsManager.credentials()
done()
}
} else {
done()
}
#endif
}
}
it("should return the credentials using custom parameter values") {
let key = "foo"
let value = "bar"
let credentialsManager = credentialsManager!
stub(condition: isToken(Domain) && hasAtLeast(["refresh_token": RefreshToken, key: value]) && hasHeader(key, value: "bar")) { _ in
return authResponse(accessToken: NewAccessToken, idToken: NewIdToken, refreshToken: NewRefreshToken, expiresIn: ExpiresIn)
}
credentials = Credentials(accessToken: AccessToken, tokenType: TokenType, idToken: IdToken, refreshToken: RefreshToken, expiresIn: Date(timeIntervalSinceNow: -ExpiresIn), scope: "openid profile")
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
#if compiler(>=5.5.2)
if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) {
Task.init {
_ = try await credentialsManager.credentials(withScope: "openid profile offline_access",
minTTL: ValidTTL,
parameters: [key: value],
headers: [key: value])
done()
}
}
#else
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
Task.init {
_ = try await credentialsManager.credentials(withScope: "openid profile offline_access",
minTTL: ValidTTL,
parameters: [key: value],
headers: [key: value])
done()
}
} else {
done()
}
#endif
}
}
it("should throw an error") {
let credentialsManager = credentialsManager!
waitUntil(timeout: Timeout) { done in
#if compiler(>=5.5.2)
if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) {
Task.init {
do {
_ = try await credentialsManager.credentials()
} catch {
done()
}
}
}
#else
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
Task.init {
do {
_ = try await credentialsManager.credentials()
} catch {
done()
}
}
} else {
done()
}
#endif
}
}
}
context("revoke") {
it("should revoke using the default parameter values") {
let credentialsManager = credentialsManager!
stub(condition: isRevokeToken(Domain) && hasAtLeast(["token": RefreshToken])) { _ in
return revokeTokenResponse()
}
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
#if compiler(>=5.5.2)
if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) {
Task.init {
_ = try await credentialsManager.revoke()
done()
}
}
#else
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
Task.init {
_ = try await credentialsManager.revoke()
done()
}
} else {
done()
}
#endif
}
}
it("should revoke using custom parameter values") {
let key = "foo"
let value = "bar"
let credentialsManager = credentialsManager!
stub(condition: isRevokeToken(Domain) && hasAtLeast(["token": RefreshToken]) && hasHeader(key, value: value)) { _ in
return revokeTokenResponse()
}
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
#if compiler(>=5.5.2)
if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) {
Task.init {
_ = try await credentialsManager.revoke(headers: [key: value])
done()
}
}
#else
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
Task.init {
_ = try await credentialsManager.revoke(headers: [key: value])
done()
}
} else {
done()
}
#endif
}
}
it("should throw an error") {
let credentialsManager = credentialsManager!
stub(condition: isRevokeToken(Domain) && hasAtLeast(["token": RefreshToken])) { _ in
return apiFailureResponse()
}
_ = credentialsManager.store(credentials: credentials)
waitUntil(timeout: Timeout) { done in
#if compiler(>=5.5.2)
if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) {
Task.init {
do {
_ = try await credentialsManager.revoke()
} catch {
done()
}
}
}
#else
if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
Task.init {
do {
_ = try await credentialsManager.revoke()
} catch {
done()
}
}
} else {
done()
}
#endif
}
}
}
}
#endif
}
}
| mit | 807068b78ee6404f28496e90d845ac1b | 49.551664 | 245 | 0.493002 | 6.237709 | false | false | false | false |
WestlakeAPC/game-off-2016 | external/Fiber2D/Fiber2D/Node+Actions.swift | 1 | 4228 | //
// Node+Actions.swift
//
// Created by Andrey Volodin on 23.07.16.
// Copyright © 2016. All rights reserved.
//
public extension Node {
/**
Has the node run an action.
@note Depending on when in the frame update cycle this method gets called, the action passed in may either start running
in the current frame or in the next frame.
@param action ActionContainer to run.
@return The action that is executed (same as the one that was passed in).
@see ActionContainer
*/
public func run(action: ActionContainer) {
if let scheduler = self.scheduler {
scheduler.add(action: action, target: self, paused: !self.active)
} else {
queuedActions.append(action)
}
}
/** Stops and removes all actions running on the node.
@node It is not necessary to call this when removing a node. Removing a node from its parent will also stop its actions. */
public func stopAllActions() {
queuedActions = []
scheduler?.removeAllActions(from: self)
}
/**
* Removes an action from the running action list given its tag. If there are multiple actions with the same tag it will
* only remove the first action found that has this tag.
*
* @param name Name of the action to remove.
*/
public func stopAction(by tag: Int) {
if let idx = queuedActions.index(where: { $0.tag == tag }) {
queuedActions.remove(at: idx)
return
}
scheduler?.removeAction(by: tag, target: self)
}
/**
* Gets an action running on the node given its tag.
* If there are multiple actions with the same tag it will get the first action found that has this tag.
*
* @param name Name of the action.
*
* @return The first action with the given name, or nil if there's no running action with this name.
* @see ActionContainer
*/
public func getAction(by tag: Int) -> ActionContainer? {
return scheduler?.getAction(by: tag, target: self)
}
/**
Return a list of all actions associated with this node.
*/
public var actions: [ActionContainer]? {
return scheduler?.actions(for: self)
}
/// -----------------------------------------------------------------------
/// @name Scheduling Blocks
/// -----------------------------------------------------------------------
/**
Schedules a block to run once, after the given delay.
`TimerBlock` is a block typedef declared as `(Timer) -> Void`
@note There is currently no way to stop/cancel an already scheduled block. If a scheduled block should not run under certain circumstances,
the block's code itself must check these conditions to determine whether it should or shouldn't perform its task.
@param block Block to execute. The block takes a `Timer*` parameter as input and returns nothing.
@param delay Delay, in seconds.
@return A newly initialized Timer object.
@see Timer
*/
public func schedule(block: @escaping TimerBlock, delay: Time) -> Timer! {
guard let scheduler = self.scheduler else {
return nil
}
return scheduler.schedule(block: block, for: self, withDelay: delay)
}
}
// Internal scheduling stuff
internal extension Node {
// Used to pause/unpause a node's actions and timers when it's isRunning state changes.
internal func wasRunning(_ wasRunning: Bool) {
let isRunning = self.active
// Resume or pause scheduled update methods, Actions, and animations if the pause state has changed
if isRunning != wasRunning {
scheduler?.setPaused(paused: !isRunning, target: self)
}
}
// Recursively increment/decrement _pausedAncestors on the children of 'node'.
internal func recursivelyIncrementPausedAncestors(_ increment: Int) {
for node in children {
let wasRunning = node.active
node.pausedAncestors += increment
node.wasRunning(wasRunning)
node.recursivelyIncrementPausedAncestors(increment)
}
}
}
| apache-2.0 | e45318665ae74e7c99d5636e9ea0f716 | 35.756522 | 144 | 0.616749 | 4.749438 | false | false | false | false |
honghaoz/ZHDatePicker | Demo/Demo/ViewController.swift | 1 | 1151 | //
// ViewController.swift
// Demo
//
// Created by Honghao Zhang on 2/20/15.
// Copyright (c) 2015 Honghao Zhang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var datePicker: ZHDatePicker!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.blackColor()
// Setup View
datePicker = ZHDatePicker()
let views = ["datePicker": datePicker]
let metrics = ["fixedHeight": ZHDatePicker.kPickerFixedHeight]
datePicker.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(datePicker)
var constraints = [NSLayoutConstraint]()
constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|[datePicker]|", options: NSLayoutFormatOptions(0), metrics: nil, views: views) as! [NSLayoutConstraint]
constraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|-100-[datePicker(fixedHeight)]", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: metrics, views: views) as! [NSLayoutConstraint]
NSLayoutConstraint.activateConstraints(constraints)
}
}
| mit | c1a4c49eb00491c3ca54dc286aa96efa | 31.885714 | 205 | 0.716768 | 5.138393 | false | false | false | false |
grigaci/RateMyTalkAtMobOS | RateMyTalkAtMobOS/Classes/GUI/Common/Dialogs/Base/RMTWindowBase.swift | 1 | 1543 | //
// RMTWindowBase.swift
// RateMyTalkAtMobOS
//
// Created by Bogdan Iusco on 10/13/14.
// Copyright (c) 2014 Grigaci. All rights reserved.
//
import UIKit
class RMTWindowBase: UIWindow {
var lastWindow: UIWindow?
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(viewController: UIViewController) {
super.init(frame: UIScreen.mainScreen().bounds)
self.rootViewController = viewController
self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.5)
}
func show() {
self.lastWindow = UIApplication.sharedApplication().keyWindow
self.windowLevel = self.lastWindow!.windowLevel + 1.0
self.makeKeyAndVisible()
RMTWindowBase.registerWindow(self)
}
func hide() {
self.windowLevel = self.lastWindow!.windowLevel - 1.0
self.lastWindow?.makeKeyAndVisible()
RMTWindowBase.unregisterWindow(self)
}
class var aliveWindows: NSMutableArray {
struct Static {
static var onceToken : dispatch_once_t = 0
static var array : NSMutableArray? = nil
}
dispatch_once(&Static.onceToken) {
Static.array = NSMutableArray()
}
return Static.array!
}
class func registerWindow(window: UIWindow) {
RMTWindowBase.aliveWindows.addObject(window)
}
class func unregisterWindow(window: UIWindow) {
RMTWindowBase.aliveWindows.removeObject(window)
}
}
| bsd-3-clause | 2322a8e79264ff6bc8a8f781a66bd866 | 26.553571 | 83 | 0.645496 | 4.274238 | false | false | false | false |
zeroleaf/LeetCode | LeetCode/LeetCodeTests/13_RomanToIntegerSpec.swift | 1 | 1183 | //
// RomanToIntegerSpec.swift
// LeetCode
//
// Created by zeroleaf on 16/2/12.
// Copyright © 2016年 zeroleaf. All rights reserved.
//
import XCTest
import Quick
import Nimble
class RomanToInteger {
let map: [Character: Int] = [
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
]
func romanToInt(s: String) -> Int {
let len = s.characters.count
var sum = 0
for var i = 0; i < len; i++ {
if i + 1 < len && map[s[i + 1]] > map[s[i]] {
sum -= map[s[i]]!
} else {
sum += map[s[i]]!
}
}
return sum
}
}
class RomanToIntegerSpec: QuickSpec {
override func spec() {
describe("Roman To Integer") {
var s: RomanToInteger!
beforeEach {
s = RomanToInteger()
}
it("Test Case") {
expect(s.romanToInt("MCD")).to(equal(1400))
expect(s.romanToInt("MCDXXXVII")).to(equal(1437))
expect(s.romanToInt("MMMCCCXXXIII")).to(equal(3333))
}
}
}
}
| mit | 5933aff108403ed835d66aac751c2263 | 19 | 68 | 0.451695 | 3.554217 | false | false | false | false |
jordanekay/Mensa | Mensa/Sources/Controller/Mediator/DataMediator.swift | 1 | 11756 | //
// DataMediator.swift
// Mensa
//
// Created by Jordan Kay on 4/10/19.
// Copyright © 2019 CultivR. All rights reserved.
//
final class DataMediator<DataInterface: DataInterfacing>: NSObject, UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
typealias Item = DataInterface.DataSourceType.Item
typealias Header = DataInterface.DataSourceType.Header
var dataSource: DataInterface.DataSourceType?
var selectedIndexPath: IndexPath?
private var defaultDisplayVariants: [ItemTypeIdentifier: Variant] = [:]
private var itemMediators: [ItemTypeVariantIdentifier: ItemMediator] = [:]
private var viewControllerTypes: [ItemTypeVariantIdentifier: UIViewController.Type] = [:]
private var registeredSupplementaryViewIdentifiers: Set<ItemTypeVariantIdentifier> = []
private var headerHeightCache: [Int: CGFloat] = [:]
private weak var dataInterface: DataInterface!
init(dataInterface: DataInterface) {
self.dataInterface = dataInterface
}
// MARK: UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
dataInterface.handle(.didScroll, for: scrollView)
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let scrollEvent = ScrollEvent.willEndDragging(velocity: velocity, targetContentOffset: targetContentOffset.pointee)
dataInterface.handle(scrollEvent, for: scrollView)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
dataInterface.handle(.didEndDecelerating, for: scrollView)
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
dataInterface.handle(.didEndScrollingAnimation, for: scrollView)
}
// MARK: UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return sectionCount
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemCount(forSection: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let (identifier, itemMediator, item) = info(for: indexPath)
let cell = tableView.dequeueReusableCell(withIdentifier: identifier.value, for: indexPath) as! HostingView
let viewController = cell.viewController ?? hostContent(in: cell, for: identifier)
itemMediator.interface(viewController, item)
return cell as! UITableViewCell
}
// MARK: UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return sectionCount
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return itemCount(forSection: section)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let (identifier, itemMediator, item) = info(for: indexPath)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier.value, for: indexPath) as! HostingView
let viewController = cell.viewController ?? hostContent(in: cell, for: identifier)
itemMediator.interface(viewController, item)
return cell as! UICollectionViewCell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionView.elementKindSectionHeader:
guard let (identifier, itemMediator, header) = headerInfo(for: indexPath.section) else { return (nil as UICollectionReusableView?)! }
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: identifier.value, for: indexPath) as! HostingView
let viewController = headerView.viewController ?? hostContent(in: headerView, for: identifier)
itemMediator.interface(viewController, header)
return headerView as! UICollectionReusableView
default:
return (nil as UICollectionReusableView?)!
}
}
// MARK: UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
let (viewController, itemMediator, item) = viewControllerInfo(for: indexPath, in: collectionView)
return itemMediator.shouldSelect(viewController, item)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let (viewController, itemMediator, item) = viewControllerInfo(for: indexPath, in: collectionView)
itemMediator.prepareToSelect(viewController, item)
selectedIndexPath = indexPath
itemMediator.setSelected(viewController, item, true)
}
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
let (viewController, itemMediator, _) = viewControllerInfo(for: indexPath, in: collectionView)
let highlighted = true
let animated = false
itemMediator.highlight(viewController, highlighted, animated)
}
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
let (viewController, itemMediator, _) = viewControllerInfo(for: indexPath, in: collectionView)
let highlighted = false
let animated = !collectionView.isDragging
itemMediator.highlight(viewController, highlighted, animated)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
guard let (identifier, itemMediator, _) = headerInfo(for: section) else { return .zero }
let height = headerHeightCache[section] ?? {
let viewControllerType = viewControllerTypes[identifier]!
let viewType = self.viewType(for: viewControllerType)
let displayVariant = itemMediator.displayVariant
let view = viewType.hostedView(of: displayVariant)
let height = view.bounds.height
headerHeightCache[section] = height
return height
}()
return .init(width: collectionView.bounds.width, height: height)
}
}
// MARK: -
extension DataMediator {
var itemTypeVariantIdentifiers: [ItemTypeVariantIdentifier] {
return Array(viewControllerTypes.keys)
}
func supportInterfacing<Interface: ItemInterfacing>(with itemType: Any.Type, using interfaceType: Interface.Type) {
let variants = Interface.View.itemDisplayVariants
for variant in variants {
let itemTypeIdentifier = ItemTypeIdentifier(itemType: itemType)
let itemTypeVariantIdentifier = ItemTypeVariantIdentifier(itemTypeIdentifier: itemTypeIdentifier, variant: variant)
defaultDisplayVariants[itemTypeIdentifier] = Interface.View.defaultVariant
itemMediators[itemTypeVariantIdentifier] = .init(interfaceType: interfaceType, displayVariant: variant, dataInterface: dataInterface)
viewControllerTypes[itemTypeVariantIdentifier] = interfaceType
}
}
}
// MARK: -
private extension DataMediator {
var sectionCount: Int {
let sections = dataSource?.sections
return sections?.count ?? 0
}
func itemCount(forSection section: Int) -> Int {
let section = dataSource?.sections[section]
return section?.itemCount ?? 0
}
func info(for indexPath: IndexPath) -> (ItemTypeVariantIdentifier, ItemMediator, Item) {
let item = dataSource!.item(at: indexPath)
let itemType = type(of: item as Any)
let itemTypeIdentifier = ItemTypeIdentifier(itemType: itemType)
let itemCount = self.itemCount(forSection: indexPath.section)
let itemPosition = ItemPosition(indexPath: indexPath, itemCount: itemCount)
let displayVariant = dataInterface.displayVariant(for: item, at: itemPosition) ?? defaultDisplayVariants[itemTypeIdentifier] ?? Invariant()
let itemTypeVariantIdentifier = ItemTypeVariantIdentifier(itemTypeIdentifier: itemTypeIdentifier, variant: displayVariant)
let itemMediator = itemMediators[itemTypeVariantIdentifier]!
return (itemTypeVariantIdentifier, itemMediator, item)
}
func headerInfo(for section: Int) -> (ItemTypeVariantIdentifier, ItemMediator, Header)? {
guard let header = dataSource!.header(for: section) else { return nil }
let itemType = type(of: header)
let itemTypeIdentifier = ItemTypeIdentifier(itemType: itemType)
let displayVariant = dataInterface.displayVariant(for: header) ?? defaultDisplayVariants[itemTypeIdentifier] ?? Invariant()
let itemTypeVariantIdentifier = ItemTypeVariantIdentifier(itemTypeIdentifier: itemTypeIdentifier, variant: displayVariant)
let itemMediator = itemMediators[itemTypeVariantIdentifier]!
return (itemTypeVariantIdentifier, itemMediator, header)
}
func viewControllerInfo(for indexPath: IndexPath, in tableView: UITableView) -> (UIViewController, ItemMediator, Item) {
let (_, itemMediator, item) = info(for: indexPath)
let cell = tableView.cellForRow(at: indexPath) as! HostingView
let viewController = cell.viewController!
return (viewController, itemMediator, item)
}
func viewControllerInfo(for indexPath: IndexPath, in collectionView: UICollectionView) -> (UIViewController, ItemMediator, Item) {
let (_, itemMediator, item) = info(for: indexPath)
let cell = collectionView.cellForItem(at: indexPath) as! HostingView
let viewController = cell.viewController!
return (viewController, itemMediator, item)
}
func viewType(for viewControllerType: UIViewController.Type) -> NibLoadable.Type {
let viewControllerName = String(describing: viewControllerType)
let viewName = viewControllerName.replacingOccurrences(of: "Controller", with: "")
return NSClassFromString("View.\(viewName)") as! NibLoadable.Type
}
func headerIdentifier(for section: Int) -> ItemTypeVariantIdentifier? {
guard let header = dataSource?.sections[section].header else { return nil }
let headerTypeIdentifier = ItemTypeIdentifier(itemType: type(of: header))
return .init(itemTypeIdentifier: headerTypeIdentifier, variant: Invariant())
}
func hostContent(in hostingView: HostingView, for identifier: ItemTypeVariantIdentifier) -> UIViewController {
let viewControllerType = viewControllerTypes[identifier]!
let viewController = viewControllerType.init()
let viewType = self.viewType(for: viewControllerType)
let hostingViewController = dataInterface as UIViewController
let mediator = itemMediators[identifier]!
let displayVariant = mediator.displayVariant
hostingView.hostContent(of: viewType, from: viewController, with: displayVariant)
hostingViewController.addChild(viewController)
viewController.didMove(toParent: hostingViewController)
return viewController
}
}
// MARK: -
extension IndexPath: SectionIndexPath {}
private extension CGSize {
static let defaultItemSize: CGSize = .init(width: 50, height: 50)
}
| bsd-2-clause | 4b7ce3475dcfea65ce82c1913a27ae59 | 46.784553 | 202 | 0.714504 | 5.492991 | false | false | false | false |
depinette/Depsic | Depsic/Sources/Depsic.swift | 1 | 9441 | //
// HTTPRequest.swift
// Depsic
//
// Created by depinette on 02/01/2016.
// Copyright © 2016 depsys. All rights reserved.
//
// Depsic glues together the socket servers, the Simple SCGI parser and the request handlers.
//
import Foundation
#if os(Linux)
import Glibc
import CDispatch
#else
import Darwin
#endif
public class EmptyType {}
public typealias RequestInfo = Request<EmptyType>
public typealias RequestHandlerPredicate = (request:RequestInfo) -> Bool
public enum HTTPCode : String, ErrorType
{
case Status_200 = "200 OK"
case Status_404 = "404 Not Found"
case Status_400 = "400 Bad Request"
case Status_500 = "500 Internal Server Error"
}
public protocol RequestPredicate
{
func canHandleRequest(request:RequestInfo) -> Bool
func createHandler() -> RequestHandler
}
public protocol RequestHandler : ConnectedClientDelegate
{
func didReceiveHeader(connectedClient:ConnectedClient, request:Request<EmptyType>)
}
public struct Request<RequestDataType>
{
let headers:Dictionary<String, String>
var body:RequestDataType?
init?(headers:Dictionary<String, String>)
{
if Request.checkMandatoryCGIVariables(headers) == false {
return nil
}
self.headers = headers
}
init?(headers:Dictionary<String, String>, body:RequestDataType)
{
self.init(headers:headers)
self.body = body
}
var uri:String
{
get
{
let uri = headers["REQUEST_URI"]
return uri! //checked during init
}
}
var contentLength:Int
{
get
{
let strLength = headers["CONTENT_LENGTH"]
if let length = Int(strLength!) {
return length
}
return 0
}
}
var method:String
{
get
{
let method = headers["REQUEST_METHOD"]
return method!
}
}
static func checkMandatoryCGIVariables(headers:Dictionary<String, String>) -> Bool
{
let mandatories = ["REQUEST_URI", "REQUEST_METHOD", "CONTENT_LENGTH"]
for mandatory in mandatories {
if headers[mandatory] == nil {
return false
}
}
return true
}
}
public struct Response<ResponseDataType>
{
let headers:CaseInsensitiveDictionary<String>
let content:ResponseDataType
init(content:ResponseDataType)
{
headers = [:]
self.content = content
}
init(headers:CaseInsensitiveDictionary<String>, content:ResponseDataType)
{
self.headers = headers
self.content = content
}
init(headers:Dictionary<String, String>, content:ResponseDataType)
{
self.headers = CaseInsensitiveDictionary<String>(headers)
self.content = content
}
init(code:HTTPCode, content:ResponseDataType)
{
self.headers = CaseInsensitiveDictionary<String>(["Status":code.rawValue])
self.content = content
}
}
//Depsic is the glue between
//-Socketserver and ConnectedClient which receive data from the web server
//-SCGIParser which is used to parse the SCGI variables/headers
//-RequestHandlers which... well... handle requests.
public class Depsic : SocketServerDelegate, ConnectedClientDelegate
{
init()
{
serversGroup = dispatch_group_create();
pthread_mutex_init(&self.mutexHandler, nil)
pthread_mutex_init(&self.mutexClient, nil)
}
//MARK:Servers management/////////////////
private var servers : Array<SocketServer> = []
private let serversGroup:dispatch_group_t
public func addServer(server:SocketServer)
{
servers.append(server)
//start a thread for this server
let block = { server.start(self); return}
my_dispatch_group_async(serversGroup, dispatch_get_global_queue(Int(DISPATCH_QUEUE_PRIORITY_HIGH), 0), block)
}
func waitForServers()
{
dispatch_group_wait(serversGroup, DISPATCH_TIME_FOREVER)
}
//MARK: Handlers management///////////////
private var requestConditions : Array<RequestPredicate> = []
private var mutexHandler = pthread_mutex_t()
private func getHandler(headers:Dictionary<String, String>) -> RequestHandler?
{
//we need to protect from multithread here the access to request condition array
var foundRequestHandler:RequestHandler? = nil
pthread_mutex_lock(&self.mutexHandler)
for requestCondition in self.requestConditions {
if let request = RequestInfo(headers:headers) {
if requestCondition.canHandleRequest(request) {
foundRequestHandler = requestCondition.createHandler()
break
}
}
}
pthread_mutex_unlock(&self.mutexHandler)
return foundRequestHandler
}
public func addRequestPredicate(requestCondition:RequestPredicate)
{
pthread_mutex_lock(&self.mutexHandler)
requestConditions.append(requestCondition)
pthread_mutex_unlock(&self.mutexHandler)
}
//MARK:Clients management/////////////////
struct Client
{
let connectedClient:ConnectedClient
let parser:SCGIParser
}
private var clients : Array<Client> = []
private var mutexClient = pthread_mutex_t()
private func removeClient(connectedClient:ConnectedClient)
{
pthread_mutex_lock(&self.mutexClient)
if let index = clients.indexOf({ (client:Client) -> Bool in client.connectedClient === connectedClient }) {
clients.removeAtIndex(index)
}
pthread_mutex_unlock(&self.mutexClient)
}
private func addClient(client:Client)
{
pthread_mutex_lock(&self.mutexClient)
clients.append(client)
pthread_mutex_unlock(&self.mutexClient)
}
private func getClient(connectedClient:ConnectedClient) -> Client?
{
var client:Client?
pthread_mutex_lock(&self.mutexClient)
if let index = clients.indexOf({ (client:Client) -> Bool in client.connectedClient === connectedClient }) {
client = clients[index]
}
pthread_mutex_unlock(&self.mutexClient)
return client
}
//MARK: SocketServerDelegate/////////////////
public func didAcceptClient(connectedClient:ConnectedClient)
{
//create the SCGIParser and its completionblock
let decoder = SCGIParser() {
[unowned self] (headers:Dictionary<String, String>, contentLength:Int, remainingBytes:ArraySlice<UInt8>?) in
//test request
guard let request = RequestInfo(headers:headers)
else {
connectedClient.send(.Status_400)
return
}
//test all the request condition
guard let requestHandler = self.getHandler(headers)
else {
connectedClient.send(.Status_404)
return
}
//request handler found
requestHandler.didReceiveHeader(connectedClient, request:request)
if contentLength > 0 {
if remainingBytes != nil {
requestHandler.didReceiveData(connectedClient, buffer: Array<UInt8>(remainingBytes!))
}
connectedClient.delegate = requestHandler
}
}
//set us as delegate to process the first bytes (headers)
connectedClient.delegate = self
//store the client and the parser
let client = Client(connectedClient: connectedClient, parser: decoder)
addClient(client)
}
public func didDisconnectClient(connectedClient:ConnectedClient)
{
removeClient(connectedClient)
}
//MARK:ConnectedClientDelegate
public func didReceiveData(connectedClient:ConnectedClient, buffer:[UInt8])
{
if let client = getClient(connectedClient) {
do {
try client.parser.decode(buffer)
} catch {
connectedClient.send(.Status_500)
}
}
}
public func didDisconnect(connectedClient:ConnectedClient)
{
//print("disconnected")
}
}
//MARK: HTTP Send helpers
extension ConnectedClient
{
func sendHeaders(headers:CaseInsensitiveDictionary<String>)
{
var headers = headers
self.sendString("Status: ")
if let status = headers.removeValueForKey("Status") {
self.sendString(status)
} else {
self.sendString("200 OK")
}
self.sendString("\r\n")
self.sendString("Content-Type: ")
if let contentType = headers.removeValueForKey("Content-Type") {
self.sendString(contentType)
} else {
self.sendString("text/html")
}
self.sendString("\r\n")
for (key, value) in headers {
self.sendString(key)
self.sendString(": ")
self.sendString(value)
self.sendString("\r\n")
}
self.sendString("\r\n")
}
func send(status:HTTPCode, _ disconnect:Bool = true)
{
self.sendHeaders(["Status":status.rawValue])
if disconnect { self.disconnect()}
}
}
| mit | 38ee9593d50a488bec96942f01f4b76d | 28.968254 | 120 | 0.610169 | 4.717641 | false | false | false | false |
qianyu09/AppLove | App Love/Custom/LoadingProgressBar/TerritoryBar.swift | 1 | 4358 | //
// TerritoryBar.swift
// App Love
//
// Created by Woodie Dovich on 2016-04-07.
// Copyright © 2016 Snowpunch. All rights reserved.
//
// Represents 1 territory mini bar on the LoadingProgressBar.
// backgroundBar CALayer is light gray, green when loading, red when error.
// reviewCountBar: blue means (1-49 reviews loaded), black means 50-500 loaded.
//
import UIKit
class TerritoryBar: UIView {
var territoryCode:String?
var backgroundBar = CALayer()
var reviewCountBar = CALayer()
var width1:Int = 0
var maxBarHeight = 0
var hasStarted = false
var lightGrayBack = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0).CGColor
var verticalAnimationDistance:CGFloat = 4.0
init(territoryCode:String, width:CGFloat, height:Int) {
super.init(frame: CGRect.zero)
self.width1 = Int(width)
self.maxBarHeight = height
self.territoryCode = territoryCode
backgroundBar.frame = CGRect(x: 0,y: 0,width: Int(width),height: maxBarHeight)
backgroundBar.backgroundColor = lightGrayBack
backgroundBar.cornerRadius = 3
backgroundBar.opacity = 0.5
self.layer.addSublayer(backgroundBar)
reviewCountBar.frame = CGRect(x: 5,y: 0,width: width,height: 1)
reviewCountBar.backgroundColor = UIColor.blueColor().CGColor
reviewCountBar.cornerRadius = 3
self.layer.addSublayer(reviewCountBar)
reviewCountBar.opacity = 0.0
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func displayLoadAmount(loadState:LoadState) {
if loadState.count < 50 {
showFewReviewsViaBlueBar(loadState.count)
}
else {
showManyReviewsViaBlackBar(loadState.count)
}
}
func restoreState(loadState:LoadState) {
displayLoadAmount(loadState)
if loadState.error {
backgroundBar.backgroundColor = UIColor.redColor().CGColor
}
}
func showFewReviewsViaBlueBar(reviews:Int) {
let height = maxBarHeight * reviews/50
reviewCountBar.backgroundColor = UIColor.blueColor().CGColor
updateReviewCountBar(reviews, width: width1, height: height)
}
func showManyReviewsViaBlackBar(reviews:Int) {
let height = maxBarHeight * reviews/500
reviewCountBar.backgroundColor = UIColor.blackColor().CGColor
updateReviewCountBar(reviews, width: width1, height: height)
}
func updateReviewCountBar(reviews:Int, width:Int, height:Int) {
var barHeight = height
if barHeight > maxBarHeight { barHeight = maxBarHeight }
if reviews > 0 {
reviewCountBar.opacity = 1.0
if reviews < 4 && reviews > 0 { // ensure minimum bar height is visible.
barHeight = 2
}
}
reviewCountBar.frame = CGRect(x: 0,y: maxBarHeight,width: width,height: -barHeight)
}
func showError() {
backgroundBar.backgroundColor = UIColor.redColor().CGColor
}
func updateProgress(loadState:LoadState) {
activeLoadingStart()
displayLoadAmount(loadState)
loadState.error = false
backgroundBar.backgroundColor = UIColor.greenColor().CGColor
}
func activeLoadingStart() {
guard hasStarted == false else { return }
backgroundBar.backgroundColor = UIColor.greenColor().CGColor
reviewCountBar.frame = CGRect(x: 0,y: maxBarHeight,width: width1,height: 0)
self.hasStarted = true
let pos = self.center
UIView.animateWithDuration(0.3, animations: { () -> Void in // shift down
self.center = CGPoint(x:pos.x,y: pos.y + self.verticalAnimationDistance)
})
}
func finishedLoading(loadState:LoadState) {
if loadState.error {
backgroundBar.backgroundColor = UIColor.redColor().CGColor
}
else {
backgroundBar.backgroundColor = lightGrayBack
}
let pos = self.center
if self.hasStarted == true {
UIView.animateWithDuration(0.3, animations: { () -> Void in // shift up
self.center = CGPoint(x:pos.x,y: pos.y - self.verticalAnimationDistance)
})
}
}
}
| mit | 8c0619ec3df0c5c8a4ebc94f8f8c1603 | 33.039063 | 91 | 0.634611 | 4.378894 | false | false | false | false |
Merlini93/Weibo | Weibo/Weibo/Classes/Main/BaseTableViewController.swift | 1 | 4155 | //
// BaseTableViewController.swift
// Weibo
//
// Created by 李遨东 on 16/9/8.
// Copyright © 2016年 Merlini. All rights reserved.
//
import UIKit
class BaseTableViewController: UITableViewController,VisitorViewDelegate {
var userLogin = true
var visitorView: VisitorView?
override func loadView() {
userLogin ? super.loadView() : setupVisitorView()
}
private func setupVisitorView(){
let customView = VisitorView()
view = customView
customView.delegate = self
visitorView = customView
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(regFunc))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(loginFunc))
// navigationController?.navigationBar.tintColor = UIColor.orangeColor()
}
func loginFunc() {
print("响应登录")
}
func regFunc() {
print("响应注册")
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 8cd1e201a8a1946606e3fca98c4ae87d | 31.714286 | 157 | 0.672732 | 5.555256 | false | false | false | false |
matt/PeopleManager | PeopleManager/RegionViewController.swift | 1 | 2777 | //
// RegionViewController.swift
// PeopleManager
//
// Created by Matthew Mohrman on 8/22/14.
// Copyright (c) 2014 Matthew Mohrman. All rights reserved.
//
import UIKit
protocol RegionViewControllerDelegate {
func doneSelectingRegion(region: String)
}
class RegionViewController: UITableViewController {
var delegate: RegionViewControllerDelegate
let regions: [String] = {
var error: NSError? = nil
let filePath = NSBundle.mainBundle().pathForResource("countries", ofType: "json")
let data = NSData.dataWithContentsOfFile(filePath!, options: nil, error: &error)
let regionObjs = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as [String: [String: String]]!
var regions = [String]()
for (regionName, _) in regionObjs {
regions.append(regionName)
}
return sorted(regions, <)
}()
let cellIdentifier = "regionCell"
init(delegate: RegionViewControllerDelegate) {
self.delegate = delegate
super.init(nibName: nil, bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Country"
let cancelItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: Selector.convertFromStringLiteral("cancelTapped"))
navigationItem.rightBarButtonItem = cancelItem
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
}
// MARK: - UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return regions.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: cellIdentifier)
}
cell!.textLabel!.text = regions[indexPath.row]
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
delegate.doneSelectingRegion(regions[indexPath.row])
dismissViewControllerAnimated(true, completion: nil)
}
func cancelTapped() {
dismissViewControllerAnimated(true, completion: nil)
}
} | mit | 4f43c8a196dc5208d96e1d1d3543e301 | 30.931034 | 164 | 0.661865 | 5.445098 | false | false | false | false |
Takanu/Pelican | Sources/Pelican/API/Types/Markup/Inline/InlineKeyboard.swift | 1 | 10547 | //
// Inline.swift
// Pelican
//
// Created by Takanu Kyriako on 31/08/2017.
//
import Foundation
/**
Represents a series of inline buttons that will be displayed underneath the message when included with it.
Each inline button can do one of the following:
_ _ _ _ _
**Callback Data**
This sends a small String back to the bot as a `CallbackQuery`, which is automatically filtered
back to the session and to a `callbackState` if one exists.
Alternatively if the keyboard the button belongs to is part of a `Prompt`, it will automatically
be received by it in the respective ChatSession, and the prompt will respond based on how you have set
it up.
**URL**
The button when pressed will re-direct users to a webpage.
**Inine Query Switch**
This can only be used when the bot supports Inline Queries. This prompts the user to select one of their chats
to open it, and when open the client will insert the bot‘s username and a specified query in the input field.
**Inline Query Current Chat**
This can only be used when the bot supports Inline Queries. Pressing the button will insert the bot‘s username
and an optional specific inline query in the current chat's input field.
*/
final public class MarkupInline: MarkupType, Codable, Equatable {
public var keyboard: [[MarkupInlineKey]] = []
/// Coding keys to map values when Encoding and Decoding.
enum CodingKeys: String, CodingKey {
case keyboard = "inline_keyboard"
}
// Blank!
public init() {
return
}
/**
Creates an Inline Keyboard using a series of specified `MarkupInlineKey` types, where all buttons will
be arranged on a single row.
- parameter buttonsIn: The buttons to be included in the keyboard.
*/
public init(withButtons buttonsIn: MarkupInlineKey...) {
var array: [MarkupInlineKey] = []
for button in buttonsIn {
array.append(button)
}
keyboard.append(array)
}
/**
Creates an Inline Keyboard using a series of specified button label and URL string pairs, where all buttons will
be arranged on a single row.
- parameter pair: A sequence of label/url String tuples that will define each key on the keyboard.
*/
public init(withURL sequence: (url: String, text: String)...) {
var array: [MarkupInlineKey] = []
for tuple in sequence {
let button = MarkupInlineKey(fromURL: tuple.url, text: tuple.text)
array.append(button)
}
keyboard.append(array)
}
/**
Creates an Inline Keyboard using a series of specified button label and callback String pairs, where all buttons will
be arranged on a single row.
- parameter pair: A sequence of label/callback String tuples that will define each key on the keyboard.
*/
public init?(withCallback sequence: (query: String, text: String?)...) {
var array: [MarkupInlineKey] = []
for tuple in sequence {
// Try to process them, but propogate the error if it fails.
guard let button = MarkupInlineKey(fromCallbackData: tuple.query, text: tuple.text) else {
return nil
}
array.append(button)
}
keyboard.append(array)
}
/**
Creates an Inline Keyboard using sets of arrays containing label and callback tuples, where each tuple array
is a single row.
- parameter array: A an array of label/callback String tuple arrays that will define each row on the keyboard.
*/
public init?(withCallback array: [[(query: String, text: String)]]) {
for row in array {
var array: [MarkupInlineKey] = []
for tuple in row {
// Try to process them, but propogate the error if it fails.
guard let button = MarkupInlineKey(fromCallbackData: tuple.query, text: tuple.text) else {
return nil
}
array.append(button)
}
keyboard.append(array)
}
}
/**
Creates an Inline Keyboard using a series of specified button label and "Inline Query Current Chat" String pairs, where all buttons will
be arranged on a single row.
- parameter pair: A sequence of label/"Inline Query Current Chat" String tuples that will define each key on the keyboard.
*/
public init(withInlineQueryCurrent sequence: (query: String, text: String)...) {
var array: [MarkupInlineKey] = []
for tuple in sequence {
let button = MarkupInlineKey(fromInlineQueryCurrent: tuple.query, text: tuple.text)
array.append(button)
}
keyboard.append(array)
}
/**
Creates an Inline Keyboard using a series of specified button label and "Inline Query New Chat" String pairs, where all buttons will
be arranged on a single row.
- parameter pair: A sequence of label/"Inline Query New Chat" String tuples that will define each key on the keyboard.
*/
public init(withInlineQueryNewChat sequence: (query: String, text: String)...) {
var array: [MarkupInlineKey] = []
for tuple in sequence {
let button = MarkupInlineKey(fromInlineQueryNewChat: tuple.query, text: tuple.text)
array.append(button)
}
keyboard.append(array)
}
/**
Creates an Inline Keyboard using a series of labels. The initializer will then generate an associated ID value for each
label and assign it to the button as Callback data, starting with "1" and incrementing upwards.
All buttons wil be arranged on a single row.
- parameter labels: A sequence of String labels that will define each key on the keyboard.
*/
public init?(withGenCallback sequence: String...) {
var array: [MarkupInlineKey] = []
var id = 1
for label in sequence {
guard let button = MarkupInlineKey(fromCallbackData: String(id), text: label) else {
return nil
}
array.append(button)
id += 1
}
keyboard.append(array)
}
/**
Creates an Inline Keyboard using a set of nested String Arrays, where the array structure defines the specific arrangement
of the keyboard.
The initializer will generate an associated ID value for eachlabel and assign it to the button as Callback data, starting
with "1" and incrementing upwards.
- parameter rows: A nested set of String Arrays, where each String array will form a single row on the inline keyboard.
*/
public init?(withGenCallback rows: [[String]]) {
var id = 1
for row in rows {
var array: [MarkupInlineKey] = []
for label in row {
guard let button = MarkupInlineKey(fromCallbackData: String(id), text: label) else {
return nil
}
array.append(button)
id += 1
}
keyboard.append(array)
}
}
/**
Adds an extra row to the keyboard using the sequence of buttons provided.
*/
public func addRow(sequence: MarkupInlineKey...) {
var array: [MarkupInlineKey] = []
for button in sequence {
array.append(button)
}
keyboard.append(array)
}
/**
Adds extra rows to the keyboard based on the array of buttons you provide.
*/
public func addRow(array: [MarkupInlineKey]...) {
for item in array {
keyboard.append(item)
}
}
/**
Returns all available callback data from any button held inside this markup
*/
public func getCallbackData() -> [String]? {
var data: [String] = []
for row in keyboard {
for key in row {
if key.type == .callbackData {
data.append(key.data)
}
}
}
return data
}
/**
Returns all labels associated with the inline keyboard.
*/
public func getLabels() -> [String] {
var labels: [String] = []
for row in keyboard {
for key in row {
labels.append(key.text)
}
}
return labels
}
/**
Returns the label thats associated with the provided data, if it exists.
*/
public func getLabel(withData data: String) -> String? {
for row in keyboard {
for key in row {
if key.data == data { return key.text }
}
}
return nil
}
/**
Returns the key thats associated with the provided data, if it exists.
*/
public func getKey(withData data: String) -> MarkupInlineKey? {
for row in keyboard {
for key in row {
if key.data == data { return key }
}
}
return nil
}
/**
Replaces a key with another provided one, by trying to match the given data with a key
*/
public func replaceKey(usingType type: InlineKeyType, data: String, newKey: MarkupInlineKey) -> Bool {
for (rowIndex, row) in keyboard.enumerated() {
var newRow = row
var replaced = false
// Iterate through each key in each row for a match
for (i, key) in newRow.enumerated() {
if replaced == true { continue }
if key.type == type {
if key.data == data {
newRow.remove(at: i)
newRow.insert(newKey, at: i)
replaced = true
}
}
}
// If we made a match, switch out the rows and exit
if replaced == true {
keyboard.remove(at: rowIndex)
keyboard.insert(newRow, at: rowIndex)
return true
}
}
return false
}
/**
Replaces a key with another provided one, by trying to match the keys it has with one that's provided.
*/
public func replaceKey(oldKey: MarkupInlineKey, newKey: MarkupInlineKey) -> Bool {
for (rowIndex, row) in keyboard.enumerated() {
var newRow = row
var replaced = false
// Iterate through each key in each row for a match
for (i, key) in newRow.enumerated() {
if replaced == true { continue }
if key == oldKey {
newRow.remove(at: i)
newRow.insert(newKey, at: i)
replaced = true
}
}
// If we made a match, switch out the rows and exit
if replaced == true {
keyboard.remove(at: rowIndex)
keyboard.insert(newRow, at: rowIndex)
return true
}
}
return false
}
/**
Tries to find and delete a key, based on a match with one provided.
*/
public func deleteKey(key: MarkupInlineKey) -> Bool {
for (rowIndex, row) in keyboard.enumerated() {
var newRow = row
var removed = false
// Iterate through each key in each row for a match
for (i, newKey) in newRow.enumerated() {
if removed == true { continue }
if key == newKey {
newRow.remove(at: i)
removed = true
}
}
// If we made a match, switch out the rows and exit
if removed == true {
keyboard.remove(at: rowIndex)
keyboard.insert(newRow, at: rowIndex)
return true
}
}
return false
}
static public func ==(lhs: MarkupInline, rhs: MarkupInline) -> Bool {
if lhs.keyboard.count != rhs.keyboard.count { return false }
for (i, lhsRow) in lhs.keyboard.enumerated() {
let rhsRow = rhs.keyboard[i]
if lhsRow.count != rhsRow.count { return false }
for (iKey, lhsKey) in lhsRow.enumerated() {
let rhsKey = rhsRow[iKey]
if lhsKey != rhsKey { return false }
}
}
return true
}
}
| mit | 490c3ac09d7fcbaf8ee41133487a1697 | 24.840686 | 137 | 0.680072 | 3.663308 | false | false | false | false |
ostholz/ercode | ERCode/PatientData.swift | 1 | 429 | //
// PetientData.swift
// ERCode
//
// Created by Dong Wang on 16.10.14.
// Copyright (c) 2014 i2dm. All rights reserved.
//
import Foundation
struct PatientData {
var blood_type = ""
var allergies = ""
var medical_conditions = ""
var medical_notes = ""
var medications = ""
var emergency_contacts = [Contact]()
var weight = ""
var height = ""
var ercode = ""
var organ_donor = ""
} | apache-2.0 | 714c4ed0d11cb5f3f99a2bc99a20c931 | 18.545455 | 49 | 0.594406 | 3.432 | false | false | false | false |
WhisperSystems/Signal-iOS | SignalMessaging/environment/migrations/OWS110SortIdMigration.swift | 1 | 5496 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
public class OWS110SortIdMigration: YDBDatabaseMigration {
// increment a similar constant for each migration.
@objc
public override class var migrationId: String {
// append char "x" because we want to rerun on some internal devices which
// have already run this migration.
return "110x"
}
override public func runUp(completion: @escaping OWSDatabaseMigrationCompletion) {
Logger.debug("")
BenchAsync(title: "Sort Migration") { completeBenchmark in
self.doMigration {
completeBenchmark()
completion()
}
}
}
private func doMigration(completion: @escaping OWSDatabaseMigrationCompletion) {
// TODO batch this?
self.ydbReadWriteConnection.readWrite { transaction in
var archivedThreads: [TSThread] = []
// get archived threads before migration
TSThread.ydb_enumerateCollectionObjects(with: transaction) { (object, _) in
guard let thread = object as? TSThread else {
owsFailDebug("unexpected object: \(type(of: object))")
return
}
if thread.isArchivedByLegacyTimestampForSorting {
archivedThreads.append(thread)
}
}
guard let legacySorting = transaction.safeAutoViewTransaction(TSMessageDatabaseViewExtensionName_Legacy) else {
owsFailDebug("legacySorting was unexpectedly nil")
return
}
let totalCount: UInt = legacySorting.numberOfItemsInAllGroups()
var completedCount: UInt = 0
var allGroups = [String]()
legacySorting.enumerateGroups { group, _ in
allGroups.append(group)
}
var seenGroups: Set<String> = Set()
for group in allGroups {
autoreleasepool {
// Sanity Check #1
// Make sure our enumeration is monotonically increasing.
// Note: sortIds increase monotonically WRT timestampForLegacySorting, but only WRT the interaction's thread.
//
// e.g. When we migrate the **next** thread, we start with that thread's oldest interaction. So it's possible and expected
// that thread2's oldest interaction will have a smaller timestampForLegacySorting, but a greater sortId then an interaction
// in thread1. That's OK because we only sort messages with respect to the thread they belong in. We don't have any sort of
// "global sort" of messages across all threads.
var previousTimestampForLegacySorting: UInt64 = 0
// Sanity Check #2
// Ensure we only process a DB View's group (i.e. threadId) once.
guard !seenGroups.contains(group) else {
owsFail("unexpectedly seeing a repeated group: \(group)")
}
seenGroups.insert(group)
var groupKeys = [String]()
legacySorting.enumerateKeys(inGroup: group, using: { (_, key, _, _) in
groupKeys.append(key)
})
let groupKeyBatchSize: Int = 1024
for batch in groupKeys.chunked(by: groupKeyBatchSize) {
autoreleasepool {
for uniqueId in batch {
guard let interaction = TSInteraction.ydb_fetch(uniqueId: uniqueId, transaction: transaction) else {
owsFailDebug("Could not load interaction: \(uniqueId)")
return
}
if interaction.timestampForLegacySorting() < previousTimestampForLegacySorting {
owsFailDebug("unexpected object ordering previousTimestampForLegacySorting: \(previousTimestampForLegacySorting) interaction.timestampForLegacySorting: \(interaction.timestampForLegacySorting())")
}
previousTimestampForLegacySorting = interaction.timestampForLegacySorting()
interaction.ydb_saveNextSortId(transaction: transaction)
completedCount += 1
if completedCount % 100 == 0 {
// Legit usage of legacy sorting for migration to new sorting
Logger.info("thread: \(interaction.uniqueThreadId), timestampForLegacySorting:\(interaction.timestampForLegacySorting()), sortId: \(interaction.sortId) totalCount: \(totalCount), completedcount: \(completedCount)")
}
}
}
}
}
}
Logger.info("re-archiving \(archivedThreads.count) threads which were previously archived")
for archivedThread in archivedThreads {
archivedThread.archiveThread(with: transaction.asAnyWrite)
}
self.markAsComplete(with: transaction.asAnyWrite)
}
completion()
}
}
| gpl-3.0 | 3e65497a1f6364292909826ed6d1307b | 45.576271 | 250 | 0.555313 | 5.973913 | false | false | false | false |
TBXark/Ruler | Ruler/Source/Localization.swift | 1 | 1020 | //
// Localization.swift
// Ruler
//
// Created by TBXark on 2020/7/17.
// Copyright © 2020 Tbxark. All rights reserved.
//
import Foundation
enum Localization: String {
case arNotAvailable = "ARNotAvailable"
case arInitializing = "ARInitializing"
case arInsufficientFeatures = "ARInsufficientFeatures"
case arExcessiveMotion = "ARExcessiveMotion"
case arInitializingMessage = "ARInitializingMessage"
case arInsufficientFeaturesMessage = "ARInsufficientFeaturesMessage"
case arExcessiveMotionMessage = "ARExcessiveMotionMessage"
case arRelocalizing = "ARRelocalizing"
case saveSuccess = "SaveSuccess"
case saveFail = "SaveFail"
case saveNeedPermission = "SaveNeedPermission"
case didCopy = "DidCopy"
case setting = "Setting"
case startArea = "StartArea"
case startLength = "StartLength"
func toString() -> String {
return NSLocalizedString(self.rawValue, tableName: nil, bundle: Bundle.main, value: "", comment: "")
}
}
| mit | 7d2b26017856188f2d9325239087543e | 28.970588 | 108 | 0.711482 | 4.17623 | false | false | false | false |
tresorit/ZeroKit-Realm-encrypted-tasks | ios/Pods/ZeroKit/ZeroKit/InternalApi.swift | 1 | 8086 | import WebKit
class InternalApi: NSObject {
typealias JsApiResultCallback = (/*success:*/ Bool, /*result:*/ AnyObject) -> Void
typealias ErrorCallback = (Error?) -> Void
struct MethodParameter {
let value: String
init(plainValue: String) {
self.value = InternalApi.escapeParameter(plainValue)
}
init(escapedValue: String) {
self.value = escapedValue
}
}
private enum ApiState {
case notLoaded
case loading
case didLoad
}
private let apiUrl: URL
private var apiState = ApiState.notLoaded
private var webView: WKWebView!
private var webViewDelegate: WebViewDelegate!
private var callbacks = [String: JsApiResultCallback]()
private var apiLoadCompletions = [ErrorCallback]()
private weak var zeroKit: ZeroKit?
let processPool = WKProcessPool()
var isLoaded: Bool {
get { return self.apiState == .didLoad }
}
deinit {
self.webView?.stopLoading()
self.webView?.removeFromSuperview()
}
init(apiUrl: URL, webViewHostView: UIView, zeroKit: ZeroKit) {
self.apiUrl = apiUrl
self.zeroKit = zeroKit
super.init()
createWebView(hostView: webViewHostView)
loadApi { _ in }
}
private func createWebView(hostView: UIView) {
self.webViewDelegate = WebViewDelegate(internalApi: self)
let controller = WKUserContentController()
let messageHandlerName = "ZeroKitHandler" // referenced in javascript
controller.add(self.webViewDelegate, name: messageHandlerName)
let scriptJsUrl = Bundle(for: self.classForCoder).url(forResource: "ZeroKit", withExtension: "js")!
let scriptJs = try! String(contentsOf: scriptJsUrl)
let script = WKUserScript(source: scriptJs, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
controller.addUserScript(script)
let config = WKWebViewConfiguration()
config.processPool = self.processPool
config.userContentController = controller;
self.webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), configuration: config)
self.webView.navigationDelegate = self.webViewDelegate
hostView.insertSubview(self.webView, at: 0)
}
// MARK: API calls
func callMethod(_ methodOnObject: String, parameters: [String], callback: @escaping JsApiResultCallback) {
var methodParams = [MethodParameter]()
for param in parameters {
methodParams.append(MethodParameter(plainValue: param))
}
callMethod(methodOnObject, methodParameters: methodParams, callback: callback)
}
func callMethod(_ methodOnObject: String, methodParameters: [MethodParameter], callback: @escaping JsApiResultCallback) {
loadApi { error in
if error != nil {
callback(false, ZeroKitError.apiLoadingError.nserrorValue)
} else {
self.callMethodInner(methodOnObject, methodParameters: methodParameters, callback: callback)
}
}
}
private func callMethodInner(_ methodOnObject: String, methodParameters: [MethodParameter], callback: @escaping JsApiResultCallback) {
let paramStr = InternalApi.parameterString(methodParameters)
let callbackId = UUID().uuidString
callbacks[callbackId] = callback
let object: String
if let lastDot = methodOnObject.range(of: ".", options: .backwards, range: nil, locale: nil) {
object = methodOnObject.substring(to: lastDot.lowerBound)
} else {
object = "null"
}
var js = "ios_callApiMethod(\(object), \(methodOnObject), \"\(callbackId)\""
if paramStr.characters.count > 0 {
js.append(", \(paramStr)")
}
js.append(")")
self.webView!.evaluateJavaScript(js) { (obj: Any?, error: Error?) in
if error != nil {
print("ZeroKit error evaluating javascript")
}
}
}
class private func parameterString(_ parameters: [MethodParameter]) -> String {
var escapedParams = [String]()
for param in parameters {
escapedParams.append(String(format: "\"%@\"", param.value))
}
return escapedParams.joined(separator: ",")
}
class func escapeParameter(_ parameter: String) -> String {
var escaped = ""
for unicode in parameter.unicodeScalars {
let val = unicode.value
escaped.append(String(format: "\\u%04x", val))
}
return escaped;
}
func runJavascript(_ js: String, completion: ((Any?, Error?) -> Void)? = nil) {
loadApi { error in
if error != nil {
completion?(nil, ZeroKitError.apiLoadingError.nserrorValue)
} else {
self.webView!.evaluateJavaScript(js, completionHandler: { (obj: Any?, error: Error?) in
completion?(obj, error)
})
}
}
}
// MARK: API loading
private func loadApi(completion: @escaping ErrorCallback) {
if self.apiState == .didLoad {
completion(nil)
return
}
apiLoadCompletions.append(completion)
enterState(.loading)
}
private func enterState(_ newState: ApiState, error: Error? = nil) {
guard self.apiState != newState else {
return
}
self.apiState = newState
switch newState {
case .notLoaded:
NotificationCenter.default.post(name: ZeroKit.DidFailLoadingNotificationInner, object: zeroKit)
runApiLoadCompletions(error: error ?? ZeroKitError.unknownError)
case .loading:
self.webView!.load(URLRequest(url: self.apiUrl))
case .didLoad:
NotificationCenter.default.post(name: ZeroKit.DidLoadNotificationInner, object: zeroKit)
runApiLoadCompletions()
}
}
private func runApiLoadCompletions(error: Error? = nil) {
for completion in apiLoadCompletions {
completion(error)
}
apiLoadCompletions.removeAll()
}
// MARK: Web view delegate
private class WebViewDelegate: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
weak var internalApi: InternalApi?
init(internalApi: InternalApi) {
self.internalApi = internalApi
}
// MARK: WKScriptMessageHandler
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
let resultArray = message.body as! [AnyObject]
let success: Bool = (resultArray[0] as! NSNumber).boolValue;
let callbackId = resultArray[1] as! String
let resultValue = resultArray[2]
let callback = self.internalApi?.callbacks[callbackId]
_ = self.internalApi?.callbacks.removeValue(forKey: callbackId)
callback?(success, resultValue)
}
// MARK: WKNavigationDelegate
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("ZeroKit API loaded")
self.internalApi?.enterState(.didLoad)
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print("Failed loading ZeroKit API")
self.internalApi?.enterState(.notLoaded, error: error)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("Failed loading ZeroKit API")
self.internalApi?.enterState(.notLoaded, error: error)
}
}
}
| bsd-3-clause | c3b3b5bdea5e3d6c602d29911cbf39fa | 34.310044 | 138 | 0.603265 | 5.104798 | false | false | false | false |
zjjzmw1/speedxSwift | speedxSwift/speedxSwift/Tool/Urls.swift | 2 | 1755 | //
// Urls.swift
// PinGo
//
// Created by GaoWanli on 16/1/16.
// Copyright © 2016年 GWL. All rights reserved.
//
import Foundation
let kAPI_URL = "http://api.impingo.me"
let kAPI_USERID = "userID=1404034"
let kAPI_SESSION_ID = "sessionID=e5c8c1b3e8153e78ab"
let kAPI_SESSION_TOKEN = "sessionToken=cce76093c4"
let kAPI_KEY = "key=B57B690BD66AE7B4C7F17A5E60293B20"
let kAPI_PEERID = "peerID=6EDEE890B4E5"
let kAPI_PRODUCTID = "productID=com.joyodream.pingo"
let kAPI_VERSION = "version=3.7"
let kAPI_VERSION_CODE = "versionCode=15"
let kAPI_SYSVERSION = "sysVersion=9.2.1"
let kAPI_CHANNELID = "channelID=App%20Store"
let kAPI_OS = "os=ios"
/// 首页精选列表的地址
let kHOME_TOPIC_LIST_URL = kAPI_URL + "/topic/listSelectionBottleTopic"
/// 首页关注列表的地址
let kHOME_FOLLOW_TOPIC_LIST_URL = kAPI_URL + "/topic/listOnlineBottleTopic"
/// 话题首页banner列表的地址
let kDISCOVER_BANNER_LIST_URL = kAPI_URL + "/banner/listBanner"
/// 话题首页推荐列表的地址
let kDISCOVER_SUBJECTINFO_LIST_URL = kAPI_URL + "/subject/listSubjectCategory"
/// 获取话题信息的地址
let kGET_SUBJECTINFO_URL = kAPI_URL + "/subject/getSubject"
/// 获取话题下Topic的地址
let kGET_LISTSUBJECTTOPIC_URL = kAPI_URL + "/subject/listSubjectTopic"
/// 访客记录的地址
let kVISITOR_RECORD_URL = kAPI_URL + "/user/listVisitUser"// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com | mit | 26828bfbce4f2bce99bfb0d2e2bb415d | 40.710526 | 81 | 0.622475 | 2.874773 | false | false | false | false |
AllisonWangJiaoJiao/KnowledgeAccumulation | 20.算法/算法/ViewController.swift | 1 | 3073 | //
// ViewController.swift
// 算法
//
// Created by Allison on 2017/11/19.
// Copyright © 2017年 Allison. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// let a = [6,2,7,3,8,9]
// let newArr = bubble_sort(a: a)
// print(newArr)
// let a = [6,2,7,3,8,9]
// let newArr = quickSort(oArr: a)
// print(newArr)
let a = [6,2,7,3,8,9]
let newArr3 = insertionSort(oArr: a)
print(newArr3)
// let a = [6,2,7,3,8,9]
// let newArr4 = selectSort(oArr: a)
// print(newArr4)
}
}
extension ViewController {
// MARK: - 冒泡排序
func bubble_sort<T: Comparable> (a : [T]) -> [T] {
var arr = a
for i in 0 ..< arr.count - 1 {
for j in 0 ..< arr.count - 1 - i {
if arr[j] > arr[j+1] {
let temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
}
}
}
return arr
}
// MARK: - 快速排序
func quickSort<T: Comparable> (oArr: [T]) -> [T] {
let arr = oArr
if let (k, rest) = arr.decompose {
let lesser = rest.filter { $0 < k }
let greater = rest.filter { $0 >= k }
let les = quickSort(oArr: lesser)
let gre = quickSort(oArr: greater)
return les + [k] + gre
} else {
return []
}
}
// MARK: - 插入排序 O(N2/4)
func insertionSort<T: Comparable>(oArr: [T]) -> [T] {
var arr = oArr
for i in 1..<arr.count {
let temp = arr[i]
var j = i
// 与已排序的数逐一比较,大于temp时,改数后移
while j > 0 && arr[j - 1] >= temp {
print(arr[j - 1])
arr[j] = arr[j - 1]
j -= 1
}
arr[j] = temp
print(arr[j])
}
print(arr)
return arr
}
//选择排序 O(N)
func selectSort<T: Comparable>(oArr: [T]) -> [T] {
var arr = oArr
var minIndex = 0 //记录每次遍历的最小值
for outerIndex in 0..<arr.count {
minIndex = outerIndex
for innerIndex in (outerIndex + 1)..<arr.count {
if arr[minIndex] > arr[innerIndex] {
minIndex = innerIndex //判断最小值,记住下标
}
if minIndex != outerIndex { //一个轮回结束交换
let temp = arr[outerIndex]
arr[outerIndex] = arr[minIndex]
arr[minIndex] = temp
}
}
}
print(arr)
return arr
}
}
extension Array {
var decompose : (head: Element, tail: [Element])? {
return (count > 0) ? (self[0], Array(self[1..<count])) : nil
}
}
| mit | 48c95fb48256548c6bd13fdf72e9104b | 23.739496 | 79 | 0.444633 | 3.423256 | false | false | false | false |
johnno1962d/swift | stdlib/private/SwiftPrivateLibcExtras/Subprocess.swift | 1 | 9774 | //===--- Subprocess.swift -------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftPrivate
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(Android)
import Glibc
#endif
// posix_spawn is not available on Android.
#if !os(Android)
// swift_posix_spawn isn't available in the public watchOS SDK, we sneak by the
// unavailable attribute declaration here of the APIs that we need.
// FIXME: Come up with a better way to deal with APIs that are pointers on some
// platforms but not others.
#if os(Linux)
typealias swift_posix_spawn_file_actions_t = posix_spawn_file_actions_t
#else
typealias swift_posix_spawn_file_actions_t = posix_spawn_file_actions_t?
#endif
@_silgen_name("swift_posix_spawn_file_actions_init")
func swift_posix_spawn_file_actions_init(
_ file_actions: UnsafeMutablePointer<swift_posix_spawn_file_actions_t>
) -> CInt
@_silgen_name("swift_posix_spawn_file_actions_destroy")
func swift_posix_spawn_file_actions_destroy(
_ file_actions: UnsafeMutablePointer<swift_posix_spawn_file_actions_t>
) -> CInt
@_silgen_name("swift_posix_spawn_file_actions_addclose")
func swift_posix_spawn_file_actions_addclose(
_ file_actions: UnsafeMutablePointer<swift_posix_spawn_file_actions_t>,
_ filedes: CInt) -> CInt
@_silgen_name("swift_posix_spawn_file_actions_adddup2")
func swift_posix_spawn_file_actions_adddup2(
_ file_actions: UnsafeMutablePointer<swift_posix_spawn_file_actions_t>,
_ filedes: CInt,
_ newfiledes: CInt) -> CInt
@_silgen_name("swift_posix_spawn")
func swift_posix_spawn(
_ pid: UnsafeMutablePointer<pid_t>?,
_ file: UnsafePointer<Int8>,
_ file_actions: UnsafePointer<swift_posix_spawn_file_actions_t>?,
_ attrp: UnsafePointer<posix_spawnattr_t>?,
_ argv: UnsafePointer<UnsafeMutablePointer<Int8>?>,
_ envp: UnsafePointer<UnsafeMutablePointer<Int8>?>?) -> CInt
#endif
/// Calls POSIX `pipe()`.
func posixPipe() -> (readFD: CInt, writeFD: CInt) {
var fds: [CInt] = [ -1, -1 ]
if pipe(&fds) != 0 {
preconditionFailure("pipe() failed")
}
return (fds[0], fds[1])
}
/// Start the same executable as a child process, redirecting its stdout and
/// stderr.
public func spawnChild(_ args: [String])
-> (pid: pid_t, stdinFD: CInt, stdoutFD: CInt, stderrFD: CInt) {
// The stdout, stdin, and stderr from the child process will be redirected
// to these pipes.
let childStdout = posixPipe()
let childStdin = posixPipe()
let childStderr = posixPipe()
#if os(Android)
// posix_spawn isn't available on Android. Instead, we fork and exec.
// To correctly communicate the exit status of the child process to this
// (parent) process, we'll use this pipe.
let childToParentPipe = posixPipe()
let pid = fork()
precondition(pid >= 0, "fork() failed")
if pid == 0 {
// pid of 0 means we are now in the child process.
// Capture the output before executing the program.
dup2(childStdout.writeFD, STDOUT_FILENO)
dup2(childStdin.readFD, STDIN_FILENO)
dup2(childStderr.writeFD, STDERR_FILENO)
// Set the "close on exec" flag on the parent write pipe. This will
// close the pipe if the execve() below successfully executes a child
// process.
let closeResult = fcntl(childToParentPipe.writeFD, F_SETFD, FD_CLOEXEC)
let closeErrno = errno
precondition(
closeResult == 0,
"Could not set the close behavior of the child-to-parent pipe; " +
"errno: \(closeErrno)")
// Start the executable. If execve() does not encounter an error, the
// code after this block will never be executed, and the parent write pipe
// will be closed.
withArrayOfCStrings([Process.arguments[0]] + args) {
execve(Process.arguments[0], $0, _getEnviron())
}
// If execve() encountered an error, we write the errno encountered to the
// parent write pipe.
let errnoSize = sizeof(errno.dynamicType)
var execveErrno = errno
let writtenBytes = withUnsafePointer(&execveErrno) {
write(childToParentPipe.writeFD, UnsafePointer($0), errnoSize)
}
let writeErrno = errno
if writtenBytes > 0 && writtenBytes < errnoSize {
// We were able to write some of our error, but not all of it.
// FIXME: Retry in this case.
preconditionFailure("Unable to write entire error to child-to-parent " +
"pipe.")
} else if writtenBytes == 0 {
preconditionFailure("Unable to write error to child-to-parent pipe.")
} else if writtenBytes < 0 {
preconditionFailure("An error occurred when writing error to " +
"child-to-parent pipe; errno: \(writeErrno)")
}
// Close the pipe when we're done writing the error.
close(childToParentPipe.writeFD)
}
#else
var fileActions = _make_posix_spawn_file_actions_t()
if swift_posix_spawn_file_actions_init(&fileActions) != 0 {
preconditionFailure("swift_posix_spawn_file_actions_init() failed")
}
// Close the write end of the pipe on the child side.
if swift_posix_spawn_file_actions_addclose(
&fileActions, childStdin.writeFD) != 0 {
preconditionFailure("swift_posix_spawn_file_actions_addclose() failed")
}
// Remap child's stdin.
if swift_posix_spawn_file_actions_adddup2(
&fileActions, childStdin.readFD, STDIN_FILENO) != 0 {
preconditionFailure("swift_posix_spawn_file_actions_adddup2() failed")
}
// Close the read end of the pipe on the child side.
if swift_posix_spawn_file_actions_addclose(
&fileActions, childStdout.readFD) != 0 {
preconditionFailure("swift_posix_spawn_file_actions_addclose() failed")
}
// Remap child's stdout.
if swift_posix_spawn_file_actions_adddup2(
&fileActions, childStdout.writeFD, STDOUT_FILENO) != 0 {
preconditionFailure("swift_posix_spawn_file_actions_adddup2() failed")
}
// Close the read end of the pipe on the child side.
if swift_posix_spawn_file_actions_addclose(
&fileActions, childStderr.readFD) != 0 {
preconditionFailure("swift_posix_spawn_file_actions_addclose() failed")
}
// Remap child's stderr.
if swift_posix_spawn_file_actions_adddup2(
&fileActions, childStderr.writeFD, STDERR_FILENO) != 0 {
preconditionFailure("swift_posix_spawn_file_actions_adddup2() failed")
}
var pid: pid_t = -1
var childArgs = args
childArgs.insert(Process.arguments[0], at: 0)
let interpreter = getenv("SWIFT_INTERPRETER")
if interpreter != nil {
if let invocation = String(validatingUTF8: interpreter) {
childArgs.insert(invocation, at: 0)
}
}
let spawnResult = withArrayOfCStrings(childArgs) {
swift_posix_spawn(
&pid, childArgs[0], &fileActions, nil, $0, _getEnviron())
}
if spawnResult != 0 {
print(String(cString: strerror(spawnResult)))
preconditionFailure("swift_posix_spawn() failed")
}
if swift_posix_spawn_file_actions_destroy(&fileActions) != 0 {
preconditionFailure("swift_posix_spawn_file_actions_destroy() failed")
}
#endif
// Close the read end of the pipe on the parent side.
if close(childStdin.readFD) != 0 {
preconditionFailure("close() failed")
}
// Close the write end of the pipe on the parent side.
if close(childStdout.writeFD) != 0 {
preconditionFailure("close() failed")
}
// Close the write end of the pipe on the parent side.
if close(childStderr.writeFD) != 0 {
preconditionFailure("close() failed")
}
return (pid, childStdin.writeFD, childStdout.readFD, childStderr.readFD)
}
#if !os(Android)
#if os(Linux)
internal func _make_posix_spawn_file_actions_t()
-> swift_posix_spawn_file_actions_t {
return posix_spawn_file_actions_t()
}
#else
internal func _make_posix_spawn_file_actions_t()
-> swift_posix_spawn_file_actions_t {
return nil
}
#endif
#endif
internal func _signalToString(_ signal: Int) -> String {
switch CInt(signal) {
case SIGILL: return "SIGILL"
case SIGTRAP: return "SIGTRAP"
case SIGABRT: return "SIGABRT"
case SIGFPE: return "SIGFPE"
case SIGBUS: return "SIGBUS"
case SIGSEGV: return "SIGSEGV"
case SIGSYS: return "SIGSYS"
default: return "SIG???? (\(signal))"
}
}
public enum ProcessTerminationStatus : CustomStringConvertible {
case exit(Int)
case signal(Int)
public var description: String {
switch self {
case .exit(let status):
return "Exit(\(status))"
case .signal(let signal):
return "Signal(\(_signalToString(signal)))"
}
}
}
public func posixWaitpid(_ pid: pid_t) -> ProcessTerminationStatus {
var status: CInt = 0
if waitpid(pid, &status, 0) < 0 {
preconditionFailure("waitpid() failed")
}
if (WIFEXITED(status)) {
return .exit(Int(WEXITSTATUS(status)))
}
if (WIFSIGNALED(status)) {
return .signal(Int(WTERMSIG(status)))
}
preconditionFailure("did not understand what happened to child process")
}
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
@_silgen_name("swift_SwiftPrivateLibcExtras_NSGetEnviron")
func _NSGetEnviron() -> UnsafeMutablePointer<UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>>
#endif
internal func _getEnviron() -> UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> {
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
return _NSGetEnviron().pointee
#elseif os(FreeBSD)
return environ;
#elseif os(Android)
return environ
#else
return __environ
#endif
}
| apache-2.0 | 367ee4e9be0e9a4dc0889622af799349 | 32.358362 | 96 | 0.686618 | 3.767926 | false | false | false | false |
PerfectServers/APIDocumentationServer | Sources/APIDocumentationServer/Handlers/group/groupModAction.swift | 1 | 1920 | //
// userModAction.swift
// ServerMonitor
//
// Created by Jonathan Guthrie on 2017-04-30.
//
//
import SwiftMoment
import PerfectHTTP
import PerfectLogger
import LocalAuthentication
extension WebHandlers {
static func groupModAction(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
let contextAccountID = request.session?.userid ?? ""
let contextAuthenticated = !(request.session?.userid ?? "").isEmpty
if !contextAuthenticated { response.redirect(path: "/login") }
let obj = APIGroup()
var msg = ""
if let id = request.urlVariables["id"] {
try? obj.get(id)
if obj.id.isEmpty {
redirectRequest(request, response, msg: "Invalid Group", template: "views/groups")
}
}
if let name = request.param(name: "name"), !name.isEmpty,
let displayorder = request.param(name: "displayorder"), !displayorder.isEmpty,
let status = request.param(name: "status"), !status.isEmpty {
obj.name = name
obj.displayOrder = Int(displayorder) ?? 1000
if status == "active" {
obj.objectStatus = 1
} else {
obj.objectStatus = 0
}
if obj.id.isEmpty {
obj.makeID()
try? obj.create()
} else {
try? obj.save()
}
} else {
msg = "Please enter the all the details."
redirectRequest(request, response, msg: msg, template: "views/groups", additional: [
"usermod?":"true",
])
}
let list = APIGroup.listGroups()
var context: [String : Any] = [
"accountID": contextAccountID,
"authenticated": contextAuthenticated,
"grouplist?":"true",
"groups": list,
"msg": msg
]
if contextAuthenticated {
for i in WebHandlers.extras(request) {
context[i.0] = i.1
}
}
// add app config vars
for i in WebHandlers.appExtras(request) {
context[i.0] = i.1
}
response.render(template: "views/groups", context: context)
}
}
}
| apache-2.0 | 45b7c1386598e6c016fea7183e6d4143 | 21.325581 | 88 | 0.633854 | 3.33913 | false | false | false | false |
JakeLin/IBAnimatable | Sources/ActivityIndicators/Animations/ActivityIndicatorAnimationBallZigZagDeflect.swift | 2 | 2602 | //
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationBallZigZagDeflect: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let duration: CFTimeInterval = 0.7
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSize: CGFloat = size.width / 5
let duration: CFTimeInterval = 0.75
let deltaX = size.width / 2 - circleSize / 2
let deltaY = size.height / 2 - circleSize / 2
let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2,
y: (layer.bounds.size.height - circleSize) / 2,
width: circleSize,
height: circleSize)
// Circle 1
let animation = CAKeyframeAnimation(keyPath: .transform)
animation.keyTimes = [0.0, 0.33, 0.66, 1.0]
animation.timingFunctionType = .linear
animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, -deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, -deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))]
animation.duration = duration
animation.repeatCount = .infinity
animation.autoreverses = true
animation.isRemovedOnCompletion = false
let circle1 = makeCircleLayer(frame: frame, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation)
layer.addSublayer(circle1)
// Circle 2
animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, deltaY, 0)),
NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))]
let circle2 = makeCircleLayer(frame: frame, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation)
layer.addSublayer(circle2)
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationBallZigZagDeflect {
func makeCircleLayer(frame: CGRect, size: CGSize, color: UIColor, animation: CAAnimation) -> CALayer {
let circle = ActivityIndicatorShape.circle.makeLayer(size: size, color: color)
circle.frame = frame
circle.add(animation, forKey: "animation")
return circle
}
}
| mit | 5e57182c27b8ac36e9113207cbcaf1f3 | 39.65625 | 136 | 0.681783 | 4.556918 | false | false | false | false |
zvonler/PasswordElephant | external/github.com/apple/swift-protobuf/Sources/protoc-gen-swift/ExtensionSetGenerator.swift | 4 | 10531 | // Sources/protoc-gen-swift/ExtensionSetGenerator.swift - Handle Proto2 extension
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Each instance of ExtensionGenerator represents a single Proto2 extension
/// and contains the logic necessary to emit the various required sources.
/// Note that this wraps the same FieldDescriptorProto used by MessageFieldGenerator,
/// even though the Swift source emitted is very, very different.
///
// -----------------------------------------------------------------------------
import Foundation
import SwiftProtobufPluginLibrary
import SwiftProtobuf
/// Provides the generation for proto2 syntax extensions in a file.
class ExtensionSetGenerator {
/// Private helper used for the ExtensionSetGenerator.
private class ExtensionGenerator {
let fieldDescriptor: FieldDescriptor
let generatorOptions: GeneratorOptions
let namer: SwiftProtobufNamer
let comments: String
let containingTypeSwiftFullName: String
let swiftFullExtensionName: String
var extensionFieldType: String {
let label: String
switch fieldDescriptor.label {
case .optional: label = "Optional"
case .required: label = "Required"
case .repeated: label = fieldDescriptor.isPacked ? "Packed" : "Repeated"
}
let modifier: String
switch fieldDescriptor.type {
case .group: modifier = "Group"
case .message: modifier = "Message"
case .enum: modifier = "Enum"
default: modifier = ""
}
return "SwiftProtobuf.\(label)\(modifier)ExtensionField"
}
init(descriptor: FieldDescriptor, generatorOptions: GeneratorOptions, namer: SwiftProtobufNamer) {
self.fieldDescriptor = descriptor
self.generatorOptions = generatorOptions
self.namer = namer
swiftFullExtensionName = namer.fullName(extensionField: descriptor)
comments = descriptor.protoSourceComments()
containingTypeSwiftFullName = namer.fullName(message: fieldDescriptor.containingType)
}
func generateProtobufExtensionDeclarations(printer p: inout CodePrinter) {
let scope = fieldDescriptor.extensionScope == nil ? "" : "static "
let traitsType = fieldDescriptor.traitsType(namer: namer)
let swiftRelativeExtensionName = namer.relativeName(extensionField: fieldDescriptor)
var fieldNamePath: String
if fieldDescriptor.containingType.useMessageSetWireFormat &&
fieldDescriptor.type == .message &&
fieldDescriptor.label == .optional &&
fieldDescriptor.messageType === fieldDescriptor.extensionScope {
fieldNamePath = fieldDescriptor.messageType.fullName
} else {
fieldNamePath = fieldDescriptor.fullName
}
assert(fieldNamePath.hasPrefix("."))
fieldNamePath.remove(at: fieldNamePath.startIndex) // Remove the leading '.'
p.print(
comments,
"\(scope)let \(swiftRelativeExtensionName) = SwiftProtobuf.MessageExtension<\(extensionFieldType)<\(traitsType)>, \(containingTypeSwiftFullName)>(\n")
p.indent()
p.print(
"_protobuf_fieldNumber: \(fieldDescriptor.number),\n",
"fieldName: \"\(fieldNamePath)\"\n")
p.outdent()
p.print(")\n")
}
func generateMessageSwiftExtension(printer p: inout CodePrinter) {
let visibility = generatorOptions.visibilitySourceSnippet
let apiType = fieldDescriptor.swiftType(namer: namer)
let extensionNames = namer.messagePropertyNames(extensionField: fieldDescriptor)
let defaultValue = fieldDescriptor.swiftDefaultValue(namer: namer)
// ExtensionGenerator.Set provides the context to write out the properties.
p.print(
"\n",
comments,
"\(visibility)var \(extensionNames.value): \(apiType) {\n")
p.indent()
p.print(
"get {return getExtensionValue(ext: \(swiftFullExtensionName)) ?? \(defaultValue)}\n",
"set {setExtensionValue(ext: \(swiftFullExtensionName), value: newValue)}\n")
p.outdent()
p.print("}\n")
p.print(
"/// Returns true if extension `\(swiftFullExtensionName)`\n/// has been explicitly set.\n",
"\(visibility)var \(extensionNames.has): Bool {\n")
p.indent()
p.print("return hasExtensionValue(ext: \(swiftFullExtensionName))\n")
p.outdent()
p.print("}\n")
p.print(
"/// Clears the value of extension `\(swiftFullExtensionName)`.\n/// Subsequent reads from it will return its default value.\n",
"\(visibility)mutating func \(extensionNames.clear)() {\n")
p.indent()
p.print("clearExtensionValue(ext: \(swiftFullExtensionName))\n")
p.outdent()
p.print("}\n")
}
}
private let fileDescriptor: FileDescriptor
private let generatorOptions: GeneratorOptions
private let namer: SwiftProtobufNamer
// The order of these is as they are created, so it keeps them grouped by
// where they were declared.
private var extensions: [ExtensionGenerator] = []
var isEmpty: Bool { return extensions.isEmpty }
init(
fileDescriptor: FileDescriptor,
generatorOptions: GeneratorOptions,
namer: SwiftProtobufNamer
) {
self.fileDescriptor = fileDescriptor
self.generatorOptions = generatorOptions
self.namer = namer
}
func add(extensionFields: [FieldDescriptor]) {
for e in extensionFields {
assert(e.isExtension)
let extensionGenerator = ExtensionGenerator(descriptor: e,
generatorOptions: generatorOptions,
namer: namer)
extensions.append(extensionGenerator)
}
}
func generateMessageSwiftExtensions(printer p: inout CodePrinter) {
guard !extensions.isEmpty else { return }
// Reorder the list so they are grouped by the Message being extended, but
// maintaining the order they were within the file within those groups.
let grouped: [ExtensionGenerator] = extensions.enumerated().sorted {
// When they extend the same Message, use the original order.
if $0.element.containingTypeSwiftFullName == $1.element.containingTypeSwiftFullName {
return $0.offset < $1.offset
}
// Otherwise, sort by the Message being extended.
return $0.element.containingTypeSwiftFullName < $1.element.containingTypeSwiftFullName
}.map {
// Now strip off the original index to just get the list of ExtensionGenerators
// again.
return $0.element
}
// Loop through the group list and each time a new containing type is hit,
// generate the Swift Extension block. This way there is only one Swift
// Extension for each Message rather then one for every extension. This make
// the file a little easier to navigate.
var currentType: String = ""
for e in grouped {
if currentType != e.containingTypeSwiftFullName {
if !currentType.isEmpty {
p.outdent()
p.print("}\n")
}
currentType = e.containingTypeSwiftFullName
p.print(
"\n",
"extension \(currentType) {\n")
p.indent()
}
e.generateMessageSwiftExtension(printer: &p)
}
p.outdent()
p.print(
"\n",
"}\n")
}
func generateFileProtobufExtensionRegistry(printer p: inout CodePrinter) {
guard !extensions.isEmpty else { return }
let pathParts = splitPath(pathname: fileDescriptor.name)
let filenameAsIdentifer = NamingUtils.toUpperCamelCase(pathParts.base)
let filePrefix = namer.typePrefix(forFile: fileDescriptor)
p.print(
"\n",
"/// A `SwiftProtobuf.SimpleExtensionMap` that includes all of the extensions defined by\n",
"/// this .proto file. It can be used any place an `SwiftProtobuf.ExtensionMap` is needed\n",
"/// in parsing, or it can be combined with other `SwiftProtobuf.SimpleExtensionMap`s to create\n",
"/// a larger `SwiftProtobuf.SimpleExtensionMap`.\n",
"\(generatorOptions.visibilitySourceSnippet)let \(filePrefix)\(filenameAsIdentifer)_Extensions: SwiftProtobuf.SimpleExtensionMap = [\n")
p.indent()
var separator = ""
for e in extensions {
p.print(separator, e.swiftFullExtensionName)
separator = ",\n"
}
p.print("\n")
p.outdent()
p.print("]\n")
}
func generateProtobufExtensionDeclarations(printer p: inout CodePrinter) {
guard !extensions.isEmpty else { return }
func endScope() {
p.outdent()
p.print("}\n")
p.outdent()
p.print("}\n")
}
var currentScope: Descriptor? = nil
var addNewline = true
for e in extensions {
if currentScope !== e.fieldDescriptor.extensionScope {
if currentScope != nil { endScope() }
currentScope = e.fieldDescriptor.extensionScope
let scopeSwiftFullName = namer.fullName(message: currentScope!)
p.print(
"\n",
"extension \(scopeSwiftFullName) {\n")
p.indent()
p.print("enum Extensions {\n")
p.indent()
addNewline = false
}
if addNewline {
p.print("\n")
} else {
addNewline = true
}
e.generateProtobufExtensionDeclarations(printer: &p)
}
if currentScope != nil { endScope() }
}
}
| gpl-3.0 | 901644582097bc4a78ae6ffac3713c63 | 39.348659 | 164 | 0.599088 | 5.26024 | false | false | false | false |
caobo56/Juyou | JuYou/JuYou/ThirdParty/CyclePictureView/CyclePictureCell.swift | 1 | 3698 | //
// CyclePictureCell.swift
// CyclePictureView
//
// Created by wl on 15/11/7.
// Copyright © 2015年 wl. All rights reserved.
//
/***************************************************
* 如果您发现任何BUG,或者有更好的建议或者意见,欢迎您的指出。
*邮箱:[email protected].感谢您的支持
***************************************************/
import UIKit
import SDWebImage
class CyclePictureCell: UICollectionViewCell {
var imageSource: ImageSource = ImageSource.Local(name: ""){
didSet {
switch imageSource {
case let .Local(name):
self.imageView.image = UIImage(named: name)
case let .Network(urlStr):
let encodeString = urlStr.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
self.imageView.sd_setImageWithURL(NSURL(string: encodeString)!, placeholderImage: placeholderImage)
}
}
}
var placeholderImage: UIImage?
var imageDetail: String? {
didSet {
detailLable.hidden = false
detailLable.text = imageDetail
}
}
var detailLableTextFont: UIFont = UIFont(name: "Helvetica-Bold", size: 18)! {
didSet {
detailLable.font = detailLableTextFont
}
}
var detailLableTextColor: UIColor = UIColor.whiteColor() {
didSet {
detailLable.textColor = detailLableTextColor
}
}
var detailLableBackgroundColor: UIColor = UIColor.clearColor() {
didSet {
detailLable.backgroundColor = detailLableBackgroundColor
}
}
var detailLableHeight: CGFloat = 60 {
didSet {
detailLable.frame.size.height = detailLableHeight
}
}
var detailLableAlpha: CGFloat = 1 {
didSet {
detailLable.alpha = detailLableAlpha
}
}
var pictureContentMode: UIViewContentMode = .ScaleAspectFill {
didSet {
imageView.contentMode = pictureContentMode
}
}
private var imageView: UIImageView!
private var detailLable: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
self.setupImageView()
self.setupDetailLable()
// self.backgroundColor = UIColor.grayColor()
}
private func setupImageView() {
imageView = UIImageView()
imageView.contentMode = pictureContentMode
imageView.clipsToBounds = true
self.addSubview(imageView)
}
private func setupDetailLable() {
detailLable = UILabel()
detailLable.textColor = detailLableTextColor
detailLable.shadowColor = UIColor.grayColor()
detailLable.numberOfLines = 0
detailLable.backgroundColor = detailLableBackgroundColor
detailLable.hidden = true //默认是没有描述的,所以隐藏它
self.addSubview(detailLable!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = self.bounds
if let _ = self.imageDetail {
let lableX: CGFloat = 0
let lableH: CGFloat = detailLableHeight
let lableW: CGFloat = self.frame.width - lableX
let lableY: CGFloat = self.frame.height - lableH
detailLable.frame = CGRectMake(lableX, lableY, lableW, lableH)
detailLable.font = detailLableTextFont
}
}
}
| apache-2.0 | 97872d981cac82bb0ea01fe6eb5bbc6b | 28.008065 | 139 | 0.588546 | 5.24344 | false | false | false | false |
chinaljw/PhotoBrowser | PhotoBrowser/PhotoBrowser/Controller/PhotoBrowser+Indicator.swift | 13 | 908 | //
// PhotoBrowser+Indicator.swift
// PhotoBrowser
//
// Created by 冯成林 on 15/8/13.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import UIKit
extension PhotoBrowser{
/** pagecontrol准备 */
func pagecontrolPrepare(){
if !hideMsgForZoomAndDismissWithSingleTap {return}
view.addSubview(pagecontrol)
pagecontrol.make_bottomInsets_bottomHeight(left: 0, bottom: 0, right: 0, bottomHeight: 37)
pagecontrol.numberOfPages = photoModels.count
pagecontrol.enabled = false
}
/** pageControl页面变动 */
func pageControlPageChanged(page: Int){
if page<0 || page>=photoModels.count {return}
if showType == PhotoBrowser.ShowType.ZoomAndDismissWithSingleTap && hideMsgForZoomAndDismissWithSingleTap{
pagecontrol.currentPage = page
}
}
}
| mit | 86492f191cbf3ccf246b7e086b4a43b8 | 24.941176 | 114 | 0.639456 | 4.366337 | false | false | false | false |
AndyQ/CNCPlotter | CNCPlotter/StringExt.swift | 1 | 1556 | //
// StringExt.swift
// CNCPlotter
//
// Created by Andy Qua on 02/01/2017.
// Copyright © 2017 Andy Qua. All rights reserved.
//
import Cocoa
/*
extension String {
func index(from: Int) -> Index {
return self.index(startIndex, offsetBy: from)
}
func substring(from: Int) -> String {
let fromIndex = index(from: from)
return substring(from: fromIndex)
}
func substring(to: Int) -> String {
let toIndex = index(from: to)
return substring(to: toIndex)
}
func substring(with r: Range<Int>) -> String {
let startIndex = index(from: r.lowerBound)
let endIndex = index(from: r.upperBound)
return substring(with: startIndex..<endIndex)
}
}
*/
extension String {
var length: Int {
return self.characters.count
}
subscript (i: Int) -> String {
return self[Range(i ..< i + 1)]
}
func substring(from: Int) -> String {
return self[Range(min(from, length) ..< length)]
}
func substring(to: Int) -> String {
return self[Range(0 ..< max(0, to))]
}
subscript (r: Range<Int>) -> String {
let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)),
upper: min(length, max(0, r.upperBound))))
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(start, offsetBy: range.upperBound - range.lowerBound)
return self[Range(start ..< end)]
}
}
| apache-2.0 | f9902a9be964767e367f185d5422e77a | 24.491803 | 86 | 0.565916 | 3.916877 | false | false | false | false |
jigneshsheth/Datastructures | DataStructure/DataStructureTests/Stack/StackChallengeTestCase.swift | 1 | 881 | //
// StackChallengeTestCase.swift
// DataStructureTests
//
// Created by Jigs Sheth on 11/13/21.
// Copyright © 2021 jigneshsheth.com. All rights reserved.
//
import XCTest
@testable import DataStructure
func checkParentheses(_ string: String) -> Bool {
var stack = Stack<Character>()
for char in string {
if char == "(" {
stack.push(char)
} else if char == ")" {
if stack.isEmpty{
return false
} else {
stack.pop()
}
}
}
return stack.isEmpty
}
final class StackChallengeTestCase: XCTestCase {
func test_checkParens() {
XCTAssertTrue( checkParentheses("()") )
}
func test_checkParens1() {
XCTAssertTrue( checkParentheses("hello(world)()") )
}
func test_checkParens2() {
XCTAssertFalse( checkParentheses("(hello world") )
}
func test_checkParens3() {
XCTAssertFalse( checkParentheses("((())(meow)))()))") )
}
}
| mit | d65e2ae43e4f34292d763257307abed3 | 18.130435 | 60 | 0.653409 | 3.271375 | false | true | false | false |
MakeBetterMe/PonyFrameworkOnSwift | PonyFrameworkOnSwift/Extensions/UIDevice+/UIDevice+Add.swift | 1 | 2755 | //
// UIDevice+Add.swift
// SwiftProject
//
// Created by 王云鹏 on 16/3/4.
// Copyright © 2016年 王涛. All rights reserved.
//
import Foundation
public enum DeviceType: Int
{
case DT_UNKNOWN = 0
case DT_iPhone4S //iPhone4S、iPhone4
case DT_iPhone5 //iPhone5、iPhone5C和iPhone5S
case DT_iPhone6 //iPhone6
case DT_iPhone6_Plus //iPhone6 Plus
case DT_iPad //iPad1、iPad2
case DT_iPad_Mini //iPad mini1
case DT_iPad_Retina //New iPad、iPad4和iPad Air
case DT_iPad_Mini_Retina //iPad mini2
}
public extension UIDevice{
static var deviceType:DeviceType{
get {
if let size = UIScreen.mainScreen().currentMode?.size{
switch size{
case CGSizeMake(640 , 960 ) : return .DT_iPhone4S
case CGSizeMake(640 , 1136) : return .DT_iPhone5
case CGSizeMake(750 , 1334) : return .DT_iPhone6
case CGSizeMake(1242, 2208) : return .DT_iPhone6_Plus
case CGSizeMake(1024, 768 ) : return .DT_iPad
case CGSizeMake(768 , 1024) : return .DT_iPad_Mini
case CGSizeMake(2048, 1536) : return .DT_iPad_Retina
case CGSizeMake(1536, 2048) : return .DT_iPad_Mini_Retina
default : return .DT_UNKNOWN
}
}
return .DT_UNKNOWN
}
}
/**
判断当前设备是不是iPhone设备
*/
class func isPhone() -> Bool {
return UIDevice.currentDevice().userInterfaceIdiom == .Phone
}
/**
判断当前设备是不是iPad设备
*/
class func isPad() -> Bool {
return UIDevice.currentDevice().userInterfaceIdiom == .Pad
}
/**
判断当前设备是不是iPad mini
*/
class func isPadMini() -> Bool {
if isPad() {
let type = deviceType
if type == .DT_iPad_Mini || type == .DT_iPad_Mini_Retina {
return true
}
}
return false
}
/**
判断当前设备是不是iPad设备,不包括iPad mini
*/
class func isBigPad() -> Bool {
if isPad() && isPadMini() == false {
return true
}
return false
}
/**
判断当前设备的系统版本是否大于或者等于#version
*/
func isGE(version version: String) -> Bool {
return compare(version: version) != .OrderedAscending
}
func compare(version version: String) -> NSComparisonResult {
return UIDevice.currentDevice().systemVersion.compare(version, options: NSStringCompareOptions.NumericSearch)
}
} | mit | ea1230bb39fc7f276045b49e60115579 | 26.09375 | 117 | 0.547692 | 4.241436 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.