repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
yaobanglin/viossvc | refs/heads/master | viossvc/Scenes/Chat/ChatLocation/GetLocationInfoViewController.swift | apache-2.0 | 1 | //
// GetLocationInfoViewController.swift
// TestAdress
//
// Created by J-bb on 16/12/28.
// Copyright © 2016年 J-bb. All rights reserved.
//
import UIKit
protocol SendLocationMessageDelegate:NSObjectProtocol {
func sendLocation(poiModel:POIInfoModel?)
}
class GetLocationInfoViewController: UIViewController {
var isFirst = true
var annotation:MAPointAnnotation?
var poiArray = Array<POIInfoModel>()
var selectIndex = 0
var centerPOIModel:POIInfoModel?
var city:String?
weak var delegate:SendLocationMessageDelegate?
weak var mapView:MAMapView?
lazy var searchManager:AMapSearchAPI = {
let searchAPI = AMapSearchAPI()
searchAPI.delegate = self
return searchAPI
}()
lazy var geocoder:CLGeocoder = {
let geocoder = CLGeocoder()
return geocoder
}()
lazy var tableView:UITableView = {
let tableView = UITableView(frame: CGRectZero, style: .Plain)
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = 50
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
title = "位置"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Done, target: self, action: #selector(GetLocationInfoViewController.sendLocation))
view.addSubview(tableView)
tableView.snp_makeConstraints { (make) in
make.edges.equalTo(view)
}
tableView.backgroundColor = UIColor(red: 242 / 255.0, green: 242 / 255.0, blue: 242 / 255.0, alpha: 1.0)
tableView.registerClass(ChatLocationAnotherCell.self, forCellReuseIdentifier: "POIInfoCell")
tableView.registerClass(ChatLocationMeCell.self, forCellReuseIdentifier: "meCell")
tableView.registerClass(POIInfoCell.self, forCellReuseIdentifier: "poi")
tableView.registerClass(ShowMapHeaderView.self, forHeaderFooterViewReuseIdentifier: "header")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if CLLocationManager.locationServicesEnabled() == false || CLLocationManager.authorizationStatus() != .AuthorizedWhenInUse {
let alert = UIAlertController.init(title: "提示", message: "无法获取您的位置信息。请到手机系统的[设置]->[隐私]->[定位服务]中打开定位服务,并允许优悦助理使用定位服务", preferredStyle: .Alert)
let goto = UIAlertAction.init(title: "确定", style: .Default, handler: { (action) in
self.navigationController?.popViewControllerAnimated(true)
})
alert.addAction(goto)
presentViewController(alert, animated: true, completion: {})
}
}
func sendLocation() {
navigationController?.popViewControllerAnimated(true)
guard delegate != nil else {return}
delegate?.sendLocation(centerPOIModel)
}
}
extension GetLocationInfoViewController:UITableViewDataSource, UITableViewDelegate,ShowSearchVCDelegate, SelectPoiDelegate{
func selectPOI(poi: POIInfoModel) {
mapView?.removeAnnotation(annotation)
let coordinate = CLLocationCoordinate2D(latitude: poi.latiude, longitude: poi.longtiude)
addAnnotationWithCoordinate(coordinate)
mapView?.centerCoordinate = coordinate
getInfoWithLocation(CLLocation(latitude: poi.latiude, longitude: poi.longtiude))
}
func showSearchVC() {
let searchVC = SearchListViewController()
searchVC.delegate = self
searchVC.city = city
searchVC.modalTransitionStyle = .CrossDissolve
presentViewController(searchVC, animated: true, completion: nil)
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectModel = poiArray[selectIndex]
selectModel.isSelect = false
let willSelectModel = poiArray[indexPath.row]
willSelectModel.isSelect = true
centerPOIModel = willSelectModel
tableView.reloadRowsAtIndexPaths([NSIndexPath.init(forRow: selectIndex, inSection: 0), NSIndexPath.init(forRow: indexPath.row, inSection: 0)], withRowAnimation: .None)
selectIndex = indexPath.row
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier("header") as! ShowMapHeaderView
mapView = headerView.mapView
mapView?.delegate = self
headerView.delegate = self
return headerView
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 255
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return poiArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let model = poiArray[indexPath.row]
let poiCell = tableView.dequeueReusableCellWithIdentifier("poi", forIndexPath: indexPath) as! POIInfoCell
poiCell.setDataWithModel(model)
return poiCell
}
}
extension GetLocationInfoViewController:MAMapViewDelegate, AMapSearchDelegate{
func addCenterAnnotation() {
selectIndex = 0
mapView!.removeAnnotation(annotation)
addAnnotationWithCoordinate(mapView!.centerCoordinate)
}
func addAnnotationWithCoordinate(coordinate:CLLocationCoordinate2D) {
annotation = MAPointAnnotation()
annotation!.coordinate = coordinate
mapView!.addAnnotations([annotation!])
}
func mapView(mapView: MAMapView!, mapDidMoveByUser wasUserAction: Bool) {
guard wasUserAction == true else {return}
addCenterAnnotation()
getInfoWithLocation(CLLocation(latitude: mapView.centerCoordinate.latitude, longitude: mapView.centerCoordinate.longitude))
}
func mapView(mapView: MAMapView!, viewForAnnotation annotation: MAAnnotation!) -> MAAnnotationView! {
if annotation.coordinate.latitude == mapView.centerCoordinate.latitude && annotation.coordinate.longitude == mapView.centerCoordinate.longitude {
let identifier = "center"
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)
if annotationView == nil {
annotationView = MAAnnotationView(annotation: annotation, reuseIdentifier: identifier)
}
annotationView.image = UIImage(named: "chat_location")
return annotationView
}
return nil
}
internal func mapView(mapView: MAMapView!, didUpdateUserLocation userLocation: MAUserLocation!, updatingLocation: Bool) {
if userLocation.location != nil {
if isFirst {
mapView?.setZoomLevel(12, animated: false)
mapView.centerCoordinate = userLocation.coordinate
addCenterAnnotation()
getInfoWithLocation(userLocation.location)
isFirst = false
}
}
}
func getLocationWithCoordinate(coordinate:CLLocationCoordinate2D) -> CLLocation? {
return nil
}
func getInfoWithLocation(location:CLLocation) {
geocoder.reverseGeocodeLocation(location) { (placeMarks: [CLPlacemark]?, err: NSError?) in
guard placeMarks?.count > 0 else {return}
for placeMark in placeMarks! {
print("name == \(placeMark.name)\n")
self.city = placeMark.locality
let poiModel = POIInfoModel()
poiModel.latiude = location.coordinate.latitude
poiModel.longtiude = location.coordinate.longitude
poiModel.name = placeMark.name
poiModel.isSelect = true
poiModel.detail = placeMark.locality! + placeMark.name!
self.centerPOIModel = poiModel
self.getPOIInfosWithLocation(location)
}
}
}
func getPOIInfosWithLocation(location:CLLocation){
let request = AMapPOIAroundSearchRequest()
let currentLocation = AMapGeoPoint()
currentLocation.latitude = CGFloat(location.coordinate.latitude)
currentLocation.longitude = CGFloat(location.coordinate.longitude)
request.location = currentLocation
request.radius = 500
request.types = "风景名胜|公司企业|交通设施服务"
searchManager.AMapPOIAroundSearch(request)
}
func AMapSearchRequest(request: AnyObject!, didFailWithError error: NSError!) {
//搜索附近POI出错
}
func onPOISearchDone(request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) {
poiArray.removeAll()
for poi in response.pois {
let poiModel = POIInfoModel()
poiModel.name = poi.name
poiModel.detail = poi.address
poiModel.latiude = Double(poi.location.latitude)
poiModel.longtiude = Double(poi.location.longitude)
poiArray.append(poiModel)
}
poiArray.insert(centerPOIModel!, atIndex: 0)
tableView.reloadData()
}
}
| baabab08c281644579b81920c7d5abfa | 35.81323 | 175 | 0.659444 | false | false | false | false |
danpratt/Simply-Zen | refs/heads/master | Simply Zen/Model/GuidedMeditationsExtension.swift | apache-2.0 | 1 | //
// GuidedMeditationsExtension.swift
// Simply Zen
//
// Created by Daniel Pratt on 5/25/17.
// Copyright © 2017 Daniel Pratt. All rights reserved.
//
import Foundation
// MARK: - SZCourse Extension for Guided Meditations
enum GuidedMeditationCourses: String {
case Heart = "Heart Meditation Course"
case Beginning = "Beginning Zen Course"
case Advanced = "Advanced Breathing Course"
case Relax = "Learning to Relax Course"
case LettingGo = "Learning to Let Go"
}
extension SZCourse {
// MARK: - Heart Meditation Course
static func heartMeditationCourse() -> SZCourse {
// create the lessons for the course
var heartLessons = [SZLesson]()
let intro = SZLesson(addLesson: "Intro to Heart Meditation", withFilename: "Intro to Heart meditation", level: 0, durationInSeconds: 104)
let openToYourself = SZLesson(addLesson: "Opening Your Heart to Yourself", withFilename: "Opening Your Heart to Yourself", level: 1, durationInSeconds: 379)
let openToOthers = SZLesson(addLesson: "Opening Your Heart to Others", withFilename: "Opening Your Heart to Others", level: 2, durationInSeconds: 418)
let openToDifficult = SZLesson(addLesson: "Opening Your Heart to a Difficult Person", withFilename: "Opening Your Heart to Difficult People", level: 3, durationInSeconds: 487)
let openToAll = SZLesson(addLesson: "Opening Your Heart to the Universe", withFilename: "Opening Your Heart to the Universe", level: 4, durationInSeconds: 626)
let innerLight = SZLesson(addLesson: "Inner Light Meditation", withFilename: "Inner Light Meditation", level: 5, durationInSeconds: 617)
// add lessons
heartLessons.append(intro)
heartLessons.append(openToYourself)
heartLessons.append(openToOthers)
heartLessons.append(openToDifficult)
heartLessons.append(openToAll)
heartLessons.append(innerLight)
return SZCourse(named: "Heart Meditation Course", withlessons: heartLessons)
}
// MARK: - Beginning Zen Course
static func beginningZenCourse() -> SZCourse {
// create the lessons for the course
var beginningZenLessons = [SZLesson]()
let intro = SZLesson(addLesson: "Intro to Meditation", withFilename: "Intro to Meditation", level: 0, durationInSeconds: 108)
let learnToBreath = SZLesson(addLesson: "Learning to Breath", withFilename: "Learning to Breath", level: 1, durationInSeconds: 227)
let distractions = SZLesson(addLesson: "Dealing with Distractions", withFilename: "Dealing with Distractions", level: 2, durationInSeconds: 290)
let deeperBreathAwareness = SZLesson(addLesson: "Deeper Breath Awareness", withFilename: "Deeper Breath Awareness", level: 3, durationInSeconds: 339)
let bodyAwareness = SZLesson(addLesson: "Becoming Aware of Your Body", withFilename: "Becoming Aware of Your Body", level: 4, durationInSeconds: 317)
let fullSession = SZLesson(addLesson: "Full Meditation Session", withFilename: "Full Meditation Session", level: 5, durationInSeconds: 376)
// add lessons
beginningZenLessons.append(intro)
beginningZenLessons.append(learnToBreath)
beginningZenLessons.append(distractions)
beginningZenLessons.append(deeperBreathAwareness)
beginningZenLessons.append(bodyAwareness)
beginningZenLessons.append(fullSession)
return SZCourse(named: "Beginning Zen Course", withlessons: beginningZenLessons)
}
// MARK: - Advanced Breathing Course
static func advancedBreathingCourse() -> SZCourse {
// create the lessons for the course
var advancedBreathingLessons = [SZLesson]()
let intro = SZLesson(addLesson: "Intro to Advanced Breathing", withFilename: "Intro to Advanced Breathing", level: 0, durationInSeconds: 116)
let findingFocus = SZLesson(addLesson: "Finding Your Focus", withFilename: "Finding Your Focus", level: 1, durationInSeconds: 351)
let fullBreathAwareness = SZLesson(addLesson: "Full Breath Awareness", withFilename: "Full Breath Awareness", level: 2, durationInSeconds: 373)
let returningToBreath = SZLesson(addLesson: "Returning to the Breath", withFilename: "Returning to the Breath", level: 3, durationInSeconds: 446)
let beingKind = SZLesson(addLesson: "Being Kind", withFilename: "Being Kind", level: 4, durationInSeconds: 554)
let fullSession = SZLesson(addLesson: "Full Breath Session", withFilename: "Full Breath Session", level: 5, durationInSeconds: 629)
// add lessons
advancedBreathingLessons.append(intro)
advancedBreathingLessons.append(findingFocus)
advancedBreathingLessons.append(fullBreathAwareness)
advancedBreathingLessons.append(returningToBreath)
advancedBreathingLessons.append(beingKind)
advancedBreathingLessons.append(fullSession)
return SZCourse(named: "Advanced Breathing Course", withlessons: advancedBreathingLessons)
}
// MARK: - Learning to Relax Course
static func relaxCourse() -> SZCourse {
// create the lessons for the course
var relaxLessons = [SZLesson]()
let intro = SZLesson(addLesson: "Intro to Relaxing with Meditation", withFilename: "Intro to Relaxing with Meditation", level: 0, durationInSeconds: 60)
let breathing = SZLesson(addLesson: "Breathing While Lying Down", withFilename: "Breathing While Lying Down", level: 1, durationInSeconds: 358)
let learningToVisualize = SZLesson(addLesson: "Learning to Visualize", withFilename: "Learning to Visualize", level: 2, durationInSeconds: 422)
let warmingYourBody = SZLesson(addLesson: "Warming Your Body", withFilename: "Warming Your Body", level: 3, durationInSeconds: 317)
let fillingWithSand = SZLesson(addLesson: "Filling With Sand", withFilename: "Filling With Sand", level: 4, durationInSeconds: 337)
let fullSession = SZLesson(addLesson: "Fully Relax", withFilename: "Fully Relax", level: 5, durationInSeconds: 440)
// add lessons
relaxLessons.append(intro)
relaxLessons.append(breathing)
relaxLessons.append(learningToVisualize)
relaxLessons.append(warmingYourBody)
relaxLessons.append(fillingWithSand)
relaxLessons.append(fullSession)
return SZCourse(named: "Learning to Relax Course", withlessons: relaxLessons)
}
// MARK: - Learning to let Go Course
static func lettingGoCourse() -> SZCourse {
// create the lessons for the course
var lettingGoLessons = [SZLesson]()
let intro = SZLesson(addLesson: "Intro to Letting Go with Meditation", withFilename: "Intro to Letting Go with Meditation", level: 0, durationInSeconds: 95)
let lovingYourself = SZLesson(addLesson: "Loving Yourself", withFilename: "Loving Yourself", level: 1, durationInSeconds: 372)
let indentifyingHurt = SZLesson(addLesson: "Identifying Hurt", withFilename: "Identifying Hurt", level: 2, durationInSeconds: 398)
let rejectNegativity = SZLesson(addLesson: "Rejecting Negativity", withFilename: "Rejecting Negativity", level: 3, durationInSeconds: 468)
let lettingGo = SZLesson(addLesson: "Letting Go", withFilename: "Letting Go", level: 4, durationInSeconds: 370)
let fullSession = SZLesson(addLesson: "Full Session", withFilename: "Full Letting Go Session", level: 5, durationInSeconds: 623)
// add lessons
lettingGoLessons.append(intro)
lettingGoLessons.append(lovingYourself)
lettingGoLessons.append(indentifyingHurt)
lettingGoLessons.append(rejectNegativity)
lettingGoLessons.append(lettingGo)
lettingGoLessons.append(fullSession)
return SZCourse(named: "Learning to Let Go", withlessons: lettingGoLessons)
}
}
| f7396fc606caa4d5793500353647ea39 | 58.729323 | 183 | 0.711229 | false | false | false | false |
SwiftAndroid/swift | refs/heads/master | stdlib/public/Platform/Platform.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
//===----------------------------------------------------------------------===//
// MacTypes.h
//===----------------------------------------------------------------------===//
public var noErr: OSStatus { return 0 }
/// The `Boolean` type declared in MacTypes.h and used throughout Core
/// Foundation.
///
/// The C type is a typedef for `unsigned char`.
@_fixed_layout
public struct DarwinBoolean : Boolean, BooleanLiteralConvertible {
var _value: UInt8
public init(_ value: Bool) {
self._value = value ? 1 : 0
}
/// The value of `self`, expressed as a `Bool`.
public var boolValue: Bool {
return _value != 0
}
/// Create an instance initialized to `value`.
@_transparent
public init(booleanLiteral value: Bool) {
self.init(value)
}
}
extension DarwinBoolean : CustomReflectable {
/// Returns a mirror that reflects `self`.
public var customMirror: Mirror {
return Mirror(reflecting: boolValue)
}
}
extension DarwinBoolean : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return self.boolValue.description
}
}
extension DarwinBoolean : Equatable {}
@warn_unused_result
public func ==(lhs: DarwinBoolean, rhs: DarwinBoolean) -> Bool {
return lhs.boolValue == rhs.boolValue
}
@warn_unused_result
public // COMPILER_INTRINSIC
func _convertBoolToDarwinBoolean(_ x: Bool) -> DarwinBoolean {
return DarwinBoolean(x)
}
@warn_unused_result
public // COMPILER_INTRINSIC
func _convertDarwinBooleanToBool(_ x: DarwinBoolean) -> Bool {
return Bool(x)
}
// FIXME: We can't make the fully-generic versions @_transparent due to
// rdar://problem/19418937, so here are some @_transparent overloads
// for DarwinBoolean.
@_transparent
@warn_unused_result
public func && <T : Boolean>(
lhs: T,
@autoclosure rhs: () -> DarwinBoolean
) -> Bool {
return lhs.boolValue ? rhs().boolValue : false
}
@_transparent
@warn_unused_result
public func || <T : Boolean>(
lhs: T,
@autoclosure rhs: () -> DarwinBoolean
) -> Bool {
return lhs.boolValue ? true : rhs().boolValue
}
#endif
//===----------------------------------------------------------------------===//
// sys/errno.h
//===----------------------------------------------------------------------===//
public var errno : Int32 {
get {
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD)
return __error().pointee
#elseif os(Android)
return __errno().pointee
#else
return __errno_location().pointee
#endif
}
set(val) {
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD)
return __error().pointee = val
#elseif os(Android)
return __errno().pointee = val
#else
return __errno_location().pointee = val
#endif
}
}
//===----------------------------------------------------------------------===//
// stdio.h
//===----------------------------------------------------------------------===//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD)
public var stdin : UnsafeMutablePointer<FILE> {
get {
return __stdinp
}
set {
__stdinp = newValue
}
}
public var stdout : UnsafeMutablePointer<FILE> {
get {
return __stdoutp
}
set {
__stdoutp = newValue
}
}
public var stderr : UnsafeMutablePointer<FILE> {
get {
return __stderrp
}
set {
__stderrp = newValue
}
}
#endif
//===----------------------------------------------------------------------===//
// fcntl.h
//===----------------------------------------------------------------------===//
@warn_unused_result
@_silgen_name("_swift_Platform_open")
func _swift_Platform_open(
_ path: UnsafePointer<CChar>,
_ oflag: CInt,
_ mode: mode_t
) -> CInt
@warn_unused_result
@_silgen_name("_swift_Platform_openat")
func _swift_Platform_openat(
_ fd: CInt,
_ path: UnsafePointer<CChar>,
_ oflag: CInt,
_ mode: mode_t
) -> CInt
@warn_unused_result
public func open(
_ path: UnsafePointer<CChar>,
_ oflag: CInt
) -> CInt {
return _swift_Platform_open(path, oflag, 0)
}
@warn_unused_result
public func open(
_ path: UnsafePointer<CChar>,
_ oflag: CInt,
_ mode: mode_t
) -> CInt {
return _swift_Platform_open(path, oflag, mode)
}
@warn_unused_result
public func openat(
_ fd: CInt,
_ path: UnsafePointer<CChar>,
_ oflag: CInt
) -> CInt {
return _swift_Platform_openat(fd, path, oflag, 0)
}
@warn_unused_result
public func openat(
_ fd: CInt,
_ path: UnsafePointer<CChar>,
_ oflag: CInt,
_ mode: mode_t
) -> CInt {
return _swift_Platform_openat(fd, path, oflag, mode)
}
@warn_unused_result
@_silgen_name("_swift_Platform_fcntl")
internal func _swift_Platform_fcntl(
_ fd: CInt,
_ cmd: CInt,
_ value: CInt
) -> CInt
@warn_unused_result
@_silgen_name("_swift_Platform_fcntlPtr")
internal func _swift_Platform_fcntlPtr(
_ fd: CInt,
_ cmd: CInt,
_ ptr: UnsafeMutablePointer<Void>
) -> CInt
@warn_unused_result
public func fcntl(
_ fd: CInt,
_ cmd: CInt
) -> CInt {
return _swift_Platform_fcntl(fd, cmd, 0)
}
@warn_unused_result
public func fcntl(
_ fd: CInt,
_ cmd: CInt,
_ value: CInt
) -> CInt {
return _swift_Platform_fcntl(fd, cmd, value)
}
@warn_unused_result
public func fcntl(
_ fd: CInt,
_ cmd: CInt,
_ ptr: UnsafeMutablePointer<Void>
) -> CInt {
return _swift_Platform_fcntlPtr(fd, cmd, ptr)
}
public var S_IFMT: mode_t { return mode_t(0o170000) }
public var S_IFIFO: mode_t { return mode_t(0o010000) }
public var S_IFCHR: mode_t { return mode_t(0o020000) }
public var S_IFDIR: mode_t { return mode_t(0o040000) }
public var S_IFBLK: mode_t { return mode_t(0o060000) }
public var S_IFREG: mode_t { return mode_t(0o100000) }
public var S_IFLNK: mode_t { return mode_t(0o120000) }
public var S_IFSOCK: mode_t { return mode_t(0o140000) }
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
public var S_IFWHT: mode_t { return mode_t(0o160000) }
#endif
public var S_IRWXU: mode_t { return mode_t(0o000700) }
public var S_IRUSR: mode_t { return mode_t(0o000400) }
public var S_IWUSR: mode_t { return mode_t(0o000200) }
public var S_IXUSR: mode_t { return mode_t(0o000100) }
public var S_IRWXG: mode_t { return mode_t(0o000070) }
public var S_IRGRP: mode_t { return mode_t(0o000040) }
public var S_IWGRP: mode_t { return mode_t(0o000020) }
public var S_IXGRP: mode_t { return mode_t(0o000010) }
public var S_IRWXO: mode_t { return mode_t(0o000007) }
public var S_IROTH: mode_t { return mode_t(0o000004) }
public var S_IWOTH: mode_t { return mode_t(0o000002) }
public var S_IXOTH: mode_t { return mode_t(0o000001) }
public var S_ISUID: mode_t { return mode_t(0o004000) }
public var S_ISGID: mode_t { return mode_t(0o002000) }
public var S_ISVTX: mode_t { return mode_t(0o001000) }
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
public var S_ISTXT: mode_t { return S_ISVTX }
public var S_IREAD: mode_t { return S_IRUSR }
public var S_IWRITE: mode_t { return S_IWUSR }
public var S_IEXEC: mode_t { return S_IXUSR }
#endif
//===----------------------------------------------------------------------===//
// unistd.h
//===----------------------------------------------------------------------===//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
@available(*, unavailable, message: "Please use threads or posix_spawn*()")
public func fork() -> Int32 {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "Please use threads or posix_spawn*()")
public func vfork() -> Int32 {
fatalError("unavailable function can't be called")
}
#endif
//===----------------------------------------------------------------------===//
// signal.h
//===----------------------------------------------------------------------===//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
public var SIG_DFL: sig_t? { return nil }
public var SIG_IGN: sig_t { return unsafeBitCast(1, to: sig_t.self) }
public var SIG_ERR: sig_t { return unsafeBitCast(-1, to: sig_t.self) }
public var SIG_HOLD: sig_t { return unsafeBitCast(5, to: sig_t.self) }
#elseif os(Linux) || os(FreeBSD) || os(Android)
public typealias sighandler_t = __sighandler_t
public var SIG_DFL: sighandler_t? { return nil }
public var SIG_IGN: sighandler_t {
return unsafeBitCast(1, to: sighandler_t.self)
}
public var SIG_ERR: sighandler_t {
return unsafeBitCast(-1, to: sighandler_t.self)
}
public var SIG_HOLD: sighandler_t {
return unsafeBitCast(2, to: sighandler_t.self)
}
#else
internal var _ignore = _UnsupportedPlatformError()
#endif
//===----------------------------------------------------------------------===//
// semaphore.h
//===----------------------------------------------------------------------===//
/// The value returned by `sem_open()` in the case of failure.
public var SEM_FAILED: UnsafeMutablePointer<sem_t>? {
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
// The value is ABI. Value verified to be correct for OS X, iOS, watchOS, tvOS.
return UnsafeMutablePointer<sem_t>(bitPattern: -1)
#elseif os(Linux) || os(FreeBSD) || os(Android)
// The value is ABI. Value verified to be correct on Glibc.
return UnsafeMutablePointer<sem_t>(bitPattern: 0)
#else
_UnsupportedPlatformError()
#endif
}
@warn_unused_result
@_silgen_name("_swift_Platform_sem_open2")
internal func _swift_Platform_sem_open2(
_ name: UnsafePointer<CChar>,
_ oflag: CInt
) -> UnsafeMutablePointer<sem_t>?
@warn_unused_result
@_silgen_name("_swift_Platform_sem_open4")
internal func _swift_Platform_sem_open4(
_ name: UnsafePointer<CChar>,
_ oflag: CInt,
_ mode: mode_t,
_ value: CUnsignedInt
) -> UnsafeMutablePointer<sem_t>?
@warn_unused_result
public func sem_open(
_ name: UnsafePointer<CChar>,
_ oflag: CInt
) -> UnsafeMutablePointer<sem_t>? {
return _swift_Platform_sem_open2(name, oflag)
}
@warn_unused_result
public func sem_open(
_ name: UnsafePointer<CChar>,
_ oflag: CInt,
_ mode: mode_t,
_ value: CUnsignedInt
) -> UnsafeMutablePointer<sem_t>? {
return _swift_Platform_sem_open4(name, oflag, mode, value)
}
//===----------------------------------------------------------------------===//
// Misc.
//===----------------------------------------------------------------------===//
// FreeBSD defines extern char **environ differently than Linux.
#if os(FreeBSD)
@warn_unused_result
@_silgen_name("_swift_FreeBSD_getEnv")
func _swift_FreeBSD_getEnv(
) -> UnsafeMutablePointer<UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>>
public var environ: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> {
return _swift_FreeBSD_getEnv().pointee
}
#endif
| a903c36d11096a198db7bd2e32dc3dd0 | 26.511166 | 82 | 0.591594 | false | false | false | false |
grandiere/box | refs/heads/master | box/Model/Main/MSessionLevelUp.swift | mit | 1 | import Foundation
class MSessionLevelUp
{
private static let kResourceName:String = "ResourceLevels"
private static let kResourceExtension:String = "plist"
class func levelUp()
{
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{
asyncLevelUp()
}
}
private class func asyncLevelUp()
{
guard
let resourceLevels:URL = Bundle.main.url(
forResource:kResourceName,
withExtension:kResourceExtension),
let levelsArray:NSArray = NSArray(
contentsOf:resourceLevels),
let levelsList:[Int] = levelsArray as? [Int]
else
{
return
}
let level:Int = MSession.sharedInstance.level
let score:Int = MSession.sharedInstance.score
let scoreForLevelUp:Int = levelsList[level]
if score >= scoreForLevelUp
{
let maxLevel:Int = Int(DUser.kMaxStats)
if level < maxLevel
{
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{
MSession.sharedInstance.performLevelUp()
let message:String = NSLocalizedString("MSessionLevelUp_levelUp", comment:"")
VToast.messageBlue(message:message)
}
}
else
{
let message:String = NSLocalizedString("MSessionLevelUp_maxLevel", comment:"")
VToast.messageOrange(message:message)
}
}
}
}
| 628ad6605a65c10a79a2a8d29a90b4d6 | 28.403509 | 97 | 0.533413 | false | false | false | false |
coderZsq/coderZsq.target.swift | refs/heads/master | StudyNotes/iOS Collection/Business/Business/iPad/Home/View/iPadMiddleMenuView.swift | mit | 1 | //
// iPadMiddleMenuView.swift
// Business
//
// Created by 朱双泉 on 2018/11/12.
// Copyright © 2018 Castie!. All rights reserved.
//
import UIKit
protocol iPadMiddleMenuViewDelegate {
func dockDidSelect(toIndex: Int)
}
class iPadMiddleMenuView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
addMenus()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var delegate: iPadMiddleMenuViewDelegate?
func addMenus() {
for i in 0..<6 {
let button = iPadMenuButton(type: .system)
button.tintColor = .lightGray
button.setTitle(" CoderZsq - " + "\(i)", for: .normal)
button.setImage(UIImage(named: "Mark"), for: .normal)
button.addTarget(self, action: #selector(menuClick(sender:)), for: .touchDown)
button.tag = subviews.count
addSubview(button)
}
}
@objc
func menuClick(sender: UIButton) {
delegate?.dockDidSelect(toIndex: sender.tag)
}
override func layoutSubviews() {
super.layoutSubviews()
var index: CGFloat = 0
for view in subviews {
view.height = height / CGFloat(subviews.count)
view.width = width
view.left = 0
view.top = view.height * index
index += 1
}
}
}
| 9ad89e1c93e77910bf260e1a896f6520 | 24.625 | 90 | 0.577003 | false | false | false | false |
suvov/VSStoreKit | refs/heads/master | VSStoreKit/ProductsDataSource.swift | mit | 1 | //
// ProductsDataSource.swift
// VSStoreKit
//
// Created by Vladimir Shutyuk on 07/06/2017.
// Copyright © 2017 Vladimir Shutyuk. All rights reserved.
//
import Foundation
/// A `ProductsDataSource` is responsible for providing actual products data, given `LocalProductsDataSource` and `StoreProductsDataSource` objects.
public class ProductsDataSource {
private let localProducts: LocalProductsDataSource
private let storeProducts: StoreProductsDataSource
/**
Initializes a new products data source.
- parameter localProducts: `LocalProductsDataSource` object.
- parameter storeProducts: `StoreProductsDataSource` object.
- returns: A new `ProductsDataSource` instance.
*/
public init(localProducts: LocalProductsDataSource, storeProducts: StoreProductsDataSource) {
self.localProducts = localProducts
self.storeProducts = storeProducts
}
/// The number of products.
public var numProducts: Int {
return localProducts.productsCount
}
/**
Localized name for product at index. If products received from the store, returns localized name received from the store, otherwise returns name of corresponding local product, localized with NSLocalizedString macro.
- parameter index: An index of product in the data source.
- returns: Localized name for product on specified index.
*/
public func localizedNameForProductAtIndex(_ index: Int) -> String {
let productIdentifier = localProducts.identifierForProductAtIndex(index)
if storeProducts.productsReceived, let name = storeProducts.localizedNameForProductWithIdentifier(productIdentifier) {
return name
} else {
return NSLocalizedString(localProducts.nameForProductAtIndex(index), comment: "")
}
}
/**
Localized description for product at index. If products received from the store, returns localized description received from the store, otherwise returns description of corresponding local product, localized with NSLocalizedString macro.
- parameter index: An index of product in the data source.
- returns: Localized description for product on specified index.
*/
public func localizedDescriptionForProductAtIndex(_ index: Int) -> String {
let productIdentifier = localProducts.identifierForProductAtIndex(index)
if storeProducts.productsReceived, let description = storeProducts.localizedDescriptionForProductWithIdentifier(productIdentifier) {
return description
} else {
return NSLocalizedString(localProducts.descriptionForProductAtIndex(index), comment: "")
}
}
/**
Localized price for product at index. If products received from the store, returns localized price received from the store, otherwise returns nil.
- parameter index: An index of product in the data source.
- returns: Localized price for product on specified index.
*/
public func localizedPriceForProductAtIndex(_ index: Int) -> String? {
let productIdentifier = localProducts.identifierForProductAtIndex(index)
if storeProducts.productsReceived, let price = storeProducts.localizedPriceForProductWithIdentifier(productIdentifier) {
return price
}
return nil
}
/**
- parameter index: An index of product in the data source.
- returns: Identifier for product on specified index.
*/
public func identifierForProductAtIndex(_ index: Int) -> String {
return localProducts.identifierForProductAtIndex(index)
}
}
| 43c2008e5e743cb143ea87c1f989a4e1 | 39.966667 | 242 | 0.714131 | false | false | false | false |
hanjoes/Smashtag | refs/heads/master | Smashtag/TweetTableViewCell.swift | mit | 1 | //
// TweetTableViewCell.swift
// Smashtag
//
// Created by Hanzhou Shi on 1/5/16.
// Copyright © 2016 USF. All rights reserved.
//
import UIKit
class TweetTableViewCell: UITableViewCell {
@IBOutlet weak var tweetProfileImageView: UIImageView!
@IBOutlet weak var tweetScreenNameLabel: UILabel!
@IBOutlet weak var tweetTextLabel: UILabel!
@IBOutlet weak var tweetTimeLabel: UILabel!
var tweet: Tweet? {
didSet {
updateUI()
}
}
func updateUI() {
// reset any existing tweet information
tweetTextLabel?.attributedText = nil
tweetScreenNameLabel?.text = nil
tweetProfileImageView?.image = nil
// tweetCreatedLabel?.text = nil
// load new information from our tweet (if any)
if let tweet = self.tweet {
tweetTextLabel?.text = tweet.text
if tweetTextLabel?.text != nil {
// highlight mentions
let mutableAttributedString = NSMutableAttributedString(attributedString: tweetTextLabel.attributedText!)
let attributesForUrl = [NSForegroundColorAttributeName: UIColor.darkGrayColor(),
NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]
let _ = tweet.urls.map({ (kw) -> Void in
mutableAttributedString.addAttributes(attributesForUrl, range: kw.nsrange!)
})
let attributesForHashTags = [NSForegroundColorAttributeName: UIColor.blueColor(),
NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]
let _ = tweet.hashtags.map({ (kw) -> Void in
mutableAttributedString.addAttributes(attributesForHashTags, range: kw.nsrange!)
})
let attributesForMentions = [NSForegroundColorAttributeName: UIColor.orangeColor()]
let _ = tweet.userMentions.map({ (kw) -> Void in
mutableAttributedString.addAttributes(attributesForMentions, range: kw.nsrange!)
})
tweetTextLabel.attributedText = mutableAttributedString
for _ in tweet.media {
tweetTextLabel.text! += " 📷"
}
}
tweetScreenNameLabel?.text = "\(tweet.user)"
if let profileImageURL = tweet.user.profileImageURL {
if let imageData = NSData(contentsOfURL: profileImageURL) {
// blocks main thread!!
tweetProfileImageView?.image = UIImage(data: imageData)
}
}
let formatter = NSDateFormatter()
if NSDate().timeIntervalSinceDate(tweet.created) > 24*60*60 {
formatter.dateStyle = NSDateFormatterStyle.ShortStyle
}
else {
formatter.timeStyle = NSDateFormatterStyle.ShortStyle
}
tweetTimeLabel?.text = formatter.stringFromDate(tweet.created)
}
}
}
| d1ca6f9bc5ab2036d0196ec04f184ed2 | 39.441558 | 121 | 0.585421 | false | false | false | false |
mihyaeru21/RxTwift | refs/heads/master | Example/Tests/CryptoSpec.swift | mit | 1 | //
// Crypto.swift
// RxTwift
//
// Created by Mihyaeru on 3/13/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Quick
import Nimble
import RxTwift
class CryptoSpec: QuickSpec {
override func spec() {
describe("sha1") {
it("empty") {
expect(Crypto.sha1("")) == "2jmj7l5rSw0yVb/vlWAYkK/YBwk="
}
it("example") {
expect(Crypto.sha1("The quick brown fox jumps over the lazy dog")) == "L9ThxnotKPzthJ7hu3bnORuT6xI="
expect(Crypto.sha1("The quick brown fox jumps over the lazy cog")) == "3p8sf9JeGzr60+haC9F9mxANtLM="
}
it("long message") {
let message = "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data"
expect(Crypto.sha1(message)) == "trL9zWiHQGvVWtLlwZ4IzPX0ikU="
}
context("border") {
it("message.count == blockSize") {
let message = String(count: 54, repeatedValue: "a" as Character)
expect(Array(message.utf8Array).count) == 54
expect(Crypto.sha1(message)) == "sF1xxkl5y5X6dKM82zGkDSWK4C4="
}
it("message.count == blockSize-1") {
let message = String(count: 55, repeatedValue: "a" as Character)
expect(Array(message.utf8Array).count) == 55
expect(Crypto.sha1(message)) == "wci73CJ5bijA4VFj0giZtlYh1lo="
}
it("message.count == blockSize-1") {
let message = String(count: 56, repeatedValue: "a" as Character)
expect(Array(message.utf8Array).count) == 56
expect(Crypto.sha1(message)) == "wtszD2CDhUyZ1LW/tujynyAb5pk="
}
}
}
describe("hmacSha1") {
it("empty") {
expect(Crypto.hmacSha1(key: "", message: "")) == "+9sdGxiqbAgyS31ktx+3Y3BpDh0="
}
it("string wrapper") {
let key = "key"
let message = "The quick brown fox jumps over the lazy dog"
expect(Crypto.hmacSha1(key: key, message: message)) == "3nybhbi3iqa8ino29wqQcBydtNk="
}
// from https://www.ipa.go.jp/security/rfc/RFC2202JA.html
context("IPA tests") {
it("case 1") {
let key = Array<UInt8>(count: 20, repeatedValue: 0x0b)
let message = "Hi There".utf8Array
let hmac: [UInt8] = [0xb6, 0x17, 0x31, 0x86, 0x55, 0x05, 0x72, 0x64, 0xe2, 0x8b, 0xc0, 0xb6, 0xfb, 0x37, 0x8c, 0x8e, 0xf1, 0x46, 0xbe, 0x00]
expect(Crypto.hmacSha1(key: key, message: message)) == hmac
}
it("case 2") {
let key = "Jefe".utf8Array
let message = "what do ya want for nothing?".utf8Array
let hmac: [UInt8] = [0xef, 0xfc, 0xdf, 0x6a, 0xe5, 0xeb, 0x2f, 0xa2, 0xd2, 0x74, 0x16, 0xd5, 0xf1, 0x84, 0xdf, 0x9c, 0x25, 0x9a, 0x7c, 0x79]
expect(Crypto.hmacSha1(key: key, message: message)) == hmac
}
it("case 3") {
let key = Array<UInt8>(count: 20, repeatedValue: 0xaa)
let message = Array<UInt8>(count: 50, repeatedValue: 0xdd)
let hmac: [UInt8] = [0x12, 0x5d, 0x73, 0x42, 0xb9, 0xac, 0x11, 0xcd, 0x91, 0xa3, 0x9a, 0xf4, 0x8a, 0xa1, 0x7b, 0x4f, 0x63, 0xf1, 0x75, 0xd3]
expect(Crypto.hmacSha1(key: key, message: message)) == hmac
}
it("case 4") {
let key: [UInt8] = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19]
let message = Array<UInt8>(count: 50, repeatedValue: 0xcd)
let hmac: [UInt8] = [0x4c, 0x90, 0x07, 0xf4, 0x02, 0x62, 0x50, 0xc6, 0xbc, 0x84, 0x14, 0xf9, 0xbf, 0x50, 0xc8, 0x6c, 0x2d, 0x72, 0x35, 0xda]
expect(Crypto.hmacSha1(key: key, message: message)) == hmac
}
it("case 5") {
let key = Array<UInt8>(count: 20, repeatedValue: 0x0c)
let message = "Test With Truncation".utf8Array
let hmac: [UInt8] = [0x4c, 0x1a, 0x03, 0x42, 0x4b, 0x55, 0xe0, 0x7f, 0xe7, 0xf2, 0x7b, 0xe1, 0xd5, 0x8b, 0xb9, 0x32, 0x4a, 0x9a, 0x5a, 0x04]
expect(Crypto.hmacSha1(key: key, message: message)) == hmac
}
it("case 6") {
let key = Array<UInt8>(count: 80, repeatedValue: 0xaa)
let message = "Test Using Larger Than Block-Size Key - Hash Key First".utf8Array
let hmac: [UInt8] = [0xaa, 0x4a, 0xe5, 0xe1, 0x52, 0x72, 0xd0, 0x0e, 0x95, 0x70, 0x56, 0x37, 0xce, 0x8a, 0x3b, 0x55, 0xed, 0x40, 0x21, 0x12]
expect(Crypto.hmacSha1(key: key, message: message)) == hmac
}
it("case 7") {
let key = Array<UInt8>(count: 80, repeatedValue: 0xaa)
let message = "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data".utf8Array
let hmac: [UInt8] = [0xe8, 0xe9, 0x9d, 0x0f, 0x45, 0x23, 0x7d, 0x78, 0x6d, 0x6b, 0xba, 0xa7, 0x96, 0x5c, 0x78, 0x08, 0xbb, 0xff, 0x1a, 0x91]
expect(Crypto.hmacSha1(key: key, message: message)) == hmac
}
}
}
}
}
private extension String {
private var utf8Array: [UInt8] {
return Array(self.utf8)
}
}
| 9944afa00512a67cbc69dc67ac9f2aa1 | 46.46281 | 189 | 0.52133 | false | false | false | false |
czerenkow/LublinWeather | refs/heads/master | App/Dashboard/DashboardViewController.swift | mit | 1 | //
// DashboardViewController.swift
// LublinWeather
//
// Created by Damian Rzeszot on 24/04/2018.
// Copyright © 2018 Damian Rzeszot. All rights reserved.
//
import UIKit
protocol DashboardPresentable: class {
func configure(with model: DashboardViewModel)
}
protocol DashboardOutput: class {
func appearing()
func stations()
func settings()
func refresh()
}
protocol SlideOpenTransitioningHandler: class {
func handle(_ recognizer: UIPanGestureRecognizer)
}
final class DashboardViewController: UIViewController {
// MARK: -
weak var handler: SlideOpenTransitioningHandler!
weak var output: DashboardOutput!
var localizer: Localizer!
// MARK: -
var model: DashboardViewModel!
// MARK: - Outlets
@IBOutlet var tableView: UITableView!
@IBOutlet var panningRecognizer: UIPanGestureRecognizer!
// MARK: - Actions
@objc func settingsAction() {
output.settings()
}
@objc func refreshAction() {
output.refresh()
}
@IBAction func panningAction(_ sender: UIPanGestureRecognizer) {
handler.handle(sender)
}
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(types: [DashboardStationNameCell.self, DashboardMeasurementCell.self])
navigationItem.title = "Lubelskie Stacje Pogodowe"
navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "settings"), style: .plain, target: self, action: #selector(settingsAction))
navigationItem.rightBarButtonItem = item(refreshing: model?.loading ?? false)
// panningRecognizer.isEnabled = false
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
output.appearing()
}
// MARK: -
private func item(refreshing: Bool) -> UIBarButtonItem {
if refreshing {
let activity = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activity.startAnimating()
return UIBarButtonItem(customView: activity)
} else {
return UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refreshAction))
}
}
// MARK: - Status Bar
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
}
extension DashboardViewController: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ recognizer: UIGestureRecognizer) -> Bool {
guard let recognizer = recognizer as? UIPanGestureRecognizer else { return true }
return recognizer.translation(in: nil).x > 0
}
}
extension DashboardViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
} else {
return model.measurements.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(with: DashboardStationNameCell.self, for: indexPath)
configure(cell: cell, at: indexPath)
return cell
} else {
let cell = tableView.dequeueReusableCell(with: DashboardMeasurementCell.self, for: indexPath)
configure(cell: cell, at: indexPath)
return cell
}
}
func configure(cell: UITableViewCell, at path: IndexPath) {
if let cell = cell as? DashboardStationNameCell {
cell.configure(name: model.station)
} else if let cell = cell as? DashboardMeasurementCell {
let keys = DashboardViewModel.Measurement.all.filter { model.measurements[$0] != nil }
let key = keys[path.row]
let value = model.measurements[key] ?? ""
cell.configure(key: key, value: value, obsolete: key == .date && model.obsolete, localizer: localizer)
}
}
}
extension DashboardViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard indexPath.section == 0 else { return }
tableView.deselectRow(at: indexPath, animated: true)
output.stations()
}
}
extension DashboardViewController: DashboardPresentable {
func configure(with model: DashboardViewModel) {
self.model = model
tableView?.reloadData()
navigationItem.rightBarButtonItem = item(refreshing: model.loading)
}
}
| 3ac08ee118172efc98195fc3f0feb733 | 25.184358 | 170 | 0.665244 | false | false | false | false |
ethanneff/organize | refs/heads/master | Organize/Remote.swift | mit | 1 | //
// Remote.swift
// Organize
//
// Created by Ethan Neff on 5/28/16.
// Copyright © 2016 Ethan Neff. All rights reserved.
//
import Foundation
import Firebase
struct Remote {
typealias completionBlock = (error: String?) -> ()
static private let database = FIRDatabase.database().reference()
struct Auth {
// TODO: make background threads
// TODO: have custom error messages
private static func authError(code code: Int) -> String {
switch code {
// TODO: word better
case 17000: return "Invalid custom token"
case 17002: return "Custom token mismatch"
case 17004: return "Invalid credentials"
case 17005: return "User disabled"
case 17006: return "Operation not allowed"
case 17007: return "Email already in use"
case 17008: return "Invalid email"
case 17009: return "Invalid password"
case 17010: return "Too many requests"
case 17011: return "No account with this email"
case 17012: return "Account exists with different credentials"
case 17014: return "Requires re-login"
case 17015: return "Provider already linked"
case 17016: return "No such Provider"
case 17017: return "Invalid user token"
case 17020: return "No internet connection"
case 17021: return "User token expired"
case 17023: return "Invalid API key"
case 17024: return "User mismatch"
case 17025: return "Credential already in use"
case 17026: return "Weak password"
case 17028: return "App not authorized"
case 17995: return "Keychain error"
case 17999: return "Internal Error"
default: return "Unknown error"
}
}
// MARK: - public
static var user: FIRUser? {
return FIRAuth.auth()?.currentUser ?? nil
}
static func signup(controller controller: UIViewController, email: String, password: String, name: String, completion: completionBlock) {
let logout = true
let loadingModal = ModalLoading()
loadingModal.show(controller: controller)
createSignup(email: email, password: password) { (error, user) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
let user = user!
createProfile(user: user, displayName: name) { (error) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
readDeviceUUID { (error, uuid) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
let notebook = Notebook(title: Constant.App.name)
updateDatabaseSignup(user: user, email: email, name: name, uuid: uuid, notebook: notebook) { (error) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
updateLocalNotebook(notebook: notebook) { (error) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: nil)
}
}
}
}
}
}
static func login(controller controller: UIViewController, email: String, password: String, completion: completionBlock) {
let logout = true
let loadingModal = ModalLoading()
loadingModal.show(controller: controller)
createLogin(email: email, password: password) { (error, user) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
let user = user!
readDeviceUUID { (error, uuid) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
updateDatabaseLogin(email: email, user: user, uuid: uuid) { (error) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
readDatabaseNotebookId(user: user) { (error, notebookId) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
readDatabaseNotebook(notebookId: notebookId) { (error, notebook) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
readDatabaseNotebookNotes(notebook: notebook) { (error, notes) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
convertNotesRemoteToLocal(notebook: notebook, notes: notes) { (error, notes, display) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
convertNotebookRemoteToLocal(notebook: notebook, notes: notes, display: display) { (error, notebook) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
updateLocalNotebook(notebook: notebook) { (error) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: nil)
}
}
}
}
}
}
}
}
}
}
static func logout(controller controller: UIViewController, notebook: Notebook, completion: completionBlock) {
let logout = true
let loadingModal = ModalLoading()
loadingModal.show(controller: controller)
if !Util.hasNetworkConnection {
return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: authError(code: 17020))
}
readUser { (error, user) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
let user = user!
let update = convertNotebookLocalToRemote(notebook: notebook, user: user)
updateDatabase(data: update) { (error) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
let notebook = Notebook(notes: [])
updateLocalNotebook(notebook: notebook) { (error) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
LocalNotification.sharedInstance.destroy()
signOut()
return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: nil)
}
}
}
}
static func signOut() {
try! FIRAuth.auth()!.signOut()
}
static func resetPassword(controller controller: UIViewController, email: String, completion: completionBlock) {
let logout = true
let loadingModal = ModalLoading()
loadingModal.show(controller: controller)
FIRAuth.auth()?.sendPasswordResetWithEmail(email) { (error) in
if let error = error {
return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: authError(code: error.code))
} else {
return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: nil)
}
}
}
static func changeEmail(controller controller: UIViewController, email: String, completion: completionBlock) {
let logout = false
let loadingModal = ModalLoading()
loadingModal.show(controller: controller)
readUser { (error, user) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
let user = user!
user.updateEmail(email) { error in
if let error = error {
return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: authError(code: error.code))
} else {
return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: nil)
}
}
}
}
static func changePassword(controller controller: UIViewController, password: String, completion: completionBlock) {
let logout = false
let loadingModal = ModalLoading()
loadingModal.show(controller: controller)
readUser { (error, user) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
let user = user!
user.updatePassword(password) { error in
if let error = error {
return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: authError(code: error.code))
} else {
return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: nil)
}
}
}
}
static func delete(controller controller: UIViewController, completion: completionBlock) {
let logout = false
let loadingModal = ModalLoading()
loadingModal.show(controller: controller)
if !Util.hasNetworkConnection {
return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: authError(code: 17020))
}
readUser { (error, user) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
let user = user!
let delete: [String: AnyObject] = ["users/\(user.uid)/active": false]
updateDatabase(data: delete) { (error) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
}
FIRAuth.auth()?.currentUser?.deleteWithCompletion { error in
if let error = error {
return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: authError(code: error.code))
} else {
return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: nil)
}
}
}
}
static func upload(notebook notebook: Notebook, completion: completionBlock? = nil) {
readUser { (error, user) in
if let error = error {
Report.sharedInstance.log("upload get user error: \(error)")
if let completion = completion {
completion(error: error)
}
return
}
let user = user!
let update = convertNotebookLocalToRemote(notebook: notebook, user: user)
updateDatabase(data: update) { (error) in
if let error = error {
Report.sharedInstance.log("upload update database error: \(error)")
if let completion = completion {
completion(error: error)
}
return
}
if let completion = completion {
completion(error: nil)
}
return
}
}
}
static func download(controller controller: UIViewController, completion: completionBlock) {
let logout = false
let loadingModal = ModalLoading()
loadingModal.show(controller: controller)
if !Util.hasNetworkConnection {
return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: authError(code: 17020))
}
readUser { (error, user) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
let user = user!
readDeviceUUID { (error, uuid) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
readDatabaseNotebookId(user: user) { (error, notebookId) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
readDatabaseNotebook(notebookId: notebookId) { (error, notebook) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
readDatabaseNotebookNotes(notebook: notebook) { (error, notes) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
convertNotesRemoteToLocal(notebook: notebook, notes: notes) { (error, notes, display) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
convertNotebookRemoteToLocal(notebook: notebook, notes: notes, display: display) { (error, notebook) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
updateLocalNotebook(notebook: notebook) { (error) in
if let error = error { return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: error) }
return finish(loadingModal: loadingModal, logout: logout, completion: completion, error: nil)
}
}
}
}
}
}
}
}
}
// MARK: - create
static private func createSignup(email email: String, password: String, completion: (error: String?, user: FIRUser?) -> ()) {
FIRAuth.auth()?.createUserWithEmail(email, password: password) { (user, error) in
if let error = error {
Report.sharedInstance.log("get signup attempt: \(error)")
completion(error: authError(code: error.code), user: user)
} else if user == nil {
Report.sharedInstance.log("get signup user")
completion(error: authError(code: 17999), user: user)
} else {
completion(error: nil, user: user)
}
}
}
static private func createProfile(user user: FIRUser, displayName: String, completion: (error: String?) -> ()) {
let changeRequest = user.profileChangeRequest()
changeRequest.displayName = displayName
changeRequest.commitChangesWithCompletion() { error in
if let error = error {
Report.sharedInstance.log("sign up update profile: \(error)")
completion(error: authError(code: error.code))
} else {
completion(error: nil)
}
}
}
static private func createLogin(email email: String, password: String, completion: (error: String?, user: FIRUser?) -> ()) {
FIRAuth.auth()?.signInWithEmail(email, password: password) { (user, error) in
if let error = error {
Report.sharedInstance.log("get login attempt: \(error)")
completion(error: authError(code: error.code), user: user)
} else if user == nil {
Report.sharedInstance.log("get login user")
completion(error: authError(code: 17999), user: user)
} else {
completion(error: nil, user: user)
}
}
}
// MARK: - read
static private func readDeviceUUID(completion: (error: String?, uuid: String) -> ()) {
if let uuid = UIDevice.currentDevice().identifierForVendor?.UUIDString {
completion(error: nil, uuid: uuid)
} else {
Report.sharedInstance.log("get device uuid")
completion(error: authError(code: 17999), uuid: "")
}
}
static private func readUser(completion: (error: String?, user: FIRUser?) -> ()) {
if let user = Remote.Auth.user {
completion(error: nil, user: user)
} else {
Report.sharedInstance.log("missing user")
completion(error: authError(code: 17999), user: nil)
}
}
// MARK: - database
static private func updateDatabase(data data: [String: AnyObject], completion: (error: String?) -> ()) {
database.updateChildValues(data, withCompletionBlock: { (error: NSError?, reference: FIRDatabaseReference) in
if let error = error {
Report.sharedInstance.log("update database: \(error)")
completion(error: authError(code: 17999))
} else {
completion(error: nil)
}
})
}
static private func updateDatabaseSignup(user user: FIRUser, email: String, name: String, uuid: String, notebook: Notebook, completion: (error: String?) -> ()) {
database.updateChildValues([
// user
"users/\(user.uid)/email": email,
"users/\(user.uid)/name": name,
"users/\(user.uid)/active": true,
"users/\(user.uid)/notebook": notebook.id,
"users/\(user.uid)/notebooks/\(notebook.id)": true,
"users/\(user.uid)/updated": FIRServerValue.timestamp(),
"users/\(user.uid)/created": FIRServerValue.timestamp(),
// devices
"users/\(user.uid)/devices/\(uuid)": true,
"devices/\(uuid)/users/\(user.uid)": true,
// notebook
"notebooks/\(notebook.id)/title": notebook.title,
"notebooks/\(notebook.id)/tags": [],
"notebooks/\(notebook.id)/notes": [],
"notebooks/\(notebook.id)/display": [],
"notebooks/\(notebook.id)/user": user.uid,
"notebooks/\(notebook.id)/active": true,
"notebooks/\(notebook.id)/created": notebook.created.timeIntervalSince1970,
"notebooks/\(notebook.id)/updated": notebook.updated.timeIntervalSince1970,
], withCompletionBlock: { (error: NSError?, reference: FIRDatabaseReference) in
if let error = error {
Report.sharedInstance.log("signup update user database: \(error)")
completion(error: authError(code: 17999))
} else {
completion(error: nil)
}
})
}
static private func updateDatabaseLogin(email email: String, user: FIRUser, uuid: String, completion: (error: String?) -> ()) {
database.updateChildValues([
// user
"users/\(user.uid)/email": email,
"users/\(user.uid)/active": true,
"users/\(user.uid)/updated": FIRServerValue.timestamp(),
// devices
"users/\(user.uid)/devices/\(uuid)": true,
"devices/\(uuid)/users/\(user.uid)": true,
], withCompletionBlock: { (error: NSError?, reference: FIRDatabaseReference) in
if let error = error {
Report.sharedInstance.log("login update user database: \(error)")
completion(error: authError(code: 17999))
} else {
completion(error: nil)
}
})
}
static private func readDatabaseNotebookId(user user: FIRUser, completion: (error: String?, notebookId: String) -> ()) {
database.child("users/\(user.uid)/notebook").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
if let remoteNotebookId = snapshot.value as? String {
completion(error: nil, notebookId: remoteNotebookId)
} else {
Report.sharedInstance.log("missing notebook id")
completion(error: authError(code: 17999), notebookId: "")
}
})
}
static private func readDatabaseNotebook(notebookId notebookId: String, completion: (error: String?, notebook: [String: AnyObject]) -> ()) {
database.child("notebooks/\(notebookId)").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
if var notebook = snapshot.value as? [String: AnyObject] {
notebook["id"] = notebookId
completion(error: nil, notebook: notebook)
} else {
Report.sharedInstance.log("missing notebook")
completion(error: authError(code: 17999), notebook: [:])
}
})
}
static private func readDatabaseNotebookNotes(notebook notebook: [String: AnyObject], completion: (error: String?, notes: [[String: AnyObject]]) -> ()) {
guard let noteIds = notebook["notes"] as? [String] else {
return completion(error: nil, notes: [])
}
// download notes
let start: NSDate = NSDate()
let timeout: Double = 120 // 2 minutes
var count: Int = noteIds.count
var error: Bool = false
var notes: [[String: AnyObject]] = []
for id in noteIds {
database.child("notes/\(id)").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
// catch max timeout
if NSDate().timeIntervalSinceDate(start) > timeout {
Report.sharedInstance.log("timeout download notes")
return completion(error: authError(code: 17010), notes: [])
}
// catch error (only report once)
guard var note = snapshot.value as? [String: AnyObject] else {
if !error {
error = true
Report.sharedInstance.log("missing note")
return completion(error: authError(code: 17999), notes: [])
}
return
}
// save note
note["id"] = id
notes.append(note)
// complete
count -= 1
if count == 0 {
return completion(error: nil, notes: notes)
}
})
}
}
static private func updateLocalNotebook(notebook notebook: Notebook, completion: completionBlock) {
Notebook.set(data: notebook) { success in
if !success {
Report.sharedInstance.log("save notebook")
completion(error: authError(code: 17999))
} else {
completion(error: nil)
}
}
}
// MARK: - finish
static private func finish(loadingModal loadingModal: ModalLoading, logout: Bool, completion: completionBlock, error: String?) {
loadingModal.hide {
if let error = error {
if logout {
try! FIRAuth.auth()!.signOut()
}
completion(error: error)
} else {
completion(error: nil)
}
}
}
// MARK: - convert
static private func convertNotesRemoteToLocal(notebook notebook: [String: AnyObject], notes: [[String: AnyObject]], completion: (error: String?, notes: [Note], display: [Note]) -> ()) {
// quick exit
guard let noteIds = notebook["notes"] as? [String], let displayIds = notebook["display"] as? [String] else {
return completion(error: nil, notes: [], display: [])
}
// dictionary to Note
var unorganized: [Note] = []
for note in notes {
let body = note["body"] as? String
guard let id = note["id"] as? String,
let title = note["title"] as? String,
let bolded = note["bolded"] as? Bool,
let completed = note["completed"] as? Bool,
let collapsed = note["collapsed"] as? Bool,
let children = note["children"] as? Int,
let indent = note["indent"] as? Int,
let created = note["created"] as? Double,
let updated = note["updated"] as? Double else {
Report.sharedInstance.log("creating note")
return completion(error: authError(code: 17999), notes: [], display: [])
}
var reminder: Reminder?
if let noteReminder = note["reminder"] as? [String: AnyObject] {
guard let id = noteReminder["id"] as? String,
let uid = noteReminder["uid"] as? String,
let date = noteReminder["date"] as? Double,
let type = noteReminder["type"] as? Int,
let created = note["created"] as? Double,
let updated = note["updated"] as? Double else {
Report.sharedInstance.log("creating reminder")
return completion(error: authError(code: 17999), notes: [], display: [])
}
let reminderType = ReminderType(rawValue: type) ?? ReminderType(rawValue: 0)!
reminder = Reminder(id: id, uid: uid, type: reminderType, date: NSDate(timeIntervalSince1970: date), created: NSDate(timeIntervalSince1970: created), updated: NSDate(timeIntervalSince1970: updated))
}
let note = Note(id: id, title: title, body: body, bolded: bolded, completed: completed, collapsed: collapsed, children: children, indent: indent, reminder: reminder, created: NSDate(timeIntervalSince1970: created), updated: NSDate(timeIntervalSince1970: updated))
unorganized.append(note)
}
// unorganize to note and display
var notes: [Note] = []
var display: [Note] = []
for id in noteIds {
for i in 0..<unorganized.count {
let note = unorganized[i]
if note.id == id {
notes.append(note)
unorganized.removeAtIndex(i)
break
}
}
}
var found = 0
for id in displayIds {
for i in found..<notes.count {
let note = notes[i]
if note.id == id {
found += 1
display.append(note)
break
}
}
}
// update local reminders
LocalNotification.sharedInstance.destroy()
// TODO: push notifications accept before download on login
if LocalNotification.sharedInstance.hasPremission() {
for note in notes {
if let reminder = note.reminder, let controller = UIApplication.topViewController() {
LocalNotification.sharedInstance.create(controller: controller, body: note.title, action: nil, fireDate: reminder.date, soundName: nil, uid: reminder.uid, completion: nil)
}
}
}
return completion(error: nil, notes: notes, display: display)
}
static private func convertNotebookRemoteToLocal(notebook notebook: [String: AnyObject], notes: [Note], display: [Note], completion: (error: String?, notebook: Notebook) -> ()) {
guard let title = notebook["title"] as? String,
let id = notebook["id"] as? String,
let created = notebook["created"] as? Double,
let updated = notebook["updated"] as? Double else {
Report.sharedInstance.log("missing notebook info")
return completion(error: authError(code: 17999), notebook: Notebook(title: ""))
}
let notebook = Notebook(id: id, title: title, notes: notes, display: display, history: [], created: NSDate(timeIntervalSince1970: created), updated: NSDate(timeIntervalSince1970: updated))
return completion(error: nil, notebook: notebook)
}
static private func convertNotebookLocalToRemote(notebook notebook: Notebook, user: FIRUser) -> [String: AnyObject] {
// update notebook
var update: [String: AnyObject] = [:]
var notes: [String] = []
var display: [String] = []
update["notebooks/\(notebook.id)/title"] = notebook.title
update["notebooks/\(notebook.id)/updated"] = notebook.updated.timeIntervalSince1970
// create new notes
for note in notebook.notes {
update["notes/\(note.id)/user"] = user.uid
update["notes/\(note.id)/notebook"] = notebook.id
update["notes/\(note.id)/title"] = note.title
update["notes/\(note.id)/body"] = note.body ?? ""
update["notes/\(note.id)/bolded"] = note.bolded
update["notes/\(note.id)/completed"] = note.completed
update["notes/\(note.id)/collapsed"] = note.collapsed
update["notes/\(note.id)/children"] = note.children
update["notes/\(note.id)/indent"] = note.indent
update["notes/\(note.id)/created"] = note.created.timeIntervalSince1970
update["notes/\(note.id)/updated"] = note.updated.timeIntervalSince1970
// create new reminders
if let reminder = note.reminder {
update["notes/\(note.id)/reminder/id"] = reminder.id
update["notes/\(note.id)/reminder/uid"] = reminder.uid
update["notes/\(note.id)/reminder/date"] = reminder.date.timeIntervalSince1970
update["notes/\(note.id)/reminder/type"] = reminder.type.rawValue
update["notes/\(note.id)/reminder/created"] = reminder.created.timeIntervalSince1970
update["notes/\(note.id)/reminder/updated"] = reminder.updated.timeIntervalSince1970
} else {
update["notes/\(note.id)/reminder"] = false
}
// create note array
notes.append(note.id)
}
for note in notebook.display {
// create display array
display.append(note.id)
}
update["notebooks/\(notebook.id)/notes"] = notes
update["notebooks/\(notebook.id)/display"] = display
return update
}
}
struct Device {
static func open() {
update()
access()
}
static func updatePushAPN(token token: String) {
// apn push
if let uuid = UIDevice.currentDevice().identifierForVendor?.UUIDString {
database.updateChildValues(["devices/\(uuid)/apn/": token])
}
}
static func updatePushFCM(token token: String) {
// firebase push
if let uuid = UIDevice.currentDevice().identifierForVendor?.UUIDString {
database.updateChildValues(["devices/\(uuid)/fcm/": token])
}
}
static private func update() {
// called on device open
let uuid: String = UIDevice.currentDevice().identifierForVendor?.UUIDString ?? "" // changes on app deletion
let model = UIDevice.currentDevice().modelName
let version = UIDevice.currentDevice().systemVersion
let app: String = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
database.child("devices/\(uuid)/").updateChildValues([
"os": "iOS",
"model": model,
"version": version,
"app": app
])
}
static private func access() {
if let uuid = UIDevice.currentDevice().identifierForVendor?.UUIDString {
let accessedRef = FIRDatabase.database().referenceWithPath("devices/\(uuid)/accessed")
let connectedRef = FIRDatabase.database().referenceWithPath(".info/connected")
connectedRef.observeEventType(.Value, withBlock: { snapshot in
accessedRef.onDisconnectSetValue(FIRServerValue.timestamp())
})
}
}
}
struct User {
static func open() {
access()
}
static private func access() {
if let user = Remote.Auth.user, let uuid = UIDevice.currentDevice().identifierForVendor?.UUIDString {
let myConnectionsRef = FIRDatabase.database().referenceWithPath("users/\(user.uid)/connections")
let accessedRef = FIRDatabase.database().referenceWithPath("users/\(user.uid)/accessed")
let connectedRef = FIRDatabase.database().referenceWithPath(".info/connected")
connectedRef.observeEventType(.Value, withBlock: { snapshot in
let connected = snapshot.value as? Bool
if connected != nil && connected! {
let con = myConnectionsRef.child(uuid)
con.setValue(true)
con.onDisconnectRemoveValue()
accessedRef.onDisconnectSetValue(FIRServerValue.timestamp())
}
})
}
}
}
struct Config {
enum Keys: String {
case ShowAds
case ShowReview
}
static func fetch(completion: (config: FIRRemoteConfig?) -> ()) {
let remoteConfig: FIRRemoteConfig = FIRRemoteConfig.remoteConfig()
remoteConfig.configSettings = FIRRemoteConfigSettings(developerModeEnabled: Constant.App.release ? false : true)!
let expirationDuration: Double = remoteConfig.configSettings.isDeveloperModeEnabled ? 0 : 60*60
remoteConfig.fetchWithExpirationDuration(expirationDuration) { (status, error) in
if (status == .Success) {
remoteConfig.activateFetched()
completion(config: remoteConfig)
} else {
Report.sharedInstance.log("Config not fetched \(error)")
completion(config: nil)
}
}
}
}
} | 3e5b5e6ad9fd35995f929f954f4f3219 | 41.901299 | 271 | 0.609118 | false | false | false | false |
dclelland/DirectedPanGestureRecognizer | refs/heads/master | DirectedPanDemo/DirectedPanDemo/ViewController.swift | mit | 1 | //
// ViewController.swift
// DirectedPanDemo
//
// Created by Daniel Clelland on 11/04/16.
// Copyright © 2016 Daniel Clelland. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var panGestureRecognizer: DirectedPanGestureRecognizer!
@IBOutlet weak var translationLabel: UILabel!
@IBOutlet weak var velocityLabel: UILabel!
@IBOutlet weak var arrowLabel: UILabel!
@IBOutlet weak var directionSegmentedControl: UISegmentedControl!
@IBOutlet weak var minimumTranslationLabel: UILabel!
@IBOutlet weak var minimumTranslationSlider: UISlider!
@IBOutlet weak var minimumVelocityLabel: UILabel!
@IBOutlet weak var minimumVelocitySlider: UISlider!
// MARK: Overrides
override func viewDidLoad() {
super.viewDidLoad()
updateView()
}
// MARK: View state
func updateView() {
let currentDirection = direction(forIndex: directionSegmentedControl.selectedSegmentIndex)!
let translationText = String(format: "%.2f", panGestureRecognizer.translation())
let velocityText = String(format: "%.2f", panGestureRecognizer.velocity())
translationLabel.text = "Translation: " + translationText
velocityLabel.text = "Velocity: " + velocityText
let translationColor = panGestureRecognizer.translation() < panGestureRecognizer.minimumTranslation ? UIColor.red : UIColor.green
let velocityColor = panGestureRecognizer.velocity() < panGestureRecognizer.minimumVelocity ? UIColor.red : UIColor.green
translationLabel.backgroundColor = translationColor
velocityLabel.backgroundColor = velocityColor
let arrowText = arrow(forDirection: currentDirection)
arrowLabel.text = arrowText
let minimumTranslationText = String(format: "%.2f", panGestureRecognizer.minimumTranslation)
let minimumVelocityText = String(format: "%.2f", panGestureRecognizer.minimumVelocity)
minimumTranslationLabel.text = "Minimum translation: " + minimumTranslationText
minimumVelocityLabel.text = "Minimum velocity: " + minimumVelocityText
}
// MARK: Actions
@IBAction func directionSegmentedControlDidChangeValue(_ segmentedControl: UISegmentedControl) {
updateView()
}
@IBAction func minimumTranslationSliderDidChangeValue(_ slider: UISlider) {
panGestureRecognizer.minimumTranslation = minimumTranslation(forValue: slider.value)
updateView()
}
@IBAction func minimumVelocitySliderDidChangeValue(_ slider: UISlider) {
panGestureRecognizer.minimumVelocity = minimumVelocity(forValue: slider.value)
updateView()
}
}
// MARK: - Gesture recognizer delegate
extension ViewController: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
switch gestureRecognizer {
case let panGestureRecognizer as DirectedPanGestureRecognizer where panGestureRecognizer == self.panGestureRecognizer:
return panGestureRecognizer.direction == direction(forIndex: directionSegmentedControl.selectedSegmentIndex)!
default:
return true
}
}
}
// MARK: - Directed pan gesture recognizer delegate
extension ViewController: DirectedPanGestureRecognizerDelegate {
func directedPanGestureRecognizer(didStart gestureRecognizer: DirectedPanGestureRecognizer) {
arrowLabel.backgroundColor = .clear
updateView()
}
func directedPanGestureRecognizer(didUpdate gestureRecognizer: DirectedPanGestureRecognizer) {
arrowLabel.backgroundColor = .clear
updateView()
}
func directedPanGestureRecognizer(didCancel gestureRecognizer: DirectedPanGestureRecognizer) {
arrowLabel.backgroundColor = .red
updateView()
}
func directedPanGestureRecognizer(didFinish gestureRecognizer: DirectedPanGestureRecognizer) {
arrowLabel.backgroundColor = .green
updateView()
}
}
// MARK: - Private helpers
private extension ViewController {
func direction(forIndex index: Int) -> DirectedPanGestureRecognizer.Direction? {
switch index {
case 0:
return .up
case 1:
return .left
case 2:
return .down
case 3:
return .right
default:
return nil
}
}
func minimumTranslation(forValue value: Float) -> CGFloat {
return CGFloat(value) * view.frame.width
}
func minimumVelocity(forValue value: Float) -> CGFloat {
return CGFloat(value) * view.frame.width
}
func arrow(forDirection direction: DirectedPanGestureRecognizer.Direction) -> String {
switch direction {
case .up:
return "↑"
case .left:
return "←"
case .down:
return "↓"
case .right:
return "→"
}
}
}
| fbb128f344fcd1f7f42594d49dba94bd | 30.592593 | 137 | 0.67585 | false | false | false | false |
gudjao/XLPagerTabStrip | refs/heads/master | Sources/BaseButtonBarPagerTabStripViewController.swift | mit | 1 | // BaseButtonBarPagerTabStripViewController.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com )
//
//
// 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
open class BaseButtonBarPagerTabStripViewController<ButtonBarCellType : UICollectionViewCell>: PagerTabStripViewController, PagerTabStripDataSource, PagerTabStripIsProgressiveDelegate, UICollectionViewDelegate, UICollectionViewDataSource {
public var settings = ButtonBarPagerTabStripSettings()
public var buttonBarItemSpec: ButtonBarItemSpec<ButtonBarCellType>!
public var changeCurrentIndex: ((_ oldCell: ButtonBarCellType?, _ newCell: ButtonBarCellType?, _ animated: Bool) -> Void)?
public var changeCurrentIndexProgressive: ((_ oldCell: ButtonBarCellType?, _ newCell: ButtonBarCellType?, _ progressPercentage: CGFloat, _ changeCurrentIndex: Bool, _ animated: Bool) -> Void)?
@IBOutlet public weak var buttonBarView: ButtonBarView!
lazy private var cachedCellWidths: [CGFloat]? = { [unowned self] in
return self.calculateWidths()
}()
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
delegate = self
datasource = self
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delegate = self
datasource = self
}
open override func viewDidLoad() {
super.viewDidLoad()
buttonBarView = buttonBarView ?? {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .horizontal
flowLayout.sectionInset = UIEdgeInsetsMake(0, settings.style.buttonBarLeftContentInset ?? 35, 0, settings.style.buttonBarRightContentInset ?? 35)
let buttonBarHeight = settings.style.buttonBarHeight ?? 44
let buttonBar = ButtonBarView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: buttonBarHeight), collectionViewLayout: flowLayout)
buttonBar.backgroundColor = .orange
buttonBar.selectedBar.backgroundColor = .black
buttonBar.autoresizingMask = .flexibleWidth
var newContainerViewFrame = containerView.frame
newContainerViewFrame.origin.y = buttonBarHeight
newContainerViewFrame.size.height = containerView.frame.size.height - (buttonBarHeight - containerView.frame.origin.y)
containerView.frame = newContainerViewFrame
return buttonBar
}()
if buttonBarView.superview == nil {
view.addSubview(buttonBarView)
}
if buttonBarView.delegate == nil {
buttonBarView.delegate = self
}
if buttonBarView.dataSource == nil {
buttonBarView.dataSource = self
}
buttonBarView.scrollsToTop = false
let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout
flowLayout.scrollDirection = .horizontal
flowLayout.minimumInteritemSpacing = settings.style.buttonBarMinimumInteritemSpacing ?? flowLayout.minimumInteritemSpacing
flowLayout.minimumLineSpacing = settings.style.buttonBarMinimumLineSpacing ?? flowLayout.minimumLineSpacing
let sectionInset = flowLayout.sectionInset
flowLayout.sectionInset = UIEdgeInsetsMake(sectionInset.top, settings.style.buttonBarLeftContentInset ?? sectionInset.left, sectionInset.bottom, settings.style.buttonBarRightContentInset ?? sectionInset.right)
buttonBarView.showsHorizontalScrollIndicator = false
buttonBarView.backgroundColor = settings.style.buttonBarBackgroundColor ?? buttonBarView.backgroundColor
buttonBarView.selectedBar.backgroundColor = settings.style.selectedBarBackgroundColor
buttonBarView.selectedBarHeight = settings.style.selectedBarHeight
// register button bar item cell
switch buttonBarItemSpec! {
case .nibFile(let nibName, let bundle, _):
buttonBarView.register(UINib(nibName: nibName, bundle: bundle), forCellWithReuseIdentifier:"Cell")
case .cellClass:
buttonBarView.register(ButtonBarCellType.self, forCellWithReuseIdentifier:"Cell")
}
//-
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
buttonBarView.layoutIfNeeded()
isViewAppearing = true
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isViewAppearing = false
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard isViewAppearing || isViewRotating else { return }
// Force the UICollectionViewFlowLayout to get laid out again with the new size if
// a) The view is appearing. This ensures that
// collectionView:layout:sizeForItemAtIndexPath: is called for a second time
// when the view is shown and when the view *frame(s)* are actually set
// (we need the view frame's to have been set to work out the size's and on the
// first call to collectionView:layout:sizeForItemAtIndexPath: the view frame(s)
// aren't set correctly)
// b) The view is rotating. This ensures that
// collectionView:layout:sizeForItemAtIndexPath: is called again and can use the views
// *new* frame so that the buttonBarView cell's actually get resized correctly
cachedCellWidths = calculateWidths()
buttonBarView.collectionViewLayout.invalidateLayout()
// When the view first appears or is rotated we also need to ensure that the barButtonView's
// selectedBar is resized and its contentOffset/scroll is set correctly (the selected
// tab/cell may end up either skewed or off screen after a rotation otherwise)
buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .scrollOnlyIfOutOfScreen)
}
// MARK: - View Rotation
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
}
// MARK: - Public Methods
open override func reloadPagerTabStripView() {
super.reloadPagerTabStripView()
guard isViewLoaded else { return }
buttonBarView.reloadData()
cachedCellWidths = calculateWidths()
buttonBarView.moveTo(index: currentIndex, animated: false, swipeDirection: .none, pagerScroll: .yes)
}
open func calculateStretchedCellWidths(_ minimumCellWidths: [CGFloat], suggestedStretchedCellWidth: CGFloat, previousNumberOfLargeCells: Int) -> CGFloat {
var numberOfLargeCells = 0
var totalWidthOfLargeCells: CGFloat = 0
for minimumCellWidthValue in minimumCellWidths {
if minimumCellWidthValue > suggestedStretchedCellWidth {
totalWidthOfLargeCells += minimumCellWidthValue
numberOfLargeCells += 1
}
}
guard numberOfLargeCells > previousNumberOfLargeCells else { return suggestedStretchedCellWidth }
let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout
let collectionViewAvailiableWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right
let numberOfCells = minimumCellWidths.count
let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing
let numberOfSmallCells = numberOfCells - numberOfLargeCells
let newSuggestedStretchedCellWidth = (collectionViewAvailiableWidth - totalWidthOfLargeCells - cellSpacingTotal) / CGFloat(numberOfSmallCells)
return calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: newSuggestedStretchedCellWidth, previousNumberOfLargeCells: numberOfLargeCells)
}
open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) {
guard shouldUpdateButtonBarView else { return }
buttonBarView.moveTo(index: toIndex, animated: true, swipeDirection: toIndex < fromIndex ? .right : .left, pagerScroll: .yes)
if let changeCurrentIndex = changeCurrentIndex {
let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarCellType
let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
changeCurrentIndex(oldCell, newCell, true)
}
}
open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) {
guard shouldUpdateButtonBarView else { return }
buttonBarView.move(fromIndex: fromIndex, toIndex: toIndex, progressPercentage: progressPercentage, pagerScroll: .yes)
if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex != fromIndex ? fromIndex : toIndex, section: 0)) as? ButtonBarCellType
let newCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
changeCurrentIndexProgressive(oldCell, newCell, progressPercentage, indexWasChanged, true)
}
}
// MARK: - UICollectionViewDelegateFlowLayut
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
guard let cellWidthValue = cachedCellWidths?[indexPath.row] else {
fatalError("cachedCellWidths for \(indexPath.row) must not be nil")
}
return CGSize(width: cellWidthValue, height: collectionView.frame.size.height)
}
open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard indexPath.item != currentIndex else { return }
buttonBarView.moveTo(index: indexPath.item, animated: true, swipeDirection: .none, pagerScroll: .yes)
shouldUpdateButtonBarView = false
let oldCell = buttonBarView.cellForItem(at: IndexPath(item: currentIndex, section: 0)) as? ButtonBarCellType
let newCell = buttonBarView.cellForItem(at: IndexPath(item: indexPath.item, section: 0)) as? ButtonBarCellType
if pagerBehaviour.isProgressiveIndicator {
if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
changeCurrentIndexProgressive(oldCell, newCell, 1, true, true)
}
}
else {
if let changeCurrentIndex = changeCurrentIndex {
changeCurrentIndex(oldCell, newCell, true)
}
}
moveToViewController(at: indexPath.item)
}
// MARK: - UICollectionViewDataSource
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewControllers.count
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? ButtonBarCellType else {
fatalError("UICollectionViewCell should be or extend from ButtonBarViewCell")
}
let childController = viewControllers[indexPath.item] as! IndicatorInfoProvider
let indicatorInfo = childController.indicatorInfo(for: self)
configure(cell: cell, for: indicatorInfo)
if pagerBehaviour.isProgressiveIndicator {
if let changeCurrentIndexProgressive = changeCurrentIndexProgressive {
changeCurrentIndexProgressive(currentIndex == indexPath.item ? nil : cell, currentIndex == indexPath.item ? cell : nil, 1, true, false)
}
}
else {
if let changeCurrentIndex = changeCurrentIndex {
changeCurrentIndex(currentIndex == indexPath.item ? nil : cell, currentIndex == indexPath.item ? cell : nil, false)
}
}
return cell
}
// MARK: - UIScrollViewDelegate
open override func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
super.scrollViewDidEndScrollingAnimation(scrollView)
guard scrollView == containerView else { return }
shouldUpdateButtonBarView = true
}
open func configure(cell: ButtonBarCellType, for indicatorInfo: IndicatorInfo){
fatalError("You must override this method to set up ButtonBarView cell accordingly")
}
private func calculateWidths() -> [CGFloat] {
let flowLayout = buttonBarView.collectionViewLayout as! UICollectionViewFlowLayout
let numberOfCells = viewControllers.count
var minimumCellWidths = [CGFloat]()
var collectionViewContentWidth: CGFloat = 0
for viewController in viewControllers {
let childController = viewController as! IndicatorInfoProvider
let indicatorInfo = childController.indicatorInfo(for: self)
switch buttonBarItemSpec! {
case .cellClass(let widthCallback):
let width = widthCallback(indicatorInfo)
minimumCellWidths.append(width)
collectionViewContentWidth += width
case .nibFile(_, _, let widthCallback):
let width = widthCallback(indicatorInfo)
minimumCellWidths.append(width)
collectionViewContentWidth += width
}
}
let cellSpacingTotal = CGFloat(numberOfCells - 1) * flowLayout.minimumLineSpacing
collectionViewContentWidth += cellSpacingTotal
let collectionViewAvailableVisibleWidth = buttonBarView.frame.size.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right
if !settings.style.buttonBarItemsShouldFillAvailableWidth || collectionViewAvailableVisibleWidth < collectionViewContentWidth {
return minimumCellWidths
}
else {
let stretchedCellWidthIfAllEqual = (collectionViewAvailableVisibleWidth - cellSpacingTotal) / CGFloat(numberOfCells)
let generalMinimumCellWidth = calculateStretchedCellWidths(minimumCellWidths, suggestedStretchedCellWidth: stretchedCellWidthIfAllEqual, previousNumberOfLargeCells: 0)
var stretchedCellWidths = [CGFloat]()
for minimumCellWidthValue in minimumCellWidths {
let cellWidth = (minimumCellWidthValue > generalMinimumCellWidth) ? minimumCellWidthValue : generalMinimumCellWidth
stretchedCellWidths.append(cellWidth)
}
return stretchedCellWidths
}
}
private var shouldUpdateButtonBarView = true
}
open class ExampleBaseButtonBarPagerTabStripViewController: BaseButtonBarPagerTabStripViewController<ButtonBarViewCell> {
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initialize()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
open func initialize(){
buttonBarItemSpec = .nibFile(nibName: "ButtonCell", bundle: Bundle(for: ButtonBarViewCell.self), width:{ [weak self] (childItemInfo) -> CGFloat in
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = self?.settings.style.buttonBarItemFont ?? label.font
label.text = childItemInfo.title
let labelSize = label.intrinsicContentSize
return labelSize.width + CGFloat(self?.settings.style.buttonBarItemLeftRightMargin ?? 8 * 2)
})
}
open override func configure(cell: ButtonBarViewCell, for indicatorInfo: IndicatorInfo){
cell.label.text = indicatorInfo.title
if let image = indicatorInfo.image {
cell.imageView.image = image
}
if let highlightedImage = indicatorInfo.highlightedImage {
cell.imageView.highlightedImage = highlightedImage
}
}
}
| e8d3c2105a618142eff770c3d7c50560 | 49.347701 | 239 | 0.712459 | false | false | false | false |
Adlai-Holler/ReflowLabel | refs/heads/master | reflowlabel/Utilities.swift | mit | 1 | import Foundation
extension String {
func nsRangeFromRange(range : Range<String.Index>) -> NSRange {
let utf16view = self.utf16
let from = String.UTF16Index(range.startIndex, within: utf16view)
let to = String.UTF16Index(range.endIndex, within: utf16view)
let location = utf16view.startIndex.distanceTo(from)
let length = from.distanceTo(to)
return NSMakeRange(location, length)
}
}
| 95eb094aa9c7a0dbd5ed3714f4af7f1c | 35.666667 | 73 | 0.686364 | false | false | false | false |
alblue/swift | refs/heads/master | validation-test/stdlib/String.swift | apache-2.0 | 1 | // RUN: %empty-directory(%t)
// RUN: if [ %target-runtime == "objc" ]; \
// RUN: then \
// RUN: %target-clang -fobjc-arc %S/Inputs/NSSlowString/NSSlowString.m -c -o %t/NSSlowString.o && \
// RUN: %target-build-swift -I %S/Inputs/NSSlowString/ %t/NSSlowString.o %s -Xfrontend -disable-access-control -o %t/String; \
// RUN: else \
// RUN: %target-build-swift %s -Xfrontend -disable-access-control -o %t/String; \
// RUN: fi
// RUN: %target-codesign %t/String
// RUN: %target-run %t/String
// REQUIRES: executable_test
// XFAIL: interpret
import StdlibUnittest
import StdlibCollectionUnittest
#if _runtime(_ObjC)
import NSSlowString
import Foundation // For NSRange
#endif
extension Collection {
internal func index(_nth n: Int) -> Index {
precondition(n >= 0)
return index(startIndex, offsetBy: numericCast(n))
}
internal func index(_nthLast n: Int) -> Index {
precondition(n >= 0)
return index(endIndex, offsetBy: -numericCast(n))
}
}
extension String {
var nativeCapacity: Int {
switch self._classify()._form {
case ._native: break
default: preconditionFailure()
}
return self._classify()._capacity
}
var capacity: Int {
return self._classify()._capacity
}
var unusedCapacity: Int {
return Swift.max(0, self._classify()._capacity - self._classify()._count)
}
var bufferID: ObjectIdentifier? {
return _rawIdentifier()
}
func _rawIdentifier() -> ObjectIdentifier? {
return self._classify()._objectIdentifier
}
var byteWidth: Int {
return _classify()._isASCII ? 1 : 2
}
}
extension Substring {
var bufferID: ObjectIdentifier? {
return _wholeString.bufferID
}
}
// A thin wrapper around _StringGuts implementing RangeReplaceableCollection
struct StringFauxUTF16Collection: RangeReplaceableCollection, RandomAccessCollection {
typealias Element = UTF16.CodeUnit
typealias Index = Int
typealias Indices = CountableRange<Int>
init(_ guts: _StringGuts) {
self._str = String(guts)
}
init() {
self.init(_StringGuts())
}
var _str: String
var _guts: _StringGuts { return _str._guts }
var startIndex: Index { return 0 }
var endIndex: Index { return _str.utf16.count }
var indices: Indices { return startIndex..<endIndex }
subscript(position: Index) -> Element {
return _str.utf16[_str._toUTF16Index(position)]
}
mutating func replaceSubrange<C>(
_ subrange: Range<Index>,
with newElements: C
) where C : Collection, C.Element == Element {
var utf16 = Array(_str.utf16)
utf16.replaceSubrange(subrange, with: newElements)
self._str = String(decoding: utf16, as: UTF16.self)
}
mutating func reserveCapacity(_ n: Int) {
_str.reserveCapacity(n)
}
}
var StringTests = TestSuite("StringTests")
StringTests.test("sizeof") {
#if arch(i386) || arch(arm)
expectEqual(12, MemoryLayout<String>.size)
#else
expectEqual(16, MemoryLayout<String>.size)
#endif
}
StringTests.test("AssociatedTypes-UTF8View") {
typealias View = String.UTF8View
expectCollectionAssociatedTypes(
collectionType: View.self,
iteratorType: View.Iterator.self,
subSequenceType: Substring.UTF8View.self,
indexType: View.Index.self,
indicesType: DefaultIndices<View>.self)
}
StringTests.test("AssociatedTypes-UTF16View") {
typealias View = String.UTF16View
expectCollectionAssociatedTypes(
collectionType: View.self,
iteratorType: IndexingIterator<View>.self,
subSequenceType: Substring.UTF16View.self,
indexType: View.Index.self,
indicesType: View.Indices.self)
}
StringTests.test("AssociatedTypes-UnicodeScalarView") {
typealias View = String.UnicodeScalarView
expectCollectionAssociatedTypes(
collectionType: View.self,
iteratorType: View.Iterator.self,
subSequenceType: Substring.UnicodeScalarView.self,
indexType: View.Index.self,
indicesType: DefaultIndices<View>.self)
}
StringTests.test("AssociatedTypes-CharacterView") {
expectCollectionAssociatedTypes(
collectionType: String.self,
iteratorType: IndexingIterator<String>.self,
subSequenceType: Substring.self,
indexType: String.Index.self,
indicesType: DefaultIndices<String>.self)
}
func checkUnicodeScalarViewIteration(
_ expectedScalars: [UInt32], _ str: String
) {
do {
let us = str.unicodeScalars
var i = us.startIndex
let end = us.endIndex
var decoded: [UInt32] = []
while i != end {
expectTrue(i < us.index(after: i)) // Check for Comparable conformance
decoded.append(us[i].value)
i = us.index(after: i)
}
expectEqual(expectedScalars, decoded)
}
do {
let us = str.unicodeScalars
let start = us.startIndex
var i = us.endIndex
var decoded: [UInt32] = []
while i != start {
i = us.index(before: i)
decoded.append(us[i].value)
}
expectEqual(expectedScalars, decoded)
}
}
StringTests.test("unicodeScalars") {
checkUnicodeScalarViewIteration([], "")
checkUnicodeScalarViewIteration([ 0x0000 ], "\u{0000}")
checkUnicodeScalarViewIteration([ 0x0041 ], "A")
checkUnicodeScalarViewIteration([ 0x007f ], "\u{007f}")
checkUnicodeScalarViewIteration([ 0x0080 ], "\u{0080}")
checkUnicodeScalarViewIteration([ 0x07ff ], "\u{07ff}")
checkUnicodeScalarViewIteration([ 0x0800 ], "\u{0800}")
checkUnicodeScalarViewIteration([ 0xd7ff ], "\u{d7ff}")
checkUnicodeScalarViewIteration([ 0x8000 ], "\u{8000}")
checkUnicodeScalarViewIteration([ 0xe000 ], "\u{e000}")
checkUnicodeScalarViewIteration([ 0xfffd ], "\u{fffd}")
checkUnicodeScalarViewIteration([ 0xffff ], "\u{ffff}")
checkUnicodeScalarViewIteration([ 0x10000 ], "\u{00010000}")
checkUnicodeScalarViewIteration([ 0x10ffff ], "\u{0010ffff}")
}
StringTests.test("Index/Comparable") {
let empty = ""
expectTrue(empty.startIndex == empty.endIndex)
expectFalse(empty.startIndex != empty.endIndex)
expectTrue(empty.startIndex <= empty.endIndex)
expectTrue(empty.startIndex >= empty.endIndex)
expectFalse(empty.startIndex > empty.endIndex)
expectFalse(empty.startIndex < empty.endIndex)
let nonEmpty = "borkus biqualificated"
expectFalse(nonEmpty.startIndex == nonEmpty.endIndex)
expectTrue(nonEmpty.startIndex != nonEmpty.endIndex)
expectTrue(nonEmpty.startIndex <= nonEmpty.endIndex)
expectFalse(nonEmpty.startIndex >= nonEmpty.endIndex)
expectFalse(nonEmpty.startIndex > nonEmpty.endIndex)
expectTrue(nonEmpty.startIndex < nonEmpty.endIndex)
}
StringTests.test("Index/Hashable") {
let s = "abcdef"
let t = Set(s.indices)
expectEqual(s.count, t.count)
expectTrue(t.contains(s.startIndex))
}
StringTests.test("ForeignIndexes/Valid") {
// It is actually unclear what the correct behavior is. This test is just a
// change detector.
//
// <rdar://problem/18037897> Design, document, implement invalidation model
// for foreign String indexes
do {
let donor = "abcdef"
let acceptor = "uvwxyz"
expectEqual("u", acceptor[donor.startIndex])
expectEqual("wxy",
acceptor[donor.index(_nth: 2)..<donor.index(_nth: 5)])
}
do {
let donor = "abcdef"
let acceptor = "\u{1f601}\u{1f602}\u{1f603}"
expectEqual("\u{1f601}", acceptor[donor.startIndex])
expectEqual("\u{1f601}", acceptor[donor.index(after: donor.startIndex)])
}
}
StringTests.test("ForeignIndexes/UnexpectedCrash") {
let donor = "\u{1f601}\u{1f602}\u{1f603}"
let acceptor = "abcdef"
// Adjust donor.startIndex to ensure it caches a stride
let start = donor.index(before: donor.index(after: donor.startIndex))
expectEqual("a", acceptor[start])
}
StringTests.test("ForeignIndexes/subscript(Index)/OutOfBoundsTrap") {
let donor = "abcdef"
let acceptor = "uvw"
expectEqual("u", acceptor[donor.index(_nth: 0)])
expectEqual("v", acceptor[donor.index(_nth: 1)])
expectEqual("w", acceptor[donor.index(_nth: 2)])
let i = donor.index(_nth: 3)
expectCrashLater()
_ = acceptor[i]
}
StringTests.test("String/subscript(_:Range)") {
let s = "foobar"
let from = s.startIndex
let to = s.index(before: s.endIndex)
let actual = s[from..<to]
expectEqual("fooba", actual)
}
StringTests.test("String/subscript(_:ClosedRange)") {
let s = "foobar"
let from = s.startIndex
let to = s.index(before: s.endIndex)
let actual = s[from...to]
expectEqual(s, actual)
}
StringTests.test("ForeignIndexes/subscript(Range)/OutOfBoundsTrap/1") {
let donor = "abcdef"
let acceptor = "uvw"
expectEqual("uvw", acceptor[donor.startIndex..<donor.index(_nth: 3)])
let r = donor.startIndex..<donor.index(_nth: 4)
expectCrashLater()
_ = acceptor[r]
}
StringTests.test("ForeignIndexes/subscript(Range)/OutOfBoundsTrap/2") {
let donor = "abcdef"
let acceptor = "uvw"
expectEqual("uvw", acceptor[donor.startIndex..<donor.index(_nth: 3)])
let r = donor.index(_nth: 4)..<donor.index(_nth: 5)
expectCrashLater()
_ = acceptor[r]
}
StringTests.test("ForeignIndexes/subscript(ClosedRange)/OutOfBoundsTrap/1") {
let donor = "abcdef"
let acceptor = "uvw"
expectEqual("uvw", acceptor[donor.startIndex...donor.index(_nth: 2)])
let r = donor.startIndex...donor.index(_nth: 3)
expectCrashLater()
_ = acceptor[r]
}
StringTests.test("ForeignIndexes/subscript(ClosedRange)/OutOfBoundsTrap/2") {
let donor = "abcdef"
let acceptor = "uvw"
expectEqual("uvw", acceptor[donor.startIndex...donor.index(_nth: 2)])
let r = donor.index(_nth: 3)...donor.index(_nth: 5)
expectCrashLater()
_ = acceptor[r]
}
StringTests.test("ForeignIndexes/replaceSubrange/OutOfBoundsTrap/1") {
let donor = "abcdef"
var acceptor = "uvw"
acceptor.replaceSubrange(
donor.startIndex..<donor.index(_nth: 1), with: "u")
expectEqual("uvw", acceptor)
let r = donor.startIndex..<donor.index(_nth: 4)
expectCrashLater()
acceptor.replaceSubrange(r, with: "")
}
StringTests.test("ForeignIndexes/replaceSubrange/OutOfBoundsTrap/2") {
let donor = "abcdef"
var acceptor = "uvw"
acceptor.replaceSubrange(
donor.startIndex..<donor.index(_nth: 1), with: "u")
expectEqual("uvw", acceptor)
let r = donor.index(_nth: 4)..<donor.index(_nth: 5)
expectCrashLater()
acceptor.replaceSubrange(r, with: "")
}
StringTests.test("ForeignIndexes/removeAt/OutOfBoundsTrap") {
do {
let donor = "abcdef"
var acceptor = "uvw"
let removed = acceptor.remove(at: donor.startIndex)
expectEqual("u", removed)
expectEqual("vw", acceptor)
}
let donor = "abcdef"
var acceptor = "uvw"
let i = donor.index(_nth: 4)
expectCrashLater()
acceptor.remove(at: i)
}
StringTests.test("ForeignIndexes/removeSubrange/OutOfBoundsTrap/1") {
do {
let donor = "abcdef"
var acceptor = "uvw"
acceptor.removeSubrange(
donor.startIndex..<donor.index(after: donor.startIndex))
expectEqual("vw", acceptor)
}
let donor = "abcdef"
var acceptor = "uvw"
let r = donor.startIndex..<donor.index(_nth: 4)
expectCrashLater()
acceptor.removeSubrange(r)
}
StringTests.test("ForeignIndexes/removeSubrange/OutOfBoundsTrap/2") {
let donor = "abcdef"
var acceptor = "uvw"
let r = donor.index(_nth: 4)..<donor.index(_nth: 5)
expectCrashLater()
acceptor.removeSubrange(r)
}
StringTests.test("hasPrefix")
.skip(.nativeRuntime("String.hasPrefix undefined without _runtime(_ObjC)"))
.code {
#if _runtime(_ObjC)
expectTrue("".hasPrefix(""))
expectFalse("".hasPrefix("a"))
expectTrue("a".hasPrefix(""))
expectTrue("a".hasPrefix("a"))
// U+0301 COMBINING ACUTE ACCENT
// U+00E1 LATIN SMALL LETTER A WITH ACUTE
expectFalse("abc".hasPrefix("a\u{0301}"))
expectFalse("a\u{0301}bc".hasPrefix("a"))
expectTrue("\u{00e1}bc".hasPrefix("a\u{0301}"))
expectTrue("a\u{0301}bc".hasPrefix("\u{00e1}"))
#else
expectUnreachable()
#endif
}
StringTests.test("literalConcatenation") {
do {
// UnicodeScalarLiteral + UnicodeScalarLiteral
var s = "1" + "2"
expectType(String.self, &s)
expectEqual("12", s)
}
do {
// UnicodeScalarLiteral + ExtendedGraphemeClusterLiteral
var s = "1" + "a\u{0301}"
expectType(String.self, &s)
expectEqual("1a\u{0301}", s)
}
do {
// UnicodeScalarLiteral + StringLiteral
var s = "1" + "xyz"
expectType(String.self, &s)
expectEqual("1xyz", s)
}
do {
// ExtendedGraphemeClusterLiteral + UnicodeScalar
var s = "a\u{0301}" + "z"
expectType(String.self, &s)
expectEqual("a\u{0301}z", s)
}
do {
// ExtendedGraphemeClusterLiteral + ExtendedGraphemeClusterLiteral
var s = "a\u{0301}" + "e\u{0302}"
expectType(String.self, &s)
expectEqual("a\u{0301}e\u{0302}", s)
}
do {
// ExtendedGraphemeClusterLiteral + StringLiteral
var s = "a\u{0301}" + "xyz"
expectType(String.self, &s)
expectEqual("a\u{0301}xyz", s)
}
do {
// StringLiteral + UnicodeScalar
var s = "xyz" + "1"
expectType(String.self, &s)
expectEqual("xyz1", s)
}
do {
// StringLiteral + ExtendedGraphemeClusterLiteral
var s = "xyz" + "a\u{0301}"
expectType(String.self, &s)
expectEqual("xyza\u{0301}", s)
}
do {
// StringLiteral + StringLiteral
var s = "xyz" + "abc"
expectType(String.self, &s)
expectEqual("xyzabc", s)
}
}
StringTests.test("substringDoesNotCopy/Swift3")
.xfail(.always("Swift 3 compatibility: Self-sliced Strings are copied"))
.code {
let size = 16
for sliceStart in [0, 2, 8, size] {
for sliceEnd in [0, 2, 8, sliceStart + 1] {
if sliceStart > size || sliceEnd > size || sliceEnd < sliceStart {
continue
}
var s0 = String(repeating: "x", count: size)
let originalIdentity = s0.bufferID
s0 = String(s0[s0.index(_nth: sliceStart)..<s0.index(_nth: sliceEnd)])
expectEqual(originalIdentity, s0.bufferID)
}
}
}
StringTests.test("substringDoesNotCopy/Swift4") {
let size = 16
for sliceStart in [0, 2, 8, size] {
for sliceEnd in [0, 2, 8, sliceStart + 1] {
if sliceStart > size || sliceEnd > size || sliceEnd < sliceStart {
continue
}
let s0 = String(repeating: "x", count: size)
let originalIdentity = s0.bufferID
let s1 = s0[s0.index(_nth: sliceStart)..<s0.index(_nth: sliceEnd)]
expectEqual(s1.bufferID, originalIdentity)
}
}
}
StringTests.test("appendToEmptyString") {
let x = "Bumfuzzle"
expectNil(x.bufferID)
// Appending to empty string literal should replace it.
var a1 = ""
a1 += x
expectNil(a1.bufferID)
// Appending to native string should keep the existing buffer.
var b1 = ""
b1.reserveCapacity(20)
let b1ID = b1.bufferID
b1 += x
expectEqual(b1.bufferID, b1ID)
// .append(_:) should have the same behavior as +=
var a2 = ""
a2.append(x)
expectNil(a2.bufferID)
var b2 = ""
b2.reserveCapacity(20)
let b2ID = b2.bufferID
b2.append(x)
expectEqual(b2.bufferID, b2ID)
}
StringTests.test("Swift3Slice/Empty") {
let size = 16
let s = String(repeating: "x", count: size)
expectNotNil(s.bufferID)
for i in 0 ... size {
let slice = s[s.index(_nth: i)..<s.index(_nth: i)]
// Empty substrings still have indices relative to their base and can refer
// to the whole string. If the whole string has storage, so should its
// substring.
expectNotNil(slice.bufferID)
}
}
StringTests.test("Swift3Slice/Full") {
let size = 16
let s = String(repeating: "x", count: size)
let slice = s[s.startIndex..<s.endIndex]
// Most Swift 3 substrings are extracted into their own buffer,
// but if the substring covers the full original string, it is used instead.
expectEqual(slice.bufferID, s.bufferID)
}
StringTests.test("appendToSubstring") {
for initialSize in 1..<16 {
for sliceStart in [0, 2, 8, initialSize] {
for sliceEnd in [0, 2, 8, sliceStart + 1] {
if sliceStart > initialSize || sliceEnd > initialSize ||
sliceEnd < sliceStart {
continue
}
var s0 = String(repeating: "x", count: initialSize)
s0 = String(s0[s0.index(_nth: sliceStart)..<s0.index(_nth: sliceEnd)])
s0 += "x"
expectEqual(
String(
repeating: "x",
count: sliceEnd - sliceStart + 1),
s0)
}
}
}
}
StringTests.test("appendToSubstringBug")
.xfail(.always("Swift 3 compatibility: Self-sliced Strings are copied"))
.code {
// String used to have a heap overflow bug when one attempted to append to a
// substring that pointed to the end of a string buffer.
//
// Unused capacity
// VVV
// String buffer [abcdefghijk ]
// ^ ^
// +----+
// Substring -----------+
//
// In the example above, there are only three elements of unused capacity.
// The bug was that the implementation mistakenly assumed 9 elements of
// unused capacity (length of the prefix "abcdef" plus truly unused elements
// at the end).
func stringWithUnusedCapacity() -> (String, Int) {
var s0 = String(repeating: "x", count: 17)
if s0.unusedCapacity == 0 { s0 += "y" }
let cap = s0.unusedCapacity
expectNotEqual(0, cap)
// This sorta checks for the original bug
expectEqual(
cap, String(s0[s0.index(_nth: 1)..<s0.endIndex]).unusedCapacity)
return (s0, cap)
}
do {
var (s, _) = { ()->(String, Int) in
let (s0, unused) = stringWithUnusedCapacity()
return (String(s0[s0.index(_nth: 5)..<s0.endIndex]), unused)
}()
let originalID = s.bufferID
// Appending to a String always results in storage that
// starts at the beginning of its native buffer
s += "z"
expectNotEqual(originalID, s.bufferID)
}
do {
var (s, _) = { ()->(Substring, Int) in
let (s0, unused) = stringWithUnusedCapacity()
return (s0[s0.index(_nth: 5)..<s0.endIndex], unused)
}()
let originalID = s.bufferID
// FIXME: Ideally, appending to a Substring with a unique buffer reference
// does not reallocate unless necessary. Today, however, it appears to do
// so unconditionally unless the slice falls at the beginning of its buffer.
s += "z"
expectNotEqual(originalID, s.bufferID)
}
// Try again at the beginning of the buffer
do {
var (s, unused) = { ()->(Substring, Int) in
let (s0, unused) = stringWithUnusedCapacity()
return (s0[...], unused)
}()
let originalID = s.bufferID
s += "z"
expectEqual(originalID, s.bufferID)
s += String(repeating: "z", count: unused - 1)
expectEqual(originalID, s.bufferID)
s += "."
expectNotEqual(originalID, s.bufferID)
unused += 0 // warning suppression
}
}
StringTests.test("COW/removeSubrange/start") {
var str = "12345678"
str.reserveCapacity(1024) // Ensure on heap
let literalIdentity = str.bufferID
// Check literal-to-heap reallocation.
do {
let slice = str
expectNotNil(literalIdentity)
expectEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
expectEqual("12345678", str)
expectEqual("12345678", slice)
// This mutation should reallocate the string.
str.removeSubrange(str.startIndex..<str.index(_nth: 1))
expectNotEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
let heapStrIdentity = str.bufferID
expectEqual("2345678", str)
expectEqual("12345678", slice)
// No more reallocations are expected.
str.removeSubrange(str.startIndex..<str.index(_nth: 1))
expectEqual(heapStrIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
expectEqual("345678", str)
expectEqual("12345678", slice)
}
// Check heap-to-heap reallocation.
expectEqual("345678", str)
do {
str.reserveCapacity(1024) // Ensure on heap
let heapStrIdentity1 = str.bufferID
let slice = str
expectNotNil(heapStrIdentity1)
expectEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("345678", str)
expectEqual("345678", slice)
// This mutation should reallocate the string.
str.removeSubrange(str.startIndex..<str.index(_nth: 1))
expectNotEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
let heapStrIdentity2 = str.bufferID
expectEqual("45678", str)
expectEqual("345678", slice)
// No more reallocations are expected.
str.removeSubrange(str.startIndex..<str.index(_nth: 1))
expectEqual(heapStrIdentity2, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("5678", str)
expectEqual("345678", slice)
}
}
StringTests.test("COW/removeSubrange/end") {
var str = "12345678"
str.reserveCapacity(1024) // Ensure on heap
let literalIdentity = str.bufferID
// Check literal-to-heap reallocation.
expectEqual("12345678", str)
do {
let slice = str
expectNotNil(literalIdentity)
expectEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
expectEqual("12345678", str)
expectEqual("12345678", slice)
// This mutation should reallocate the string.
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
expectNotEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
let heapStrIdentity = str.bufferID
expectEqual("1234567", str)
expectEqual("12345678", slice)
// No more reallocations are expected.
str.append("x")
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
expectEqual(heapStrIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
expectEqual("1234567", str)
expectEqual("12345678", slice)
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
str.append("x")
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
expectEqual(heapStrIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
expectEqual("123456", str)
expectEqual("12345678", slice)
}
// Check heap-to-heap reallocation.
expectEqual("123456", str)
do {
str.reserveCapacity(1024) // Ensure on heap
let heapStrIdentity1 = str.bufferID
let slice = str
expectNotNil(heapStrIdentity1)
expectEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("123456", str)
expectEqual("123456", slice)
// This mutation should reallocate the string.
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
expectNotEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
let heapStrIdentity = str.bufferID
expectEqual("12345", str)
expectEqual("123456", slice)
// No more reallocations are expected.
str.append("x")
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
expectEqual(heapStrIdentity, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("12345", str)
expectEqual("123456", slice)
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
str.append("x")
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
expectEqual(heapStrIdentity, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("1234", str)
expectEqual("123456", slice)
}
}
StringTests.test("COW/replaceSubrange/end") {
// Check literal-to-heap reallocation.
do {
var str = "12345678"
str.reserveCapacity(1024) // Ensure on heap
let literalIdentity = str.bufferID
var slice = str[str.startIndex..<str.index(_nth: 7)]
expectNotNil(literalIdentity)
expectEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
expectEqual("12345678", str)
expectEqual("1234567", slice)
// This mutation should reallocate the string.
slice.replaceSubrange(slice.endIndex..<slice.endIndex, with: "a")
expectNotEqual(literalIdentity, slice.bufferID)
expectEqual(literalIdentity, str.bufferID)
let heapStrIdentity = slice.bufferID
expectEqual("1234567a", slice)
expectEqual("12345678", str)
// No more reallocations are expected.
slice.replaceSubrange(
slice.index(_nthLast: 1)..<slice.endIndex, with: "b")
expectEqual(heapStrIdentity, slice.bufferID)
expectEqual(literalIdentity, str.bufferID)
expectEqual("1234567b", slice)
expectEqual("12345678", str)
}
// Check literal-to-heap reallocation.
do {
var str = "12345678"
let literalIdentity = str.bufferID
// Move the string to the heap.
str.reserveCapacity(32)
expectNotEqual(literalIdentity, str.bufferID)
let heapStrIdentity1 = str.bufferID
expectNotNil(heapStrIdentity1)
// FIXME: We have to use Swift 4's Substring to get the desired storage
// semantics; in Swift 3 mode, self-sliced strings get allocated a new
// buffer immediately.
var slice = str[str.startIndex..<str.index(_nth: 7)]
expectEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
// This mutation should reallocate the string.
slice.replaceSubrange(slice.endIndex..<slice.endIndex, with: "a")
expectNotEqual(heapStrIdentity1, slice.bufferID)
expectEqual(heapStrIdentity1, str.bufferID)
let heapStrIdentity2 = slice.bufferID
expectEqual("1234567a", slice)
expectEqual("12345678", str)
// No more reallocations are expected.
slice.replaceSubrange(
slice.index(_nthLast: 1)..<slice.endIndex, with: "b")
expectEqual(heapStrIdentity2, slice.bufferID)
expectEqual(heapStrIdentity1, str.bufferID)
expectEqual("1234567b", slice)
expectEqual("12345678", str)
}
}
func asciiString<
S: Sequence
>(_ content: S) -> String
where S.Iterator.Element == Character {
var s = String()
s.append(contentsOf: content)
expectTrue(s._classify()._isASCII)
return s
}
StringTests.test("stringGutsExtensibility")
.skip(.nativeRuntime("Foundation dependency"))
.code {
#if _runtime(_ObjC)
let ascii = UTF16.CodeUnit(UnicodeScalar("X").value)
let nonAscii = UTF16.CodeUnit(UnicodeScalar("é").value)
for k in 0..<3 {
for count in 1..<16 {
for boundary in 0..<count {
var x = (
k == 0 ? asciiString("b")
: k == 1 ? ("b" as NSString as String)
: ("b" as NSMutableString as String)
)
if k == 0 { expectTrue(x._guts.isFastUTF8) }
for i in 0..<count {
x.append(String(
decoding: repeatElement(i < boundary ? ascii : nonAscii, count: 3),
as: UTF16.self))
}
// Make sure we can append pure ASCII to wide storage
x.append(String(
decoding: repeatElement(ascii, count: 2), as: UTF16.self))
expectEqualSequence(
[UTF16.CodeUnit(UnicodeScalar("b").value)]
+ Array(repeatElement(ascii, count: 3*boundary))
+ repeatElement(nonAscii, count: 3*(count - boundary))
+ repeatElement(ascii, count: 2),
StringFauxUTF16Collection(x.utf16)
)
}
}
}
#else
expectUnreachable()
#endif
}
StringTests.test("stringGutsReserve")
.skip(.nativeRuntime("Foundation dependency"))
.code {
#if _runtime(_ObjC)
guard #available(macOS 10.13, iOS 11.0, tvOS 11.0, *) else { return }
for k in 0...7 {
var base: String
var startedNative: Bool
let shared: String = "X"
// Managed native, unmanaged native, or small
func isSwiftNative(_ s: String) -> Bool {
switch s._classify()._form {
case ._native: return true
case ._small: return true
case ._immortal: return true
default: return false
}
}
switch k {
case 0: (base, startedNative) = (String(), true)
case 1: (base, startedNative) = (asciiString("x"), true)
case 2: (base, startedNative) = ("Ξ", true)
#if arch(i386) || arch(arm)
case 3: (base, startedNative) = ("x" as NSString as String, false)
case 4: (base, startedNative) = ("x" as NSMutableString as String, false)
#else
case 3: (base, startedNative) = ("x" as NSString as String, true)
case 4: (base, startedNative) = ("x" as NSMutableString as String, true)
#endif
case 5: (base, startedNative) = (shared, true)
case 6: (base, startedNative) = ("xá" as NSString as String, false)
case 7: (base, startedNative) = ("xá" as NSMutableString as String, false)
default:
fatalError("case unhandled!")
}
expectEqual(isSwiftNative(base), startedNative)
let originalBuffer = base.bufferID
let isUnique = base._guts.isUniqueNative
let startedUnique =
startedNative &&
base._classify()._objectIdentifier != nil &&
isUnique
base.reserveCapacity(16)
// Now it's unique
// If it was already native and unique, no reallocation
if startedUnique && startedNative {
expectEqual(originalBuffer, base.bufferID)
}
else {
expectNotEqual(originalBuffer, base.bufferID)
}
// Reserving up to the capacity in a unique native buffer is a no-op
let nativeBuffer = base.bufferID
let currentCapacity = base.capacity
base.reserveCapacity(currentCapacity)
expectEqual(nativeBuffer, base.bufferID)
// Reserving more capacity should reallocate
base.reserveCapacity(currentCapacity + 1)
expectNotEqual(nativeBuffer, base.bufferID)
// None of this should change the string contents
var expected: String
switch k {
case 0: expected = ""
case 1,3,4: expected = "x"
case 2: expected = "Ξ"
case 5: expected = shared
case 6,7: expected = "xá"
default:
fatalError("case unhandled!")
}
expectEqual(expected, base)
}
#else
expectUnreachable()
#endif
}
func makeStringGuts(_ base: String) -> _StringGuts {
var x = String(_StringGuts())
// make sure some - but not all - replacements will have to grow the buffer
x.reserveCapacity(base._classify()._count * 3 / 2)
let capacity = x.capacity
x.append(base)
// Widening the guts should not make it lose its capacity,
// but the allocator may decide to get more storage.
expectGE(x.capacity, capacity)
return x._guts
}
StringTests.test("StringGutsReplace") {
let narrow = "01234567890"
let wide = "ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪ"
for s1 in [narrow, wide] {
for s2 in [narrow, wide] {
let g1 = makeStringGuts(s1)
let g2 = makeStringGuts(s2 + s2)
checkRangeReplaceable(
{ StringFauxUTF16Collection(g1) },
{ StringFauxUTF16Collection(g2)[0..<$0] }
)
checkRangeReplaceable(
{ StringFauxUTF16Collection(g1) },
{ Array(StringFauxUTF16Collection(g2))[0..<$0] }
)
}
}
}
StringTests.test("UnicodeScalarViewReplace") {
let narrow = "01234567890"
let wide = "ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪ"
for s1 in [narrow, wide] {
for s2 in [narrow, wide] {
let doubleS2 = Array(String(makeStringGuts(s2 + s2)).utf16)
checkRangeReplaceable(
{ () -> String.UnicodeScalarView in String(makeStringGuts(s1)).unicodeScalars },
{ String(decoding: doubleS2[0..<$0], as: UTF16.self).unicodeScalars }
)
checkRangeReplaceable(
{ String(makeStringGuts(s1)).unicodeScalars },
{ Array(String(makeStringGuts(s2 + s2)).unicodeScalars)[0..<$0] }
)
}
}
}
StringTests.test("StringRRC") {
let narrow = "01234567890"
let wide = "ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪ"
for s1 in [narrow, wide] {
for s2 in [narrow, wide] {
let doubleS2 = Array(String(makeStringGuts(s2 + s2)).utf16)
checkRangeReplaceable(
{ () -> String in String(makeStringGuts(s1)) },
{ String(decoding: doubleS2[0..<$0], as: UTF16.self) }
)
checkRangeReplaceable(
{ String(makeStringGuts(s1)) },
{ Array(String(makeStringGuts(s2 + s2)))[0..<$0] }
)
}
}
}
StringTests.test("reserveCapacity") {
var s = ""
let id0 = s.bufferID
let oldCap = s.capacity
let x: Character = "x" // Help the typechecker - <rdar://problem/17128913>
s.insert(contentsOf: repeatElement(x, count: s.capacity + 1), at: s.endIndex)
expectNotEqual(id0, s.bufferID)
s = ""
print("empty capacity \(s.capacity)")
s.reserveCapacity(oldCap + 2)
print("reserving \(oldCap + 2) [actual capacity: \(s.capacity)]")
let id1 = s.bufferID
s.insert(contentsOf: repeatElement(x, count: oldCap + 2), at: s.endIndex)
print("extending by \(oldCap + 2) [actual capacity: \(s.capacity)]")
expectEqual(id1, s.bufferID)
s.insert(contentsOf: repeatElement(x, count: s.capacity + 100), at: s.endIndex)
expectNotEqual(id1, s.bufferID)
}
StringTests.test("toInt") {
expectNil(Int(""))
expectNil(Int("+"))
expectNil(Int("-"))
expectEqual(20, Int("+20"))
expectEqual(0, Int("0"))
expectEqual(-20, Int("-20"))
expectNil(Int("-cc20"))
expectNil(Int(" -20"))
expectNil(Int(" \t 20ddd"))
expectEqual(Int.min, Int("\(Int.min)"))
expectEqual(Int.min + 1, Int("\(Int.min + 1)"))
expectEqual(Int.max, Int("\(Int.max)"))
expectEqual(Int.max - 1, Int("\(Int.max - 1)"))
expectNil(Int("\(Int.min)0"))
expectNil(Int("\(Int.max)0"))
// Make a String from an Int, mangle the String's characters,
// then print if the new String is or is not still an Int.
func testConvertabilityOfStringWithModification(
_ initialValue: Int,
modification: (_ chars: inout [UTF8.CodeUnit]) -> Void
) {
var chars = Array(String(initialValue).utf8)
modification(&chars)
let str = String(decoding: chars, as: UTF8.self)
expectNil(Int(str))
}
testConvertabilityOfStringWithModification(Int.min) {
$0[2] += 1; () // underflow by lots
}
testConvertabilityOfStringWithModification(Int.max) {
$0[1] += 1; () // overflow by lots
}
// Test values lower than min.
do {
let base = UInt(Int.max)
expectEqual(Int.min + 1, Int("-\(base)"))
expectEqual(Int.min, Int("-\(base + 1)"))
for i in 2..<20 {
expectNil(Int("-\(base + UInt(i))"))
}
}
// Test values greater than min.
do {
let base = UInt(Int.max)
for i in UInt(0)..<20 {
expectEqual(-Int(base - i) , Int("-\(base - i)"))
}
}
// Test values greater than max.
do {
let base = UInt(Int.max)
expectEqual(Int.max, Int("\(base)"))
for i in 1..<20 {
expectNil(Int("\(base + UInt(i))"))
}
}
// Test values lower than max.
do {
let base = Int.max
for i in 0..<20 {
expectEqual(base - i, Int("\(base - i)"))
}
}
}
// Make sure strings don't grow unreasonably quickly when appended-to
StringTests.test("growth") {
var s = ""
var s2 = s
for _ in 0..<20 {
s += "x"
s2 = s
}
expectEqual(s2, s)
expectLE(s.nativeCapacity, 40)
}
StringTests.test("Construction") {
expectEqual("abc", String(["a", "b", "c"] as [Character]))
}
StringTests.test("Conversions") {
// Whether we are natively ASCII or small ASCII
func isKnownASCII(_ s: String) -> Bool {
return s.byteWidth == 1
}
do {
let c: Character = "a"
let x = String(c)
expectTrue(isKnownASCII(x))
let s: String = "a"
expectEqual(s, x)
}
do {
let c: Character = "\u{B977}"
let x = String(c)
expectFalse(isKnownASCII(x))
let s: String = "\u{B977}"
expectEqual(s, x)
}
}
#if os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
import Glibc
#endif
StringTests.test("lowercased()") {
// Use setlocale so tolower() is correct on ASCII.
setlocale(LC_ALL, "C")
// Check the ASCII domain.
let asciiDomain: [Int32] = Array(0..<128)
expectEqualFunctionsForDomain(
asciiDomain,
{ String(UnicodeScalar(Int(tolower($0)))!) },
{ String(UnicodeScalar(Int($0))!).lowercased() })
expectEqual("", "".lowercased())
expectEqual("abcd", "abCD".lowercased())
expectEqual("абвг", "абВГ".lowercased())
expectEqual("たちつてと", "たちつてと".lowercased())
//
// Special casing.
//
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
expectEqual("\u{0069}\u{0307}", "\u{0130}".lowercased())
// U+0049 LATIN CAPITAL LETTER I
// U+0307 COMBINING DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
expectEqual("\u{0069}\u{0307}", "\u{0049}\u{0307}".lowercased())
}
StringTests.test("uppercased()") {
// Use setlocale so toupper() is correct on ASCII.
setlocale(LC_ALL, "C")
// Check the ASCII domain.
let asciiDomain: [Int32] = Array(0..<128)
expectEqualFunctionsForDomain(
asciiDomain,
{ String(UnicodeScalar(Int(toupper($0)))!) },
{ String(UnicodeScalar(Int($0))!).uppercased() })
expectEqual("", "".uppercased())
expectEqual("ABCD", "abCD".uppercased())
expectEqual("АБВГ", "абВГ".uppercased())
expectEqual("たちつてと", "たちつてと".uppercased())
//
// Special casing.
//
// U+0069 LATIN SMALL LETTER I
// to upper case:
// U+0049 LATIN CAPITAL LETTER I
expectEqual("\u{0049}", "\u{0069}".uppercased())
// U+00DF LATIN SMALL LETTER SHARP S
// to upper case:
// U+0053 LATIN CAPITAL LETTER S
// U+0073 LATIN SMALL LETTER S
// But because the whole string is converted to uppercase, we just get two
// U+0053.
expectEqual("\u{0053}\u{0053}", "\u{00df}".uppercased())
// U+FB01 LATIN SMALL LIGATURE FI
// to upper case:
// U+0046 LATIN CAPITAL LETTER F
// U+0069 LATIN SMALL LETTER I
// But because the whole string is converted to uppercase, we get U+0049
// LATIN CAPITAL LETTER I.
expectEqual("\u{0046}\u{0049}", "\u{fb01}".uppercased())
}
StringTests.test("unicodeViews") {
// Check the UTF views work with slicing
// U+FFFD REPLACEMENT CHARACTER
// U+1F3C2 SNOWBOARDER
// U+2603 SNOWMAN
let winter = "\u{1F3C2}\u{2603}"
// slices
// First scalar is 4 bytes long, so this should be invalid
expectNil(
String(winter.utf8[
winter.utf8.startIndex
..<
winter.utf8.index(after: winter.utf8.index(after: winter.utf8.startIndex))
]))
/*
// FIXME: note changed String(describing:) results
expectEqual(
"\u{FFFD}",
String(describing:
winter.utf8[
winter.utf8.startIndex
..<
winter.utf8.index(after: winter.utf8.index(after: winter.utf8.startIndex))
]))
*/
expectEqual(
"\u{1F3C2}", String(
winter.utf8[winter.utf8.startIndex..<winter.utf8.index(_nth: 4)]))
expectEqual(
"\u{1F3C2}", String(
winter.utf16[winter.utf16.startIndex..<winter.utf16.index(_nth: 2)]))
expectEqual(
"\u{1F3C2}", String(
winter.unicodeScalars[
winter.unicodeScalars.startIndex..<winter.unicodeScalars.index(_nth: 1)
]))
// views
expectEqual(
winter, String(
winter.utf8[winter.utf8.startIndex..<winter.utf8.index(_nth: 7)]))
expectEqual(
winter, String(
winter.utf16[winter.utf16.startIndex..<winter.utf16.index(_nth: 3)]))
expectEqual(
winter, String(
winter.unicodeScalars[
winter.unicodeScalars.startIndex..<winter.unicodeScalars.index(_nth: 2)
]))
let ga = "\u{304b}\u{3099}"
expectEqual(ga, String(ga.utf8[ga.utf8.startIndex..<ga.utf8.index(_nth: 6)]))
}
// Validate that index conversion does something useful for Cocoa
// programmers.
StringTests.test("indexConversion")
.skip(.nativeRuntime("Foundation dependency"))
.code {
#if _runtime(_ObjC)
let re : NSRegularExpression
do {
re = try NSRegularExpression(
pattern: "([^ ]+)er", options: NSRegularExpression.Options())
} catch { fatalError("couldn't build regexp: \(error)") }
let s = "go further into the larder to barter."
var matches: [String] = []
re.enumerateMatches(
in: s, options: NSRegularExpression.MatchingOptions(), range: NSRange(0..<s.utf16.count)
) {
result, flags, stop
in
let r = result!.range(at: 1)
let start = String.Index(encodedOffset: r.location)
let end = String.Index(encodedOffset: r.location + r.length)
matches.append(String(s.utf16[start..<end])!)
}
expectEqual(["furth", "lard", "bart"], matches)
#else
expectUnreachable()
#endif
}
StringTests.test("String.append(_: UnicodeScalar)") {
var s = ""
do {
// U+0061 LATIN SMALL LETTER A
let input: UnicodeScalar = "\u{61}"
s.append(String(input))
expectEqual(["\u{61}"], Array(s.unicodeScalars))
}
do {
// U+304B HIRAGANA LETTER KA
let input: UnicodeScalar = "\u{304b}"
s.append(String(input))
expectEqual(["\u{61}", "\u{304b}"], Array(s.unicodeScalars))
}
do {
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
let input: UnicodeScalar = "\u{3099}"
s.append(String(input))
expectEqual(["\u{61}", "\u{304b}", "\u{3099}"], Array(s.unicodeScalars))
}
do {
// U+1F425 FRONT-FACING BABY CHICK
let input: UnicodeScalar = "\u{1f425}"
s.append(String(input))
expectEqual(
["\u{61}", "\u{304b}", "\u{3099}", "\u{1f425}"],
Array(s.unicodeScalars))
}
}
StringTests.test("String.append(_: Character)") {
let baseCharacters: [Character] = [
// U+0061 LATIN SMALL LETTER A
"\u{61}",
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
"\u{304b}\u{3099}",
// U+3072 HIRAGANA LETTER HI
// U+309A COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
"\u{3072}\u{309A}",
// U+1F425 FRONT-FACING BABY CHICK
"\u{1f425}",
// U+0061 LATIN SMALL LETTER A
// U+0300 COMBINING GRAVE ACCENT
// U+0301 COMBINING ACUTE ACCENT
"\u{61}\u{0300}\u{0301}",
// U+0061 LATIN SMALL LETTER A
// U+0300 COMBINING GRAVE ACCENT
// U+0301 COMBINING ACUTE ACCENT
// U+0302 COMBINING CIRCUMFLEX ACCENT
"\u{61}\u{0300}\u{0301}\u{0302}",
// U+0061 LATIN SMALL LETTER A
// U+0300 COMBINING GRAVE ACCENT
// U+0301 COMBINING ACUTE ACCENT
// U+0302 COMBINING CIRCUMFLEX ACCENT
// U+0303 COMBINING TILDE
"\u{61}\u{0300}\u{0301}\u{0302}\u{0303}",
]
let baseStrings = [""] + baseCharacters.map { String($0) }
for baseIdx in baseStrings.indices {
for prefix in ["", " "] {
let base = baseStrings[baseIdx]
for inputIdx in baseCharacters.indices {
let input = (prefix + String(baseCharacters[inputIdx])).last!
var s = base
s.append(input)
expectEqualSequence(
Array(base) + [input],
Array(s),
"baseIdx=\(baseIdx) inputIdx=\(inputIdx)")
}
}
}
}
internal func decodeCString<
C : UnicodeCodec
>(_ s: String, as codec: C.Type)
-> (result: String, repairsMade: Bool)? {
let units = s.unicodeScalars.map({ $0.value }) + [0]
return units.map({ C.CodeUnit($0) }).withUnsafeBufferPointer {
String.decodeCString($0.baseAddress, as: C.self)
}
}
StringTests.test("String.decodeCString/UTF8") {
let actual = decodeCString("foobar", as: UTF8.self)
expectFalse(actual!.repairsMade)
expectEqual("foobar", actual!.result)
}
StringTests.test("String.decodeCString/UTF16") {
let actual = decodeCString("foobar", as: UTF16.self)
expectFalse(actual!.repairsMade)
expectEqual("foobar", actual!.result)
}
StringTests.test("String.decodeCString/UTF32") {
let actual = decodeCString("foobar", as: UTF32.self)
expectFalse(actual!.repairsMade)
expectEqual("foobar", actual!.result)
}
internal struct ReplaceSubrangeTest {
let original: String
let newElements: String
let rangeSelection: RangeSelection
let expected: String
let closedExpected: String?
let loc: SourceLoc
internal init(
original: String, newElements: String,
rangeSelection: RangeSelection, expected: String, closedExpected: String? = nil,
file: String = #file, line: UInt = #line
) {
self.original = original
self.newElements = newElements
self.rangeSelection = rangeSelection
self.expected = expected
self.closedExpected = closedExpected
self.loc = SourceLoc(file, line, comment: "replaceSubrange() test data")
}
}
internal struct RemoveSubrangeTest {
let original: String
let rangeSelection: RangeSelection
let expected: String
let closedExpected: String
let loc: SourceLoc
internal init(
original: String, rangeSelection: RangeSelection, expected: String,
closedExpected: String? = nil,
file: String = #file, line: UInt = #line
) {
self.original = original
self.rangeSelection = rangeSelection
self.expected = expected
self.closedExpected = closedExpected ?? expected
self.loc = SourceLoc(file, line, comment: "replaceSubrange() test data")
}
}
let replaceSubrangeTests = [
ReplaceSubrangeTest(
original: "",
newElements: "",
rangeSelection: .emptyRange,
expected: ""
),
ReplaceSubrangeTest(
original: "",
newElements: "meela",
rangeSelection: .emptyRange,
expected: "meela"
),
ReplaceSubrangeTest(
original: "eela",
newElements: "m",
rangeSelection: .leftEdge,
expected: "meela",
closedExpected: "mela"
),
ReplaceSubrangeTest(
original: "meel",
newElements: "a",
rangeSelection: .rightEdge,
expected: "meela",
closedExpected: "meea"
),
ReplaceSubrangeTest(
original: "a",
newElements: "meel",
rangeSelection: .leftEdge,
expected: "meela",
closedExpected: "meel"
),
ReplaceSubrangeTest(
original: "m",
newElements: "eela",
rangeSelection: .rightEdge,
expected: "meela",
closedExpected: "eela"
),
ReplaceSubrangeTest(
original: "alice",
newElements: "bob",
rangeSelection: .offsets(1, 1),
expected: "aboblice",
closedExpected: "abobice"
),
ReplaceSubrangeTest(
original: "alice",
newElements: "bob",
rangeSelection: .offsets(1, 2),
expected: "abobice",
closedExpected: "abobce"
),
ReplaceSubrangeTest(
original: "alice",
newElements: "bob",
rangeSelection: .offsets(1, 3),
expected: "abobce",
closedExpected: "abobe"
),
ReplaceSubrangeTest(
original: "alice",
newElements: "bob",
rangeSelection: .offsets(1, 4),
expected: "abobe",
closedExpected: "abob"
),
ReplaceSubrangeTest(
original: "alice",
newElements: "bob",
rangeSelection: .offsets(1, 5),
expected: "abob"
),
ReplaceSubrangeTest(
original: "bob",
newElements: "meela",
rangeSelection: .offsets(1, 2),
expected: "bmeelab",
closedExpected: "bmeela"
),
ReplaceSubrangeTest(
original: "bobbobbobbobbobbobbobbobbobbob",
newElements: "meela",
rangeSelection: .offsets(1, 2),
expected: "bmeelabbobbobbobbobbobbobbobbobbob",
closedExpected: "bmeelabobbobbobbobbobbobbobbobbob"
),
ReplaceSubrangeTest(
original: "bob",
newElements: "meelameelameelameelameela",
rangeSelection: .offsets(1, 2),
expected: "bmeelameelameelameelameelab",
closedExpected: "bmeelameelameelameelameela"
),
]
let removeSubrangeTests = [
RemoveSubrangeTest(
original: "",
rangeSelection: .emptyRange,
expected: ""
),
RemoveSubrangeTest(
original: "a",
rangeSelection: .middle,
expected: ""
),
RemoveSubrangeTest(
original: "perdicus",
rangeSelection: .leftHalf,
expected: "icus"
),
RemoveSubrangeTest(
original: "perdicus",
rangeSelection: .rightHalf,
expected: "perd"
),
RemoveSubrangeTest(
original: "alice",
rangeSelection: .middle,
expected: "ae"
),
RemoveSubrangeTest(
original: "perdicus",
rangeSelection: .middle,
expected: "pes"
),
RemoveSubrangeTest(
original: "perdicus",
rangeSelection: .offsets(1, 2),
expected: "prdicus",
closedExpected: "pdicus"
),
RemoveSubrangeTest(
original: "perdicus",
rangeSelection: .offsets(3, 6),
expected: "perus",
closedExpected: "pers"
),
RemoveSubrangeTest(
original: "perdicusaliceandbob",
rangeSelection: .offsets(3, 6),
expected: "perusaliceandbob",
closedExpected: "persaliceandbob"
)
]
StringTests.test("String.replaceSubrange()/characters/range") {
for test in replaceSubrangeTests {
var theString = test.original
let c = test.original
let rangeToReplace = test.rangeSelection.range(in: c)
let newCharacters : [Character] = Array(test.newElements)
theString.replaceSubrange(rangeToReplace, with: newCharacters)
expectEqual(
test.expected,
theString,
stackTrace: SourceLocStack().with(test.loc))
// Test unique-native optimized path
var uniqNative = String(Array(test.original))
uniqNative.replaceSubrange(rangeToReplace, with: newCharacters)
expectEqual(theString, uniqNative,
stackTrace: SourceLocStack().with(test.loc))
}
}
StringTests.test("String.replaceSubrange()/string/range") {
for test in replaceSubrangeTests {
var theString = test.original
let c = test.original
let rangeToReplace = test.rangeSelection.range(in: c)
theString.replaceSubrange(rangeToReplace, with: test.newElements)
expectEqual(
test.expected,
theString,
stackTrace: SourceLocStack().with(test.loc))
// Test unique-native optimized path
var uniqNative = String(Array(test.original))
uniqNative.replaceSubrange(rangeToReplace, with: test.newElements)
expectEqual(theString, uniqNative,
stackTrace: SourceLocStack().with(test.loc))
}
}
StringTests.test("String.replaceSubrange()/characters/closedRange") {
for test in replaceSubrangeTests {
guard let closedExpected = test.closedExpected else {
continue
}
var theString = test.original
let c = test.original
let rangeToReplace = test.rangeSelection.closedRange(in: c)
let newCharacters = Array(test.newElements)
theString.replaceSubrange(rangeToReplace, with: newCharacters)
expectEqual(
closedExpected,
theString,
stackTrace: SourceLocStack().with(test.loc))
// Test unique-native optimized path
var uniqNative = String(Array(test.original))
uniqNative.replaceSubrange(rangeToReplace, with: newCharacters)
expectEqual(theString, uniqNative,
stackTrace: SourceLocStack().with(test.loc))
}
}
StringTests.test("String.replaceSubrange()/string/closedRange") {
for test in replaceSubrangeTests {
guard let closedExpected = test.closedExpected else {
continue
}
var theString = test.original
let c = test.original
let rangeToReplace = test.rangeSelection.closedRange(in: c)
theString.replaceSubrange(rangeToReplace, with: test.newElements)
expectEqual(
closedExpected,
theString,
stackTrace: SourceLocStack().with(test.loc))
// Test unique-native optimized path
var uniqNative = String(Array(test.original))
uniqNative.replaceSubrange(rangeToReplace, with: test.newElements)
expectEqual(theString, uniqNative,
stackTrace: SourceLocStack().with(test.loc))
}
}
StringTests.test("String.removeSubrange()/range") {
for test in removeSubrangeTests {
var theString = test.original
let c = test.original
let rangeToRemove = test.rangeSelection.range(in: c)
theString.removeSubrange(rangeToRemove)
expectEqual(
test.expected,
theString,
stackTrace: SourceLocStack().with(test.loc))
// Test unique-native optimized path
var uniqNative = String(Array(test.original))
uniqNative.removeSubrange(rangeToRemove)
expectEqual(theString, uniqNative,
stackTrace: SourceLocStack().with(test.loc))
}
}
StringTests.test("String.removeSubrange()/closedRange") {
for test in removeSubrangeTests {
switch test.rangeSelection {
case .emptyRange: continue
default: break
}
var theString = test.original
let c = test.original
let rangeToRemove = test.rangeSelection.closedRange(in: c)
theString.removeSubrange(rangeToRemove)
expectEqual(
test.closedExpected,
theString,
stackTrace: SourceLocStack().with(test.loc))
// Test unique-native optimized path
var uniqNative = String(Array(test.original))
uniqNative.removeSubrange(rangeToRemove)
expectEqual(theString, uniqNative,
stackTrace: SourceLocStack().with(test.loc))
}
}
//===----------------------------------------------------------------------===//
// COW(🐄) tests
//===----------------------------------------------------------------------===//
public let testSuffix = "z"
StringTests.test("COW.Smoke") {
var s1 = "COW Smoke Cypseloides" + testSuffix
let identity1 = s1._rawIdentifier()
var s2 = s1
expectEqual(identity1, s2._rawIdentifier())
s2.append(" cryptus")
expectTrue(identity1 != s2._rawIdentifier())
s1.remove(at: s1.startIndex)
expectEqual(identity1, s1._rawIdentifier())
_fixLifetime(s1)
_fixLifetime(s2)
}
struct COWStringTest {
let test: String
let name: String
}
var testCases: [COWStringTest] {
return [ COWStringTest(test: "abcdefghijklmnopqrxtuvwxyz", name: "ASCII"),
COWStringTest(test: "🐮🐄🤠👢🐴", name: "Unicode")
]
}
for test in testCases {
StringTests.test("COW.\(test.name).IndexesDontAffectUniquenessCheck") {
let s = test.test + testSuffix
let identity1 = s._rawIdentifier()
let startIndex = s.startIndex
let endIndex = s.endIndex
expectNotEqual(startIndex, endIndex)
expectLT(startIndex, endIndex)
expectLE(startIndex, endIndex)
expectGT(endIndex, startIndex)
expectGE(endIndex, startIndex)
expectEqual(identity1, s._rawIdentifier())
// Keep indexes alive during the calls above
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
}
for test in testCases {
StringTests.test("COW.\(test.name).SubscriptWithIndexDoesNotReallocate") {
let s = test.test + testSuffix
let identity1 = s._rawIdentifier()
let startIndex = s.startIndex
let empty = startIndex == s.endIndex
expectNotEqual((s.startIndex < s.endIndex), empty)
expectLE(s.startIndex, s.endIndex)
expectEqual((s.startIndex >= s.endIndex), empty)
expectGT(s.endIndex, s.startIndex)
expectEqual(identity1, s._rawIdentifier())
}
}
for test in testCases {
StringTests.test("COW.\(test.name).RemoveAtDoesNotReallocate") {
do {
var s = test.test + testSuffix
let identity1 = s._rawIdentifier()
let index1 = s.startIndex
expectEqual(identity1, s._rawIdentifier())
let _ = s.remove(at: index1)
expectEqual(identity1, s._rawIdentifier())
}
do {
let s1 = test.test + testSuffix
let identity1 = s1._rawIdentifier()
var s2 = s1
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
let index1 = s1.startIndex
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
let _ = s2.remove(at: index1)
expectEqual(identity1, s1._rawIdentifier())
expectTrue(identity1 == s2._rawIdentifier())
}
}
}
for test in testCases {
StringTests.test("COW.\(test.name).RemoveAtDoesNotReallocate") {
do {
var s = test.test + testSuffix
expectGT(s.count, 0)
s.removeAll()
let identity1 = s._rawIdentifier()
expectEqual(0, s.count)
expectEqual(identity1, s._rawIdentifier())
}
do {
var s = test.test + testSuffix
let identity1 = s._rawIdentifier()
expectGT(s.count, 3)
s.removeAll(keepingCapacity: true)
expectEqual(identity1, s._rawIdentifier())
expectEqual(0, s.count)
}
do {
let s1 = test.test + testSuffix
let identity1 = s1._rawIdentifier()
expectGT(s1.count, 0)
var s2 = s1
s2.removeAll()
let identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectTrue(identity2 != identity1)
expectGT(s1.count, 0)
expectEqual(0, s2.count)
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
do {
let s1 = test.test + testSuffix
let identity1 = s1._rawIdentifier()
expectGT(s1.count, 0)
var s2 = s1
s2.removeAll(keepingCapacity: true)
let identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectTrue(identity2 != identity1)
expectGT(s1.count, 0)
expectEqual(0, s2.count)
// Keep variables alive.
_fixLifetime(s1)
_fixLifetime(s2)
}
}
}
for test in testCases {
StringTests.test("COW.\(test.name).CountDoesNotReallocate") {
let s = test.test + testSuffix
let identity1 = s._rawIdentifier()
expectGT(s.count, 0)
expectEqual(identity1, s._rawIdentifier())
}
}
for test in testCases {
StringTests.test("COW.\(test.name).GenerateDoesNotReallocate") {
let s = test.test + testSuffix
let identity1 = s._rawIdentifier()
var iter = s.makeIterator()
var copy = String()
while let value = iter.next() {
copy.append(value)
}
expectEqual(copy, s)
expectEqual(identity1, s._rawIdentifier())
}
}
for test in testCases {
StringTests.test("COW.\(test.name).EqualityTestDoesNotReallocate") {
let s1 = test.test + testSuffix
let identity1 = s1._rawIdentifier()
var s2 = test.test + testSuffix
let identity2 = s2._rawIdentifier()
expectEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity2, s2._rawIdentifier())
s2.remove(at: s2.startIndex)
expectNotEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity2, s2._rawIdentifier())
}
}
enum _Ordering: Int, Equatable {
case less = -1
case equal = 0
case greater = 1
var flipped: _Ordering {
switch self {
case .less: return .greater
case .equal: return .equal
case .greater: return .less
}
}
init(signedNotation int: Int) {
self = int < 0 ? .less : int == 0 ? .equal : .greater
}
}
struct ComparisonTestCase {
var strings: [String]
// var test: (String, String) -> Void
var comparison: _Ordering
init(_ strings: [String], _ comparison: _Ordering) {
self.strings = strings
self.comparison = comparison
}
func test() {
for pair in zip(strings, strings[1...]) {
switch comparison {
case .less:
expectLT(pair.0, pair.1)
case .greater:
expectGT(pair.0, pair.1)
case .equal:
expectEqual(pair.0, pair.1)
}
}
}
func testOpaqueStrings() {
#if _runtime(_ObjC)
let opaqueStrings = strings.map { NSSlowString(string: $0) as String }
for pair in zip(opaqueStrings, opaqueStrings[1...]) {
switch comparison {
case .less:
expectLT(pair.0, pair.1)
case .greater:
expectGT(pair.0, pair.1)
case .equal:
expectEqual(pair.0, pair.1)
}
}
#endif
}
func testOpaqueSubstrings() {
#if _runtime(_ObjC)
for pair in zip(strings, strings[1...]) {
let string1 = pair.0.dropLast()
let string2 = pair.1
let opaqueString = (NSSlowString(string: pair.0) as String).dropLast()
guard string1.count > 0 else { return }
let expectedResult: _Ordering = string1 < string2 ? .less : (string1 > string2 ? .greater : .equal)
let opaqueResult: _Ordering = opaqueString < string2 ? .less : (opaqueString > string2 ? .greater : .equal)
expectEqual(opaqueResult, expectedResult)
}
#endif
}
}
let comparisonTestCases = [
ComparisonTestCase(["a", "a"], .equal),
ComparisonTestCase(["abcdefg", "abcdefg"], .equal),
ComparisonTestCase(["", "Z", "a", "b", "c", "\u{00c5}", "á"], .less),
ComparisonTestCase(["ábcdefg", "ábcdefgh", "ábcdefghi"], .less),
ComparisonTestCase(["abcdefg", "abcdefgh", "abcdefghi"], .less),
ComparisonTestCase(["á", "\u{0061}\u{0301}"], .equal),
ComparisonTestCase(["à", "\u{0061}\u{0301}", "â", "\u{e3}", "a\u{0308}"], .less),
// Exploding scalars AND exploding segments
ComparisonTestCase(["\u{fa2}", "\u{fa1}\u{fb7}"], .equal),
ComparisonTestCase([
"\u{fa2}\u{fa2}\u{fa2}\u{fa2}",
"\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}"
], .equal),
ComparisonTestCase([
"\u{fa2}\u{fa2}\u{fa2}\u{fa2}\u{fa2}\u{fa2}\u{fa2}\u{fa2}",
"\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}"
], .equal),
ComparisonTestCase([
"a\u{fa2}\u{fa2}a\u{fa2}\u{fa2}\u{fa2}\u{fa2}\u{fa2}\u{fa2}",
"a\u{fa1}\u{fb7}\u{fa1}\u{fb7}a\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}"
], .equal),
ComparisonTestCase(["a\u{301}\u{0301}", "\u{e1}"], .greater),
ComparisonTestCase(["😀", "😀"], .equal),
ComparisonTestCase(["\u{2f9df}", "\u{8f38}"], .equal),
ComparisonTestCase([
"a",
"\u{2f9df}", // D87E DDDF as written, but normalizes to 8f38
"\u{2f9df}\u{2f9df}", // D87E DDDF as written, but normalizes to 8f38
"👨🏻", // D83D DC68 D83C DFFB
"👨🏻⚕️", // D83D DC68 D83C DFFB 200D 2695 FE0F
"👩⚕️", // D83D DC69 200D 2695 FE0F
"👩🏾", // D83D DC69 D83C DFFE
"👩🏾⚕", // D83D DC69 D83C DFFE 200D 2695 FE0F
"😀", // D83D DE00
"😅", // D83D DE05
"🧀" // D83E DDC0 -- aka a really big scalar
], .less),
ComparisonTestCase(["f̛̗̘̙̜̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦ͘͜͟͢͝͞͠͡", "ơ̗̘̙̜̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͥͦͧͨͩͪͫͬͭͮ͘"], .less),
ComparisonTestCase(["\u{f90b}", "\u{5587}"], .equal),
ComparisonTestCase(["a\u{1D160}a", "a\u{1D158}\u{1D1C7}"], .less),
ComparisonTestCase(["\u{212b}", "\u{00c5}"], .equal),
ComparisonTestCase([
"A",
"a",
"aa",
"ae",
"ae🧀",
"az",
"aze\u{300}",
"ae\u{301}",
"ae\u{301}ae\u{301}",
"ae\u{301}ae\u{301}ae\u{301}",
"ae\u{301}ae\u{301}ae\u{301}ae\u{301}",
"ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}",
"ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}",
"ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}",
"ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}",
"ae\u{302}",
"ae\u{302}{303}",
"ae\u{302}🧀",
"ae\u{303}",
"\u{f90b}\u{f90c}\u{f90d}", // Normalizes to BMP scalars
"\u{FFEE}", // half width CJK dot
"🧀", // D83E DDC0 -- aka a really big scalar
], .less),
ComparisonTestCase(["ư̴̵̶̷̸̗̘̙̜̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡", "ì̡̢̧̨̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̹̺̻̼͇͈͉͍͎́̂̃̄̉̊̋̌̍̎̏̐̑̒̓̽̾̿̀́͂̓̈́͆͊͋͌ͅ͏͓͔͕͖͙͐͑͒͗ͬͭͮ͘"], .greater),
ComparisonTestCase(["ư̴̵̶̷̸̗̘̙̜̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡", "aì̡̢̧̨̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̹̺̻̼͇͈͉͍͎́̂̃̄̉̊̋̌̍̎̏̐̑̒̓̽̾̿̀́͂̓̈́͆͊͋͌ͅ͏͓͔͕͖͙͐͑͒͗ͬͭͮ͘"], .greater),
ComparisonTestCase(["ì̡̢̧̨̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̹̺̻̼͇͈͉͍͎́̂̃̄̉̊̋̌̍̎̏̐̑̒̓̽̾̿̀́͂̓̈́͆͊͋͌ͅ͏͓͔͕͖͙͐͑͒͗ͬͭͮ͘", "ì̡̢̧̨̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̹̺̻̼͇͈͉͍͎́̂̃̄̉̊̋̌̍̎̏̐̑̒̓̽̾̿̀́͂̓̈́͆͊͋͌ͅ͏͓͔͕͖͙͐͑͒͗ͬͭͮ͘"], .equal)
]
for test in comparisonTestCases {
StringTests.test("Comparison.\(test.strings)") {
test.test()
}
StringTests.test("Comparison.OpaqueString.\(test.strings)")
.skip(.linuxAny(reason: "NSSlowString requires ObjC interop"))
.code {
test.testOpaqueStrings()
}
StringTests.test("Comparison.OpaqueSubstring.\(test.strings)")
.skip(.linuxAny(reason: "NSSlowString requires ObjC interop"))
.code {
test.testOpaqueSubstrings()
}
}
runAllTests()
| c3b2ac9691b747a7b84a2a2ff1fbdd1f | 27.881061 | 184 | 0.649191 | false | true | false | false |
pyromobile/nubomedia-ouatclient-src | refs/heads/master | ios/LiveTales-smartphones/uoat/AccesoriesMgr.swift | apache-2.0 | 2 | //
// AccesoriesMgr.swift
// uoat
//
// Created by Pyro User on 18/8/16.
// Copyright © 2016 Zed. All rights reserved.
//
import Foundation
class AccesoriesMgr
{
static func getInstance()->AccesoriesMgr
{
return AccesoriesMgr.instance!
}
static func create(isHD:Bool)
{
AccesoriesMgr.instance = AccesoriesMgr( isHD:isHD )
AccesoriesMgr.instance?.load()
}
func getAll() -> [String:[Complement]]
{
return self.accesoriesByPack
}
func getByPack(pack:String) -> [Complement]
{
return self.accesoriesByPack[pack]!
}
/*=============================================================*/
/* Private Section */
/*=============================================================*/
private init(isHD:Bool)
{
self.isHD = isHD
self.accesoriesByPack = [String:[Complement]]()
}
private func load()
{
//let fm = NSFileManager.defaultManager()
let talesPath = NSBundle.mainBundle().pathsForResourcesOfType("", inDirectory: "Res/tales/")
for talePath in talesPath
{
let file = talePath+"/description.json"
do
{
let fileContent = try NSString(contentsOfFile: file, encoding: NSUTF8StringEncoding )
let fc = fileContent as String!
self.processComplements( fc )
}
catch let error as NSError
{
print( "Failed to load: \(error.localizedDescription)" )
}
}
}
private func processComplements( description:String )
{
let complement:AnyObject = self.getJSON( description )!
let id:String = complement["id"] as! String
let complements = complement["complements"] as! [String]
let resolutionPath = (self.isHD) ? "/" : "/sd/"
self.accesoriesByPack[id] = [Complement]()
for complementId:String in complements
{
let imagePath = NSBundle.mainBundle().pathForResource( "\(complementId)", ofType: "png", inDirectory: "Res/tales/\(id)/complements\(resolutionPath)" )
let complement = Complement( id:complementId, imagePath:imagePath!, pack:id )
self.accesoriesByPack[id]?.append( complement )
}
}
private func getJSON(stringJSON:String)->AnyObject?
{
let json:AnyObject?;
do
{
let data = stringJSON.dataUsingEncoding( NSUTF8StringEncoding, allowLossyConversion: false );
json = try NSJSONSerialization.JSONObjectWithData( data!, options: .AllowFragments );
}
catch let error as NSError
{
print( "Failed to load: \(error.localizedDescription)" );
json = nil;
}
return json;
}
private static var instance:AccesoriesMgr? = nil
private var accesoriesByPack:[String:[Complement]]
private var isHD:Bool
} | 10aebc65d4231debe4216b2210aa2ff9 | 28.990196 | 162 | 0.547744 | false | false | false | false |
richardpiazza/SOSwift | refs/heads/master | Sources/SOSwift/ItemListOrMusicRecording.swift | mit | 1 | import Foundation
import CodablePlus
public enum ItemListOrMusicRecording: Codable {
case itemList(value: ItemList)
case musicRecording(value: MusicRecording)
public init(_ value: ItemList) {
self = .itemList(value: value)
}
public init(_ value: MusicRecording) {
self = .musicRecording(value: value)
}
public init(from decoder: Decoder) throws {
let jsonContainer = try decoder.container(keyedBy: DictionaryKeys.self)
let dictionary = try jsonContainer.decode(Dictionary<String, Any>.self)
guard let type = dictionary[SchemaKeys.type.rawValue] as? String else {
throw SchemaError.typeDecodingError
}
let container = try decoder.singleValueContainer()
switch type {
case ItemList.schemaName:
let value = try container.decode(ItemList.self)
self = .itemList(value: value)
case MusicRecording.schemaName:
let value = try container.decode(MusicRecording.self)
self = .musicRecording(value: value)
default:
throw SchemaError.typeDecodingError
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .itemList(let value):
try container.encode(value)
case .musicRecording(let value):
try container.encode(value)
}
}
public var itemList: ItemList? {
switch self {
case .itemList(let value):
return value
default:
return nil
}
}
public var musicRecording: MusicRecording? {
switch self {
case .musicRecording(let value):
return value
default:
return nil
}
}
}
| f8d6180932e19a89c19021470a37d788 | 27.515152 | 79 | 0.591923 | false | false | false | false |
eliasbloemendaal/KITEGURU | refs/heads/master | KITEGURU/BasicFunctions.swift | mit | 1 | //
// BasicFunctions.swift
// KITEGURU
//
// Created by Elias Houttuijn Bloemendaal on 27-01-16.
// Copyright © 2016 Elias Houttuijn Bloemendaal. All rights reserved.
//
import Foundation
class Functions{
// Een functie die automatische een screenshot maakt
func screenShotMethod() {
let layer = UIApplication.sharedApplication().keyWindow!.layer
let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale);
layer.renderInContext(UIGraphicsGetCurrentContext()!)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(screenshot, nil, nil, nil)
}
// Trim een string tot een normaal te leze string
func trimString(UntrimmedString: String) -> String {
let text = String(UntrimmedString)
let textWithoutNewLines = text.stringByReplacingOccurrencesOfString("\n", withString: "")
let textWithoutLeftComma = textWithoutNewLines.stringByReplacingOccurrencesOfString("(", withString: "")
let textWithoutRightComma = textWithoutLeftComma.stringByReplacingOccurrencesOfString(")", withString: "")
let textWithoutSpace = textWithoutRightComma.stringByReplacingOccurrencesOfString(" ", withString: "")
let textChanged = textWithoutSpace.stringByReplacingOccurrencesOfString(",", withString: "-")
return textChanged
}
// Trim een string, om daarna in een array te plaatsen
func trimThaString(UntrimmedString: String) -> String {
let text = String(UntrimmedString)
let textChanged = text.stringByReplacingOccurrencesOfString("-", withString: " ")
return textChanged
}
// Een verschillende cijfers van de KITEGURU, geeft een verschillend advies
func advise(input: Int) -> String{
if input == 1 {
return "Kiting is impossible"
}else if input == 2 {
return "Your Guru does not recommend kiting. Your equipment is not appropriate for the weather conditions"
}else if input == 3 {
return "Your Guru does not recommend kiting. Your equipment is not appropriate for the weather conditions"
}else if input == 4 {
return "Kiting is possible for advanced kite surfers only. Adjustments to your gear may be necessary"
}else if input == 5 {
return "Kiting is possible but tough for beginners. Advanced surfers may be able to withstand the weather conditions and enjoy themselves"
}else if input == 6 {
return "Your Guru recommends you to go kiting! The weather conditions and your gear are ok"
}else if input == 7 {
return "With your gear and in this weather it is definitely worthwhile to go kiting!"
}else if input == 8 {
return "Don’t hesitate: go kiting and have fun!"
}else if input == 9 {
return "All conditions are in place for a great kiting day!"
}else if input == 10 {
return "It’s your lucky day! The conditions could not be better. Your Guru wishes you a nice day!"
}
return "Error"
}
// Een functie die check of het textfield alleen maar cijfers bevat
func containsOnlyNumbers(input: String) -> Bool {
for char in input.characters {
if (!(char >= "0" && char <= "9")) {
return false
}
}
return true
}
// Check of er maar 1 cijfer wordt gegeven (voor de wetsuits)
func checkQuantityCharacters(input: String) -> Bool {
if input.characters.count != 1 {
return false
}
return true
}
// Check of het 2 of 3 karakters worden gegeven (voor het gewicht)
func checkQuantityCharactersDos(input: String) -> Bool {
if input.characters.count == 2 || input.characters.count == 3 {
return false
}
return true
}
// Check of het 1 of 2 karakters (voor de kite)
func checkQueantityCharactesrTwo(input: String) -> Bool {
if input.characters.count > 0 && input.characters.count < 3 {
return true
}
return false
}
} | 32d025aa791526f3e803b6cab9ad427c | 40.582524 | 152 | 0.645493 | false | false | false | false |
NeoTeo/SwiftBase58 | refs/heads/master | SwiftBase58/SwiftBase58.swift | mit | 1 | //
// SwiftBase58.swift
// SwiftBase58
//
// Created by Teo on 19/05/15.
// Copyright (c) 2015 Teo. All rights reserved.
//
// Licensed under MIT See LICENCE file in the root of this project for details.
import Foundation
import SwiftGMP
let BTCAlphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
let bigRadix = GMPInteger(58)
let bigZero = GMPInteger(0)
public func decode(_ b: String) -> [UInt8] {
return decodeAlphabet(b, alphabet: BTCAlphabet)
}
public func encode(_ b: [UInt8]) -> String {
return encodeAlphabet(b, alphabet: BTCAlphabet)
}
func decodeAlphabet(_ b: String, alphabet: String) -> [UInt8] {
var answer = GMPInteger(0)
var j = GMPInteger(1)
for ch in Array(b.reversed()) {
// Find the index of the letter ch in the alphabet.
if let charRange = alphabet.range(of: String(ch)) {
let letterIndex = alphabet.distance(from: alphabet.startIndex, to: charRange.lowerBound)
let idx = GMPInteger(letterIndex)
var tmp1 = GMPInteger(0)
tmp1 = .mul(j, idx)
answer = .add(answer, tmp1)
j = .mul(j, bigRadix)
} else {
return []
}
}
/// Remove leading 1's
// Find the first character that isn't 1
let bArr = Array(b)
let zChar = Array(alphabet).first
var nz = 0
for _ in 0 ..< b.count {
if bArr[nz] != zChar { break }
nz += 1
}
let tmpval = GMPInteger.bytes(answer)
var val = [UInt8](repeating: 0, count: nz)
val += tmpval
return val
}
func encodeAlphabet(_ byteSlice: [UInt8], alphabet: String) -> String {
var bytesAsIntBig = GMPInteger(byteSlice)
let byteAlphabet = [UInt8](alphabet.utf8)
var answer = [UInt8]()//(count: byteSlice.count*136/100, repeatedValue: 0)
while GMPInteger.cmp(bytesAsIntBig, bigZero) > 0 {
let mod = GMPInteger()
let (quotient, modulus) = GMPInteger.divMod(bytesAsIntBig, bigRadix, mod)
bytesAsIntBig = quotient
// Make the String into an array of characters.
answer.insert(byteAlphabet[GMPInteger.getInt64(modulus)!], at: 0)
}
// leading zero bytes
for ch in byteSlice {
if ch != 0 { break }
answer.insert(byteAlphabet[0], at: 0)
}
return String(bytes: answer, encoding: String.Encoding.utf8)!
}
| 90088ab6a4bb7ddd533be3b59539a0b9 | 25.717391 | 100 | 0.603336 | false | false | false | false |
cotkjaer/SilverbackFramework | refs/heads/master | SilverbackFramework/UILabel.swift | mit | 1 | //
// UILabel.swift
// SilverbackFramework
//
// Created by Christian Otkjær on 25/08/15.
// Copyright © 2015 Christian Otkjær. All rights reserved.
//
import UIKit
public extension UILabel
{
public var substituteFontName : String
{
get { return self.font.fontName }
set { self.font = UIFont(name: newValue, size: self.font.pointSize) }
}
}
public extension UILabel
{
public convenience init(text: String, font: UIFont? = nil)
{
self.init(frame: CGRectZero)
self.text = text
if let alternateFont = font
{
self.font = alternateFont
}
self.sizeToFit()
}
}
| 2e777dc0f49442e54ce132ea1f70a370 | 19.78125 | 77 | 0.610526 | false | false | false | false |
wireapp/wire-ios | refs/heads/develop | Wire-iOS Tests/Notification Service Extension/SimpleNotificationServiceExtension/AccessTokenEndpointTests.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2022 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import XCTest
@testable import Wire_Notification_Service_Extension
class AccessTokenEndpointTests: XCTestCase {
// MARK: - Request generation
func test_RequestGeneration() {
// Given
let sut = AccessTokenEndpoint()
// When
let request = sut.request
// Then
XCTAssertEqual(request.path, "/access")
XCTAssertEqual(request.httpMethod, .post)
XCTAssertEqual(request.contentType, .json)
XCTAssertEqual(request.acceptType, .json)
}
// MARK: - Response parsing
let validPayload = """
{
"access_token": "testToken",
"token_type": "type",
"expires_in": 3600
}
""".data(using: .utf8)!
let invalidPayload = """
{
"foo": "bar"
}
""".data(using: .utf8)!
func test_ParseSuccessResponse() {
// Given
let sut = AccessTokenEndpoint()
let response = SuccessResponse(status: 200, data: validPayload)
// When
let result = sut.parseResponse(.success(response))
// Then
guard case .success(let token) = result else {
XCTFail("expected success result")
return
}
XCTAssertEqual(token.token, "testToken")
XCTAssertEqual(token.type, "type")
XCTAssertEqual(token.expirationDate.timeIntervalSinceNow, 3600, accuracy: 0.1)
}
func test_ParseSuccess_FailedToDecodeError() {
// Given
let sut = AccessTokenEndpoint()
let response = SuccessResponse(status: 200, data: invalidPayload)
// When
let result = sut.parseResponse(.success(response))
// Then
XCTAssertEqual(result, .failure(.failedToDecodePayload))
}
func test_ParseSuccess_InvalidResponse() {
// Given
let sut = AccessTokenEndpoint()
let response = SuccessResponse(status: 222, data: validPayload)
// When
let result = sut.parseResponse(.success(response))
// Then
XCTAssertEqual(result, .failure(.invalidResponse))
}
func test_ParseError_AuthenticationError() {
// Given
let sut = AccessTokenEndpoint()
let response = ErrorResponse(code: 403, label: "invalid-credentials", message: "error")
// When
let result = sut.parseResponse(.failure(response))
// Then
XCTAssertEqual(result, .failure(.authenticationError))
}
func test_ParseError_UnknownError() {
// Given
let sut = AccessTokenEndpoint()
let response = ErrorResponse(code: 500, label: "server-error", message: "error")
// When
let result = sut.parseResponse(.failure(response))
// Then
XCTAssertEqual(result, .failure(.unknownError(response)))
}
}
| 079b3c0a483fa59ff14df2b3885235d7 | 27.634146 | 95 | 0.624929 | false | true | false | false |
quickthyme/PUTcat | refs/heads/master | PUTcat/Application/Data/Variable/DataStore/PCVariableDataStoreLocal.swift | apache-2.0 | 1 |
import Foundation
class PCVariableDataStoreLocal : PCVariableDataStore {
private static let StorageFile_Pfx = "PCVariableList_"
private static let StorageFile_Sfx = ".json"
private static let StorageKey = "variables"
private static func StorageFileName(_ parentID: String) -> String {
return "\(StorageFile_Pfx)\(parentID)\(StorageFile_Sfx)"
}
static func fetch(environmentID: String) -> Composed.Action<Any, PCList<PCVariable>> {
return Composed.Action<Any, PCList<PCVariable>> { _, completion in
guard
let path = DocumentsDirectory.existingFilePathWithName(StorageFileName(environmentID)),
let dict = xJSON.parse(file: path) as? [String:Any],
let items = dict[StorageKey] as? [[String:Any]]
else {
return completion(.success(PCList<PCVariable>()))
}
completion(.success(PCList<PCVariable>(fromLocal: items)))
}
}
static func store(environmentID: String) -> Composed.Action<PCList<PCVariable>, PCList<PCVariable>> {
return Composed.Action<PCList<PCVariable>, PCList<PCVariable>> { list, completion in
guard let list = list else {
return completion(.failure(PCError(code: 404, text: "No list to store \(StorageKey)")))
}
let path = DocumentsDirectory.filePathWithName(StorageFileName(environmentID))
let dict = [ StorageKey : list.toLocal() ]
if xJSON.write(dict, toFile: path) { completion(.success(list)) }
else {
completion(.failure(PCError(code: 404, text: "Error writing \(StorageKey)")))
}
}
}
}
| 12d22422449100e6d9f7e4c51e658865 | 40.97561 | 105 | 0.619988 | false | false | false | false |
RoverPlatform/rover-ios-beta | refs/heads/master | Sources/Services/Analytics.swift | mit | 1 | //
// Analytics.swift
// Rover
//
// Created by Sean Rucker on 2019-05-01.
// Copyright © 2019 Rover Labs Inc. All rights reserved.
//
import os.log
import UIKit
class Analytics {
/// The shared singleton analytics service.
static var shared = Analytics()
private let session = URLSession(configuration: URLSessionConfiguration.default)
private var tokens: [NSObjectProtocol] = []
func enable() {
guard tokens.isEmpty else {
return
}
tokens = [
NotificationCenter.default.addObserver(
forName: UIApplication.didBecomeActiveNotification,
object: nil,
queue: nil,
using: { [weak self] notification in
self?.trackEvent(name: "App Opened", properties: EmptyProperties())
}
),
NotificationCenter.default.addObserver(
forName: ExperienceViewController.experiencePresentedNotification,
object: nil,
queue: nil,
using: { [weak self] in
self?.trackEvent(
name: "Experience Presented",
properties: ExperiencePresentedProperties(userInfo: $0.userInfo)
)
}
),
NotificationCenter.default.addObserver(
forName: ExperienceViewController.experienceDismissedNotification,
object: nil,
queue: nil,
using: { [weak self] in
self?.trackEvent(
name: "Experience Dismissed",
properties: ExperienceDismissedProperties(userInfo: $0.userInfo)
)
}
),
NotificationCenter.default.addObserver(
forName: ExperienceViewController.experienceViewedNotification,
object: nil,
queue: nil,
using: { [weak self] in
self?.trackEvent(
name: "Experience Viewed",
properties: ExperienceViewedProperties(userInfo: $0.userInfo)
)
}
),
NotificationCenter.default.addObserver(
forName: ScreenViewController.screenPresentedNotification,
object: nil,
queue: nil,
using: { [weak self] in
self?.trackEvent(
name: "Screen Presented",
properties: ScreenPresentedProperties(userInfo: $0.userInfo)
)
}
),
NotificationCenter.default.addObserver(
forName: ScreenViewController.screenDismissedNotification,
object: nil,
queue: nil,
using: { [weak self] in
self?.trackEvent(
name: "Screen Dismissed",
properties: ScreenDismissedProperties(userInfo: $0.userInfo)
)
}
),
NotificationCenter.default.addObserver(
forName: ScreenViewController.screenViewedNotification,
object: nil,
queue: nil,
using: { [weak self] in
self?.trackEvent(
name: "Screen Viewed",
properties: ScreenViewedProperties(userInfo: $0.userInfo)
)
}
),
NotificationCenter.default.addObserver(
forName: ScreenViewController.blockTappedNotification,
object: nil,
queue: nil,
using: { [weak self] in
self?.trackEvent(
name: "Block Tapped",
properties: BlockTappedProperties(userInfo: $0.userInfo)
)
}
),
NotificationCenter.default.addObserver(
forName: ScreenViewController.pollAnsweredNotification,
object: nil,
queue: nil,
using: { [weak self] in
self?.trackEvent(name: "Poll Answered", properties: PollAnsweredProperties(userInfo: $0.userInfo))
}
)
]
}
func disable() {
tokens.forEach(NotificationCenter.default.removeObserver)
tokens = []
}
deinit {
disable()
}
private func trackEvent<Properties>(name: String, properties: Properties) where Properties: Encodable {
let event = Event(name: name, properties: properties)
let data: Data
do {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .formatted(DateFormatter.rfc3339)
data = try encoder.encode(event)
} catch {
os_log("Failed to encode analytics event: %@", log: .rover, type: .error, error.debugDescription)
return
}
let url = URL(string: "https://analytics.rover.io")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "content-type")
request.setValue(Rover.accountToken, forHTTPHeaderField: "x-rover-account-token")
request.setRoverUserAgent()
var backgroundTaskID: UIBackgroundTaskIdentifier!
backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "Upload Analytics Event") {
os_log("Failed to upload analytics event: %@", log: .rover, type: .error, "App was suspended during upload")
UIApplication.shared.endBackgroundTask(backgroundTaskID)
}
let sessionTask = session.uploadTask(with: request, from: data) { _, _, error in
if let error = error {
os_log("Failed to upload analytics event: %@", log: .rover, type: .error, error.debugDescription)
}
UIApplication.shared.endBackgroundTask(backgroundTaskID)
}
sessionTask.resume()
}
}
private struct Event<Properties>: Encodable where Properties: Encodable {
let name: String
let properties: Properties
let timestamp = Date()
let anonymousID = UIDevice.current.identifierForVendor?.uuidString
enum CodingKeys: String, CodingKey {
case name = "event"
case properties
case timestamp
case anonymousID
}
}
private struct ExperiencePresentedProperties: Encodable {
var experienceID: String
var experienceName: String
var experienceTags: [String]
var campaignID: String?
init?(userInfo: [AnyHashable: Any]?) {
guard let userInfo = userInfo,
let experience = userInfo[ExperienceViewController.experienceUserInfoKey] as? Experience else {
return nil
}
self.experienceID = experience.id
self.experienceName = experience.name
self.experienceTags = experience.tags
if let campaignID = userInfo[ExperienceViewController.campaignIDUserInfoKey] as? String {
self.campaignID = campaignID
}
}
}
private struct ExperienceDismissedProperties: Encodable {
var experienceID: String
var experienceName: String
var experienceTags: [String]
var campaignID: String?
init?(userInfo: [AnyHashable: Any]?) {
guard let userInfo = userInfo,
let experience = userInfo[ExperienceViewController.experienceUserInfoKey] as? Experience else {
return nil
}
self.experienceID = experience.id
self.experienceName = experience.name
self.experienceTags = experience.tags
if let campaignID = userInfo[ExperienceViewController.campaignIDUserInfoKey] as? String {
self.campaignID = campaignID
}
}
}
private struct ExperienceViewedProperties: Encodable {
var experienceID: String
var experienceName: String
var experienceTags: [String]
var duration: Double
var campaignID: String?
init?(userInfo: [AnyHashable: Any]?) {
guard let userInfo = userInfo,
let experience = userInfo[ExperienceViewController.experienceUserInfoKey] as? Experience,
let duration = userInfo[ExperienceViewController.durationUserInfoKey] as? Double else {
return nil
}
self.experienceID = experience.id
self.experienceName = experience.name
self.experienceTags = experience.tags
self.duration = duration
if let campaignID = userInfo[ExperienceViewController.campaignIDUserInfoKey] as? String {
self.campaignID = campaignID
}
}
}
private struct ScreenPresentedProperties: Encodable {
var experienceID: String
var experienceName: String
var experienceTags: [String]
var screenID: String
var screenName: String
var screenTags: [String]
var campaignID: String?
init?(userInfo: [AnyHashable: Any]?) {
guard let userInfo = userInfo,
let experience = userInfo[ScreenViewController.experienceUserInfoKey] as? Experience,
let screen = userInfo[ScreenViewController.screenUserInfoKey] as? Screen else {
return nil
}
self.experienceID = experience.id
self.experienceName = experience.name
self.experienceTags = experience.tags
self.screenID = screen.id
self.screenName = screen.name
self.screenTags = screen.tags
if let campaignID = userInfo[ScreenViewController.campaignIDUserInfoKey] as? String {
self.campaignID = campaignID
}
}
}
private struct ScreenDismissedProperties: Encodable {
var experienceID: String
var experienceName: String
var experienceTags: [String]
var screenID: String
var screenName: String
var screenTags: [String]
var campaignID: String?
init?(userInfo: [AnyHashable: Any]?) {
guard let userInfo = userInfo,
let experience = userInfo[ScreenViewController.experienceUserInfoKey] as? Experience,
let screen = userInfo[ScreenViewController.screenUserInfoKey] as? Screen else {
return nil
}
self.experienceID = experience.id
self.experienceName = experience.name
self.experienceTags = experience.tags
self.screenID = screen.id
self.screenName = screen.name
self.screenTags = screen.tags
if let campaignID = userInfo[ScreenViewController.campaignIDUserInfoKey] as? String {
self.campaignID = campaignID
}
}
}
private struct ScreenViewedProperties: Encodable {
var experienceID: String
var experienceName: String
var experienceTags: [String]
var screenID: String
var screenName: String
var screenTags: [String]
var duration: Double
var campaignID: String?
init?(userInfo: [AnyHashable: Any]?) {
guard let userInfo = userInfo,
let experience = userInfo[ScreenViewController.experienceUserInfoKey] as? Experience,
let screen = userInfo[ScreenViewController.screenUserInfoKey] as? Screen,
let duration = userInfo[ScreenViewController.durationUserInfoKey] as? Double else {
return nil
}
self.experienceID = experience.id
self.experienceName = experience.name
self.experienceTags = experience.tags
self.screenID = screen.id
self.screenName = screen.name
self.screenTags = screen.tags
self.duration = duration
if let campaignID = userInfo[ScreenViewController.campaignIDUserInfoKey] as? String {
self.campaignID = campaignID
}
}
}
private struct BlockTappedProperties: Encodable {
var experienceID: String
var experienceName: String
var experienceTags: [String]
var screenID: String
var screenName: String
var screenTags: [String]
var blockID: String
var blockName: String
var blockTags: [String]
var campaignID: String?
init?(userInfo: [AnyHashable: Any]?) {
guard let userInfo = userInfo,
let experience = userInfo[ScreenViewController.experienceUserInfoKey] as? Experience,
let screen = userInfo[ScreenViewController.screenUserInfoKey] as? Screen,
let block = userInfo[ScreenViewController.blockUserInfoKey] as? Block else {
return nil
}
self.experienceID = experience.id
self.experienceName = experience.name
self.experienceTags = experience.tags
self.screenID = screen.id
self.screenName = screen.name
self.screenTags = screen.tags
self.blockID = block.id
self.blockName = block.name
self.blockTags = block.tags
if let campaignID = userInfo[ScreenViewController.campaignIDUserInfoKey] as? String {
self.campaignID = campaignID
}
}
}
private struct PollAnsweredProperties: Encodable {
var experienceID: String
var experienceName: String
var experienceTags: [String]
var screenID: String
var screenName: String
var screenTags: [String]
var blockID: String
var blockName: String
var blockTags: [String]
var optionID: String
var optionText: String
var optionImage: String? // URL
var campaignID: String?
init?(userInfo: [AnyHashable: Any]?) {
guard let userInfo = userInfo,
let experience = userInfo[ScreenViewController.experienceUserInfoKey] as? Experience,
let screen = userInfo[ScreenViewController.screenUserInfoKey] as? Screen,
let block = userInfo[ScreenViewController.blockUserInfoKey] as? PollBlock,
let option = userInfo[ScreenViewController.optionUserInfoKey] as? PollOption
else {
return nil
}
self.experienceID = experience.id
self.experienceName = experience.name
self.experienceTags = experience.tags
self.screenID = screen.id
self.screenName = screen.name
self.screenTags = screen.tags
self.blockID = block.id
self.blockName = block.name
self.blockTags = block.tags
self.optionID = option.id
self.optionText = option.text.rawValue
self.optionImage = (option as? ImagePollBlock.ImagePoll.Option)?.image?.url.absoluteString
if let campaignID = userInfo[ScreenViewController.campaignIDUserInfoKey] as? String {
self.campaignID = campaignID
}
}
}
private struct EmptyProperties: Encodable {
}
| e4e5044167cf771c7a4ae17675de3bf2 | 34.56057 | 120 | 0.600895 | false | false | false | false |
WhisperSystems/Signal-iOS | refs/heads/master | Signal/src/Models/PhoneNumberValidator.swift | gpl-3.0 | 1 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import SignalServiceKit
@objc
public enum ValidatedPhoneCountryCodes: UInt {
case unitedStates = 1
case brazil = 55
}
@objc
public class PhoneNumberValidator: NSObject {
@objc
public func isValidForRegistration(phoneNumber: PhoneNumber) -> Bool {
guard let countryCode = phoneNumber.getCountryCode() else {
return false
}
guard let validatedCountryCode = ValidatedPhoneCountryCodes(rawValue: countryCode.uintValue) else {
// no extra validation for this country
return true
}
switch validatedCountryCode {
case .brazil:
return isValidForBrazilRegistration(phoneNumber: phoneNumber)
case .unitedStates:
return isValidForUnitedStatesRegistration(phoneNumber: phoneNumber)
}
}
let validBrazilPhoneNumberRegex = try! NSRegularExpression(pattern: "^\\+55\\d{2}9?\\d{8}$", options: [])
private func isValidForBrazilRegistration(phoneNumber: PhoneNumber) -> Bool {
let e164 = phoneNumber.toE164()
return validBrazilPhoneNumberRegex.hasMatch(input: e164)
}
let validUnitedStatesPhoneNumberRegex = try! NSRegularExpression(pattern: "^\\+1\\d{10}$", options: [])
private func isValidForUnitedStatesRegistration(phoneNumber: PhoneNumber) -> Bool {
let e164 = phoneNumber.toE164()
return validUnitedStatesPhoneNumberRegex.hasMatch(input: e164)
}
}
| 4a10a89b77a9ad14f8522c3a4f4afcb5 | 31.638298 | 109 | 0.691004 | false | false | false | false |
prey/prey-ios-client | refs/heads/master | Prey/Classes/QRCodeScannerVC.swift | gpl-3.0 | 1 | //
// QRCodeScannerVC.swift
// Prey
//
// Created by Javier Cala Uribe on 19/07/16.
// Copyright © 2016 Prey, Inc. All rights reserved.
//
import Foundation
import AVFoundation
import UIKit
class QRCodeScannerVC: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
// MARK: Properties
let device : AVCaptureDevice! = AVCaptureDevice.default(for: AVMediaType.video)
let session : AVCaptureSession = AVCaptureSession()
let output : AVCaptureMetadataOutput = AVCaptureMetadataOutput()
var preview : AVCaptureVideoPreviewLayer!
// MARK: Init
override func viewDidLoad() {
super.viewDidLoad()
// View title for GAnalytics
//self.screenName = "QRCodeScanner"
// Set background color
self.view.backgroundColor = UIColor.black
// Config navigationBar
let widthScreen = UIScreen.main.bounds.size.width
let navBar = UINavigationBar(frame:CGRect(x: 0,y: 0,width: widthScreen,height: 44))
navBar.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
self.view.addSubview(navBar)
// Config navItem
let navItem = UINavigationItem(title:"Prey Control Panel".localized)
navItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem:.cancel, target:self, action:#selector(cancel))
navBar.pushItem(navItem, animated:false)
// Check camera available
guard isCameraAvailable() else {
displayErrorAlert("Couldn't add your device".localized,
titleMessage:"Error camera isn't available".localized)
return
}
// Config session QR-Code
do {
let inputDevice : AVCaptureDeviceInput = try AVCaptureDeviceInput(device:device)
setupScanner(inputDevice)
// Start scanning
startScanning()
} catch let error as NSError{
PreyLogger("QrCode error: \(error.localizedDescription)")
displayErrorAlert("Couldn't add your device".localized,
titleMessage:"The scanned QR code is invalid".localized)
return
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Methods
// Setup scanner
func setupScanner(_ input:AVCaptureDeviceInput) {
// Config session
session.addOutput(output)
session.addInput(input)
// Config output
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
output.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
// Config preview
preview = AVCaptureVideoPreviewLayer(session:session)
preview.videoGravity = AVLayerVideoGravity.resizeAspectFill
preview.frame = CGRect(x: 0, y: 0,width: self.view.frame.size.width, height: self.view.frame.size.height)
preview.connection?.videoOrientation = .portrait
self.view.layer.insertSublayer(preview, at:0)
// Config label
let screen = UIScreen.main.bounds.size
let widthLbl = screen.width
let fontSize:CGFloat = IS_IPAD ? 16.0 : 12.0
let message = IS_IPAD ? "Visit panel.preyproject.com/qr on your computer and scan the QR code".localized :
"Visit panel.preyproject.com/qr \non your computer and scan the QR code".localized
let infoQR = UILabel(frame:CGRect(x: 0, y: screen.height-50, width: widthLbl, height: 50))
infoQR.textColor = UIColor(red:0.3019, green:0.3411, blue:0.4, alpha:0.7)
infoQR.backgroundColor = UIColor.white
infoQR.textAlignment = .center
infoQR.font = UIFont(name:fontTitilliumRegular, size:fontSize)
infoQR.text = message
infoQR.numberOfLines = 2
infoQR.adjustsFontSizeToFitWidth = true
self.view.addSubview(infoQR)
// Config QrZone image
let qrZoneSize = IS_IPAD ? screen.width*0.6 : screen.width*0.78
let qrZonePosY = (screen.height - qrZoneSize)/2
let qrZonePosX = (screen.width - qrZoneSize)/2
let qrZoneImg = UIImageView(image:UIImage(named:"QrZone"))
qrZoneImg.frame = CGRect(x: qrZonePosX, y: qrZonePosY, width: qrZoneSize, height: qrZoneSize)
self.view.addSubview(qrZoneImg)
}
// Success scan
func successfullyScan(_ scannedValue: NSString) {
let validQr = "prey?api_key=" as NSString
let checkQr:NSString = (scannedValue.length > validQr.length) ? scannedValue.substring(to: validQr.length) as NSString : "" as NSString
let apikeyQr:NSString = (scannedValue.length > validQr.length) ? scannedValue.substring(from: validQr.length) as NSString : "" as NSString
stopScanning()
self.dismiss(animated: true, completion: {() -> Void in
if checkQr.isEqual(to: validQr as String) {
PreyDeployment.sharedInstance.addDeviceWith(apikeyQr as String, fromQRCode:true)
} else {
displayErrorAlert("The scanned QR code is invalid".localized,
titleMessage:"Couldn't add your device".localized)
}
})
}
func startScanning() {
self.session.startRunning()
}
func stopScanning() {
self.session.stopRunning()
}
func isCameraAvailable() -> Bool {
return AVCaptureDevice.devices(for: AVMediaType.video).count > 0 ? true : false
}
@objc func cancel() {
self.dismiss(animated: true, completion:nil)
}
// MARK: AVCaptureMetadataOutputObjectsDelegate
// CaptureOutput
func metadataOutput(_ captureOutput: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
for current in metadataObjects {
if current is AVMetadataMachineReadableCodeObject {
if let scannedValue = (current as! AVMetadataMachineReadableCodeObject).stringValue {
successfullyScan(scannedValue as NSString)
}
}
}
}
}
| c61e8e3cffc00e17679af0307f40ef8f | 38.526627 | 152 | 0.599401 | false | false | false | false |
wibosco/WhiteBoardCodingChallenges | refs/heads/main | WhiteBoardCodingChallenges/Challenges/CrackingTheCodingInterview/BuildOrder/ProjectBuildOrder.swift | mit | 1 | //
// BuildOrder.swift
// WhiteBoardCodingChallenges
//
// Created by William Boles on 02/06/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import UIKit
//CtCI 4.7
class ProjectBuildOrder: NSObject {
class func buildOrder(projects: [String], dependencies: [[String]]) -> [ProjectBuildOrderNode]? {
let nodes = buildNodes(projects: projects, dependencies: dependencies)
for node in nodes {
for dependency in node.dependencies {
if dependencyCycleExistsBetweenNodes(source: dependency, destination: node) {
return nil
}
}
}
var orderedNodes = [ProjectBuildOrderNode]()
for node in nodes {
if !node.pathVisited {
buildOrder(rootNode: node, vistedNodes: &orderedNodes)
}
}
return orderedNodes
}
private class func buildOrder(rootNode: ProjectBuildOrderNode, vistedNodes: inout [ProjectBuildOrderNode]) {
for dependency in rootNode.dependencies {
if !dependency.pathVisited {
buildOrder(rootNode: dependency, vistedNodes: &vistedNodes)
}
}
vistedNodes.append(rootNode)
rootNode.pathVisited = true
}
private class func buildNodes(projects: [String], dependencies: [[String]]) -> [ProjectBuildOrderNode] {
var nodes = [String: ProjectBuildOrderNode]()
for project in projects {
let node = ProjectBuildOrderNode.init(value: project)
nodes[project] = node
}
for dependencyPair in dependencies {
let dependent = dependencyPair[1]
let dependency = dependencyPair[0]
let dependentNode = nodes[dependent]
let dependencyNode = nodes[dependency]
dependentNode?.addDependency(dependency: dependencyNode!)
}
return Array(nodes.values)
}
private class func dependencyCycleExistsBetweenNodes(source: ProjectBuildOrderNode, destination: ProjectBuildOrderNode) -> Bool {
var queue = [ProjectBuildOrderNode]()
queue.append(source)
while queue.count > 0 {
let node = queue.removeFirst()
for dependency in node.dependencies {
if dependency == destination {
return true
}
if !dependency.visited {
dependency.visited = true
queue.append(dependency)
}
}
}
return false
}
}
| ab97d615666bdd2a2383055a870ff98a | 26.805556 | 133 | 0.509158 | false | false | false | false |
huonw/swift | refs/heads/master | stdlib/public/core/CompilerProtocols.swift | apache-2.0 | 2 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Intrinsic protocols shared with the compiler
//===----------------------------------------------------------------------===//
/// A type that can be converted to and from an associated raw value.
///
/// With a `RawRepresentable` type, you can switch back and forth between a
/// custom type and an associated `RawValue` type without losing the value of
/// the original `RawRepresentable` type. Using the raw value of a conforming
/// type streamlines interoperation with Objective-C and legacy APIs and
/// simplifies conformance to other protocols, such as `Equatable`,
/// `Comparable`, and `Hashable`.
///
/// The `RawRepresentable` protocol is seen mainly in two categories of types:
/// enumerations with raw value types and option sets.
///
/// Enumerations with Raw Values
/// ============================
///
/// For any enumeration with a string, integer, or floating-point raw type, the
/// Swift compiler automatically adds `RawRepresentable` conformance. When
/// defining your own custom enumeration, you give it a raw type by specifying
/// the raw type as the first item in the enumeration's type inheritance list.
/// You can also use literals to specify values for one or more cases.
///
/// For example, the `Counter` enumeration defined here has an `Int` raw value
/// type and gives the first case a raw value of `1`:
///
/// enum Counter: Int {
/// case one = 1, two, three, four, five
/// }
///
/// You can create a `Counter` instance from an integer value between 1 and 5
/// by using the `init?(rawValue:)` initializer declared in the
/// `RawRepresentable` protocol. This initializer is failable because although
/// every case of the `Counter` type has a corresponding `Int` value, there
/// are many `Int` values that *don't* correspond to a case of `Counter`.
///
/// for i in 3...6 {
/// print(Counter(rawValue: i))
/// }
/// // Prints "Optional(Counter.three)"
/// // Prints "Optional(Counter.four)"
/// // Prints "Optional(Counter.five)"
/// // Prints "nil"
///
/// Option Sets
/// ===========
///
/// Option sets all conform to `RawRepresentable` by inheritance using the
/// `OptionSet` protocol. Whether using an option set or creating your own,
/// you use the raw value of an option set instance to store the instance's
/// bitfield. The raw value must therefore be of a type that conforms to the
/// `FixedWidthInteger` protocol, such as `UInt8` or `Int`. For example, the
/// `Direction` type defines an option set for the four directions you can
/// move in a game.
///
/// struct Directions: OptionSet {
/// let rawValue: UInt8
///
/// static let up = Directions(rawValue: 1 << 0)
/// static let down = Directions(rawValue: 1 << 1)
/// static let left = Directions(rawValue: 1 << 2)
/// static let right = Directions(rawValue: 1 << 3)
/// }
///
/// Unlike enumerations, option sets provide a nonfailable `init(rawValue:)`
/// initializer to convert from a raw value, because option sets don't have an
/// enumerated list of all possible cases. Option set values have
/// a one-to-one correspondence with their associated raw values.
///
/// In the case of the `Directions` option set, an instance can contain zero,
/// one, or more of the four defined directions. This example declares a
/// constant with three currently allowed moves. The raw value of the
/// `allowedMoves` instance is the result of the bitwise OR of its three
/// members' raw values:
///
/// let allowedMoves: Directions = [.up, .down, .left]
/// print(allowedMoves.rawValue)
/// // Prints "7"
///
/// Option sets use bitwise operations on their associated raw values to
/// implement their mathematical set operations. For example, the `contains()`
/// method on `allowedMoves` performs a bitwise AND operation to check whether
/// the option set contains an element.
///
/// print(allowedMoves.contains(.right))
/// // Prints "false"
/// print(allowedMoves.rawValue & Directions.right.rawValue)
/// // Prints "0"
public protocol RawRepresentable {
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
associatedtype RawValue
/// Creates a new instance with the specified raw value.
///
/// If there is no value of the type that corresponds with the specified raw
/// value, this initializer returns `nil`. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// print(PaperSize(rawValue: "Legal"))
/// // Prints "Optional("PaperSize.Legal")"
///
/// print(PaperSize(rawValue: "Tabloid"))
/// // Prints "nil"
///
/// - Parameter rawValue: The raw value to use for the new instance.
init?(rawValue: RawValue)
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
var rawValue: RawValue { get }
}
/// Returns a Boolean value indicating whether the two arguments are equal.
///
/// - Parameters:
/// - lhs: A raw-representable instance.
/// - rhs: A second raw-representable instance.
@inlinable // FIXME(sil-serialize-all)
public func == <T : RawRepresentable>(lhs: T, rhs: T) -> Bool
where T.RawValue : Equatable {
return lhs.rawValue == rhs.rawValue
}
/// Returns a Boolean value indicating whether the two arguments are not equal.
///
/// - Parameters:
/// - lhs: A raw-representable instance.
/// - rhs: A second raw-representable instance.
@inlinable // FIXME(sil-serialize-all)
public func != <T : RawRepresentable>(lhs: T, rhs: T) -> Bool
where T.RawValue : Equatable {
return lhs.rawValue != rhs.rawValue
}
// This overload is needed for ambiguity resolution against the
// implementation of != for T : Equatable
/// Returns a Boolean value indicating whether the two arguments are not equal.
///
/// - Parameters:
/// - lhs: A raw-representable instance.
/// - rhs: A second raw-representable instance.
@inlinable // FIXME(sil-serialize-all)
public func != <T : Equatable>(lhs: T, rhs: T) -> Bool
where T : RawRepresentable, T.RawValue : Equatable {
return lhs.rawValue != rhs.rawValue
}
/// A type that provides a collection of all of its values.
///
/// Types that conform to the `CaseIterable` protocol are typically
/// enumerations without associated values. When using a `CaseIterable` type,
/// you can access a collection of all of the type's cases by using the type's
/// `allCases` property.
///
/// For example, the `CompassDirection` enumeration declared in this example
/// conforms to `CaseIterable`. You access the number of cases and the cases
/// themselves through `CompassDirection.allCases`.
///
/// enum CompassDirection: CaseIterable {
/// case north, south, east, west
/// }
///
/// print("There are \(CompassDirection.allCases.count) directions.")
/// // Prints "There are 4 directions."
/// let caseList = CompassDirection.allCases
/// .map({ "\($0)" })
/// .joined(separator: ", ")
/// // caseList == "north, south, east, west"
///
/// Conforming to the CaseIterable Protocol
/// =======================================
///
/// The compiler can automatically provide an implementation of the
/// `CaseIterable` requirements for any enumeration without associated values
/// or `@available` attributes on its cases. The synthesized `allCases`
/// collection provides the cases in order of their declaration.
///
/// You can take advantage of this compiler support when defining your own
/// custom enumeration by declaring conformance to `CaseIterable` in the
/// enumeration's original declaration. The `CompassDirection` example above
/// demonstrates this automatic implementation.
public protocol CaseIterable {
/// A type that can represent a collection of all values of this type.
associatedtype AllCases: Collection
where AllCases.Element == Self
/// A collection of all values of this type.
static var allCases: AllCases { get }
}
/// A type that can be initialized using the nil literal, `nil`.
///
/// `nil` has a specific meaning in Swift---the absence of a value. Only the
/// `Optional` type conforms to `ExpressibleByNilLiteral`.
/// `ExpressibleByNilLiteral` conformance for types that use `nil` for other
/// purposes is discouraged.
public protocol ExpressibleByNilLiteral {
/// Creates an instance initialized with `nil`.
init(nilLiteral: ())
}
public protocol _ExpressibleByBuiltinIntegerLiteral {
init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType)
}
/// A type that can be initialized with an integer literal.
///
/// The standard library integer and floating-point types, such as `Int` and
/// `Double`, conform to the `ExpressibleByIntegerLiteral` protocol. You can
/// initialize a variable or constant of any of these types by assigning an
/// integer literal.
///
/// // Type inferred as 'Int'
/// let cookieCount = 12
///
/// // An array of 'Int'
/// let chipsPerCookie = [21, 22, 25, 23, 24, 19]
///
/// // A floating-point value initialized using an integer literal
/// let redPercentage: Double = 1
/// // redPercentage == 1.0
///
/// Conforming to ExpressibleByIntegerLiteral
/// =========================================
///
/// To add `ExpressibleByIntegerLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByIntegerLiteral {
/// A type that represents an integer literal.
///
/// The standard library integer and floating-point types are all valid types
/// for `IntegerLiteralType`.
associatedtype IntegerLiteralType : _ExpressibleByBuiltinIntegerLiteral
/// Creates an instance initialized to the specified integer value.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using an integer literal. For example:
///
/// let x = 23
///
/// In this example, the assignment to the `x` constant calls this integer
/// literal initializer behind the scenes.
///
/// - Parameter value: The value to create.
init(integerLiteral value: IntegerLiteralType)
}
public protocol _ExpressibleByBuiltinFloatLiteral {
init(_builtinFloatLiteral value: _MaxBuiltinFloatType)
}
/// A type that can be initialized with a floating-point literal.
///
/// The standard library floating-point types---`Float`, `Double`, and
/// `Float80` where available---all conform to the `ExpressibleByFloatLiteral`
/// protocol. You can initialize a variable or constant of any of these types
/// by assigning a floating-point literal.
///
/// // Type inferred as 'Double'
/// let threshold = 6.0
///
/// // An array of 'Double'
/// let measurements = [2.2, 4.1, 3.65, 4.2, 9.1]
///
/// Conforming to ExpressibleByFloatLiteral
/// =======================================
///
/// To add `ExpressibleByFloatLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByFloatLiteral {
/// A type that represents a floating-point literal.
///
/// Valid types for `FloatLiteralType` are `Float`, `Double`, and `Float80`
/// where available.
associatedtype FloatLiteralType : _ExpressibleByBuiltinFloatLiteral
/// Creates an instance initialized to the specified floating-point value.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using a floating-point literal. For example:
///
/// let x = 21.5
///
/// In this example, the assignment to the `x` constant calls this
/// floating-point literal initializer behind the scenes.
///
/// - Parameter value: The value to create.
init(floatLiteral value: FloatLiteralType)
}
public protocol _ExpressibleByBuiltinBooleanLiteral {
init(_builtinBooleanLiteral value: Builtin.Int1)
}
/// A type that can be initialized with the Boolean literals `true` and
/// `false`.
///
/// Only three types provided by Swift---`Bool`, `DarwinBoolean`, and
/// `ObjCBool`---are treated as Boolean values. Expanding this set to include
/// types that represent more than simple Boolean values is discouraged.
///
/// To add `ExpressibleByBooleanLiteral` conformance to your custom type,
/// implement the `init(booleanLiteral:)` initializer that creates an instance
/// of your type with the given Boolean value.
public protocol ExpressibleByBooleanLiteral {
/// A type that represents a Boolean literal, such as `Bool`.
associatedtype BooleanLiteralType : _ExpressibleByBuiltinBooleanLiteral
/// Creates an instance initialized to the given Boolean value.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using one of the Boolean literals `true` and `false`. For
/// example:
///
/// let twasBrillig = true
///
/// In this example, the assignment to the `twasBrillig` constant calls this
/// Boolean literal initializer behind the scenes.
///
/// - Parameter value: The value of the new instance.
init(booleanLiteral value: BooleanLiteralType)
}
public protocol _ExpressibleByBuiltinUnicodeScalarLiteral {
init(_builtinUnicodeScalarLiteral value: Builtin.Int32)
}
/// A type that can be initialized with a string literal containing a single
/// Unicode scalar value.
///
/// The `String`, `StaticString`, `Character`, and `Unicode.Scalar` types all
/// conform to the `ExpressibleByUnicodeScalarLiteral` protocol. You can
/// initialize a variable of any of these types using a string literal that
/// holds a single Unicode scalar.
///
/// let ñ: Unicode.Scalar = "ñ"
/// print(ñ)
/// // Prints "ñ"
///
/// Conforming to ExpressibleByUnicodeScalarLiteral
/// ===============================================
///
/// To add `ExpressibleByUnicodeScalarLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByUnicodeScalarLiteral {
/// A type that represents a Unicode scalar literal.
///
/// Valid types for `UnicodeScalarLiteralType` are `Unicode.Scalar`,
/// `Character`, `String`, and `StaticString`.
associatedtype UnicodeScalarLiteralType : _ExpressibleByBuiltinUnicodeScalarLiteral
/// Creates an instance initialized to the given value.
///
/// - Parameter value: The value of the new instance.
init(unicodeScalarLiteral value: UnicodeScalarLiteralType)
}
public protocol _ExpressibleByBuiltinUTF16ExtendedGraphemeClusterLiteral
: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral {
init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf16CodeUnitCount: Builtin.Word)
}
public protocol _ExpressibleByBuiltinExtendedGraphemeClusterLiteral
: _ExpressibleByBuiltinUnicodeScalarLiteral {
init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1)
}
/// A type that can be initialized with a string literal containing a single
/// extended grapheme cluster.
///
/// An *extended grapheme cluster* is a group of one or more Unicode scalar
/// values that approximates a single user-perceived character. Many
/// individual characters, such as "é", "김", and "🇮🇳", can be made up of
/// multiple Unicode scalar values. These code points are combined by
/// Unicode's boundary algorithms into extended grapheme clusters.
///
/// The `String`, `StaticString`, and `Character` types conform to the
/// `ExpressibleByExtendedGraphemeClusterLiteral` protocol. You can initialize
/// a variable or constant of any of these types using a string literal that
/// holds a single character.
///
/// let snowflake: Character = "❄︎"
/// print(snowflake)
/// // Prints "❄︎"
///
/// Conforming to ExpressibleByExtendedGraphemeClusterLiteral
/// =========================================================
///
/// To add `ExpressibleByExtendedGraphemeClusterLiteral` conformance to your
/// custom type, implement the required initializer.
public protocol ExpressibleByExtendedGraphemeClusterLiteral
: ExpressibleByUnicodeScalarLiteral {
/// A type that represents an extended grapheme cluster literal.
///
/// Valid types for `ExtendedGraphemeClusterLiteralType` are `Character`,
/// `String`, and `StaticString`.
associatedtype ExtendedGraphemeClusterLiteralType
: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral
/// Creates an instance initialized to the given value.
///
/// - Parameter value: The value of the new instance.
init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType)
}
extension ExpressibleByExtendedGraphemeClusterLiteral
where ExtendedGraphemeClusterLiteralType == UnicodeScalarLiteralType {
@inlinable // FIXME(sil-serialize-all)
@_transparent
public init(unicodeScalarLiteral value: ExtendedGraphemeClusterLiteralType) {
self.init(extendedGraphemeClusterLiteral: value)
}
}
public protocol _ExpressibleByBuiltinStringLiteral
: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral {
init(
_builtinStringLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1)
}
public protocol _ExpressibleByBuiltinUTF16StringLiteral
: _ExpressibleByBuiltinStringLiteral {
init(
_builtinUTF16StringLiteral start: Builtin.RawPointer,
utf16CodeUnitCount: Builtin.Word)
}
public protocol _ExpressibleByBuiltinConstStringLiteral
: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral {
init(_builtinConstStringLiteral constantString: Builtin.RawPointer)
}
public protocol _ExpressibleByBuiltinConstUTF16StringLiteral
: _ExpressibleByBuiltinConstStringLiteral {
init(_builtinConstUTF16StringLiteral constantUTF16String: Builtin.RawPointer)
}
/// A type that can be initialized with a string literal.
///
/// The `String` and `StaticString` types conform to the
/// `ExpressibleByStringLiteral` protocol. You can initialize a variable or
/// constant of either of these types using a string literal of any length.
///
/// let picnicGuest = "Deserving porcupine"
///
/// Conforming to ExpressibleByStringLiteral
/// ========================================
///
/// To add `ExpressibleByStringLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByStringLiteral
: ExpressibleByExtendedGraphemeClusterLiteral {
/// A type that represents a string literal.
///
/// Valid types for `StringLiteralType` are `String` and `StaticString`.
associatedtype StringLiteralType : _ExpressibleByBuiltinStringLiteral
/// Creates an instance initialized to the given string value.
///
/// - Parameter value: The value of the new instance.
init(stringLiteral value: StringLiteralType)
}
extension ExpressibleByStringLiteral
where StringLiteralType == ExtendedGraphemeClusterLiteralType {
@inlinable // FIXME(sil-serialize-all)
@_transparent
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(stringLiteral: value)
}
}
/// A type that can be initialized using an array literal.
///
/// An array literal is a simple way of expressing a list of values. Simply
/// surround a comma-separated list of values, instances, or literals with
/// square brackets to create an array literal. You can use an array literal
/// anywhere an instance of an `ExpressibleByArrayLiteral` type is expected: as
/// a value assigned to a variable or constant, as a parameter to a method or
/// initializer, or even as the subject of a nonmutating operation like
/// `map(_:)` or `filter(_:)`.
///
/// Arrays, sets, and option sets all conform to `ExpressibleByArrayLiteral`,
/// and your own custom types can as well. Here's an example of creating a set
/// and an array using array literals:
///
/// let employeesSet: Set<String> = ["Amir", "Jihye", "Dave", "Alessia", "Dave"]
/// print(employeesSet)
/// // Prints "["Amir", "Dave", "Jihye", "Alessia"]"
///
/// let employeesArray: [String] = ["Amir", "Jihye", "Dave", "Alessia", "Dave"]
/// print(employeesArray)
/// // Prints "["Amir", "Jihye", "Dave", "Alessia", "Dave"]"
///
/// The `Set` and `Array` types each handle array literals in their own way to
/// create new instances. In this case, the newly created set drops the
/// duplicate value ("Dave") and doesn't maintain the order of the array
/// literal's elements. The new array, on the other hand, matches the order
/// and number of elements provided.
///
/// - Note: An array literal is not the same as an `Array` instance. You can't
/// initialize a type that conforms to `ExpressibleByArrayLiteral` simply by
/// assigning an existing array.
///
/// let anotherSet: Set = employeesArray
/// // error: cannot convert value of type '[String]' to specified type 'Set'
///
/// Type Inference of Array Literals
/// ================================
///
/// Whenever possible, Swift's compiler infers the full intended type of your
/// array literal. Because `Array` is the default type for an array literal,
/// without writing any other code, you can declare an array with a particular
/// element type by providing one or more values.
///
/// In this example, the compiler infers the full type of each array literal.
///
/// let integers = [1, 2, 3]
/// // 'integers' has type '[Int]'
///
/// let strings = ["a", "b", "c"]
/// // 'strings' has type '[String]'
///
/// An empty array literal alone doesn't provide enough information for the
/// compiler to infer the intended type of the `Array` instance. When using an
/// empty array literal, specify the type of the variable or constant.
///
/// var emptyArray: [Bool] = []
/// // 'emptyArray' has type '[Bool]'
///
/// Because many functions and initializers fully specify the types of their
/// parameters, you can often use an array literal with or without elements as
/// a parameter. For example, the `sum(_:)` function shown here takes an `Int`
/// array as a parameter:
///
/// func sum(values: [Int]) -> Int {
/// return values.reduce(0, +)
/// }
///
/// let sumOfFour = sum([5, 10, 15, 20])
/// // 'sumOfFour' == 50
///
/// let sumOfNone = sum([])
/// // 'sumOfNone' == 0
///
/// When you call a function that does not fully specify its parameters' types,
/// use the type-cast operator (`as`) to specify the type of an array literal.
/// For example, the `log(name:value:)` function shown here has an
/// unconstrained generic `value` parameter.
///
/// func log<T>(name name: String, value: T) {
/// print("\(name): \(value)")
/// }
///
/// log(name: "Four integers", value: [5, 10, 15, 20])
/// // Prints "Four integers: [5, 10, 15, 20]"
///
/// log(name: "Zero integers", value: [] as [Int])
/// // Prints "Zero integers: []"
///
/// Conforming to ExpressibleByArrayLiteral
/// =======================================
///
/// Add the capability to be initialized with an array literal to your own
/// custom types by declaring an `init(arrayLiteral:)` initializer. The
/// following example shows the array literal initializer for a hypothetical
/// `OrderedSet` type, which has setlike semantics but maintains the order of
/// its elements.
///
/// struct OrderedSet<Element: Hashable>: Collection, SetAlgebra {
/// // implementation details
/// }
///
/// extension OrderedSet: ExpressibleByArrayLiteral {
/// init(arrayLiteral: Element...) {
/// self.init()
/// for element in arrayLiteral {
/// self.append(element)
/// }
/// }
/// }
public protocol ExpressibleByArrayLiteral {
/// The type of the elements of an array literal.
associatedtype ArrayLiteralElement
/// Creates an instance initialized with the given elements.
init(arrayLiteral elements: ArrayLiteralElement...)
}
/// A type that can be initialized using a dictionary literal.
///
/// A dictionary literal is a simple way of writing a list of key-value pairs.
/// You write each key-value pair with a colon (`:`) separating the key and
/// the value. The dictionary literal is made up of one or more key-value
/// pairs, separated by commas and surrounded with square brackets.
///
/// To declare a dictionary, assign a dictionary literal to a variable or
/// constant:
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana",
/// "JP": "Japan", "US": "United States"]
/// // 'countryCodes' has type [String: String]
///
/// print(countryCodes["BR"]!)
/// // Prints "Brazil"
///
/// When the context provides enough type information, you can use a special
/// form of the dictionary literal, square brackets surrounding a single
/// colon, to initialize an empty dictionary.
///
/// var frequencies: [String: Int] = [:]
/// print(frequencies.count)
/// // Prints "0"
///
/// - Note: A dictionary literal is *not* the same as an instance of
/// `Dictionary` or the similarly named `DictionaryLiteral` type. You can't
/// initialize a type that conforms to `ExpressibleByDictionaryLiteral` simply
/// by assigning an instance of one of these types.
///
/// Conforming to the ExpressibleByDictionaryLiteral Protocol
/// =========================================================
///
/// To add the capability to be initialized with a dictionary literal to your
/// own custom types, declare an `init(dictionaryLiteral:)` initializer. The
/// following example shows the dictionary literal initializer for a
/// hypothetical `CountedSet` type, which uses setlike semantics while keeping
/// track of the count for duplicate elements:
///
/// struct CountedSet<Element: Hashable>: Collection, SetAlgebra {
/// // implementation details
///
/// /// Updates the count stored in the set for the given element,
/// /// adding the element if necessary.
/// ///
/// /// - Parameter n: The new count for `element`. `n` must be greater
/// /// than or equal to zero.
/// /// - Parameter element: The element to set the new count on.
/// mutating func updateCount(_ n: Int, for element: Element)
/// }
///
/// extension CountedSet: ExpressibleByDictionaryLiteral {
/// init(dictionaryLiteral elements: (Element, Int)...) {
/// self.init()
/// for (element, count) in elements {
/// self.updateCount(count, for: element)
/// }
/// }
/// }
public protocol ExpressibleByDictionaryLiteral {
/// The key type of a dictionary literal.
associatedtype Key
/// The value type of a dictionary literal.
associatedtype Value
/// Creates an instance initialized with the given key-value pairs.
init(dictionaryLiteral elements: (Key, Value)...)
}
/// A type that can be initialized by string interpolation with a string
/// literal that includes expressions.
///
/// Use string interpolation to include one or more expressions in a string
/// literal, wrapped in a set of parentheses and prefixed by a backslash. For
/// example:
///
/// let price = 2
/// let number = 3
/// let message = "One cookie: $\(price), \(number) cookies: $\(price * number)."
/// print(message)
/// // Prints "One cookie: $2, 3 cookies: $6."
///
/// Conforming to the ExpressibleByStringInterpolation Protocol
/// ===========================================================
///
/// The `ExpressibleByStringInterpolation` protocol is deprecated. Do not add
/// new conformances to the protocol.
@available(*, deprecated, message: "it will be replaced or redesigned in Swift 4.0. Instead of conforming to 'ExpressibleByStringInterpolation', consider adding an 'init(_:String)'")
public typealias ExpressibleByStringInterpolation = _ExpressibleByStringInterpolation
public protocol _ExpressibleByStringInterpolation {
/// Creates an instance by concatenating the given values.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you use string interpolation. For example:
///
/// let s = "\(5) x \(2) = \(5 * 2)"
/// print(s)
/// // Prints "5 x 2 = 10"
///
/// After calling `init(stringInterpolationSegment:)` with each segment of
/// the string literal, this initializer is called with their string
/// representations.
///
/// - Parameter strings: An array of instances of the conforming type.
init(stringInterpolation strings: Self...)
/// Creates an instance containing the appropriate representation for the
/// given value.
///
/// Do not call this initializer directly. It is used by the compiler for
/// each string interpolation segment when you use string interpolation. For
/// example:
///
/// let s = "\(5) x \(2) = \(5 * 2)"
/// print(s)
/// // Prints "5 x 2 = 10"
///
/// This initializer is called five times when processing the string literal
/// in the example above; once each for the following: the integer `5`, the
/// string `" x "`, the integer `2`, the string `" = "`, and the result of
/// the expression `5 * 2`.
///
/// - Parameter expr: The expression to represent.
init<T>(stringInterpolationSegment expr: T)
}
/// A type that can be initialized using a color literal (e.g.
/// `#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)`).
public protocol _ExpressibleByColorLiteral {
/// Creates an instance initialized with the given properties of a color
/// literal.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using a color literal.
init(_colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float)
}
extension _ExpressibleByColorLiteral {
@inlinable // FIXME(sil-serialize-all)
@available(swift, deprecated: 3.2, obsoleted: 4.0,
message: "This initializer is only meant to be used by color literals")
public init(
colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float
) {
self.init(
_colorLiteralRed: red, green: green, blue: blue, alpha: alpha)
}
}
/// A type that can be initialized using an image literal (e.g.
/// `#imageLiteral(resourceName: "hi.png")`).
public protocol _ExpressibleByImageLiteral {
/// Creates an instance initialized with the given resource name.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using an image literal.
init(imageLiteralResourceName path: String)
}
/// A type that can be initialized using a file reference literal (e.g.
/// `#fileLiteral(resourceName: "resource.txt")`).
public protocol _ExpressibleByFileReferenceLiteral {
/// Creates an instance initialized with the given resource name.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using a file reference literal.
init(fileReferenceLiteralResourceName path: String)
}
/// A container is destructor safe if whether it may store to memory on
/// destruction only depends on its type parameters destructors.
/// For example, whether `Array<Element>` may store to memory on destruction
/// depends only on `Element`.
/// If `Element` is an `Int` we know the `Array<Int>` does not store to memory
/// during destruction. If `Element` is an arbitrary class
/// `Array<MemoryUnsafeDestructorClass>` then the compiler will deduce may
/// store to memory on destruction because `MemoryUnsafeDestructorClass`'s
/// destructor may store to memory on destruction.
/// If in this example during `Array`'s destructor we would call a method on any
/// type parameter - say `Element.extraCleanup()` - that could store to memory,
/// then Array would no longer be a _DestructorSafeContainer.
public protocol _DestructorSafeContainer {
}
// Deprecated by SE-0115.
@available(*, deprecated, renamed: "ExpressibleByNilLiteral")
public typealias NilLiteralConvertible
= ExpressibleByNilLiteral
@available(*, deprecated, renamed: "_ExpressibleByBuiltinIntegerLiteral")
public typealias _BuiltinIntegerLiteralConvertible
= _ExpressibleByBuiltinIntegerLiteral
@available(*, deprecated, renamed: "ExpressibleByIntegerLiteral")
public typealias IntegerLiteralConvertible
= ExpressibleByIntegerLiteral
@available(*, deprecated, renamed: "_ExpressibleByBuiltinFloatLiteral")
public typealias _BuiltinFloatLiteralConvertible
= _ExpressibleByBuiltinFloatLiteral
@available(*, deprecated, renamed: "ExpressibleByFloatLiteral")
public typealias FloatLiteralConvertible
= ExpressibleByFloatLiteral
@available(*, deprecated, renamed: "_ExpressibleByBuiltinBooleanLiteral")
public typealias _BuiltinBooleanLiteralConvertible
= _ExpressibleByBuiltinBooleanLiteral
@available(*, deprecated, renamed: "ExpressibleByBooleanLiteral")
public typealias BooleanLiteralConvertible
= ExpressibleByBooleanLiteral
@available(*, deprecated, renamed: "_ExpressibleByBuiltinUnicodeScalarLiteral")
public typealias _BuiltinUnicodeScalarLiteralConvertible
= _ExpressibleByBuiltinUnicodeScalarLiteral
@available(*, deprecated, renamed: "ExpressibleByUnicodeScalarLiteral")
public typealias UnicodeScalarLiteralConvertible
= ExpressibleByUnicodeScalarLiteral
@available(*, deprecated, renamed: "_ExpressibleByBuiltinExtendedGraphemeClusterLiteral")
public typealias _BuiltinExtendedGraphemeClusterLiteralConvertible
= _ExpressibleByBuiltinExtendedGraphemeClusterLiteral
@available(*, deprecated, renamed: "ExpressibleByExtendedGraphemeClusterLiteral")
public typealias ExtendedGraphemeClusterLiteralConvertible
= ExpressibleByExtendedGraphemeClusterLiteral
@available(*, deprecated, renamed: "_ExpressibleByBuiltinStringLiteral")
public typealias _BuiltinStringLiteralConvertible
= _ExpressibleByBuiltinStringLiteral
@available(*, deprecated, renamed: "_ExpressibleByBuiltinUTF16StringLiteral")
public typealias _BuiltinUTF16StringLiteralConvertible
= _ExpressibleByBuiltinUTF16StringLiteral
@available(*, deprecated, renamed: "ExpressibleByStringLiteral")
public typealias StringLiteralConvertible
= ExpressibleByStringLiteral
@available(*, deprecated, renamed: "ExpressibleByArrayLiteral")
public typealias ArrayLiteralConvertible
= ExpressibleByArrayLiteral
@available(*, deprecated, renamed: "ExpressibleByDictionaryLiteral")
public typealias DictionaryLiteralConvertible
= ExpressibleByDictionaryLiteral
@available(*, deprecated, message: "it will be replaced or redesigned in Swift 4.0. Instead of conforming to 'StringInterpolationConvertible', consider adding an 'init(_:String)'")
public typealias StringInterpolationConvertible
= ExpressibleByStringInterpolation
@available(*, deprecated, renamed: "_ExpressibleByColorLiteral")
public typealias _ColorLiteralConvertible
= _ExpressibleByColorLiteral
@available(*, deprecated, renamed: "_ExpressibleByImageLiteral")
public typealias _ImageLiteralConvertible
= _ExpressibleByImageLiteral
@available(*, deprecated, renamed: "_ExpressibleByFileReferenceLiteral")
public typealias _FileReferenceLiteralConvertible
= _ExpressibleByFileReferenceLiteral
| e5f28846ee6017c4c263c4d6174f7779 | 39.882486 | 183 | 0.696692 | false | false | false | false |
e-liu/LayoutKit | refs/heads/develop | Carthage/Checkouts/LayoutKit/LayoutKitSampleApp/StackViewController.swift | apache-2.0 | 6 | // Copyright 2016 LinkedIn Corp.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import UIKit
import LayoutKit
/**
Uses a stack view to layout subviews.
*/
class StackViewController: UIViewController {
private var stackView: StackView!
override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = UIRectEdge()
stackView = StackView(axis: .vertical, spacing: 4)
stackView.addArrangedSubviews([
UILabel(text: "Nick"),
UILabel(text: "Software Engineer")
])
stackView.frame = view.bounds
stackView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
stackView.backgroundColor = UIColor.purple
view.addSubview(stackView)
}
}
extension UILabel {
convenience init(text: String) {
self.init()
self.text = text
}
}
| 27de917d4f72e628dc1b98571aff25a4 | 28.904762 | 131 | 0.682325 | false | false | false | false |
callam/Heimdall.swift | refs/heads/master | Heimdall/NSURLRequestExtensions.swift | apache-2.0 | 5 | import Foundation
/// An HTTP authentication is used for authorizing requests to either the token
/// or the resource endpoint.
public enum HTTPAuthentication: Equatable {
/// HTTP Basic Authentication.
///
/// :param: username The username.
/// :param: password The password.
case BasicAuthentication(username: String, password: String)
/// Access Token Authentication.
///
/// :param: _ The access token.
case AccessTokenAuthentication(OAuthAccessToken)
/// Returns the authentication encoded as `String` suitable for the HTTP
/// `Authorization` header.
private var value: String? {
switch self {
case .BasicAuthentication(let username, let password):
if let credentials = "\(username):\(password)"
.dataUsingEncoding(NSASCIIStringEncoding)?
.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(0)) {
return "Basic \(credentials)"
} else {
return nil
}
case .AccessTokenAuthentication(let accessToken):
return "\(accessToken.tokenType) \(accessToken.accessToken)"
}
}
}
public func == (lhs: HTTPAuthentication, rhs: HTTPAuthentication) -> Bool {
switch (lhs, rhs) {
case (.BasicAuthentication(let lusername, let lpassword), .BasicAuthentication(let rusername, let rpassword)):
return lusername == rusername
&& lpassword == rpassword
case (.AccessTokenAuthentication(let laccessToken), .AccessTokenAuthentication(let raccessToken)):
return laccessToken == raccessToken
default:
return false
}
}
private let HTTPRequestHeaderFieldAuthorization = "Authorization"
public extension NSURLRequest {
/// Returns the HTTP `Authorization` header value or `nil` if not set.
public var HTTPAuthorization: String? {
return self.valueForHTTPHeaderField(HTTPRequestHeaderFieldAuthorization)
}
}
public extension NSMutableURLRequest {
/// Sets the HTTP `Authorization` header value.
///
/// :param: value The value to be set or `nil`.
///
/// TODO: Declarations in extensions cannot override yet.
public func setHTTPAuthorization(value: String?) {
self.setValue(value, forHTTPHeaderField: HTTPRequestHeaderFieldAuthorization)
}
/// Sets the HTTP `Authorization` header value using the given HTTP
/// authentication.
///
/// :param: authentication The HTTP authentication to be set.
public func setHTTPAuthorization(authentication: HTTPAuthentication) {
self.setHTTPAuthorization(authentication.value)
}
/// Sets the HTTP body using the given paramters encoded as query string.
///
/// :param: parameters The parameters to be encoded or `nil`.
///
/// TODO: Tests crash without named parameter.
public func setHTTPBody(#parameters: [String: AnyObject]?) {
if let parameters = parameters {
var components: [(String, String)] = []
for (key, value) in parameters {
components += queryComponents(key, value)
}
var bodyString = join("&", components.map { "\($0)=\($1)" } )
HTTPBody = bodyString.dataUsingEncoding(NSUTF8StringEncoding)
} else {
HTTPBody = nil
}
}
// Taken from https://github.com/Alamofire/Alamofire/blob/master/Source/ParameterEncoding.swift#L136
private func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.extend([(escapeQuery(key), escapeQuery("\(value)"))])
}
return components
}
private func escapeQuery(string: String) -> String {
let legalURLCharactersToBeEscaped: CFStringRef = ":&=;+!@#$()',*"
let charactersToLeaveUnescaped: CFStringRef = "[]."
return CFURLCreateStringByAddingPercentEscapes(nil, string, charactersToLeaveUnescaped, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as! String
}
}
| 1812e9afe9474062ad20becbe4a5978d | 37.655172 | 177 | 0.642953 | false | false | false | false |
MartinLasek/vaporberlinBE | refs/heads/master | Sources/App/Backend/Token/Model/Token.swift | mit | 1 | import FluentProvider
import Vapor
import Crypto
final class Token: Model {
let storage = Storage()
let token: String
let userId: Identifier
init(token: String, user: User) throws {
self.token = token
self.userId = try user.assertExists()
}
init(row: Row) throws {
self.token = try row.get("token")
self.userId = try row.get(User.foreignIdKey)
}
func makeRow() throws -> Row{
var row = Row()
try row.set("token", token)
try row.set(User.foreignIdKey, userId)
return row
}
}
extension Token: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self) { builder in
builder.id()
builder.string("token")
builder.foreignId(for: User.self)
}
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
/// - create relation to user
extension Token {
var user: Parent<Token, User> {
return parent(id: userId)
}
}
/// - generate random token
/// - initialize model with token and given user
/// - return Token-Object
extension Token {
static func generate(for user: User) throws -> Token {
let random = try Crypto.Random.bytes(count: 16)
return try Token(token: random.base64Encoded.makeString(), user: user)
}
}
/// - create JSON format
extension Token: JSONRepresentable {
func makeJSON() throws -> JSON {
var json = JSON()
try json.set("token", token)
return json
}
}
| 50f2a416be7ac02f1261814c053ed313 | 21.090909 | 74 | 0.657064 | false | false | false | false |
ZevEisenberg/Padiddle | refs/heads/main | Experiments/Path Smoothing Tester.playground/Contents.swift | mit | 1 | import UIKit
import PlaygroundSupport
final class PathView: UIView {
private var path: CGPath? = nil
class func smoothedPathSegment(points: [CGPoint]) -> CGPath {
assert(points.count == 4)
let p0 = points[3]
let p1 = points[2]
let p2 = points[1]
let p3 = points[0]
let c1 = CGPoint(
x: (p0.x + p1.x) / 2.0,
y: (p0.y + p1.y) / 2.0)
let c2 = CGPoint(
x: (p1.x + p2.x) / 2.0,
y: (p1.y + p2.y) / 2.0)
let c3 = CGPoint(
x: (p2.x + p3.x) / 2.0,
y: (p2.y + p3.y) / 2.0)
let len1 = sqrt(pow(p1.x - p0.x, 2.0) + pow(p1.y - p0.y, 2.0))
let len2 = sqrt(pow(p2.x - p1.x, 2.0) + pow(p2.y - p1.y, 2.0))
let len3 = sqrt(pow(p3.x - p2.x, 2.0) + pow(p3.y - p2.y, 2.0))
let divisor1 = len1 + len2
let divisor2 = len2 + len3
let k1 = len1 / divisor1
let k2 = len2 / divisor2
let m1 = CGPoint(
x: c1.x + (c2.x - c1.x) * k1,
y: c1.y + (c2.y - c1.y) * k1)
let m2 = CGPoint(
x: c2.x + (c3.x - c2.x) * k2,
y: c2.y + (c3.y - c2.y) * k2)
// Resulting control points. Here smooth_value is mentioned
// above coefficient K whose value should be in range [0...1].
let smoothValue = CGFloat(1.0)
let ctrl1: CGPoint = {
let x = m1.x + (c2.x - m1.x) * smoothValue + p1.x - m1.x
let y = m1.y + (c2.y - m1.y) * smoothValue + p1.y - m1.y
return CGPoint(x: x, y: y)
}()
let ctrl2: CGPoint = {
let x = m2.x + (c2.x - m2.x) * smoothValue + p2.x - m2.x
let y = m2.y + (c2.y - m2.y) * smoothValue + p2.y - m2.y
return CGPoint(x: x, y: y)
}()
let pathSegment = CGMutablePath()
pathSegment.move(to: p1)
pathSegment.addCurve(to: p2, control1: ctrl1, control2: ctrl2)
return pathSegment
}
func update(with points: [CGPoint]) {
assert(points.count == 4)
let mutablePath = CGMutablePath()
mutablePath.addPath(PathView.smoothedPathSegment(points: points))
path = mutablePath
setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
super.draw(rect)
guard let path = path else { return }
let uiPath = UIBezierPath(cgPath: path)
uiPath.lineWidth = 2
UIColor.red.setFill()
uiPath.stroke()
}
}
final class MovableView: UIView {
private let dragNotifier: () -> ()
init(frame: CGRect, dragNotifier: @escaping () -> ()) {
self.dragNotifier = dragNotifier
super.init(frame: frame)
isOpaque = false
let pan = UIPanGestureRecognizer(target: self, action: #selector(panned(_:)))
addGestureRecognizer(pan)
}
@available(*, unavailable) required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
UIColor.blue.setFill()
UIBezierPath(ovalIn: bounds).fill()
}
func panned(_ sender: UIPanGestureRecognizer) {
switch sender.state {
case .changed:
guard let superview = superview else {
fatalError()
}
let location = sender.location(in: superview)
center = location
dragNotifier()
default:
break
}
}
}
let pathView = PathView(frame: CGRect(x: 0, y: 0, width: 400, height: 300))
pathView.backgroundColor = .lightGray
let positions = [
CGPoint(x: 20, y: 20),
CGPoint(x: 50, y: 30),
CGPoint(x: 120, y: 20),
CGPoint(x: 180, y: 50),
]
let notifier = {
let centers = pathView.subviews.map { $0.center }
pathView.update(with: centers)
}
let movables = positions.map { point in
MovableView(frame: CGRect(origin: point, size: CGSize(width: 25, height: 25)), dragNotifier: notifier)
}
for view in movables {
pathView.addSubview(view)
}
notifier()
PlaygroundPage.current.liveView = pathView | 86274c6cb96656fd6902720667df0ebb | 26.904762 | 106 | 0.541331 | false | false | false | false |
NeilNie/Done- | refs/heads/master | Pods/Charts/Source/Charts/Renderers/YAxisRenderer.swift | apache-2.0 | 2 | //
// YAxisRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
@objc(ChartYAxisRenderer)
open class YAxisRenderer: AxisRendererBase
{
@objc public init(viewPortHandler: ViewPortHandler, yAxis: YAxis?, transformer: Transformer?)
{
super.init(viewPortHandler: viewPortHandler, transformer: transformer, axis: yAxis)
}
/// draws the y-axis labels to the screen
open override func renderAxisLabels(context: CGContext)
{
guard let yAxis = self.axis as? YAxis else { return }
if !yAxis.isEnabled || !yAxis.isDrawLabelsEnabled
{
return
}
let xoffset = yAxis.xOffset
let yoffset = yAxis.labelFont.lineHeight / 2.5 + yAxis.yOffset
let dependency = yAxis.axisDependency
let labelPosition = yAxis.labelPosition
var xPos = CGFloat(0.0)
var textAlign: NSTextAlignment
if dependency == .left
{
if labelPosition == .outsideChart
{
textAlign = .right
xPos = viewPortHandler.offsetLeft - xoffset
}
else
{
textAlign = .left
xPos = viewPortHandler.offsetLeft + xoffset
}
}
else
{
if labelPosition == .outsideChart
{
textAlign = .left
xPos = viewPortHandler.contentRight + xoffset
}
else
{
textAlign = .right
xPos = viewPortHandler.contentRight - xoffset
}
}
drawYLabels(
context: context,
fixedPosition: xPos,
positions: transformedPositions(),
offset: yoffset - yAxis.labelFont.lineHeight,
textAlign: textAlign)
}
open override func renderAxisLine(context: CGContext)
{
guard let yAxis = self.axis as? YAxis else { return }
if !yAxis.isEnabled || !yAxis.drawAxisLineEnabled
{
return
}
context.saveGState()
context.setStrokeColor(yAxis.axisLineColor.cgColor)
context.setLineWidth(yAxis.axisLineWidth)
if yAxis.axisLineDashLengths != nil
{
context.setLineDash(phase: yAxis.axisLineDashPhase, lengths: yAxis.axisLineDashLengths)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
if yAxis.axisDependency == .left
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
context.strokePath()
}
else
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom))
context.strokePath()
}
context.restoreGState()
}
/// draws the y-labels on the specified x-position
internal func drawYLabels(
context: CGContext,
fixedPosition: CGFloat,
positions: [CGPoint],
offset: CGFloat,
textAlign: NSTextAlignment)
{
guard
let yAxis = self.axis as? YAxis
else { return }
let labelFont = yAxis.labelFont
let labelTextColor = yAxis.labelTextColor
let from = yAxis.isDrawBottomYLabelEntryEnabled ? 0 : 1
let to = yAxis.isDrawTopYLabelEntryEnabled ? yAxis.entryCount : (yAxis.entryCount - 1)
for i in stride(from: from, to: to, by: 1)
{
let text = yAxis.getFormattedLabel(i)
ChartUtils.drawText(
context: context,
text: text,
point: CGPoint(x: fixedPosition, y: positions[i].y + offset),
align: textAlign,
attributes: [NSAttributedString.Key.font: labelFont, NSAttributedString.Key.foregroundColor: labelTextColor])
}
}
open override func renderGridLines(context: CGContext)
{
guard let
yAxis = self.axis as? YAxis
else { return }
if !yAxis.isEnabled
{
return
}
if yAxis.drawGridLinesEnabled
{
let positions = transformedPositions()
context.saveGState()
defer { context.restoreGState() }
context.clip(to: self.gridClippingRect)
context.setShouldAntialias(yAxis.gridAntialiasEnabled)
context.setStrokeColor(yAxis.gridColor.cgColor)
context.setLineWidth(yAxis.gridLineWidth)
context.setLineCap(yAxis.gridLineCap)
if yAxis.gridLineDashLengths != nil
{
context.setLineDash(phase: yAxis.gridLineDashPhase, lengths: yAxis.gridLineDashLengths)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
// draw the grid
for i in 0 ..< positions.count
{
drawGridLine(context: context, position: positions[i])
}
}
if yAxis.drawZeroLineEnabled
{
// draw zero line
drawZeroLine(context: context)
}
}
@objc open var gridClippingRect: CGRect
{
var contentRect = viewPortHandler.contentRect
let dy = self.axis?.gridLineWidth ?? 0.0
contentRect.origin.y -= dy / 2.0
contentRect.size.height += dy
return contentRect
}
@objc open func drawGridLine(
context: CGContext,
position: CGPoint)
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y))
context.strokePath()
}
@objc open func transformedPositions() -> [CGPoint]
{
guard
let yAxis = self.axis as? YAxis,
let transformer = self.transformer
else { return [CGPoint]() }
var positions = [CGPoint]()
positions.reserveCapacity(yAxis.entryCount)
let entries = yAxis.entries
for i in stride(from: 0, to: yAxis.entryCount, by: 1)
{
positions.append(CGPoint(x: 0.0, y: entries[i]))
}
transformer.pointValuesToPixel(&positions)
return positions
}
/// Draws the zero line at the specified position.
@objc open func drawZeroLine(context: CGContext)
{
guard
let yAxis = self.axis as? YAxis,
let transformer = self.transformer,
let zeroLineColor = yAxis.zeroLineColor
else { return }
context.saveGState()
defer { context.restoreGState() }
var clippingRect = viewPortHandler.contentRect
clippingRect.origin.y -= yAxis.zeroLineWidth / 2.0
clippingRect.size.height += yAxis.zeroLineWidth
context.clip(to: clippingRect)
context.setStrokeColor(zeroLineColor.cgColor)
context.setLineWidth(yAxis.zeroLineWidth)
let pos = transformer.pixelForValues(x: 0.0, y: 0.0)
if yAxis.zeroLineDashLengths != nil
{
context.setLineDash(phase: yAxis.zeroLineDashPhase, lengths: yAxis.zeroLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: pos.y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: pos.y))
context.drawPath(using: CGPathDrawingMode.stroke)
}
open override func renderLimitLines(context: CGContext)
{
guard
let yAxis = self.axis as? YAxis,
let transformer = self.transformer
else { return }
var limitLines = yAxis.limitLines
if limitLines.count == 0
{
return
}
context.saveGState()
let trans = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for i in 0 ..< limitLines.count
{
let l = limitLines[i]
if !l.isEnabled
{
continue
}
context.saveGState()
defer { context.restoreGState() }
var clippingRect = viewPortHandler.contentRect
clippingRect.origin.y -= l.lineWidth / 2.0
clippingRect.size.height += l.lineWidth
context.clip(to: clippingRect)
position.x = 0.0
position.y = CGFloat(l.limit)
position = position.applying(trans)
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y))
context.setStrokeColor(l.lineColor.cgColor)
context.setLineWidth(l.lineWidth)
if l.lineDashLengths != nil
{
context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.strokePath()
let label = l.label
// if drawing the limit-value label is enabled
if l.drawLabelEnabled && label.count > 0
{
let labelLineHeight = l.valueFont.lineHeight
let xOffset: CGFloat = 4.0 + l.xOffset
let yOffset: CGFloat = l.lineWidth + labelLineHeight + l.yOffset
if l.labelPosition == .rightTop
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y - yOffset),
align: .right,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
else if l.labelPosition == .rightBottom
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y + yOffset - labelLineHeight),
align: .right,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
else if l.labelPosition == .leftTop
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y - yOffset),
align: .left,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
else
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y + yOffset - labelLineHeight),
align: .left,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
}
}
context.restoreGState()
}
}
| edc012e6c00731f416e2a69ca4185800 | 31.522959 | 137 | 0.529689 | false | false | false | false |
narner/AudioKit | refs/heads/master | Playgrounds/AudioKitPlaygrounds/Playgrounds/Synthesis.playground/Pages/Microtonality.xcplaygroundpage/Contents.swift | mit | 1 | //: ## Microtonality
import AudioKitPlaygrounds
import AudioKit
// SEQUENCER PARAMETERS
let playRate: Double = 4
var transposition: Int = 0
var performanceCounter: Int = 0
// OSC
let osc = AKMorphingOscillatorBank()
osc.index = 0.8
osc.attackDuration = 0.001
osc.decayDuration = 0.25
osc.sustainLevel = 0.238_186
osc.releaseDuration = 0.125
// FILTER
let filter = AKKorgLowPassFilter(osc)
filter.cutoffFrequency = 5_500
filter.resonance = 0.2
let generatorBooster = AKBooster(filter)
generatorBooster.gain = 0.618
// DELAY
let delay = AKDelay(generatorBooster)
delay.time = 1.0 / playRate
delay.feedback = 0.618
delay.lowPassCutoff = 12_048
delay.dryWetMix = 0.75
let delayBooster = AKBooster(delay)
delayBooster.gain = 1.550_8
// REVERB
let reverb = AKCostelloReverb(delayBooster)
reverb.feedback = 0.758_816_18
reverb.cutoffFrequency = 2_222 + 1_000
let reverbBooster = AKBooster(reverb)
reverbBooster.gain = 0.746_7
// MIX
let mixer = AKMixer(generatorBooster, reverbBooster)
// MICROTONAL PRESETS
var presetDictionary = [String: () -> Void]()
let tuningTable = AKPolyphonicNode.tuningTable
presetDictionary["Ahir Bhairav"] = { tuningTable.presetPersian17NorthIndian19AhirBhairav() }
presetDictionary["Basant Mukhari"] = { tuningTable.presetPersian17NorthIndian21BasantMukhari() }
presetDictionary["Champakali"] = { tuningTable.presetPersian17NorthIndian22Champakali() }
presetDictionary["Chandra Kanada"] = { tuningTable.presetPersian17NorthIndian20ChandraKanada() }
presetDictionary["Diaphonic Tetrachhord"] = { tuningTable.presetDiaphonicTetrachord() }
presetDictionary["ET 5"] = { tuningTable.equalTemperament(notesPerOctave: 5) }
presetDictionary["Hexany (1,5,9,15)"] = { tuningTable.hexany(1, 5, 9, 15) }
presetDictionary["Hexany (3,4.,7.,10.)"] = { tuningTable.hexany(3, 4.051, 7.051, 10.051) }
presetDictionary["Highland Bagpipes"] = { tuningTable.presetHighlandBagPipes() }
presetDictionary["Madhubanti"] = { tuningTable.presetPersian17NorthIndian17Madhubanti() }
presetDictionary["Mohan Kauns"] = { tuningTable.presetPersian17NorthIndian24MohanKauns() }
presetDictionary["MOS 0.2381 9 tones"] = { tuningTable.momentOfSymmetry(generator: 0.238_186, level: 6) }
presetDictionary["MOS 0.2641 7 tones"] = { tuningTable.momentOfSymmetry(generator: 0.264_100, level: 5) }
presetDictionary["MOS 0.2926 7 tones"] = { tuningTable.momentOfSymmetry(generator: 0.292_626, level: 5, murchana: 3) }
presetDictionary["MOS 0.5833 7 tones"] = { tuningTable.momentOfSymmetry(generator: 0.583_333, level: 5) }
presetDictionary["MOS 0.5833 7 tones Mode 2"] = { tuningTable.momentOfSymmetry(generator: 0.583_333, level: 5, murchana: 2) }
presetDictionary["Nat Bhairav"] = { tuningTable.presetPersian17NorthIndian18NatBhairav() }
presetDictionary["Patdeep"] = { tuningTable.presetPersian17NorthIndian23Patdeep() }
presetDictionary["Recurrence Relation"] = { tuningTable.presetRecurrenceRelation01() }
presetDictionary["Tetrany Major (1,5,9,15)"] = { tuningTable.majorTetrany(1, 5, 9, 15) }
presetDictionary["Tetrany Minor (1,5,9,15)"] = { tuningTable.minorTetrany(1, 5, 9, 15) }
let presetArray = presetDictionary.keys.sorted()
let numTunings = presetArray.count
// SELECT A TUNING
func selectTuning(_ index: Int) {
let i = index % numTunings
let key = presetArray[i]
presetDictionary[key]?()
}
// DEFAULT TUNING
selectTuning(0)
let sequencerPatterns: [String: [Int]] = [
"Up Down": [0, 1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1],
"Arp 1": [1, 0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 4, 5, 3, 4, 2, 3, 1, 2, 0, 1],
"Arp 2": [0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7, 9, 8, 6, 7, 5, 6, 4, 5, 3, 4, 2, 3, 1]]
let sequencerPatternPresets = sequencerPatterns.keys.sorted()
var sequencerPattern = sequencerPatterns[sequencerPatternPresets[0]]!
// SEQUENCER CALCULATION
func nnCalc(_ counter: Int) -> MIDINoteNumber {
// negative time
if counter < 0 {
return 0
}
let npo = sequencerPattern.count
var note: Int = counter % npo
note = sequencerPattern[note]
let rootNN: Int = 60
let nn = MIDINoteNumber(note + rootNN + transposition)
return nn
}
// periodic function for arpeggio
let sequencerFunction = AKPeriodicFunction(frequency: playRate) {
// send note off for notes in the past
let pastNN = nnCalc(performanceCounter - 2)
osc.stop(noteNumber: pastNN)
// send note on for notes in the present
let presentNN = nnCalc(performanceCounter)
let frequency = AKPolyphonicNode.tuningTable.frequency(forNoteNumber: presentNN)
osc.play(noteNumber: presentNN, velocity: 127, frequency: frequency)
performanceCounter += 1
}
// Start Audio
AudioKit.output = mixer
AudioKit.start(withPeriodicFunctions: sequencerFunction)
sequencerFunction.start()
import AudioKitUI
class LiveView: AKLiveViewController {
override func viewDidLoad() {
addTitle("Microtonal Morphing Oscillator")
addView(AKPresetLoaderView(presets: presetArray) { preset in
presetDictionary[preset]?()
})
addView(AKPresetLoaderView(presets: sequencerPatternPresets) { preset in
osc.reset()
sequencerPattern = sequencerPatterns[preset]!
})
addView(AKSlider(property: "MIDI Transposition",
value: Double(transposition),
range: -16 ... 16,
format: "%.0f"
) { sliderValue in
transposition = Int(sliderValue)
osc.reset()
})
addView(AKSlider(property: "OSC Morph Index", value: osc.index, range: 0 ... 3) { sliderValue in
osc.index = sliderValue
})
addView(AKSlider(property: "OSC Gain", value: generatorBooster.gain, range: 0 ... 4) { sliderValue in
generatorBooster.gain = sliderValue
})
addView(AKSlider(property: "FILTER Frequency Cutoff",
value: filter.cutoffFrequency,
range: 1 ... 12_000
) { sliderValue in
filter.cutoffFrequency = sliderValue
})
addView(AKSlider(property: "FILTER Frequency Resonance",
value: filter.resonance,
range: 0 ... 4
) { sliderValue in
filter.resonance = sliderValue
})
addView(AKSlider(property: "OSC Amp Attack",
value: osc.attackDuration,
range: 0 ... 2,
format: "%0.3f s"
) { sliderValue in
osc.attackDuration = sliderValue
})
addView(AKSlider(property: "OSC Amp Decay",
value: osc.decayDuration,
range: 0 ... 2,
format: "%0.3f s"
) { sliderValue in
osc.decayDuration = sliderValue
})
addView(AKSlider(property: "OSC Amp Sustain",
value: osc.sustainLevel,
range: 0 ... 2,
format: "%0.3f s"
) { sliderValue in
osc.sustainLevel = sliderValue
})
addView(AKSlider(property: "OSC Amp Release",
value: osc.releaseDuration,
range: 0 ... 2,
format: "%0.3f s"
) { sliderValue in
osc.releaseDuration = sliderValue
})
addView(AKSlider(property: "Detuning Offset",
value: osc.detuningOffset,
range: -1_200 ... 1_200,
format: "%0.1f Cents"
) { sliderValue in
osc.detuningOffset = sliderValue
})
addView(AKSlider(property: "Detuning Multiplier",
value: osc.detuningMultiplier,
range: 0.5 ... 2.0,
taper: log(3) / log(2)
) { sliderValue in
osc.detuningMultiplier = sliderValue
})
}
}
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = LiveView()
| e311c787baf48af4ac4d0ece198cfed2 | 35.035556 | 125 | 0.635792 | false | false | false | false |
BalestraPatrick/Tweetometer | refs/heads/master | Carthage/Checkouts/twitter-kit-ios/DemoApp/DemoApp/Authentication/AuthenticationViewController.swift | mit | 2 | //
// AuthenticationViewController.swift
// FabricSampleApp
//
// Created by Steven Hepting on 8/19/15.
// Copyright (c) 2015 Twitter. All rights reserved.
//
import UIKit
extension CGRect {
func offset(offsetValue: Int) -> CGRect {
return self.offsetBy(dx: 0, dy: CGFloat(offsetValue))
}
}
@objc protocol AuthenticationViewControllerDelegate {
@objc func authenticationViewControllerDidTapHome(viewController: AuthenticationViewController)
}
class AuthenticationViewController: UIViewController {
enum Section: Int {
case users
case addUser
}
// MARK: - Public Variables
weak var delegate: AuthenticationViewControllerDelegate?
// MARK: - Private Variables
fileprivate lazy var collectionView: UICollectionView = { [unowned self] in
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.sectionInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 10.0, right: 0.0)
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = .groupTableViewBackground
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.bounces = true
collectionView.alwaysBounceVertical = true
collectionView.contentInset = UIEdgeInsets(top: 10.0, left: 0.0, bottom: 10.0, right: 0.0)
collectionView.register(TwitterSessionCollectionViewCell.self, forCellWithReuseIdentifier: AuthenticationViewController.cellIdentifier)
collectionView.register(TwitterLoginCollectionViewCell.self, forCellWithReuseIdentifier: AuthenticationViewController.loginCellIdentifier)
return collectionView
}()
fileprivate static let cellIdentifier = "authCell"
fileprivate static let loginCellIdentifier = "loginCell"
fileprivate var sessionStore: TWTRSessionStore
// MARK: - Init
required init() {
self.sessionStore = TWTRTwitter.sharedInstance().sessionStore
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
title = "Authentication"
setupCollectionView()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Home", style: .plain, target: self, action: #selector(home))
}
// MARK: - Actions
func home() {
delegate?.authenticationViewControllerDidTapHome(viewController: self)
}
// MARK: - Private Methods
private func setupCollectionView() {
view.addSubview(collectionView)
collectionView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
collectionView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
collectionView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
collectionView.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
}
}
// MARK: - UICollectionViewDataSource
extension AuthenticationViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let section = Section(rawValue: indexPath.section) {
switch section {
case .users:
return collectionView.dequeueReusableCell(withReuseIdentifier: AuthenticationViewController.cellIdentifier, for: indexPath)
case .addUser:
return collectionView.dequeueReusableCell(withReuseIdentifier: AuthenticationViewController.loginCellIdentifier, for: indexPath)
}
} else {
return collectionView.dequeueReusableCell(withReuseIdentifier: AuthenticationViewController.cellIdentifier, for: indexPath)
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let section = Section(rawValue: section) else { return 0 }
switch section {
case .users: return sessionStore.existingUserSessions().count
case .addUser: return 1
}
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
}
// MARK: - UICollectionViewDelegate
extension AuthenticationViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let section = Section(rawValue: indexPath.section) else { return }
switch section {
case .users:
if let cell = cell as? TwitterSessionCollectionViewCell, let session = sessionStore.existingUserSessions()[indexPath.row] as? TWTRSession {
cell.delegate = self
cell.configure(with: session)
}
case .addUser:
if let cell = cell as? TwitterLoginCollectionViewCell {
cell.delegate = self
cell.configure()
}
}
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension AuthenticationViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
guard let section = Section(rawValue: indexPath.section) else { return .zero }
switch section {
case .users: return CGSize(width: collectionView.frame.width - 20.0, height: 60.0)
case .addUser: return CGSize(width: collectionView.frame.width - 20.0, height: 48.0)
}
}
}
// MARK: - TwitterLoginCollectionViewCellDelegate
extension AuthenticationViewController: TwitterLoginCollectionViewCellDelegate {
func loginCollectionViewCellDidTapAddAccountButton(cell: TwitterLoginCollectionViewCell) {
let viewController = LoginViewController()
viewController.delegate = self
viewController.modalPresentationStyle = .overCurrentContext
present(viewController, animated: true, completion: nil)
}
}
// MARK: - TwitterSessionCollectionViewCellDelegate
extension AuthenticationViewController: TwitterSessionCollectionViewCellDelegate {
func sessionCollectionViewCell(collectionViewCell: TwitterSessionCollectionViewCell, didTapLogoutFor session: TWTRSession) {
TWTRTwitter.sharedInstance().sessionStore.logOutUserID(session.userID)
collectionView.reloadData()
}
}
// MARK: - LoginViewControllerDelegate
extension AuthenticationViewController: LoginViewControllerDelegate {
func loginViewControllerDidClearAccounts(viewController: LoginViewController) {
collectionView.reloadData()
}
func loginViewController(viewController: LoginViewController, didAuthWith session: TWTRSession) {
collectionView.reloadData()
}
}
| c78ed7741978e681d41e2fa73665ff33 | 37.362162 | 160 | 0.720445 | false | false | false | false |
dhanvi/firefox-ios | refs/heads/master | Client/Frontend/Browser/BrowserLocationView.swift | mpl-2.0 | 2 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import Shared
import SnapKit
protocol BrowserLocationViewDelegate {
func browserLocationViewDidTapLocation(browserLocationView: BrowserLocationView)
func browserLocationViewDidLongPressLocation(browserLocationView: BrowserLocationView)
func browserLocationViewDidTapReaderMode(browserLocationView: BrowserLocationView)
/// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied
func browserLocationViewDidLongPressReaderMode(browserLocationView: BrowserLocationView) -> Bool
func browserLocationViewLocationAccessibilityActions(browserLocationView: BrowserLocationView) -> [UIAccessibilityCustomAction]?
}
struct BrowserLocationViewUX {
static let HostFontColor = UIColor.blackColor()
static let BaseURLFontColor = UIColor.grayColor()
static let BaseURLPitch = 0.75
static let HostPitch = 1.0
static let LocationContentInset = 8
}
class BrowserLocationView: UIView {
var delegate: BrowserLocationViewDelegate?
var longPressRecognizer: UILongPressGestureRecognizer!
var tapRecognizer: UITapGestureRecognizer!
dynamic var baseURLFontColor: UIColor = BrowserLocationViewUX.BaseURLFontColor {
didSet { updateTextWithURL() }
}
dynamic var hostFontColor: UIColor = BrowserLocationViewUX.HostFontColor {
didSet { updateTextWithURL() }
}
var url: NSURL? {
didSet {
let wasHidden = lockImageView.hidden
lockImageView.hidden = url?.scheme != "https"
if wasHidden != lockImageView.hidden {
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil)
}
updateTextWithURL()
setNeedsUpdateConstraints()
}
}
var readerModeState: ReaderModeState {
get {
return readerModeButton.readerModeState
}
set (newReaderModeState) {
if newReaderModeState != self.readerModeButton.readerModeState {
let wasHidden = readerModeButton.hidden
self.readerModeButton.readerModeState = newReaderModeState
readerModeButton.hidden = (newReaderModeState == ReaderModeState.Unavailable)
if wasHidden != readerModeButton.hidden {
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil)
}
UIView.animateWithDuration(0.1, animations: { () -> Void in
if newReaderModeState == ReaderModeState.Unavailable {
self.readerModeButton.alpha = 0.0
} else {
self.readerModeButton.alpha = 1.0
}
self.setNeedsUpdateConstraints()
self.layoutIfNeeded()
})
}
}
}
lazy var placeholder: NSAttributedString = {
let placeholderText = NSLocalizedString("Search or enter address", comment: "The text shown in the URL bar on about:home")
return NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor.grayColor()])
}()
lazy var urlTextField: UITextField = {
let urlTextField = DisplayTextField()
self.longPressRecognizer.delegate = self
urlTextField.addGestureRecognizer(self.longPressRecognizer)
self.tapRecognizer.delegate = self
urlTextField.addGestureRecognizer(self.tapRecognizer)
// Prevent the field from compressing the toolbar buttons on the 4S in landscape.
urlTextField.setContentCompressionResistancePriority(250, forAxis: UILayoutConstraintAxis.Horizontal)
urlTextField.attributedPlaceholder = self.placeholder
urlTextField.accessibilityIdentifier = "url"
urlTextField.accessibilityActionsSource = self
urlTextField.font = UIConstants.DefaultMediumFont
return urlTextField
}()
private lazy var lockImageView: UIImageView = {
let lockImageView = UIImageView(image: UIImage(named: "lock_verified.png"))
lockImageView.hidden = true
lockImageView.isAccessibilityElement = true
lockImageView.contentMode = UIViewContentMode.Center
lockImageView.accessibilityLabel = NSLocalizedString("Secure connection", comment: "Accessibility label for the lock icon, which is only present if the connection is secure")
return lockImageView
}()
private lazy var readerModeButton: ReaderModeButton = {
let readerModeButton = ReaderModeButton(frame: CGRectZero)
readerModeButton.hidden = true
readerModeButton.addTarget(self, action: "SELtapReaderModeButton", forControlEvents: .TouchUpInside)
readerModeButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: "SELlongPressReaderModeButton:"))
readerModeButton.isAccessibilityElement = true
readerModeButton.accessibilityLabel = NSLocalizedString("Reader View", comment: "Accessibility label for the Reader View button")
readerModeButton.accessibilityCustomActions = [UIAccessibilityCustomAction(name: NSLocalizedString("Add to Reading List", comment: "Accessibility label for action adding current page to reading list."), target: self, selector: "SELreaderModeCustomAction")]
return readerModeButton
}()
override init(frame: CGRect) {
super.init(frame: frame)
longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "SELlongPressLocation:")
tapRecognizer = UITapGestureRecognizer(target: self, action: "SELtapLocation:")
self.backgroundColor = UIColor.whiteColor()
addSubview(urlTextField)
addSubview(lockImageView)
addSubview(readerModeButton)
lockImageView.snp_makeConstraints { make in
make.leading.centerY.equalTo(self)
make.width.equalTo(self.lockImageView.intrinsicContentSize().width + CGFloat(BrowserLocationViewUX.LocationContentInset * 2))
}
readerModeButton.snp_makeConstraints { make in
make.trailing.centerY.equalTo(self)
make.width.equalTo(self.readerModeButton.intrinsicContentSize().width + CGFloat(BrowserLocationViewUX.LocationContentInset * 2))
}
}
override var accessibilityElements: [AnyObject]! {
get {
return [lockImageView, urlTextField, readerModeButton].filter { !$0.hidden }
}
set {
super.accessibilityElements = newValue
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateConstraints() {
urlTextField.snp_remakeConstraints { make in
make.top.bottom.equalTo(self)
if lockImageView.hidden {
make.leading.equalTo(self).offset(BrowserLocationViewUX.LocationContentInset)
} else {
make.leading.equalTo(self.lockImageView.snp_trailing)
}
if readerModeButton.hidden {
make.trailing.equalTo(self).offset(-BrowserLocationViewUX.LocationContentInset)
} else {
make.trailing.equalTo(self.readerModeButton.snp_leading)
}
}
super.updateConstraints()
}
func SELtapReaderModeButton() {
delegate?.browserLocationViewDidTapReaderMode(self)
}
func SELlongPressReaderModeButton(recognizer: UILongPressGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.Began {
delegate?.browserLocationViewDidLongPressReaderMode(self)
}
}
func SELlongPressLocation(recognizer: UITapGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.Began {
delegate?.browserLocationViewDidLongPressLocation(self)
}
}
func SELtapLocation(recognizer: UITapGestureRecognizer) {
delegate?.browserLocationViewDidTapLocation(self)
}
func SELreaderModeCustomAction() -> Bool {
return delegate?.browserLocationViewDidLongPressReaderMode(self) ?? false
}
private func updateTextWithURL() {
if let httplessURL = url?.absoluteStringWithoutHTTPScheme(), let baseDomain = url?.baseDomain() {
// Highlight the base domain of the current URL.
let attributedString = NSMutableAttributedString(string: httplessURL)
let nsRange = NSMakeRange(0, httplessURL.characters.count)
attributedString.addAttribute(NSForegroundColorAttributeName, value: baseURLFontColor, range: nsRange)
attributedString.colorSubstring(baseDomain, withColor: hostFontColor)
attributedString.addAttribute(UIAccessibilitySpeechAttributePitch, value: NSNumber(double: BrowserLocationViewUX.BaseURLPitch), range: nsRange)
attributedString.pitchSubstring(baseDomain, withPitch: BrowserLocationViewUX.HostPitch)
urlTextField.attributedText = attributedString
} else {
// If we're unable to highlight the domain, just use the URL as is.
urlTextField.text = url?.absoluteString
}
}
}
extension BrowserLocationView: UIGestureRecognizerDelegate {
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// If the longPressRecognizer is active, fail all other recognizers to avoid conflicts.
return gestureRecognizer == longPressRecognizer
}
}
extension BrowserLocationView: AccessibilityActionsSource {
func accessibilityCustomActionsForView(view: UIView) -> [UIAccessibilityCustomAction]? {
if view === urlTextField {
return delegate?.browserLocationViewLocationAccessibilityActions(self)
}
return nil
}
}
private class ReaderModeButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setImage(UIImage(named: "reader.png"), forState: UIControlState.Normal)
setImage(UIImage(named: "reader_active.png"), forState: UIControlState.Selected)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var _readerModeState: ReaderModeState = ReaderModeState.Unavailable
var readerModeState: ReaderModeState {
get {
return _readerModeState;
}
set (newReaderModeState) {
_readerModeState = newReaderModeState
switch _readerModeState {
case .Available:
self.enabled = true
self.selected = false
case .Unavailable:
self.enabled = false
self.selected = false
case .Active:
self.enabled = true
self.selected = true
}
}
}
}
private class DisplayTextField: UITextField {
weak var accessibilityActionsSource: AccessibilityActionsSource?
override var accessibilityCustomActions: [UIAccessibilityCustomAction]? {
get {
return accessibilityActionsSource?.accessibilityCustomActionsForView(self)
}
set {
super.accessibilityCustomActions = newValue
}
}
private override func canBecomeFirstResponder() -> Bool {
return false
}
}
| 44edd6c5ba28bb76dc55a405a6bb9487 | 40.646853 | 264 | 0.691126 | false | false | false | false |
superk589/CGSSGuide | refs/heads/master | DereGuide/Controller/BaseFilterSortController.swift | mit | 2 | //
// BaseFilterSortController.swift
// DereGuide
//
// Created by zzk on 2017/1/12.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
import SnapKit
class BaseFilterSortController: BaseViewController, UITableViewDelegate, UITableViewDataSource {
let toolbar = UIToolbar()
let tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(FilterTableViewCell.self, forCellReuseIdentifier: "FilterCell")
tableView.register(SortTableViewCell.self, forCellReuseIdentifier: "SortCell")
tableView.delegate = self
tableView.dataSource = self
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 44, right: 0)
tableView.tableFooterView = UIView(frame: .zero)
tableView.estimatedRowHeight = 50
tableView.cellLayoutMarginsFollowReadableWidth = false
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.left.right.bottom.equalToSuperview()
make.top.equalTo(topLayoutGuide.snp.bottom)
}
toolbar.tintColor = .parade
view.addSubview(toolbar)
toolbar.snp.makeConstraints { (make) in
if #available(iOS 11.0, *) {
make.left.right.equalToSuperview()
make.bottom.equalTo(view.safeAreaLayoutGuide)
} else {
make.bottom.left.right.equalToSuperview()
}
make.height.equalTo(44)
}
let leftSpaceItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
leftSpaceItem.width = 0
let doneItem = UIBarButtonItem(title: NSLocalizedString("完成", comment: "导航栏按钮"), style: .done, target: self, action: #selector(doneAction))
let middleSpaceItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let resetItem = UIBarButtonItem(title: NSLocalizedString("重置", comment: "导航栏按钮"), style: .plain, target: self, action: #selector(resetAction))
let rightSpaceItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
rightSpaceItem.width = 0
toolbar.setItems([leftSpaceItem, resetItem, middleSpaceItem, doneItem, rightSpaceItem], animated: false)
}
@objc func doneAction() {
}
@objc func resetAction() {
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { [weak self] (context) in
// since the size changes, update all table cells to fit the new size
self?.tableView.beginUpdates()
self?.tableView.endUpdates()
}, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return UITableViewCell()
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return NSLocalizedString("筛选", comment: "")
} else {
return NSLocalizedString("排序", comment: "")
}
}
}
| 3b2664b956f214cdacdd0d3ad588090d | 34.634615 | 150 | 0.644091 | false | false | false | false |
manavgabhawala/swift | refs/heads/master | test/SILGen/implicitly_unwrapped_optional.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s
func foo(f f: (() -> ())!) {
var f: (() -> ())! = f
f?()
}
// CHECK: sil hidden @{{.*}}foo{{.*}} : $@convention(thin) (@owned Optional<@callee_owned () -> ()>) -> () {
// CHECK: bb0([[T0:%.*]] : $Optional<@callee_owned () -> ()>):
// CHECK: [[F:%.*]] = alloc_box ${ var Optional<@callee_owned () -> ()> }
// CHECK: [[PF:%.*]] = project_box [[F]]
// CHECK: [[BORROWED_T0:%.*]] = begin_borrow [[T0]]
// CHECK: [[T0_COPY:%.*]] = copy_value [[BORROWED_T0]]
// CHECK: store [[T0_COPY]] to [init] [[PF]]
// CHECK: end_borrow [[BORROWED_T0]] from [[T0]]
// CHECK: [[T1:%.*]] = select_enum_addr [[PF]]
// CHECK: cond_br [[T1]], bb1, bb3
// If it does, project and load the value out of the implicitly unwrapped
// optional...
// CHECK: bb1:
// CHECK-NEXT: [[FN0_ADDR:%.*]] = unchecked_take_enum_data_addr [[PF]]
// CHECK-NEXT: [[FN0:%.*]] = load [copy] [[FN0_ADDR]]
// .... then call it
// CHECK: apply [[FN0]]() : $@callee_owned () -> ()
// CHECK: br bb2
// CHECK: bb2(
// CHECK: destroy_value [[F]]
// CHECK: destroy_value [[T0]]
// CHECK: return
// CHECK: bb3:
// CHECK: enum $Optional<()>, #Optional.none!enumelt
// CHECK: br bb2
// The rest of this is tested in optional.swift
// } // end sil function '{{.*}}foo{{.*}}'
func wrap<T>(x x: T) -> T! { return x }
// CHECK-LABEL: sil hidden @_T029implicitly_unwrapped_optional16wrap_then_unwrap{{[_0-9a-zA-Z]*}}F
func wrap_then_unwrap<T>(x x: T) -> T {
// CHECK: switch_enum_addr {{%.*}}, case #Optional.some!enumelt.1: [[OK:bb[0-9]+]], case #Optional.none!enumelt: [[FAIL:bb[0-9]+]]
// CHECK: [[FAIL]]:
// CHECK: unreachable
// CHECK: [[OK]]:
return wrap(x: x)!
}
// CHECK-LABEL: sil hidden @_T029implicitly_unwrapped_optional10tuple_bindSSSgSQySi_SStG1x_tF : $@convention(thin) (@owned Optional<(Int, String)>) -> @owned Optional<String> {
func tuple_bind(x x: (Int, String)!) -> String? {
return x?.1
// CHECK: cond_br {{%.*}}, [[NONNULL:bb[0-9]+]], [[NULL:bb[0-9]+]]
// CHECK: [[NONNULL]]:
// CHECK: [[STRING:%.*]] = tuple_extract {{%.*}} : $(Int, String), 1
// CHECK-NOT: destroy_value [[STRING]]
}
// CHECK-LABEL: sil hidden @_T029implicitly_unwrapped_optional011tuple_bind_a1_B0SSSQySi_SStG1x_tF
func tuple_bind_implicitly_unwrapped(x x: (Int, String)!) -> String {
return x.1
}
func return_any() -> AnyObject! { return nil }
func bind_any() {
let object : AnyObject? = return_any()
}
// CHECK-LABEL: sil hidden @_T029implicitly_unwrapped_optional6sr3758yyF
func sr3758() {
// Verify that there are no additional reabstractions introduced.
// CHECK: [[CLOSURE:%.+]] = function_ref @_T029implicitly_unwrapped_optional6sr3758yyFySQyypGcfU_ : $@convention(thin) (@in Optional<Any>) -> ()
// CHECK: [[F:%.+]] = thin_to_thick_function [[CLOSURE]] : $@convention(thin) (@in Optional<Any>) -> () to $@callee_owned (@in Optional<Any>) -> ()
// CHECK: [[BORROWED_F:%.*]] = begin_borrow [[F]]
// CHECK: [[CALLEE:%.+]] = copy_value [[BORROWED_F]] : $@callee_owned (@in Optional<Any>) -> ()
// CHECK: = apply [[CALLEE]]({{%.+}}) : $@callee_owned (@in Optional<Any>) -> ()
// CHECK: end_borrow [[BORROWED_F]] from [[F]]
// CHECK: destroy_value [[F]]
let f: ((Any?) -> Void) = { (arg: Any!) in }
f(nil)
} // CHECK: end sil function '_T029implicitly_unwrapped_optional6sr3758yyF'
| 651a3469be3578a437080d68a23ecd19 | 43.324675 | 176 | 0.586288 | false | false | false | false |
kperryua/swift | refs/heads/master | test/IDE/complete_at_top_level.swift | apache-2.0 | 3 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_1 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_2 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_3 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_4 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_5 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_5
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_6 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_KW_1 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_KW_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1 | %FileCheck %s -check-prefix=TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_INIT_1 > %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_INIT_1 < %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_INIT_1_NEGATIVE < %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_INIT_2 | %FileCheck %s -check-prefix=TOP_LEVEL_VAR_INIT_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PLAIN_TOP_LEVEL_1 > %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL < %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL_NO_DUPLICATES < %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PLAIN_TOP_LEVEL_2 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PLAIN_TOP_LEVEL_2 | %FileCheck %s -check-prefix=NEGATIVE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_CLOSURE_1 | %FileCheck %s -check-prefix=TOP_LEVEL_CLOSURE_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_1 > %t.toplevel.1.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.1.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.1.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.1.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_2 > %t.toplevel.2.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.2.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.2.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.2.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_3 > %t.toplevel.3.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.3.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.3.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.3.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_4 > %t.toplevel.4.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.4.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.4.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.4.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_5 > %t.toplevel.5.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.5.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.5.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.5.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_5 > %t.toplevel.5.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.5.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.5.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.5.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_VAR_TYPE_6 > %t.toplevel.6.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel.6.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel.6.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel.6.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_EXPR_TYPE_1 > %t.toplevel-expr.1.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel-expr.1.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel-expr.1.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel-expr.1.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_EXPR_TYPE_2 > %t.toplevel-expr.2.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel-expr.2.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel-expr.2.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel-expr.2.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_EXPR_TYPE_3 > %t.toplevel-expr.3.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel-expr.3.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel-expr.3.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel-expr.3.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_EXPR_TYPE_4 > %t.toplevel-expr.4.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel-expr.4.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel-expr.4.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel-expr.4.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_EXPR_TYPE_2 > %t.toplevel-expr.2.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_1 < %t.toplevel-expr.2.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_VAR_TYPE_NEGATIVE_1 < %t.toplevel-expr.2.txt
// RUN: %FileCheck %s -check-prefix=NEGATIVE < %t.toplevel-expr.2.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_1 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_2 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_3 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_4 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_5 > %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL < %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_STMT_5 < %t.toplevel.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_6 > %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL < %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_STMT_6 < %t.toplevel.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_7 > %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL < %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_STMT_7 < %t.toplevel.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_8 > %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL < %t.toplevel.txt
// RUN: %FileCheck %s -check-prefix=TOP_LEVEL_STMT_8 < %t.toplevel.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_9 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_STMT_10 | %FileCheck %s -check-prefix=PLAIN_TOP_LEVEL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_AUTOCLOSURE_1 | %FileCheck %s -check-prefix=AUTOCLOSURE_STRING
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_SWITCH_CASE_1 | %FileCheck %s -check-prefix=TOP_LEVEL_SWITCH_CASE_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_BEFORE_GUARD_NAME_1 | %FileCheck %s -check-prefix=TOP_LEVEL_BEFORE_GUARD_NAME
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_BEFORE_GUARD_NAME_2 | %FileCheck %s -check-prefix=TOP_LEVEL_BEFORE_GUARD_NAME
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_GUARD_1 | %FileCheck %s -check-prefix=TOP_LEVEL_GUARD
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_GUARD_2 | %FileCheck %s -check-prefix=TOP_LEVEL_GUARD
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRING_INTERP_1 | %FileCheck %s -check-prefix=STRING_INTERP
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRING_INTERP_2 | %FileCheck %s -check-prefix=STRING_INTERP
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRING_INTERP_3 | %FileCheck %s -check-prefix=STRING_INTERP
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=STRING_INTERP_4 | %FileCheck %s -check-prefix=STRING_INTERP
// Test code completion in top-level code.
//
// This test is not meant to test that we can correctly form all kinds of
// completion results in general; that should be tested elsewhere.
struct FooStruct {
var instanceVar = 0
func instanceFunc(_ a: Int) {}
// Add more stuff as needed.
}
var fooObject : FooStruct
func fooFunc1() {}
func fooFunc2(_ a: Int, _ b: Double) {}
func erroneous1(_ x: Undeclared) {}
//===--- Test code completions of expressions that can be typechecked.
// Although the parser can recover in most of these test cases, we resync it
// anyway to ensure that there parser recovery does not interfere with code
// completion.
func resyncParser1() {}
fooObject#^TYPE_CHECKED_EXPR_1^#
// TYPE_CHECKED_EXPR_1: Begin completions
// TYPE_CHECKED_EXPR_1-NEXT: Decl[InstanceVar]/CurrNominal: .instanceVar[#Int#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_1-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_1-NEXT: BuiltinOperator/None: = {#FooStruct#}[#Void#];
// TYPE_CHECKED_EXPR_1-NEXT: End completions
func resyncParser2() {}
// Test that we can code complete after a top-level var decl.
var _tmpVar1 : FooStruct
fooObject#^TYPE_CHECKED_EXPR_2^#
// TYPE_CHECKED_EXPR_2: Begin completions
// TYPE_CHECKED_EXPR_2-NEXT: Decl[InstanceVar]/CurrNominal: .instanceVar[#Int#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_2-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_2-NEXT: BuiltinOperator/None: = {#FooStruct#}[#Void#];
// TYPE_CHECKED_EXPR_2-NEXT: End completions
func resyncParser3() {}
fooObject#^TYPE_CHECKED_EXPR_3^#.bar
// TYPE_CHECKED_EXPR_3: Begin completions
// TYPE_CHECKED_EXPR_3-NEXT: Decl[InstanceVar]/CurrNominal: .instanceVar[#Int#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_3-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_3-NEXT: BuiltinOperator/None: = {#FooStruct#}[#Void#];
// TYPE_CHECKED_EXPR_3-NEXT: End completions
func resyncParser4() {}
fooObject.#^TYPE_CHECKED_EXPR_4^#
// TYPE_CHECKED_EXPR_4: Begin completions
// TYPE_CHECKED_EXPR_4-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_4-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_4-NEXT: End completions
func resyncParser5() {}
fooObject.#^TYPE_CHECKED_EXPR_5^#.bar
// TYPE_CHECKED_EXPR_5: Begin completions
// TYPE_CHECKED_EXPR_5-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_5-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_5-NEXT: End completions
func resyncParser6() {}
fooObject.instanceFunc(#^TYPE_CHECKED_EXPR_6^#
func resyncParser6() {}
fooObject.is#^TYPE_CHECKED_EXPR_KW_1^#
// TYPE_CHECKED_EXPR_KW_1: found code completion token
// TYPE_CHECKED_EXPR_KW_1-NOT: Begin completions
func resyncParser7() {}
// We have an error in the initializer here, but the type is explicitly written
// in the source.
var fooObjectWithErrorInInit : FooStruct = unknown_var
fooObjectWithErrorInInit.#^TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1^#
// TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1: Begin completions
// TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc({#(a): Int#})[#Void#]{{; name=.+$}}
// TYPE_CHECKED_EXPR_WITH_ERROR_IN_INIT_1-NEXT: End completions
func resyncParser6a() {}
var topLevelVar1 = #^TOP_LEVEL_VAR_INIT_1^#
// TOP_LEVEL_VAR_INIT_1: Begin completions
// TOP_LEVEL_VAR_INIT_1-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_1-DAG: Decl[FreeFunction]/CurrModule: fooFunc1()[#Void#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_1-DAG: Decl[GlobalVar]/Local: fooObject[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_1: End completions
// Check that the variable itself does not show up.
// TOP_LEVEL_VAR_INIT_1_NEGATIVE-NOT: topLevelVar1
func resyncParser7() {}
var topLevelVar2 = FooStruct#^TOP_LEVEL_VAR_INIT_2^#
// TOP_LEVEL_VAR_INIT_2: Begin completions
// TOP_LEVEL_VAR_INIT_2-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#self: FooStruct#})[#(Int) -> Void#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_2-NEXT: Decl[Constructor]/CurrNominal: ({#instanceVar: Int#})[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_2-NEXT: Decl[Constructor]/CurrNominal: ()[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_VAR_INIT_2-NEXT: End completions
func resyncParser8() {}
#^PLAIN_TOP_LEVEL_1^#
// PLAIN_TOP_LEVEL: Begin completions
// PLAIN_TOP_LEVEL-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// PLAIN_TOP_LEVEL-DAG: Decl[GlobalVar]/Local: fooObject[#FooStruct#]{{; name=.+$}}
// PLAIN_TOP_LEVEL: End completions
// PLAIN_TOP_LEVEL_NO_DUPLICATES: Begin completions
// PLAIN_TOP_LEVEL_NO_DUPLICATES-DAG: Decl[FreeFunction]/CurrModule: fooFunc1()[#Void#]{{; name=.+$}}
// PLAIN_TOP_LEVEL_NO_DUPLICATES-DAG: Decl[FreeFunction]/CurrModule: fooFunc2({#(a): Int#}, {#(b): Double#})[#Void#]{{; name=.+$}}
// PLAIN_TOP_LEVEL_NO_DUPLICATES-NOT: fooFunc1
// PLAIN_TOP_LEVEL_NO_DUPLICATES-NOT: fooFunc2
// PLAIN_TOP_LEVEL_NO_DUPLICATES: End completions
func resyncParser9() {}
// Test that we can code complete immediately after a decl with a syntax error.
func _tmpFuncWithSyntaxError() { if return }
#^PLAIN_TOP_LEVEL_2^#
func resyncParser10() {}
_ = {
#^TOP_LEVEL_CLOSURE_1^#
}()
// TOP_LEVEL_CLOSURE_1: Begin completions
// TOP_LEVEL_CLOSURE_1-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_CLOSURE_1-DAG: Decl[FreeFunction]/CurrModule: fooFunc1()[#Void#]{{; name=.+$}}
// TOP_LEVEL_CLOSURE_1-DAG: Decl[GlobalVar]/Local: fooObject[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_CLOSURE_1: End completions
func resyncParser11() {}
//===--- Test code completions of types.
func resyncParserA1() {}
var topLevelVarType1 : #^TOP_LEVEL_VAR_TYPE_1^#
// TOP_LEVEL_VAR_TYPE_1: Begin completions
// TOP_LEVEL_VAR_TYPE_1-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// TOP_LEVEL_VAR_TYPE_1: End completions
// TOP_LEVEL_VAR_TYPE_NEGATIVE_1-NOT: Decl[GlobalVar
// TOP_LEVEL_VAR_TYPE_NEGATIVE_1-NOT: Decl[FreeFunc
func resyncParserA1_1() {}
var topLevelVarType2 : [#^TOP_LEVEL_VAR_TYPE_2^#]
func resyncParserA1_2() {}
var topLevelVarType3 : [#^TOP_LEVEL_VAR_TYPE_3^#: Int]
func resyncParserA1_3() {}
var topLevelVarType4 : [Int: #^TOP_LEVEL_VAR_TYPE_4^#]
func resyncParserA1_4() {}
if let topLevelVarType5 : [#^TOP_LEVEL_VAR_TYPE_5^#] {}
func resyncParserA1_5() {}
guard let topLevelVarType6 : [#^TOP_LEVEL_VAR_TYPE_6^#] else {}
func resyncParserA1_6() {}
_ = ("a" as #^TOP_LEVEL_EXPR_TYPE_1^#)
func resyncParserA1_7() {}
_ = ("a" as! #^TOP_LEVEL_EXPR_TYPE_2^#)
func resyncParserA1_8() {}
_ = ("a" as? #^TOP_LEVEL_EXPR_TYPE_3^#)
func resyncParserA1_9() {}
_ = ("a" is #^TOP_LEVEL_EXPR_TYPE_4^#)
func resyncParserA2() {}
//===--- Test code completion in statements.
func resyncParserB1() {}
if (true) {
#^TOP_LEVEL_STMT_1^#
}
func resyncParserB2() {}
while (true) {
#^TOP_LEVEL_STMT_2^#
}
func resyncParserB3() {}
repeat {
#^TOP_LEVEL_STMT_3^#
} while true
func resyncParserB4() {}
for ; ; {
#^TOP_LEVEL_STMT_4^#
}
func resyncParserB5() {}
for var i = 0; ; {
#^TOP_LEVEL_STMT_5^#
// TOP_LEVEL_STMT_5: Begin completions
// TOP_LEVEL_STMT_5: Decl[LocalVar]/Local: i[#Int#]{{; name=.+$}}
// TOP_LEVEL_STMT_5: End completions
}
func resyncParserB6() {}
for i in [] {
#^TOP_LEVEL_STMT_6^#
// TOP_LEVEL_STMT_6: Begin completions
// TOP_LEVEL_STMT_6: Decl[LocalVar]/Local: i[#Any#]{{; name=.+$}}
// TOP_LEVEL_STMT_6: End completions
}
func resyncParserB7() {}
for i in [1, 2, 3] {
#^TOP_LEVEL_STMT_7^#
// TOP_LEVEL_STMT_7: Begin completions
// TOP_LEVEL_STMT_7: Decl[LocalVar]/Local: i[#Int#]{{; name=.+$}}
// TOP_LEVEL_STMT_7: End completions
}
func resyncParserB8() {}
for i in unknown_var {
#^TOP_LEVEL_STMT_8^#
// TOP_LEVEL_STMT_8: Begin completions
// TOP_LEVEL_STMT_8: Decl[LocalVar]/Local: i[#<<error type>>#]{{; name=.+$}}
// TOP_LEVEL_STMT_8: End completions
}
func resyncParserB9() {}
switch (0, 42) {
case (0, 0):
#^TOP_LEVEL_STMT_9^#
}
func resyncParserB10() {}
// rdar://20738314
if true {
var z = #^TOP_LEVEL_STMT_10^#
} else {
assertionFailure("Shouldn't be here")
}
func resyncParserB11() {}
// rdar://21346928
func optStr() -> String? { return nil }
let x = (optStr() ?? "autoclosure").#^TOP_LEVEL_AUTOCLOSURE_1^#
// AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal: utf16[#String.UTF16View#]
// AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal: characters[#String.CharacterView#]
// AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal: utf8[#String.UTF8View#]
func resyncParserB12() {}
// rdar://21661308
switch 1 {
case #^TOP_LEVEL_SWITCH_CASE_1^#
}
// TOP_LEVEL_SWITCH_CASE_1: Begin completions
func resyncParserB13() {}
#^TOP_LEVEL_BEFORE_GUARD_NAME_1^#
// TOP_LEVEL_BEFORE_GUARD_NAME-NOT: name=guardedName
guard let guardedName = 1 as Int? {
#^TOP_LEVEL_BEFORE_GUARD_NAME_2^#
}
#^TOP_LEVEL_GUARD_1^#
func interstitial() {}
#^TOP_LEVEL_GUARD_2^#
// TOP_LEVEL_GUARD: Decl[LocalVar]/Local: guardedName[#Int#]; name=guardedName
func resyncParserB14() {}
"\(#^STRING_INTERP_1^#)"
"\(1) \(#^STRING_INTERP_2^#) \(2)"
var stringInterp = "\(#^STRING_INTERP_3^#)"
_ = "" + "\(#^STRING_INTERP_4^#)" + ""
// STRING_INTERP: Begin completions
// STRING_INTERP-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#];
// STRING_INTERP-DAG: Decl[FreeFunction]/CurrModule: fooFunc1()[#Void#];
// STRING_INTERP-DAG: Decl[GlobalVar]/Local: fooObject[#FooStruct#];
// STRING_INTERP: End completions
func resyncParserC1() {}
//
//===--- DON'T ADD ANY TESTS AFTER THIS LINE.
//
// These declarations should not show up in top-level code completion results
// because forward references are not allowed at the top level.
struct StructAtEOF {}
// NEGATIVE-NOT: StructAtEOF
extension FooStruct {
func instanceFuncAtEOF() {}
// NEGATIVE-NOT: instanceFuncAtEOF
}
var varAtEOF : Int
// NEGATIVE-NOT: varAtEOF
| 051e1d035e1d0640b0490c341c33a509 | 44.982495 | 198 | 0.707386 | false | true | false | false |
Killectro/GiphySearch | refs/heads/master | GiphySearch/GiphySearch/View Controllers/Trending/TrendingViewController.swift | mit | 1 | //
// TrendingViewController.swift
// GiphySearch
//
// Created by DJ Mitchell on 8/17/16.
// Copyright © 2016 Killectro. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
import NSObject_Rx
import Moya
import Moya_ObjectMapper
final class TrendingViewController: UIViewController {
// MARK: - Public Properties
var viewModel: TrendingDisplayable!
// MARK: - Private Properties
fileprivate let startLoadingOffset: CGFloat = 20.0
@IBOutlet fileprivate var noResultsView: UIView!
@IBOutlet var sadFaceImage: UIImageView! {
didSet {
sadFaceImage.tintColor = UIColor(red: 146/255, green: 146/255, blue: 146/255, alpha: 1.0)
}
}
@IBOutlet fileprivate var tableView: UITableView!
@IBOutlet fileprivate var searchBar: UISearchBar!
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupBindings()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// SDWebImage automatically wipes mem cache when it receives a mem warning so do nothing here
}
}
// MARK: - Setup
private extension TrendingViewController {
func setupBindings() {
setupViewModel()
setupKeyboard()
}
func setupViewModel() {
let searchText = searchBar.rx.text.orEmpty
.throttle(0.3, scheduler: MainScheduler.instance)
.distinctUntilChanged()
.shareReplay(1)
let paginate = tableView.rx
.contentOffset
.filter { [weak self] offset in
guard let `self` = self else { return false }
return self.tableView.isNearBottom(threshold: self.startLoadingOffset)
}
.flatMap { _ in return Observable.just() }
viewModel.setupObservables(paginate: paginate, searchText: searchText)
// Bind our table view to our result GIFs once we set up our view model
setupTableView()
}
func setupTableView() {
// Bind gifs to table view cells
viewModel.gifs
.bindTo(
tableView.rx.items(cellIdentifier: "gifCell", cellType: GifTableViewCell.self),
curriedArgument: configureTableCell
)
.addDisposableTo(rx_disposeBag)
viewModel.gifs
.map { gifs in gifs.count != 0 }
.bindTo(noResultsView.rx.isHidden)
.addDisposableTo(rx_disposeBag)
}
func setupKeyboard() {
// Hide the keyboard when we're scrolling
tableView.rx.contentOffset.subscribe(onNext: { [weak self] _ in
guard let `self` = self else { return }
if self.searchBar.isFirstResponder {
self.searchBar.resignFirstResponder()
}
})
.addDisposableTo(rx_disposeBag)
}
func configureTableCell(_ row: Int, viewModel: GifDisplayable, cell: GifTableViewCell) {
cell.viewModel = viewModel
}
}
| 37572b966c5d27a284b56aa049ef0856 | 27.875 | 101 | 0.630703 | false | false | false | false |
pixyzehn/MediumScrollFullScreen | refs/heads/master | MediumScrollFullScreen-Sample/MediumScrollFullScreen-Sample/WebViewController.swift | mit | 1 | //
// ViewController.swift
// MediumScrollFullScreen-Sample
//
// Created by pixyzehn on 2/24/15.
// Copyright (c) 2015 pixyzehn. All rights reserved.
//
import UIKit
class WebViewController: UIViewController {
enum State {
case Showing
case Hiding
}
@IBOutlet weak var webView: UIWebView!
var statement: State = .Hiding
var scrollProxy: MediumScrollFullScreen?
var scrollView: UIScrollView?
var enableTap = false
override func viewDidLoad() {
super.viewDidLoad()
scrollProxy = MediumScrollFullScreen(forwardTarget: webView)
webView.scrollView.delegate = scrollProxy
scrollProxy?.delegate = self as MediumScrollFullScreenDelegate
webView.loadRequest(NSURLRequest(URL: NSURL(string: "http://nshipster.com/swift-collection-protocols/")!))
let screenTap = UITapGestureRecognizer(target: self, action: "tapGesture:")
screenTap.delegate = self
webView.addGestureRecognizer(screenTap)
// NOTE: Add temporary item
navigationItem.hidesBackButton = true
let menuColor = UIColor(red:0.2, green:0.2, blue:0.2, alpha:1)
let backButton = UIBarButtonItem(image: UIImage(named: "back_arrow"), style: .Plain, target: self, action: "popView")
backButton.tintColor = menuColor
navigationItem.leftBarButtonItem = backButton
let rightButton = UIButton(type: .Custom)
rightButton.frame = CGRectMake(0, 0, 60, 60)
rightButton.addTarget(self, action: "changeIcon:", forControlEvents: .TouchUpInside)
rightButton.setImage(UIImage(named: "star_n"), forState: .Normal)
rightButton.setImage(UIImage(named: "star_s"), forState: .Selected)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
let favButton = UIButton(type: .Custom)
favButton.frame = CGRectMake(0, 0, 60, 60)
favButton.addTarget(self, action: "changeIcon:", forControlEvents: .TouchUpInside)
favButton.setImage(UIImage(named: "fav_n"), forState: .Normal)
favButton.setImage(UIImage(named: "fav_s"), forState: .Selected)
let toolItem: UIBarButtonItem = UIBarButtonItem(customView: favButton)
let timeLabel = UILabel(frame: CGRectMake(0, 0, 100, 20))
timeLabel.text = "?? min left"
timeLabel.textAlignment = .Center
timeLabel.tintColor = menuColor
let timeButton = UIBarButtonItem(customView: timeLabel as UIView)
let actionButton = UIBarButtonItem(barButtonSystemItem: .Action, target: nil, action: nil)
actionButton.tintColor = menuColor
let gap = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
let fixedSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
fixedSpace.width = 20
toolbarItems = [toolItem, gap, timeButton, gap, actionButton, fixedSpace]
}
func changeIcon(sender: UIButton) {
sender.selected = !sender.selected
}
func popView() {
navigationController?.popViewControllerAnimated(true)
}
func tapGesture(sender: UITapGestureRecognizer) {
if !enableTap {
return
}
if statement == .Hiding {
statement = .Showing
showNavigationBar()
showToolbar()
} else {
statement = .Hiding
hideNavigationBar()
hideToolbar()
}
}
}
extension WebViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
extension WebViewController: MediumScrollFullScreenDelegate {
func scrollFullScreen(fullScreenProxy: MediumScrollFullScreen, scrollViewDidScrollUp deltaY: CGFloat, userInteractionEnabled enabled: Bool) {
enableTap = enabled ? false : true
moveNavigationBar(deltaY: deltaY)
moveToolbar(deltaY: -deltaY)
}
func scrollFullScreen(fullScreenProxy: MediumScrollFullScreen, scrollViewDidScrollDown deltaY: CGFloat, userInteractionEnabled enabled: Bool) {
enableTap = enabled ? false : true
if enabled {
moveNavigationBar(deltaY: deltaY)
hideToolbar()
} else {
moveNavigationBar(deltaY: -deltaY)
moveToolbar(deltaY: deltaY)
}
}
func scrollFullScreenScrollViewDidEndDraggingScrollUp(fullScreenProxy: MediumScrollFullScreen, userInteractionEnabled enabled: Bool) {
statement = .Hiding
hideNavigationBar()
hideToolbar()
}
func scrollFullScreenScrollViewDidEndDraggingScrollDown(fullScreenProxy: MediumScrollFullScreen, userInteractionEnabled enabled: Bool) {
if enabled {
statement = .Showing
showNavigationBar()
hideToolbar()
} else {
statement = .Hiding
hideNavigationBar()
hideToolbar()
}
}
}
| 8595786486985b9e317705fe3e079a8d | 35.517483 | 147 | 0.658368 | false | false | false | false |
LeeShiYoung/LSYWeibo | refs/heads/master | LSYWeiBo/Profile/ProfileTableViewController.swift | artistic-2.0 | 1 | //
// ProfileTableViewController.swift
// LSYWeiBo
//
// Created by 李世洋 on 16/5/1.
// Copyright © 2016年 李世洋. All rights reserved.
//
import UIKit
class ProfileTableViewController: BaseTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
if !login
{
visitorView?.setupVisitorInfo(false, iconStr: "visitordiscover_image_profile", text: "登录后,你的微博、相册、个人资料会显示在这里,展示给别人")
}
}
// 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.
}
*/
}
| 85c02c610d2fe359c5940e5cca73591b | 31.087912 | 157 | 0.677055 | false | false | false | false |
ProcedureKit/ProcedureKit | refs/heads/development | Sources/TestingProcedureKit/TestableNetworkReachability.swift | mit | 2 | //
// ProcedureKit
//
// Copyright © 2015-2018 ProcedureKit. All rights reserved.
//
import Foundation
import SystemConfiguration
import XCTest
import ProcedureKit
public class TestableNetworkReachability {
typealias Reachability = String
public var flags: SCNetworkReachabilityFlags {
get { return stateLock.withCriticalScope { _flags } }
set {
stateLock.withCriticalScope {
_flags = newValue
}
}
}
public var didStartNotifier: Bool {
get { return stateLock.withCriticalScope { _didStartNotifier } }
set {
stateLock.withCriticalScope {
_didStartNotifier = newValue
}
}
}
public var didStopNotifier: Bool {
get { return stateLock.withCriticalScope { _didStopNotifier } }
set {
stateLock.withCriticalScope {
_didStopNotifier = newValue
}
}
}
public var log: LogChannel {
get { return stateLock.withCriticalScope { _log } }
set {
stateLock.withCriticalScope {
_log = newValue
}
}
}
public weak var delegate: NetworkReachabilityDelegate? {
get { return stateLock.withCriticalScope { _delegate } }
set {
stateLock.withCriticalScope {
_delegate = newValue
}
}
}
private var stateLock = NSRecursiveLock()
private var _flags: SCNetworkReachabilityFlags = .reachable {
didSet {
delegate?.didChangeReachability(flags: flags)
}
}
private var _didStartNotifier = false
private var _didStopNotifier = false
private var _log: LogChannel = Log.Channel<Log>()
private weak var _delegate: NetworkReachabilityDelegate?
public init() { }
}
extension TestableNetworkReachability: NetworkReachability {
public func startNotifier(onQueue queue: DispatchQueue) throws {
log.message("Started Reachability Notifier")
didStartNotifier = true
delegate?.didChangeReachability(flags: flags)
}
public func stopNotifier() {
log.message("Stopped Reachability Notifier")
didStopNotifier = true
}
}
| 6392bf2d5654d098c9cb72b0c9349857 | 26.192771 | 72 | 0.61276 | false | false | false | false |
NoryCao/zhuishushenqi | refs/heads/master | zhuishushenqi/TXTReader/BookDetail/Models/BookDetail.swift | mit | 1 | //
// BookDetail.swift
// zhuishushenqi
//
// Created by Nory Cao on 16/10/4.
// Copyright © 2016年 QS. All rights reserved.
//
import UIKit
import HandyJSON
import SQLite
//let db = try? Connection("path/to/db.sqlite3")
//
//let users = Table("users")
//let id = Expression<Int64>("id")
//let name = Expression<String?>("name")
//let email = Expression<String>("email")
//
//try? db?.run(users.create { t in
// t.column(id, primaryKey: true)
// t.column(name)
// t.column(email, unique: true)
//})
//// CREATE TABLE "users" (
//// "id" INTEGER PRIMARY KEY NOT NULL,
//// "name" TEXT,
//// "email" TEXT NOT NULL UNIQUE
//// )
//
//let insert = users.insert(name <- "Alice", email <- "[email protected]")
//let rowid = try? db?.run(insert)
//// INSERT INTO "users" ("name", "email") VALUES ('Alice', '[email protected]')
//
//for user in try? db?.prepare(users) {
// print("id: \(user[id]), name: \(user[name]), email: \(user[email])")
// // id: 1, name: Optional("Alice"), email: [email protected]
//}
//// SELECT * FROM "users"
//
//let alice = users.filter(id == rowid)
//
//try? db.run(alice.update(email <- email.replace("mac.com", with: "me.com")))
//// UPDATE "users" SET "email" = replace("email", 'mac.com', 'me.com')
//// WHERE ("id" = 1)
//
//try? db?.run(alice.delete())
//// DELETE FROM "users" WHERE ("id" = 1)
//
//try? db?.scalar(users.count) // 0
//// SELECT count(*) FROM "users"
extension BookDetail:DBSaveProtocol {
func db_save(){
let homePath = NSHomeDirectory()
let dbPath = "\(homePath)/db.sqlite3"
if let db = try? Connection(dbPath) {
let detail = Table("BookDetail")
let author = Expression<String>("author")
let cover = Expression<String>("cover")
let creater = Expression<String>("creater")
let longIntro = Expression<String>("longIntro")
let title = Expression<String>("title")
let cat = Expression<String>("cat")
let majorCate = Expression<String>("majorCate")
let minorCate = Expression<String>("minorCate")
let latelyFollower = Expression<String>("latelyFollower")
let retentionRatio = Expression<String>("retentionRatio")
let serializeWordCount = Expression<String>("serializeWordCount")
let wordCount = Expression<String>("wordCount")
let updated = Expression<String>("updated")
let tags = Expression<String>("tags")
let id = Expression<String>("_id")
let postCount = Expression<Int>("postCount")
let copyright = Expression<String>("copyright")
let sourceIndex = Expression<Int>("sourceIndex")
let record = Expression<String>("record")
let chapter = Expression<Int>("chapter")
let page = Expression<Int>("page")
let resources = Expression<String>("resources")
let chapters = Expression<String>("chapters")
let chaptersInfo = Expression<String>("chaptersInfo")
let isUpdated = Expression<Int>("isUpdated")
let book = Expression<String>("book")
let updateInfo = Expression<String>("updateInfo")
_ = try? db.run(detail.create(temporary: false, ifNotExists: true, withoutRowid: true) { (t) in
t.column(id, primaryKey: true)
t.column(author)
t.column(cover)
t.column(creater)
t.column(longIntro)
t.column(title)
t.column(cat)
t.column(majorCate)
t.column(minorCate)
t.column(latelyFollower)
t.column(retentionRatio)
t.column(serializeWordCount)
t.column(wordCount)
t.column(updated)
t.column(tags)
t.column(postCount)
t.column(copyright)
t.column(sourceIndex)
t.column(record)
t.column(chapter)
t.column(page)
t.column(resources)
t.column(chapters)
t.column(chaptersInfo)
t.column(isUpdated)
t.column(book)
t.column(updateInfo)
})
}
}
}
@objc(BookDetail)
class BookDetail: NSObject,NSCoding ,HandyJSON{
var _id:String = ""
var author:String = ""
var cover:String = ""
var creater:String = ""
var longIntro:String = ""
var title:String = ""
var cat:String = ""
var majorCate:String = ""
var minorCate:String = ""
var latelyFollower:String = ""
var retentionRatio:String = ""
var serializeWordCount:String = ""//每天更新字数
var wordCount:String = ""
var updated:String = ""//更新时间
var tags:NSArray?
var postCount:Int = 0
var copyright:String = ""
var sourceIndex:Int = 1 //当前选择的源
// 阅读记录,
var record:QSRecord?
// 废弃
var chapter:Int = 0 //最后阅读的章节
var page:Int = 0 //最后阅读的页数
var resources:[ResourceModel]?
var chapters:[NSDictionary]? // 新的代码完成后去掉
var chaptersInfo:[ZSChapterInfo]? // 代替chapters
var isUpdated:Bool = false //是否存在更新,如果存在更新,进入书籍后修改状态
// book 一直存在,默认初始化,不保存任何章节
var book:QSBook!
// 书架缓存状态
var bookCacheState:SwipeCellState = .none
//更新信息
var updateInfo:BookShelf?
required init?(coder aDecoder: NSCoder) {
super.init()
self._id = aDecoder.decodeObject(forKey: "_id") as? String ?? ""
self.author = aDecoder.decodeObject(forKey: "author") as? String ?? ""
self.cover = aDecoder.decodeObject(forKey: "cover") as? String ?? ""
self.creater = aDecoder.decodeObject(forKey: "creater") as? String ?? ""
self.longIntro = aDecoder.decodeObject(forKey: "longIntro") as? String ?? ""
self.title = aDecoder.decodeObject(forKey: "title") as? String ?? ""
self.cat = aDecoder.decodeObject(forKey: "cat") as? String ?? ""
self.majorCate = aDecoder.decodeObject(forKey: "majorCate") as? String ?? ""
self.minorCate = aDecoder.decodeObject(forKey: "minorCate") as? String ?? ""
self.latelyFollower = aDecoder.decodeObject(forKey: "latelyFollower") as? String ?? ""
self.retentionRatio = aDecoder.decodeObject(forKey: "retentionRatio") as? String ?? ""
self.serializeWordCount = aDecoder.decodeObject(forKey: "serializeWordCount") as? String ?? ""
self.wordCount = aDecoder.decodeObject(forKey: "wordCount") as? String ?? ""
self.updated = aDecoder.decodeObject(forKey: "updated") as? String ?? ""
self.tags = aDecoder.decodeObject(forKey: "tags") as? NSArray
self.updateInfo = aDecoder.decodeObject(forKey: "updateInfo") as? BookShelf
self.chapter = aDecoder.decodeInteger(forKey:"chapter")
self.page = aDecoder.decodeInteger(forKey:"page")
self.sourceIndex = aDecoder.decodeInteger(forKey:"sourceIndex")
self.resources = aDecoder.decodeObject(forKey: "resources") as? [ResourceModel]
self.chapters = aDecoder.decodeObject(forKey: "chapters") as? [NSDictionary]
self.copyright = aDecoder.decodeObject(forKey: "copyright") as? String ?? ""
self.postCount = aDecoder.decodeInteger(forKey: "postCount")
self.isUpdated = aDecoder.decodeBool(forKey: "isUpdated")
self.book = aDecoder.decodeObject(forKey: "book") as? QSBook
self.record = aDecoder.decodeObject(forKey: "record") as? QSRecord
self.chaptersInfo = aDecoder.decodeObject(forKey: "chaptersInfo") as? [ZSChapterInfo]
self.bookCacheState = SwipeCellState.init(rawValue: aDecoder.decodeObject(forKey: "bookCacheState") as? String ?? "") ?? .none
setupBook()
}
private func setupBook(){
if book == nil {
book = QSBook()
}
}
required override init() {
super.init()
setupBook()
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self._id, forKey: "_id")
aCoder.encode(self.author, forKey: "author")
aCoder.encode(self.cover, forKey: "cover")
aCoder.encode(self.creater, forKey: "creater")
aCoder.encode(self.longIntro, forKey: "longIntro")
aCoder.encode(self.title, forKey: "title")
aCoder.encode(self.cat, forKey: "cat")
aCoder.encode(self.majorCate, forKey: "majorCate")
aCoder.encode(self.minorCate, forKey: "minorCate")
aCoder.encode(self.latelyFollower, forKey: "latelyFollower")
aCoder.encode(self.retentionRatio, forKey: "retentionRatio")
aCoder.encode(self.serializeWordCount, forKey: "serializeWordCount")
aCoder.encode(self.wordCount, forKey: "wordCount")
aCoder.encode(self.updated, forKey: "updated")
aCoder.encode(self.tags, forKey: "tags")
aCoder.encode(self.updateInfo, forKey: "updateInfo")
aCoder.encode(self.chapter, forKey: "chapter")
aCoder.encode(self.page, forKey: "page")
aCoder.encode(self.sourceIndex, forKey: "sourceIndex")
aCoder.encode(self.resources, forKey: "resources")
aCoder.encode(self.chapters, forKey: "chapters")
aCoder.encode(self.copyright, forKey: "copyright")
aCoder.encode(self.postCount, forKey: "postCount")
aCoder.encode(self.isUpdated, forKey: "isUpdated")
aCoder.encode(self.book, forKey: "book")
aCoder.encode(self.record, forKey: "record")
aCoder.encode(self.chaptersInfo,forKey:"chaptersInfo")
aCoder.encode(self.bookCacheState.rawValue, forKey: "bookCacheState")
}
}
| ba9721717af92e0267e894fcbc73a953 | 39.157025 | 134 | 0.605269 | false | false | false | false |
HockeyWX/HockeySDK-iOSDemo-Swift | refs/heads/master | Classes/BITCrashReportsViewController.swift | mit | 2 | //
// BITCrashReportsViewController.swift
// HockeySDK-iOSDemo-Swift
//
// Created by Kevin Li on 18/10/2016.
//
import UIKit
class BITCrashReportsViewController: UITableViewController {
//MARK: - Private
func triggerSignalCrash() {
/* Trigger a crash */
abort()
}
func triggerExceptionCrash() {
/* Trigger a crash */
let array = NSArray.init()
array.object(at: 23)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if section == 0 {
return 2
} else {
return 3
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return NSLocalizedString("Test Crashes", comment: "")
} else {
return NSLocalizedString("Alerts", comment: "")
}
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if section == 1 {
return NSLocalizedString("Presented UI relevant for localization", comment: "")
}
return nil;
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
}
// Configure the cell...
if indexPath.section == 0 {
if indexPath.row == 0 {
cell!.textLabel?.text = NSLocalizedString("Signal", comment: "");
} else {
cell!.textLabel?.text = NSLocalizedString("Exception", comment: "");
}
} else {
if (indexPath.row == 0) {
cell!.textLabel?.text = NSLocalizedString("Anonymous", comment: "");
} else if (indexPath.row == 1) {
cell!.textLabel?.text = NSLocalizedString("Anonymous 3 buttons", comment: "");
} else {
cell!.textLabel?.text = NSLocalizedString("Non-anonymous", comment: "");
}
}
return cell!
}
//MARK: - Table view delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == 0 {
if indexPath.row == 0 {
triggerSignalCrash()
} else {
triggerExceptionCrash()
}
} else {
let appName = "DemoApp"
var alertDescription = String(format: BITHockeyLocalizedString("CrashDataFoundAnonymousDescription"), appName)
if indexPath.row == 2 {
alertDescription = String(format: BITHockeyLocalizedString("CrashDataFoundDescription"), appName)
}
let alert = UIAlertController(title:String(format:BITHockeyLocalizedString("CrashDataFoundTitle"), appName), message: alertDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: BITHockeyLocalizedString("CrashDontSendReport"), style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: BITHockeyLocalizedString("CrashSendReport"), style: .default, handler: nil))
if indexPath.row == 1 {
alert.addAction(UIAlertAction(title: BITHockeyLocalizedString("CrashSendReportAlways"), style: .default, handler: nil))
}
self.present(alert, animated: true, completion: nil)
}
}
}
| b5f8a9eab79fb746bcff4bd91ad9eb16 | 34.068966 | 171 | 0.592183 | false | false | false | false |
k-o-d-e-n/CGLayout | refs/heads/master | Example/CGLayoutPlayground.playground/Pages/LayoutWorkspacePull.xcplaygroundpage/Contents.swift | mit | 1 | //: [Previous](@previous)
import UIKit
import CGLayout
import PlaygroundSupport
extension UIView {
convenience init(frame: CGRect, backgroundColor: UIColor) {
self.init(frame: frame)
self.backgroundColor = backgroundColor
}
}
public extension UIView {
func addSubviews<S: Sequence>(_ subviews: S) where S.Iterator.Element: UIView {
subviews.map {
$0.backgroundColor = $0.backgroundColor?.withAlphaComponent(0.5)
return $0
}.forEach(addSubview)
}
}
public extension CGRect {
static func random(in source: CGRect) -> CGRect {
let o = CGPoint(x: CGFloat(arc4random_uniform(UInt32(source.width))), y: CGFloat(arc4random_uniform(UInt32(source.height))))
let s = CGSize(width: CGFloat(arc4random_uniform(UInt32(source.width - o.x))), height: CGFloat(arc4random_uniform(UInt32(source.height - o.y))))
return CGRect(origin: o, size: s)
}
}
func view(by index: Int, color: UIColor, frame: CGRect) -> UIView {
let label = UILabel(frame: frame, backgroundColor: color)
label.text = String(index)
label.textAlignment = .center
return label
}
let workspaceView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568))
workspaceView.backgroundColor = .lightGray
PlaygroundPage.current.liveView = workspaceView
let rect1 = view(by: 1, color: .red,
frame: workspaceView.bounds.insetBy(dx: 100, dy: 200))
let inner = LayoutWorkspace.After.pull(axis: _RectAxis.horizontal, anchor: _RectAxisAnchor.leading)
// cropped
let rect2 = view(by: 2, color: .blue,
frame: CGRect(origin: .zero, size: CGSize(width: 250, height: 100)))
// cropped to zero
let rect4 = view(by: 4, color: .yellow,
frame: CGRect(x: 40, y: 400, width: 40, height: 40))
// pulled
let rect6 = view(by: 6, color: .cyan,
frame: CGRect(x: 120, y: 500, width: 40, height: 40))
let outer = LayoutWorkspace.Before.pull(axis: _RectAxis.horizontal, anchor: _RectAxisAnchor.leading)
// cropped
let rect3 = view(by: 3, color: .green,
frame: CGRect(origin: CGPoint(x: 70, y: 200), size: CGSize(width: 50, height: 100)))
// cropped to zero
let rect5 = view(by: 5, color: .magenta,
frame: CGRect(x: 120, y: 400, width: 40, height: 40))
// pulled
let rect7 = view(by: 7, color: .brown,
frame: CGRect(x: 10, y: 450, width: 40, height: 40))
/// comment for show initial state
inner.formConstrain(sourceRect: &rect2.frame, by: rect1.frame)
inner.formConstrain(sourceRect: &rect4.frame, by: rect1.frame)
inner.formConstrain(sourceRect: &rect6.frame, by: rect1.frame)
outer.formConstrain(sourceRect: &rect3.frame, by: rect1.frame)
outer.formConstrain(sourceRect: &rect5.frame, by: rect1.frame)
outer.formConstrain(sourceRect: &rect7.frame, by: rect1.frame)
workspaceView.addSubviews([rect1, rect2, rect3, rect4, rect5, rect6, rect7])
| 6de254cf359d74a676941a3905de61de | 37.933333 | 152 | 0.673288 | false | false | false | false |
joelbanzatto/MVCarouselCollectionView | refs/heads/master | MVCarouselCollectionViewDemo/Carousel/MVEmbeddedCarouselViewController.swift | mit | 2 | // MVEmbeddedCarouselViewController.swift
//
// Copyright (c) 2015 Andrea Bizzotto ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import MVCarouselCollectionView
class MVEmbeddedCarouselViewController: UIViewController, MVCarouselCollectionViewDelegate, MVFullScreenCarouselViewControllerDelegate {
var imagePaths : [String] = []
var imageLoader: ((imageView: UIImageView, imagePath : String, completion: (newImage: Bool) -> ()) -> ())?
@IBOutlet var collectionView : MVCarouselCollectionView!
@IBOutlet var pageControl : MVCarouselPageControl!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.setTranslatesAutoresizingMaskIntoConstraints(false)
self.pageControl.numberOfPages = imagePaths.count
// Configure collection view
self.collectionView.selectDelegate = self
self.collectionView.imagePaths = imagePaths
self.collectionView.commonImageLoader = self.imageLoader
self.collectionView.maximumZoom = 2.0
self.collectionView.reloadData()
}
func addAsChildViewController(parentViewController : UIViewController, attachToView parentView: UIView) {
parentViewController.addChildViewController(self)
self.didMoveToParentViewController(parentViewController)
parentView.addSubview(self.view)
self.autoLayout(parentView)
}
func autoLayout(parentView: UIView) {
self.matchLayoutAttribute(.Left, parentView:parentView)
self.matchLayoutAttribute(.Right, parentView:parentView)
self.matchLayoutAttribute(.Bottom, parentView:parentView)
self.matchLayoutAttribute(.Top, parentView:parentView)
}
func matchLayoutAttribute(attribute : NSLayoutAttribute, parentView: UIView) {
parentView.addConstraint(
NSLayoutConstraint(item:self.view, attribute:attribute, relatedBy:NSLayoutRelation.Equal, toItem:parentView, attribute:attribute, multiplier:1.0, constant:0))
}
// MARK: MVCarouselCollectionViewDelegate
func carousel(carousel: MVCarouselCollectionView, didSelectCellAtIndexPath indexPath: NSIndexPath) {
// Send indexPath.row as index to use
self.performSegueWithIdentifier("FullScreenSegue", sender:indexPath);
}
func carousel(carousel: MVCarouselCollectionView, didScrollToCellAtIndex cellIndex : NSInteger) {
self.pageControl.currentPage = cellIndex
}
// MARK: IBActions
@IBAction func pageControlEventChanged(sender: UIPageControl) {
self.collectionView.setCurrentPageIndex(sender.currentPage, animated: true)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "FullScreenSegue" {
var nc = segue.destinationViewController as? UINavigationController
var vc = nc?.viewControllers[0] as? MVFullScreenCarouselViewController
if let vc = vc {
vc.imageLoader = self.imageLoader
vc.imagePaths = self.imagePaths
vc.delegate = self
vc.title = self.parentViewController?.navigationItem.title
if let indexPath = sender as? NSIndexPath {
vc.initialViewIndex = indexPath.row
}
}
}
}
// MARK: FullScreenViewControllerDelegate
func willCloseWithSelectedIndexPath(indexPath: NSIndexPath) {
self.collectionView.resetZoom()
self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition:UICollectionViewScrollPosition.CenteredHorizontally, animated:false)
}
}
| ca46a819735e8617353da980b349d58c | 40.504348 | 166 | 0.720302 | false | false | false | false |
JaSpa/swift | refs/heads/master | test/expr/postfix/dot/init_ref_delegation.swift | apache-2.0 | 26 | // RUN: %target-typecheck-verify-swift
// Tests for initializer delegation via self.init(...).
// Initializer delegation: classes
class C0 {
convenience init() {
self.init(value: 5)
}
init(value: Int) { /* ... */ }
}
class C1 {
convenience init() {
self.init(value: 5)
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
// Initializer delegation: structs
struct S0 {
init() {
self.init(value: 5)
}
init(value: Int) { /* ... */ }
}
struct S1 {
init() {
self.init(value: 5)
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
// Initializer delegation: enum
enum E0 {
case A
case B
init() {
self.init(value: 5)
}
init(value: Int) { /* ... */ }
}
enum E1 {
case A
case B
init() {
self.init(value: 5)
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
// Ill-formed initializer delegation: no matching constructor
class Z0 {
init() { // expected-error {{designated initializer for 'Z0' cannot delegate (with 'self.init'); did you mean this to be a convenience initializer?}} {{3-3=convenience }}
// expected-note @+2 {{delegation occurs here}}
self.init(5, 5) // expected-error{{cannot invoke 'Z0.init' with an argument list of type '(Int, Int)'}}
// expected-note @-1 {{overloads for 'Z0.init' exist with these partially matching parameter lists: (), (value: Int), (value: Double)}}
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
struct Z1 {
init() {
self.init(5, 5) // expected-error{{cannot invoke 'Z1.init' with an argument list of type '(Int, Int)'}}
// expected-note @-1 {{overloads for 'Z1.init' exist with these partially matching parameter lists: (), (value: Int), (value: Double)}}
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
enum Z2 {
case A
case B
init() {
self.init(5, 5) // expected-error{{cannot invoke 'Z2.init' with an argument list of type '(Int, Int)'}}
// expected-note @-1 {{overloads for 'Z2.init' exist with these partially matching parameter lists: (), (value: Int), (value: Double)}}
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
// Ill-formed initialization: wrong context.
class Z3 {
func f() {
self.init() // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{10-10=type(of: }} {{14-14=)}}
}
init() { }
}
// 'init' is a static-ish member.
class Z4 {
init() {} // expected-note{{selected non-required initializer}}
convenience init(other: Z4) {
other.init() // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{11-11=type(of: }} {{15-15=)}}
type(of: other).init() // expected-error{{must use a 'required' initializer}} expected-warning{{unused}}
}
}
class Z5 : Z4 {
override init() { }
convenience init(other: Z5) {
other.init() // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{11-11=type(of: }} {{15-15=)}}
}
}
// Ill-formed initialization: failure to call initializer.
class Z6 {
convenience init() {
var _ : () -> Z6 = self.init // expected-error{{partial application of 'self.init' initializer delegation is not allowed}}
}
init(other: Z6) { }
}
// Ill-formed initialization: both superclass and delegating.
class Z7Base { }
class Z7 : Z7Base {
override init() { }
init(b: Bool) {
if b { super.init() } // expected-note{{previous chaining call is here}}
else { self.init() } // expected-error{{initializer cannot both delegate ('self.init') and chain to a }}
}
}
struct RDar16603812 {
var i = 42
init() {}
func foo() {
self.init() // expected-error {{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{12-12=type(of: }} {{16-16=)}}
type(of: self).init() // expected-warning{{result of 'RDar16603812' initializer is unused}}
}
}
class RDar16666631 {
var i: Int
var d: Double
var s: String
init(i: Int, d: Double, s: String) {
self.i = i
self.d = d
self.s = s
}
convenience init(i: Int, s: String) {
self.init(i: i, d: 0.1, s: s)
}
}
let rdar16666631 = RDar16666631(i: 5, d: 6) // expected-error {{incorrect argument label in call (have 'i:d:', expected 'i:s:')}}
struct S {
init() {
let _ = S.init()
self.init()
let _ = self.init // expected-error{{partial application of 'self.init' initializer delegation is not allowed}}
}
}
class C {
convenience init() { // expected-note 11 {{selected non-required initializer 'init()'}}
self.init()
let _: C = self.init() // expected-error{{cannot convert value of type '()' to specified type 'C'}}
let _: () -> C = self.init // expected-error{{partial application of 'self.init' initializer delegation is not allowed}}
}
init(x: Int) {} // expected-note 11 {{selected non-required initializer 'init(x:)'}}
required init(required: Double) {}
}
class D: C {
override init(x: Int) {
super.init(x: x)
let _: C = super.init() // expected-error{{cannot convert value of type '()' to specified type 'C'}}
let _: () -> C = super.init // expected-error{{partial application of 'super.init' initializer chain is not allowed}}
}
func foo() {
self.init(x: 0) // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{10-10=type(of: }} {{14-14=)}}
}
func bar() {
super.init(x: 0) // expected-error{{'super.init' cannot be called outside of an initializer}}
}
class func zim() -> Self {
return self.init(required: 0)
}
class func zang() -> C {
return super.init(required: 0)
}
required init(required: Double) {}
}
func init_tests() {
var s = S.self
var s1 = s.init()
var ss1 = S.init()
var c: C.Type = D.self
var c1 = c.init(required: 0)
var c2 = c.init(x: 0) // expected-error{{'required' initializer}}
var c3 = c.init() // expected-error{{'required' initializer}}
var c1a = c.init(required: 0)
var c2a = c.init(x: 0) // expected-error{{'required' initializer}}
var c3a = c.init() // expected-error{{'required' initializer}}
var cf1: (Double) -> C = c.init
var cf2: (Int) -> C = c.init // expected-error{{'required' initializer}}
var cf3: () -> C = c.init // expected-error{{'required' initializer}}
var cs1 = C.init(required: 0)
var cs2 = C.init(x: 0)
var cs3 = C.init()
var csf1: (Double) -> C = C.init
var csf2: (Int) -> C = C.init
var csf3: () -> C = C.init
var cs1a = C(required: 0)
var cs2a = C(x: 0)
var cs3a = C()
var y = x.init() // expected-error{{use of unresolved identifier 'x'}}
}
protocol P {
init(proto: String)
}
func foo<T: C>(_ x: T, y: T.Type) where T: P {
var c1 = type(of: x).init(required: 0)
var c2 = type(of: x).init(x: 0) // expected-error{{'required' initializer}}
var c3 = type(of: x).init() // expected-error{{'required' initializer}}
var c4 = type(of: x).init(proto: "")
var cf1: (Double) -> T = type(of: x).init
var cf2: (Int) -> T = type(of: x).init // expected-error{{'required' initializer}}
var cf3: () -> T = type(of: x).init // expected-error{{'required' initializer}}
var cf4: (String) -> T = type(of: x).init
var c1a = type(of: x).init(required: 0)
var c2a = type(of: x).init(x: 0) // expected-error{{'required' initializer}}
var c3a = type(of: x).init() // expected-error{{'required' initializer}}
var c4a = type(of: x).init(proto: "")
var ci1 = x.init(required: 0) // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{15-15=type(of: }} {{19-19=)}}
var ci2 = x.init(x: 0) // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{15-15=type(of: }} {{19-19=)}}
var ci3 = x.init() // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{15-15=type(of: }} {{19-19=)}}
var ci4 = x.init(proto: "") // expected-error{{'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type}} {{15-15=type(of: }} {{19-19=)}}
var ci1a = x(required: 0) // expected-error{{cannot call value of non-function type 'T'}}
var ci2a = x(x: 0) // expected-error{{cannot call value of non-function type 'T'}}
var ci3a = x() // expected-error{{cannot call value of non-function type 'T'}}{{15-17=}}
var ci4a = x(proto: "") // expected-error{{cannot call value of non-function type 'T'}}
var cm1 = y.init(required: 0)
var cm2 = y.init(x: 0) // expected-error{{'required' initializer}}
var cm3 = y.init() // expected-error{{'required' initializer}}
var cm4 = y.init(proto: "")
var cm1a = y.init(required: 0)
var cm2a = y.init(x: 0) // expected-error{{'required' initializer}}
var cm3a = y.init() // expected-error{{'required' initializer}}
var cm4a = y.init(proto: "")
var cs1 = T.init(required: 0)
var cs2 = T.init(x: 0) // expected-error{{'required' initializer}}
var cs3 = T.init() // expected-error{{'required' initializer}}
var cs4 = T.init(proto: "")
var cs5 = T.init(notfound: "") // expected-error{{argument labels '(notfound:)' do not match any available overloads}}
// expected-note @-1 {{overloads for 'T.Type.init' exist with these partially matching parameter lists: (x: Int), (required: Double), (proto: String)}}
var csf1: (Double) -> T = T.init
var csf2: (Int) -> T = T.init // expected-error{{'required' initializer}}
var csf3: () -> T = T.init // expected-error{{'required' initializer}}
var csf4: (String) -> T = T.init
var cs1a = T(required: 0)
var cs2a = T(x: 0) // expected-error{{'required' initializer}}
var cs3a = T() // expected-error{{'required' initializer}}
var cs4a = T(proto: "")
}
class TestOverloadSets {
convenience init() {
self.init(5, 5) // expected-error{{cannot invoke 'TestOverloadSets.init' with an argument list of type '(Int, Int)'}}
// expected-note @-1 {{overloads for 'TestOverloadSets.init' exist with these partially matching parameter lists: (), (a: Z0), (value: Int), (value: Double)}}
}
convenience init(a : Z0) {
self.init(42 as Int8) // expected-error{{argument labels '(_:)' do not match any available overloads}}
// expected-note @-1 {{overloads for 'TestOverloadSets.init' exist with these partially matching parameter lists: (a: Z0), (value: Int), (value: Double)}}
}
init(value: Int) { /* ... */ }
init(value: Double) { /* ... */ }
}
class TestNestedExpr {
init() {}
init?(fail: Bool) {}
init(error: Bool) throws {}
convenience init(a: Int) {
let x: () = self.init() // expected-error {{initializer delegation ('self.init') cannot be nested in another statement}}
// expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
}
convenience init(b: Int) {
func use(_ x: ()) {}
use(self.init()) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
convenience init(c: Int) {
_ = ((), self.init()) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
convenience init(d: Int) {
let x: () = self.init(fail: true)! // expected-error {{initializer delegation ('self.init') cannot be nested in another statement}}
// expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
}
convenience init(e: Int) {
func use(_ x: ()) {}
use(self.init(fail: true)!) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
convenience init(f: Int) {
_ = ((), self.init(fail: true)!) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
convenience init(g: Int) {
let x: () = try! self.init(error: true) // expected-error {{initializer delegation ('self.init') cannot be nested in another statement}}
// expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
}
convenience init(h: Int) {
func use(_ x: ()) {}
use(try! self.init(error: true)) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
convenience init(i: Int) {
_ = ((), try! self.init(error: true)) // expected-error {{initializer delegation ('self.init') cannot be nested in another expression}}
}
}
class TestNestedExprSub : TestNestedExpr {
init(a: Int) {
let x: () = super.init() // expected-error {{initializer chaining ('super.init') cannot be nested in another statement}}
// expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
}
init(b: Int) {
func use(_ x: ()) {}
use(super.init()) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
init(c: Int) {
_ = ((), super.init()) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
init(d: Int) {
let x: () = super.init(fail: true)! // expected-error {{initializer chaining ('super.init') cannot be nested in another statement}}
// expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
}
init(e: Int) {
func use(_ x: ()) {}
use(super.init(fail: true)!) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
init(f: Int) {
_ = ((), super.init(fail: true)!) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
init(g: Int) {
let x: () = try! super.init(error: true) // expected-error {{initializer chaining ('super.init') cannot be nested in another statement}}
// expected-warning@-1 {{immutable value 'x' was never used; consider replacing with '_' or removing it}}
}
init(h: Int) {
func use(_ x: ()) {}
use(try! super.init(error: true)) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
init(i: Int) {
_ = ((), try! super.init(error: true)) // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
}
class TestOptionalTry {
init() throws {}
convenience init(a: Int) { // expected-note {{propagate the failure with 'init?'}} {{19-19=?}}
try? self.init() // expected-error {{a non-failable initializer cannot use 'try?' to delegate to another initializer}}
// expected-note@-1 {{force potentially-failing result with 'try!'}} {{5-9=try!}}
}
init?(fail: Bool) throws {}
convenience init(failA: Int) { // expected-note {{propagate the failure with 'init?'}} {{19-19=?}}
try? self.init(fail: true)! // expected-error {{a non-failable initializer cannot use 'try?' to delegate to another initializer}}
// expected-note@-1 {{force potentially-failing result with 'try!'}} {{5-9=try!}}
}
convenience init(failB: Int) { // expected-note {{propagate the failure with 'init?'}} {{19-19=?}}
try! self.init(fail: true) // expected-error {{a non-failable initializer cannot delegate to failable initializer 'init(fail:)' written with 'init?'}}
// expected-note@-1 {{force potentially-failing result with '!'}} {{31-31=!}}
}
convenience init(failC: Int) {
try! self.init(fail: true)! // okay
}
convenience init?(failD: Int) {
try? self.init(fail: true) // okay
}
convenience init?(failE: Int) {
try! self.init(fail: true) // okay
}
convenience init?(failF: Int) {
try! self.init(fail: true)! // okay
}
convenience init?(failG: Int) {
try? self.init(fail: true) // okay
}
}
class TestOptionalTrySub : TestOptionalTry {
init(a: Int) { // expected-note {{propagate the failure with 'init?'}} {{7-7=?}}
try? super.init() // expected-error {{a non-failable initializer cannot use 'try?' to chain to another initializer}}
// expected-note@-1 {{force potentially-failing result with 'try!'}} {{5-9=try!}}
}
}
| cfc2c00f15bbcb4573ec6ceee5636ef4 | 34.074786 | 189 | 0.624368 | false | false | false | false |
AbidHussainCom/HackingWithSwift | refs/heads/master | project11/Project11/GameScene.swift | unlicense | 20 | //
// GameScene.swift
// Project11
//
// Created by Hudzilla on 22/11/2014.
// Copyright (c) 2014 Hudzilla. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var scoreLabel: SKLabelNode!
var score: Int = 0 {
didSet {
scoreLabel.text = "Score: \(score)"
}
}
var editLabel: SKLabelNode!
var editingMode: Bool = false {
didSet {
if editingMode {
editLabel.text = "Done"
} else {
editLabel.text = "Edit"
}
}
}
override func didMoveToView(view: SKView) {
let background = SKSpriteNode(imageNamed: "background.jpg")
background.position = CGPoint(x: 512, y: 384)
background.blendMode = .Replace
background.zPosition = -1
addChild(background)
physicsBody = SKPhysicsBody(edgeLoopFromRect:CGRect(x: 0, y: 0, width: 1024, height: 768))
physicsWorld.contactDelegate = self
makeSlotAt(CGPoint(x: 128, y: 0), isGood: true)
makeSlotAt(CGPoint(x: 384, y: 0), isGood: false)
makeSlotAt(CGPoint(x: 640, y: 0), isGood: true)
makeSlotAt(CGPoint(x: 896, y:0), isGood: false)
makeBouncerAt(CGPoint(x: 0, y: 0))
makeBouncerAt(CGPoint(x: 256, y: 0))
makeBouncerAt(CGPoint(x: 512, y: 0))
makeBouncerAt(CGPoint(x: 768, y: 0))
makeBouncerAt(CGPoint(x: 1024, y: 0))
scoreLabel = SKLabelNode(fontNamed: "Chalkduster")
scoreLabel.text = "Score: 0"
scoreLabel.horizontalAlignmentMode = .Right
scoreLabel.position = CGPoint(x: 980, y: 700)
addChild(scoreLabel)
editLabel = SKLabelNode(fontNamed: "Chalkduster")
editLabel.text = "Edit"
editLabel.position = CGPoint(x: 80, y: 700)
addChild(editLabel)
}
func makeBouncerAt(position: CGPoint) {
let bouncer = SKSpriteNode(imageNamed: "bouncer")
bouncer.position = position
bouncer.physicsBody = SKPhysicsBody(circleOfRadius: bouncer.size.width / 2.0)
bouncer.physicsBody!.dynamic = false
addChild(bouncer)
}
func makeSlotAt(position: CGPoint, isGood: Bool) {
var slotBase: SKSpriteNode
var slotGlow: SKSpriteNode
if isGood {
slotBase = SKSpriteNode(imageNamed: "slotBaseGood")
slotGlow = SKSpriteNode(imageNamed: "slotGlowGood")
slotBase.name = "good"
} else {
slotBase = SKSpriteNode(imageNamed: "slotBaseBad")
slotGlow = SKSpriteNode(imageNamed: "slotGlowBad")
slotBase.name = "bad"
}
slotBase.position = position
slotGlow.position = position
slotBase.physicsBody = SKPhysicsBody(rectangleOfSize: slotBase.size)
slotBase.physicsBody!.contactTestBitMask = slotBase.physicsBody!.collisionBitMask
slotBase.physicsBody!.dynamic = false
addChild(slotBase)
addChild(slotGlow)
let spin = SKAction.rotateByAngle(CGFloat(M_PI_2), duration: 10)
let spinForever = SKAction.repeatActionForever(spin)
slotGlow.runAction(spinForever)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if let touch = touches.first as? UITouch {
let location = touch.locationInNode(self)
let objects = nodesAtPoint(location) as! [SKNode]
if contains(objects, editLabel) {
editingMode = !editingMode
} else {
if editingMode {
let size = CGSize(width: RandomInt(min: 16, max: 128), height: 16)
let box = SKSpriteNode(color: RandomColor(), size: size)
box.zRotation = RandomCGFloat(min: 0, max: 3)
box.position = location
box.physicsBody = SKPhysicsBody(rectangleOfSize: box.size)
box.physicsBody!.dynamic = false
addChild(box)
} else {
var ball: SKSpriteNode
switch RandomInt(min: 0, max: 3) {
case 0:
ball = SKSpriteNode(imageNamed: "ballRed")
break
case 1:
ball = SKSpriteNode(imageNamed: "ballBlue")
break
case 2:
ball = SKSpriteNode(imageNamed: "ballGreen")
break
case 3:
ball = SKSpriteNode(imageNamed: "ballYellow")
break
default:
return
}
ball.name = "ball"
ball.position = CGPoint(x: location.x, y: 700)
addChild(ball)
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width / 2.0)
ball.physicsBody!.contactTestBitMask = ball.physicsBody!.collisionBitMask
ball.physicsBody!.restitution = 0.4
}
}
}
}
func didBeginContact(contact: SKPhysicsContact) {
if contact.bodyA.node!.name == "ball" {
collisionBetweenBall(contact.bodyA.node!, object: contact.bodyB.node!)
} else if contact.bodyB.node!.name == "ball" {
collisionBetweenBall(contact.bodyB.node!, object: contact.bodyA.node!)
}
}
func collisionBetweenBall(ball: SKNode, object: SKNode) {
if object.name == "good" {
destroyBall(ball)
++score
} else if object.name == "bad" {
destroyBall(ball)
--score
}
}
func destroyBall(ball: SKNode) {
if let myParticlePath = NSBundle.mainBundle().pathForResource("FireParticles", ofType: "sks") {
let fireParticles = NSKeyedUnarchiver.unarchiveObjectWithFile(myParticlePath) as! SKEmitterNode
fireParticles.position = ball.position
addChild(fireParticles)
}
ball.removeFromParent()
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
| ebf072598a2c2cb3ddb133cbd7806263 | 25.889474 | 98 | 0.693286 | false | false | false | false |
kingcos/CS193P_2017 | refs/heads/master | CoreDataExample/CoreDataExample/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// CoreDataExample
//
// Created by 买明 on 19/03/2017.
// Copyright © 2017 买明. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. 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 active 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 persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded 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.
*/
let container = NSPersistentContainer(name: "Model")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| d8157eb9cad178efded347c81aa4cd74 | 48.236559 | 285 | 0.685302 | false | false | false | false |
fleurdeswift/code-editor | refs/heads/master | CodeEditorCore/Controller+Navigation.swift | mit | 1 | //
// Controller+Navigation.swift
// CodeEditorCore
//
// Copyright © 2015 Fleur de Swift. All rights reserved.
//
import Foundation
public extension Controller {
private func moveCursors(block: (inout position: Position, context: ModificationContext) -> Bool, extendsSelection: Bool) -> Bool {
do {
return try document.modify({ (context: ModificationContext) -> Bool in
return self.moveCursors(block, extendsSelection: extendsSelection, context: context);
}).result;
}
catch {
return false;
}
}
private func moveCursors(block: (inout position: Position, context: ModificationContext) -> Bool, extendsSelection: Bool, context: ModificationContext) -> Bool {
var modified = false;
for cursor in cursors {
if cursor.type != .Edit {
continue;
}
modified |= moveCursor(block, cursor: cursor, extendsSelection: extendsSelection, context: context);
}
return modified;
}
private func moveCursor(block: (inout position: Position, context: ModificationContext) -> Bool, cursor: Cursor, extendsSelection: Bool, context: ModificationContext) -> Bool {
if block(position: &cursor.range.end, context: context) {
if !extendsSelection {
cursor.range.start = cursor.range.end;
}
onCursorMoved(cursor);
return true;
}
return false;
}
public func normalize(inout position: Position, context: ReadContext) -> Bool {
if position.line >= document.lines.count {
position = document.endPosition(context);
return true;
}
else if position.line < 0 {
position = document.beginPosition;
return true;
}
let line = document.lines[position.line];
let length = line.length;
if position.column > length {
position.column = length;
return true;
}
else if position.column < 0 {
assert(false);
position.column = 0;
return true;
}
return false;
}
public func moveBackward(inout position: Position, context: ModificationContext) -> Bool {
if (normalize(&position, context: context)) {
return true;
}
if position.column == 0 {
if position.line == 0 {
return false;
}
position.line--;
position.column = document.lines[position.line].length;
}
else {
position.column--;
}
return true;
}
public func moveBackward(inout position: Position, characterIterator: (ch: Character) -> Bool, context: ModificationContext) -> Bool {
if (normalize(&position, context: context)) {
return true;
}
while true {
let ch = document.lines[position.line].charAt(position.column);
if characterIterator(ch: ch) {
break;
}
if position.column == 0 {
if position.line == 0 {
return false;
}
position.line--;
position.column = document.lines[position.line].length;
}
else {
position.column--;
}
}
return true;
}
public func moveCursorBackward(cursor: Cursor, extendsSelection: Bool, context: ModificationContext) -> Bool {
return moveCursor(moveBackward, cursor: cursor, extendsSelection: extendsSelection, context: context);
}
public func moveCursorsBackward(extendsSelection: Bool, context: ModificationContext) -> Bool {
return moveCursors(moveBackward, extendsSelection: extendsSelection, context: context);
}
public func moveCursorsBackward(extendsSelection: Bool) -> Bool {
return moveCursors(moveBackward, extendsSelection: extendsSelection);
}
public func moveForward(inout position: Position, context: ModificationContext) -> Bool {
if (normalize(&position, context: context)) {
return true;
}
let line = document.lines[position.line];
if position.column < line.length {
position.column++;
return true;
}
if (document.lines.count - 1) == position.line {
return false;
}
position.line++;
position.column = 0;
return true;
}
public func moveForward(inout position: Position, characterIterator: (ch: Character) -> Bool, context: ModificationContext) -> Bool {
if (normalize(&position, context: context)) {
return true;
}
while true {
let ch = document.lines[position.line].charAt(position.column);
if characterIterator(ch: ch) {
break;
}
let line = document.lines[position.line];
if position.column < line.length {
position.column++;
continue;
}
if (document.lines.count - 1) == position.line {
return false;
}
position.line++;
position.column = 0;
}
return true;
}
public func moveCursorForward(cursor: Cursor, extendsSelection: Bool, context: ModificationContext) -> Bool {
return moveCursor(moveForward, cursor: cursor, extendsSelection: extendsSelection, context: context);
}
public func moveCursorsForward(extendsSelection: Bool, context: ModificationContext) -> Bool {
return moveCursors(moveForward, extendsSelection: extendsSelection, context: context);
}
public func moveCursorsForward(extendsSelection: Bool) -> Bool {
return moveCursors(moveForward, extendsSelection: extendsSelection);
}
public func moveToEndOfLine(inout position: Position, context: ModificationContext) -> Bool {
if (normalize(&position, context: context)) {
return true;
}
let line = document.lines[position.line];
if position.column != line.length {
position.column = line.length;
return true;
}
return true;
}
public func moveCursorToEndOfLine(cursor: Cursor, extendsSelection: Bool, context: ModificationContext) -> Bool {
return moveCursor(moveToEndOfLine, cursor: cursor, extendsSelection: extendsSelection, context: context);
}
public func moveCursorsToEndOfLine(extendsSelection: Bool, context: ModificationContext) -> Bool {
return moveCursors(moveToEndOfLine, extendsSelection: extendsSelection, context: context);
}
public func moveCursorsToEndOfLine(extendsSelection: Bool) -> Bool {
return moveCursors(moveToEndOfLine, extendsSelection: extendsSelection);
}
public func moveToStartOfLine(inout position: Position, context: ModificationContext) -> Bool {
if (normalize(&position, context: context)) {
return true;
}
if position.column != 0 {
position.column = 0;
return true;
}
return true;
}
public func moveCursorToStartOfLine(cursor: Cursor, extendsSelection: Bool, context: ModificationContext) -> Bool {
return moveCursor(moveToStartOfLine, cursor: cursor, extendsSelection: extendsSelection, context: context);
}
public func moveCursorsToStartOfLine(extendsSelection: Bool, context: ModificationContext) -> Bool {
return moveCursors(moveToStartOfLine, extendsSelection: extendsSelection, context: context);
}
public func moveCursorsToStartOfLine(extendsSelection: Bool) -> Bool {
return moveCursors(moveToStartOfLine, extendsSelection: extendsSelection);
}
}
| c2fd5a72fd4e2900cae8a27de0c70a4b | 31.907631 | 180 | 0.583964 | false | false | false | false |
phatblat/realm-cocoa | refs/heads/master | examples/ios/swift/Migration/Examples/Example_v0.swift | apache-2.0 | 2 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2021 Realm Inc.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////
#if SCHEMA_VERSION_0
import Foundation
import RealmSwift
// MARK: - Schema
let schemaVersion = 0
class Person: Object {
@Persisted var firstName = ""
@Persisted var lastName = ""
@Persisted var age = 0
convenience init(firstName: String, lastName: String, age: Int) {
self.init()
self.firstName = firstName
self.lastName = lastName
self.age = age
}
}
// MARK: - Migration
// Migration block to migrate from *any* previous version to this version.
let migrationBlock: MigrationBlock = { _, _ in }
// This block checks if the migration led to the expected result.
// All older versions should have been migrated to the below stated `exampleData`.
let migrationCheck: (Realm) -> Void = { realm in
let persons = realm.objects(Person.self)
assert(persons.count == 3)
assert(persons[0].firstName == "John")
assert(persons[0].lastName == "Doe")
assert(persons[0].age == 42)
assert(persons[1].firstName == "Jane")
assert(persons[1].lastName == "Doe")
assert(persons[1].age == 43)
assert(persons[2].firstName == "John")
assert(persons[2].lastName == "Smith")
assert(persons[2].age == 44)
}
// MARK: - Example data
// Example data for this schema version.
let exampleData: (Realm) -> Void = { realm in
let person1 = Person(firstName: "John", lastName: "Doe", age: 42)
let person2 = Person(firstName: "Jane", lastName: "Doe", age: 43)
let person3 = Person(firstName: "John", lastName: "Smith", age: 44)
realm.add([person1, person2, person3])
}
#endif
| 97cf785607c8c72004080d10f84dce6f | 31.478873 | 82 | 0.633998 | false | false | false | false |
mpclarkson/vapor | refs/heads/master | Tests/Vapor/HTTPStreamTests.swift | mit | 1 | //
// JeevesTests.swift
// Vapor
//
// Created by Logan Wright on 3/12/16.
// Copyright © 2016 Tanner Nelson. All rights reserved.
//
import Foundation
import XCTest
@testable import Vapor
class HTTPStreamTests: XCTestCase {
static var allTests: [(String, HTTPStreamTests -> () throws -> Void)] {
return [
("testStream", testStream)
]
}
func testStream() throws {
let stream = TestHTTPStream.makeStream()
//MARK: Create Request
let content = "{\"hello\": \"world\"}"
var data = "POST /json HTTP/1.1\r\n"
data += "Accept-Encoding: gzip, deflate\r\n"
data += "Accept: */*\r\n"
data += "Accept-Language: en-us\r\n"
data += "Cookie: 1=1\r\n"
data += "Cookie: 2=2\r\n"
data += "Content-Type: application/json\r\n"
data += "Content-Length: \(content.characters.count)\r\n"
data += "\r\n"
data += content
//MARK: Send Request
try stream.send(data)
//MARK: Read Request
var request: Request
do {
request = try stream.receive()
} catch {
XCTFail("Error receiving from stream: \(error)")
return
}
request.parseData()
//MARK: Verify Request
XCTAssert(request.method == Request.Method.post, "Incorrect method \(request.method)")
XCTAssert(request.uri.path == "/json", "Incorrect path \(request.uri.path)")
XCTAssert(request.version.major == 1 && request.version.minor == 1, "Incorrect version")
XCTAssert(request.headers["cookie"].count == 2, "Incorrect cookies count")
XCTAssert(request.cookies["1"] == "1" && request.cookies["2"] == "2", "Cookies not parsed")
XCTAssert(request.data["hello"]?.string == "world")
//MARK: Create Response
var response = Response(status: .enhanceYourCalm, headers: [
"Test": ["123", "456"],
"Content-Type": "text/plain"
], body: { stream in
try stream.send("Hello, world")
})
response.cookies["key"] = "val"
//MARK: Send Response
try stream.send(response, keepAlive: true)
//MARK: Read Response
do {
let data = try stream.receive(max: Int.max)
print(data)
let expected = "HTTP/1.1 420 Enhance Your Calm\r\nConnection: keep-alive\r\nContent-Type: text/plain\r\nSet-Cookie: key=val\r\nTest: 123\r\nTest: 456\r\nTransfer-Encoding: chunked\r\n\r\nHello, world"
//MARK: Verify Response
XCTAssert(data == expected.data)
} catch {
XCTFail("Could not parse response string \(error)")
}
}
}
| d232d204a8234298c45305a250a2acc2 | 29.943182 | 212 | 0.566287 | false | true | false | false |
OrRon/NexmiiHack | refs/heads/develop | Carthage/Checkouts/LayoutKit/LayoutKit/Views/ReloadableViewLayoutAdapter+UICollectionView.swift | apache-2.0 | 5 | // Copyright 2016 LinkedIn Corp.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import UIKit
// MARK: - UICollectionViewDelegateFlowLayout
extension ReloadableViewLayoutAdapter: UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return currentArrangement[indexPath.section].items[indexPath.item].frame.size
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return currentArrangement[section].header?.frame.size ?? .zero
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return currentArrangement[section].footer?.frame.size ?? .zero
}
}
// MARK: - UICollectionViewDataSource
extension ReloadableViewLayoutAdapter: UICollectionViewDataSource {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return currentArrangement[section].items.count
}
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return currentArrangement.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let item = currentArrangement[indexPath.section].items[indexPath.item]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
item.makeViews(in: cell.contentView)
return cell
}
public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: reuseIdentifier, for: indexPath)
let arrangement: LayoutArrangement?
switch kind {
case UICollectionElementKindSectionHeader:
arrangement = currentArrangement[indexPath.section].header
case UICollectionElementKindSectionFooter:
arrangement = currentArrangement[indexPath.section].footer
default:
arrangement = nil
assertionFailure("unknown supplementary view kind \(kind)")
}
arrangement?.makeViews(in: view)
return view
}
}
| 0a6e09de74b08dd05dd71e2f1a8e8861 | 47.354839 | 177 | 0.753836 | false | false | false | false |
OmarBizreh/IOSTrainingApp | refs/heads/master | IOSTrainingApp/ViewController.swift | mit | 1 | //
// ViewController.swift
// IOSTrainingApp
//
// Created by Omar Bizreh on 2/6/16.
// Copyright © 2016 Omar Bizreh. All rights reserved.
//
import UIKit
import KYDrawerController
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var lblTitle: UILabel!
@IBOutlet var tableView: UITableView!
@IBOutlet var viewHeader: UIView!
private let cellIdentifier = "reuseCell"
private let headersArray: [String] = ["Controls", "General"]
private var drawerView: KYDrawerController?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//self.viewHeader.backgroundColor = UIColor(patternImage: UIImage(named: "header_image.jpg")!)
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier)
self.drawerView = (UIApplication.sharedApplication().windows[0].rootViewController as! KYDrawerController)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 3
}else{
return 2
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier)
if indexPath.section == 0 {
cell?.textLabel?.text = "Hello World"
}
else{
cell?.textLabel?.text = "Hello World"
}
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.drawerView?.setDrawerState(.Closed, animated: true)
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.headersArray[section]
}
}
| b30b20fb19b49c1be94eec77530c0e63 | 31.470588 | 114 | 0.667572 | false | false | false | false |
linebounce/HLT-Challenge | refs/heads/master | HLTChallenge/FlickrPhotoCommentCollection.swift | mit | 1 | //
// FlickrPhotoCommentCollection.swift
// HLTChallenge
//
// Created by Key Hoffman on 10/25/16.
// Copyright © 2016 Key Hoffman. All rights reserved.
//
import Foundation
// MARK: - FlickrPhotoCommentCollection
struct FlickrPhotoCommentCollection: FlickrCollection {
let elements: Set<FlickrPhotoComment>
}
// MARK: - EmptyInitializable Conformance
extension FlickrPhotoCommentCollection {
init() {
elements = .empty
}
init(from array: [FlickrPhotoComment]) {
elements = Set(array)
}
}
// MARK: - FlickrCollection Conformance
extension FlickrPhotoCommentCollection {
static let urlQueryParameters = urlGeneralQueryParameters + [
FlickrConstants.Parameters.Keys.CommentCollection.method: FlickrConstants.Parameters.Values.CommentCollection.method
]
static func create(from dict: JSONDictionary) -> Result<FlickrPhotoCommentCollection> {
guard let commentsDict = dict[FlickrConstants.Response.Keys.CommentCollection.commentDictionary] >>- _JSONDictionary,
let status = dict[FlickrConstants.Response.Keys.General.status] >>- JSONString,
status == FlickrConstants.Response.Values.Status.success else { return Result(CreationError.Flickr.comment) }
guard let commentsArray = commentsDict[FlickrConstants.Response.Keys.CommentCollection.commentArray] >>- JSONArray else { return Result.init <| .empty }
return commentsArray.map(FlickrPhotoComment.create).inverted <^> FlickrPhotoCommentCollection.init
}
}
| d59927f6384ee96637f0f6275e0e64df | 35.348837 | 160 | 0.726168 | false | false | false | false |
DianQK/LearnRxSwift | refs/heads/master | LearnRxSwift/RxNetwork/ObjectMapper/UserModel.swift | mit | 1 | //
// UserModel.swift
// LearnRxSwift
//
// Created by DianQK on 16/2/22.
// Copyright © 2016年 DianQK. All rights reserved.
//
import ObjectMapper
import RxDataSources
struct UserListModel {
var users: [UserModel]!
}
struct UserModel {
var name: String!
var age: String!
}
extension UserListModel: Mappable {
init?(_ map: Map) { }
mutating func mapping(map: Map) {
users <- map["users"]
}
}
extension UserListModel: Hashable {
var hashValue: Int {
return users.description.hashValue
}
}
extension UserListModel: IdentifiableType {
var identity: Int {
return hashValue
}
}
func ==(lhs: UserListModel, rhs: UserListModel) -> Bool {
return lhs.hashValue == rhs.hashValue
}
extension UserModel: Mappable {
init?(_ map: Map) { }
mutating func mapping(map: Map) {
name <- map["name"]
age <- map["age"]
}
}
extension UserModel: Hashable {
var hashValue: Int {
return name.hashValue
}
}
extension UserModel: IdentifiableType {
var identity: Int {
return hashValue
}
}
func ==(lhs: UserModel, rhs: UserModel) -> Bool {
return lhs.name == rhs.name
} | 54a14b705a8a1b007bd530c4814c371e | 16.602941 | 57 | 0.62291 | false | false | false | false |
google/JacquardSDKiOS | refs/heads/main | Example/JacquardSDK/IMUDataCollectionView/IMUSessionDetailsViewController.swift | apache-2.0 | 1 | // Copyright 2021 Google 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 JacquardSDK
import UIKit
final class IMUSessionDetailsViewController: UIViewController {
struct IMUSampleCellModel: Hashable {
let sample: IMUSample
static func == (lhs: IMUSampleCellModel, rhs: IMUSampleCellModel) -> Bool {
return lhs.sample.timestamp == rhs.sample.timestamp
}
func hash(into hasher: inout Hasher) {
sample.timestamp.hash(into: &hasher)
}
}
// Session to show the samples.
var selectedSession: IMUSessionData!
@IBOutlet private weak var sessionName: UILabel!
@IBOutlet private weak var samplesTableView: UITableView!
private var samplesDiffableDataSource: UITableViewDiffableDataSource<Int, IMUSampleCellModel>?
private lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.timeStyle = DateFormatter.Style.medium
formatter.dateStyle = DateFormatter.Style.medium
formatter.timeZone = .current
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
if let timestamp = TimeInterval(selectedSession.metadata.sessionID) {
let date = Date(timeIntervalSinceReferenceDate: timestamp)
sessionName.text = dateFormatter.string(from: date)
} else {
sessionName.text = selectedSession.metadata.sessionID
}
configureSessionTableView()
updateDataSource()
}
private func configureSessionTableView() {
let nib = UINib(nibName: IMUSessionDetailTableViewCell.reuseIdentifier, bundle: nil)
samplesTableView.register(
nib, forCellReuseIdentifier: IMUSessionDetailTableViewCell.reuseIdentifier)
samplesTableView.dataSource = samplesDiffableDataSource
samplesTableView.delegate = self
samplesTableView.rowHeight = 64.0
samplesDiffableDataSource = UITableViewDiffableDataSource<Int, IMUSampleCellModel>(
tableView: samplesTableView,
cellProvider: { (tableView, indexPath, sampleModel) -> UITableViewCell? in
let cell = tableView.dequeueReusableCell(
withIdentifier: IMUSessionDetailTableViewCell.reuseIdentifier,
for: indexPath
)
guard
let sampleCell = cell as? IMUSessionDetailTableViewCell
else {
assertionFailure("Cell can not be casted to IMUSessionTableViewCell.")
return cell
}
sampleCell.configureCell(model: sampleModel.sample)
return sampleCell
})
}
func updateDataSource() {
let samples = selectedSession.samples.map { IMUSampleCellModel(sample: $0) }
var snapshot = NSDiffableDataSourceSnapshot<Int, IMUSampleCellModel>()
snapshot.appendSections([0])
snapshot.appendItems(samples, toSection: 0)
self.samplesDiffableDataSource?.apply(snapshot)
}
}
extension IMUSessionDetailsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = JacquardSectionHeader(
frame: CGRect(x: 0.0, y: 0.0, width: samplesTableView.frame.width, height: 40.0))
headerView.title = "DATA: (\(selectedSession.samples.count) samples)"
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40.0
}
}
| ba100040a6499cfd6ec86f70537dd300 | 34.277778 | 96 | 0.734383 | false | false | false | false |
luizlopezm/ios-Luis-Trucking | refs/heads/master | Pods/SwiftForms/SwiftForms/cells/FormSliderCell.swift | mit | 1 | //
// FormSliderCell.swift
// SwiftFormsApplication
//
// Created by Miguel Angel Ortuno Ortuno on 23/5/15.
// Copyright (c) 2015 Miguel Angel Ortuno Ortuno. All rights reserved.
//
public class FormSliderCell: FormTitleCell {
// MARK: Cell views
public let sliderView = UISlider()
// MARK: FormBaseCell
public override func configure() {
super.configure()
selectionStyle = .None
titleLabel.translatesAutoresizingMaskIntoConstraints = false
sliderView.translatesAutoresizingMaskIntoConstraints = false
titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
contentView.addSubview(titleLabel)
contentView.addSubview(sliderView)
titleLabel.setContentHuggingPriority(500, forAxis: .Horizontal)
contentView.addConstraint(NSLayoutConstraint(item: sliderView, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
sliderView.addTarget(self, action: #selector(FormSliderCell.valueChanged(_:)), forControlEvents: .ValueChanged)
}
public override func update() {
super.update()
if let maximumValue = rowDescriptor.configuration[FormRowDescriptor.Configuration.MaximumValue] as? Float {
sliderView.maximumValue = maximumValue
}
if let minimumValue = rowDescriptor.configuration[FormRowDescriptor.Configuration.MinimumValue] as? Float {
sliderView.minimumValue = minimumValue
}
if let continuous = rowDescriptor.configuration[FormRowDescriptor.Configuration.Continuous] as? Bool {
sliderView.continuous = continuous
}
titleLabel.text = rowDescriptor.title
if rowDescriptor.value != nil {
sliderView.value = rowDescriptor.value as! Float
}
else {
sliderView.value = sliderView.minimumValue
rowDescriptor.value = sliderView.minimumValue
}
}
public override func constraintsViews() -> [String : UIView] {
return ["titleLabel" : titleLabel, "sliderView" : sliderView]
}
public override func defaultVisualConstraints() -> [String] {
var constraints: [String] = []
constraints.append("V:|[titleLabel]|")
constraints.append("H:|-16-[titleLabel]-16-[sliderView]-16-|")
return constraints
}
// MARK: Actions
internal func valueChanged(_: UISlider) {
rowDescriptor.value = sliderView.value
}
}
| d3a0714def13ff8e8725be177dd4a901 | 32.074074 | 185 | 0.640538 | false | true | false | false |
mikeckennedy/DevWeek2015 | refs/heads/master | swift/ttt/ttt/ViewController.swift | cc0-1.0 | 1 | //
// ViewController.swift
// ttt
//
// Created by Michael Kennedy on 3/25/15.
// Copyright (c) 2015 DevelopMentor. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var button11: UIButton!
@IBOutlet weak var button12: UIButton!
@IBOutlet weak var button13: UIButton!
@IBOutlet weak var button21: UIButton!
@IBOutlet weak var button22: UIButton!
@IBOutlet weak var button23: UIButton!
@IBOutlet weak var button31: UIButton!
@IBOutlet weak var button32: UIButton!
@IBOutlet weak var button33: UIButton!
@IBOutlet weak var labelOutcome: UILabel!
var buttons : [[UIButton!]] = []
var game = Game()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
labelOutcome.text = ""
// button11.removeConstraints(button11.constraints())
// button11.setTranslatesAutoresizingMaskIntoConstraints(true)
//
// button11.frame = CGRect(x: 0, y: 0, width: 200, height: 200
//)
var row1 = [button11, button12, button13]
var row2 = [button21, button22, button23]
var row3 = [button31, button32, button33]
buttons.append(row1)
buttons.append(row2)
buttons.append(row3)
syncGameToButtons()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonPlayClicked(sender: UIButton) {
if game.hasWinner {
return
}
let (r, c) = getIndexForButton(sender)
var currentPlayer = game.currentPlayerName
if game.play(r, col: c) {
game.swapPlayers()
}
syncGameToButtons()
if game.hasWinner {
labelOutcome.text = "We have a winner! " + currentPlayer
}
}
func getIndexForButton(btn : UIButton!) -> (Int, Int) {
for (idx_r, row) in enumerate(buttons) {
for (idx_c, b) in enumerate(row) {
if b == btn {
return (idx_r, idx_c)
}
}
}
return (-1, -1)
}
func syncGameToButtons() {
for row in buttons {
for b in row {
let (r, c) = getIndexForButton(b)
if let text = game.getCellText(r,c: c) {
b.setTitle(text, forState: .Normal)
} else {
b.setTitle("___", forState: .Normal)
}
}
}
}
}
| ec4a7ec5d9f3cbe5d61b8069c8318c46 | 24.906542 | 80 | 0.539683 | false | false | false | false |
zhixingxi/JJA_Swift | refs/heads/master | JJA_Swift/Pods/TimedSilver/Sources/UIKit/UIButton+TSTouchArea.swift | mit | 1 | //
// UIButton+TSTouchArea.swift
// TimedSilver
// Source: https://github.com/hilen/TimedSilver
//
// Created by Hilen on 9/22/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import UIKit
private var ts_touchAreaEdgeInsets: UIEdgeInsets = .zero
extension UIButton {
/// Increase your button touch area.
/// If your button frame is (0,0,40,40). Then call button.ts_touchInsets = UIEdgeInsetsMake(-30, -30, -30, -30), it will Increase the touch area
public var ts_touchInsets: UIEdgeInsets {
get {
if let value = objc_getAssociatedObject(self, &ts_touchAreaEdgeInsets) as? NSValue {
var edgeInsets: UIEdgeInsets = .zero
value.getValue(&edgeInsets)
return edgeInsets
}
else {
return .zero
}
}
set(newValue) {
var newValueCopy = newValue
let objCType = NSValue(uiEdgeInsets: .zero).objCType
let value = NSValue(&newValueCopy, withObjCType: objCType)
objc_setAssociatedObject(self, &ts_touchAreaEdgeInsets, value, .OBJC_ASSOCIATION_RETAIN)
}
}
open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if UIEdgeInsetsEqualToEdgeInsets(self.ts_touchInsets, .zero) || !self.isEnabled || self.isHidden {
return super.point(inside: point, with: event)
}
let relativeFrame = self.bounds
let hitFrame = UIEdgeInsetsInsetRect(relativeFrame, self.ts_touchInsets)
return hitFrame.contains(point)
}
}
| b199ebbe1b8ea6b102fbf0953a0cc774 | 32.666667 | 148 | 0.619431 | false | false | false | false |
ZhaoBingDong/EasySwifty | refs/heads/master | EasySwifty/Classes/EasyDataHelper.swift | apache-2.0 | 1 | //
// EasyDataHelper.swift
// MiaoTuProject
//
// Created by dzb on 2019/7/4.
// Copyright © 2019 大兵布莱恩特. All rights reserved.
//
import Foundation
//import SwiftyJSON
//
//protocol MTJSONCodable : class {
// init(fromJson json: JSON!)
//}
//
//class EasyDataHelper<T :MTJSONCodable> {
// let num : Int = 10
// typealias EasyDataResponse = (data : [T],indexPaths : [IndexPath]?, noData : Bool)
//
// class func loadMoreData(_ jsonData : [JSON], startPage : Int,currentPage : Int, source : [T]) -> EasyDataResponse {
// var temp : [T] = [T]()
// var dataArray = [T](source)
// var location = source.count
// let isRefresh : Bool = (startPage == currentPage)
// var indexPaths : [IndexPath]? = !isRefresh ? [IndexPath]() : nil
// for i in 0..<jsonData.count {
// let dict = jsonData[i]
// let object = T(fromJson: dict)
// temp.append(object)
// if (!isRefresh) {
// let indexPath = IndexPath(row: location,section: 0)
// indexPaths?.append(indexPath)
// location += 1
// }
// }
// if isRefresh {
// dataArray = temp
// } else {
// dataArray.append(contentsOf: temp)
// }
// let nodata : Bool = (temp.count < 10)
// return (dataArray,indexPaths,nodata)
// }
//
// static func loadMoreData(_ jsonData : [JSON], page : Int, source : [T]) -> EasyDataResponse {
// return loadMoreData(jsonData, startPage: 1, currentPage: page, source: source)
// }
//
//}
//
| 8bdc3a13c6a270f1cfcfa3d90e8204ba | 31.14 | 122 | 0.54636 | false | false | false | false |
KBryan/SwiftFoundation | refs/heads/develop | Source/FileManager.swift | mit | 1 | //
// FileManager.swift
// SwiftFoundation
//
// Created by Alsey Coleman Miller on 6/29/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
public typealias FileSystemAttributes = statfs
public typealias FileAttributes = stat
/// Class for interacting with the file system.
public final class FileManager {
// MARK: - Determining Access to Files
/// Determines whether a file descriptor exists at the specified path. Can be regular file, directory, socket, etc.
public static func itemExists(atPath path: String) -> Bool {
return (stat(path, nil) == 0)
}
/// Determines whether a file exists at the specified path.
public static func fileExists(atPath path: String) -> Bool {
var inodeInfo = stat()
guard stat(path, &inodeInfo) == 0
else { return false }
guard (inodeInfo.st_mode & S_IFMT) == S_IFREG
else { return false }
return true
}
/// Determines whether a directory exists at the specified path.
public static func directoryExists(atPath path: String) -> Bool {
var inodeInfo = stat()
guard stat(path, &inodeInfo) == 0
else { return false }
guard (inodeInfo.st_mode & S_IFMT) == S_IFDIR
else { return false }
return true
}
// MARK: - Managing the Current Directory
/// Attempts to change the current directory
public static func changeCurrentDirectory(newCurrentDirectory: String) throws {
guard chdir(newCurrentDirectory) == 0 else {
throw POSIXError.fromErrorNumber!
}
}
/// Gets the current directory
public static var currentDirectory: String {
let stringBufferSize = Int(PATH_MAX)
let path = UnsafeMutablePointer<CChar>.alloc(stringBufferSize)
defer { path.dealloc(stringBufferSize) }
getcwd(path, stringBufferSize - 1)
return String.fromCString(path)!
}
// MARK: - Creating and Deleting Items
public static func createFile(atPath path: String, contents: Data? = nil, attributes: FileAttributes = FileAttributes()) throws {
}
public static func createDirectory(atPath path: String, withIntermediateDirectories createIntermediates: Bool = false, attributes: FileAttributes = FileAttributes()) throws {
if createIntermediates {
fatalError("Not Implemented")
}
guard mkdir(path, attributes.st_mode) == 0 else {
throw POSIXError.fromErrorNumber!
}
}
public static func removeItem(atPath path: String) throws {
guard remove(path) == 0 else {
throw POSIXError.fromErrorNumber!
}
}
// MARK: - Creating Symbolic and Hard Links
public static func createSymbolicLink(atPath path: String, withDestinationPath destinationPath: String) throws {
}
public static func linkItemAtPath(path: String, toPath destinationPath: String) throws {
}
public static func destinationOfSymbolicLink(atPath path: String) throws -> String {
fatalError()
}
// MARK: - Moving and Copying Items
public static func copyItem(atPath sourcePath: String, toPath destinationPath: String) throws {
}
public static func moveItem(atPath sourcePath: String, toPath destinationPath: String) throws {
}
// MARK: - Getting and Setting Attributes
public static func attributesOfItem(atPath path: String) throws -> FileAttributes {
return try FileAttributes(path: path)
}
public static func setAttributes(attributes: FileAttributes, ofItemAtPath path: String) throws {
// let originalAttributes = try self.attributesOfItem(atPath: path)
}
public static func attributesOfFileSystem(forPath path: String) throws -> FileSystemAttributes {
return try FileSystemAttributes(path: path)
}
// MARK: - Getting and Comparing File Contents
public static func contents(atPath path: String) -> Data? {
guard self.fileExists(atPath: path)
else { return nil }
return []
}
}
| ec62a48ed1c7515508e763dae1ac4898 | 27 | 178 | 0.599647 | false | false | false | false |
stripe/stripe-ios | refs/heads/master | StripeIdentity/StripeIdentity/Source/NativeComponents/Views/Selfie/SelfieCaptureView.swift | mit | 1 | //
// SelfieCaptureView.swift
// StripeIdentity
//
// Created by Mel Ludowise on 4/27/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
@_spi(STP) import StripeUICore
import UIKit
/// Displays either an instructional camera scanning view or an error message
final class SelfieCaptureView: UIView {
struct Styling {
// Used for errorView and vertical insets of scanningView
static let contentInsets = IdentityFlowView.Style.defaultContentViewInsets
}
enum ViewModel {
case scan(SelfieScanningView.ViewModel)
case error(ErrorView.ViewModel)
}
private let scanningView = SelfieScanningView()
private let errorView = ErrorView()
private lazy var stackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.alignment = .center
stackView.distribution = .fill
return stackView
}()
// MARK: - Init
init() {
super.init(frame: .zero)
installViews()
installConstraints()
}
required init?(
coder: NSCoder
) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Configure
func configure(with viewModel: ViewModel, analyticsClient: IdentityAnalyticsClient?) {
switch viewModel {
case .scan(let scanningViewModel):
scanningView.configure(
with: scanningViewModel,
analyticsClient: analyticsClient
)
scanningView.isHidden = false
errorView.isHidden = true
case .error(let errorViewModel):
errorView.configure(with: errorViewModel)
scanningView.isHidden = true
errorView.isHidden = false
}
}
}
// MARK: - Private Helpers
extension SelfieCaptureView {
fileprivate func installViews() {
// Add top/bottom content insets to stackView
addAndPinSubview(
stackView,
insets: .init(
top: Styling.contentInsets.top,
leading: 0,
bottom: Styling.contentInsets.bottom,
trailing: 0
)
)
stackView.addArrangedSubview(scanningView)
stackView.addArrangedSubview(errorView)
}
fileprivate func installConstraints() {
// Add the horizontal contentInset to errorView (scanningView has horizontal insets built in already)
NSLayoutConstraint.activate([
widthAnchor.constraint(
equalTo: errorView.widthAnchor,
constant: Styling.contentInsets.leading + Styling.contentInsets.trailing
),
scanningView.widthAnchor.constraint(equalTo: widthAnchor),
])
}
}
| acca3ada13a9a490ef1892049d46b871 | 27.183673 | 109 | 0.623099 | false | false | false | false |
hirohisa/RxSwift | refs/heads/master | RxExample/RxExample/Examples/WikipediaImageSearch/Views/WikipediaSearchCell.swift | mit | 3 | //
// WikipediaSearchCell.swift
// Example
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
public class WikipediaSearchCell: UITableViewCell {
@IBOutlet var titleOutlet: UILabel!
@IBOutlet var URLOutlet: UILabel!
@IBOutlet var imagesOutlet: UICollectionView!
var disposeBag: DisposeBag!
let imageService = DefaultImageService.sharedImageService
public override func awakeFromNib() {
super.awakeFromNib()
self.imagesOutlet.registerNib(UINib(nibName: "WikipediaImageCell", bundle: nil), forCellWithReuseIdentifier: "ImageCell")
}
var viewModel: SearchResultViewModel! {
didSet {
let $ = viewModel.$
let disposeBag = DisposeBag()
self.titleOutlet.rx_subscribeTextTo(viewModel?.title ?? just("")) >- disposeBag.addDisposable
self.URLOutlet.text = viewModel.searchResult.URL.absoluteString ?? ""
viewModel.imageURLs
>- self.imagesOutlet.rx_subscribeItemsToWithCellIdentifier("ImageCell") { [unowned self] (_, URL, cell: CollectionViewImageCell) in
let loadingPlaceholder: UIImage? = nil
cell.image = self.imageService.imageFromURL(URL)
>- map { $0 as UIImage? }
>- catch(nil)
>- startWith(loadingPlaceholder)
}
>- disposeBag.addDisposable
self.disposeBag = disposeBag
}
}
public override func prepareForReuse() {
super.prepareForReuse()
self.disposeBag = nil
}
deinit {
}
} | a6b6f8b76cbb16c5cbd06c590a3cf8bb | 28.03125 | 147 | 0.595046 | false | false | false | false |
open-swift/S4 | refs/heads/master | Tests/S4Tests/XcTest.swift | mit | 2 | import Foundation
import XCTest
extension XCTestCase {
class func series(tasks asyncTasks: [((Void) -> Void) -> Void], completion: @escaping (Void) -> Void) {
var index = 0
func _series(_ current: (((Void) -> Void) -> Void)) {
current {
index += 1
index < asyncTasks.count ? _series(asyncTasks[index]) : completion()
}
}
_series(asyncTasks[index])
}
#if swift(>=3.0)
func waitForExpectations(delay sec: TimeInterval = 1, withDescription: String, callback: ((Void) -> Void) -> Void) {
let expectation = self.expectation(description: withDescription)
let done = {
expectation.fulfill()
}
callback(done)
self.waitForExpectations(timeout: sec) {
XCTAssertNil($0, "Timeout of \(Int(sec)) exceeded")
}
}
#else
func waitForExpectations(delay sec: NSTimeInterval = 1, withDescription: String, callback: ((Void) -> Void) -> Void) {
let expectation = self.expectationWithDescription(withDescription)
let done = {
expectation.fulfill()
}
callback(done)
waitForExpectationsWithTimeout(sec) {
XCTAssertNil($0, "Timeout of \(Int(sec)) exceeded")
}
}
#endif
}
| 9a975bf4ffd5a065f57f448a14fddf2e | 28.888889 | 122 | 0.560595 | false | false | false | false |
SoCM/iOS-FastTrack-2014-2015 | refs/heads/master | 04-App Architecture/Swift 3/4-4-Presentation/PresentingDemo4/PresentingDemo/ViewController.swift | mit | 2 | //
// ViewController.swift
// PresentingDemo
//
// Created by Nicholas Outram on 14/01/2016.
// Copyright © 2016 Plymouth University. All rights reserved.
//
import UIKit
class ViewController: UIViewController, ModalViewController1Protocol {
@IBOutlet weak var resultLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? ModalViewController1 {
vc.delegate = self
switch (segue.identifier) {
case "DEMO1"?:
vc.titleText = "DEMO 1"
case "DEMO2"?:
vc.titleText = "DEMO 2"
default:
break
} //end switch
} //end if
}
@IBAction func doDemo2(_ sender: AnyObject) {
self.performSegue(withIdentifier: "DEMO2", sender: self)
}
@IBAction func doDemo3(_ sender: AnyObject) {
let sb = UIStoryboard(name: "ModalStoryboard", bundle: nil)
if let vc = sb.instantiateViewController(withIdentifier: "DEMO3") as? ModalViewController1{
vc.delegate = self
vc.titleText = "DEMO 3"
self.present(vc, animated: true, completion: { })
}
}
@IBAction func doDemo4(_ sender: AnyObject) {
let vc = ModalViewController1(nibName: "Demo4", bundle: nil)
vc.delegate = self
vc.titleText = "DEMO 4"
self.present(vc, animated: true, completion: { })
}
//Call back
func dismissWithStringData(_ str: String) {
self.dismiss(animated: true) {
self.resultLabel.text = str
}
}
}
| f704c169f015a727136ef601c08c075c | 25.727273 | 99 | 0.562196 | false | false | false | false |
tavon321/GluberLabConceptTest | refs/heads/master | GluberLabConceptTest/GluberLabConceptTest/Layer+Customization.swift | mit | 1 | //
// Layer+Customization.swift
// GluberLabConceptTest
//
// Created by Gustavo Mario Londoño Correa on 4/20/17.
// Copyright © 2017 Gustavo Mario Londoño Correa. All rights reserved.
//
import Foundation
import UIKit
extension UIView {
// MARK: - Corners
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
// MARK: - Rounded
@IBInspectable var rounded: Bool {
get {
return layer.masksToBounds
}
set {
if newValue {
layer.cornerRadius = layer.frame.midX / 10
layer.masksToBounds = true
}
}
}
// MARK: - Shadows
@IBInspectable var shadowRadius: Double {
get {
return Double(self.layer.shadowRadius)
}
set {
self.layer.shadowRadius = CGFloat(newValue)
}
}
// The opacity of the shadow. Defaults to 0. Specifying a value outside the [0,1] range will give undefined results. Animatable.
@IBInspectable var shadowOpacity: Float {
get {
return self.layer.shadowOpacity
}
set {
self.layer.shadowOpacity = newValue
}
}
// The shadow offset. Defaults to (0, -3). Animatable.
@IBInspectable var shadowOffset: CGSize {
get {
return self.layer.shadowOffset
}
set {
self.layer.shadowOffset = newValue
}
}
// The color of the shadow. Defaults to opaque black. Colors created from patterns are currently NOT supported. Animatable.
@IBInspectable var shadowColor: UIColor? {
get {
return UIColor(cgColor: self.layer.shadowColor ?? UIColor.clear.cgColor)
}
set {
self.layer.shadowColor = newValue?.cgColor
}
}
// Off - Will show shadow | On - Won't show shadow.
@IBInspectable var masksToBounds: Bool {
get {
return self.layer.masksToBounds
}
set {
self.layer.masksToBounds = newValue
}
}
}
| bd381804c7ccacdbed7bea3a42f396db | 25.831325 | 132 | 0.563089 | false | false | false | false |
danielcwj16/ConnectedAlarmApp | refs/heads/master | Pods/SwiftAddressBook/Pod/Classes/SwiftAddressBookWrapper.swift | mit | 2 | //SwiftAddressBook - A strong-typed Swift Wrapper for ABAddressBook
//Copyright (C) 2014 Socialbit GmbH
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
import UIKit
import AddressBook
@available(iOS, deprecated: 9.0)
//MARK: global address book variable (automatically lazy)
public let swiftAddressBook : SwiftAddressBook! = SwiftAddressBook()
public var accessError : CFError?
//MARK: Address Book
open class SwiftAddressBook {
open var internalAddressBook : ABAddressBook!
//fileprivate lazy var addressBookObserver = SwiftAddressBookObserver()
public init?() {
var err : Unmanaged<CFError>? = nil
let abUnmanaged : Unmanaged<ABAddressBook>? = ABAddressBookCreateWithOptions(nil, &err)
//assign error or internalAddressBook, according to outcome
if err == nil {
internalAddressBook = abUnmanaged?.takeRetainedValue()
}
else {
accessError = err?.takeRetainedValue()
return nil
}
}
open class func authorizationStatus() -> ABAuthorizationStatus {
return ABAddressBookGetAuthorizationStatus()
}
open class func requestAccessWithCompletion( _ completion : @escaping (Bool, CFError?) -> Void ) {
ABAddressBookRequestAccessWithCompletion(nil, completion)
}
open func hasUnsavedChanges() -> Bool {
return ABAddressBookHasUnsavedChanges(internalAddressBook)
}
open func save() -> CFError? {
return errorIfNoSuccess { ABAddressBookSave(self.internalAddressBook, $0)}
}
open func revert() {
ABAddressBookRevert(internalAddressBook)
}
open func addRecord(_ record : SwiftAddressBookRecord) -> CFError? {
return errorIfNoSuccess { ABAddressBookAddRecord(self.internalAddressBook, record.internalRecord, $0) }
}
open func removeRecord(_ record : SwiftAddressBookRecord) -> CFError? {
return errorIfNoSuccess { ABAddressBookRemoveRecord(self.internalAddressBook, record.internalRecord, $0) }
}
//MARK: person records
open var personCount : Int {
return ABAddressBookGetPersonCount(internalAddressBook)
}
open func personWithRecordId(_ recordId : Int32) -> SwiftAddressBookPerson? {
return SwiftAddressBookPerson(record: ABAddressBookGetPersonWithRecordID(internalAddressBook, recordId)?.takeUnretainedValue())
}
open var allPeople : [SwiftAddressBookPerson]? {
return convertRecordsToPersons(ABAddressBookCopyArrayOfAllPeople(internalAddressBook).takeRetainedValue())
}
// open func registerExternalChangeCallback(_ callback: @escaping () -> Void) {
// addressBookObserver.startObserveChanges { (addressBook) -> Void in
// callback()
// }
// }
//
// open func unregisterExternalChangeCallback(_ callback: () -> Void) {
// addressBookObserver.stopObserveChanges()
// callback()
// }
open var allPeopleExcludingLinkedContacts : [SwiftAddressBookPerson]? {
if let all = allPeople {
let filtered : NSMutableArray = NSMutableArray(array: all)
for person in all {
if !(NSArray(array: filtered) as! [SwiftAddressBookPerson]).contains(where: {
(p : SwiftAddressBookPerson) -> Bool in
return p.recordID == person.recordID
}) {
//already filtered out this contact
continue
}
//throw out duplicates
let allFiltered : [SwiftAddressBookPerson] = NSArray(array: filtered) as! [SwiftAddressBookPerson]
for possibleDuplicate in allFiltered {
if let linked = person.allLinkedPeople {
if possibleDuplicate.recordID != person.recordID
&& linked.contains(where: {
(p : SwiftAddressBookPerson) -> Bool in
return p.recordID == possibleDuplicate.recordID
}) {
(filtered as NSMutableArray).remove(possibleDuplicate)
}
}
}
}
return NSArray(array: filtered) as? [SwiftAddressBookPerson]
}
return nil
}
open func allPeopleInSource(_ source : SwiftAddressBookSource) -> [SwiftAddressBookPerson]? {
return convertRecordsToPersons(ABAddressBookCopyArrayOfAllPeopleInSource(internalAddressBook, source.internalRecord).takeRetainedValue())
}
open func allPeopleInSourceWithSortOrdering(_ source : SwiftAddressBookSource, ordering : SwiftAddressBookOrdering) -> [SwiftAddressBookPerson]? {
return convertRecordsToPersons(ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(internalAddressBook, source.internalRecord, ordering.abPersonSortOrderingValue).takeRetainedValue())
}
open func peopleWithName(_ name : String) -> [SwiftAddressBookPerson]? {
return convertRecordsToPersons(ABAddressBookCopyPeopleWithName(internalAddressBook, (name as CFString)).takeRetainedValue())
}
//MARK: group records
open func groupWithRecordId(_ recordId : Int32) -> SwiftAddressBookGroup? {
return SwiftAddressBookGroup(record: ABAddressBookGetGroupWithRecordID(internalAddressBook, recordId)?.takeUnretainedValue())
}
open var groupCount : Int {
return ABAddressBookGetGroupCount(internalAddressBook)
}
open var arrayOfAllGroups : [SwiftAddressBookGroup]? {
return convertRecordsToGroups(ABAddressBookCopyArrayOfAllGroups(internalAddressBook).takeRetainedValue())
}
open func allGroupsInSource(_ source : SwiftAddressBookSource) -> [SwiftAddressBookGroup]? {
return convertRecordsToGroups(ABAddressBookCopyArrayOfAllGroupsInSource(internalAddressBook, source.internalRecord).takeRetainedValue())
}
//MARK: sources
open var defaultSource : SwiftAddressBookSource? {
return SwiftAddressBookSource(record: ABAddressBookCopyDefaultSource(internalAddressBook)?.takeRetainedValue())
}
open func sourceWithRecordId(_ sourceId : Int32) -> SwiftAddressBookSource? {
return SwiftAddressBookSource(record: ABAddressBookGetSourceWithRecordID(internalAddressBook, sourceId)?.takeUnretainedValue())
}
open var allSources : [SwiftAddressBookSource]? {
return convertRecordsToSources(ABAddressBookCopyArrayOfAllSources(internalAddressBook).takeRetainedValue())
}
}
| 9393ca8fb30007d13d7366614a935a4d | 35.808989 | 197 | 0.7384 | false | false | false | false |
ArnavChawla/InteliChat | refs/heads/master | Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/DocumentSnapshot.swift | mit | 1 | /**
* Copyright IBM Corporation 2018
*
* 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
/** DocumentSnapshot. */
public struct DocumentSnapshot: Decodable {
public enum Step: String {
case htmlInput = "html_input"
case htmlOutput = "html_output"
case jsonOutput = "json_output"
case jsonNormalizationsOutput = "json_normalizations_output"
case enrichmentsOutput = "enrichments_output"
case normalizationsOutput = "normalizations_output"
}
public var step: String?
public var snapshot: [String: JSON]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case step = "step"
case snapshot = "snapshot"
}
}
| e0c3594e20c2880fafca6bca5818ea8f | 30.731707 | 82 | 0.700231 | false | false | false | false |
choofie/MusicTinder | refs/heads/master | MusicTinder/Classes/BusinessLogic/Services/Chart/ChartService.swift | mit | 1 | //
// ChartService.swift
// MusicTinder
//
// Created by Mate Lorincz on 05/11/16.
// Copyright © 2016 MateLorincz. All rights reserved.
//
import Foundation
protocol GetTopArtistDelegate : class {
func getTopArtistsFinishedWithResult(_ result: [Artist])
func getTopArtistsFinishedWithError(_ error: String)
}
let DefaultTimeoutInterval = 20.0
class ChartService {
fileprivate weak var getTopArtistDelegate: GetTopArtistDelegate?
required init(getTopArtistDelegate : GetTopArtistDelegate) {
self.getTopArtistDelegate = getTopArtistDelegate
}
func getTopArtists() {
guard let urlString = URLProvider.topArtistsURL() else {
getTopArtistDelegate?.getTopArtistsFinishedWithError("Error with urlString")
return
}
guard let url = URL(string: urlString.appendResultFormat(.JSON)) else {
return
}
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.timeoutInterval = DefaultTimeoutInterval
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) -> Void in
if let _ = error {
self.loadGetTopArtistsCachedResponse()
}
else {
guard let data = data else {
self.loadGetTopArtistsCachedResponse()
return
}
do {
let jsonResult = try JSONSerialization.jsonObject(with: data, options:.allowFragments)
let artists = self.processResultData(jsonResult as AnyObject)
if artists.isEmpty {
self.loadGetTopArtistsCachedResponse()
}
else {
self.getTopArtistDelegate?.getTopArtistsFinishedWithResult(self.processResultData(jsonResult as AnyObject))
}
}
catch _ as NSError {
self.loadGetTopArtistsCachedResponse()
}
}
}
task.resume()
}
}
private extension ChartService {
func loadGetTopArtistsCachedResponse() {
if let path = Bundle.main.path(forResource: "topArtists", ofType: "json") {
do {
let jsonData = try Data(contentsOf: URL(fileURLWithPath: path), options: NSData.ReadingOptions.mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: jsonData, options:.allowFragments)
getTopArtistDelegate?.getTopArtistsFinishedWithResult(processResultData(jsonResult as AnyObject))
}
catch let error as NSError {
getTopArtistDelegate?.getTopArtistsFinishedWithError(error.localizedDescription)
}
}
else {
getTopArtistDelegate?.getTopArtistsFinishedWithError("Invalid filename/path")
}
}
func processResultData(_ resultData: AnyObject) -> [Artist] {
var result: [Artist] = []
if let artistsDictionary = resultData["artists"] as? [String : AnyObject] {
if let artistArray = artistsDictionary["artist"] as? [AnyObject] {
for artistData in artistArray {
if let artistData = artistData as? [String : AnyObject] {
if let name = artistData["name"] as? String, let mbid = artistData["mbid"] as? String, let images = artistData["image"] as? [[String : String]] {
if let imageURL = images[images.count - 2]["#text"], imageURL.isEmpty == false {
result.append(Artist(name: name , mbid: mbid , info: "no info", genre: "no genre", imageURL: URL(string:imageURL)!))
}
}
}
}
}
}
return result
}
}
| 5879230352a4960cc6cb078445fefbcc | 35.526786 | 169 | 0.556588 | false | false | false | false |
MadAppGang/SmartLog | refs/heads/master | Pods/CoreStore/Sources/CSDataStack.swift | mit | 2 | //
// CSDataStack.swift
// CoreStore
//
// Copyright © 2016 John Rommel Estropia
//
// 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 CoreData
// MARK: - CSDataStack
/**
The `CSDataStack` serves as the Objective-C bridging type for `DataStack`.
- SeeAlso: `DataStack`
*/
@objc
public final class CSDataStack: NSObject, CoreStoreObjectiveCType {
/**
Initializes a `CSDataStack` with default settings. CoreStore searches for <CFBundleName>.xcdatamodeld from the main `NSBundle` and loads an `NSManagedObjectModel` from it. An assertion is raised if the model could not be found.
*/
@objc
public convenience override init() {
self.init(DataStack())
}
/**
Initializes a `CSDataStack` from the model with the specified `modelName` in the specified `bundle`.
- parameter xcodeModelName: the name of the (.xcdatamodeld) model file. If not specified, the application name (CFBundleName) will be used if it exists, or "CoreData" if it the bundle name was not set.
- parameter bundle: an optional bundle to load models from. If not specified, the main bundle will be used.
- parameter versionChain: the version strings that indicate the sequence of model versions to be used as the order for progressive migrations. If not specified, will default to a non-migrating data stack.
*/
@objc
public convenience init(xcodeModelName: XcodeDataModelFileName?, bundle: Bundle?, versionChain: [String]?) {
self.init(
DataStack(
xcodeModelName: xcodeModelName ?? DataStack.applicationName,
bundle: bundle ?? Bundle.main,
migrationChain: versionChain.flatMap { MigrationChain($0) } ?? nil
)
)
}
/**
Returns the stack's model version. The version string is the same as the name of the version-specific .xcdatamodeld file.
*/
@objc
public var modelVersion: String {
return self.bridgeToSwift.modelVersion
}
/**
Returns the entity name-to-class type mapping from the `CSDataStack`'s model.
*/
@objc
public func entityTypesByNameForType(_ type: NSManagedObject.Type) -> [EntityName: NSManagedObject.Type] {
return self.bridgeToSwift.entityTypesByName(for: type)
}
/**
Returns the `NSEntityDescription` for the specified `NSManagedObject` subclass from stack's model.
*/
@objc
public func entityDescriptionForClass(_ type: NSManagedObject.Type) -> NSEntityDescription? {
return self.bridgeToSwift.entityDescription(for: type)
}
/**
Creates an `CSInMemoryStore` with default parameters and adds it to the stack. This method blocks until completion.
```
CSSQLiteStore *storage = [dataStack addInMemoryStorageAndWaitAndReturnError:&error];
```
- parameter error: the `NSError` pointer that indicates the reason in case of an failure
- returns: the `CSInMemoryStore` added to the stack
*/
@objc
@discardableResult
public func addInMemoryStorageAndWaitAndReturnError(_ error: NSErrorPointer) -> CSInMemoryStore? {
return bridge(error) {
try self.bridgeToSwift.addStorageAndWait(InMemoryStore())
}
}
/**
Creates an `CSSQLiteStore` with default parameters and adds it to the stack. This method blocks until completion.
```
CSSQLiteStore *storage = [dataStack addSQLiteStorageAndWaitAndReturnError:&error];
```
- parameter error: the `NSError` pointer that indicates the reason in case of an failure
- returns: the `CSSQLiteStore` added to the stack
*/
@objc
@discardableResult
public func addSQLiteStorageAndWaitAndReturnError(_ error: NSErrorPointer) -> CSSQLiteStore? {
return bridge(error) {
try self.bridgeToSwift.addStorageAndWait(SQLiteStore())
}
}
/**
Adds a `CSInMemoryStore` to the stack and blocks until completion.
```
NSError *error;
CSInMemoryStore *storage = [dataStack
addStorageAndWait: [[CSInMemoryStore alloc] initWithConfiguration: @"Config1"]
error: &error];
```
- parameter storage: the `CSInMemoryStore`
- parameter error: the `NSError` pointer that indicates the reason in case of an failure
- returns: the `CSInMemoryStore` added to the stack
*/
@objc
@discardableResult
public func addInMemoryStorageAndWait(_ storage: CSInMemoryStore, error: NSErrorPointer) -> CSInMemoryStore? {
return bridge(error) {
try self.bridgeToSwift.addStorageAndWait(storage.bridgeToSwift)
}
}
/**
Adds a `CSSQLiteStore` to the stack and blocks until completion.
```
NSError *error;
CSSQLiteStore *storage = [dataStack
addStorageAndWait: [[CSSQLiteStore alloc] initWithConfiguration: @"Config1"]
error: &error];
```
- parameter storage: the `CSSQLiteStore`
- parameter error: the `NSError` pointer that indicates the reason in case of an failure
- returns: the `CSSQLiteStore` added to the stack
*/
@objc
@discardableResult
public func addSQLiteStorageAndWait(_ storage: CSSQLiteStore, error: NSErrorPointer) -> CSSQLiteStore? {
return bridge(error) {
try self.bridgeToSwift.addStorageAndWait(storage.bridgeToSwift)
}
}
// MARK: NSObject
public override var hash: Int {
return ObjectIdentifier(self.bridgeToSwift).hashValue
}
public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? CSDataStack else {
return false
}
return self.bridgeToSwift == object.bridgeToSwift
}
public override var description: String {
return "(\(String(reflecting: type(of: self)))) \(self.bridgeToSwift.coreStoreDumpString)"
}
// MARK: CoreStoreObjectiveCType
public let bridgeToSwift: DataStack
public init(_ swiftValue: DataStack) {
self.bridgeToSwift = swiftValue
super.init()
}
// MARK: Deprecated
@available(*, deprecated, message: "Use the -[initWithXcodeModelName:bundle:versionChain:] initializer.")
@objc
public convenience init(modelName: XcodeDataModelFileName?, bundle: Bundle?, versionChain: [String]?) {
self.init(
DataStack(
xcodeModelName: modelName ?? DataStack.applicationName,
bundle: bundle ?? Bundle.main,
migrationChain: versionChain.flatMap { MigrationChain($0) } ?? nil
)
)
}
@available(*, deprecated, message: "Use the -[initWithModelName:bundle:versionChain:] initializer.")
@objc
public convenience init(model: NSManagedObjectModel, versionChain: [String]?) {
self.init(
DataStack(
model: model,
migrationChain: versionChain.flatMap { MigrationChain($0) } ?? nil
)
)
}
@available(*, deprecated, message: "Use the -[initWithModelName:bundle:versionTree:] initializer.")
@objc
public convenience init(model: NSManagedObjectModel, versionTree: [String]?) {
self.init(
DataStack(
model: model,
migrationChain: versionTree.flatMap { MigrationChain($0) } ?? nil
)
)
}
@available(*, deprecated, message: "Use the new -entityTypesByNameForType: method passing `[NSManagedObject class]` as argument.")
@objc
public var entityClassesByName: [EntityName: NSManagedObject.Type] {
return self.bridgeToSwift.entityTypesByName
}
@available(*, deprecated, message: "Use the new -entityTypesByNameForType: method passing `[NSManagedObject class]` as argument.")
@objc
public func entityClassWithName(_ name: EntityName) -> NSManagedObject.Type? {
return self.bridgeToSwift.entityTypesByName[name]
}
}
// MARK: - DataStack
extension DataStack: CoreStoreSwiftType {
// MARK: CoreStoreSwiftType
public var bridgeToObjectiveC: CSDataStack {
return CSDataStack(self)
}
}
| 70cfde90f1b12e22d8dfef24000352c3 | 33.744526 | 232 | 0.652626 | false | true | false | false |
Dwarven/ShadowsocksX-NG | refs/heads/develop | MoyaRefreshToken/Pods/RxSwift/RxSwift/Observables/Just.swift | apache-2.0 | 4 | //
// Just.swift
// RxSwift
//
// Created by Krunoslav Zaher on 8/30/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- returns: An observable sequence containing the single specified element.
*/
public static func just(_ element: E) -> Observable<E> {
return Just(element: element)
}
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- parameter scheduler: Scheduler to send the single element on.
- returns: An observable sequence containing the single specified element.
*/
public static func just(_ element: E, scheduler: ImmediateSchedulerType) -> Observable<E> {
return JustScheduled(element: element, scheduler: scheduler)
}
}
final private class JustScheduledSink<O: ObserverType>: Sink<O> {
typealias Parent = JustScheduled<O.E>
private let _parent: Parent
init(parent: Parent, observer: O, cancel: Cancelable) {
self._parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let scheduler = self._parent._scheduler
return scheduler.schedule(self._parent._element) { element in
self.forwardOn(.next(element))
return scheduler.schedule(()) { _ in
self.forwardOn(.completed)
self.dispose()
return Disposables.create()
}
}
}
}
final private class JustScheduled<Element>: Producer<Element> {
fileprivate let _scheduler: ImmediateSchedulerType
fileprivate let _element: Element
init(element: Element, scheduler: ImmediateSchedulerType) {
self._scheduler = scheduler
self._element = element
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E {
let sink = JustScheduledSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
final private class Just<Element>: Producer<Element> {
private let _element: Element
init(element: Element) {
self._element = element
}
override func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == Element {
observer.on(.next(self._element))
observer.on(.completed)
return Disposables.create()
}
}
| 704b4acbf6c3503f591f7799383b2c56 | 32.390805 | 139 | 0.662306 | false | false | false | false |
BrandonMA/SwifterUI | refs/heads/master | Floral/Pods/Kingfisher/Sources/Networking/ImageDataProcessor.swift | apache-2.0 | 9 | //
// ImageDataProcessor.swift
// Kingfisher
//
// Created by Wei Wang on 2018/10/11.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
private let sharedProcessingQueue: CallbackQueue =
.dispatch(DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process"))
// Handles image processing work on an own process queue.
class ImageDataProcessor {
let data: Data
let callbacks: [SessionDataTask.TaskCallback]
let queue: CallbackQueue
// Note: We have an optimization choice there, to reduce queue dispatch by checking callback
// queue settings in each option...
let onImageProcessed = Delegate<(Result<Image, KingfisherError>, SessionDataTask.TaskCallback), Void>()
init(data: Data, callbacks: [SessionDataTask.TaskCallback], processingQueue: CallbackQueue?) {
self.data = data
self.callbacks = callbacks
self.queue = processingQueue ?? sharedProcessingQueue
}
func process() {
queue.execute(doProcess)
}
private func doProcess() {
var processedImages = [String: Image]()
for callback in callbacks {
let processor = callback.options.processor
var image = processedImages[processor.identifier]
if image == nil {
image = processor.process(item: .data(data), options: callback.options)
processedImages[processor.identifier] = image
}
let result: Result<Image, KingfisherError>
if let image = image {
var finalImage = image
if let imageModifier = callback.options.imageModifier {
finalImage = imageModifier.modify(image)
}
if callback.options.backgroundDecode {
finalImage = finalImage.kf.decoded
}
result = .success(finalImage)
} else {
let error = KingfisherError.processorError(
reason: .processingFailed(processor: processor, item: .data(data)))
result = .failure(error)
}
onImageProcessed.call((result, callback))
}
}
}
| 98bbcddc5844d34075e116aaa7f2146b | 40.1 | 107 | 0.665754 | false | false | false | false |
Speicher210/wingu-sdk-ios-demoapp | refs/heads/master | Example/Pods/RSBarcodes_Swift/Source/RSCode93Generator.swift | apache-2.0 | 2 | //
// RSCode93Generator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/11/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
// http://www.barcodeisland.com/code93.phtml
open class RSCode93Generator: RSAbstractCodeGenerator, RSCheckDigitGenerator {
let CODE93_ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*"
let CODE93_PLACEHOLDER_STRING = "abcd";
let CODE93_CHARACTER_ENCODINGS = [
"100010100",
"101001000",
"101000100",
"101000010",
"100101000",
"100100100",
"100100010",
"101010000",
"100010010",
"100001010",
"110101000",
"110100100",
"110100010",
"110010100",
"110010010",
"110001010",
"101101000",
"101100100",
"101100010",
"100110100",
"100011010",
"101011000",
"101001100",
"101000110",
"100101100",
"100010110",
"110110100",
"110110010",
"110101100",
"110100110",
"110010110",
"110011010",
"101101100",
"101100110",
"100110110",
"100111010",
"100101110",
"111010100",
"111010010",
"111001010",
"101101110",
"101110110",
"110101110",
"100100110",
"111011010",
"111010110",
"100110010",
"101011110"
]
func encodeCharacterString(_ characterString:String) -> String {
return CODE93_CHARACTER_ENCODINGS[CODE93_ALPHABET_STRING.location(characterString)]
}
override open func isValid(_ contents: String) -> Bool {
if contents.length() > 0 && contents == contents.uppercased() {
for i in 0..<contents.length() {
if CODE93_ALPHABET_STRING.location(contents[i]) == NSNotFound {
return false
}
if CODE93_PLACEHOLDER_STRING.location(contents[i]) != NSNotFound {
return false
}
}
return true
}
return false
}
override open func initiator() -> String {
return self.encodeCharacterString("*")
}
override open func terminator() -> String {
// With the termination bar: 1
return self.encodeCharacterString("*") + "1"
}
override open func barcode(_ contents: String) -> String {
var barcode = ""
for character in contents.characters {
barcode += self.encodeCharacterString(String(character))
}
let checkDigits = self.checkDigit(contents)
for character in checkDigits.characters {
barcode += self.encodeCharacterString(String(character))
}
return barcode
}
// MARK: RSCheckDigitGenerator
open func checkDigit(_ contents: String) -> String {
// Weighted sum += value * weight
// The first character
var sum = 0
for i in 0..<contents.length() {
if let character = contents[contents.length() - i - 1] {
let characterValue = CODE93_ALPHABET_STRING.location(character)
sum += characterValue * (i % 20 + 1)
}
}
var checkDigits = ""
checkDigits += CODE93_ALPHABET_STRING[sum % 47]
// The second character
sum = 0
let newContents = contents + checkDigits
for i in 0..<newContents.length() {
if let character = newContents[newContents.length() - i - 1] {
let characterValue = CODE93_ALPHABET_STRING.location(character)
sum += characterValue * (i % 15 + 1)
}
}
checkDigits += CODE93_ALPHABET_STRING[sum % 47]
return checkDigits
}
}
| 7513479416c1dc86f001faa053ee6ba6 | 27.231884 | 91 | 0.536961 | false | false | false | false |
JaSpa/swift | refs/heads/master | stdlib/public/SDK/AppKit/NSError.swift | apache-2.0 | 8 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import AppKit
extension CocoaError.Code {
public static var textReadInapplicableDocumentType: CocoaError.Code {
return CocoaError.Code(rawValue: 65806)
}
public static var textWriteInapplicableDocumentType: CocoaError.Code {
return CocoaError.Code(rawValue: 66062)
}
public static var serviceApplicationNotFound: CocoaError.Code {
return CocoaError.Code(rawValue: 66560)
}
public static var serviceApplicationLaunchFailed: CocoaError.Code {
return CocoaError.Code(rawValue: 66561)
}
public static var serviceRequestTimedOut: CocoaError.Code {
return CocoaError.Code(rawValue: 66562)
}
public static var serviceInvalidPasteboardData: CocoaError.Code {
return CocoaError.Code(rawValue: 66563)
}
public static var serviceMalformedServiceDictionary: CocoaError.Code {
return CocoaError.Code(rawValue: 66564)
}
public static var serviceMiscellaneous: CocoaError.Code {
return CocoaError.Code(rawValue: 66800)
}
public static var sharingServiceNotConfigured: CocoaError.Code {
return CocoaError.Code(rawValue: 67072)
}
}
// Names deprecated late in Swift 3
extension CocoaError.Code {
@available(*, deprecated, renamed: "textReadInapplicableDocumentType")
public static var textReadInapplicableDocumentTypeError: CocoaError.Code {
return CocoaError.Code(rawValue: 65806)
}
@available(*, deprecated, renamed: "textWriteInapplicableDocumentType")
public static var textWriteInapplicableDocumentTypeError: CocoaError.Code {
return CocoaError.Code(rawValue: 66062)
}
@available(*, deprecated, renamed: "serviceApplicationNotFound")
public static var serviceApplicationNotFoundError: CocoaError.Code {
return CocoaError.Code(rawValue: 66560)
}
@available(*, deprecated, renamed: "serviceApplicationLaunchFailed")
public static var serviceApplicationLaunchFailedError: CocoaError.Code {
return CocoaError.Code(rawValue: 66561)
}
@available(*, deprecated, renamed: "serviceRequestTimedOut")
public static var serviceRequestTimedOutError: CocoaError.Code {
return CocoaError.Code(rawValue: 66562)
}
@available(*, deprecated, renamed: "serviceInvalidPasteboardData")
public static var serviceInvalidPasteboardDataError: CocoaError.Code {
return CocoaError.Code(rawValue: 66563)
}
@available(*, deprecated, renamed: "serviceMalformedServiceDictionary")
public static var serviceMalformedServiceDictionaryError: CocoaError.Code {
return CocoaError.Code(rawValue: 66564)
}
@available(*, deprecated, renamed: "serviceMiscellaneous")
public static var serviceMiscellaneousError: CocoaError.Code {
return CocoaError.Code(rawValue: 66800)
}
@available(*, deprecated, renamed: "sharingServiceNotConfigured")
public static var sharingServiceNotConfiguredError: CocoaError.Code {
return CocoaError.Code(rawValue: 67072)
}
}
extension CocoaError {
public static var textReadInapplicableDocumentType: CocoaError.Code {
return CocoaError.Code(rawValue: 65806)
}
public static var textWriteInapplicableDocumentType: CocoaError.Code {
return CocoaError.Code(rawValue: 66062)
}
public static var serviceApplicationNotFound: CocoaError.Code {
return CocoaError.Code(rawValue: 66560)
}
public static var serviceApplicationLaunchFailed: CocoaError.Code {
return CocoaError.Code(rawValue: 66561)
}
public static var serviceRequestTimedOut: CocoaError.Code {
return CocoaError.Code(rawValue: 66562)
}
public static var serviceInvalidPasteboardData: CocoaError.Code {
return CocoaError.Code(rawValue: 66563)
}
public static var serviceMalformedServiceDictionary: CocoaError.Code {
return CocoaError.Code(rawValue: 66564)
}
public static var serviceMiscellaneous: CocoaError.Code {
return CocoaError.Code(rawValue: 66800)
}
public static var sharingServiceNotConfigured: CocoaError.Code {
return CocoaError.Code(rawValue: 67072)
}
}
// Names deprecated late in Swift 3
extension CocoaError {
@available(*, deprecated, renamed: "textReadInapplicableDocumentType")
public static var textReadInapplicableDocumentTypeError: CocoaError.Code {
return CocoaError.Code(rawValue: 65806)
}
@available(*, deprecated, renamed: "textWriteInapplicableDocumentType")
public static var textWriteInapplicableDocumentTypeError: CocoaError.Code {
return CocoaError.Code(rawValue: 66062)
}
@available(*, deprecated, renamed: "serviceApplicationNotFound")
public static var serviceApplicationNotFoundError: CocoaError.Code {
return CocoaError.Code(rawValue: 66560)
}
@available(*, deprecated, renamed: "serviceApplicationLaunchFailed")
public static var serviceApplicationLaunchFailedError: CocoaError.Code {
return CocoaError.Code(rawValue: 66561)
}
@available(*, deprecated, renamed: "serviceRequestTimedOut")
public static var serviceRequestTimedOutError: CocoaError.Code {
return CocoaError.Code(rawValue: 66562)
}
@available(*, deprecated, renamed: "serviceInvalidPasteboardData")
public static var serviceInvalidPasteboardDataError: CocoaError.Code {
return CocoaError.Code(rawValue: 66563)
}
@available(*, deprecated, renamed: "serviceMalformedServiceDictionary")
public static var serviceMalformedServiceDictionaryError: CocoaError.Code {
return CocoaError.Code(rawValue: 66564)
}
@available(*, deprecated, renamed: "serviceMiscellaneous")
public static var serviceMiscellaneousError: CocoaError.Code {
return CocoaError.Code(rawValue: 66800)
}
@available(*, deprecated, renamed: "sharingServiceNotConfigured")
public static var sharingServiceNotConfiguredError: CocoaError.Code {
return CocoaError.Code(rawValue: 67072)
}
}
extension CocoaError {
public var isServiceError: Bool {
return code.rawValue >= 66560 && code.rawValue <= 66817
}
public var isSharingServiceError: Bool {
return code.rawValue >= 67072 && code.rawValue <= 67327
}
public var isTextReadWriteError: Bool {
return code.rawValue >= 65792 && code.rawValue <= 66303
}
}
extension CocoaError {
@available(*, deprecated, renamed: "textReadInapplicableDocumentType")
public static var TextReadInapplicableDocumentTypeError: CocoaError.Code {
return CocoaError.Code(rawValue: 65806)
}
@available(*, deprecated, renamed: "textWriteInapplicableDocumentType")
public static var TextWriteInapplicableDocumentTypeError: CocoaError.Code {
return CocoaError.Code(rawValue: 66062)
}
@available(*, deprecated, renamed: "serviceApplicationNotFound")
public static var ServiceApplicationNotFoundError: CocoaError.Code {
return CocoaError.Code(rawValue: 66560)
}
@available(*, deprecated, renamed: "serviceApplicationLaunchFailed")
public static var ServiceApplicationLaunchFailedError: CocoaError.Code {
return CocoaError.Code(rawValue: 66561)
}
@available(*, deprecated, renamed: "serviceRequestTimedOut")
public static var ServiceRequestTimedOutError: CocoaError.Code {
return CocoaError.Code(rawValue: 66562)
}
@available(*, deprecated, renamed: "serviceInvalidPasteboardData")
public static var ServiceInvalidPasteboardDataError: CocoaError.Code {
return CocoaError.Code(rawValue: 66563)
}
@available(*, deprecated, renamed: "serviceMalformedServiceDictionary")
public static var ServiceMalformedServiceDictionaryError: CocoaError.Code {
return CocoaError.Code(rawValue: 66564)
}
@available(*, deprecated, renamed: "serviceMiscellaneous")
public static var ServiceMiscellaneousError: CocoaError.Code {
return CocoaError.Code(rawValue: 66800)
}
@available(*, deprecated, renamed: "sharingServiceNotConfigured")
public static var SharingServiceNotConfiguredError: CocoaError.Code {
return CocoaError.Code(rawValue: 67072)
}
}
extension CocoaError.Code {
@available(*, deprecated, renamed: "textReadInapplicableDocumentType")
public static var TextReadInapplicableDocumentTypeError: CocoaError.Code {
return CocoaError.Code(rawValue: 65806)
}
@available(*, deprecated, renamed: "textWriteInapplicableDocumentType")
public static var TextWriteInapplicableDocumentTypeError: CocoaError.Code {
return CocoaError.Code(rawValue: 66062)
}
@available(*, deprecated, renamed: "serviceApplicationNotFound")
public static var ServiceApplicationNotFoundError: CocoaError.Code {
return CocoaError.Code(rawValue: 66560)
}
@available(*, deprecated, renamed: "serviceApplicationLaunchFailed")
public static var ServiceApplicationLaunchFailedError: CocoaError.Code {
return CocoaError.Code(rawValue: 66561)
}
@available(*, deprecated, renamed: "serviceRequestTimedOut")
public static var ServiceRequestTimedOutError: CocoaError.Code {
return CocoaError.Code(rawValue: 66562)
}
@available(*, deprecated, renamed: "serviceInvalidPasteboardData")
public static var ServiceInvalidPasteboardDataError: CocoaError.Code {
return CocoaError.Code(rawValue: 66563)
}
@available(*, deprecated, renamed: "serviceMalformedServiceDictionary")
public static var ServiceMalformedServiceDictionaryError: CocoaError.Code {
return CocoaError.Code(rawValue: 66564)
}
@available(*, deprecated, renamed: "serviceMiscellaneous")
public static var ServiceMiscellaneousError: CocoaError.Code {
return CocoaError.Code(rawValue: 66800)
}
@available(*, deprecated, renamed: "sharingServiceNotConfigured")
public static var SharingServiceNotConfiguredError: CocoaError.Code {
return CocoaError.Code(rawValue: 67072)
}
}
| 32778c06aca2a372c3f322d246bfb16b | 40.172131 | 80 | 0.763787 | false | false | false | false |
p-rothen/PRViews | refs/heads/master | PRViews/RoundedButton.swift | mit | 1 | //
// RoundedButton.swift
// Doctor Cloud
//
// Created by Pedro on 14-12-16.
// Copyright © 2016 IQS. All rights reserved.
//
import UIKit
public class RoundedButton : UIButton {
public override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
func setup() {
self.layer.cornerRadius = 3
//Default font
if let fontName = self.titleLabel?.font.fontName where fontName == ".SFUIText" {
self.titleLabel?.font = UIFont.boldSystemFontOfSize(15)
}
self.layer.shadowOpacity = 0.4;
self.layer.shadowRadius = 1;
self.layer.shadowColor = UIColor.blackColor().CGColor;
self.layer.shadowOffset = CGSizeMake(0.5, 0.5);
self.layer.masksToBounds = false
}
}
| 015a9f9d7fd5e3f57c303bf292785848 | 24.971429 | 88 | 0.608361 | false | false | false | false |
Limon-O-O/Lego | refs/heads/master | Frameworks/LegoProvider/LegoProvider/Observable+LegoProvider.swift | mit | 1 | //
// Observable+LegoProvider.swift
// Pods
//
// Created by Limon on 17/03/2017.
//
//
import Foundation
import RxSwift
import Moya
import Decodable
extension Observable {
public func mapObject<T: Decodable>(type: T.Type) -> Observable<T> {
return map { representor in
guard let response = (representor as? Moya.Response) ?? (representor as? Moya.ProgressResponse)?.response else {
throw ProviderError.noRepresentor
}
try response.validStatusCode()
let mapedJSON = try response.mapJSON()
guard let json = mapedJSON as? [String: Any] else {
throw ProviderError.jsonSerializationFailed
}
guard let object = type.decoding(json: json) else {
throw ProviderError.generationObjectFailed
}
return object
}
}
public func mapObjects<T: Decodable>(type: T.Type) -> Observable<[T]> {
return map { representor in
guard let response = (representor as? Moya.Response) ?? (representor as? Moya.ProgressResponse)?.response else {
throw ProviderError.noRepresentor
}
try response.validStatusCode()
let mapedJSON = try response.mapJSON()
guard let jsons = mapedJSON as? [[String: Any]] else {
throw ProviderError.jsonSerializationFailed
}
return jsons.flatMap { type.decoding(json: $0) }
}
}
}
extension Moya.Response {
func validStatusCode() throws {
guard !((200...209) ~= statusCode) else { return }
if let json = try mapJSON() as? [String: Any] {
print("Got error message: \(json)")
// json 的`错误信息和错误码`的 key,需自行修改,与服务器对应即可
if let errorCode = json["error_code"] as? Int, let message = json["error_msg"] as? String {
throw ProviderError(code: errorCode, failureReason: message)
}
}
throw ProviderError.notSuccessfulHTTP
}
}
| c5b74af3e41db017671d0837a17e9e83 | 26.065789 | 124 | 0.586291 | false | false | false | false |
vexy/Fridge | refs/heads/main | Sources/Fridge/Grabber.swift | mit | 1 | //
// Grabber.swift
// Fridge
// Copyright (c) 2016-2022 Veljko Tekelerović
/*
MIT License
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
@available(macOS 12.0, *)
@available(iOS 15.0, *)
final internal class Grabber {
func grab<D: Decodable>(from url: URL) async throws -> D {
guard let rawData = try? await URLSession.shared.data(from: url).0 else {
throw FridgeErrors.grabFailed
}
guard let decodedObject = try? JSONDecoder().decode(D.self, from: rawData) else {
throw FridgeErrors.decodingFailed
}
// return decoded object
return decodedObject
}
func grab<D: Decodable>(using urlRequest: URLRequest) async throws -> D {
guard let rawData = try? await URLSession.shared.data(for: urlRequest).0 else {
throw FridgeErrors.grabFailed
}
guard let decodedObject = try? JSONDecoder().decode(D.self, from: rawData) else {
throw FridgeErrors.grabFailed
}
// return decoded object
return decodedObject
}
//MARK: -
func push<E: Encodable, D: Decodable>(object: E, urlString: String) async throws -> D {
do {
var request = try constructURLRequest(from: urlString)
request.httpBody = try serializeObject(object)
//execute request and wait for response
let responseRawData = try await URLSession.shared.data(for: request).0 //first tuple item contains Data
// try to decode returned data into given return type
return try deserializeData(responseRawData)
} catch let e {
throw e //just rethrow the same error further
}
}
func push<E: Encodable, D: Decodable>(object: E, urlRequest: URLRequest) async throws -> D {
do {
var request = urlRequest
request.httpBody = try serializeObject(object)
//execute request and wait for response
let responseRawData = try await URLSession.shared.data(for: request).0 //first tuple item contains Data
// try to decode returned data into given return type
return try deserializeData(responseRawData)
} catch let e {
throw e //just rethrow the same error further
}
}
}
//MARK: - Private helpers
@available(macOS 12.0, *)
@available(iOS 15.0, *)
extension Grabber {
/// Constructs a JSON based `URLRequest` from given url `String`
private func constructURLRequest(from string: String) throws -> URLRequest {
guard let urlObject = URL(string: string) else { throw FridgeErrors.decodingFailed }
var request = URLRequest(url: urlObject)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Fridge.grab", forHTTPHeaderField: "User-Agent")
return request
}
/// Serialize given object and attach it to request body
private func serializeObject<E: Encodable>(_ objectToSerialize: E) throws -> Data {
guard let serializedObject = try? JSONEncoder().encode(objectToSerialize.self) else {
throw FridgeErrors.decodingFailed
}
return serializedObject
}
/// Tries to decode given data into given `Decodable` object
private func deserializeData<D: Decodable>(_ rawData: Data) throws -> D {
guard let decodedObject = try? JSONDecoder().decode(D.self, from: rawData) else {
throw FridgeErrors.decodingFailed
}
return decodedObject
}
}
| 59039d861dad08b4829eabcbf81274d9 | 39.5 | 116 | 0.661132 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | test/DebugInfo/closure-args.swift | apache-2.0 | 4 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
import Swift
func main() -> Void
{
// I am line 6.
var random_string = "b"
var random_int = 5
var out_only = 2013
var backward_ptr =
// CHECK: define internal {{.*}} i1 @_T04mainAAyyFSbSS_SStcfU_(
// CHECK: %[[RANDOM_STR_ADDR:.*]] = alloca %TSS*, align {{(4|8)}}
// CHECK-NEXT: call void @llvm.dbg.declare(metadata %TSS** %[[RANDOM_STR_ADDR]], metadata !{{.*}}, metadata !DIExpression()), !dbg
// CHECK: store %TSS* %{{.*}}, %TSS** %[[RANDOM_STR_ADDR]], align {{(4|8)}}
// CHECK-DAG: !DILocalVariable(name: "lhs",{{.*}} line: [[@LINE+5]],
// CHECK-DAG: !DILocalVariable(name: "rhs",{{.*}} line: [[@LINE+4]],
// CHECK-DAG: !DILocalVariable(name: "random_string",{{.*}} line: 8,
// CHECK-DAG: !DILocalVariable(name: "random_int",{{.*}} line: 9,
// CHECK-DAG: !DILocalVariable(name: "out_only",{{.*}} line: 10,
{ (lhs : String, rhs : String) -> Bool in
if rhs == random_string
|| rhs.unicodeScalars.count == random_int
{
// Ensure the two local_vars are in different lexical scopes.
// CHECK-DAG: !DILocalVariable(name: "local_var", scope: ![[THENSCOPE:[0-9]+]],{{.*}} line: [[@LINE+2]],
// CHECK-DAG: ![[THENSCOPE]] = distinct !DILexicalBlock({{.*}} line: [[@LINE-3]]
var local_var : Int64 = 10
print("I have an int here \(local_var).\n", terminator: "")
return false
}
else
{
// CHECK-DAG: !DILocalVariable(name: "local_var", scope: ![[ELSESCOPE:[0-9]+]],{{.*}} line: [[@LINE+2]]
// CHECK-DAG: ![[ELSESCOPE]] = distinct !DILexicalBlock({{.*}} line: [[@LINE-2]],
var local_var : String = "g"
print("I have another string here \(local_var).\n", terminator: "")
// Assign to all the captured variables to inhibit capture promotion.
random_string = "c"
random_int = -1
out_only = 333
return rhs < lhs
}
}
var bool = backward_ptr("a" , "b")
}
main()
| f1191957e4b5da469210bb15faded1e8 | 42.156863 | 134 | 0.51204 | false | false | false | false |
prine/ROGoogleTranslate | refs/heads/master | Source/ROGoogleTranslate.swift | mit | 1 | //
// ROGoogleTranslate.swift
// ROGoogleTranslate
//
// Created by Robin Oster on 20/10/16.
// Copyright © 2016 prine.ch. All rights reserved.
//
import Foundation
public struct ROGoogleTranslateParams {
public init() {
}
public init(source:String, target:String, text:String) {
self.source = source
self.target = target
self.text = text
}
public var source = "de"
public var target = "en"
public var text = "Ich glaube, du hast den Text zum Übersetzen vergessen"
}
/// Offers easier access to the Google Translate API
open class ROGoogleTranslate {
/// Store here the Google Translate API Key
public var apiKey = ""
///
/// Initial constructor
///
public init() {
}
///
/// Translate a phrase from one language into another
///
/// - parameter params: ROGoogleTranslate Struct contains all the needed parameters to translate with the Google Translate API
/// - parameter callback: The translated string will be returned in the callback
///
open func translate(params:ROGoogleTranslateParams, callback:@escaping (_ translatedText:String) -> ()) {
guard apiKey != "" else {
print("Warning: You should set the api key before calling the translate method.")
return
}
if let urlEncodedText = params.text.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
if let url = URL(string: "https://translation.googleapis.com/language/translate/v2?key=\(self.apiKey)&q=\(urlEncodedText)&source=\(params.source)&target=\(params.target)&format=text") {
let httprequest = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
guard error == nil else {
print("Something went wrong: \(error?.localizedDescription)")
return
}
if let httpResponse = response as? HTTPURLResponse {
guard httpResponse.statusCode == 200 else {
if let data = data {
print("Response [\(httpResponse.statusCode)] - \(data)")
}
return
}
do {
// Pyramid of optional json retrieving. I know with SwiftyJSON it would be easier, but I didn't want to add an external library
if let data = data {
if let json = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary {
if let jsonData = json["data"] as? [String : Any] {
if let translations = jsonData["translations"] as? [NSDictionary] {
if let translation = translations.first as? [String : Any] {
if let translatedText = translation["translatedText"] as? String {
callback(translatedText)
}
}
}
}
}
}
} catch {
print("Serialization failed: \(error.localizedDescription)")
}
}
})
httprequest.resume()
}
}
}
}
| 973a8d6efdd734a2840447e90f2a5c3d | 38.25 | 197 | 0.477707 | false | false | false | false |
webim/webim-client-sdk-ios | refs/heads/master | Example/WebimClientLibrary/Models/UIAlertHandler.swift | mit | 1 | //
// UIAlertHandler.swift
// WebimClientLibrary_Tests
//
// Created by Nikita Lazarev-Zubov on 13.02.18.
// Copyright © 2018 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 UIKit
import WebimClientLibrary
final class UIAlertHandler {
// MARK: - Properties
private weak var delegate: UIViewController?
private var alertController: UIAlertController!
// MARK: - Initializer
init(delegate: UIViewController) {
self.delegate = delegate
}
// MARK: - Methods
func showDialog(
withMessage message: String,
title: String?,
buttonTitle: String = "OK".localized,
buttonStyle: UIAlertAction.Style = .cancel,
action: (() -> Void)? = nil
) {
alertController = UIAlertController(
title: title,
message: message,
preferredStyle: .alert
)
let alertAction = UIAlertAction(
title: buttonTitle,
style: buttonStyle,
handler: { _ in
action?()
})
alertController.addAction(alertAction)
if buttonStyle != .cancel {
let alertActionOther = UIAlertAction(
title: "Cancel".localized,
style: .cancel)
alertController.addAction(alertActionOther)
}
delegate?.present(alertController, animated: true)
}
func showDepartmentListDialog(
withDepartmentList departmentList: [Department],
action: @escaping (String) -> Void,
senderButton: UIView?,
cancelAction: (() -> Void)?
) {
alertController = UIAlertController(
title: "Contact topic".localized,
message: nil,
preferredStyle: .actionSheet
)
for department in departmentList {
let departmentAction = UIAlertAction(
title: department.getName(),
style: .default,
handler: { _ in
action(department.getKey())
}
)
alertController.addAction(departmentAction)
}
let alertAction = UIAlertAction(
title: "Cancel".localized,
style: .cancel,
handler: { _ in cancelAction?() })
alertController.addAction(alertAction)
if let popoverController = alertController.popoverPresentationController {
if senderButton == nil {
fatalError("No source view for presenting alert popover")
}
popoverController.sourceView = senderButton
}
delegate?.present(alertController, animated: true)
}
func showSendFailureDialog(
withMessage message: String,
title: String,
action: (() -> Void)? = nil
) {
showDialog(
withMessage: message,
title: title,
buttonTitle: "OK".localized,
action: action
)
}
func showChatClosedDialog() {
showDialog(
withMessage: "Chat finished.".localized,
title: nil,
buttonTitle: "OK".localized
)
}
func showCreatingSessionFailureDialog(withMessage message: String) {
showDialog(
withMessage: message,
title: "Session creation failed".localized,
buttonTitle: "OK".localized
)
}
func showFileLoadingFailureDialog(withError error: Error) {
showDialog(
withMessage: error.localizedDescription,
title: "LoadError".localized,
buttonTitle: "OK".localized
)
}
func showFileSavingFailureDialog(withError error: Error) {
let action = getGoToSettingsAction()
showDialog(
withMessage: "SaveFileErrorMessage".localized,
title: "Save error".localized,
buttonTitle: "Go to Settings".localized,
buttonStyle: .default,
action: action
)
}
func showImageSavingFailureDialog(withError error: NSError) {
let action = getGoToSettingsAction()
showDialog(
withMessage: "SaveErrorMessage".localized,
title: "SaveError".localized,
buttonTitle: "Go to Settings".localized,
buttonStyle: .default,
action: action
)
}
func showImageSavingSuccessDialog() {
showDialog(
withMessage: "The image has been saved to your photos".localized,
title: "Saved!".localized,
buttonTitle: "OK".localized
)
}
func showNoCurrentOperatorDialog() {
showDialog(
withMessage: "There is no current agent to rate".localized,
title: "No agents available".localized,
buttonTitle: "OK".localized
)
}
func showSettingsAlertDialog(withMessage message: String) {
showDialog(
withMessage: message,
title: "InvalidSettings".localized,
buttonTitle: "OK".localized
)
}
func showOperatorInfo(withMessage message: String) {
showDialog(
withMessage: message,
title: "Operator Info".localized,
buttonTitle: "OK".localized
)
}
func showAlertForAccountName() {
showDialog(
withMessage: "Alert account name".localized,
title: "Account".localized,
buttonTitle: "OK".localized
)
}
// MARK: - Private methods
private func getGoToSettingsAction() -> (() -> Void) {
return {
guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, completionHandler: { (_) in
})
}
}
}
private func dismiss() {
let time = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: time) {
self.alertController.dismiss(animated: true, completion: nil)
}
}
}
| 6f431f61fa1c9a632217025bcf681255 | 30.353191 | 91 | 0.584555 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/SILGen/didset_oldvalue_not_accessed_silgen.swift | apache-2.0 | 12 | // RUN: %target-swift-emit-silgen %s | %FileCheck %s
// Make sure we do not call the getter to get the oldValue and pass it to didSet
// when the didSet does not reference the oldValue in its body.
class Foo<T> {
var value: T {
// CHECK-LABEL: sil private [ossa] @$s35didset_oldvalue_not_accessed_silgen3FooC5valuexvW : $@convention(method) <T> (@guaranteed Foo<T>) -> ()
// CHECK: debug_value %0 : $Foo<T>, let, name "self", argno {{[0-9]+}}
// CHECK-NOT: debug_value_addr %0 : $*T, let, name "oldValue", argno {{[0-9]+}}
didSet { print("didSet called!") }
}
init(value: T) {
self.value = value
}
}
let foo = Foo(value: "Hello")
// Foo.value.setter //
// CHECK-LABEL: sil hidden [ossa] @$s35didset_oldvalue_not_accessed_silgen3FooC5valuexvs : $@convention(method) <T> (@in T, @guaranteed Foo<T>) -> ()
// CHECK: debug_value_addr [[VALUE:%.*]] : $*T, let, name "value", argno {{[0-9+]}}
// CHECK-NEXT: debug_value [[SELF:%.*]] : $Foo<T>, let, name "self", argno {{[0-9+]}}
// CHECK-NEXT: [[ALLOC_STACK:%.*]] = alloc_stack $T
// CHECK-NEXT: copy_addr [[VALUE]] to [initialization] [[ALLOC_STACK]] : $*T
// CHECK-NEXT: [[REF_ADDR:%.*]] = ref_element_addr [[SELF]] : $Foo<T>, #Foo.value
// CHECK-NEXT: [[BEGIN_ACCESS:%.*]] = begin_access [modify] [dynamic] [[REF_ADDR]] : $*T
// CHECK-NEXT: copy_addr [take] [[ALLOC_STACK]] to [[BEGIN_ACCESS]] : $*T
// CHECK-NEXT: end_access [[BEGIN_ACCESS]] : $*T
// CHECK-NEXT: dealloc_stack [[ALLOC_STACK]] : $*T
// CHECK: [[DIDSET:%.*]] = function_ref @$s35didset_oldvalue_not_accessed_silgen3FooC5valuexvW : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = apply [[DIDSET]]<T>([[SELF]]) : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> ()
// Foo.value.modify //
// CHECK-LABEL: sil hidden [ossa] @$s35didset_oldvalue_not_accessed_silgen3FooC5valuexvM : $@yield_once @convention(method) <T> (@guaranteed Foo<T>) -> @yields @inout T
// CHECK: debug_value [[SELF:%.*]] : $Foo<T>, let, name "self", argno {{[0-9+]}}
// CHECK-NEXT: [[REF_ADDR:%.*]] = ref_element_addr [[SELF]] : $Foo<T>, #Foo.value
// CHECK-NEXT: [[BEGIN_ACCESS:%.*]] = begin_access [modify] [dynamic] [[REF_ADDR]] : $*T
// CHECK-NEXT: yield [[BEGIN_ACCESS]] : $*T, resume bb1, unwind bb2
// CHECK: bb1:
// CHECK-NEXT: end_access [[BEGIN_ACCESS]] : $*T
// CHECK-NEXT: // function_ref Foo.value.didset
// CHECK-NEXT: [[DIDSET:%.*]] = function_ref @$s35didset_oldvalue_not_accessed_silgen3FooC5valuexvW : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = apply [[DIDSET]]<T>([[SELF]]) : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> ()
// CHECK: bb2:
// CHECK-NEXT: end_access [[BEGIN_ACCESS]] : $*T
// CHECK-NEXT: unwind
foo.value = "World"
| 7d40edb8ea2c4c25da7a82a53567596f | 51.490566 | 168 | 0.615385 | false | false | false | false |
cameronklein/BigScreenGifs | refs/heads/master | BigScreenGifs/BigScreenGifs/GifCollectionViewCell.swift | mit | 1 | //
// GifCollectionViewCell.swift
// BigScreenGifs
//
// Created by Cameron Klein on 9/19/15.
// Copyright © 2015 Cameron Klein. All rights reserved.
//
import UIKit
import AVKit
let cellPopAnimationDuration : NSTimeInterval = 0.2
let cellPopAnimationScale : CGFloat = 1.15
class GifCollectionViewCell: UICollectionViewCell {
// MARK: - Constants
let popTransform = CGAffineTransformMakeScale(cellPopAnimationScale, cellPopAnimationScale)
let player = AVPlayer()
let playerLayer = AVPlayerLayer()
// MARK - Variables
var playerItem : AVPlayerItem!
var gif : Gif! {
willSet {
NSNotificationCenter.defaultCenter().removeObserver(self, name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem)
}
didSet {
self.playerItem = AVPlayerItem(asset: gif.asset)
self.player.replaceCurrentItemWithPlayerItem(self.playerItem)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "itemDidEnd:",
name: AVPlayerItemDidPlayToEndTimeNotification,
object: playerItem)
}
}
// MARK: - Initializers
override init(frame: CGRect) {
super.init(frame: frame)
playerLayer.player = player
playerLayer.videoGravity = AVLayerVideoGravityResizeAspect
contentView.layer.addSublayer(playerLayer)
self.layer.shadowColor = UIColor.blackColor().CGColor
self.layer.shadowOffset = CGSizeMake(0, 0)
self.layer.shadowRadius = 10
self.layer.shadowOpacity = 0.5
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Methods
override func layoutSubviews() {
super.layoutSubviews()
playerLayer.frame = contentView.bounds
}
// MARK: - Animation Methods
func pop() {
self.transform = self.popTransform
self.layer.shadowOpacity = 0.5
self.layer.shadowOffset = CGSizeMake(0, 10)
}
func unpop() {
self.transform = CGAffineTransformIdentity
self.layer.shadowOpacity = 0.0
self.layer.shadowOffset = CGSizeMake(0, 0)
}
// MARK: - Notification Handlers
func itemDidEnd(sender: NSNotification) {
playerItem.seekToTime(kCMTimeZero)
player.play()
}
}
| 2cd7c45b504a515f07a3f2e40fbaaf03 | 27.139535 | 137 | 0.646694 | false | false | false | false |
LeoFangQ/CMSwiftUIKit | refs/heads/master | CMSwiftUIKit/Pods/EZSwiftExtensions/Sources/UIViewExtensions.swift | mit | 1 | //
// UIViewExtensions.swift
// EZSwiftExtensions
//
// Created by Goktug Yilmaz on 15/07/15.
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit
// MARK: Custom UIView Initilizers
extension UIView {
/// EZSwiftExtensions
public convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) {
self.init(frame: CGRect(x: x, y: y, width: w, height: h))
}
/// EZSwiftExtensions, puts padding around the view
public convenience init(superView: UIView, padding: CGFloat) {
self.init(frame: CGRect(x: superView.x + padding, y: superView.y + padding, width: superView.w - padding*2, height: superView.h - padding*2))
}
/// EZSwiftExtensions - Copies size of superview
public convenience init(superView: UIView) {
self.init(frame: CGRect(origin: CGPoint.zero, size: superView.size))
}
}
// MARK: Frame Extensions
extension UIView {
/// EZSwiftExtensions, add multiple subviews
public func addSubviews(_ views: [UIView]) {
views.forEach { eachView in
self.addSubview(eachView)
}
}
//TODO: Add pics to readme
/// EZSwiftExtensions, resizes this view so it fits the largest subview
public func resizeToFitSubviews() {
var width: CGFloat = 0
var height: CGFloat = 0
for someView in self.subviews {
let aView = someView
let newWidth = aView.x + aView.w
let newHeight = aView.y + aView.h
width = max(width, newWidth)
height = max(height, newHeight)
}
frame = CGRect(x: x, y: y, width: width, height: height)
}
/// EZSwiftExtensions, resizes this view so it fits the largest subview
public func resizeToFitSubviews(_ tagsToIgnore: [Int]) {
var width: CGFloat = 0
var height: CGFloat = 0
for someView in self.subviews {
let aView = someView
if !tagsToIgnore.contains(someView.tag) {
let newWidth = aView.x + aView.w
let newHeight = aView.y + aView.h
width = max(width, newWidth)
height = max(height, newHeight)
}
}
frame = CGRect(x: x, y: y, width: width, height: height)
}
/// EZSwiftExtensions
public func resizeToFitWidth() {
let currentHeight = self.h
self.sizeToFit()
self.h = currentHeight
}
/// EZSwiftExtensions
public func resizeToFitHeight() {
let currentWidth = self.w
self.sizeToFit()
self.w = currentWidth
}
/// EZSwiftExtensions
public var x: CGFloat {
get {
return self.frame.origin.x
} set(value) {
self.frame = CGRect(x: value, y: self.y, width: self.w, height: self.h)
}
}
/// EZSwiftExtensions
public var y: CGFloat {
get {
return self.frame.origin.y
} set(value) {
self.frame = CGRect(x: self.x, y: value, width: self.w, height: self.h)
}
}
/// EZSwiftExtensions
public var w: CGFloat {
get {
return self.frame.size.width
} set(value) {
self.frame = CGRect(x: self.x, y: self.y, width: value, height: self.h)
}
}
/// EZSwiftExtensions
public var h: CGFloat {
get {
return self.frame.size.height
} set(value) {
self.frame = CGRect(x: self.x, y: self.y, width: self.w, height: value)
}
}
/// EZSwiftExtensions
public var left: CGFloat {
get {
return self.x
} set(value) {
self.x = value
}
}
/// EZSwiftExtensions
public var right: CGFloat {
get {
return self.x + self.w
} set(value) {
self.x = value - self.w
}
}
/// EZSwiftExtensions
public var top: CGFloat {
get {
return self.y
} set(value) {
self.y = value
}
}
/// EZSwiftExtensions
public var bottom: CGFloat {
get {
return self.y + self.h
} set(value) {
self.y = value - self.h
}
}
/// EZSwiftExtensions
public var origin: CGPoint {
get {
return self.frame.origin
} set(value) {
self.frame = CGRect(origin: value, size: self.frame.size)
}
}
/// EZSwiftExtensions
public var centerX: CGFloat {
get {
return self.center.x
} set(value) {
self.center.x = value
}
}
/// EZSwiftExtensions
public var centerY: CGFloat {
get {
return self.center.y
} set(value) {
self.center.y = value
}
}
/// EZSwiftExtensions
public var size: CGSize {
get {
return self.frame.size
} set(value) {
self.frame = CGRect(origin: self.frame.origin, size: value)
}
}
/// EZSwiftExtensions
public func leftOffset(_ offset: CGFloat) -> CGFloat {
return self.left - offset
}
/// EZSwiftExtensions
public func rightOffset(_ offset: CGFloat) -> CGFloat {
return self.right + offset
}
/// EZSwiftExtensions
public func topOffset(_ offset: CGFloat) -> CGFloat {
return self.top - offset
}
/// EZSwiftExtensions
public func bottomOffset(_ offset: CGFloat) -> CGFloat {
return self.bottom + offset
}
//TODO: Add to readme
/// EZSwiftExtensions
public func alignRight(_ offset: CGFloat) -> CGFloat {
return self.w - offset
}
/// EZSwiftExtensions
public func reorderSubViews(_ reorder: Bool = false, tagsToIgnore: [Int] = []) -> CGFloat {
var currentHeight: CGFloat = 0
for someView in subviews {
if !tagsToIgnore.contains(someView.tag) && !(someView ).isHidden {
if reorder {
let aView = someView
aView.frame = CGRect(x: aView.frame.origin.x, y: currentHeight, width: aView.frame.width, height: aView.frame.height)
}
currentHeight += someView.frame.height
}
}
return currentHeight
}
public func removeSubviews() {
for subview in subviews {
subview.removeFromSuperview()
}
}
/// EZSE: Centers view in superview horizontally
public func centerXInSuperView() {
guard let parentView = superview else {
assertionFailure("EZSwiftExtensions Error: The view \(self) doesn't have a superview")
return
}
self.x = parentView.w/2 - self.w/2
}
/// EZSE: Centers view in superview vertically
public func centerYInSuperView() {
guard let parentView = superview else {
assertionFailure("EZSwiftExtensions Error: The view \(self) doesn't have a superview")
return
}
self.y = parentView.h/2 - self.h/2
}
/// EZSE: Centers view in superview horizontally & vertically
public func centerInSuperView() {
self.centerXInSuperView()
self.centerYInSuperView()
}
}
// MARK: Transform Extensions
extension UIView {
/// EZSwiftExtensions
public func setRotationX(_ x: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, x.degreesToRadians(), 1.0, 0.0, 0.0)
self.layer.transform = transform
}
/// EZSwiftExtensions
public func setRotationY(_ y: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, y.degreesToRadians(), 0.0, 1.0, 0.0)
self.layer.transform = transform
}
/// EZSwiftExtensions
public func setRotationZ(_ z: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, z.degreesToRadians(), 0.0, 0.0, 1.0)
self.layer.transform = transform
}
/// EZSwiftExtensions
public func setRotation(x: CGFloat, y: CGFloat, z: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, x.degreesToRadians(), 1.0, 0.0, 0.0)
transform = CATransform3DRotate(transform, y.degreesToRadians(), 0.0, 1.0, 0.0)
transform = CATransform3DRotate(transform, z.degreesToRadians(), 0.0, 0.0, 1.0)
self.layer.transform = transform
}
/// EZSwiftExtensions
public func setScale(x: CGFloat, y: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DScale(transform, x, y, 1)
self.layer.transform = transform
}
}
// MARK: Layer Extensions
extension UIView {
/// EZSwiftExtensions
public func setCornerRadius(radius: CGFloat) {
self.layer.cornerRadius = radius
self.layer.masksToBounds = true
}
//TODO: add this to readme
/// EZSwiftExtensions
public func addShadow(offset: CGSize, radius: CGFloat, color: UIColor, opacity: Float, cornerRadius: CGFloat? = nil) {
self.layer.shadowOffset = offset
self.layer.shadowRadius = radius
self.layer.shadowOpacity = opacity
self.layer.shadowColor = color.cgColor
if let r = cornerRadius {
self.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: r).cgPath
}
}
/// EZSwiftExtensions
public func addBorder(width: CGFloat, color: UIColor) {
layer.borderWidth = width
layer.borderColor = color.cgColor
layer.masksToBounds = true
}
/// EZSwiftExtensions
public func addBorderTop(size: CGFloat, color: UIColor) {
addBorderUtility(x: 0, y: 0, width: frame.width, height: size, color: color)
}
//TODO: add to readme
/// EZSwiftExtensions
public func addBorderTopWithPadding(size: CGFloat, color: UIColor, padding: CGFloat) {
addBorderUtility(x: padding, y: 0, width: frame.width - padding*2, height: size, color: color)
}
/// EZSwiftExtensions
public func addBorderBottom(size: CGFloat, color: UIColor) {
addBorderUtility(x: 0, y: frame.height - size, width: frame.width, height: size, color: color)
}
/// EZSwiftExtensions
public func addBorderLeft(size: CGFloat, color: UIColor) {
addBorderUtility(x: 0, y: 0, width: size, height: frame.height, color: color)
}
/// EZSwiftExtensions
public func addBorderRight(size: CGFloat, color: UIColor) {
addBorderUtility(x: frame.width - size, y: 0, width: size, height: frame.height, color: color)
}
/// EZSwiftExtensions
fileprivate func addBorderUtility(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, color: UIColor) {
let border = CALayer()
border.backgroundColor = color.cgColor
border.frame = CGRect(x: x, y: y, width: width, height: height)
layer.addSublayer(border)
}
//TODO: add this to readme
/// EZSwiftExtensions
public func drawCircle(fillColor: UIColor, strokeColor: UIColor, strokeWidth: CGFloat) {
let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.w, height: self.w), cornerRadius: self.w/2)
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.fillColor = fillColor.cgColor
shapeLayer.strokeColor = strokeColor.cgColor
shapeLayer.lineWidth = strokeWidth
self.layer.addSublayer(shapeLayer)
}
//TODO: add this to readme
/// EZSwiftExtensions
public func drawStroke(width: CGFloat, color: UIColor) {
let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.w, height: self.w), cornerRadius: self.w/2)
let shapeLayer = CAShapeLayer ()
shapeLayer.path = path.cgPath
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = color.cgColor
shapeLayer.lineWidth = width
self.layer.addSublayer(shapeLayer)
}
}
private let UIViewAnimationDuration: TimeInterval = 1
private let UIViewAnimationSpringDamping: CGFloat = 0.5
private let UIViewAnimationSpringVelocity: CGFloat = 0.5
//TODO: add this to readme
// MARK: Animation Extensions
extension UIView {
/// EZSwiftExtensions
public func spring(animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) {
spring(duration: UIViewAnimationDuration, animations: animations, completion: completion)
}
/// EZSwiftExtensions
public func spring(duration: TimeInterval, animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) {
UIView.animate(
withDuration: UIViewAnimationDuration,
delay: 0,
usingSpringWithDamping: UIViewAnimationSpringDamping,
initialSpringVelocity: UIViewAnimationSpringVelocity,
options: UIViewAnimationOptions.allowAnimatedContent,
animations: animations,
completion: completion
)
}
/// EZSwiftExtensions
public func animate(duration: TimeInterval, animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) {
UIView.animate(withDuration: duration, animations: animations, completion: completion)
}
/// EZSwiftExtensions
public func animate(animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) {
animate(duration: UIViewAnimationDuration, animations: animations, completion: completion)
}
/// EZSwiftExtensions
public func pop() {
setScale(x: 1.1, y: 1.1)
spring(duration: 0.2, animations: { [unowned self] () -> Void in
self.setScale(x: 1, y: 1)
})
}
/// EZSwiftExtensions
public func popBig() {
setScale(x: 1.25, y: 1.25)
spring(duration: 0.2, animations: { [unowned self] () -> Void in
self.setScale(x: 1, y: 1)
})
}
//EZSE: Reverse pop, good for button animations
public func reversePop() {
setScale(x: 0.9, y: 0.9)
UIView.animate(withDuration: 0.05, delay: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: { [weak self] Void in
self?.setScale(x: 1, y: 1)
}) { (bool) in }
}
}
//TODO: add this to readme
// MARK: Render Extensions
extension UIView {
/// EZSwiftExtensions
public func toImage () -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0.0)
drawHierarchy(in: bounds, afterScreenUpdates: false)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}
// MARK: Gesture Extensions
extension UIView {
/// http://stackoverflow.com/questions/4660371/how-to-add-a-touch-event-to-a-uiview/32182866#32182866
/// EZSwiftExtensions
public func addTapGesture(tapNumber: Int = 1, target: AnyObject, action: Selector) {
let tap = UITapGestureRecognizer(target: target, action: action)
tap.numberOfTapsRequired = tapNumber
addGestureRecognizer(tap)
isUserInteractionEnabled = true
}
/// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public func addTapGesture(tapNumber: Int = 1, action: ((UITapGestureRecognizer) -> ())?) {
let tap = BlockTap(tapCount: tapNumber, fingerCount: 1, action: action)
addGestureRecognizer(tap)
isUserInteractionEnabled = true
}
/// EZSwiftExtensions
public func addSwipeGesture(direction: UISwipeGestureRecognizerDirection, numberOfTouches: Int = 1, target: AnyObject, action: Selector) {
let swipe = UISwipeGestureRecognizer(target: target, action: action)
swipe.direction = direction
#if os(iOS)
swipe.numberOfTouchesRequired = numberOfTouches
#endif
addGestureRecognizer(swipe)
isUserInteractionEnabled = true
}
/// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public func addSwipeGesture(direction: UISwipeGestureRecognizerDirection, numberOfTouches: Int = 1, action: ((UISwipeGestureRecognizer) -> ())?) {
let swipe = BlockSwipe(direction: direction, fingerCount: numberOfTouches, action: action)
addGestureRecognizer(swipe)
isUserInteractionEnabled = true
}
/// EZSwiftExtensions
public func addPanGesture(target: AnyObject, action: Selector) {
let pan = UIPanGestureRecognizer(target: target, action: action)
addGestureRecognizer(pan)
isUserInteractionEnabled = true
}
/// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public func addPanGesture(action: ((UIPanGestureRecognizer) -> ())?) {
let pan = BlockPan(action: action)
addGestureRecognizer(pan)
isUserInteractionEnabled = true
}
#if os(iOS)
/// EZSwiftExtensions
public func addPinchGesture(target: AnyObject, action: Selector) {
let pinch = UIPinchGestureRecognizer(target: target, action: action)
addGestureRecognizer(pinch)
isUserInteractionEnabled = true
}
#endif
#if os(iOS)
/// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public func addPinchGesture(action: ((UIPinchGestureRecognizer) -> ())?) {
let pinch = BlockPinch(action: action)
addGestureRecognizer(pinch)
isUserInteractionEnabled = true
}
#endif
/// EZSwiftExtensions
public func addLongPressGesture(target: AnyObject, action: Selector) {
let longPress = UILongPressGestureRecognizer(target: target, action: action)
addGestureRecognizer(longPress)
isUserInteractionEnabled = true
}
/// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public func addLongPressGesture(action: ((UILongPressGestureRecognizer) -> ())?) {
let longPress = BlockLongPress(action: action)
addGestureRecognizer(longPress)
isUserInteractionEnabled = true
}
}
//TODO: add to readme
extension UIView {
/// EZSwiftExtensions [UIRectCorner.TopLeft, UIRectCorner.TopRight]
public func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
/// EZSwiftExtensions
public func roundView() {
self.layer.cornerRadius = min(self.frame.size.height, self.frame.size.width) / 2
}
}
extension UIView {
///EZSE: Shakes the view for as many number of times as given in the argument.
public func shakeViewForTimes(_ times: Int) {
let anim = CAKeyframeAnimation(keyPath: "transform")
anim.values = [
NSValue(caTransform3D: CATransform3DMakeTranslation(-5, 0, 0 )),
NSValue(caTransform3D: CATransform3DMakeTranslation( 5, 0, 0 ))
]
anim.autoreverses = true
anim.repeatCount = Float(times)
anim.duration = 7/100
self.layer.add(anim, forKey: nil)
}
}
extension UIView {
///EZSE: Loops until it finds the top root view. //TODO: Add to readme
func rootView() -> UIView {
guard let parentView = superview else {
return self
}
return parentView.rootView()
}
}
//MARK: Fade Extensions
private let UIViewDefaultFadeDuration: TimeInterval = 0.4
extension UIView {
///EZSE: Fade in with duration, delay and completion block.
public func fadeIn(_ duration: TimeInterval? = UIViewDefaultFadeDuration, delay _delay: TimeInterval? = 0.0, completion: ((Bool) -> Void)? = nil) {
UIView.animate(withDuration: duration ?? UIViewDefaultFadeDuration, delay: _delay ?? 0.0, options: UIViewAnimationOptions(rawValue: UInt(0)), animations: {
self.alpha = 1.0
}, completion:completion)
}
/// EZSwiftExtensions
public func fadeOut(_ duration: TimeInterval? = UIViewDefaultFadeDuration, delay _delay: TimeInterval? = 0.0, completion: ((Bool) -> Void)? = nil) {
UIView.animate(withDuration: duration ?? UIViewDefaultFadeDuration, delay: _delay ?? 0.0, options: UIViewAnimationOptions(rawValue: UInt(0)), animations: {
self.alpha = 0.0
}, completion:completion)
}
/// Fade to specific value with duration, delay and completion block.
public func fadeTo(_ value: CGFloat, duration _duration: TimeInterval? = UIViewDefaultFadeDuration, delay _delay: TimeInterval? = 0.0, completion: ((Bool) -> Void)? = nil) {
UIView.animate(withDuration: _duration ?? UIViewDefaultFadeDuration, delay: _delay ?? UIViewDefaultFadeDuration, options: UIViewAnimationOptions(rawValue: UInt(0)), animations: {
self.alpha = value
}, completion:completion)
}
}
| 541f58fe726c2384d154d8da7a575005 | 33.432 | 186 | 0.631041 | false | false | false | false |
xdliu002/TongjiAppleClubDeviceManagement | refs/heads/master | TAC-DM/BorrowRecord.swift | mit | 1 | //
// BorrowRecord.swift
// TAC-DM
//
// Created by Shepard Wang on 15/8/27.
// Copyright (c) 2015 TAC. All rights reserved.
//
import UIKit
import Foundation
class BorrowRecord: NSObject {
var recordId: Int = 0
var borrowerName: String = ""
var tele: String = ""
var itemId: Int = 0
var itemName: String = ""
var itemDescription: String = ""
var borrowDate: NSDate
var returnDate: NSDate
var number: Int = 0
override init(){
borrowDate = NSDate()
returnDate = NSDate()
}
}
| 150f7369c44b456d47462f71cf39f597 | 18.642857 | 48 | 0.605455 | false | false | false | false |
fgengine/quickly | refs/heads/master | Quickly/Extensions/Date.swift | mit | 1 | //
// Quickly
//
public extension Date {
func isEqual(calendar: Calendar, date: Date, component: Calendar.Component) -> Bool {
return calendar.isDate(self, equalTo: date, toGranularity: component)
}
func format(_ format: String, calendar: Calendar = Calendar.current, locale: Locale = Locale.current) -> String {
let formatter = DateFormatter()
formatter.calendar = calendar
formatter.locale = locale
formatter.dateFormat = format
return formatter.string(from: self)
}
}
| 0d77c9ccbe4385de55ebcb1b57675229 | 27.842105 | 117 | 0.65146 | false | false | false | false |
rob-brown/SwiftRedux | refs/heads/master | Source/DiffNotifier.swift | mit | 1 | //
// DiffNotifier.swift
// SwiftRedux
//
// Created by Robert Brown on 11/6/15.
// Copyright © 2015 Robert Brown. All rights reserved.
//
import Foundation
public class DiffNotifier<T: Equatable> {
public typealias Listener = (T)->()
public typealias Unsubscriber = ()->()
public var currentState: T {
didSet {
if currentState != oldValue {
listeners.forEach { $0.1(currentState) }
}
}
}
private var listeners = [String:Listener]()
public init(_ initialState: T) {
currentState = initialState
}
public func subscribe(listener: Listener) -> Unsubscriber {
let key = NSUUID().UUIDString
listeners[key] = listener
listener(currentState)
return {
self.listeners.removeValueForKey(key)
}
}
}
public class DiffListNotifier<T: Equatable> {
public typealias Listener = ([T])->()
public typealias Unsubscriber = ()->()
public var currentState: [T] {
didSet {
if currentState != oldValue {
listeners.forEach { $0.1(currentState) }
}
}
}
private var listeners = [String:Listener]()
public init(_ initialState: [T]) {
currentState = initialState
}
public func subscribe(listener: Listener) -> Unsubscriber {
let key = NSUUID().UUIDString
listeners[key] = listener
listener(currentState)
return {
self.listeners.removeValueForKey(key)
}
}
}
| da50c2b40fc04da959a079ea60590f7c | 24.047619 | 63 | 0.569708 | false | false | false | false |
silence0201/Swift-Study | refs/heads/master | Learn/05.控制语句/switch中使用where语句.playground/section-1.swift | mit | 1 |
var student = (id:"1002", name:"李四", age:32, ChineseScore:90, EnglishScore:91)
var desc: String
switch student {
case (_, _, let age, 90...100, 90...100) where age > 20:
desc = "优"
case (_, _, _, 80..<90, 80..<90):
desc = "良"
case (_, _, _, 60..<80, 60..<80):
desc = "中"
case (_, _, _, 60..<80, 90...100), (_, _, _, 90...100, 60..<80):
desc = "偏科"
case (_, _, _, 0..<80, 90...100), (_, _, _, 90...100, 0..<80):
desc = "严重偏科"
default:
desc = "无"
}
print("说明:\(desc)")
| 046b5af598d00308785be14587431c80 | 20.608696 | 78 | 0.460765 | false | false | false | false |
epv44/TwitchAPIWrapper | refs/heads/master | Example/Tests/Request Tests/AllStreamTagRequestTests.swift | mit | 1 | //
// AllStreamTagRequestTests.swift
// TwitchAPIWrapper_Tests
//
// Created by Eric Vennaro on 6/9/21.
// Copyright © 2021 CocoaPods. All rights reserved.
//
import XCTest
@testable import TwitchAPIWrapper
class AllStreamTagRequestTests: XCTestCase {
override func setUpWithError() throws {
TwitchAuthorizationManager.sharedInstance.clientID = "1"
TwitchAuthorizationManager.sharedInstance.credentials = Credentials(accessToken: "XXX", scopes: ["user", "read"])
super.setUp()
}
func testBuildRequest_withRequiredParams_shouldSucceed() throws {
let request = AllStreamTagRequest()
XCTAssertEqual(
request.url!.absoluteString,
expectedURL: "https://api.twitch.tv/helix/tags/streams")
XCTAssertEqual(request.data, Data())
XCTAssertEqual(request.headers, ["Client-Id": "1", "Authorization": "Bearer XXX"])
}
func testBuildRequest_withOptionalParams_shouldSucceed() throws {
let request = AllStreamTagRequest(after: "1", first: "2", tagIDs: ["3"])
XCTAssertEqual(
request.url!.absoluteString,
expectedURL: "https://api.twitch.tv/helix/tags/streams?after=1&first=2&tag_id=3")
XCTAssertEqual(request.data, Data())
XCTAssertEqual(request.headers, ["Client-Id": "1", "Authorization": "Bearer XXX"])
}
}
| 2b75f99fbf58b2b5a0fc44f4209a37bc | 35.972973 | 121 | 0.675439 | false | true | false | false |
NordicSemiconductor/IOS-Pods-DFU-Library | refs/heads/master | iOSDFULibrary/Classes/Utilities/crc32.swift | bsd-3-clause | 1 | /*
Copyright (C) 1995-1998 Mark Adler
Copyright (C) 2015 C.W. "Madd the Sane" Betts
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jean-loup Gailly Mark Adler
[email protected] [email protected]
*/
import Foundation
/**
Table of CRC-32's of all single-byte values (made by make_crc_table)
*/
private let crcTable: [UInt32] = [
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
0x2d02ef8d]
/// Calculates CRC32 value from the given Data.
///
/// - parameter data: Data to calculate CRC from.
/// - returns: The CRC32 calculated over the whole Data object.
func crc32(data: Data?) -> UInt32 {
return crc32(0, data: data)
}
/// Updates the running crc with the bytes from given Data.
///
/// - parameter crc: The crc to be updated.
/// - parameter data: Data to calculate CRC from.
/// - returns: The CRC32 updated using whole Data object.
func crc32(_ crc: UInt32, data: Data?) -> UInt32 {
guard let data = data else {
return crc32(0, buffer: nil, length: 0)
}
return crc32(crc, buffer: (data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count), length: data.count)
}
/**
Update a running crc with the bytes buf[0..len-1] and return the updated
crc. If buf is `nil`, this function returns the required initial value
for the crc. Pre- and post-conditioning (one's complement) is performed
within this function so it shouldn't be done by the application.
Usage example:
var crc: UInt32 = crc32(0, nil, 0);
while (read_buffer(buffer, length) != EOF) {
crc = crc32(crc, buffer: buffer, length: length)
}
if (crc != original_crc) error();
*/
func crc32(_ crc: UInt32, buffer: UnsafePointer<UInt8>?, length: Int) -> UInt32 {
if buffer == nil {
return 0
}
var crc1 = crc ^ 0xffffffff
var len = length
var buf = buffer
func DO1() {
let toBuf = buf?.pointee
buf = buf! + 1
crc1 = crcTable[Int((crc1 ^ UInt32(toBuf!)) & 0xFF)] ^ crc1 >> 8
}
func DO2() { DO1(); DO1(); }
func DO4() { DO2(); DO2(); }
func DO8() { DO4(); DO4(); }
while len >= 8 {
DO8()
len -= 8
}
if len != 0 {
repeat {
len -= 1
DO1()
} while len != 0
}
return crc1 ^ 0xffffffff;
}
/*
func ==(lhs: CRC32Calculator, rhs: CRC32Calculator) -> Bool {
return lhs.initialized == rhs.initialized && lhs.crc == rhs.crc
}
final class CRC32Calculator: Hashable {
fileprivate var initialized = false
fileprivate(set) var crc: UInt32 = 0
init() {}
convenience init(data: Data) {
self.init()
crc = crc32(crc, data: data)
initialized = true
}
func run(buffer: UnsafePointer<UInt8>, length: Int) {
crc = crc32(crc, buffer: buffer, length: length)
initialized = true
}
func run(data: Data) {
crc = crc32(crc, data: data)
initialized = true
}
func hash(into hasher: inout Hasher) {
hasher.combine(crc)
}
}*/
| 5907e1a604a0527e8eb6888da6e32da2 | 38.2 | 122 | 0.70394 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | test/Interpreter/SDK/libc.swift | apache-2.0 | 9 | /* magic */
// Do not edit the line above.
// RUN: %empty-directory(%t)
// RUN: %target-run-simple-swift %s %t | %FileCheck %s
// REQUIRES: executable_test
// TODO: rdar://problem/33388782
// REQUIRES: CPU=x86_64
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
import Glibc
#endif
let sourcePath = CommandLine.arguments[1]
let tempPath = CommandLine.arguments[2] + "/libc.txt"
// CHECK: Hello world
fputs("Hello world", stdout)
// CHECK: 4294967295
print("\(UINT32_MAX)")
// CHECK: the magic word is ///* magic *///
let sourceFile = open(sourcePath, O_RDONLY)
assert(sourceFile >= 0)
var bytes = UnsafeMutablePointer<CChar>.allocate(capacity: 12)
var readed = read(sourceFile, bytes, 11)
close(sourceFile)
assert(readed == 11)
bytes[11] = CChar(0)
print("the magic word is //\(String(cString: bytes))//")
// CHECK: O_CREAT|O_EXCL returned errno *17*
let errFile =
open(sourcePath, O_RDONLY | O_CREAT | O_EXCL)
if errFile != -1 {
print("O_CREAT|O_EXCL failed to return an error")
} else {
let e = errno
print("O_CREAT|O_EXCL returned errno *\(e)*")
}
// CHECK-NOT: error
// CHECK: created mode *33216* *33216*
let tempFile =
open(tempPath, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IXUSR)
if tempFile == -1 {
let e = errno
print("error: open(tempPath \(tempPath)) returned -1, errno \(e)")
abort()
}
let written = write(tempFile, bytes, 11)
if (written != 11) {
print("error: write(tempFile) returned \(written), errno \(errno)")
abort()
}
var err: Int32
var statbuf1 = stat()
err = fstat(tempFile, &statbuf1)
if err != 0 {
let e = errno
print("error: fstat returned \(err), errno \(e)")
abort()
}
close(tempFile)
var statbuf2 = stat()
err = stat(tempPath, &statbuf2)
if err != 0 {
let e = errno
print("error: stat returned \(err), errno \(e)")
abort()
}
print("created mode *\(statbuf1.st_mode)* *\(statbuf2.st_mode)*")
assert(statbuf1.st_mode == S_IFREG | S_IRUSR | S_IWUSR | S_IXUSR)
assert(statbuf1.st_mode == statbuf2.st_mode)
| e838b35862ef1f6149b4d002a566fa17 | 23.352941 | 72 | 0.653623 | false | false | false | false |
Pluto-Y/SwiftyEcharts | refs/heads/master | SwiftyEcharts/Models/Type/Position.swift | mit | 1 | //
// Position.swift
// SwiftyEcharts
//
// Created by Pluto-Y on 15/02/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
/// 位置
public enum Position: FunctionOrOthers {
case auto, left, center, right, top, middle, bottom, start, end, inside, inner, outside, insideLeft, insideTop, insideRight, insideBottom, insideTopLeft, insideBottomLeft, insideTopRight, insideBottomRight
case value(LengthValue)
case point(Point)
case function(Function)
public var jsonString: String {
switch self {
case .auto:
return "auto".jsonString
case .left:
return "left".jsonString
case .right:
return "right".jsonString
case .center:
return "center".jsonString
case .top:
return "top".jsonString
case .bottom:
return "bottom".jsonString
case .middle:
return "middle".jsonString
case .start:
return "start".jsonString
case .end:
return "end".jsonString
case .inside:
return "inside".jsonString
case .inner:
return "inner".jsonString
case .outside:
return "outside".jsonString
case .insideLeft:
return "insideLeft".jsonString
case .insideRight:
return "insideRight".jsonString
case .insideTop:
return "insideTop".jsonString
case .insideBottom:
return "insideBottom".jsonString
case .insideTopLeft:
return "insideTopLeft".jsonString
case .insideBottomLeft:
return "insideBottomLeft".jsonString
case .insideTopRight:
return "insideTopRight".jsonString
case .insideBottomRight:
return "insideBottomRight".jsonString
case let .point(point):
return point.jsonString
case let .value(val):
return val.jsonString
case let .function(f):
return f.jsonString
}
}
}
extension Position: ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral {
public init(floatLiteral value: Float) {
self = .value(value)
}
public init(integerLiteral value: Int) {
self = .value(value)
}
}
public enum Location: String, Jsonable {
case start = "start"
case middle = "middle"
case end = "end"
public var jsonString: String {
return self.rawValue.jsonString
}
}
| ea2ce75e48d1e9e2fd777118f7aabe6a | 28.081395 | 209 | 0.598161 | false | false | false | false |
mbigatti/ImagesGenerator | refs/heads/master | ImagesGenerator/ViewController.swift | mit | 1 | //
// ViewController.swift
// ImagesGenerator
//
// Created by Massimiliano Bigatti on 19/06/15.
// Copyright © 2015 Massimiliano Bigatti. All rights reserved.
//
import UIKit
import CoreGraphics
class ViewController: UIViewController {
@IBOutlet weak var circleView: UIView!
@IBOutlet weak var color1TextField: UITextField!
@IBOutlet weak var lineWidthTextField: UITextField!
@IBOutlet weak var color2TextField: UITextField!
@IBOutlet weak var sizeSlider: UISlider!
let gradientLayer = CAGradientLayer()
let shapeLayer = CAShapeLayer()
let backgroundShapeLayer = CAShapeLayer()
override func viewDidLoad() {
super.viewDidLoad()
//
//
//
gradientLayer.frame = CGRect(x: 0, y: 0, width: circleView.layer.frame.width, height: circleView.layer.frame.height)
gradientLayer.startPoint = CGPoint(x: 0, y: 0)
gradientLayer.endPoint = CGPoint(x: 0, y: 1)
gradientLayer.mask = shapeLayer
circleView.layer.addSublayer(backgroundShapeLayer)
circleView.layer.addSublayer(gradientLayer)
updateImage()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sizeSliderValueChanged(sender: UISlider) {
updateImage()
}
@IBAction func dataChanged(sender: UITextField) {
updateImage()
}
@IBAction func export(sender: UIButton) {
let oldSize = sizeSlider.value
for index in 1...60 {
sizeSlider.setValue(Float(index), animated: false)
updateImage()
let filename = "progress-\(index)@2x.png"
saveImage(filename)
}
sizeSlider.value = oldSize
updateImage()
}
private func updateImage() {
updateGradient()
updateBackgroundShape()
updateArcShape()
}
private func updateGradient() {
//
// gradient
//
let color1 = UIColor.colorWithRGBString(color1TextField.text!)
let color2 = UIColor.colorWithRGBString(color2TextField.text!)
var colors = [AnyObject]()
colors.append(color1.CGColor)
colors.append(color2.CGColor)
gradientLayer.colors = colors
}
private func updateBackgroundShape() {
let center = CGPoint(x: circleView.frame.size.width / 2, y: circleView.frame.size.height / 2)
let bezierPath = UIBezierPath(arcCenter: center,
radius: (circleView.frame.size.width - CGFloat(strtoul(lineWidthTextField.text!, nil, 10))) / 2,
startAngle: CGFloat(-M_PI_2),
endAngle: CGFloat(3 * M_PI_2),
clockwise: true)
let path = CGPathCreateCopyByStrokingPath(bezierPath.CGPath, nil, CGFloat(strtoul(lineWidthTextField.text!, nil, 10)), bezierPath.lineCapStyle, bezierPath.lineJoinStyle, bezierPath.miterLimit)
backgroundShapeLayer.path = path
backgroundShapeLayer.fillColor = UIColor(white: 1.0, alpha: 0.2).CGColor
}
private func updateArcShape() {
let center = CGPoint(x: circleView.frame.size.width / 2, y: circleView.frame.size.height / 2)
let endAngle = (Double(sizeSlider.value) * 4 * M_PI_2) / 60 - M_PI_2
let bezierPath = UIBezierPath(arcCenter: center,
radius: (circleView.frame.size.width - CGFloat(strtoul(lineWidthTextField.text!, nil, 10))) / 2,
startAngle: CGFloat(-M_PI_2),
endAngle: CGFloat(endAngle),
clockwise: true)
bezierPath.lineCapStyle = .Round
let path = CGPathCreateCopyByStrokingPath(bezierPath.CGPath, nil, CGFloat(strtoul(lineWidthTextField.text!, nil, 10)), bezierPath.lineCapStyle, bezierPath.lineJoinStyle, bezierPath.miterLimit)
shapeLayer.path = path
}
func saveImage(filename: String) {
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
let localUrl = NSURL(string: filename, relativeToURL: documentsUrl)!
print("\(localUrl)")
let color = circleView.backgroundColor;
circleView.backgroundColor = UIColor.clearColor()
UIGraphicsBeginImageContext(circleView.frame.size);
circleView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
let imageData = UIImagePNGRepresentation(image);
imageData?.writeToURL(localUrl, atomically: true)
circleView.backgroundColor = color;
}
}
extension UIColor {
class func colorWithRGBString(hexString: String) -> UIColor {
let redString = hexString.substringWithRange(Range(start: hexString.startIndex, end: hexString.startIndex.advancedBy(2)))
let greenString = hexString.substringWithRange(Range(start: hexString.startIndex.advancedBy(2), end: hexString.startIndex.advancedBy(4)))
let blueString = hexString.substringWithRange(Range(start: hexString.startIndex.advancedBy(4), end: hexString.startIndex.advancedBy(6)))
let red = CGFloat(strtoul(redString, nil, 16)) / 255
let green = CGFloat(strtoul(greenString, nil, 16)) / 255
let blue = CGFloat(strtoul(blueString, nil, 16)) / 255
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
}
| 8010f9f06e75a0550c0a862029b3fdd9 | 35.320513 | 200 | 0.643134 | false | false | false | false |
whiteshadow-gr/HatForIOS | refs/heads/master | HAT/Objects/Notes/HATNotesAuthor.swift | mpl-2.0 | 1 | /**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* 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 SwiftyJSON
// MARK: Struct
public struct HATNotesAuthor: HATObject, HatApiType {
// MARK: - JSON Fields
/**
The JSON fields used by the hat
The Fields are the following:
* `nickname` in JSON is `nick`
* `name` in JSON is `name`
* `photoURL` in JSON is `photo_url`
* `phata` in JSON is `phata`
* `authorID` in JSON is `authorID`
*/
private enum CodingKeys: String, CodingKey {
case nickname = "nick"
case name = "name"
case photoURL = "photo_url"
case phata = "phata"
case authorID = "id"
}
// MARK: - Variables
/// the nickname of the author. Optional
public var nickname: String?
/// the name of the author. Optional
public var name: String?
/// the photo url of the author. Optional
public var photoURL: String?
/// the phata of the author. Required
public var phata: String = ""
/// the id of the author. Optional
public var authorID: Int?
// MARK: - Initialiser
/**
The default initialiser. Initialises everything to default values.
*/
public init() {
}
/**
It initialises everything from the received JSON file from the HAT
- dict: The JSON file received from the HAT
*/
public init(dict: Dictionary<String, JSON>) {
self.init()
self.inititialize(dict: dict)
}
/**
It initialises everything from the received JSON file from the HAT
- dict: The JSON file received from the HAT
*/
public mutating func inititialize(dict: Dictionary<String, JSON>) {
// this field will always have a value no need to use if let
if let tempPHATA: String = dict[CodingKeys.phata.rawValue]?.string {
phata = tempPHATA
}
// check optional fields for value, if found assign it to the correct variable
if let tempID: String = dict[CodingKeys.authorID.rawValue]?.stringValue, !tempID.isEmpty {
if let intTempID: Int = Int(tempID) {
authorID = intTempID
}
}
if let tempNickName: String = dict[CodingKeys.nickname.rawValue]?.string {
nickname = tempNickName
}
if let tempName: String = dict[CodingKeys.name.rawValue]?.string {
name = tempName
}
if let tempPhotoURL: String = dict[CodingKeys.photoURL.rawValue]?.string {
photoURL = tempPhotoURL
}
}
/**
It initialises everything from the received Dictionary file from the cache
- fromCache: The dictionary file received from the cache
*/
public mutating func initialize(fromCache: Dictionary<String, Any>) {
let dictionary: JSON = JSON(fromCache)
self.inititialize(dict: dictionary.dictionaryValue)
}
// MARK: - JSON Mapper
/**
Returns the object as Dictionary, JSON
- returns: Dictionary<String, String>
*/
public func toJSON() -> Dictionary<String, Any> {
return [
CodingKeys.phata.rawValue: self.phata,
CodingKeys.authorID.rawValue: self.authorID ?? "",
CodingKeys.nickname.rawValue: self.nickname ?? "",
CodingKeys.name.rawValue: self.name ?? "",
CodingKeys.photoURL.rawValue: self.photoURL ?? ""
]
}
}
| e49f869196d62a79dfa339320b89cc05 | 26.802817 | 98 | 0.574975 | false | false | false | false |
PurpleSweetPotatoes/SwiftKit | refs/heads/master | SwiftKit/control/BQRefresh/BQRefreshView.swift | apache-2.0 | 1 | //
// BQRefreshView.swift
// BQRefresh
//
// Created by baiqiang on 2017/7/5.
// Copyright © 2017年 baiqiang. All rights reserved.
//
import UIKit
enum RefreshStatus: Int {
case idle //闲置
case pull //拖拽
case refreshing //刷新
case willRefresh //即将刷新
case noMoreData //无更多数据
}
enum ObserverName: String {
case scrollerOffset = "contentOffset"
case scrollerSize = "contentSize"
}
typealias CallBlock = ()->()
class BQRefreshView: UIView {
//MARK: - ***** Ivars *****
var origiOffsetY: CGFloat = 0
public var scrollViewOriginalInset: UIEdgeInsets = .zero
public var status: RefreshStatus = .idle
public weak var scrollView: UIScrollView!
public var refreshBlock: CallBlock!
//MARK: - ***** public Method *****
public class func refreshLab() -> UILabel {
let lab = UILabel()
lab.font = UIFont.systemFont(ofSize: 14)
lab.textAlignment = .center
return lab
}
override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
if !(newSuperview is UIScrollView) {
return
}
self.removeObservers()
self.sizeW = newSuperview?.sizeW ?? 0
self.left = 0
self.scrollView = newSuperview as! UIScrollView
self.scrollViewOriginalInset = self.scrollView.contentInset
self.addObservers()
//初始化状态(防止第一次无数据tableView下拉时出现异常)
self.scrollView.contentOffset = CGPoint.zero
}
override func removeFromSuperview() {
self.removeObservers()
super.removeFromSuperview()
}
//MARK: - ***** private Method *****
private func addObservers() {
let options: NSKeyValueObservingOptions = [.new, .old]
self.scrollView.addObserver(self, forKeyPath: ObserverName.scrollerOffset.rawValue, options: options, context: nil)
self.scrollView.addObserver(self, forKeyPath: ObserverName.scrollerSize.rawValue, options: options, context: nil)
}
private func removeObservers() {
self.superview?.removeObserver(self, forKeyPath: ObserverName.scrollerOffset.rawValue)
self.superview?.removeObserver(self, forKeyPath: ObserverName.scrollerSize.rawValue)
}
//MARK: - ***** respond event Method *****
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if !self.isUserInteractionEnabled {
return
}
if self.isHidden {
return
}
if let key = keyPath {
let value = ObserverName(rawValue: key)!
switch value {
case .scrollerOffset:
self.contentOffsetDidChange(change: change)
case .scrollerSize:
self.contentSizeDidChange(change: change)
}
}
}
func contentOffsetDidChange(change: [NSKeyValueChangeKey : Any]?) {
if self.status == .idle && !self.scrollView.isDragging {
origiOffsetY = self.scrollView.contentOffset.y
self.status = .pull
}
}
func contentSizeDidChange(change: [NSKeyValueChangeKey : Any]?) {
}
}
| 0599c50cc84581972244e04d6fae2a46 | 30.407767 | 151 | 0.633385 | false | false | false | false |
dclelland/AudioKit | refs/heads/master | AudioKit/Common/Instruments/AKWavetableSynth.swift | mit | 1 | //
// AKWavetableSynth.swift
// AudioKit
//
// Created by Jeff Cooper, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
import AVFoundation
/// A wrapper for AKOscillator to make it playable as a polyphonic instrument.
public class AKWavetableSynth: AKPolyphonicInstrument {
/// Attack time
public var attackDuration: Double = 0.1 {
didSet {
for voice in voices {
let oscillatorVoice = voice as! AKOscillatorVoice
oscillatorVoice.adsr.attackDuration = attackDuration
}
}
}
/// Decay time
public var decayDuration: Double = 0.1 {
didSet {
for voice in voices {
let oscillatorVoice = voice as! AKOscillatorVoice
oscillatorVoice.adsr.decayDuration = decayDuration
}
}
}
/// Sustain Level
public var sustainLevel: Double = 0.66 {
didSet {
for voice in voices {
let oscillatorVoice = voice as! AKOscillatorVoice
oscillatorVoice.adsr.sustainLevel = sustainLevel
}
}
}
/// Release time
public var releaseDuration: Double = 0.5 {
didSet {
for voice in voices {
let oscillatorVoice = voice as! AKOscillatorVoice
oscillatorVoice.adsr.releaseDuration = releaseDuration
}
}
}
/// Instantiate the Oscillator Instrument
///
/// - parameter waveform: Shape of the waveform to oscillate
/// - parameter voiceCount: Maximum number of voices that will be required
///
public init(waveform: AKTable, voiceCount: Int) {
super.init(voice: AKOscillatorVoice(waveform: waveform), voiceCount: voiceCount)
}
/// Start playback of a particular voice with MIDI style note and velocity
///
/// - parameter voice: Voice to start
/// - parameter note: MIDI Note Number
/// - parameter velocity: MIDI Velocity (0-127)
///
override internal func playVoice(voice: AKVoice, note: Int, velocity: Int) {
let frequency = note.midiNoteToFrequency()
let amplitude = Double(velocity) / 127.0 * 0.3
let oscillatorVoice = voice as! AKOscillatorVoice
oscillatorVoice.oscillator.frequency = frequency
oscillatorVoice.oscillator.amplitude = amplitude
oscillatorVoice.start()
}
/// Stop playback of a particular voice
///
/// - parameter voice: Voice to stop
/// - parameter note: MIDI Note Number
///
override internal func stopVoice(voice: AKVoice, note: Int) {
let oscillatorVoice = voice as! AKOscillatorVoice
oscillatorVoice.stop()
}
}
internal class AKOscillatorVoice: AKVoice {
var oscillator: AKOscillator
var adsr: AKAmplitudeEnvelope
var waveform: AKTable
init(waveform: AKTable) {
oscillator = AKOscillator(waveform: waveform)
adsr = AKAmplitudeEnvelope(oscillator,
attackDuration: 0.2,
decayDuration: 0.2,
sustainLevel: 0.8,
releaseDuration: 1.0)
self.waveform = waveform
super.init()
avAudioNode = adsr.avAudioNode
}
/// Function create an identical new node for use in creating polyphonic instruments
override func duplicate() -> AKVoice {
let copy = AKOscillatorVoice(waveform: self.waveform)
return copy
}
/// Tells whether the node is processing (ie. started, playing, or active)
override var isStarted: Bool {
return oscillator.isPlaying
}
/// Function to start, play, or activate the node, all do the same thing
override func start() {
oscillator.start()
adsr.start()
}
/// Function to stop or bypass the node, both are equivalent
override func stop() {
adsr.stop()
}
}
| ef4049541f2b89f778dc46f551d19eb5 | 30.015625 | 88 | 0.615617 | false | false | false | false |
schrismartin/dont-shoot-the-messenger | refs/heads/master | Sources/Library/Models/FBIncomingMessage.swift | mit | 1 | //
// FBMessageInformation.swift
// the-narrator
//
// Created by Chris Martin on 11/14/16.
//
//
import Foundation
import Vapor
import HTTP
public struct FBIncomingMessage {
public var senderId: SCMIdentifier
public var recipientId: SCMIdentifier
public var date: Date
public var text: String?
public var postback: String?
/// Constructs an expected Facebook Messenger event from the received JSON data
/// - Parameter json: The JSON payload representation of an event
/// Fails if
public init?(json: JSON) {
// Extract Components
guard let senderId = json[ "sender" ]?[ "id" ]?.string,
let recipientId = json[ "recipient" ]?[ "id" ]?.string,
let timestamp = json[ "timestamp" ]?.int else {
console.log("Facebook Message must contain senderId, recipientId, and timestamp")
return nil
}
// Make assignments
self.senderId = SCMIdentifier(string: senderId)
self.recipientId = SCMIdentifier(string: recipientId)
self.date = Date(timeIntervalSince1970: TimeInterval(timestamp))
text = json[ "message" ]?[ "text" ]?.string
postback = json[ "postback" ]?[ "payload" ]?.string
}
}
extension FBIncomingMessage: CustomStringConvertible {
public var description: String {
return "Sender: \(senderId.string), Recipient: \(recipientId.string), Message: \(text), date: \(date)"
}
}
| 15b05f476d106e7617b3b2e334fa35eb | 30.638298 | 110 | 0.634163 | false | false | false | false |
ProsoftEngineering/TimeMachineRemoteStatus | refs/heads/master | TimeMachineRemoteStatus/AppDelegate.swift | bsd-3-clause | 1 | // Copyright © 2016-2017, Prosoft Engineering, Inc. (A.K.A "Prosoft")
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Prosoft nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL PROSOFT ENGINEERING, INC. BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
var statusItem: NSStatusItem?
var statusImage: NSImage!
let fmt = DateFormatter()
let backupsManager = BackupsManager()
var prefsController: PreferencesController!
var scheduleTimer: Timer!
var nextScheduledUpdate: Date!
var lastUpdatedItem: NSMenuItem!
var updateCount = 0
var backups: [String: BackupHost] = [:]
var lastUpdate: Date?
func applicationDidFinishLaunching(_ aNotification: Notification) {
UserDefaults.standard.register(defaults: ["WarningNumDays": 1])
statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
statusImage = NSImage(named: "img")
statusItem?.alternateImage = colorizeImage(image: statusImage, color: NSColor.white)
fmt.doesRelativeDateFormatting = true
fmt.timeStyle = .short
fmt.dateStyle = .short
NotificationCenter.default.addObserver(forName: PreferencesController.hostsDidUpdateNotification, object: nil, queue: nil, using: {(_) in
self.startUpdate()
})
NSWorkspace.shared().notificationCenter.addObserver(forName: .NSWorkspaceDidWake, object: nil, queue: nil, using: {(_) in
self.updateCycle()
})
updateCycle()
}
func colorizeImage(image: NSImage, color: NSColor) -> NSImage {
let newImage = NSImage(size: image.size)
newImage.lockFocus()
let rect = NSMakeRect(0, 0, image.size.width, image.size.height)
image.draw(in: rect, from: NSZeroRect, operation: .sourceOver, fraction: 1.0)
color.setFill()
NSRectFillUsingOperation(rect, .sourceAtop)
newImage.unlockFocus()
return newImage
}
func updateCycle() {
startUpdate()
scheduleNextUpdate()
}
func startUpdate() {
updateCount = updateCount + 1
if let hosts = UserDefaults().value(forKey: "Hosts") as? [String] {
backupsManager.hosts = hosts
}
buildMenu() // to show "Updating..."
backupsManager.update { (backups: [String : BackupHost]) -> (Void) in
self.updateCount = self.updateCount - 1
self.lastUpdate = Date()
self.backups = backups
self.buildMenu()
}
}
func buildMenu() {
let menu = NSMenu()
var error = false
let now = NSDate()
var warning = false
let secondsInADay = 86400
let warningNumDays = Double(secondsInADay * UserDefaults.standard.integer(forKey: "WarningNumDays"))
// Sort backup keys (hosts) based on their order in the original hosts array
let backupsKeys = backups.keys.sorted { (s1: String, s2: String) -> Bool in
// Indexes can be nil if a host is removed or renamed
let index1 = backupsManager.hosts.index(of: s1)
let index2 = backupsManager.hosts.index(of: s2)
let s1 = index1 != nil ? index1! : Int.max
let s2 = index2 != nil ? index2! : Int.max
return s1 < s2
}
for host in backupsKeys {
let backupHost = backups[host]
let hostItem = NSMenuItem(title: host, action: nil, keyEquivalent: "")
menu.addItem(hostItem)
if let backups = backupHost?.backups.sorted(by: { $0.date > $1.date }), backups.count > 0 {
let item = backups[0]
let dateStr = fmt.string(from: item.date)
let titleStr = String(format: NSLocalizedString("Latest Backup to \"%@\":", comment: ""), item.volumeName)
let titleItem = NSMenuItem(title: titleStr, action: nil, keyEquivalent: "")
let dateItem = NSMenuItem(title: dateStr, action: nil, keyEquivalent: "")
titleItem.indentationLevel = 1
dateItem.indentationLevel = 1
menu.addItem(titleItem)
menu.addItem(dateItem)
if now.timeIntervalSince(item.date) > warningNumDays {
warning = true
}
} else {
let errorItem = NSMenuItem(title: NSLocalizedString("Error", comment: ""), action: #selector(showError), keyEquivalent: "")
errorItem.target = self
errorItem.representedObject = backupHost!
menu.addItem(errorItem)
error = true
}
menu.addItem(NSMenuItem.separator())
}
let lastUpdateItemTitle: String
if lastUpdate == nil {
lastUpdateItemTitle = NSLocalizedString("Updated: Never", comment: "")
} else {
lastUpdateItemTitle = String(format: NSLocalizedString("Updated: %@", comment: ""), fmt.string(from: lastUpdate!))
}
lastUpdatedItem = NSMenuItem(title: lastUpdateItemTitle, action: nil, keyEquivalent: "")
updateLastUpdatedItemToolTip()
let updateItem: NSMenuItem
if updateCount == 0 {
updateItem = NSMenuItem(title: NSLocalizedString("Update Now", comment: ""), action: #selector(startUpdate), keyEquivalent: "")
} else {
updateItem = NSMenuItem(title: NSLocalizedString("Updating…", comment: ""), action: nil, keyEquivalent: "")
}
updateItem.target = self
menu.addItem(lastUpdatedItem)
menu.addItem(updateItem)
menu.addItem(NSMenuItem.separator())
let prefsItem = NSMenuItem(title: NSLocalizedString("Preferences", comment: ""), action: #selector(showPreferences), keyEquivalent: "")
prefsItem.target = self
menu.addItem(prefsItem)
let aboutStr = String(format: NSLocalizedString("About %@", comment: ""), NSRunningApplication.current().localizedName!)
let aboutItem = NSMenuItem(title: aboutStr, action: #selector(showAbout), keyEquivalent: "")
aboutItem.target = self
menu.addItem(aboutItem)
let quitItem = NSMenuItem(title: NSLocalizedString("Quit", comment: ""), action: #selector(NSApp.terminate), keyEquivalent: "")
quitItem.target = NSApp
menu.addItem(quitItem)
if error {
statusItem?.image = colorizeImage(image: statusImage, color: NSColor.red)
} else if warning {
statusItem?.image = colorizeImage(image: statusImage, color: NSColor(calibratedRed:0.50, green:0.00, blue:1.00, alpha:1.0))
} else {
statusItem?.image = statusImage
}
statusItem?.menu = menu
}
func updateLastUpdatedItemToolTip() {
if lastUpdatedItem == nil {
return
}
if nextScheduledUpdate != nil {
lastUpdatedItem.toolTip = String(format: NSLocalizedString("Next Update: %@", comment: ""), fmt.string(from: nextScheduledUpdate))
} else {
lastUpdatedItem.toolTip = nil
}
}
func showError(sender: Any?) {
if let item = sender as? NSMenuItem, let backupHost = item.representedObject as? BackupHost {
let alert = NSAlert()
alert.informativeText = backupHost.error
alert.alertStyle = .critical
alert.runModal()
}
}
func showPreferences(sender: Any?) {
if prefsController == nil {
prefsController = PreferencesController()
}
NSApp.activate(ignoringOtherApps: true)
prefsController?.window?.makeKeyAndOrderFront(sender)
}
func showAbout(sender: Any?) {
NSApp.activate(ignoringOtherApps: true)
NSApp.orderFrontStandardAboutPanel(sender)
}
func scheduleNextUpdate() {
// Update every hour at X:30
guard let cal = NSCalendar(calendarIdentifier: .gregorian) else {
print("ERROR: Got nil calendar")
return
}
let now = Date()
let nowComps = cal.components([.hour, .minute], from: now)
let scheduledMinute = 30
// If we're under 1 minute of the scheduled time, use the current hour. Otherwise use the next hour
let hour: Int
if nowComps.minute! < (scheduledMinute - 1) {
hour = nowComps.hour!
} else {
hour = nowComps.hour! + 1
}
guard let scheduledDate = cal.date(bySettingHour: hour, minute: scheduledMinute, second: 0, of: now) else {
print("ERROR: Got nil date")
return
}
nextScheduledUpdate = scheduledDate
let timerBlock = {(timer: Timer) in
self.updateCycle()
}
if scheduleTimer != nil {
scheduleTimer.invalidate()
}
scheduleTimer = Timer(fire: scheduledDate, interval: 0, repeats: false, block: timerBlock)
RunLoop.current.add(scheduleTimer, forMode: RunLoopMode.defaultRunLoopMode)
updateLastUpdatedItemToolTip()
}
}
| 19efd3ac441a64a2275ba48d16aacf3e | 41.408 | 145 | 0.624882 | false | false | false | false |
systers/PowerUp | refs/heads/develop | Powerup/MinesweeperGameScene.swift | gpl-2.0 | 1 | import SpriteKit
class MinesweeperGameScene: SKScene {
// Make it as an array, so it is easy to add new entries.
var possiblityPercentages = [90.0]
// MARK: Game Constants
let gridSizeCount = 5
let tutorialSceneImages = [
"minesweeper_tutorial_1",
"minesweeper_tutorial_2",
"minesweeper_tutorial_3"
]
// How many boxes could be selected each round.
let selectionMaxCount = 5
// Colors of game UIs.
let uiColor = UIColor(red: 42.0 / 255.0, green: 203.0 / 255.0, blue: 211.0 / 255.0, alpha: 1.0)
let textColor = UIColor(red: 21.0 / 255.0, green: 124.0 / 255.0, blue: 129.0 / 255.0, alpha: 1.0)
let prosTextColor = UIColor(red: 105.0 / 255.0, green: 255.0 / 255.0, blue: 97.0 / 255.0, alpha: 1.0)
let consTextColor = UIColor(red: 255.0 / 255.0, green: 105.0 / 255.0, blue: 105.0 / 255.0, alpha: 1.0)
// Animation constants.
let boxEnlargingScale = CGFloat(1.2)
let boxEnlargingDuration = 0.25
let buttonWaitDuration = 0.5
let boxFlipInterval = 0.2
let showAllBoxesInterval = 0.3
let boxDarkening = SKAction.colorize(with: UIColor(white: 0.6, alpha: 0.8), colorBlendFactor: 1.0, duration: 0.2)
let fadeInAction = SKAction.fadeIn(withDuration: 0.8)
let fadeOutAction = SKAction.fadeOut(withDuration: 0.8)
let scoreTextPopScale = CGFloat(1.2)
let scoreTextPopDuraion = 0.25
// These are relative to the size of the view, so they can be applied to different screen sizes.
let gridOffsetYRelativeToHeight = 0.0822
let gridSpacingRelativeToWidth = 0.0125
var gridOffsetXRelativeToWidth:Double
var boxSizeRelativeToWidth:Double
let continueButtonBottomMargin = 0.08
let continueButtonHeightRelativeToSceneHeight = 0.2
let continueButtonAspectRatio = 2.783
let prosDescriptionPosYRelativeToHeight = 0.77
let consDescriptionPosYRelativeToHeight = 0.33
let descriptionTextPosXReleativeToWidth = 0.53
// Offset the text in y direction so that it appears in the center of the button.
let buttonTextOffsetY = -7.0
let scoreTextOffsetX = 10.0
let scoreTextOffsetY = 25.0
// Fonts.
let scoreTextFontSize = CGFloat(20)
let buttonTextFontSize = CGFloat(18)
let descriptionTitleFontSize = CGFloat(24)
let descriptionFontSize = CGFloat(20)
let fontName = "Montserrat-Bold"
let buttonStrokeWidth = CGFloat(3)
// These are the actual sizing and positioning, will be calculated in init()
let boxSize: Double
let gridOffsetX: Double
let gridOffsetY: Double
let gridSpacing: Double
// Sprite nodes
let backgroundImage = SKSpriteNode(imageNamed: "minesweeper_background")
let resultBanner = SKSpriteNode()
let descriptionBanner = SKSpriteNode(imageNamed: "minesweeper_pros_cons_banner")
let continueButton = SKSpriteNode(imageNamed: "continue_button")
// Label wrapper nodes
let scoreLabelNode = SKNode()
let prosLabelNode = SKNode()
let consLabelNode = SKNode()
// Label nodes
let scoreLabel = SKLabelNode()
let prosLabel = SKLabelNode(text: "Pros text goes here...")
let consLabel = SKLabelNode(text: "Cons text goes here...")
// Textures
let successBannerTexture = SKTexture(imageNamed: "success_banner")
let failureBannerTexture = SKTexture(imageNamed: "failure_banner")
// TODO: Replace the temporary sprite.
let endGameText = "End Game"
let scoreTextPrefix = "Score: "
// Layer index, aka. zPosition.
let backgroundLayer = CGFloat(-0.1)
let gridLayer = CGFloat(0.1)
let bannerLayer = CGFloat(0.2)
let uiLayer = CGFloat(0.3)
let uiTextLayer = CGFloat(0.4)
let tutorialSceneLayer = CGFloat(5)
// MARK: Properties
var tutorialScene: SKTutorialScene!
// Keep a reference to the view controller for end game transition.
// (This is assigned in the MiniGameViewController class.)
var viewController: MiniGameViewController!
// Holding each boxes
var gameGrid: [[GuessingBox]] = []
var roundCount = 0
var currBox: GuessingBox? = nil
// Score. +1 if a successful box is chosen. +0 if a failed box is chosen.
var score = 0
// Selected box count.
var selectedBoxes = 0
// Avoid player interaction with boxes when they are animating.
var boxSelected: Bool = false
// Avoid player interaction with boxes when the game is in tutorial scene.
var inTutorial = true
// MARK: Constructor
override init(size: CGSize) {
// Positioning and sizing background image.
backgroundImage.size = size
backgroundImage.position = CGPoint(x: size.width / 2.0, y: size.height / 2.0)
backgroundImage.zPosition = backgroundLayer
// Positioning and sizing result banner.
resultBanner.size = size
resultBanner.position = CGPoint(x: size.width / 2.0, y: size.height / 2.0)
resultBanner.zPosition = bannerLayer
resultBanner.isHidden = true
// Description Banner
descriptionBanner.size = size
descriptionBanner.anchorPoint = CGPoint.zero
descriptionBanner.position = CGPoint.zero
descriptionBanner.zPosition = bannerLayer
descriptionBanner.isHidden = true
// Score text
scoreLabelNode.position = CGPoint(x: Double(size.width) - scoreTextOffsetX, y: Double(size.height) - scoreTextOffsetY)
scoreLabelNode.zPosition = bannerLayer
scoreLabel.position = CGPoint.zero
scoreLabel.fontName = fontName
scoreLabel.fontSize = scoreTextFontSize
scoreLabel.zPosition = uiLayer
scoreLabel.fontColor = uiColor
scoreLabel.horizontalAlignmentMode = .right
scoreLabelNode.addChild(scoreLabel)
// Continue button
continueButton.anchorPoint = CGPoint(x: 1.0, y: 0.0)
continueButton.size = CGSize(width: CGFloat(continueButtonAspectRatio * continueButtonHeightRelativeToSceneHeight) * size.height, height: size.height * CGFloat(continueButtonHeightRelativeToSceneHeight))
continueButton.position = CGPoint(x: size.width, y: size.height * CGFloat(continueButtonBottomMargin))
continueButton.zPosition = uiLayer
continueButton.isHidden = true
// Pros label.
prosLabelNode.position = CGPoint(x: Double(size.width) * descriptionTextPosXReleativeToWidth, y: Double(size.height) * prosDescriptionPosYRelativeToHeight)
prosLabelNode.zPosition = bannerLayer
prosLabel.position = CGPoint.zero
prosLabel.horizontalAlignmentMode = .left
prosLabel.fontName = fontName
prosLabel.fontSize = descriptionFontSize
prosLabel.fontColor = prosTextColor
prosLabel.zPosition = uiLayer
prosLabelNode.addChild(prosLabel)
descriptionBanner.addChild(prosLabelNode)
// Cons label.
consLabelNode.position = CGPoint(x: Double(size.width) * descriptionTextPosXReleativeToWidth, y: Double(size.height) * consDescriptionPosYRelativeToHeight)
consLabelNode.zPosition = bannerLayer
consLabel.position = CGPoint.zero
consLabel.horizontalAlignmentMode = .left
consLabel.fontName = fontName
consLabel.fontSize = descriptionFontSize
consLabel.fontColor = consTextColor
consLabel.zPosition = uiLayer
consLabelNode.addChild(consLabel)
descriptionBanner.addChild(consLabelNode)
// Set different values of boxSizeRelativeToWidth, gridOffsetXRelativeToWidth for different screen width size
let sizeWidth = Double(size.width)
if (sizeWidth > 738.0){
gridOffsetXRelativeToWidth = 0.35
boxSizeRelativeToWidth = 0.066
}
else{
gridOffsetXRelativeToWidth = 0.31
boxSizeRelativeToWidth = 0.084
}
// Calcuate positioning and sizing according to the size of the view.
boxSize = Double(size.width) * boxSizeRelativeToWidth
gridOffsetX = Double(size.width) * gridOffsetXRelativeToWidth + boxSize / 2.0
gridOffsetY = Double(size.height) * gridOffsetYRelativeToHeight + boxSize / 2.0
gridSpacing = Double(size.width) * gridSpacingRelativeToWidth
super.init(size: size)
// Initialize grid.
for x in 0..<gridSizeCount {
gameGrid.append([GuessingBox]())
for y in 0..<gridSizeCount {
let newBox = GuessingBox(xOfGrid: x, yOfGrid: y, isCorrect: false, size: CGSize(width: boxSize, height: boxSize))
// Positioning and sizing.
let xPos = gridOffsetX + (boxSize + gridSpacing) * Double(x)
let yPos = gridOffsetY + (boxSize + gridSpacing) * Double(y)
newBox.position = CGPoint(x: xPos, y: yPos)
newBox.zPosition = gridLayer
gameGrid[x].append(newBox)
}
}
}
// MARK: Functions
// For initializing the nodes of the game.
override func didMove(to view: SKView) {
backgroundColor = SKColor.white
// Add background image.
addChild(backgroundImage)
// Add banners.
addChild(resultBanner)
addChild(descriptionBanner)
// Add score label.
scoreLabel.text = scoreTextPrefix + String(score)
addChild(scoreLabelNode)
// Add continue button.
addChild(continueButton)
// Add boxes.
for gridX in gameGrid {
for box in gridX {
addChild(box)
}
}
if !UserDefaults.tutorialViewed(key: .MineSweeperTutorialViewed) {
// Show tutorial scene. After that, start the game.
tutorialScene = SKTutorialScene(namedImages: tutorialSceneImages, size: size) {
self.newRound()
self.inTutorial = false
}
tutorialScene.position = CGPoint(x: size.width / 2.0, y: size.height / 2.0)
tutorialScene.zPosition = tutorialSceneLayer
addChild(tutorialScene)
} else {
self.newRound()
self.inTutorial = false
}
}
/**
Reset the grid for a new round.
- Parameter: The possibility of the contrceptive method in percentage.
*/
func newRound() {
let possibility = possiblityPercentages[roundCount]
// Reset selected box count.
selectedBoxes = 0
// Successful boxes, grounded to an interger.
let totalBoxCount = gridSizeCount * gridSizeCount
let successfulBoxCount = Int(Double(totalBoxCount) * possibility / 100.0)
let failureBoxCount = totalBoxCount - successfulBoxCount
// An array of true/false values according to the success rate.
var correctBoxes = [Bool](repeating: true, count: successfulBoxCount)
correctBoxes.append(contentsOf: [Bool](repeating: false, count: failureBoxCount))
// Shuffle the array randomly.
correctBoxes.shuffle()
// Configure each box.
for x in 0..<gridSizeCount {
for y in 0..<gridSizeCount {
let currBox = gameGrid[x][y]
// Set whether it is a "success" box or a "failure" box.
currBox.isCorrect = correctBoxes.popLast()!
// Turn to back side.
if currBox.onFrontSide {
currBox.changeSide()
}
// Reset color.
currBox.color = UIColor.white
}
}
roundCount += 1
boxSelected = false
}
func selectBox(box: GuessingBox) {
boxSelected = true
selectedBoxes += 1
// Animations.
let scaleBackAction = SKAction.scale(to: 1.0, duration: self.boxEnlargingDuration)
let waitAction = SKAction.wait(forDuration: boxFlipInterval)
let scaleBackAndWait = SKAction.sequence([scaleBackAction, waitAction])
box.flip(scaleX: boxEnlargingScale) {
// Scale the box back to the original scale.
box.run(scaleBackAndWait) {
// Check if the round should end.
if !box.isCorrect {
// A failure box is chosen.
self.showAllResults(isSuccessful: false)
} else {
// Update score. (With a pop animation)
self.scoreLabel.setScale(self.scoreTextPopScale)
self.score += 1
self.scoreLabel.text = self.scoreTextPrefix + String(self.score)
self.scoreLabel.run(SKAction.scale(to: 1.0, duration: self.scoreTextPopDuraion))
// Check if max selection count is reached.
if self.selectedBoxes == self.selectionMaxCount {
self.showAllResults(isSuccessful: true)
} else {
// Reset boxSelected flag so that player could continue to select the next box.
self.boxSelected = false
}
}
}
}
currBox = nil
}
func showAllResults(isSuccessful: Bool) {
// Show result banner.
resultBanner.texture = isSuccessful ? successBannerTexture : failureBannerTexture
resultBanner.alpha = 0.0
resultBanner.isHidden = false
let waitAction = SKAction.wait(forDuration: showAllBoxesInterval)
let bannerAnimation = SKAction.sequence([fadeInAction, waitAction])
let buttonWaitAction = SKAction.wait(forDuration: buttonWaitDuration)
// Fade in banner.
resultBanner.run(bannerAnimation) {
for x in 0..<self.gridSizeCount {
for y in 0..<self.gridSizeCount {
let currBox = self.gameGrid[x][y]
// Don't darken the selected box.
if currBox.onFrontSide { continue }
// Darkens the color and flip the box.
currBox.run(self.boxDarkening) {
currBox.changeSide()
}
}
}
// Continue button. Change text and fade in.
self.continueButton.alpha = 0.0
self.continueButton.isHidden = false
self.continueButton.run(SKAction.sequence([buttonWaitAction, self.fadeInAction]))
}
}
// Called when "continue button" is pressed under the "result banner".
func showDescription() {
// Fade out result banner.
resultBanner.run(fadeOutAction) {
self.resultBanner.isHidden = true
}
// Fade in description banner.
descriptionBanner.isHidden = false
descriptionBanner.alpha = 0.0
descriptionBanner.run(fadeInAction) {
// Fade in "next round" or "end game" button.
self.continueButton.alpha = 0.0
self.continueButton.isHidden = false
self.continueButton.run(self.fadeInAction)
}
}
// Called when "continue button" is pressed under the "description banner".
func hideDescription() {
// Fade out description banner.
descriptionBanner.run(fadeOutAction) {
self.descriptionBanner.isHidden = true
}
}
// MARK: Touch inputs
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if inTutorial { return }
// Only the first touch is effective.
guard let touch = touches.first else {
return
}
let location = touch.location(in: self)
// Continue button pressed.
if !continueButton.isHidden && continueButton.contains(location) {
// Hide button. Avoid multiple touches.
continueButton.isHidden = true
// Check if it is the button of "result banner" or "description banner".
if !resultBanner.isHidden {
// Button in the result banner. Show description when tapped.
showDescription()
// Record score to update karma points
viewController.score = score
viewController.endGame()
} else if roundCount < possiblityPercentages.count {
// Not the last round, hide description banner and start a new round.
newRound()
hideDescription()
// Record score to update karma points
viewController.score = score
viewController.endGame()
} else {
// Record score to update karma points
viewController.score = score
// End game.
viewController.endGame()
}
}
// Guessing box selected, not animating, and not selected yet.
if let guessingBox = atPoint(location) as? GuessingBox, !boxSelected, !guessingBox.onFrontSide {
currBox = guessingBox
// Perform animation.
guessingBox.removeAction(forKey: boxShrinkingKey)
guessingBox.run(SKAction.scale(to: boxEnlargingScale, duration: boxEnlargingDuration), withKey: boxEnlargingKey)
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if inTutorial { return }
// Only the first touch is effective.
guard let touch = touches.first else {
return
}
let location = touch.location(in: self)
// Guessing box selected, equals to the current selected box, and no box is selected yet.
if let guessingBox = atPoint(location) as? GuessingBox, guessingBox == currBox, !boxSelected {
selectBox(box: guessingBox)
} else if let box = currBox {
// Animate (shrink) back the card.
box.removeAction(forKey: boxEnlargingKey)
box.run(SKAction.scale(to: 1.0, duration: boxEnlargingDuration), withKey: boxEnlargingKey)
currBox = nil
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) not implemented.")
}
}
| d9b8f1cc1bf87b2e376b8ceaf21f7cba | 37.006024 | 211 | 0.60094 | false | false | false | false |
ricardorauber/iOS-Swift | refs/heads/master | iOS-Swift.playground/Pages/Constants and Variables.xcplaygroundpage/Contents.swift | mit | 1 | //: ## Constants and Variables
//: ----
//: [Previous](@previous)
import Foundation
//: Constants
let constant = "My first constant!"
//: Variables
var variable = "My first variable!"
var r = 250.0, g = 100.0, b = 210.0
//: Type Annotations
var hello: String
hello = "Hello!"
//: Emoji Names
//: - Emoji shortcut: control + command + space
let 😎 = ":)"
//: Printing
print(😎)
print("Using a string with a constant or variable: \(hello) \(😎)")
//: Comments
// One line comment
/*
Multiple
Lines
Comment
*/
//: Integer
let intConstant1 = 10
let intConstant2: Int = 10
let uIntConstant: UInt = 20
let uInt8Constant: UInt8 = 8
let uInt16Constant: UInt16 = 16
let uInt32Constant: UInt32 = 32
let uInt64Constant: UInt64 = 21
//: Float
let floatConstant: Float = 10.5
//: Double
let doubleConstant1 = 30.7
let doubleConstant2: Double = 30.7
//: Boolean
let trueConstant = true
let falseConstant: Bool = false
let anotherOne = !trueConstant
//: String
let stringConstant1 = "You already know that, right?"
let stringConstant2: String = "Yes, you know!"
//: Tuples
let tupleWith2Values = (100, "A message")
let tupleWith2NamedValues = (number: 200, text: "Another Message")
let (intValue, stringValue) = tupleWith2Values
let (onlyTheIntValue, _) = tupleWith2NamedValues
let (_, onlyTheStringValue) = tupleWith2NamedValues
let standardConstantFromTuple = tupleWith2Values.0
let standardConstantFromNamedTuple = tupleWith2NamedValues.text
print(
intValue,
stringValue,
onlyTheIntValue,
onlyTheStringValue,
standardConstantFromTuple,
standardConstantFromNamedTuple
)
//: Type aliases
typealias MyInt = Int8
var customAlias1 = MyInt.min
var customAlias2 = MyInt.max
//: Converting types
let doubleToIntConstant = Int(45.32)
let intToDoubleConstant = Double(50)
//: [Next](@next)
| 3976e04bae7e5ac197098997e8dd872b | 17.029703 | 66 | 0.716639 | false | false | false | false |
e78l/swift-corelibs-foundation | refs/heads/master | Foundation/NSPlatform.swift | apache-2.0 | 2 | // 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
//
#if os(macOS) || os(iOS)
fileprivate let _NSPageSize = Int(vm_page_size)
#elseif os(Linux) || os(Android)
fileprivate let _NSPageSize = Int(getpagesize())
#elseif os(Windows)
import WinSDK
fileprivate var _NSPageSize: Int {
var siInfo: SYSTEM_INFO = SYSTEM_INFO()
GetSystemInfo(&siInfo)
return Int(siInfo.dwPageSize)
}
#endif
public func NSPageSize() -> Int {
return _NSPageSize
}
public func NSRoundUpToMultipleOfPageSize(_ size: Int) -> Int {
let ps = NSPageSize()
return (size + ps - 1) & ~(ps - 1)
}
public func NSRoundDownToMultipleOfPageSize(_ size: Int) -> Int {
return size & ~(NSPageSize() - 1)
}
func NSCopyMemoryPages(_ source: UnsafeRawPointer, _ dest: UnsafeMutableRawPointer, _ bytes: Int) {
#if os(macOS) || os(iOS)
if vm_copy(mach_task_self_, vm_address_t(bitPattern: source), vm_size_t(bytes), vm_address_t(bitPattern: dest)) != KERN_SUCCESS {
memmove(dest, source, bytes)
}
#else
memmove(dest, source, bytes)
#endif
}
| 212e778f07967b70cdcd99f034d015be | 28.688889 | 133 | 0.700599 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.