repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
MjAbuz/SwiftHamcrest | Hamcrest/OperatorMatchers.swift | 1 | 2081 | public func assertThat(resultDescription: MatchResultDescription,
file: String = __FILE__, line: UInt = __LINE__) -> String {
return reportResult(resultDescription.result, file: file, line: line)
}
public struct MatchResultDescription {
let result: String?
init(result: String?) {
self.result = result
}
init<T>(@autoclosure value: () -> T, matcher: Matcher<T>) {
self.result = applyMatcher(matcher, toValue: value)
}
}
public func === <T: AnyObject>(value: T, expectedValue: T) -> MatchResultDescription {
return MatchResultDescription(value: value, matcher: sameInstance(expectedValue))
}
public func == <T: Equatable>(value: T, expectedValue: T) -> MatchResultDescription {
return MatchResultDescription(value: value, matcher: equalTo(expectedValue))
}
public func > <T: Comparable>(value: T, expectedValue: T) -> MatchResultDescription {
return MatchResultDescription(value: value, matcher: greaterThan(expectedValue))
}
public func >= <T: Comparable>(value: T, expectedValue: T) -> MatchResultDescription {
return MatchResultDescription(value: value, matcher: greaterThanOrEqualTo(expectedValue))
}
public func < <T: Comparable>(value: T, expectedValue: T) -> MatchResultDescription {
return MatchResultDescription(value: value, matcher: lessThan(expectedValue))
}
public func <= <T: Comparable>(value: T, expectedValue: T) -> MatchResultDescription {
return MatchResultDescription(value: value, matcher: lessThanOrEqualTo(expectedValue))
}
public func && (lhs: MatchResultDescription, rhs: MatchResultDescription)
-> MatchResultDescription {
switch (lhs.result, rhs.result) {
case (nil, nil):
return MatchResultDescription(result: .None)
case let (result?, nil):
return MatchResultDescription(result: result)
case let (nil, result?):
return MatchResultDescription(result: result)
case let (lhsResult?, rhsResult?):
let result = "\(lhsResult) and \(rhsResult)"
return MatchResultDescription(result: result)
}
}
| bsd-3-clause | 64f746dd7a5a470ee3de3aa372148b85 | 36.836364 | 93 | 0.70495 | 4.42766 | false | false | false | false |
NielsKoole/RealmSugar | RealmSugar/Source/Object+Notify.swift | 1 | 1869 | //
// Object+Notify.swift
// RealmSugar
//
// Created by Niels Koole on 20/04/2017.
// Copyright © 2017 Niels Koole. All rights reserved.
//
import Foundation
import RealmSwift
// MARK: - Implement extension
extension Object: NotifyRealmObject { }
// MARK: - Protocol definition + implementation
public protocol NotifyRealmObject: class { }
extension NotifyRealmObject where Self: Object {
public func fireAndNotify(for property: String, handler: @escaping ((Self) -> Void)) -> NotificationToken {
// Return notification block
return fireAndNotify(for: [property], handler: handler)
}
public func fireAndNotify(for properties: [String]? = nil, handler: @escaping ((Self) -> Void)) -> NotificationToken {
// Fire right away
handler(self)
// Return notification block
return notify(for: properties, handler: handler)
}
public func notify(for property: String, handler: @escaping ((Self) -> Void)) -> NotificationToken {
return notify(for: [property], handler: handler)
}
public func notify(for properties: [String]? = nil, handler: @escaping ((Self) -> Void)) -> NotificationToken {
return observe({ [weak self] (change) in
guard let s = self else { return }
switch change {
case .change(let changedProperties):
if let properties = properties {
let mapped = changedProperties.map { $0.name }
let foundProps = mapped.filter { properties.index(of: $0) != nil }
if foundProps.isEmpty == false {
handler(s)
}
} else {
handler(s)
}
default: break
}
})
}
}
| apache-2.0 | 180db2f47e68480207d5ef700c316a4b | 29.622951 | 122 | 0.56531 | 4.802057 | false | false | false | false |
imclean/JLDishWashers | JLDishwasher/Skus.swift | 1 | 3743 | //
// Skus.swift
// JLDishwasher
//
// Created by Iain McLean on 21/12/2016.
// Copyright © 2016 Iain McLean. All rights reserved.
//
import Foundation
public class Skus {
public var id : Int?
public var shortSkuTitle : String?
public var d2cDeliveryLeadTime : String?
public var unitPriceInfo : UnitPriceInfo?
public var sizeHeadline : String?
public var color : String?
public var size : String?
public var availability : Availability?
public var price : Price?
public var code : Int?
public var skuTitle : String?
public var leadTime : String?
public var media : Media?
public var brandName : String?
public var swatchUrl : String?
/**
Returns an array of models based on given dictionary.
Sample usage:
let skus_list = Skus.modelsFromDictionaryArray(someDictionaryArrayFromJSON)
- parameter array: NSArray from JSON dictionary.
- returns: Array of Skus Instances.
*/
public class func modelsFromDictionaryArray(array:NSArray) -> [Skus] {
var models:[Skus] = []
for item in array {
models.append(Skus(dictionary: item as! NSDictionary)!)
}
return models
}
/**
Constructs the object based on the given dictionary.
Sample usage:
let skus = Skus(someDictionaryFromJSON)
- parameter dictionary: NSDictionary from JSON.
- returns: Skus Instance.
*/
required public init?(dictionary: NSDictionary) {
id = dictionary["id"] as? Int
shortSkuTitle = dictionary["shortSkuTitle"] as? String
d2cDeliveryLeadTime = dictionary["d2cDeliveryLeadTime"] as? String
if (dictionary["unitPriceInfo"] != nil) { unitPriceInfo = UnitPriceInfo(dictionary: dictionary["unitPriceInfo"] as! NSDictionary) }
sizeHeadline = dictionary["sizeHeadline"] as? String
color = dictionary["color"] as? String
size = dictionary["size"] as? String
if (dictionary["availability"] != nil) { availability = Availability(dictionary: dictionary["availability"] as! NSDictionary) }
if (dictionary["price"] != nil) { price = Price(dictionary: dictionary["price"] as! NSDictionary) }
code = dictionary["code"] as? Int
skuTitle = dictionary["skuTitle"] as? String
leadTime = dictionary["leadTime"] as? String
if (dictionary["media"] != nil) { media = Media(dictionary: dictionary["media"] as! NSDictionary) }
brandName = dictionary["brandName"] as? String
swatchUrl = dictionary["swatchUrl"] as? String
}
/**
Returns the dictionary representation for the current instance.
- returns: NSDictionary.
*/
public func dictionaryRepresentation() -> NSDictionary {
let dictionary = NSMutableDictionary()
dictionary.setValue(self.id, forKey: "id")
dictionary.setValue(self.shortSkuTitle, forKey: "shortSkuTitle")
dictionary.setValue(self.d2cDeliveryLeadTime, forKey: "d2cDeliveryLeadTime")
dictionary.setValue(self.unitPriceInfo?.dictionaryRepresentation(), forKey: "unitPriceInfo")
dictionary.setValue(self.sizeHeadline, forKey: "sizeHeadline")
dictionary.setValue(self.color, forKey: "color")
dictionary.setValue(self.size, forKey: "size")
dictionary.setValue(self.availability?.dictionaryRepresentation(), forKey: "availability")
dictionary.setValue(self.price?.dictionaryRepresentation(), forKey: "price")
dictionary.setValue(self.code, forKey: "code")
dictionary.setValue(self.skuTitle, forKey: "skuTitle")
dictionary.setValue(self.leadTime, forKey: "leadTime")
dictionary.setValue(self.media?.dictionaryRepresentation(), forKey: "media")
dictionary.setValue(self.brandName, forKey: "brandName")
dictionary.setValue(self.swatchUrl, forKey: "swatchUrl")
return dictionary
}
}
| gpl-3.0 | e600a35632c8ab0c8926588eb9ece42a | 34.980769 | 133 | 0.707108 | 3.989339 | false | false | false | false |
the-grid/Portal | PortalTests/Fixtures/LanguageFixtures.swift | 1 | 357 | import Argo
import Portal
let languageResponseBody = "en"
let languageJson = JSON.String(languageResponseBody)
let languageModel = Language(rawValue: languageResponseBody)!
let updatedLanguageResponseBody = "la"
let updatedLanguageJson = JSON.String(updatedLanguageResponseBody)
let updatedLanguageModel = Language(rawValue: updatedLanguageResponseBody)!
| mit | a797ddc4cde57aad61a01d244852a401 | 34.7 | 75 | 0.843137 | 4.636364 | false | false | false | false |
networkextension/SFSocket | SFSocket/SFData.swift | 1 | 2059 | //
// SFData.swift
// Surf
//
// Created by 孔祥波 on 11/10/16.
// Copyright © 2016 yarshure. All rights reserved.
//
import Foundation
protocol BinaryConvertible
{
init()
}
//extension UInt8 : BinaryConvertible {}
extension UInt16 : BinaryConvertible {}
extension UInt32 : BinaryConvertible {}
extension UInt64 : BinaryConvertible {}
extension Double : BinaryConvertible {} //<T:BinaryConvertible>:
public class SFData:CustomStringConvertible {
public var data = Data()
public var description: String {
return (data as NSData).description
}
public init() {
}
// mutating func append(_ v:T) {
// var value = v
// let storage = withUnsafePointer(to: &value) {
// Data(bytes: UnsafePointer($0), count: MemoryLayout.size(ofValue: v))
// }
// data.append(storage)
// }
public func append(_ v:UInt8){
data.append(v)
}
public func append(_ v:Data){
data.append(v)
}
public func append(_ v:UInt32) {
var value = v
let storage = withUnsafePointer(to: &value) {
Data(bytes: UnsafePointer($0), count: MemoryLayout.size(ofValue: v))
}
data.append(storage)
}
public func append(_ newElement: CChar) {
let v = UInt8(bitPattern: newElement)
data.append(v)
}
public func append(_ v:String){
let storage = v.data(using: .utf8)
data.append(storage!)
}
public func append(_ v:UInt16) {
var value = v
let storage = withUnsafePointer(to: &value) {
Data(bytes: UnsafePointer($0), count: MemoryLayout.size(ofValue: v))
}
data.append(storage)
}
public func append(_ v:Int16) {
var value = v
let storage = withUnsafePointer(to: &value) {
Data(bytes: UnsafePointer($0), count: MemoryLayout.size(ofValue: v))
}
data.append(storage)
}
public func length(_ r:Range<Data.Index>) ->Int {
return r.upperBound - r.lowerBound
}
}
| bsd-3-clause | aff9d5d3016d14712a486a37556962ba | 26.36 | 82 | 0.592105 | 3.93858 | false | false | false | false |
jackTang11/TlySina | TlySina/TlySina/Classes/View(视图和控制器)/Main/NewFeaure/WBWelcomView.swift | 1 | 1772 | //
// WBWelcomView.swift
// TlySina
//
// Created by jack_tang on 17/5/2.
// Copyright © 2017年 jack_tang. All rights reserved.
//
import UIKit
class WBWelcomView: UIView {
// class func welcomView() -> WBWelcomView{
// let nib = UINib(nibName: "WBWelcomView", bundle: nil)
// let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBWelcomView
// v.frame = UIScreen.main.bounds
// return v
//
// }
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var nameLable: UILabel!
@IBOutlet weak var bottomNum: NSLayoutConstraint!
class func welcomView() -> WBWelcomView{
let v = Bundle.main.loadNibNamed("WBWelcomView", owner: nil, options: nil)?[0] as! WBWelcomView
v.frame = UIScreen.main.bounds
return v
}
override func didMoveToWindow() {
super.didMoveToWindow()
self.layoutIfNeeded()
UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: {
self.bottomNum.constant = self.bounds.size.height - 200
self.layoutIfNeeded()
}) { (_) in
UIView.animate(withDuration: 1, animations: {
self.nameLable.alpha = 1
self.layoutIfNeeded()
}, completion: { (_) in
self.removeFromSuperview()
})
}
print(#function)
}
override func awakeFromNib() {
super.awakeFromNib()
print(#function)
iconView.layer.cornerRadius = iconView.bounds.size.height*0.5
iconView.layer.masksToBounds = true
}
}
| apache-2.0 | 2bac5459be7f92e8f47199477aa377b1 | 24.271429 | 133 | 0.563595 | 4.17217 | false | false | false | false |
crossroadlabs/Boilerplate | Sources/Boilerplate/Container.swift | 2 | 2193 | //===--- Container.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//===----------------------------------------------------------------------===//
import Foundation
import Result
postfix operator ^
postfix operator ^!
postfix operator ^!!
postfix operator ^%
public protocol ContainerType {
associatedtype Value
func withdraw() throws -> Value
}
public postfix func ^!<A, T : ContainerType>(container:T) throws -> A where T.Value == A {
return try container.withdraw()
}
/// Never use. Pure EVIL ]:->
public postfix func ^!!<A, T : ContainerType>(container:T) -> A where T.Value == A {
return try! container.withdraw()
}
public postfix func ^<A, T : ContainerType>(container:T) -> A? where T.Value == A {
return try? container.withdraw()
}
public postfix func ^%<A, T : ContainerType>(container:T) -> Result<A, AnyError> where T.Value == A {
return materializeAny {
try container.withdraw()
}
}
public protocol ContainerWithErrorType : ContainerType {
associatedtype Error : Swift.Error
func withdrawResult() -> Result<Value, Error>
}
public extension ContainerWithErrorType {
func withdraw() throws -> Value {
return try withdrawResult().dematerialize()
}
}
public extension ContainerWithErrorType where Error : AnyErrorProtocol {
func withdraw() throws -> Value {
return try withdrawResult().dematerializeAny()
}
}
public postfix func ^%<A, E : Error, T : ContainerWithErrorType>(container:T) -> Result<A, E> where T.Value == A, T.Error == E {
return container.withdrawResult()
}
| apache-2.0 | 1f05e497237d924efe43519cef59d088 | 30.328571 | 128 | 0.657091 | 4.266537 | false | false | false | false |
TarangKhanna/Inspirator | WorkoutMotivation/PicUpload.swift | 2 | 16357 | //
// PicUpload.swift
// WorkoutMotivation
//
// Created by Tarang khanna on 6/10/15.
// Copyright (c) 2015 Tarang khanna. All rights reserved.
//
import UIKit
import CoreImage
import MobileCoreServices
var imagePicker: UIImagePickerController!
var CIFilterNames = [
"CIPhotoEffectChrome",
"CIPhotoEffectFade",
"CIPhotoEffectInstant",
"CIPhotoEffectNoir",
"CIPhotoEffectProcess",
"CIPhotoEffectTonal",
"CIPhotoEffectTransfer",
"CISepiaTone"
]
var filterButton = UIButton()
class PicUpload: UIViewController,UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet var uploadBtn: MKButton!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var originalImage: UIImageView!
@IBOutlet weak var imageToFilter: UIImageView!
@IBOutlet weak var filtersScrollView: UIScrollView!
let tapRec = UITapGestureRecognizer()
@IBOutlet var text: MKTextField!
var passedGroupPic = "general"
override func prefersStatusBarHidden() -> Bool {
return true
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
override func viewWillAppear(animated: Bool) {
// originalImage.contentMode = UIViewContentMode.Center
//
// imageToFilter.contentMode = UIViewContentMode.Center
//uploadBtn.hidden = true
text.hidden = true
}
func unhide() {
uploadBtn.hidden = false
//text.hidden = false
//textLabel.bringSubviewToFront(view)
UIView.animateWithDuration(1, animations: {self.text.hidden = false})
}
func displayAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction((UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
})))
self.presentViewController(alert, animated: true, completion: nil)
}
var activityIndicator = UIActivityIndicatorView()
@IBOutlet var imageToPost: UIImageView!
@IBAction func chooseImage(sender: AnyObject) {
let image = UIImagePickerController()
image.delegate = self
image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
image.allowsEditing = false
self.presentViewController(image, animated: true, completion: nil)
//imageToFilter.hidden = false
}
@IBAction func camera(sender: AnyObject) {
// var picker = UIImagePickerController()
// picker.allowsEditing = false
// picker.sourceType = UIImagePickerControllerSourceType.Camera
// picker.delegate = self
// picker.allowsEditing = false
// picker.cameraCaptureMode = .Photo
// picker.mediaTypes = [kUTTypeImage as String]
// presentViewController(picker, animated: true, completion: nil)
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .Camera
presentViewController(imagePicker, animated: true, completion: nil)
}
//
// func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
// imagePicker.dismissViewControllerAnimated(true, completion: nil)
// imageToPost.image = info[UIImagePickerControllerOriginalImage] as? UIImage
// }
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
print(image)
imageToFilter.hidden = true
var counter = 1
self.dismissViewControllerAnimated(true, completion:nil)
imageToPost.image = image
var xCoord: CGFloat = 5
let yCoord: CGFloat = 5
let buttonWidth:CGFloat = 70
let buttonHeight: CGFloat = 70
let gapBetweenButtons: CGFloat = 5
// Items Counter
var itemCount = 0
for itemCount = 0; itemCount < CIFilterNames.count; ++itemCount {
// Button properties
filterButton = UIButton(type:UIButtonType.Custom)
filterButton.frame = CGRectMake(xCoord, yCoord, buttonWidth, buttonHeight)
filterButton.tag = itemCount
filterButton.showsTouchWhenHighlighted = true
filterButton.addTarget(self, action: "filterButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
filterButton.layer.cornerRadius = 6
filterButton.clipsToBounds = true
// Create filters for each button
let ciContext = CIContext(options: nil)
let coreImage = CIImage(image: originalImage.image!)
let filter = CIFilter(name: "\(CIFilterNames[itemCount])" )
filter!.setDefaults()
filter!.setValue(coreImage, forKey: kCIInputImageKey)
let filteredImageData = filter!.valueForKey(kCIOutputImageKey) as! CIImage
let filteredImageRef = ciContext.createCGImage(filteredImageData, fromRect: filteredImageData.extent)
let imageForButton = UIImage(CGImage: filteredImageRef);
// Assign filtered image to the button
filterButton.setBackgroundImage(imageForButton, forState: UIControlState.Normal)
// Add Buttons in the Scroll View
xCoord += buttonWidth + gapBetweenButtons
if counter >= 6 {
break
} else {
filtersScrollView.addSubview(filterButton)
}
counter++
} // END LOOP ==========================================================
// Resize Scroll View
filtersScrollView.contentSize = CGSizeMake(buttonWidth * CGFloat(itemCount+1), yCoord)
unhide()
}
override func viewDidLoad() {
super.viewDidLoad()
tapRec.addTarget(self, action: "tappedView")
self.view.addGestureRecognizer(tapRec)
self.view.userInteractionEnabled = true
text.layer.borderColor = UIColor.clearColor().CGColor
text.floatingPlaceholderEnabled = true
text.placeholder = "text.."
text.tintColor = UIColor.MKColor.Blue
text.rippleLocation = .Right
text.cornerRadius = 0
text.bottomBorderEnabled = true
text.attributedPlaceholder = NSAttributedString(string:"text..",
attributes:[NSForegroundColorAttributeName: UIColor.orangeColor()])
text.delegate = self
}
// FILTER BUTTON ACTION
func filterButtonTapped(sender: UIButton) {
let button = sender as UIButton
imageToFilter.hidden = false
imageToFilter.image = button.backgroundImageForState(UIControlState.Normal)
imageToPost.image = imageToFilter.image
}
@IBAction func savePicButton(sender: AnyObject) {
// Save the image into camera roll
UIImageWriteToSavedPhotosAlbum(imageToFilter.image!, nil, nil, nil)
let alert = UIAlertView(title: "Filters",
message: "Your image has been saved to Photo Library",
delegate: self,
cancelButtonTitle: "Ok")
alert.show()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
}
func tappedView() {
// if selected image
unhide()
}
@IBAction func uploadImage(sender: AnyObject) {
unhide()
// profile pic
activityIndicator = UIActivityIndicatorView(frame: self.view.frame)
activityIndicator.backgroundColor = UIColor(white: 1.0, alpha: 0.5)
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
let person = PFObject(className:"Person")
person["score"] = 0
person["username"] = PFUser.currentUser()?.username
//person["admin"] = true
person["group"] = passedGroupPic
if text.text == nil {
person["text"] = " "
} else {
person["text"] = text.text
}
person["startTime"] = CFAbsoluteTimeGetCurrent()
person["votedBy"] = []
if let imageData = imageToPost.image!.mediumQualityJPEGNSData as NSData? { // choose low to reduce by 1/8
var imageSize = Float(imageData.length)
imageSize = imageSize/(1024*1024) // in Mb
print("Image size is \(imageSize)Mb")
if imageSize < 5 {
if let imageFile = PFFile(name: "image.png", data: imageData) as PFFile? {
person["imageFile"] = imageFile
person.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if (success) {
//self.retrieve()
self.performSegueWithIdentifier("picUploaded", sender: self)
print("posted!")
self.text.text = "" // empty it
} else {
print("Couldn't post!")
SCLAlertView().showWarning("Error Posting", subTitle: "Check Your Internet Connection.")
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
}
}
}
} else {
SCLAlertView().showWarning("Error Posting", subTitle: "File Too Big")
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
}
} else {
SCLAlertView().showWarning("No Image", subTitle: "Select An Image to Upload.")
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
}
// activityIndicator = UIActivityIndicatorView(frame: self.view.frame)
// activityIndicator.backgroundColor = UIColor(white: 1.0, alpha: 0.5)
// activityIndicator.center = self.view.center
// activityIndicator.hidesWhenStopped = true
// activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
// view.addSubview(activityIndicator)
// activityIndicator.startAnimating()
//
// UIApplication.sharedApplication().beginIgnoringInteractionEvents()
//
// var post = PFObject(className: "Post")
//
// //post["message"] = message.text
//
// post["userId"] = PFUser.currentUser()!.objectId!
//
// //post["text"] = PFUser.currentUser()?.text
//
// let imageData = UIImagePNGRepresentation(imageToPost.image)
//
// let imageFile = PFFile(name: "image.png", data: imageData)
//
// post["imageFile"] = imageFile
//
// post.saveInBackgroundWithBlock{(success, error) -> Void in
//
// self.activityIndicator.stopAnimating()
//
// UIApplication.sharedApplication().endIgnoringInteractionEvents()
//
// if error == nil {
//
// self.displayAlert("Image Posted!", message: "Your image has been posted successfully")
//
// self.imageToPost.image = UIImage(named: "315px-Blank_woman_placeholder.svg.png")
//
// // self.message.text = ""
//
// } else {
//
// self.displayAlert("Could not post image", message: "Please try again later")
//
// }
//
// }
//
// }
//
// override func didReceiveMemoryWarning() {
// super.didReceiveMemoryWarning()
// // Dispose of any resources that can be recreated.
}
}
extension UIImage {
var highestQualityJPEGNSData:NSData { return UIImageJPEGRepresentation(self, 1.0)! }
var highQualityJPEGNSData:NSData { return UIImageJPEGRepresentation(self, 0.75)!}
var mediumQualityJPEGNSData:NSData { return UIImageJPEGRepresentation(self, 0.5)! }
var lowQualityJPEGNSData:NSData { return UIImageJPEGRepresentation(self, 0.25)!}
var lowestQualityJPEGNSData:NSData { return UIImageJPEGRepresentation(self, 0.0)! }
}
| apache-2.0 | f632d349c29ab6efba63ba53308fbf45 | 24.438569 | 142 | 0.49141 | 6.843933 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/DynamicButton/Sources/DynamicButtonStyles/DynamicButtonStyleCaretRight.swift | 3 | 2130 | /*
* DynamicButton
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.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 UIKit
/// Left caret style: ›
final public class DynamicButtonStyleCaretRight: DynamicButtonStyle {
convenience required public init(center: CGPoint, size: CGFloat, offset: CGPoint, lineWidth: CGFloat) {
let thirdSize = size / 3
let sixthSize = size / 6
let a = CGPoint(x: center.x + sixthSize, y: center.y)
let b = CGPoint(x: center.x - sixthSize, y: center.y + thirdSize)
let c = CGPoint(x: center.x - sixthSize, y: center.y - thirdSize)
let offsetFromCenter = PathHelper.gravityPointOffset(fromCenter: center, a: a, b: b, c: c)
let p1 = PathHelper.line(from: a, to: b, offset: offsetFromCenter)
let p2 = PathHelper.line(from: a, to: c, offset: offsetFromCenter)
self.init(pathVector: (p1, p1, p2, p2))
}
// MARK: - Conforming the CustomStringConvertible Protocol
/// A textual representation of "Caret Right" style.
public override var description: String {
return "Caret Right"
}
}
| mit | 2090f4eb357dd76636a43ad7b17ae4e3 | 39.150943 | 105 | 0.728853 | 4.100193 | false | false | false | false |
rsyncOSX/RsyncOSX | RsyncOSX/InterruptProcess.swift | 1 | 912 | //
// InterruptProcess.swift
// RsyncOSX
//
// Created by Thomas Evensen on 18/06/2020.
// Copyright © 2020 Thomas Evensen. All rights reserved.
//
import Foundation
struct InterruptProcess {
// Enable and disable select profile
weak var profilepopupDelegate: DisableEnablePopupSelectProfile?
init() {
profilepopupDelegate = SharedReference.shared.getvcref(viewcontroller: .vctabmain) as? ViewControllerMain
profilepopupDelegate?.enableselectpopupprofile()
guard SharedReference.shared.process != nil else { return }
let output = OutputfromProcess()
let string = "Interrupted: " + Date().long_localized_string_from_date()
output.addlinefromoutput(str: string)
_ = Logfile(TrimTwo(output.getOutput() ?? []).trimmeddata, error: true)
SharedReference.shared.process?.interrupt()
SharedReference.shared.process = nil
}
}
| mit | 50ca7692a4603229ecf98a60f969759d | 35.44 | 113 | 0.703622 | 4.217593 | false | false | false | false |
Kawoou/KWDrawerController | DrawerController/DrawerController.swift | 1 | 45160 | /*
The MIT License (MIT)
Copyright (c) 2017 Kawoou (Jungwon An)
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
@objc
public protocol DrawerControllerDelegate {
@objc optional func drawerDidAnimation(drawerController: DrawerController, side: DrawerSide, percentage: Float)
@objc optional func drawerDidBeganAnimation(drawerController: DrawerController, side: DrawerSide)
@objc optional func drawerWillFinishAnimation(drawerController: DrawerController, side: DrawerSide)
@objc optional func drawerWillCancelAnimation(drawerController: DrawerController, side: DrawerSide)
@objc optional func drawerDidFinishAnimation(drawerController: DrawerController, side: DrawerSide)
@objc optional func drawerDidCancelAnimation(drawerController: DrawerController, side: DrawerSide)
@objc optional func drawerWillOpenSide(drawerController: DrawerController, side: DrawerSide)
@objc optional func drawerWillCloseSide(drawerController: DrawerController, side: DrawerSide)
@objc optional func drawerDidOpenSide(drawerController: DrawerController, side: DrawerSide)
@objc optional func drawerDidCloseSide(drawerController: DrawerController, side: DrawerSide)
}
open class DrawerController: UIViewController, UIGestureRecognizerDelegate {
// MARK: - Define
static let OverflowPercentage: Float = 1.06
static let GestureArea: Float = 40.0
// MARK: - Property
@IBOutlet
public weak var delegate: DrawerControllerDelegate?
@IBInspectable
public var drawerWidth: Float {
get {
return internalDrawerWidth
}
set {
let updateList = contentMap
.filter { $0.value.drawerWidth != newValue }
.map { $0.key }
for side in updateList {
setDrawerWidth(newValue, for: side)
}
internalDrawerWidth = newValue
}
}
public var gestureSenstivity: DrawerGestureSensitivity = .normal
public var options: DrawerOption = DrawerOption()
@IBInspectable
public var shadowRadius: CGFloat = 10.0 {
didSet { shadowView.layer.shadowRadius = shadowRadius }
}
@IBInspectable
public var shadowOpacity: Float = 0.8 {
didSet { shadowView.layer.shadowOpacity = shadowOpacity }
}
@IBInspectable
public var fadeColor: UIColor = UIColor(white: 0, alpha: 0.8) {
didSet { fadeView.backgroundColor = fadeColor }
}
@IBInspectable
public var isEnableAutoSwitchDirection: Bool = false
@IBInspectable
public var animationDuration: TimeInterval = 0.35
@IBInspectable
public var mainSegueIdentifier: String?
@IBInspectable
public var leftSegueIdentifier: String?
@IBInspectable
public var rightSegueIdentifier: String?
public private(set) var drawerSide: DrawerSide = .none
public private(set) var isAnimating: Bool = false
public private(set) var panGestureRecognizer: UIPanGestureRecognizer?
// MARK: - Public
/// Options
public func getSideOption(for side: DrawerSide) -> DrawerOption? {
guard let content = contentMap[side] else { return nil }
return content.option
}
/// Absolute
public func getAbsolute(for side: DrawerSide) -> Bool {
guard let content = contentMap[side] else { return false }
return content.isAbsolute
}
public func setAbsolute(_ isAbsolute: Bool, for side: DrawerSide) {
guard let content = contentMap[side] else { return }
if content.isAbsolute != isAbsolute && drawerSide == side && side != .none {
closeSide() {
content.isAbsolute = isAbsolute
}
} else {
content.isAbsolute = isAbsolute
}
}
/// Bring to Front
public func getBringToFront(for side: DrawerSide) -> Bool {
guard let content = contentMap[side] else { return false }
return content.isBringToFront
}
public func setBringToFront(_ isBringToFront: Bool, for side: DrawerSide) {
guard let content = contentMap[side] else { return }
content.isBringToFront = isBringToFront
}
/// Transition
public func getTransition(for side: DrawerSide) -> DrawerTransition? {
guard let content = contentMap[side] else { return nil }
return content.transition
}
public func setTransition(_ transition: DrawerTransition, for side: DrawerSide) {
guard let content = contentMap[side] else { return }
content.transition = transition
guard !isAnimating else { return }
let percent: Float = drawerSide == .none ? 0.0 : 1.0
willBeginAnimate(side: drawerSide)
didBeginAnimate(side: drawerSide)
willAnimate(side: drawerSide, percent: percent)
didAnimate(side: drawerSide, percent: percent)
content.startTransition(side: drawerSide)
content.transition(
side: drawerSide,
percentage: calcPercentage(side: side, moveSide: drawerSide, percent),
viewRect: calcViewRect(content: content)
)
content.endTransition(side: drawerSide)
willFinishAnimate(side: drawerSide, percent: percent)
didFinishAnimate(side: drawerSide, percent: percent)
}
public func getOverflowTransition(for side: DrawerSide) -> DrawerTransition? {
guard let content = contentMap[side] else { return nil }
return content.overflowTransition
}
public func setOverflowTransition(_ transition: DrawerTransition, for side: DrawerSide) {
guard let content = contentMap[side] else { return }
content.overflowTransition = transition
}
/// Animator
public func getAnimator(for side: DrawerSide) -> DrawerAnimator? {
guard let content = contentMap[side] else { return nil }
return content.animator
}
public func setAnimator(_ animator: DrawerAnimator, for side: DrawerSide) {
guard let content = contentMap[side] else { return }
content.animator = animator
}
/// Drawer Width
public func getDrawerWidth(for side: DrawerSide) -> Float? {
guard let content = contentMap[side] else { return nil }
return content.drawerWidth
}
public func setDrawerWidth(_ drawerWidth: Float, for side: DrawerSide) {
guard let content = contentMap[side] else { return }
guard drawerSide == side else {
content.drawerWidth = drawerWidth
return
}
let oldDrawerWidth = content.drawerWidth
let variationWidth = drawerWidth - oldDrawerWidth
content.animator.doAnimate(
duration: animationDuration,
animations: { percentage in
content.drawerWidth = oldDrawerWidth + variationWidth * percentage
},
completion: { _ in }
)
}
/// View controller
public func getViewController(for side: DrawerSide) -> UIViewController? {
return contentMap[side]?.viewController
}
public func setViewController(_ viewController: UIViewController?, for side: DrawerSide) {
guard isEnable() else { return }
guard let controller = viewController else {
removeSide(side)
return
}
addSide(side, viewController: controller)
}
/// Actions
@IBAction func openLeftSide(_ sender: Any) {
openSide(.left, completion: nil)
}
@IBAction func openRightSide(_ sender: Any) {
openSide(.right, completion: nil)
}
public func openSide(_ side: DrawerSide, completion: (()->())? = nil) {
/// Golden-Path
guard isEnable(), !isAnimating else { return }
delegate?.drawerWillOpenSide?(drawerController: self, side: side)
if drawerSide != .none && side != drawerSide {
closeSide { [weak self] in
self?.openSide(side, completion: completion)
}
return
}
isAnimating = true
willBeginAnimate(side: side)
didBeginAnimate(side: side)
willAnimate(side: side, percent: 0.0)
/// Check available of animation.
guard isAnimation() else {
didAnimate(side: side, percent: 1.0)
willFinishAnimate(side: side, percent: 1.0)
didFinishAnimate(side: side, percent: 1.0)
isAnimating = false
delegate?.drawerDidOpenSide?(drawerController: self, side: side)
completion?()
return
}
if gestureLastPercentage >= 0.0 {
didAnimate(side: side, percent: gestureLastPercentage)
} else {
didAnimate(side: side, percent: 0.0)
}
if let content = contentMap[side] {
content.animator.doAnimate(
duration: animationDuration,
animations: { [weak self] percent in
guard let ss = self else { return }
if ss.gestureLastPercentage >= 0.0 {
let invertLastPercent = 1.0 - ss.gestureLastPercentage
ss.didAnimate(side: side, percent: invertLastPercent * percent + ss.gestureLastPercentage)
} else {
ss.didAnimate(side: side, percent: percent)
}
},
completion: { [weak self] isComplete in
guard let ss = self else { return }
ss.willFinishAnimate(side: side, percent: 1.0)
ss.didFinishAnimate(side: side, percent: 1.0)
ss.isAnimating = false
ss.delegate?.drawerDidOpenSide?(drawerController: ss, side: side)
completion?()
}
)
} else {
UIView.animate(
withDuration: animationDuration,
animations: { [weak self] in
guard let ss = self else { return }
ss.didAnimate(side: side, percent: 1.0)
},
completion: { [weak self] isComplete in
guard let ss = self else { return }
ss.willFinishAnimate(side: side, percent: 1.0)
ss.didFinishAnimate(side: side, percent: 1.0)
ss.isAnimating = false
ss.delegate?.drawerDidOpenSide?(drawerController: ss, side: side)
completion?()
}
)
}
}
public func closeSide(completion: (()->())? = nil) {
/// Golden-Path
guard isEnable(), !isAnimating else { return }
delegate?.drawerWillCloseSide?(drawerController: self, side: drawerSide)
let oldSide = drawerSide
isAnimating = true
willBeginAnimate(side: .none)
didBeginAnimate(side: .none)
willAnimate(side: .none, percent: 1.0)
/// Check if the animation is available.
guard isAnimation() else {
didAnimate(side: .none, percent: 0.0)
willFinishAnimate(side: .none, percent: 0.0)
didFinishAnimate(side: .none, percent: 0.0)
isAnimating = false
delegate?.drawerDidCloseSide?(drawerController: self, side: oldSide)
completion?()
return
}
if gestureLastPercentage >= 0.0 {
didAnimate(side: .none, percent: gestureLastPercentage)
} else {
didAnimate(side: .none, percent: 0.9999)
}
if let content = contentMap[drawerSide] {
content.animator.doAnimate(
duration: animationDuration,
animations: { [weak self] percent in
guard let ss = self else { return }
if ss.gestureLastPercentage >= 0.0 {
ss.didAnimate(side: .none, percent: ss.gestureLastPercentage - percent * ss.gestureLastPercentage)
} else {
ss.didAnimate(side: .none, percent: 1.0 - percent)
}
}, completion: { [weak self] isComplete in
guard let ss = self else { return }
ss.willFinishAnimate(side: .none, percent: 0.0)
ss.didFinishAnimate(side: .none, percent: 0.0)
ss.isAnimating = false
ss.delegate?.drawerDidCloseSide?(drawerController: ss, side: oldSide)
completion?()
}
)
} else {
UIView.animate(
withDuration: animationDuration,
animations: { [weak self] in
guard let ss = self else { return }
ss.didAnimate(side: .none, percent: 0.0)
}, completion: { [weak self] isComplete in
guard let ss = self else { return }
ss.willFinishAnimate(side: .none, percent: 0.0)
ss.didFinishAnimate(side: .none, percent: 0.0)
ss.isAnimating = false
ss.delegate?.drawerDidCloseSide?(drawerController: ss, side: oldSide)
completion?()
}
)
}
}
// MARK: - Private
private var contentMap: [DrawerSide: DrawerContent] = [:]
private var internalDrawerWidth: Float = 280.0
private var internalFromSide: DrawerSide = .none
private var shadowView: UIView = UIView()
private var fadeView: UIView = UIView()
private var translucentView: TranslucentView = TranslucentView()
private var tapGestureRecognizer: UITapGestureRecognizer?
private var currentOrientation: UIDeviceOrientation = .unknown
#if swift(>=3.2)
private var observeContext: NSKeyValueObservation?
#else
private var isObserveKVO: Bool = false
private static var observeContext: Int = 0
#endif
/// Gesture
private var gestureBeginPoint: CGPoint = CGPoint.zero
private var gestureMovePoint: CGPoint = CGPoint.zero
private var gestureLastPercentage: Float = -1.0
private var isGestureMoveLeft: Bool = false
private func isEnable() -> Bool {
return options.isEnable
}
private func isEnable(content: DrawerContent) -> Bool {
return options.isEnable && content.option.isEnable
}
private func isAnimation() -> Bool {
return options.isAnimation
}
private func isAnimation(content: DrawerContent) -> Bool {
return options.isAnimation && content.option.isAnimation
}
private func isOverflowAnimation() -> Bool {
return options.isOverflowAnimation
}
private func isOverflowAnimation(content: DrawerContent) -> Bool {
return options.isOverflowAnimation && content.option.isOverflowAnimation
}
private func isGesture() -> Bool {
return options.isGesture
}
private func isGesture(content: DrawerContent) -> Bool {
return options.isGesture && content.option.isGesture
}
private func isShadow(content: DrawerContent) -> Bool {
return options.isShadow && content.option.isShadow
}
private func isFadeScreen(content: DrawerContent) -> Bool {
return options.isFadeScreen && content.option.isFadeScreen
}
private func isBlur(content: DrawerContent) -> Bool {
return options.isBlur && content.option.isBlur
}
private func isTapToClose() -> Bool {
return options.isTapToClose
}
private func isTapToClose(content: DrawerContent) -> Bool {
return options.isTapToClose && content.option.isTapToClose
}
private func addSide(_ side: DrawerSide, viewController: UIViewController) {
/// Golden-Path
guard !isAnimating else { return }
/// Closure
let setNewContent: ((DrawerContent?) -> Void) = { [weak self] content in
guard let ss = self else { return }
if let oldContent = content {
oldContent.removeDrawerView()
}
let newContent = DrawerContent(
viewController: viewController,
drawerSide: side
)
newContent.addDrawerView(drawerController: ss)
newContent.drawerWidth = ss.drawerWidth
ss.contentMap[side] = newContent
if side == .none {
newContent.setVisible(true)
}
newContent.startTransition(side: .none)
newContent.transition(
side: .none,
percentage: ss.calcPercentage(side: side, moveSide: .none, 0.0),
viewRect: ss.calcViewRect(content: newContent)
)
newContent.endTransition(side: .none)
}
guard let content = contentMap[side] else {
setNewContent(nil)
return
}
/// Check exposed in screen.
if drawerSide == side {
closeSide {
setNewContent(content)
}
} else {
setNewContent(content)
}
}
private func removeSide(_ side: DrawerSide) {
/// Golden-Path
guard !isAnimating, let content = contentMap[side] else { return }
/// Closure
let unsetContent: ((DrawerContent) -> Void) = { [weak self] content in
content.removeDrawerView()
self?.contentMap.removeValue(forKey: side)
}
if drawerSide == side {
closeSide {
unsetContent(content)
}
} else {
unsetContent(content)
}
}
// MARK: - Animation
private func calcPercentage(side: DrawerSide, moveSide: DrawerSide, _ percentage: Float) -> Float {
switch (side, moveSide) {
case (.left, _):
return -1.0 + percentage
case (.right, _):
return 1.0 - percentage
case (.none, .right):
return -percentage
case (.none, _):
return percentage
}
}
private func calcViewRect(content: DrawerContent?) -> CGRect {
if let selectedContent = content {
return CGRect(
origin: .zero,
size: CGSize(width: CGFloat(selectedContent.drawerWidth), height: view.frame.height)
)
} else {
return CGRect(
origin: .zero,
size: CGSize(width: CGFloat(drawerWidth), height: view.frame.height)
)
}
}
private func willBeginAnimate(side: DrawerSide) {
for (drawerSide, content) in contentMap {
if drawerSide == side || drawerSide == .none || drawerSide == internalFromSide {
content.contentView.isHidden = false
} else {
content.contentView.isHidden = true
}
}
internalFromSide = side
/// View Controller Events
if side != .none, let sideContent = contentMap[side] {
sideContent.setVisible(true)
}
/// User Interaction
view.isUserInteractionEnabled = false
}
private func didBeginAnimate(side: DrawerSide) {
/// Golden-Path
guard let mainContent = contentMap[.none] else { return }
let moveSide = side == .none ? drawerSide : side
mainContent.startTransition(side: side)
/// Delegate
defer {
delegate?.drawerDidBeganAnimation?(drawerController: self, side: side)
}
guard let sideContent = contentMap[moveSide] else { return }
sideContent.startTransition(side: side)
/// Fade Screen
fadeView.isHidden = !isFadeScreen(content: sideContent)
if isFadeScreen(content: sideContent) {
if sideContent.isBringToFront {
view.insertSubview(fadeView, aboveSubview: mainContent.contentView)
} else {
view.insertSubview(fadeView, aboveSubview: sideContent.contentView)
}
}
/// Blur
translucentView.isHidden = !isBlur(content: sideContent)
if isBlur(content: sideContent) {
if sideContent.isBringToFront {
view.insertSubview(translucentView, aboveSubview: mainContent.contentView)
} else {
view.insertSubview(translucentView, aboveSubview: sideContent.contentView)
}
}
/// Shadow
shadowView.isHidden = !isShadow(content: sideContent)
if isShadow(content: sideContent) {
shadowView.frame = sideContent.contentView.frame
shadowView.layer.shadowPath = UIBezierPath(rect: shadowView.bounds).cgPath
view.insertSubview(shadowView, belowSubview: sideContent.contentView)
}
#if swift(>=4.2)
if sideContent.isBringToFront {
view.bringSubviewToFront(sideContent.contentView)
} else {
view.bringSubviewToFront(mainContent.contentView)
}
#else
if sideContent.isBringToFront {
view.bringSubview(toFront: sideContent.contentView)
} else {
view.bringSubview(toFront: mainContent.contentView)
}
#endif
}
private func willAnimate(side: DrawerSide, percent: Float) {}
private func didAnimate(side: DrawerSide, percent: Float) {
/// Golden-Path
guard let mainContent = contentMap[.none] else { return }
let moveSide = side == .none ? drawerSide : side
guard let sideContent = contentMap[moveSide] else {
mainContent.transition(
side: side,
percentage: calcPercentage(side: .none, moveSide: moveSide, percent),
viewRect: calcViewRect(content: nil)
)
fadeView.layer.opacity = percent
translucentView.alpha = CGFloat(percent)
return
}
if !sideContent.isAbsolute {
mainContent.transition = sideContent.transition
mainContent.overflowTransition = sideContent.overflowTransition
mainContent.transition(
side: side,
percentage: calcPercentage(side: .none, moveSide: moveSide, percent),
viewRect: calcViewRect(content: sideContent)
)
}
sideContent.transition(
side: side,
percentage: calcPercentage(side: moveSide, moveSide: moveSide, percent),
viewRect: calcViewRect(content: sideContent)
)
if isShadow(content: sideContent) {
shadowView.frame = sideContent.contentView.frame
shadowView.layer.shadowPath = UIBezierPath(rect: shadowView.bounds).cgPath
shadowView.alpha = CGFloat(percent)
}
if sideContent.isBringToFront {
fadeView.layer.opacity = percent
translucentView.alpha = CGFloat(percent)
} else {
fadeView.layer.opacity = 1.0 - percent
translucentView.alpha = CGFloat(1.0 - percent)
}
/// Delegate
delegate?.drawerDidAnimation?(drawerController: self, side: side, percentage: percent)
}
private func willFinishAnimate(side: DrawerSide, percent: Float) {
/// Delegate
delegate?.drawerWillFinishAnimation?(drawerController: self, side: side)
}
private func didFinishAnimate(side: DrawerSide, percent: Float) {
/// Golden-Path
guard let mainContent = contentMap[.none] else { return }
let moveSide = side == .none ? drawerSide : side
let sideContent = contentMap[moveSide]
if let content = sideContent {
if content.isBringToFront {
fadeView.layer.opacity = percent
translucentView.alpha = CGFloat(percent)
} else {
fadeView.layer.opacity = 1.0 - percent
translucentView.alpha = CGFloat(1.0 - percent)
}
content.endTransition(side: side)
if moveSide != .none, side == .none {
content.setVisible(false)
}
} else {
fadeView.layer.opacity = percent
translucentView.alpha = CGFloat(percent)
}
mainContent.endTransition(side: side)
/// Set User Interaction
for (drawerSide, content) in contentMap {
if drawerSide == side {
content.contentView.isUserInteractionEnabled = true
} else {
content.contentView.isUserInteractionEnabled = false
}
}
drawerSide = side
/// User Interaction
if let content = sideContent {
if !isTapToClose(content: content) {
mainContent.contentView.isUserInteractionEnabled = true
}
}
view.isUserInteractionEnabled = true
/// Delegate
delegate?.drawerDidFinishAnimation?(drawerController: self, side: side)
}
private func willCancelAnimate(side: DrawerSide, percent: Float) {
/// Delegate
delegate?.drawerWillCancelAnimation?(drawerController: self, side: side)
}
private func didCancelAnimate(side: DrawerSide, percent: Float) {
/// Golden-Path
guard let mainContent = contentMap[.none] else { return }
let moveSide = side == .none ? drawerSide : side
let sideContent = contentMap[moveSide]
if let content = sideContent {
if content.isBringToFront {
fadeView.layer.opacity = percent
translucentView.alpha = CGFloat(percent)
} else {
fadeView.layer.opacity = 1.0 - percent
translucentView.alpha = CGFloat(1.0 - percent)
}
} else {
fadeView.layer.opacity = percent
translucentView.alpha = CGFloat(percent)
}
/// Set User Interaction
for (drawerSide, content) in contentMap {
if drawerSide == side {
content.contentView.isUserInteractionEnabled = true
} else {
content.contentView.isUserInteractionEnabled = false
}
}
drawerSide = side
/// User Interaction
if let content = sideContent {
if !isTapToClose(content: content) {
mainContent.contentView.isUserInteractionEnabled = true
}
}
view.isUserInteractionEnabled = true
/// Delegate
delegate?.drawerDidCancelAnimation?(drawerController: self, side: side)
}
private func updateLayout() {
for content in contentMap.values {
content.updateView()
}
guard !isAnimating else { return }
for (side, content) in contentMap {
if side == .none { continue }
let percent: Float = drawerSide == .none ? 0.0 : 1.0
willBeginAnimate(side: drawerSide)
didBeginAnimate(side: drawerSide)
willAnimate(side: drawerSide, percent: percent)
didAnimate(side: drawerSide, percent: percent)
content.startTransition(side: drawerSide)
content.transition(
side: drawerSide,
percentage: calcPercentage(side: side, moveSide: drawerSide, percent),
viewRect: calcViewRect(content: content)
)
content.endTransition(side: drawerSide)
willFinishAnimate(side: drawerSide, percent: percent)
didFinishAnimate(side: drawerSide, percent: percent)
}
}
// MARK: - UIGestureRecognizerDelegate
private func isContentTouched(point: CGPoint, side: DrawerSide) -> Bool {
guard drawerSide != .none else { return false }
let gestureSensitivity = CGFloat(gestureSenstivity.sensitivity())
let pointRect = CGRect(
origin: CGPoint(
x: point.x - gestureSensitivity,
y: point.y - gestureSensitivity
),
size: CGSize(
width: gestureSensitivity * 2.0,
height: gestureSensitivity * 2.0
)
)
for (drawerSide, content) in contentMap where content.isAbsolute && drawerSide != side {
if content.contentView.frame.intersects(pointRect) {
return false
}
}
for (drawerSide, content) in contentMap {
if content.contentView.frame.intersects(pointRect) {
if drawerSide == side {
return true
} else {
return false
}
}
}
return false
}
@objc
private func handleTapGestureRecognizer(gesture: UITapGestureRecognizer) {
/// Golden-Path
guard isEnable(), isGesture(), !isAnimating else { return }
closeSide { [weak self] in
self?.gestureLastPercentage = -1.0
}
}
@objc
private func handlePanGestureRecognizer(gesture: UIPanGestureRecognizer) {
/// Golden-Path
guard isEnable(), isGesture(), !isAnimating else { return }
let location = gesture.location(in: view)
switch gesture.state {
case .began:
if isGestureMoveLeft == true {
willBeginAnimate(side: .left)
didBeginAnimate(side: .left)
} else {
willBeginAnimate(side: .right)
didBeginAnimate(side: .right)
}
switch drawerSide {
case .left:
gestureLastPercentage = 1.0
case .right:
gestureLastPercentage = -1.0
case .none:
gestureLastPercentage = 0.0
}
#if swift(>=4.2)
willAnimate(side: internalFromSide, percent: abs(gestureLastPercentage))
didAnimate(side: internalFromSide, percent: abs(gestureLastPercentage))
#else
willAnimate(side: internalFromSide, percent: fabs(gestureLastPercentage))
didAnimate(side: internalFromSide, percent: fabs(gestureLastPercentage))
#endif
case .changed:
guard internalFromSide != .none else { return }
let viewRect = calcViewRect(content: contentMap[internalFromSide])
let moveVariationX = Float(location.x - gestureMovePoint.x)
var percentage = gestureLastPercentage + moveVariationX / Float(viewRect.width)
if moveVariationX > 0 {
isGestureMoveLeft = false
} else if moveVariationX < 0 {
isGestureMoveLeft = true
}
let checkAndSwitchDirection = { [weak self] (from: DrawerSide, to: DrawerSide, percentage: Float) -> Float in
guard let ss = self else { return percentage }
guard ss.internalFromSide == from else { return percentage }
switch from {
case .left:
guard percentage < 0.0 else { return percentage }
case .right:
guard percentage > 0.0 else { return percentage }
default:
return percentage
}
guard ss.isEnableAutoSwitchDirection else {
switch from {
case .left:
guard percentage > 0.0 else { return 0.0 }
case .right:
guard percentage < 0.0 else { return 0.0 }
default:
return percentage
}
return percentage
}
guard ss.contentMap[to] != nil else {
return 0.0
}
ss.willAnimate(side: from, percent: 0.0)
ss.didAnimate(side: from, percent: 0.0)
ss.willFinishAnimate(side: from, percent: 0)
ss.didFinishAnimate(side: from, percent: 0)
ss.drawerSide = .none
ss.willBeginAnimate(side: to)
ss.didBeginAnimate(side: to)
return percentage
}
percentage = checkAndSwitchDirection(.right, .left, percentage)
percentage = checkAndSwitchDirection(.left, .right, percentage)
gestureMovePoint = location
if isOverflowAnimation(content: contentMap[internalFromSide]!) {
if percentage > DrawerController.OverflowPercentage {
percentage = DrawerController.OverflowPercentage
}
if percentage < -DrawerController.OverflowPercentage {
percentage = -DrawerController.OverflowPercentage
}
} else {
if percentage > 1.0 {
percentage = 1.0
}
if percentage < -1.0 {
percentage = -1.0
}
}
#if swift(>=4.2)
willAnimate(side: internalFromSide, percent: abs(percentage))
didAnimate(side: internalFromSide, percent: abs(percentage))
#else
willAnimate(side: internalFromSide, percent: fabs(percentage))
didAnimate(side: internalFromSide, percent: fabs(percentage))
#endif
gestureLastPercentage = percentage
default:
guard internalFromSide != .none else { return }
#if swift(>=4.2)
let lastPercentage = abs(gestureLastPercentage)
#else
let lastPercentage = fabs(gestureLastPercentage)
#endif
willCancelAnimate(side: internalFromSide, percent: lastPercentage)
didCancelAnimate(side: internalFromSide, percent: lastPercentage)
gestureLastPercentage = lastPercentage
if internalFromSide == .left && !isGestureMoveLeft {
openSide(.left) { [weak self] in
self?.gestureLastPercentage = -1.0
}
} else if internalFromSide == .right && isGestureMoveLeft {
openSide(.right) { [weak self] in
self?.gestureLastPercentage = -1.0
}
} else {
if lastPercentage > 1.0 {
if internalFromSide == .left {
openSide(.left) { [weak self] in
self?.gestureLastPercentage = -1.0
}
} else if internalFromSide == .right {
openSide(.right) { [weak self] in
self?.gestureLastPercentage = -1.0
}
}
} else {
closeSide { [weak self] in
self?.gestureLastPercentage = -1.0
}
}
}
gestureMovePoint.x = -1
gestureMovePoint.y = -1
}
}
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
/// Golden-Path
guard isEnable() else { return false }
guard !isAnimating else { return false }
let location = gestureRecognizer.location(in: view)
/// Check tap gesture recognizer
if gestureRecognizer is UITapGestureRecognizer {
guard isTapToClose() else { return false }
guard let sideContent = contentMap[drawerSide] else { return false }
if isContentTouched(point: location, side: .none) {
guard isTapToClose(content: sideContent) else { return false }
return true
}
return false
}
/// Check pan gesture recognizer
guard isGesture() else { return false }
guard let panGesture = gestureRecognizer as? UIPanGestureRecognizer else { return false }
let translation = panGesture.translation(in: view)
#if swift(>=4.2)
guard abs(translation.x) >= abs(translation.y) else { return false }
#else
guard fabs(translation.x) >= fabs(translation.y) else { return false }
#endif
/// Set default values
gestureBeginPoint = location
gestureMovePoint = gestureBeginPoint
let gestureSensitivity = CGFloat(gestureSenstivity.sensitivity())
let pointRect = CGRect(
origin: CGPoint(
x: (gestureBeginPoint.x - translation.x) - gestureSensitivity,
y: (gestureBeginPoint.y - translation.y) - gestureSensitivity
),
size: CGSize(
width: gestureSensitivity * 2.0,
height: gestureSensitivity * 2.0
)
)
/// Gesture Area
if drawerSide == .none {
let leftRect = CGRect(
x: CGFloat(Float(view.frame.minX) - DrawerController.GestureArea),
y: view.frame.minY,
width: CGFloat(DrawerController.GestureArea * 2.0),
height: view.frame.height
)
let rightRect = CGRect(
x: CGFloat(Float(view.frame.maxX) - DrawerController.GestureArea),
y: view.frame.origin.y,
width: CGFloat(DrawerController.GestureArea * 2.0),
height: view.frame.height
)
if let content = contentMap[.left] {
if isGesture(content: content) && leftRect.intersects(pointRect) {
isGestureMoveLeft = true
return true
}
}
if let content = contentMap[.right] {
if isGesture(content: content) && rightRect.intersects(pointRect) {
isGestureMoveLeft = false
return true
}
}
} else {
guard let content = contentMap[.none] else { return false }
guard let sideContent = contentMap[drawerSide] else { return false }
guard isGesture(content: sideContent) else { return false }
if content.contentView.frame.intersects(pointRect) {
if drawerSide == .left {
isGestureMoveLeft = true
} else {
isGestureMoveLeft = false
}
return true
}
}
return false
}
// MARK: - Lifecycle
override open func viewDidLoad() {
super.viewDidLoad()
options.isTapToClose = true
options.isGesture = true
options.isAnimation = true
options.isOverflowAnimation = true
options.isShadow = true
options.isFadeScreen = true
options.isBlur = true
options.isEnable = true
/// Default View
shadowView.layer.shadowOpacity = shadowOpacity
shadowView.layer.shadowRadius = shadowRadius
shadowView.layer.masksToBounds = false
shadowView.layer.opacity = 0.0
shadowView.isHidden = true
shadowView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(shadowView)
fadeView.frame = view.bounds
fadeView.backgroundColor = fadeColor
fadeView.alpha = 0.0
fadeView.isHidden = true
fadeView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(fadeView)
translucentView.frame = view.bounds
translucentView.layer.opacity = 0.0
translucentView.isHidden = true
translucentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(translucentView)
/// Gesture Recognizer
panGestureRecognizer = { [unowned self] in
let gesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGestureRecognizer))
gesture.delegate = self
self.view.addGestureRecognizer(gesture)
return gesture
}()
tapGestureRecognizer = { [unowned self] in
let gesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGestureRecognizer))
gesture.delegate = self
self.view.addGestureRecognizer(gesture)
return gesture
}()
view.clipsToBounds = true
/// Storyboard
if let mainSegueID = mainSegueIdentifier {
performSegue(withIdentifier: mainSegueID, sender: self)
}
if let leftSegueID = leftSegueIdentifier {
performSegue(withIdentifier: leftSegueID, sender: self)
}
if let rightSegueID = rightSegueIdentifier {
performSegue(withIdentifier: rightSegueID, sender: self)
}
/// Events
#if swift(>=3.2)
observeContext = view.observe(\.frame) { [weak self] (view, event) in
self?.updateLayout()
}
#else
view.addObserver(self, forKeyPath: "frame", options: .new, context: &DrawerController.observeContext)
isObserveKVO = true
#endif
}
deinit {
#if swift(>=3.2)
observeContext?.invalidate()
observeContext = nil
#else
if isObserveKVO {
view.removeObserver(self, forKeyPath:"frame")
}
#endif
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
for (_, content) in contentMap {
content.contentView.setNeedsUpdateConstraints()
content.contentView.setNeedsLayout()
content.contentView.layoutIfNeeded()
}
let newOrientation = UIDevice.current.orientation
guard newOrientation != .unknown, newOrientation != currentOrientation else { return }
currentOrientation = newOrientation
updateLayout()
}
#if !swift(>=3.2)
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard context == &DrawerController.observeContext else {
observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
guard isObserveKVO else { return }
if keyPath == "frame" {
updateLayout()
}
}
#endif
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
}
| mit | ce1cca1284637fde282d476dfc3c62be | 35.478191 | 155 | 0.565567 | 5.283725 | false | false | false | false |
progrmr/State_Hunt_swift | State_Hunt/Theme.swift | 1 | 796 | //
// Theme.swift
// State_Hunt
//
// Created by Gary Morris on 7/4/14.
// Copyright (c) 2014 Gary Morris. All rights reserved.
//
import Foundation
import UIKit
let s_SingletonInstance = Theme()
class Theme {
let kBackgroundColor = UIColor(gray:0.85)
let kTextColor = UIColor.blackColor()
let kDetailTextColor = UIColor(gray:0.7)
let kSeenBackgroundColor = UIColor(g:0.6)
let kSeenTextColor = UIColor.whiteColor()
let kButtonTintColor = UIColor(g:0.4)
let kButtonTextColor = UIColor(g:0.4)
let kButtonHighlightColor = UIColor(rgb:0x4444ff)
let kCellBorderColor = UIColor(gray:0.0)
class var currentTheme : Theme {
return s_SingletonInstance
}
} | gpl-2.0 | 52c40da291a81ed8d83e74679448565e | 23.151515 | 56 | 0.616834 | 3.790476 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Features/Add delete related features/AddDeleteRelatedFeaturesViewController.swift | 1 | 4471 | //
// Copyright 2016 Esri.
//
// 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 ArcGIS
class AddDeleteRelatedFeaturesViewController: UIViewController, AGSGeoViewTouchDelegate {
@IBOutlet var mapView: AGSMapView!
private var parksFeatureTable: AGSServiceFeatureTable!
private var parksFeatureLayer: AGSFeatureLayer!
private var selectedPark: AGSFeature!
override func viewDidLoad() {
super.viewDidLoad()
// add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["AddDeleteRelatedFeaturesViewController", "RelatedFeaturesViewController"]
// initialize map with basemap
let map = AGSMap(basemapStyle: .arcGISStreets)
// initial viewpoint
let point = AGSPoint(x: -16507762.575543, y: 9058828.127243, spatialReference: .webMercator())
// parks feature table
self.parksFeatureTable = AGSServiceFeatureTable(url: URL(string: "https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/ArcGIS/rest/services/AlaskaNationalParksSpecies_Add_Delete/FeatureServer/0")!)
// parks feature layer
let parksFeatureLayer = AGSFeatureLayer(featureTable: self.parksFeatureTable)
// add feature layer to the map
map.operationalLayers.add(parksFeatureLayer)
// species feature table (destination feature table)
// related to the parks feature layer in a 1..M relationship
let speciesFeatureTable = AGSServiceFeatureTable(url: URL(string: "https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/ArcGIS/rest/services/AlaskaNationalParksSpecies_Add_Delete/FeatureServer/1")!)
// add table to the map
// for the related query to work, the related table should be present in the map
map.tables.add(speciesFeatureTable)
// assign map to map view
mapView.map = map
mapView.setViewpoint(AGSViewpoint(center: point, scale: 36764077))
// set touch delegate
mapView.touchDelegate = self
// store the feature layer for later use
self.parksFeatureLayer = parksFeatureLayer
}
// MARK: - AGSGeoViewTouchDelegate
func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
// show progress hud for identify
UIApplication.shared.showProgressHUD(message: "Identifying feature")
// identify features at tapped location
self.mapView.identifyLayer(self.parksFeatureLayer, screenPoint: screenPoint, tolerance: 12, returnPopupsOnly: false) { [weak self] (result) in
// hide progress hud
UIApplication.shared.hideProgressHUD()
if let error = result.error {
// show error to user
self?.presentAlert(error: error)
} else if let feature = result.geoElements.first as? AGSFeature {
// select the first feature
self?.selectedPark = feature
// show related features view controller
self?.performSegue(withIdentifier: "RelatedFeaturesSegue", sender: self)
}
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "RelatedFeaturesSegue",
let navigationController = segue.destination as? UINavigationController,
let controller = navigationController.viewControllers.first as? RelatedFeaturesViewController {
// share selected park
controller.originFeature = self.selectedPark as? AGSArcGISFeature
// share parks feature table as origin feature table
controller.originFeatureTable = self.parksFeatureTable
}
}
}
| apache-2.0 | 5a5ec219407bb39160fe4ddbc6f6b5e2 | 41.580952 | 199 | 0.670767 | 4.807527 | false | false | false | false |
brentdax/swift | test/attr/attr_inlinable.swift | 2 | 8782 | // RUN: %target-typecheck-verify-swift -swift-version 4.2
// RUN: %target-typecheck-verify-swift -swift-version 4.2 -enable-testing
// RUN: %target-typecheck-verify-swift -swift-version 4.2 -enable-resilience
// RUN: %target-typecheck-verify-swift -swift-version 4.2 -enable-resilience -enable-testing
@inlinable struct TestInlinableStruct {}
// expected-error@-1 {{'@inlinable' attribute cannot be applied to this declaration}}
@inlinable @usableFromInline func redundantAttribute() {}
// expected-warning@-1 {{'@inlinable' declaration is already '@usableFromInline'}}
private func privateFunction() {}
// expected-note@-1{{global function 'privateFunction()' is not '@usableFromInline' or public}}
fileprivate func fileprivateFunction() {}
// expected-note@-1{{global function 'fileprivateFunction()' is not '@usableFromInline' or public}}
func internalFunction() {}
// expected-note@-1{{global function 'internalFunction()' is not '@usableFromInline' or public}}
@usableFromInline func versionedFunction() {}
public func publicFunction() {}
private struct PrivateStruct {}
// expected-note@-1 3{{struct 'PrivateStruct' is not '@usableFromInline' or public}}
struct InternalStruct {}
// expected-note@-1 4{{struct 'InternalStruct' is not '@usableFromInline' or public}}
@usableFromInline struct VersionedStruct {
@usableFromInline init() {}
}
public struct PublicStruct {
public init() {}
@inlinable public var storedProperty: Int
// expected-error@-1 {{'@inlinable' attribute cannot be applied to stored properties}}
@inlinable public lazy var lazyProperty: Int = 0
// expected-error@-1 {{'@inlinable' attribute cannot be applied to stored properties}}
}
public struct Struct {
@_transparent
public func publicTransparentMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside a '@_transparent' function}}
publicFunction()
// OK
versionedFunction()
// OK
internalFunction()
// expected-error@-1 {{global function 'internalFunction()' is internal and cannot be referenced from a '@_transparent' function}}
fileprivateFunction()
// expected-error@-1 {{global function 'fileprivateFunction()' is fileprivate and cannot be referenced from a '@_transparent' function}}
privateFunction()
// expected-error@-1 {{global function 'privateFunction()' is private and cannot be referenced from a '@_transparent' function}}
}
@inlinable
public func publicInlinableMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@inlinable' function}}
let _: PublicStruct
let _: VersionedStruct
let _: InternalStruct
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@inlinable' function}}
let _: PrivateStruct
// expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@inlinable' function}}
let _ = PublicStruct.self
let _ = VersionedStruct.self
let _ = InternalStruct.self
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@inlinable' function}}
let _ = PrivateStruct.self
// expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@inlinable' function}}
let _ = PublicStruct()
let _ = VersionedStruct()
let _ = InternalStruct()
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@inlinable' function}}
let _ = PrivateStruct()
// expected-error@-1 {{struct 'PrivateStruct' is private and cannot be referenced from an '@inlinable' function}}
}
@inline(__always)
public func publicInlineAlwaysMethod(x: Any) {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@inline(__always)' function}}
switch x {
case is InternalStruct:
// expected-error@-1 {{struct 'InternalStruct' is internal and cannot be referenced from an '@inline(__always)' function}}
_ = ()
}
}
private func privateMethod() {}
// expected-note@-1 {{instance method 'privateMethod()' is not '@usableFromInline' or public}}
@_transparent
@usableFromInline
func versionedTransparentMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside a '@_transparent' function}}
privateMethod()
// expected-error@-1 {{instance method 'privateMethod()' is private and cannot be referenced from a '@_transparent' function}}
}
@inlinable
func internalInlinableMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@inlinable' function}}
}
@inline(__always)
@usableFromInline
func versionedInlineAlwaysMethod() {
struct Nested {}
// expected-error@-1 {{type 'Nested' cannot be nested inside an '@inline(__always)' function}}
}
@_transparent
func internalTransparentMethod() {
struct Nested {}
// OK
}
@inlinable
private func privateInlinableMethod() {
// expected-error@-2 {{'@inlinable' attribute can only be applied to public declarations, but 'privateInlinableMethod' is private}}
struct Nested {}
// OK
}
@inline(__always)
func internalInlineAlwaysMethod() {
struct Nested {}
// OK
}
}
// Make sure protocol extension members can reference protocol requirements
// (which do not inherit the @usableFromInline attribute).
@usableFromInline
protocol VersionedProtocol {
associatedtype T
func requirement() -> T
}
extension VersionedProtocol {
func internalMethod() {}
// expected-note@-1 {{instance method 'internalMethod()' is not '@usableFromInline' or public}}
@inlinable
func versionedMethod() -> T {
internalMethod()
// expected-error@-1 {{instance method 'internalMethod()' is internal and cannot be referenced from an '@inlinable' function}}
return requirement()
}
}
enum InternalEnum {
// expected-note@-1 2{{enum 'InternalEnum' is not '@usableFromInline' or public}}
// expected-note@-2 {{type declared here}}
case apple
case orange
}
@inlinable public func usesInternalEnum() {
_ = InternalEnum.apple
// expected-error@-1 {{enum 'InternalEnum' is internal and cannot be referenced from an '@inlinable' function}}
let _: InternalEnum = .orange
// expected-error@-1 {{enum 'InternalEnum' is internal and cannot be referenced from an '@inlinable' function}}
}
@usableFromInline enum VersionedEnum {
case apple
case orange
case pear(InternalEnum)
// expected-warning@-1 {{type of enum case in '@usableFromInline' enum should be '@usableFromInline' or public}}
case persimmon(String)
}
@inlinable public func usesVersionedEnum() {
_ = VersionedEnum.apple
let _: VersionedEnum = .orange
_ = VersionedEnum.persimmon
}
// Inherited initializers - <rdar://problem/34398148>
@usableFromInline
@_fixed_layout
class Base {
@usableFromInline
init(x: Int) {}
}
@usableFromInline
@_fixed_layout
class Middle : Base {}
@usableFromInline
@_fixed_layout
class Derived : Middle {
@inlinable
init(y: Int) {
super.init(x: y)
}
}
// More inherited initializers
@_fixed_layout
public class Base2 {
@inlinable
public init(x: Int) {}
}
@_fixed_layout
@usableFromInline
class Middle2 : Base2 {}
@_fixed_layout
@usableFromInline
class Derived2 : Middle2 {
@inlinable
init(y: Int) {
super.init(x: y)
}
}
// Stored property initializer expressions.
//
// Note the behavior here does not depend on the state of the -enable-resilience
// flag; the test runs with both the flag on and off. Only the explicit
// presence of a '@_fixed_layout' attribute determines the behavior here.
let internalGlobal = 0
// expected-note@-1 {{let 'internalGlobal' is not '@usableFromInline' or public}}
public let publicGlobal = 0
struct InternalStructWithInit {
var x = internalGlobal // OK
var y = publicGlobal // OK
}
public struct PublicResilientStructWithInit {
var x = internalGlobal // OK
var y = publicGlobal // OK
}
private func privateIntReturningFunc() -> Int { return 0 }
internal func internalIntReturningFunc() -> Int { return 0 }
@_fixed_layout
public struct PublicFixedStructWithInit {
var x = internalGlobal // expected-error {{let 'internalGlobal' is internal and cannot be referenced from a property initializer in a '@_fixed_layout' type}}
var y = publicGlobal // OK
static var z = privateIntReturningFunc() // OK
static var a = internalIntReturningFunc() // OK
}
public struct KeypathStruct {
var x: Int
// expected-note@-1 {{property 'x' is not '@usableFromInline' or public}}
@inlinable public func usesKeypath() {
_ = \KeypathStruct.x
// expected-error@-1 {{property 'x' is internal and cannot be referenced from an '@inlinable' function}}
}
}
| apache-2.0 | 90e6b2f9235680debc2fe46fb559d351 | 31.64684 | 159 | 0.709633 | 4.351833 | false | false | false | false |
huaf22/zhihuSwiftDemo | zhihuSwiftDemo/Library/ArticleHTMLParser.swift | 1 | 561 | //
// ArticleHTMLParser.swift
// zhihuSwiftDemo
//
// Created by Afluy on 16/8/13.
// Copyright © 2016年 helios. All rights reserved.
//
import Foundation
class ArticleHTMLParser {
static func parseHTML(_ article: WLYArticleDetail) -> String? {
if let body = article.body {
if let cssUrl = article.cssArray?[0] {
let htmlString = "<html><body><link href=\"\(cssUrl)\" rel=\"stylesheet\" type=\"text/css\"/>\(body)</body><html>"
return htmlString
}
}
return nil
}
}
| mit | 6d138b2278226b26d9c01780c6a9d640 | 25.571429 | 130 | 0.578853 | 3.795918 | false | false | false | false |
bengottlieb/ios | FiveCalls/FiveCalls/ScheduleRemindersController.swift | 1 | 8107 | //
// ScheduleRemindersController.swift
// FiveCalls
//
// Created by Christopher Brandow on 2/8/17.
// Copyright © 2017 5calls. All rights reserved.
//
import Foundation
class ScheduleRemindersController: UIViewController {
@IBOutlet weak var timePicker: UIDatePicker!
@IBOutlet weak var daysOfWeekSelector: MultipleSelectionControl!
@IBOutlet weak var noDaysWarningLabel: UILabel!
lazy private var overlay: UIView = {
let overlay = UIView()
overlay.backgroundColor = .white
overlay.translatesAutoresizingMaskIntoConstraints = false
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = UIColor.fvc_lightGray
label.font = Appearance.instance.bodyFont
label.numberOfLines = 0
label.text = R.string.localizable.scheduledRemindersDescription()
label.textAlignment = .center
overlay.addSubview(label)
NSLayoutConstraint.activate([
label.widthAnchor.constraint(lessThanOrEqualTo: overlay.widthAnchor, multiplier: 0.8),
label.centerXAnchor.constraint(equalTo: overlay.centerXAnchor),
label.centerYAnchor.constraint(equalTo: overlay.centerYAnchor),
])
return overlay
}()
private var remindersEnabled: Bool {
get { return UserDefaults.standard.bool(forKey: UserDefaultsKeys.reminderEnabled.rawValue) }
set {
UserDefaults.standard.set(newValue, forKey: UserDefaultsKeys.reminderEnabled.rawValue)
if newValue {
requestNotificationAccess()
} else {
clearNotifications()
}
}
}
private var notificationsChanged = true
private func switchButton(on: Bool) -> UIBarButtonItem {
let switchControl = UISwitch()
switchControl.isOn = on
switchControl.addTarget(self, action: #selector(ScheduleRemindersController.switchValueChanged), for: .valueChanged)
let barButtonItem = UIBarButtonItem(customView: switchControl)
return barButtonItem
}
func switchValueChanged(_ sender: UISwitch) {
remindersEnabled = sender.isOn
setOverlay(visible: !sender.isOn, animated: true)
}
private func requestNotificationAccess() {
UIApplication.shared.registerUserNotificationSettings(
UIUserNotificationSettings(types: [.alert, .badge],
categories: nil)
)
}
func setOverlay(visible: Bool, animated: Bool) {
let duration = animated ? 0.3 : 0
if visible {
view.addSubview(overlay)
overlay.alpha = 0
NSLayoutConstraint.activate([
overlay.leftAnchor.constraint(equalTo: view.leftAnchor),
overlay.rightAnchor.constraint(equalTo: view.rightAnchor),
overlay.topAnchor.constraint(equalTo: view.topAnchor),
overlay.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
UIView.animate(withDuration: duration) {
self.overlay.alpha = 1.0
}
} else {
UIView.animate(withDuration: duration, animations: {
self.overlay.alpha = 0
}) { _ in
self.overlay.removeFromSuperview()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
if let notifications = UIApplication.shared.scheduledLocalNotifications {
daysOfWeekSelector.setSelectedButtons(at: indices(from: notifications))
if let date = notifications.first?.fireDate {
timePicker.setDate(date, animated: true)
}
}
if navigationController?.viewControllers.first == self {
let item = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissAction(_:)))
item.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: .normal)
navigationItem.leftBarButtonItem = item
}
navigationItem.rightBarButtonItem = switchButton(on: remindersEnabled)
setOverlay(visible: !remindersEnabled, animated: false)
timePicker.setValue(UIColor.fvc_darkBlue, forKey: "textColor")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
daysOfWeekSelector.warningBorderColor = UIColor.fvc_red.cgColor
noDaysWarningLabel.textColor = .fvc_red
updateDaysWarning()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
guard notificationsChanged == true && remindersEnabled else { return }
clearNotifications()
for selectorIndex in daysOfWeekSelector.selectedIndices {
let localNotif = createNotification(with: selectorIndex, chosenTime: timePicker.date)
UIApplication.shared.scheduleLocalNotification(localNotif)
}
}
@objc private func dismissAction(_ sender: UIBarButtonItem) {
let cannotDismiss = noDaysSelected() && remindersEnabled
if cannotDismiss {
shakeDays()
} else {
dismiss(animated: true, completion: nil)
}
}
private func clearNotifications() {
UIApplication.shared.cancelAllLocalNotifications()
}
@IBAction func timePickerChanged(_ sender: UIDatePicker) {
notificationsChanged = true
}
@IBAction func dayPickerAction(_ sender: MultipleSelectionControl) {
notificationsChanged = true
updateDaysWarning()
}
func updateDaysWarning() {
if daysOfWeekSelector.selectedIndices.count == 0 {
noDaysWarningLabel.isHidden = false
} else {
noDaysWarningLabel.isHidden = true
}
}
private func noDaysSelected() -> Bool {
return daysOfWeekSelector.selectedIndices.count == 0
}
private func shakeDays() {
UIView.animate(withDuration: 0.14, animations: {
self.daysOfWeekSelector.transform = CGAffineTransform(translationX: 10, y: 0)
}) { (_) in
UIView.animate(withDuration: 0.22, delay: 0, usingSpringWithDamping: 0.23, initialSpringVelocity: 1.0, options: .curveLinear, animations: {
self.daysOfWeekSelector.transform = CGAffineTransform(translationX: 0, y: 0)
}, completion: nil)
}
}
private func indices(from notifications: [UILocalNotification]) -> [Int] {
let calendar = Calendar(identifier: .gregorian)
return notifications.flatMap({ return calendar.component(.weekday, from: ($0.fireDate)!) - 2})
}
private func fireDate(for index: Int, date: Date) -> Date? {
let calendar = Calendar(identifier: .gregorian)
let currentDate = Date()
var dateComponents = DateComponents()
dateComponents.calendar = calendar
dateComponents.hour = calendar.component(.hour, from: date)
dateComponents.minute = calendar.component(.minute, from: date)
dateComponents.weekOfYear = calendar.component(.weekOfYear, from: currentDate)
dateComponents.year = calendar.component(.year, from: currentDate)
dateComponents.weekday = index + 2
return calendar.date(from: dateComponents)
}
private func createNotification(with index: Int, chosenTime: Date) -> UILocalNotification {
let localNotif = UILocalNotification()
localNotif.fireDate = fireDate(for: index, date: chosenTime)
localNotif.alertTitle = R.string.localizable.scheduledReminderAlertTitle()
localNotif.alertBody = R.string.localizable.scheduledReminderAlertBody()
localNotif.repeatInterval = .weekOfYear
localNotif.alertAction = R.string.localizable.okButtonTitle()
localNotif.timeZone = TimeZone(identifier: "default")
localNotif.applicationIconBadgeNumber = UIApplication.shared.applicationIconBadgeNumber + 1
return localNotif
}
}
| mit | 9e99f6e205c8e7b33aa37559fbaff191 | 37.056338 | 151 | 0.6547 | 5.378898 | false | false | false | false |
tumblr/SwiftCompilationPerformanceReporter | Sources/LogProcessor.swift | 1 | 1767 | import Foundation
/**
* A processor for the raw logs outputted from the Swift compiler.
*/
struct LogProcessor {
/// Location of the raw log file
let path: String
/// The output directory for the processed logs
let outputPath: URL
/// The total time it took for the build
let totalBuildTime: Double
/// The number of entities to include in the final log (e.g. top 10 functions that take the longest to compile)
let limit: UInt
/**
Processes the raw log file and writes out the results to `outputPath`
*/
func process() {
do {
let fullText = try String(contentsOfFile: path)
let entries = fullText.components(separatedBy: "\n").flatMap { LogEntry(line: $0) }
let mergedEntries = mergeDuplicateEntries(entries)
let buildTimePrompt = "Total build time: \(totalBuildTime)"
let outputText = ([buildTimePrompt] + mergedEntries.prefix(upTo: Int(limit)).map { String(describing: $0) }).joined(separator: "\n")
try outputText.write(toFile: "\(outputPath.pathWithAppendedTimestamp.absoluteString).txt", atomically: true, encoding: String.Encoding.utf8)
}
catch {
fatalError("Log processing failed w/ error: \(error)")
}
}
private func mergeDuplicateEntries(_ entries: [LogEntry]) -> [LogEntry] {
var timeFrequencyMap = [LogEntry: Double]()
entries.forEach {
timeFrequencyMap[$0] = (timeFrequencyMap[$0] ?? 0) + $0.compilationTime
}
return timeFrequencyMap.enumerated().sorted { $0.element.1 > $1.element.1 }.map {
$0.element.0.updateCompilation($0.element.1)
}
}
}
| apache-2.0 | be87613f2495c80a146b596cbf962b2d | 34.34 | 152 | 0.612903 | 4.462121 | false | false | false | false |
sendyhalim/Yomu | Yomu/Common/Utils/Router.swift | 1 | 935 | //
// Router.swift
// Yomu
//
// Created by Sendy Halim on 8/6/16.
// Copyright © 2016 Sendy Halim. All rights reserved.
//
import AppKit
import Swiftz
protocol RouteId {
var name: String { get }
}
protocol Route {
var id: RouteId { get }
var views: [NSView] { get }
}
struct Router {
fileprivate static var routes = List<Route>()
static func register(route: Route) {
routes = List.cons(head: route, tail: routes)
}
static func moveTo(id: RouteId) {
routes.forEach {
if $0.id.name == id.name {
show(route: $0)
} else {
hide(route: $0)
}
}
}
fileprivate static func show(route: Route) {
route.views.forEach(show)
}
fileprivate static func hide(route: Route) {
route.views.forEach(hide)
}
fileprivate static func hide(view: NSView) {
view.isHidden = true
}
fileprivate static func show(view: NSView) {
view.isHidden = false
}
}
| mit | 94f5a0cbf8ceb4fc55550ea24405f977 | 16.622642 | 54 | 0.620985 | 3.408759 | false | false | false | false |
hanjoes/Smashtag | Smashtag/DetailTableViewController.swift | 1 | 8404 | //
// DetailTableViewController.swift
// Smashtag
//
// Created by Hanzhou Shi on 1/6/16.
// Copyright © 2016 USF. All rights reserved.
//
import UIKit
class DetailTableViewController: UITableViewController {
// MARK: - Model
var tweet: Tweet? {
didSet {
if tweet != nil {
initializeDetails(tweet!)
tableView.reloadData()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return details.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return details[section].count
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch details[indexPath.section][indexPath.row] {
case .URLMention(_):
performSegueWithIdentifier(TableViewControllerConstants.ShowWebPageSegueIdentifier, sender: tableView.cellForRowAtIndexPath(indexPath))
case .Media(_):
performSegueWithIdentifier(TableViewControllerConstants.ShowImageSegueIdentifier, sender: imageCell)
default: break
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let detail = details[indexPath.section][indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(detail.detail.identifier, forIndexPath: indexPath)
// Configure the cell...
if let mentionCell = cell as? MentionTableViewCell {
mentionCell.detail = detail
}
else if let imageCell = cell as? ImageTableViewCell {
self.imageCell = imageCell
imageCell.imageItem = detail.imageItem
}
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let detail = details[indexPath.section][indexPath.row]
switch detail {
case .Media(let image):
return view.frame.width / CGFloat(image.aspectRatio)
default:
return UITableViewAutomaticDimension
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return titleBySectionIndex[section]
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
tableView.reloadData()
if let cell = imageCell {
if fromInterfaceOrientation.isPortrait {
performSegueWithIdentifier(TableViewControllerConstants.ShowImageSegueIdentifier, sender: 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?) {
var destination = segue.destinationViewController
if let navCon = destination as? UINavigationController {
destination = navCon.visibleViewController!
}
if let ttvc = destination as? TweetTableViewController {
if let cell = sender as? MentionTableViewCell {
guard cell.detail!.url == nil else { return }
ttvc.searchText = cell.detail!.detail.keyword
}
}
else if let ivc = destination as? ImageViewController {
if let cell = sender as? ImageTableViewCell {
if let image = cell.imageObj {
ivc.image = image
}
}
}
else if let wvc = destination as? WebUIViewController {
if let cell = sender as? MentionTableViewCell {
wvc.url = cell.detail?.url
}
}
}
// MARK: - Private
private var titleBySectionIndex = [Int:String]()
private var details = [[TweetDetail]]()
private var imageCell: ImageTableViewCell?
private func initializeDetails(tweet: Tweet) {
if tweet.media.count > 0 {
details.append(tweet.media.map{ .Media(image: $0) })
titleBySectionIndex[details.count-1] = "Media"
}
if tweet.urls.count > 0 {
details.append(tweet.urls.map{ .URLMention(url: $0.keyword) })
titleBySectionIndex[details.count-1] = "URLs"
}
// dealing with the user who posted the tweet.
let user = tweet.user
details.append([.UserMention(user: "@\(user.screenName)")])
titleBySectionIndex[details.count-1] = "Users"
if tweet.userMentions.count > 0 {
details[details.count-1] += tweet.userMentions.map{ .UserMention(user: $0.keyword) }
}
if tweet.hashtags.count > 0 {
details.append(tweet.hashtags.map{ .HashTag(hashTag: $0.keyword) })
titleBySectionIndex[details.count-1] = "Hash Tag"
}
}
}
private struct TableViewControllerConstants {
static let MediaReuseIdentifier = "Media"
static let MentionReuseIdentifier = "Mention"
static let ShowImageSegueIdentifier = "ShowImage"
static let ShowWebPageSegueIdentifier = "ShowWebPage"
}
enum TweetDetail {
case Media(image: MediaItem)
case URLMention(url: String)
case UserMention(user: String)
case HashTag(hashTag: String)
var height: CGFloat {
return UITableViewAutomaticDimension
}
var imageItem: MediaItem? {
switch self {
case .Media(let image):
return image
default:
return nil
}
}
var url: NSURL? {
switch self {
case .URLMention(let urlKeyword):
return NSURL(string: urlKeyword)
default:
return nil
}
}
var detail: (keyword: String?, identifier: String) {
switch self {
case .Media(_):
return (nil, TableViewControllerConstants.MediaReuseIdentifier)
case .URLMention(let url):
return (url, TableViewControllerConstants.MentionReuseIdentifier)
case .UserMention(let user):
return (user, TableViewControllerConstants.MentionReuseIdentifier)
case .HashTag(let hashTag):
return (hashTag, TableViewControllerConstants.MentionReuseIdentifier)
}
}
}
| mit | af6a1363af9b0f2ad51eecde79f04385 | 34.455696 | 157 | 0.640724 | 5.321723 | false | false | false | false |
benlangmuir/swift | utils/gen-unicode-data/Sources/GenScalarProps/NameAlias.swift | 10 | 4913 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import GenUtils
func getNameAliases(from data: String, into result: inout [(UInt32, String)]) {
for line in data.split(separator: "\n") {
// Skip comments
guard !line.hasPrefix("#") else {
continue
}
let info = line.split(separator: "#")
let components = info[0].split(separator: ";")
// Name aliases are only found with correction attribute.
guard components[2] == "correction" else {
continue
}
let scalars: ClosedRange<UInt32>
let filteredScalars = components[0].filter { !$0.isWhitespace }
// If we have . appear, it means we have a legitimate range. Otherwise,
// it's a singular scalar.
if filteredScalars.contains(".") {
let range = filteredScalars.split(separator: ".")
scalars = UInt32(range[0], radix: 16)! ... UInt32(range[1], radix: 16)!
} else {
let scalar = UInt32(filteredScalars, radix: 16)!
scalars = scalar ... scalar
}
let nameAlias = String(components[1])
result.append((scalars.lowerBound, nameAlias))
}
}
func emitNameAliases(_ data: [(UInt32, String)], into result: inout String) {
// 64 bit arrays * 8 bytes = .512 KB
var bitArrays: [BitArray] = .init(repeating: .init(size: 64), count: 64)
let chunkSize = 0x110000 / 64 / 64
var chunks: [Int] = []
for i in 0 ..< 64 * 64 {
let lower = i * chunkSize
let upper = lower + chunkSize - 1
let idx = i / 64
let bit = i % 64
for scalar in lower ... upper {
if data.contains(where: { $0.0 == scalar }) {
chunks.append(i)
bitArrays[idx][bit] = true
break
}
}
}
// Remove the trailing 0s. Currently this reduces quick look size down to
// 96 bytes from 512 bytes.
var reducedBA = Array(bitArrays.reversed())
reducedBA = Array(reducedBA.drop {
$0.words == [0x0]
})
bitArrays = reducedBA.reversed()
// Keep a record of every rank for all the bitarrays.
var ranks: [UInt16] = []
// Record our quick look ranks.
var lastRank: UInt16 = 0
for (i, _) in bitArrays.enumerated() {
guard i != 0 else {
ranks.append(0)
continue
}
var rank = UInt16(bitArrays[i - 1].words[0].nonzeroBitCount)
rank += lastRank
ranks.append(rank)
lastRank = rank
}
// Insert our quick look size at the beginning.
var size = BitArray(size: 64)
size.words = [UInt64(bitArrays.count)]
bitArrays.insert(size, at: 0)
var nameAliasData: [String] = []
for chunk in chunks {
var chunkBA = BitArray(size: chunkSize)
let lower = chunk * chunkSize
let upper = lower + chunkSize
let chunkDataIdx = UInt64(nameAliasData.endIndex)
// Insert our chunk's data index in the upper bits of the last word of our
// bit array.
chunkBA.words[chunkBA.words.endIndex - 1] |= chunkDataIdx << 16
for scalar in lower ..< upper {
if data.contains(where: { $0.0 == scalar }) {
chunkBA[scalar % chunkSize] = true
let data = data[data.firstIndex {
$0.0 == scalar
}!].1
nameAliasData.append(data)
}
}
// Append our chunk bit array's rank.
var lastRank: UInt16 = 0
for (i, _) in chunkBA.words.enumerated() {
guard i != 0 else {
ranks.append(0)
continue
}
var rank = UInt16(chunkBA.words[i - 1].nonzeroBitCount)
rank += lastRank
ranks.append(rank)
lastRank = rank
}
bitArrays += chunkBA.words.map {
var ba = BitArray(size: 64)
ba.words = [$0]
return ba
}
}
emitCollection(
nameAliasData,
name: "_swift_stdlib_nameAlias_data",
type: "char * const",
into: &result
) {
"\"\($0)\""
}
emitCollection(
ranks,
name: "_swift_stdlib_nameAlias_ranks",
into: &result
)
emitCollection(
bitArrays,
name: "_swift_stdlib_nameAlias",
type: "__swift_uint64_t",
into: &result
) {
assert($0.words.count == 1)
return "0x\(String($0.words[0], radix: 16, uppercase: true))"
}
}
func generateNameAliasProp(into result: inout String) {
let nameAliases = readFile("Data/NameAliases.txt")
var data: [(UInt32, String)] = []
getNameAliases(from: nameAliases, into: &data)
emitNameAliases(data, into: &result)
}
| apache-2.0 | 0c186773c36d4b60268cfd5ce12975fb | 24.588542 | 80 | 0.578262 | 3.889945 | false | false | false | false |
agrippa1994/iOS-PLC | Pods/Charts/Charts/Classes/Data/CombinedChartData.swift | 84 | 4151 | //
// CombinedChartData.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
public class CombinedChartData: BarLineScatterCandleChartData
{
private var _lineData: LineChartData!
private var _barData: BarChartData!
private var _scatterData: ScatterChartData!
private var _candleData: CandleChartData!
private var _bubbleData: BubbleChartData!
public override init()
{
super.init()
}
public override init(xVals: [String?]?, dataSets: [ChartDataSet]?)
{
super.init(xVals: xVals, dataSets: dataSets)
}
public override init(xVals: [NSObject]?, dataSets: [ChartDataSet]?)
{
super.init(xVals: xVals, dataSets: dataSets)
}
public var lineData: LineChartData!
{
get
{
return _lineData
}
set
{
_lineData = newValue
for dataSet in newValue.dataSets
{
_dataSets.append(dataSet)
}
checkIsLegal(newValue.dataSets)
calcMinMax(start: _lastStart, end: _lastEnd)
calcYValueSum()
calcYValueCount()
calcXValAverageLength()
}
}
public var barData: BarChartData!
{
get
{
return _barData
}
set
{
_barData = newValue
for dataSet in newValue.dataSets
{
_dataSets.append(dataSet)
}
checkIsLegal(newValue.dataSets)
calcMinMax(start: _lastStart, end: _lastEnd)
calcYValueSum()
calcYValueCount()
calcXValAverageLength()
}
}
public var scatterData: ScatterChartData!
{
get
{
return _scatterData
}
set
{
_scatterData = newValue
for dataSet in newValue.dataSets
{
_dataSets.append(dataSet)
}
checkIsLegal(newValue.dataSets)
calcMinMax(start: _lastStart, end: _lastEnd)
calcYValueSum()
calcYValueCount()
calcXValAverageLength()
}
}
public var candleData: CandleChartData!
{
get
{
return _candleData
}
set
{
_candleData = newValue
for dataSet in newValue.dataSets
{
_dataSets.append(dataSet)
}
checkIsLegal(newValue.dataSets)
calcMinMax(start: _lastStart, end: _lastEnd)
calcYValueSum()
calcYValueCount()
calcXValAverageLength()
}
}
public var bubbleData: BubbleChartData!
{
get
{
return _bubbleData
}
set
{
_bubbleData = newValue
for dataSet in newValue.dataSets
{
_dataSets.append(dataSet)
}
checkIsLegal(newValue.dataSets)
calcMinMax(start: _lastStart, end: _lastEnd)
calcYValueSum()
calcYValueCount()
calcXValAverageLength()
}
}
public override func notifyDataChanged()
{
if (_lineData !== nil)
{
_lineData.notifyDataChanged()
}
if (_barData !== nil)
{
_barData.notifyDataChanged()
}
if (_scatterData !== nil)
{
_scatterData.notifyDataChanged()
}
if (_candleData !== nil)
{
_candleData.notifyDataChanged()
}
if (_bubbleData !== nil)
{
_bubbleData.notifyDataChanged()
}
}
}
| mit | 1ab5d0d9d4932c0cf789c9a5220ff273 | 21.807692 | 71 | 0.486389 | 5.749307 | false | false | false | false |
tavultesoft/keymanweb | oem/firstvoices/ios/FirstVoices/KeyboardTableController.swift | 1 | 5399 | /*
* KeyboardTableController.swift
* FirstVoices app
*
* License: MIT
*
* Copyright © 2022 FirstVoices.
*
* Created by Shawn Schantz on 2022-01-13.
*
* The main screen of the app containing the list (UITableView) of FirstVoices keyboards.
* From here, users can tap on a keyboard which will cause it to transition to a detail page for that keyboard, or
* they can tap on the info icon for a keyboard which will load the help web page for the keyboard in the browser.
*
*/
import UIKit
let keymanHelpSite: String = "https://help.keyman.com/keyboard/"
/*
* define protocol so that KeyboardDetailController can send message to update state of checkmark in keyboard list
*/
protocol RefreshKeyboardCheckmark {
func refreshCheckmark()
}
class KeyboardTableController: UIViewController, RefreshKeyboardCheckmark {
var settingsRepo = KeyboardSettingsRepository.shared
/*
* mark the row to be reloaded after return segue -- it can be reloaded immediately
* when the state changes because it is outside the view hierachy until the user
* navigates back
*/
func refreshCheckmark() {
self.rowToReload = self.selectedKeyboardIndex
}
@IBOutlet weak var tableView: UITableView!
var selectedKeyboardIndex: IndexPath = IndexPath(row: 0, section: 0)
private var _keyboardList: FVRegionList!
private var keyboardList: FVRegionList {
get {
if _keyboardList == nil {
_keyboardList = FVRegionStorage.load()
}
return _keyboardList!
}
}
private var rowToReload: IndexPath? = nil
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController!.isNavigationBarHidden = false
navigationController?.setToolbarHidden(true, animated: false)
}
/*
* Needed to override to add the checkmark to the keyboard that has just been made active. Cannot call reloadRows before the view appears because it causes layout.
*/
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if(rowToReload != nil) {
let rows: [IndexPath] = [rowToReload!]
self.tableView.reloadRows(at: rows, with: UITableView.RowAnimation.none)
self.rowToReload = nil;
}
}
/*
* Segue to keyboard details screen.
* Before the segue, call the details view controller and pass the state of the keyboard and
* a reference to self to be called back to update the row if the state changes.
*/
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "keyboardDetails" {
let detailsController = segue.destination as! KeyboardDetailController
let indexPath = self.tableView.indexPathForSelectedRow
let keyboards = (self.keyboardList[indexPath!.section]).keyboards
let keyboard = keyboards[indexPath!.row]
if let keyboardState: KeyboardState = settingsRepo.loadKeyboardState(keyboardId: keyboard.id) {
detailsController.configure(delegate: self, keyboard: keyboardState)
} else {
print("Could not find keyboard \(keyboard.id) in available keyboards list.")
}
}
}
// TODO: stop using deprecated openURL method when we upgrade to iOS 10 or later
func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
let keyboards: FVKeyboardList = (self.keyboardList[indexPath.section]).keyboards
let keyboard: FVKeyboard = keyboards[indexPath.row]
let helpUrl: URL = URL.init(string: "\(keymanHelpSite)\(keyboard.id)")!
UIApplication.shared.openURL(helpUrl)
}
func reportFatalError(message: String) {
let alertController = UIAlertController(title: title, message: message,
preferredStyle: UIAlertController.Style.alert)
alertController.addAction(UIAlertAction(title: "OK",
style: UIAlertAction.Style.cancel,
handler: nil))
self.present(alertController, animated: true, completion: nil)
print(message)
// TODO: send the error message + call stack through to us
// some reporting mechanism
}
}
extension KeyboardTableController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return self.keyboardList.count
}
func tableView(_ tableView: UITableView,
titleForHeaderInSection section: Int) -> String? {
return self.keyboardList[section].name
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.selectedKeyboardIndex = indexPath
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.keyboardList[section].keyboards.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let keyboards = (self.keyboardList[indexPath.section]).keyboards
let keyboard = keyboards[indexPath.row]
let keyboardState = settingsRepo.loadKeyboardState(keyboardId: keyboard.id)
let cell = tableView.dequeueReusableCell(withIdentifier: "KeyboardCell")
cell!.textLabel!.text = keyboardState?.name
cell!.imageView?.isHidden = !keyboardState!.isActive
return cell!
}
}
| apache-2.0 | c44cea9a1484011b8e3c29e1425d1fde | 33.825806 | 165 | 0.71545 | 4.739245 | false | false | false | false |
RedRoma/Lexis-Database | LexisDatabase/UserDefaultsPersistence.swift | 1 | 3983 | //
// UserDefaultsPersistence.swift
// LexisDatabase
//
// Created by Wellington Moreno on 9/17/16.
// Copyright © 2016 RedRoma, Inc. All rights reserved.
//
import AlchemySwift
import Archeota
import Foundation
class UserDefaultsPersistence: LexisPersistence
{
private let suite = "tech.redroma.LexisDatabase"
private let key: String
private let defaults: UserDefaults
private let serializer = BasicJSONSerializer.instance
var synchronize = false
/**
Asynchronous loading
*/
private static let parallelism = 4
private let async: OperationQueue = {
let queue = OperationQueue()
queue.maxConcurrentOperationCount = UserDefaultsPersistence.parallelism
return queue
}()
private init?()
{
key = "\(suite).Persistence"
self.defaults = UserDefaults(suiteName: suite) ?? UserDefaults.standard
}
static let instance = UserDefaultsPersistence()
func save(words: [LexisWord]) throws
{
LOG.info("Saving \(words.count) words to UserDefaults")
let pieces = words.split(into: UserDefaultsPersistence.parallelism)
let serializedWords = NSMutableArray()
LOG.debug("Serializing \(words.count) in \(UserDefaultsPersistence.parallelism) threads")
let semaphore = DispatchSemaphore(value: 1)
let group = DispatchGroup()
for piece in pieces {
group.enter()
async.addOperation() {
let convertedWords = piece.compactMap { word in
return word.asJSON() as? NSDictionary
}
LOG.debug("Converted \(convertedWords.count) words")
semaphore.wait()
serializedWords.addObjects(from: convertedWords)
semaphore.signal()
group.leave()
}
}
group.wait()
defaults.set(serializedWords, forKey: key)
LOG.info("Saved \(serializedWords.count) words to UserDefaults")
if synchronize
{
defaults.synchronize()
}
}
func getAllWords() -> [LexisWord]
{
LOG.info("Loading Lexis Words")
guard let array = defaults.object(forKey: key) as? NSArray
else
{
LOG.info("Failed to find LexisDatabase in UserDefaults")
return []
}
LOG.info("Found \(array.count) words in UserDefaults")
guard let words = array as? [NSDictionary]
else
{
LOG.warn("Failed to convert NSArray to [NSDictionary]")
return []
}
let pieces = words.split(into: UserDefaultsPersistence.parallelism)
var lexisWords = [LexisWord]()
LOG.debug("Converting objects in \(pieces.count) threads")
let semaphore = DispatchSemaphore(value: 1)
let group = DispatchGroup()
for words in pieces {
group.enter()
async.addOperation() {
let convertedWords = words.compactMap { dictionary in
return (LexisWord.fromJSON(json: dictionary) as? LexisWord)
}
semaphore.wait()
lexisWords += convertedWords
LOG.debug("Converted \(convertedWords.size) words")
semaphore.signal()
group.leave()
}
}
group.wait()
LOG.info("Converted [\(lexisWords.size)] words from [\(words.size)] in JSON Array")
return lexisWords
}
func removeAll()
{
defaults.set(nil, forKey: key)
LOG.info("Clearing all words from UserDefaults")
if synchronize
{
defaults.synchronize()
}
}
}
| apache-2.0 | 58f49f151f94ed216cb98d60769bbb14 | 26.088435 | 97 | 0.550477 | 5.410326 | false | false | false | false |
yrchen/edx-app-ios | Source/CourseOutlineTableSource.swift | 1 | 9763 | //
// CourseOutlineTableSource.swift
// edX
//
// Created by Akiva Leffert on 4/30/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
protocol CourseOutlineTableControllerDelegate : class {
func outlineTableController(controller : CourseOutlineTableController, choseBlock:CourseBlock, withParentID:CourseBlockID)
func outlineTableController(controller : CourseOutlineTableController, choseDownloadVideos videos:[OEXHelperVideoDownload], rootedAtBlock block: CourseBlock)
func outlineTableController(controller : CourseOutlineTableController, choseDownloadVideoForBlock block:CourseBlock)
func outlineTableControllerChoseShowDownloads(controller : CourseOutlineTableController)
}
class CourseOutlineTableController : UITableViewController, CourseVideoTableViewCellDelegate, CourseSectionTableViewCellDelegate {
struct Environment {
let dataManager : DataManager
}
weak var delegate : CourseOutlineTableControllerDelegate?
private let environment : Environment
private let courseQuerier : CourseOutlineQuerier
private let headerContainer = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 44))
private let lastAccessedView = CourseOutlineHeaderView(frame: CGRectZero, styles: OEXStyles.sharedStyles(), titleText : Strings.lastAccessed, subtitleText : "Placeholder")
let refreshController = PullRefreshController()
init(environment : Environment, courseID : String) {
self.environment = environment
self.courseQuerier = environment.dataManager.courseDataManager.querierForCourseWithID(courseID)
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var groups : [CourseOutlineQuerier.BlockGroup] = []
var highlightedBlockID : CourseBlockID? = nil
override func viewDidLoad() {
tableView.dataSource = self
tableView.delegate = self
tableView.tableFooterView = UIView(frame: CGRectZero)
tableView.registerClass(CourseOutlineHeaderCell.self, forHeaderFooterViewReuseIdentifier: CourseOutlineHeaderCell.identifier)
tableView.registerClass(CourseVideoTableViewCell.self, forCellReuseIdentifier: CourseVideoTableViewCell.identifier)
tableView.registerClass(CourseHTMLTableViewCell.self, forCellReuseIdentifier: CourseHTMLTableViewCell.identifier)
tableView.registerClass(CourseProblemTableViewCell.self, forCellReuseIdentifier: CourseProblemTableViewCell.identifier)
tableView.registerClass(CourseUnknownTableViewCell.self, forCellReuseIdentifier: CourseUnknownTableViewCell.identifier)
tableView.registerClass(CourseSectionTableViewCell.self, forCellReuseIdentifier: CourseSectionTableViewCell.identifier)
headerContainer.addSubview(lastAccessedView)
lastAccessedView.snp_makeConstraints { (make) -> Void in
make.edges.equalTo(self.headerContainer)
}
refreshController.setupInScrollView(self.tableView)
}
private func indexPathForBlockWithID(blockID : CourseBlockID) -> NSIndexPath? {
for (i, group) in groups.enumerate() {
for (j, block) in group.children.enumerate() {
if block.blockID == blockID {
return NSIndexPath(forRow: j, inSection: i)
}
}
}
return nil
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let highlightID = highlightedBlockID, indexPath = indexPathForBlockWithID(highlightID)
{
tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Middle, animated: false)
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return groups.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let group = groups[section]
return group.children.count
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// Will remove manual heights when dropping iOS7 support and move to automatic cell heights.
return 60.0
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let group = groups[section]
let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier(CourseOutlineHeaderCell.identifier) as! CourseOutlineHeaderCell
header.block = group.block
return header
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let group = groups[indexPath.section]
let nodes = group.children
let block = nodes[indexPath.row]
switch nodes[indexPath.row].displayType {
case .Video:
let cell = tableView.dequeueReusableCellWithIdentifier(CourseVideoTableViewCell.identifier, forIndexPath: indexPath) as! CourseVideoTableViewCell
cell.block = block
cell.localState = OEXInterface.sharedInterface().stateForVideoWithID(block.blockID, courseID : courseQuerier.courseID)
cell.delegate = self
return cell
case .HTML(.Base):
let cell = tableView.dequeueReusableCellWithIdentifier(CourseHTMLTableViewCell.identifier, forIndexPath: indexPath) as! CourseHTMLTableViewCell
cell.block = block
return cell
case .HTML(.Problem):
let cell = tableView.dequeueReusableCellWithIdentifier(CourseProblemTableViewCell.identifier, forIndexPath: indexPath) as! CourseProblemTableViewCell
cell.block = block
return cell
case .Unknown:
let cell = tableView.dequeueReusableCellWithIdentifier(CourseUnknownTableViewCell.identifier, forIndexPath: indexPath) as! CourseUnknownTableViewCell
cell.block = block
return cell
case .Outline, .Unit:
let cell = tableView.dequeueReusableCellWithIdentifier(CourseSectionTableViewCell.identifier, forIndexPath: indexPath) as! CourseSectionTableViewCell
cell.block = nodes[indexPath.row]
let videoStream = courseQuerier.flatMapRootedAtBlockWithID(block.blockID) { block in
(block.type.asVideo != nil) ? block.blockID : nil
}
let courseID = courseQuerier.courseID
cell.videos = videoStream.map({[weak self] videoIDs in
self?.environment.dataManager.interface?.statesForVideosWithIDs(videoIDs, courseID: courseID) ?? []
})
cell.delegate = self
return cell
}
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
guard let cell = cell as? CourseBlockContainerCell else {
assertionFailure("All course outline cells should implement CourseBlockContainerCell")
return
}
let highlighted = cell.block?.blockID != nil && cell.block?.blockID == self.highlightedBlockID
cell.applyStyle(highlighted ? .Highlighted : .Normal)
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let group = groups[indexPath.section]
let chosenBlock = group.children[indexPath.row]
self.delegate?.outlineTableController(self, choseBlock: chosenBlock, withParentID: group.block.blockID)
}
override func scrollViewDidScroll(scrollView: UIScrollView) {
self.refreshController.scrollViewDidScroll(scrollView)
}
func videoCellChoseDownload(cell: CourseVideoTableViewCell, block : CourseBlock) {
self.delegate?.outlineTableController(self, choseDownloadVideoForBlock: block)
}
func videoCellChoseShowDownloads(cell: CourseVideoTableViewCell) {
self.delegate?.outlineTableControllerChoseShowDownloads(self)
}
func sectionCellChoseShowDownloads(cell: CourseSectionTableViewCell) {
self.delegate?.outlineTableControllerChoseShowDownloads(self)
}
func sectionCellChoseDownload(cell: CourseSectionTableViewCell, videos: [OEXHelperVideoDownload], forBlock block : CourseBlock) {
self.delegate?.outlineTableController(self, choseDownloadVideos: videos, rootedAtBlock:block)
}
func choseViewLastAccessedWithItem(item : CourseLastAccessed) {
for group in groups {
let childNodes = group.children
let currentLastViewedIndex = childNodes.firstIndexMatching({$0.blockID == item.moduleId})
if let matchedIndex = currentLastViewedIndex {
self.delegate?.outlineTableController(self, choseBlock: childNodes[matchedIndex], withParentID: group.block.blockID)
break
}
}
}
/// Shows the last accessed Header from the item as argument. Also, sets the relevant action if the course block exists in the course outline.
func showLastAccessedWithItem(item : CourseLastAccessed) {
tableView.tableHeaderView = self.headerContainer
lastAccessedView.subtitleText = item.moduleName
lastAccessedView.setViewButtonAction { [weak self] _ in
self?.choseViewLastAccessedWithItem(item)
}
}
func hideLastAccessed() {
tableView.tableHeaderView = nil
}
} | apache-2.0 | 7085496133c8a463474bfee065a8964d | 46.629268 | 175 | 0.7131 | 5.640092 | false | false | false | false |
society2012/PGDBK | PGDBK/PGDBK/Code/Home/Controller/HomeViewController.swift | 1 | 4057 | //
// HomeViewController.swift
// PGDBK
//
// Created by hupeng on 2017/7/5.
// Copyright © 2017年 m.zintao. All rights reserved.
//
import UIKit
import MJRefresh
import SVProgressHUD
let kHomeNoteCell = "kHomeNoteCell"
class HomeViewController: BaseViewController {
var homeTable:UITableView?
var carId:String = "999"
var page:Int = 1
lazy var dataSource:[NoteModel] = [NoteModel]()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "首页"
setupTable()
setupData()
}
func setupTable() -> Void {
homeTable = UITableView(frame: self.view.bounds, style: .plain)
homeTable?.tableFooterView = UIView()
homeTable?.delegate = self
homeTable?.dataSource = self
homeTable?.rowHeight = 120
homeTable?.autoresizingMask = [.flexibleWidth,.flexibleHeight]
homeTable?.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadNewData))
homeTable?.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMoreData))
let nib = UINib(nibName: "NoteTableViewCell", bundle: nil)
homeTable?.register(nib, forCellReuseIdentifier: kHomeNoteCell)
self.view .addSubview(homeTable!)
}
func setupData() -> Void {
SVProgressHUD.show(withStatus: "加载中")
SVProgressHUD.setDefaultStyle(.dark)
let url = SERVER_IP + "/index.php/api/AppInterface/getCatArticle"
let parmertas:[String:Any] = ["id":self.carId,"page":page,"pagesize":10]
NetWorkTools.requestData(URLString: url, type: .post, parmertas: parmertas) { (response) in
SVProgressHUD.dismiss()
guard let dic = response as? [String:Any] else{return}
guard let data = dic["data"] as?[[String:Any]] else{return}
let code = dic["code"] as?Int
self.homeTable?.mj_header.endRefreshing()
self.homeTable?.mj_footer.endRefreshing()
self.homeTable?.mj_footer.isHidden = false
if(data.count < 10){
self.homeTable?.mj_footer.isHidden = true
}
if(code == 200){
if(self.page == 1){
self.dataSource.removeAll()
}
for dic in data {
let model = NoteModel()
model.desc = dic["desc"] as?String
model.id = dic["id"] as?String
model.pic = dic["pic"] as?String
model.time = dic["time"] as?String
model.title = dic["title"] as?String
self.dataSource.append(model)
}
self.homeTable?.reloadData()
}
}
}
}
extension HomeViewController{
func loadMoreData() -> Void {
page = page + 1
setupData()
}
func loadNewData() -> Void {
page = 1
setupData()
}
}
extension HomeViewController:UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSource.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let model = self.dataSource[indexPath.row]
let detail = NoteDetailViewController(nibName: "NoteDetailViewController", bundle: nil)
detail.noteId = model.id!
self.navigationController?.pushViewController(detail, animated: true)
tableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: kHomeNoteCell, for: indexPath) as?NoteTableViewCell
cell?.newModel = self.dataSource[indexPath.row]
return cell!
}
}
| mit | 5a485bcc68426cdb8b9b698653d4c72d | 32.983193 | 124 | 0.596686 | 4.729825 | false | false | false | false |
chicio/HackerRank | 30DaysOfCode/Day4ClassvsInstance.swift | 1 | 1081 | //
// Day4ClassvsInstance.swift
// HackerRank
//
// Created by Fabrizio Duroni on 21/09/2016.
//
// https://www.hackerrank.com/challenges/30-class-vs-instance
import Foundation
public class Person {
private var age:Int
init(initialAge initAge:Int) {
if(initAge < 0) {
age = 0
print("Age is not valid, setting age to 0.")
} else {
age = initAge
}
}
public func yearPasses() {
age = age + 1
}
public func amIOld() {
switch age {
case 0 ... 12:
print("You are young.")
case 13 ... 17:
print("You are a teenager.")
default:
print("You are old.")
}
}
}
var t = Int(readLine(strippingNewline: true)!)!
while t > 0 {
let age = Int(readLine(strippingNewline: true)!)!
var p = Person(initialAge: age)
p.amIOld()
for i in 1 ... 3 {
p.yearPasses()
}
p.amIOld()
print("")
t = t - 1 // decrement t
}
| mit | 31bbd5577f5a00a5762d59ace26d68f7 | 16.435484 | 62 | 0.484736 | 3.846975 | false | false | false | false |
michael-lehew/swift-corelibs-foundation | Foundation/NSSpecialValue.swift | 1 | 4843 | // 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
//
internal protocol NSSpecialValueCoding {
static func objCType() -> String
init(bytes value: UnsafeRawPointer)
func encodeWithCoder(_ aCoder: NSCoder)
init?(coder aDecoder: NSCoder)
func getValue(_ value: UnsafeMutableRawPointer)
// Ideally we would make NSSpecialValue a generic class and specialise it for
// NSPoint, etc, but then we couldn't implement NSValue.init?(coder:) because
// it's not yet possible to specialise classes with a type determined at runtime.
//
// Nor can we make NSSpecialValueCoding conform to Equatable because it has associated
// type requirements.
//
// So in order to implement equality and hash we have the hack below.
func isEqual(_ value: Any) -> Bool
var hash: Int { get }
var description: String? { get }
}
internal class NSSpecialValue : NSValue {
// Originally these were functions in NSSpecialValueCoding but it's probably
// more convenient to keep it as a table here as nothing else really needs to
// know about them
private static let _specialTypes : Dictionary<Int, NSSpecialValueCoding.Type> = [
1 : NSPoint.self,
2 : NSSize.self,
3 : NSRect.self,
4 : NSRange.self,
12 : NSEdgeInsets.self
]
private static func _typeFromFlags(_ flags: Int) -> NSSpecialValueCoding.Type? {
return _specialTypes[flags]
}
private static func _flagsFromType(_ type: NSSpecialValueCoding.Type) -> Int {
for (F, T) in _specialTypes {
if T == type {
return F
}
}
return 0
}
private static func _objCTypeFromType(_ type: NSSpecialValueCoding.Type) -> String? {
for (_, T) in _specialTypes {
if T == type {
return T.objCType()
}
}
return nil
}
internal static func _typeFromObjCType(_ type: UnsafePointer<Int8>) -> NSSpecialValueCoding.Type? {
let objCType = String(cString: type)
for (_, T) in _specialTypes {
if T.objCType() == objCType {
return T
}
}
return nil
}
internal var _value : NSSpecialValueCoding
init(_ value: NSSpecialValueCoding) {
self._value = value
}
required init(bytes value: UnsafeRawPointer, objCType type: UnsafePointer<Int8>) {
guard let specialType = NSSpecialValue._typeFromObjCType(type) else {
NSUnimplemented()
}
self._value = specialType.init(bytes: value)
}
override func getValue(_ value: UnsafeMutableRawPointer) {
self._value.getValue(value)
}
convenience required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
let specialFlags = aDecoder.decodeInteger(forKey: "NS.special")
guard let specialType = NSSpecialValue._typeFromFlags(specialFlags) else {
return nil
}
guard let specialValue = specialType.init(coder: aDecoder) else {
return nil
}
self.init(specialValue)
}
override func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(NSSpecialValue._flagsFromType(type(of: _value)), forKey: "NS.special")
_value.encodeWithCoder(aCoder)
}
override var objCType : UnsafePointer<Int8> {
let typeName = NSSpecialValue._objCTypeFromType(type(of: _value))
return typeName!._bridgeToObjectiveC().utf8String! // leaky
}
override var classForCoder: AnyClass {
// for some day when we support class clusters
return NSValue.self
}
override var description : String {
if let description = _value.description {
return description
} else {
return super.description
}
}
override func isEqual(_ value: Any?) -> Bool {
if let object = value as? NSObject {
if self === object {
return true
} else if let special = object as? NSSpecialValue {
return _value.isEqual(special._value)
}
}
return false
}
override var hash: Int {
return _value.hash
}
}
| apache-2.0 | 863da3fd85345605abbf8f46fadff584 | 31.286667 | 103 | 0.611398 | 4.715677 | false | false | false | false |
MengQuietly/MQDouYuTV | MQDouYuTV/MQDouYuTV/Classes/Main/Model/MQAnchorGroupModel.swift | 1 | 1081 | //
// MQAnchorGroupModel.swift
// MQDouYuTV
//
// Created by mengmeng on 16/12/26.
// Copyright © 2016年 mengQuietly. All rights reserved.
// 主播组信息
import UIKit
class MQAnchorGroupModel: MQBaseGameModel {
/// 该组中对应的房间列表
var room_list : [[String: NSObject]]?{
didSet {
guard let room_list = room_list else { return }
for dict in room_list{
anchorList.append(MQAnchorModel(dict: dict))
}
}
}
/// 该组显示的icon
var icon_name : String = "home_header_normal"
/// 定义主播模型对象数组
lazy var anchorList:[MQAnchorModel] = [MQAnchorModel]()
/* 使用 KVC 转换,或者直接食用 list 的didSet 替代
override func setValue(_ value: Any?, forKey key: String) {
if key == "room_list" {
if let dataArr = value as? [[String:NSObject]] {
for dict in dataArr{
anchorList.append(MQAnchorModel(dict: dict))
}
}
}
} */
}
| mit | 247fa30594c7615e89b843db9845da4d | 25.052632 | 64 | 0.550505 | 3.913043 | false | false | false | false |
barijaona/vienna-rss | Vienna/Sources/Main window/WebKitArticleView.swift | 1 | 6871 | //
// WebKitArticleView.swift
// Vienna
//
// Copyright 2021 Barijaona Ramaholimihaso
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Cocoa
import WebKit
class WebKitArticleView: CustomWKWebView, ArticleContentView, WKNavigationDelegate, CustomWKUIDelegate {
var listView: ArticleViewDelegate?
var articles: [Article] = [] {
didSet {
guard !articles.isEmpty else {
self.loadHTMLString("<html><meta name=\"color-scheme\" content=\"light dark\"><body></body></html>", baseURL: URL.blank)
isHidden = true
return
}
deleteHtmlFile()
let htmlPath = converter.prepareArticleDisplay(self.articles)
self.htmlPath = htmlPath
self.loadFileURL(htmlPath, allowingReadAccessTo: htmlPath.deletingLastPathComponent())
isHidden = false
}
}
var htmlPath: URL?
let converter = WebKitArticleConverter()
let contextMenuCustomizer: BrowserContextMenuDelegate = WebKitContextMenuCustomizer()
@objc
init(frame: NSRect) {
super.init(frame: frame, configuration: WKWebViewConfiguration())
if responds(to: #selector(setter: _textZoomFactor)) {
_textZoomFactor = Preferences.standard.textSizeMultiplier
}
contextMenuProvider = self
}
@objc
func deleteHtmlFile() {
guard let htmlPath = htmlPath else {
return
}
do {
try FileManager.default.removeItem(at: htmlPath)
} catch {
}
}
override func load(_ request: URLRequest) -> WKNavigation? {
var navig: WKNavigation?
navig = super.load(request)
isHidden = false
return navig
}
/// handle special keys when the article view has the focus
override func keyDown(with event: NSEvent) {
if let pressedKeys = event.characters, pressedKeys.count == 1 {
let pressedKey = (pressedKeys as NSString).character(at: 0)
// give app controller preference when handling commands
if NSApp.appController.handleKeyDown(pressedKey, withFlags: event.modifierFlags.rawValue) {
return
}
}
super.keyDown(with: event)
}
func resetTextSize() {
makeTextStandardSize(self)
}
func decreaseTextSize() {
makeTextSmaller(self)
}
func increaseTextSize() {
makeTextLarger(self)
}
override func makeTextStandardSize(_ sender: Any?) {
super.makeTextStandardSize(sender)
if responds(to: #selector(getter: _textZoomFactor)) {
Preferences.standard.textSizeMultiplier = _textZoomFactor
}
}
override func makeTextLarger(_ sender: Any?) {
super.makeTextLarger(sender)
if responds(to: #selector(getter: _textZoomFactor)) {
Preferences.standard.textSizeMultiplier = _textZoomFactor
}
}
override func makeTextSmaller(_ sender: Any?) {
super.makeTextSmaller(sender)
if responds(to: #selector(getter: _textZoomFactor)) {
Preferences.standard.textSizeMultiplier = _textZoomFactor
}
}
// MARK: CustomWKUIDelegate
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
let browser = NSApp.appController.browser
if let webKitBrowser = browser as? TabbedBrowserViewController {
let newTab = webKitBrowser.createNewTab(navigationAction.request, config: configuration, inBackground: false)
if let webView = webView as? CustomWKWebView {
// The listeners are removed from the old webview userContentController on creating the new one, restore them
webView.resetScriptListeners()
}
return (newTab as? BrowserTab)?.webView
} else {
// Fallback for old browser
_ = browser?.createNewTab(navigationAction.request.url, inBackground: false, load: false)
return nil
}
}
func contextMenuItemsFor(purpose: WKWebViewContextMenuContext, existingMenuItems: [NSMenuItem]) -> [NSMenuItem] {
var menuItems = existingMenuItems
switch purpose {
case .page(url: _):
break
case .link(let url):
addLinkMenuCustomizations(&menuItems, url)
case .picture:
break
case .pictureLink(image: _, link: let link):
addLinkMenuCustomizations(&menuItems, link)
case .text:
break
}
return contextMenuCustomizer.contextMenuItemsFor(purpose: purpose, existingMenuItems: menuItems)
}
private func addLinkMenuCustomizations(_ menuItems: inout [NSMenuItem], _ url: (URL)) {
if let index = menuItems.firstIndex(where: { $0.identifier == .WKMenuItemOpenLink }) {
menuItems.remove(at: index)
}
if let index = menuItems.firstIndex(where: { $0.identifier == .WKMenuItemOpenLinkInNewWindow }) {
menuItems[index].title = NSLocalizedString("Open Link in New Tab", comment: "")
let openInBackgroundTitle = NSLocalizedString("Open Link in Background", comment: "")
let openInBackgroundItem = NSMenuItem(title: openInBackgroundTitle, action: #selector(openLinkInBackground(menuItem:)), keyEquivalent: "")
openInBackgroundItem.identifier = .WKMenuItemOpenLinkInBackground
openInBackgroundItem.representedObject = url
menuItems.insert(openInBackgroundItem, at: menuItems.index(after: index))
}
}
@objc
func openLinkInBackground(menuItem: NSMenuItem) {
if let url = menuItem.representedObject as? URL {
_ = NSApp.appController.browser.createNewTab(url, inBackground: true, load: true)
}
}
@objc
func openLinkInDefaultBrowser(menuItem: NSMenuItem) {
if let url = menuItem.representedObject as? URL {
NSApp.appController.openURL(inDefaultBrowser: url)
}
}
@objc
func contextMenuItemAction(menuItem: NSMenuItem) {
contextMenuCustomizer.contextMenuItemAction(menuItem: menuItem)
}
deinit {
deleteHtmlFile()
}
}
| apache-2.0 | 03dfeca4c4ba5a4a42fc1d9e2aae6d07 | 33.878173 | 187 | 0.648814 | 4.904354 | false | false | false | false |
teads/TeadsSDK-iOS | TeadsSampleApp/Controllers/InRead/Direct/ScrollView/InReadDirectScrollViewController.swift | 1 | 2979 | //
// InReadDirectScrollViewController.swift
// TeadsSampleApp
//
// Created by Jérémy Grosjean on 28/09/2017.
// Copyright © 2018 Teads. All rights reserved.
//
import TeadsSDK
import UIKit
class InReadDirectScrollViewController: TeadsViewController {
@IBOutlet var scrollDownImageView: TeadsGradientImageView!
@IBOutlet var teadsAdView: TeadsInReadAdView!
@IBOutlet var teadsAdHeightConstraint: NSLayoutConstraint!
var adRatio: TeadsAdRatio?
var placement: TeadsInReadAdPlacement?
override func viewDidLoad() {
super.viewDidLoad()
let pSettings = TeadsAdPlacementSettings { settings in
settings.enableDebug()
}
// keep a strong reference to placement instance
placement = Teads.createInReadPlacement(pid: Int(pid) ?? 0, settings: pSettings, delegate: self)
placement?.requestAd(requestSettings: TeadsAdRequestSettings { settings in
settings.pageUrl("https://www.teads.tv")
})
// We use an observer to know when a rotation happened, to resize the ad
// You can use whatever way you want to do so
NotificationCenter.default.addObserver(self, selector: #selector(rotationDetected), name: UIDevice.orientationDidChangeNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc func rotationDetected() {
if let adRatio = adRatio {
resizeTeadsAd(adRatio: adRatio)
}
}
func resizeTeadsAd(adRatio: TeadsAdRatio) {
self.adRatio = adRatio
teadsAdHeightConstraint.constant = adRatio.calculateHeight(for: teadsAdView.frame.width)
}
func closeAd() {
// be careful if you want to load another ad in the same page don't remove the observer
NotificationCenter.default.removeObserver(self)
teadsAdHeightConstraint.constant = 0
}
}
extension InReadDirectScrollViewController: TeadsInReadAdPlacementDelegate {
func adOpportunityTrackerView(trackerView: TeadsAdOpportunityTrackerView) {
teadsAdView.addSubview(trackerView)
}
func didReceiveAd(ad: TeadsInReadAd, adRatio: TeadsAdRatio) {
teadsAdView.bind(ad)
ad.delegate = self
resizeTeadsAd(adRatio: adRatio)
}
func didFailToReceiveAd(reason _: AdFailReason) {
closeAd()
}
func didUpdateRatio(ad _: TeadsInReadAd, adRatio: TeadsAdRatio) {
resizeTeadsAd(adRatio: adRatio)
}
}
extension InReadDirectScrollViewController: TeadsAdDelegate {
func willPresentModalView(ad _: TeadsAd) -> UIViewController? {
return self
}
func didCatchError(ad _: TeadsAd, error _: Error) {
closeAd()
}
func didClose(ad _: TeadsAd) {
closeAd()
}
func didRecordImpression(ad _: TeadsAd) {}
func didRecordClick(ad _: TeadsAd) {}
func didExpandedToFullscreen(ad _: TeadsAd) {}
func didCollapsedFromFullscreen(ad _: TeadsAd) {}
}
| mit | 9f300de72cb05ca012bb1bb90d2bd0f8 | 29.680412 | 153 | 0.689516 | 4.043478 | false | false | false | false |
teads/TeadsSDK-iOS | TeadsSampleApp/Controllers/TeadsViewController.swift | 1 | 3609 | //
// TeadsViewController.swift
// TeadsSampleApp
//
// Created by Jérémy Grosjean on 07/10/2020.
// Copyright © 2020 Teads. All rights reserved.
//
import UIKit
class TeadsViewController: UIViewController {
var hasTeadsArticleNavigationBar = true
var pid: String = PID.directLandscape
fileprivate let teadsLogo = UIImage(named: "Teads-Sample-App")
fileprivate let teadsLogoWhite = UIImage(named: "Teads-Sample-App-White")
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
hasTeadsArticleNavigationBar ? applyTeadsArticleNavigationBar() : applyDefaultNavigationBar()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
hasTeadsArticleNavigationBar ? applyTeadsArticleNavigationBar() : applyDefaultNavigationBar()
}
fileprivate func imageFromLayer(layer: CALayer) -> UIImage? {
UIGraphicsBeginImageContext(layer.frame.size)
layer.render(in: UIGraphicsGetCurrentContext()!)
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage
}
fileprivate func applyTeadsArticleNavigationBar() {
guard let navigationBar = navigationController?.navigationBar else {
return
}
let gradientLayer = CAGradientLayer()
gradientLayer.frame = navigationBar.bounds
gradientLayer.colors = [UIColor.teadsPurple.cgColor, UIColor.teadsBlue.cgColor]
gradientLayer.startPoint = CGPoint(x: 0, y: 1)
gradientLayer.endPoint = CGPoint(x: 1, y: 1)
let backgroundImage = imageFromLayer(layer: gradientLayer)
navigationBar.setBackgroundImage(backgroundImage, for: .default)
let imageView = UIImageView(image: teadsLogoWhite)
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.heightAnchor.constraint(equalToConstant: 30).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 200).isActive = true
navigationItem.titleView = imageView
navigationBar.tintColor = .white
if #available(iOS 15, *) {
navigationBar.barStyle = .black
let appearance = navigationBar.standardAppearance
appearance.backgroundImage = backgroundImage
navigationBar.standardAppearance = appearance
navigationBar.scrollEdgeAppearance = appearance
navigationBar.compactAppearance = appearance
}
}
fileprivate func applyDefaultNavigationBar() {
guard let navigationBar = navigationController?.navigationBar else {
return
}
navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
navigationBar.shadowImage = UIImage()
let imageView = UIImageView(image: teadsLogo)
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.heightAnchor.constraint(equalToConstant: 30).isActive = true
navigationItem.titleView = imageView
if #available(iOS 15, *) {
let appearance = navigationBar.standardAppearance
appearance.backgroundImage = UIImage()
appearance.shadowImage = UIImage()
navigationBar.standardAppearance = appearance
navigationBar.scrollEdgeAppearance = appearance
navigationBar.compactAppearance = appearance
}
}
}
| mit | 1bc632ba8fc9899113772f9d06eb7323 | 38.195652 | 101 | 0.7066 | 5.825525 | false | false | false | false |
ripventura/VCHTTPConnect | Example/Pods/EFQRCode/Source/EFQRCodeGenerator.swift | 2 | 28321 | //
// EFQRCodeGenerator.swift
// EFQRCode
//
// Created by EyreFree on 17/1/24.
//
// Copyright (c) 2017 EyreFree <[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.
#if os(watchOS)
import CoreGraphics
#else
import CoreImage
#endif
// EFQRCode+Create
public class EFQRCodeGenerator {
// MARK: - Parameters
// Content of QR Code
private var content: String? {
didSet {
imageQRCode = nil
imageCodes = nil
}
}
public func setContent(content: String) {
self.content = content
}
// Mode of QR Code
private var mode: EFQRCodeMode = .none {
didSet {
imageQRCode = nil
}
}
public func setMode(mode: EFQRCodeMode) {
self.mode = mode
}
// Error-tolerant rate
// L 7%
// M 15%
// Q 25%
// H 30%(Default)
private var inputCorrectionLevel: EFInputCorrectionLevel = .h {
didSet {
imageQRCode = nil
imageCodes = nil
}
}
public func setInputCorrectionLevel(inputCorrectionLevel: EFInputCorrectionLevel) {
self.inputCorrectionLevel = inputCorrectionLevel
}
// Size of QR Code
private var size: EFIntSize = EFIntSize(width: 256, height: 256) {
didSet {
imageQRCode = nil
}
}
public func setSize(size: EFIntSize) {
self.size = size
}
// Magnification of QRCode compare with the minimum size,
// (Parameter size will be ignored if magnification is not nil).
private var magnification: EFIntSize? {
didSet {
imageQRCode = nil
}
}
public func setMagnification(magnification: EFIntSize?) {
self.magnification = magnification
}
// backgroundColor
private var backgroundColor: CGColor = CGColor.EFWhite() {
didSet {
imageQRCode = nil
}
}
// foregroundColor
private var foregroundColor: CGColor = CGColor.EFBlack() {
didSet {
imageQRCode = nil
}
}
#if !os(watchOS)
public func setColors(backgroundColor: CIColor, foregroundColor: CIColor) {
self.backgroundColor = backgroundColor.toCGColor() ?? .EFWhite()
self.foregroundColor = foregroundColor.toCGColor() ?? .EFBlack()
}
#endif
public func setColors(backgroundColor: CGColor, foregroundColor: CGColor) {
self.backgroundColor = backgroundColor
self.foregroundColor = foregroundColor
}
// Icon in the middle of QR Code
private var icon: CGImage? = nil {
didSet {
imageQRCode = nil
}
}
// Size of icon
private var iconSize: EFIntSize? = nil {
didSet {
imageQRCode = nil
}
}
public func setIcon(icon: CGImage?, size: EFIntSize?) {
self.icon = icon
self.iconSize = size
}
// Watermark
private var watermark: CGImage? = nil {
didSet {
imageQRCode = nil
}
}
// Mode of watermark
private var watermarkMode: EFWatermarkMode = .scaleAspectFill {
didSet {
imageQRCode = nil
}
}
public func setWatermark(watermark: CGImage?, mode: EFWatermarkMode? = nil) {
self.watermark = watermark
if let mode = mode {
self.watermarkMode = mode
}
}
// Offset of foreground point
private var foregroundPointOffset: CGFloat = 0 {
didSet {
imageQRCode = nil
}
}
public func setForegroundPointOffset(foregroundPointOffset: CGFloat) {
self.foregroundPointOffset = foregroundPointOffset
}
// Alpha 0 area of watermark will transparent
private var allowTransparent: Bool = true {
didSet {
imageQRCode = nil
}
}
public func setAllowTransparent(allowTransparent: Bool) {
self.allowTransparent = allowTransparent
}
// Shape of foreground point
private var pointShape: EFPointShape = .square {
didSet {
imageQRCode = nil
}
}
public func setPointShape(pointShape: EFPointShape) {
self.pointShape = pointShape
}
// Threshold for binarization (Only for mode binarization).
private var binarizationThreshold: CGFloat = 0.5 {
didSet {
imageQRCode = nil
}
}
public func setBinarizationThreshold(binarizationThreshold: CGFloat) {
self.binarizationThreshold = binarizationThreshold
}
// Cache
private var imageCodes: [[Bool]]?
private var imageQRCode: CGImage?
private var minSuitableSize: EFIntSize!
// MARK: - Init
public init(
content: String,
size: EFIntSize = EFIntSize(width: 256, height: 256)
) {
self.content = content
self.size = size
}
// Final QRCode image
public func generate() -> CGImage? {
if nil == imageQRCode {
imageQRCode = createImageQRCode()
}
return imageQRCode
}
// MARK: - Draw
private func createImageQRCode() -> CGImage? {
var finalSize = self.size
let finalBackgroundColor = getBackgroundColor()
let finalForegroundColor = getForegroundColor()
let finalIcon = self.icon
let finalIconSize = self.iconSize
let finalWatermark = self.watermark
let finalWatermarkMode = self.watermarkMode
// Get QRCodes from image
guard let codes = generateCodes() else {
return nil
}
// If magnification is not nil, reset finalSize
if let tryMagnification = magnification {
finalSize = EFIntSize(
width: tryMagnification.width * codes.count, height: tryMagnification.height * codes.count
)
}
var result: CGImage?
if let context = createContext(size: finalSize) {
// Cache size
minSuitableSize = EFIntSize(
width: minSuitableSizeGreaterThanOrEqualTo(size: finalSize.widthCGFloat()) ?? finalSize.width,
height: minSuitableSizeGreaterThanOrEqualTo(size: finalSize.heightCGFloat()) ?? finalSize.height
)
// Watermark
if let tryWatermark = finalWatermark {
// Draw background with watermark
drawWatermarkImage(
context: context,
image: tryWatermark,
colorBack: finalBackgroundColor,
mode: finalWatermarkMode,
size: finalSize.toCGSize()
)
// Draw QR Code
if let tryFrontImage = createQRCodeImageTransparent(
codes: codes,
colorBack: finalBackgroundColor,
colorFront: finalForegroundColor,
size: minSuitableSize
) {
context.draw(tryFrontImage, in: CGRect(origin: .zero, size: finalSize.toCGSize()))
}
} else {
// Draw background without watermark
let colorCGBack = finalBackgroundColor
context.setFillColor(colorCGBack)
context.fill(CGRect(origin: .zero, size: finalSize.toCGSize()))
// Draw QR Code
if let tryImage = createQRCodeImage(
codes: codes,
colorBack: finalBackgroundColor,
colorFront: finalForegroundColor,
size: minSuitableSize
) {
context.draw(tryImage, in: CGRect(origin: .zero, size: finalSize.toCGSize()))
}
}
// Add icon
if let tryIcon = finalIcon {
var finalIconSizeWidth = CGFloat(finalSize.width) * 0.2
var finalIconSizeHeight = CGFloat(finalSize.width) * 0.2
if let tryFinalIconSize = finalIconSize {
finalIconSizeWidth = CGFloat(tryFinalIconSize.width)
finalIconSizeHeight = CGFloat(tryFinalIconSize.height)
}
let maxLength = [CGFloat(0.2), 0.3, 0.4, 0.5][inputCorrectionLevel.rawValue] * CGFloat(finalSize.width)
if finalIconSizeWidth > maxLength {
finalIconSizeWidth = maxLength
print("Warning: icon width too big, it has been changed.")
}
if finalIconSizeHeight > maxLength {
finalIconSizeHeight = maxLength
print("Warning: icon height too big, it has been changed.")
}
let iconSize = EFIntSize(width: Int(finalIconSizeWidth), height: Int(finalIconSizeHeight))
drawIcon(
context: context,
icon: tryIcon,
size: iconSize
)
}
result = context.makeImage()
}
// Mode apply
switch mode {
case .grayscale:
if let tryModeImage = result?.grayscale() {
result = tryModeImage
}
case .binarization:
if let tryModeImage = result?.binarization(
value: binarizationThreshold,
foregroundColor: foregroundColor,
backgroundColor: backgroundColor
) {
result = tryModeImage
}
default:
break
}
return result
}
private func getForegroundColor() -> CGColor {
if mode == .binarization {
return CGColor.EFBlack()
}
return foregroundColor
}
private func getBackgroundColor() -> CGColor {
if mode == .binarization {
return CGColor.EFWhite()
}
return backgroundColor
}
// Create Colorful QR Image
#if !os(watchOS)
private func createQRCodeImage(
codes: [[Bool]],
colorBack: CIColor,
colorFront: CIColor,
size: EFIntSize) -> CGImage? {
guard let colorCGFront = colorFront.toCGColor() else {
return nil
}
return createQRCodeImage(codes: codes, colorFront: colorCGFront, size: size)
}
#endif
private func createQRCodeImage(
codes: [[Bool]],
colorBack colorCGBack: CGColor? = nil,
colorFront colorCGFront: CGColor,
size: EFIntSize) -> CGImage? {
let scaleX = CGFloat(size.width) / CGFloat(codes.count)
let scaleY = CGFloat(size.height) / CGFloat(codes.count)
if scaleX < 1.0 || scaleY < 1.0 {
print("Warning: Size too small.")
}
let codeSize = codes.count
var result: CGImage?
if let context = createContext(size: size) {
// Point
context.setFillColor(colorCGFront)
for indexY in 0 ..< codeSize {
for indexX in 0 ..< codeSize where true == codes[indexX][indexY] {
// CTM-90
let indexXCTM = indexY
let indexYCTM = codeSize - indexX - 1
drawPoint(
context: context,
rect: CGRect(
x: CGFloat(indexXCTM) * scaleX + foregroundPointOffset,
y: CGFloat(indexYCTM) * scaleY + foregroundPointOffset,
width: scaleX - 2 * foregroundPointOffset,
height: scaleY - 2 * foregroundPointOffset
)
)
}
}
result = context.makeImage()
}
return result
}
// Create Colorful QR Image
#if !os(watchOS)
private func createQRCodeImageTransparent(
codes: [[Bool]],
colorBack: CIColor,
colorFront: CIColor,
size: EFIntSize) -> CGImage? {
guard let colorCGBack = colorBack.toCGColor(), let colorCGFront = colorFront.toCGColor() else {
return nil
}
return createQRCodeImageTransparent(codes: codes, colorBack: colorCGBack, colorFront: colorCGFront, size: size)
}
#endif
private func createQRCodeImageTransparent(
codes: [[Bool]],
colorBack colorCGBack: CGColor,
colorFront colorCGFront: CGColor,
size: EFIntSize) -> CGImage? {
let scaleX = CGFloat(size.width) / CGFloat(codes.count)
let scaleY = CGFloat(size.height) / CGFloat(codes.count)
if scaleX < 1.0 || scaleY < 1.0 {
print("Warning: Size too small.")
}
let codeSize = codes.count
let pointMinOffsetX = scaleX / 3
let pointMinOffsetY = scaleY / 3
let pointWidthOriX = scaleX
let pointWidthOriY = scaleY
let pointWidthMinX = scaleX - 2 * pointMinOffsetX
let pointWidthMinY = scaleY - 2 * pointMinOffsetY
// Get AlignmentPatternLocations first
var points = [EFIntPoint]()
if let locations = getAlignmentPatternLocations(version: getVersion(size: codeSize - 2)) {
for indexX in locations {
for indexY in locations {
let finalX = indexX + 1
let finalY = indexY + 1
if !((finalX == 7 && finalY == 7)
|| (finalX == 7 && finalY == (codeSize - 8))
|| (finalX == (codeSize - 8) && finalY == 7)) {
points.append(EFIntPoint(x: finalX, y: finalY))
}
}
}
}
var finalImage: CGImage?
if let context = createContext(size: size) {
// Back point
context.setFillColor(colorCGBack)
for indexY in 0 ..< codeSize {
for indexX in 0 ..< codeSize where false == codes[indexX][indexY] {
// CTM-90
let indexXCTM = indexY
let indexYCTM = codeSize - indexX - 1
if isStatic(x: indexX, y: indexY, size: codeSize, APLPoints: points) {
drawPoint(
context: context,
rect: CGRect(
x: CGFloat(indexXCTM) * scaleX,
y: CGFloat(indexYCTM) * scaleY,
width: pointWidthOriX,
height: pointWidthOriY
)
)
} else {
drawPoint(
context: context,
rect: CGRect(
x: CGFloat(indexXCTM) * scaleX + pointMinOffsetX,
y: CGFloat(indexYCTM) * scaleY + pointMinOffsetY,
width: pointWidthMinX,
height: pointWidthMinY
)
)
}
}
}
// Front point
context.setFillColor(colorCGFront)
for indexY in 0 ..< codeSize {
for indexX in 0 ..< codeSize where true == codes[indexX][indexY] {
// CTM-90
let indexXCTM = indexY
let indexYCTM = codeSize - indexX - 1
if isStatic(x: indexX, y: indexY, size: codeSize, APLPoints: points) {
drawPoint(
context: context,
rect: CGRect(
x: CGFloat(indexXCTM) * scaleX + foregroundPointOffset,
y: CGFloat(indexYCTM) * scaleY + foregroundPointOffset,
width: pointWidthOriX - 2 * foregroundPointOffset,
height: pointWidthOriY - 2 * foregroundPointOffset
)
)
} else {
drawPoint(
context: context,
rect: CGRect(
x: CGFloat(indexXCTM) * scaleX + pointMinOffsetX,
y: CGFloat(indexYCTM) * scaleY + pointMinOffsetY,
width: pointWidthMinX,
height: pointWidthMinY
)
)
}
}
}
finalImage = context.makeImage()
}
return finalImage
}
// Pre
#if !os(watchOS)
private func drawWatermarkImage(
context: CGContext,
image: CGImage,
colorBack: CIColor,
mode: EFWatermarkMode,
size: CGSize) {
drawWatermarkImage(context: context, image: image, colorBack: colorBack.toCGColor(), mode: mode, size: size)
}
#endif
private func drawWatermarkImage(
context: CGContext,
image: CGImage,
colorBack: CGColor?,
mode: EFWatermarkMode,
size: CGSize) {
// BGColor
if let tryColor = colorBack {
context.setFillColor(tryColor)
context.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
}
if allowTransparent {
guard let codes = generateCodes() else {
return
}
if let tryCGImage = createQRCodeImage(
codes: codes,
colorBack: getBackgroundColor(),
colorFront: getForegroundColor(),
size: minSuitableSize
) {
context.draw(tryCGImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
}
}
// Image
var finalSize = size
var finalOrigin = CGPoint.zero
let imageSize = CGSize(width: image.width, height: image.height)
switch mode {
case .bottom:
finalSize = imageSize
finalOrigin = CGPoint(x: (size.width - imageSize.width) / 2.0, y: 0)
case .bottomLeft:
finalSize = imageSize
finalOrigin = CGPoint(x: 0, y: 0)
case .bottomRight:
finalSize = imageSize
finalOrigin = CGPoint(x: size.width - imageSize.width, y: 0)
case .center:
finalSize = imageSize
finalOrigin = CGPoint(x: (size.width - imageSize.width) / 2.0, y: (size.height - imageSize.height) / 2.0)
case .left:
finalSize = imageSize
finalOrigin = CGPoint(x: 0, y: (size.height - imageSize.height) / 2.0)
case .right:
finalSize = imageSize
finalOrigin = CGPoint(x: size.width - imageSize.width, y: (size.height - imageSize.height) / 2.0)
case .top:
finalSize = imageSize
finalOrigin = CGPoint(x: (size.width - imageSize.width) / 2.0, y: size.height - imageSize.height)
case .topLeft:
finalSize = imageSize
finalOrigin = CGPoint(x: 0, y: size.height - imageSize.height)
case .topRight:
finalSize = imageSize
finalOrigin = CGPoint(x: size.width - imageSize.width, y: size.height - imageSize.height)
case .scaleAspectFill:
let scale = max(size.width / imageSize.width, size.height / imageSize.height)
finalSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
finalOrigin = CGPoint(x: (size.width - finalSize.width) / 2.0, y: (size.height - finalSize.height) / 2.0)
case .scaleAspectFit:
let scale = max(imageSize.width / size.width, imageSize.height / size.height)
finalSize = CGSize(width: imageSize.width / scale, height: imageSize.height / scale)
finalOrigin = CGPoint(x: (size.width - finalSize.width) / 2.0, y: (size.height - finalSize.height) / 2.0)
default:
break
}
context.draw(image, in: CGRect(origin: finalOrigin, size: finalSize))
}
private func drawIcon(context: CGContext, icon: CGImage, size: EFIntSize) {
context.draw(
icon,
in: CGRect(
origin: CGPoint(
x: CGFloat(context.width - size.width) / 2.0,
y: CGFloat(context.height - size.height) / 2.0
),
size: size.toCGSize()
)
)
}
private func drawPoint(context: CGContext, rect: CGRect) {
if pointShape == .circle {
context.fillEllipse(in: rect)
} else {
context.fill(rect)
}
}
private func createContext(size: EFIntSize) -> CGContext? {
return CGContext(
data: nil, width: size.width, height: size.height,
bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue
)
}
#if !os(watchOS)
// MARK: - Data
private func getPixels() -> [[EFUIntPixel]]? {
guard let finalContent = content else {
return nil
}
let finalInputCorrectionLevel = inputCorrectionLevel
guard let tryQRImagePixels = CIImage.generateQRCode(
string: finalContent, inputCorrectionLevel: finalInputCorrectionLevel
)?.toCGImage()?.pixels() else {
print("Warning: Content too large.")
return nil
}
return tryQRImagePixels
}
#endif
// Get QRCodes from pixels
private func getCodes(pixels: [[EFUIntPixel]]) -> [[Bool]] {
var codes = [[Bool]]()
for indexY in 0 ..< pixels.count {
codes.append([Bool]())
for indexX in 0 ..< pixels[0].count {
let pixel = pixels[indexY][indexX]
codes[indexY].append(
pixel.red == 0 && pixel.green == 0 && pixel.blue == 0
)
}
}
return codes
}
// Get QRCodes from pixels
private func generateCodes() -> [[Bool]]? {
if let tryImageCodes = imageCodes {
return tryImageCodes
}
func fetchPixels() -> [[Bool]]? {
#if os(iOS) || os(macOS) || os(tvOS)
// Get pixels from image
guard let tryQRImagePixels = getPixels() else {
return nil
}
// Get QRCodes from image
return getCodes(pixels: tryQRImagePixels)
#else
let level = inputCorrectionLevel.qrErrorCorrectLevel
if let finalContent = content,
let typeNumber = try? QRCodeType.typeNumber(of: finalContent, errorCorrectLevel: level),
let model = QRCodeModel(text: finalContent, typeNumber: typeNumber, errorCorrectLevel: level) {
return (0 ..< model.moduleCount).map {
r in
(0 ..< model.moduleCount).map {
c in
model.isDark(r, c)
}
}
}
return nil
#endif
}
imageCodes = fetchPixels()
return imageCodes
}
// Special Points of QRCode
private func isStatic(x: Int, y: Int, size: Int, APLPoints: [EFIntPoint]) -> Bool {
// Empty border
if x == 0 || y == 0 || x == (size - 1) || y == (size - 1) {
return true
}
// Finder Patterns
if (x <= 8 && y <= 8) || (x <= 8 && y >= (size - 9)) || (x >= (size - 9) && y <= 8) {
return true
}
// Timing Patterns
if x == 7 || y == 7 {
return true
}
// Alignment Patterns
for point in APLPoints {
if x >= (point.x - 2) && x <= (point.x + 2) && y >= (point.y - 2) && y <= (point.y + 2) {
return true
}
}
return false
}
// Alignment Pattern Locations
// http://stackoverflow.com/questions/13238704/calculating-the-position-of-qr-code-alignment-patterns
private func getAlignmentPatternLocations(version: Int) -> [Int]? {
if version == 1 {
return nil
}
let divs = 2 + version / 7
let size = getSize(version: version)
let total_dist = size - 7 - 6
let divisor = 2 * (divs - 1)
// Step must be even, for alignment patterns to agree with timing patterns
let step = (total_dist + divisor / 2 + 1) / divisor * 2 // Get the rounding right
var coords = [6]
// divs-2 down to 0, inclusive
for i in 0...(divs - 2) {
coords.append(size - 7 - (divs - 2 - i) * step)
}
return coords
}
// QRCode version
private func getVersion(size: Int) -> Int {
return (size - 21) / 4 + 1
}
// QRCode size
private func getSize(version: Int) -> Int {
return 17 + 4 * version
}
// Recommand magnification
public func minMagnificationGreaterThanOrEqualTo(size: CGFloat) -> Int? {
guard let codes = generateCodes() else {
return nil
}
let finalWatermark = watermark
let baseMagnification = max(1, Int(size / CGFloat(codes.count)))
for offset in [0, 1, 2, 3] {
let tempMagnification = baseMagnification + offset
if CGFloat(Int(tempMagnification) * codes.count) >= size {
if finalWatermark == nil {
return tempMagnification
} else if tempMagnification % 3 == 0 {
return tempMagnification
}
}
}
return nil
}
public func maxMagnificationLessThanOrEqualTo(size: CGFloat) -> Int? {
guard let codes = generateCodes() else {
return nil
}
let finalWatermark = watermark
let baseMagnification = max(1, Int(size / CGFloat(codes.count)))
for offset in [0, -1, -2, -3] {
let tempMagnification = baseMagnification + offset
if tempMagnification <= 0 {
return finalWatermark == nil ? 1 : 3
}
if CGFloat(tempMagnification * codes.count) <= size {
if finalWatermark == nil {
return tempMagnification
} else if tempMagnification % 3 == 0 {
return tempMagnification
}
}
}
return nil
}
// Calculate suitable size
private func minSuitableSizeGreaterThanOrEqualTo(size: CGFloat) -> Int? {
guard let codes = generateCodes() else {
return nil
}
let baseSuitableSize = Int(size)
for offset in 0...codes.count {
let tempSuitableSize = baseSuitableSize + offset
if tempSuitableSize % codes.count == 0 {
return tempSuitableSize
}
}
return nil
}
}
| mit | 455246ab8288ce96b10b44e9b3d2fecf | 33.622249 | 119 | 0.532361 | 4.854474 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Scenes/Surface placements/SurfacePlacementsViewController.swift | 1 | 6989 | //
// Copyright 2016 Esri.
//
// 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 ArcGIS
/// A view controller that manages the interface of the Surface Placements
/// sample.
class SurfacePlacementsViewController: UIViewController {
// MARK: Instance properties
/// A label to show the value of the slider.
@IBOutlet weak var zValueLabel: UILabel!
/// The slider to change z-value of `AGSPoint` geometries, from 0 to 140 in meters.
@IBOutlet weak var zValueSlider: UISlider! {
didSet {
zValueSlider.value = (zValueSlider.maximumValue + zValueSlider.minimumValue) / 2
}
}
/// The segmented control to toggle the visibility of two draped mode graphics overlays.
@IBOutlet weak var drapedModeSegmentedControl: UISegmentedControl!
/// The scene view managed by the view controller.
@IBOutlet var sceneView: AGSSceneView! {
didSet {
sceneView.scene = makeScene()
sceneView.setViewpointCamera(AGSCamera(latitude: 48.3889, longitude: -4.4595, altitude: 80, heading: 330, pitch: 97, roll: 0))
// Add graphics overlays of different surface placement modes to the scene.
let surfacePlacements: [AGSSurfacePlacement] = [
.drapedBillboarded,
.drapedFlat,
.relative,
.relativeToScene,
.absolute
]
let overlays = surfacePlacements.map(makeGraphicsOverlay)
overlaysBySurfacePlacement = Dictionary(uniqueKeysWithValues: zip(surfacePlacements, overlays))
sceneView.graphicsOverlays.addObjects(from: overlays)
}
}
/// A dictionary for graphics overlays of different surface placement modes.
var overlaysBySurfacePlacement = [AGSSurfacePlacement: AGSGraphicsOverlay]()
/// A formatter to format z-value strings.
let zValueFormatter: MeasurementFormatter = {
let formatter = MeasurementFormatter()
formatter.unitStyle = .short
formatter.unitOptions = .naturalScale
formatter.numberFormatter.maximumFractionDigits = 0
return formatter
}()
// MARK: - Actions
@IBAction func segmentedControlValueChanged(_ sender: UISegmentedControl) {
// Toggle the visibility of two draped mode graphics overlays respectively.
let isDrapedFlat = sender.selectedSegmentIndex == 1
overlaysBySurfacePlacement[.drapedFlat]!.isVisible = isDrapedFlat
overlaysBySurfacePlacement[.drapedBillboarded]!.isVisible = !isDrapedFlat
}
@IBAction func sliderValueChanged(_ sender: UISlider) {
let zValue = Double(sender.value)
zValueLabel.text = zValueFormatter.string(from: Measurement<UnitLength>(value: zValue, unit: .meters))
// Set the z-value of each geometry of surface placement graphics.
overlaysBySurfacePlacement.values.forEach { graphicOverlay in
graphicOverlay.graphics.forEach { graphic in
let g = graphic as! AGSGraphic
g.geometry = AGSGeometryEngine.geometry(bySettingZ: zValue, in: g.geometry!)
}
}
}
// MARK: Initialize scene and make graphics overlays
/// Create a scene.
///
/// - Returns: A new `AGSScene` object.
func makeScene() -> AGSScene {
let scene = AGSScene(basemapStyle: .arcGISImagery)
// Add a base surface for elevation data.
let surface = AGSSurface()
// Create elevation source from the Terrain 3D ArcGIS REST Service.
let worldElevationServiceURL = URL(string: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")!
let elevationSource = AGSArcGISTiledElevationSource(url: worldElevationServiceURL)
surface.elevationSources.append(elevationSource)
// Create scene layer from the Brest, France scene server.
let sceneServiceURL = URL(string: "https://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/Buildings_Brest/SceneServer")!
let sceneLayer = AGSArcGISSceneLayer(url: sceneServiceURL)
scene.baseSurface = surface
scene.operationalLayers.add(sceneLayer)
return scene
}
/// Create a graphics overlay for the given surface placement.
///
/// - Parameter surfacePlacement: The surface placement for which to create a graphics overlay.
/// - Returns: A new `AGSGraphicsOverlay` object.
func makeGraphicsOverlay(surfacePlacement: AGSSurfacePlacement) -> AGSGraphicsOverlay {
let markerSymbol = AGSSimpleMarkerSymbol(style: .triangle, color: .red, size: 20)
let textSymbol = AGSTextSymbol(text: surfacePlacement.title, color: .blue, size: 20, horizontalAlignment: .left, verticalAlignment: .middle)
// Add offset to avoid overlapping text and marker.
textSymbol.offsetY = 20
// Add offset to x and y of the geometry, to better differentiate certain geometries.
let offset = surfacePlacement == .relativeToScene ? 2e-4 : 0
let surfaceRelatedPoint = AGSPoint(x: -4.4609257 + offset, y: 48.3903965 + offset, z: 70, spatialReference: .wgs84())
let graphics = [markerSymbol, textSymbol].map { AGSGraphic(geometry: surfaceRelatedPoint, symbol: $0) }
let graphicsOverlay = AGSGraphicsOverlay()
graphicsOverlay.sceneProperties?.surfacePlacement = surfacePlacement
graphicsOverlay.graphics.addObjects(from: graphics)
return graphicsOverlay
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
// Add the source code button item to the right of navigation bar.
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["SurfacePlacementsViewController"]
// Initialize the slider and draped mode visibility.
segmentedControlValueChanged(drapedModeSegmentedControl)
sliderValueChanged(zValueSlider)
}
}
private extension AGSSurfacePlacement {
/// The human readable name of the surface placement.
var title: String {
switch self {
case .drapedBillboarded: return "Draped Billboarded"
case .absolute: return "Absolute"
case .relative: return "Relative"
case .relativeToScene: return "Relative to Scene"
case .drapedFlat: return "Draped Flat"
@unknown default: return "Unknown"
}
}
}
| apache-2.0 | 5470eb8a0ace11f89588e44de7c56cfe | 45.284768 | 148 | 0.688367 | 4.72549 | false | false | false | false |
hackersatcambridge/hac-website | Sources/HaCWebsiteLib/WorkshopManager.swift | 2 | 3805 | import Foundation
import DotEnv
import Dispatch
import Yaml
public struct WorkshopManager {
public enum Error: Swift.Error {
case updateFailed(String)
}
private static let directoryName = "workshops"
/// A concurrent queue used for parallelising workshop data updates
private static var updateQueue = DispatchQueue(
label: "com.hac.website.workshops-update-queue",
qos: .background,
attributes: .concurrent
)
private static var pollSource: DispatchSourceTimer! = nil
private static var currentlyUpdating = false
/// The list of Workshops as derived from the workshop repos last time they were processed. Keys are workshop IDs
public private(set) static var workshops: [String: Workshop] = [:]
/// All the workshop repos that we know about. Keys are workshop IDs
private static var workshopRepoUtils: [String: GitUtil] = [:]
public static func update() {
print("Updating workshops...")
// Prevent multiple updates at once (might happen if an update takes longer than the poll interval)
if !currentlyUpdating {
currentlyUpdating = true
updateRepoList()
updateWorkshopsData()
currentlyUpdating = false
}
print("Workshops updated")
}
public static func startPoll() {
let pollQueue = DispatchQueue(label: "com.hac.website.workshops-poll-timer", attributes: .concurrent)
pollSource?.cancel()
pollSource = DispatchSource.makeTimerSource(queue: pollQueue)
pollSource.setEventHandler {
update()
}
pollSource.schedule(
deadline: DispatchTime.now(),
repeating: .seconds(300),
leeway: .seconds(2)
)
pollSource.resume()
}
/// Update the list of workshop repositories synchronously. This does not update the workshops themselves
public static func updateRepoList() {
// Pull all the repos referenced by that
do {
let indexYamlString = try String(
contentsOf: URL(
string: "https://raw.githubusercontent.com/hackersatcambridge/workshops/master/workshops.yaml"
)!,
encoding: .utf8
)
let indexYaml = try Yaml.load(indexYamlString)
let workshopIDs = try stringsArray(for: "workshops", in: indexYaml)
for workshopID in workshopIDs {
let repoName = "workshop-\(workshopID)"
if workshopRepoUtils[workshopID] == nil {
workshopRepoUtils[workshopID] = GitUtil(
remoteRepoURL: "https://github.com/hackersatcambridge/\(repoName)",
directoryName: repoName
)
}
}
} catch {
print("Failed to update workshops index")
dump(error)
}
}
fileprivate static func stringsArray(for key: Yaml, in metadata: Yaml) throws -> [String] {
guard let values = metadata[key].array else {
throw Error.updateFailed("Couldn't find workshops index in workshops.yaml")
}
return try values.map({
if let stringValue = $0.string {
return stringValue
} else {
throw Error.updateFailed("Expected values in \(key) to be strings")
}
})
}
/// Update the in-memory copy of the workshops synchronously
public static func updateWorkshopsData() {
let updateDispatchGroup = DispatchGroup()
for (workshopID, repoUtil) in workshopRepoUtils {
updateDispatchGroup.enter()
updateQueue.async {
do {
repoUtil.update()
let updatedWorkshop = try Workshop(localPath: repoUtil.localRepoPath, headCommitSha: repoUtil.getHeadCommitSha())
workshops[workshopID] = updatedWorkshop
} catch {
print("Failed to initialise workshop from repo: workshop-\(workshopID)")
dump(error)
}
updateDispatchGroup.leave()
}
}
// Wait for all to finish
updateDispatchGroup.wait()
}
}
| mit | 0f7c9df4d3652b3af5dccbc663044e74 | 31.245763 | 123 | 0.672799 | 4.595411 | false | false | false | false |
kuhippo/swift-vuejs-starter | Package.swift | 1 | 1149 | //
// Package.swift
// PerfectTemplate
//
// Created by Kyle Jessup on 4/20/16.
// Copyright (C) 2016 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import PackageDescription
let package = Package(
name: "swiftStartKit",
targets: [],
dependencies: [
.Package(url: "https://github.com/PerfectlySoft/Perfect-HTTPServer.git", majorVersion: 2),
.Package(url: "https://github.com/PerfectlySoft/Perfect-PostgreSQL.git", majorVersion: 2, minor: 0),
.Package(url: "https://github.com/PerfectlySoft/Perfect-RequestLogger.git", majorVersion: 1),
.Package(url: "https://github.com/kylef/Stencil.git", majorVersion: 0, minor: 9),
.Package(url:"https://github.com/PerfectlySoft/Perfect-WebSockets.git", majorVersion: 2)
]
)
| mit | 3aff0d1991e7f694caafd1d0b65dc35d | 33.818182 | 102 | 0.609225 | 3.948454 | false | false | false | false |
mmremann/Hackathon | PushIt/PushIt/Controllers/DDPChallengeSetupViewController.swift | 1 | 2812 | //
// DDPChallengeSetupViewController.swift
// PushIt
//
// Created by Mann, Josh (US - Denver) on 9/25/15.
// Copyright © 2015 Mann, Josh (US - Denver). All rights reserved.
//
import UIKit
class DDPChallengeSetupViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func pushItRealGoodButtonPressed(sender: AnyObject) {
self.scheduleNotification()
self.scheduleNotification2()
}
func scheduleNotification() {
let now: NSDateComponents = NSCalendar.currentCalendar().components([.Hour, .Minute, .Second], fromDate: NSDate())
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let min = now.minute + ((now.second >= 50) ? 1: 0)
let date = cal.dateBySettingHour(now.hour, minute: min, second: (now.second + 10) % 60, ofDate: NSDate(), options: NSCalendarOptions())
let reminder = UILocalNotification()
reminder.fireDate = date
reminder.alertBody = "Do 12 pushups now!"
reminder.soundName = UILocalNotificationDefaultSoundName
reminder.category = "PushUpReminder"
UIApplication.sharedApplication().scheduleLocalNotification(reminder)
print("Firing at \(now.hour):\(now.minute):\(now.second)")
}
func scheduleNotification2() {
let now: NSDateComponents = NSCalendar.currentCalendar().components([.Hour, .Minute, .Second], fromDate: NSDate())
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let min = now.minute + ((now.second >= 20) ? 1: 0)
let date = cal.dateBySettingHour(now.hour, minute: min, second: (now.second + 40) % 60, ofDate: NSDate(), options: NSCalendarOptions())
let reminder = UILocalNotification()
reminder.fireDate = date
reminder.alertBody = "Did you do 12 pushups?"
reminder.soundName = UILocalNotificationDefaultSoundName
reminder.category = "PushUpDone"
UIApplication.sharedApplication().scheduleLocalNotification(reminder)
print("Firing at \(now.hour):\(now.minute):\(now.second + 40)")
}
/*
// 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.
}
*/
}
| gpl-2.0 | 159b630fed1fa6d4a2fab6a9476a1ad7 | 35.986842 | 143 | 0.660975 | 5.010695 | false | false | false | false |
JosephNK/SwiftyIamport | SwiftyIamportDemo/Controller/WKNiceViewController.swift | 1 | 5349 | //
// WKNiceViewController.swift
// SwiftyIamportDemo
//
// Created by JosephNK on 23/11/2018.
// Copyright © 2018 JosephNK. All rights reserved.
//
import UIKit
import SwiftyIamport
import WebKit
class WKNiceViewController: UIViewController {
lazy var wkWebView: WKWebView = {
var view = WKWebView()
view.backgroundColor = UIColor.clear
view.navigationDelegate = self
//view.uiDelegate = self
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(wkWebView)
self.wkWebView.frame = self.view.bounds
// 결제 환경 설정
IAMPortPay.sharedInstance.configure(scheme: "iamporttest", // info.plist에 설정한 scheme
storeIdentifier: "imp84043725") // iamport 에서 부여받은 가맹점 식별코드
IAMPortPay.sharedInstance
.setPGType(.nice) // PG사 타입
.setIdName(nil) // 상점아이디 ({PG사명}.{상점아이디}으로 생성시 사용)
.setPayMethod(.card) // 결제 형식
.setWKWebView(self.wkWebView) // 현재 Controller에 있는 WebView 지정
.setRedirectUrl(nil) // m_redirect_url 주소
// 결제 정보 데이타
let parameters: IAMPortParameters = [
"merchant_uid": String(format: "merchant_%@", String(Int(NSDate().timeIntervalSince1970 * 1000))),
"name": "결제테스트",
"amount": "1004",
"buyer_email": "[email protected]",
"buyer_name": "구매자",
"buyer_tel": "010-1234-5678",
"buyer_addr": "서울특별시 강남구 삼성동",
"buyer_postcode": "123-456",
"custom_data": ["A1": 123, "B1": "Hello"]
//"custom_data": "24"
]
IAMPortPay.sharedInstance.setParameters(parameters).commit()
// ISP 취소시 이벤트 (NicePay만 가능)
IAMPortPay.sharedInstance.setCancelListenerForNicePay { [weak self] in
DispatchQueue.main.async {
let alert = UIAlertController(title: nil, message: "ISP 결제 취소", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self?.present(alert, animated: true, completion: nil)
}
}
// 결제 웹페이지(Local) 파일 호출
if let url = IAMPortPay.sharedInstance.urlFromLocalHtmlFile() {
let request = URLRequest(url: url)
self.wkWebView.load(request)
}
}
}
extension WKNiceViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let request = navigationAction.request
IAMPortPay.sharedInstance.requestRedirectUrl(for: request, parser: { (data, response, error) -> Any? in
// Background Thread 처리
var resultData: [String: Any]?
if let httpResponse = response as? HTTPURLResponse {
let statusCode = httpResponse.statusCode
switch statusCode {
case 200:
resultData = [
"isSuccess": "OK"
]
break
default:
break
}
}
return resultData
}) { (pasingData) in
// Main Thread 처리
}
let result = IAMPortPay.sharedInstance.requestAction(for: request)
decisionHandler(result ? .allow : .cancel)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// 결제 환경으로 설정에 의한 웹페이지(Local) 호출 결과
IAMPortPay.sharedInstance.requestIAMPortPayWKWebViewDidFinishLoad(webView) { (error) in
if error != nil {
switch error! {
case .custom(let reason):
print("error: \(reason)")
break
}
}else {
print("OK")
}
}
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("didFail")
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print("didFailProvisionalNavigation \(error.localizedDescription)")
}
}
//extension WKNiceViewController: WKUIDelegate {
// func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
// guard let url = navigationAction.request.url else {
// return nil
// }
// guard let targetFrame = navigationAction.targetFrame, targetFrame.isMainFrame else {
// webView.load(NSURLRequest.init(url: url) as URLRequest)
// return nil
// }
// return nil
// }
//}
| mit | 599c57844f58253c3b7450aae3704571 | 35.604317 | 189 | 0.567414 | 4.57554 | false | false | false | false |
AntonTheDev/XCode-DI-Templates | Source/FileTemplates-tvOS/Transitioning Context.xctemplate/___FILEBASENAME___.swift | 2 | 3031 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
//___COPYRIGHT___
//
"Transitioning Context.xctemplate"
import Foundation
import UIKit
public class ___FILEBASENAME___: : NSObject, UIViewControllerContextTransitioning {
private var animatingControllers = [UITransitionContextViewControllerKey : UIViewController]()
private var appearingToRect : CGRect?
private var disappearingToRect : CGRect?
private var disappearingFromRect : CGRect?
private var appearingFromRect : CGRect?
private var completionBlock : ((_ complete : Bool) -> Void)?
public var containerView: UIView
public var presentationStyle : UIModalPresentationStyle = .custom
public var isAnimated: Bool = false
public var isInteractive: Bool = false
public var transitionWasCancelled: Bool = false
public var targetTransform: CGAffineTransform {
get { return CGAffineTransform.identity }
}
required public init(withFromViewController fromVC : UIViewController,
toViewController toVC : UIViewController,
rightDirection : Bool) {
containerView = fromVC.view.superview!
animatingControllers = [
UITransitionContextViewControllerKey.from:fromVC,
UITransitionContextViewControllerKey.to:toVC,
]
let travelDistance = (rightDirection ? -self.containerView.bounds.size.width : self.containerView.bounds.size.width);
disappearingFromRect = containerView.bounds
appearingToRect = containerView.bounds
disappearingToRect = containerView.bounds.offsetBy (dx: travelDistance, dy: 0);
disappearingFromRect = containerView.bounds.offsetBy (dx: -travelDistance, dy: 0);
super.init()
}
public func setCompletion(completion : @escaping (_ complete : Bool) -> Void ) {
completionBlock = completion
}
public func completeTransition(_ didComplete: Bool) {
completionBlock?(didComplete)
}
public func viewController(forKey key: UITransitionContextViewControllerKey) -> UIViewController? {
return animatingControllers[key]
}
public func initialFrame(for vc: UIViewController) -> CGRect {
if vc == viewController(forKey: UITransitionContextViewControllerKey.from)! {
return disappearingFromRect!
} else {
return appearingFromRect!
}
}
public func finalFrame(for vc: UIViewController) -> CGRect {
if vc == viewController(forKey: UITransitionContextViewControllerKey.from)! {
return disappearingToRect!
} else {
return appearingToRect!
}
}
public func view(forKey key: UITransitionContextViewKey) -> UIView? { return nil }
public func updateInteractiveTransition(_ percentComplete: CGFloat) { }
public func finishInteractiveTransition() { }
public func cancelInteractiveTransition() { }
public func pauseInteractiveTransition() { }
}
| mit | aab43651c3c8b0c9e305197df28c7e08 | 34.244186 | 125 | 0.686572 | 5.67603 | false | false | false | false |
dasdom/InteractivePlayground | InteractivePlayground.playground/Pages/Text Input.xcplaygroundpage/Contents.swift | 1 | 1737 | //: [Previous](@previous)
import UIKit
import PlaygroundSupport
class View: UIView {
let textField: UITextField
let label: UILabel
override init(frame: CGRect) {
textField = UITextField()
textField.backgroundColor = UIColor.yellow
textField.placeholder = "Type something"
label = UILabel()
label.backgroundColor = UIColor.black
label.textColor = UIColor.white
label.text = " "
let button = UIButton(type: .system)
button.setTitle("I'm a button!", for: .normal)
button.tintColor = UIColor.white
let stackView = UIStackView(arrangedSubviews: [textField, label, button])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.distribution = .equalSpacing
stackView.spacing = 10
super.init(frame: frame)
backgroundColor = UIColor.brown
addSubview(stackView)
button.addTarget(self, action: #selector(View.changeLabelText), for: .touchUpInside)
let views = ["stackView": stackView]
var layoutConstraints = [NSLayoutConstraint]()
layoutConstraints += NSLayoutConstraint.constraints(withVisualFormat: "|-[stackView]-|", options: [], metrics: nil, views: views)
layoutConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-[stackView]", options: [], metrics: nil, views: views)
NSLayoutConstraint.activate(layoutConstraints)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func changeLabelText() {
label.text = textField.text
}
}
let hostView = View(frame: CGRect(x: 0, y: 0, width: 320, height: 200))
PlaygroundPage.current.liveView = hostView
//: [Next](@next)
| mit | 9b24143dc7732f1b42b57b4611c2bce3 | 28.440678 | 133 | 0.696028 | 4.73297 | false | false | false | false |
brentdax/swift | test/SILGen/dynamic_lookup.swift | 2 | 19688 | // RUN: %target-swift-emit-silgen -module-name dynamic_lookup -enable-objc-interop -parse-as-library -disable-objc-attr-requires-foundation-module %s | %FileCheck %s
// RUN: %target-swift-emit-silgen -module-name dynamic_lookup -enable-objc-interop -parse-as-library -disable-objc-attr-requires-foundation-module %s | %FileCheck %s --check-prefix=GUARANTEED
class X {
@objc func f() { }
@objc class func staticF() { }
@objc var value: Int {
return 17
}
@objc subscript (i: Int) -> Int {
get {
return i
}
set {}
}
}
@objc protocol P {
func g()
}
// CHECK-LABEL: sil hidden @$s14dynamic_lookup15direct_to_class{{[_0-9a-zA-Z]*}}F
func direct_to_class(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $AnyObject):
// CHECK: [[OPENED_ARG:%[0-9]+]] = open_existential_ref [[ARG]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]]
// CHECK: [[METHOD:%[0-9]+]] = objc_method [[OPENED_ARG_COPY]] : $@opened({{.*}}) AnyObject, #X.f!1.foreign : (X) -> () -> (), $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: apply [[METHOD]]([[OPENED_ARG_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: destroy_value [[OPENED_ARG_COPY]]
obj.f!()
}
// CHECK: } // end sil function '$s14dynamic_lookup15direct_to_class{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden @$s14dynamic_lookup18direct_to_protocol{{[_0-9a-zA-Z]*}}F
func direct_to_protocol(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $AnyObject):
// CHECK: [[OPENED_ARG:%[0-9]+]] = open_existential_ref [[ARG]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]]
// CHECK: [[METHOD:%[0-9]+]] = objc_method [[OPENED_ARG_COPY]] : $@opened({{.*}}) AnyObject, #P.g!1.foreign : <Self where Self : P> (Self) -> () -> (), $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: apply [[METHOD]]([[OPENED_ARG_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: destroy_value [[OPENED_ARG_COPY]]
obj.g!()
}
// CHECK: } // end sil function '$s14dynamic_lookup18direct_to_protocol{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden @$s14dynamic_lookup23direct_to_static_method{{[_0-9a-zA-Z]*}}F
func direct_to_static_method(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $AnyObject):
var obj = obj
// CHECK: [[OBJBOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJBOX]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: store [[ARG_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK-NEXT: [[OBJCOPY:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: end_access [[READ]]
// CHECK-NEXT: [[OBJMETA:%[0-9]+]] = existential_metatype $@thick AnyObject.Type, [[OBJCOPY]] : $AnyObject
// CHECK-NEXT: [[OPENMETA:%[0-9]+]] = open_existential_metatype [[OBJMETA]] : $@thick AnyObject.Type to $@thick (@opened([[UUID:".*"]]) AnyObject).Type
// CHECK-NEXT: [[METHOD:%[0-9]+]] = objc_method [[OPENMETA]] : $@thick (@opened([[UUID]]) AnyObject).Type, #X.staticF!1.foreign : (X.Type) -> () -> (), $@convention(objc_method) (@thick (@opened([[UUID]]) AnyObject).Type) -> ()
// CHECK: apply [[METHOD]]([[OPENMETA]]) : $@convention(objc_method) (@thick (@opened([[UUID]]) AnyObject).Type) -> ()
// CHECK: destroy_value [[OBJBOX]]
type(of: obj).staticF!()
}
// } // end sil function '_TF14dynamic_lookup23direct_to_static_method{{.*}}'
// CHECK-LABEL: sil hidden @$s14dynamic_lookup12opt_to_class{{[_0-9a-zA-Z]*}}F
func opt_to_class(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $AnyObject):
var obj = obj
// CHECK: [[EXISTBOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[EXISTBOX]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: store [[ARG_COPY]] to [init] [[PBOBJ]]
// CHECK: [[OPTBOX:%[0-9]+]] = alloc_box ${ var Optional<@callee_guaranteed () -> ()> }
// CHECK: [[PBOPT:%.*]] = project_box [[OPTBOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[EXISTVAL:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[OBJ_SELF:%[0-9]*]] = open_existential_ref [[EXISTVAL]]
// CHECK: [[OPT_TMP:%.*]] = alloc_stack $Optional<@callee_guaranteed () -> ()>
// CHECK: dynamic_method_br [[OBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.f!1.foreign, [[HASBB:[a-zA-z0-9]+]], [[NOBB:[a-zA-z0-9]+]]
// Has method BB:
// CHECK: [[HASBB]]([[UNCURRIED:%[0-9]+]] : @trivial $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()):
// CHECK: [[OBJ_SELF_COPY:%.*]] = copy_value [[OBJ_SELF]]
// CHECK: [[PARTIAL:%[0-9]+]] = partial_apply [callee_guaranteed] [[UNCURRIED]]([[OBJ_SELF_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: [[THUNK_PAYLOAD:%.*]] = init_enum_data_addr [[OPT_TMP]]
// CHECK: store [[PARTIAL]] to [init] [[THUNK_PAYLOAD]]
// CHECK: inject_enum_addr [[OPT_TMP]] : $*Optional<@callee_guaranteed () -> ()>, #Optional.some!enumelt.1
// CHECK: br [[CONTBB:[a-zA-Z0-9]+]]
// No method BB:
// CHECK: [[NOBB]]:
// CHECK: inject_enum_addr [[OPT_TMP]] : {{.*}}, #Optional.none!enumelt
// CHECK: br [[CONTBB]]
// Continuation block
// CHECK: [[CONTBB]]:
// CHECK: [[OPT:%.*]] = load [take] [[OPT_TMP]]
// CHECK: store [[OPT]] to [init] [[PBOPT]] : $*Optional<@callee_guaranteed () -> ()>
// CHECK: dealloc_stack [[OPT_TMP]]
var of: (() -> ())! = obj.f
// Exit
// CHECK: destroy_value [[OBJ_SELF]] : $@opened({{".*"}}) AnyObject
// CHECK: destroy_value [[OPTBOX]] : ${ var Optional<@callee_guaranteed () -> ()> }
// CHECK: destroy_value [[EXISTBOX]] : ${ var AnyObject }
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
}
// CHECK-LABEL: sil hidden @$s14dynamic_lookup20forced_without_outer{{[_0-9a-zA-Z]*}}F
func forced_without_outer(_ obj: AnyObject) {
// CHECK: dynamic_method_br
var f = obj.f!
}
// CHECK-LABEL: sil hidden @$s14dynamic_lookup20opt_to_static_method{{[_0-9a-zA-Z]*}}F
func opt_to_static_method(_ obj: AnyObject) {
var obj = obj
// CHECK: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject):
// CHECK: [[OBJBOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJBOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[OPTBOX:%[0-9]+]] = alloc_box ${ var Optional<@callee_guaranteed () -> ()> }
// CHECK: [[PBO:%.*]] = project_box [[OPTBOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJCOPY:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[OBJMETA:%[0-9]+]] = existential_metatype $@thick AnyObject.Type, [[OBJCOPY]] : $AnyObject
// CHECK: [[OPENMETA:%[0-9]+]] = open_existential_metatype [[OBJMETA]] : $@thick AnyObject.Type to $@thick (@opened
// CHECK: [[OBJCMETA:%[0-9]+]] = thick_to_objc_metatype [[OPENMETA]]
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<@callee_guaranteed () -> ()>
// CHECK: dynamic_method_br [[OBJCMETA]] : $@objc_metatype (@opened({{".*"}}) AnyObject).Type, #X.staticF!1.foreign, [[HASMETHOD:[A-Za-z0-9_]+]], [[NOMETHOD:[A-Za-z0-9_]+]]
var optF: (() -> ())! = type(of: obj).staticF
}
// CHECK-LABEL: sil hidden @$s14dynamic_lookup15opt_to_property{{[_0-9a-zA-Z]*}}F
func opt_to_property(_ obj: AnyObject) {
var obj = obj
// CHECK: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[INT_BOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: project_box [[INT_BOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[RAWOBJ_SELF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[RAWOBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.value!getter.1.foreign, bb1, bb2
// CHECK: bb1([[METHOD:%[0-9]+]] : @trivial $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int):
// CHECK: [[RAWOBJ_SELF_COPY:%.*]] = copy_value [[RAWOBJ_SELF]]
// CHECK: [[BOUND_METHOD:%[0-9]+]] = partial_apply [callee_guaranteed] [[METHOD]]([[RAWOBJ_SELF_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int
// CHECK: [[B:%.*]] = begin_borrow [[BOUND_METHOD]]
// CHECK: [[VALUE:%[0-9]+]] = apply [[B]]() : $@callee_guaranteed () -> Int
// CHECK: end_borrow [[B]]
// CHECK: [[VALUETEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// CHECK: store [[VALUE]] to [trivial] [[VALUETEMP]]
// CHECK: inject_enum_addr [[OPTTEMP]]{{.*}}some
// CHECK: destroy_value [[BOUND_METHOD]]
// CHECK: br bb3
var i: Int = obj.value!
}
// CHECK: } // end sil function '$s14dynamic_lookup15opt_to_property{{[_0-9a-zA-Z]*}}F'
// GUARANTEED-LABEL: sil hidden @$s14dynamic_lookup15opt_to_property{{[_0-9a-zA-Z]*}}F
// GUARANTEED: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject):
// GUARANTEED: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// GUARANTEED: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// GUARANTEED: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// GUARANTEED: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// GUARANTEED: [[INT_BOX:%[0-9]+]] = alloc_box ${ var Int }
// GUARANTEED: project_box [[INT_BOX]]
// GUARANTEED: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// GUARANTEED: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// GUARANTEED: [[RAWOBJ_SELF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject
// GUARANTEED: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// GUARANTEED: dynamic_method_br [[RAWOBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.value!getter.1.foreign, bb1, bb2
// GUARANTEED: bb1([[METHOD:%[0-9]+]] : @trivial $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int):
// GUARANTEED: [[RAWOBJ_SELF_COPY:%.*]] = copy_value [[RAWOBJ_SELF]]
// GUARANTEED: [[BOUND_METHOD:%[0-9]+]] = partial_apply [callee_guaranteed] [[METHOD]]([[RAWOBJ_SELF_COPY]])
// GUARANTEED: [[BEGIN_BORROW:%.*]] = begin_borrow [[BOUND_METHOD]]
// GUARANTEED: [[VALUE:%[0-9]+]] = apply [[BEGIN_BORROW]]
// GUARANTEED: end_borrow [[BEGIN_BORROW]]
// GUARANTEED: [[VALUETEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// GUARANTEED: store [[VALUE]] to [trivial] [[VALUETEMP]]
// GUARANTEED: inject_enum_addr [[OPTTEMP]]{{.*}}some
// GUARANTEED: destroy_value [[BOUND_METHOD]]
// GUARANTEED: br bb3
// CHECK-LABEL: sil hidden @$s14dynamic_lookup19direct_to_subscript{{[_0-9a-zA-Z]*}}F
func direct_to_subscript(_ obj: AnyObject, i: Int) {
var obj = obj
var i = i
// CHECK: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject, [[I:%[0-9]+]] : @trivial $Int):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[I_BOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBI:%.*]] = project_box [[I_BOX]]
// CHECK: store [[I]] to [trivial] [[PBI]] : $*Int
// CHECK: alloc_box ${ var Int }
// CHECK: project_box
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBI]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READ]] : $*Int
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2
// CHECK: bb1([[GETTER:%[0-9]+]] : @trivial $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int):
// CHECK: [[OBJ_REF_COPY:%.*]] = copy_value [[OBJ_REF]]
// CHECK: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [callee_guaranteed] [[GETTER]]([[OBJ_REF_COPY]]) : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int
// CHECK: [[B:%.*]] = begin_borrow [[GETTER_WITH_SELF]]
// CHECK: [[RESULT:%[0-9]+]] = apply [[B]]([[I]]) : $@callee_guaranteed (Int) -> Int
// CHECK: end_borrow [[B]]
// CHECK: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// CHECK: store [[RESULT]] to [trivial] [[RESULTTEMP]]
// CHECK: inject_enum_addr [[OPTTEMP]]{{.*}}some
// CHECK: destroy_value [[GETTER_WITH_SELF]]
// CHECK: br bb3
var x: Int = obj[i]!
}
// CHECK: } // end sil function '$s14dynamic_lookup19direct_to_subscript{{[_0-9a-zA-Z]*}}F'
// GUARANTEED-LABEL: sil hidden @$s14dynamic_lookup19direct_to_subscript{{[_0-9a-zA-Z]*}}F
// GUARANTEED: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject, [[I:%[0-9]+]] : @trivial $Int):
// GUARANTEED: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// GUARANTEED: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// GUARANTEED: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// GUARANTEED: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// GUARANTEED: [[I_BOX:%[0-9]+]] = alloc_box ${ var Int }
// GUARANTEED: [[PBI:%.*]] = project_box [[I_BOX]]
// GUARANTEED: store [[I]] to [trivial] [[PBI]] : $*Int
// GUARANTEED: alloc_box ${ var Int }
// GUARANTEED: project_box
// GUARANTEED: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// GUARANTEED: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// GUARANTEED: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject
// GUARANTEED: [[READ:%.*]] = begin_access [read] [unknown] [[PBI]]
// GUARANTEED: [[I:%[0-9]+]] = load [trivial] [[READ]] : $*Int
// GUARANTEED: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// GUARANTEED: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2
// GUARANTEED: bb1([[GETTER:%[0-9]+]] : @trivial $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int):
// GUARANTEED: [[OBJ_REF_COPY:%.*]] = copy_value [[OBJ_REF]]
// GUARANTEED: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [callee_guaranteed] [[GETTER]]([[OBJ_REF_COPY]])
// GUARANTEED: [[BORROW:%.*]] = begin_borrow [[GETTER_WITH_SELF]]
// GUARANTEED: [[RESULT:%[0-9]+]] = apply [[BORROW]]([[I]])
// GUARANTEED: end_borrow [[BORROW]]
// GUARANTEED: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// GUARANTEED: store [[RESULT]] to [trivial] [[RESULTTEMP]]
// GUARANTEED: inject_enum_addr [[OPTTEMP]]{{.*}}some
// GUARANTEED: destroy_value [[GETTER_WITH_SELF]]
// GUARANTEED: br bb3
// CHECK-LABEL: sil hidden @$s14dynamic_lookup16opt_to_subscript{{[_0-9a-zA-Z]*}}F
func opt_to_subscript(_ obj: AnyObject, i: Int) {
var obj = obj
var i = i
// CHECK: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject, [[I:%[0-9]+]] : @trivial $Int):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[I_BOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBI:%.*]] = project_box [[I_BOX]]
// CHECK: store [[I]] to [trivial] [[PBI]] : $*Int
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBI]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READ]] : $*Int
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2
// CHECK: bb1([[GETTER:%[0-9]+]] : @trivial $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int):
// CHECK: [[OBJ_REF_COPY:%.*]] = copy_value [[OBJ_REF]]
// CHECK: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [callee_guaranteed] [[GETTER]]([[OBJ_REF_COPY]]) : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int
// CHECK: [[B:%.*]] = begin_borrow [[GETTER_WITH_SELF]]
// CHECK: [[RESULT:%[0-9]+]] = apply [[B]]([[I]]) : $@callee_guaranteed (Int) -> Int
// CHECK: end_borrow [[B]]
// CHECK: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// CHECK: store [[RESULT]] to [trivial] [[RESULTTEMP]]
// CHECK: inject_enum_addr [[OPTTEMP]]
// CHECK: destroy_value [[GETTER_WITH_SELF]]
// CHECK: br bb3
obj[i]
}
// CHECK-LABEL: sil hidden @$s14dynamic_lookup8downcast{{[_0-9a-zA-Z]*}}F
func downcast(_ obj: AnyObject) -> X {
var obj = obj
// CHECK: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[X:%[0-9]+]] = unconditional_checked_cast [[OBJ]] : $AnyObject to $X
// CHECK: destroy_value [[OBJ_BOX]] : ${ var AnyObject }
// CHECK: return [[X]] : $X
return obj as! X
}
@objc class Juice { }
@objc protocol Fruit {
@objc optional var juice: Juice { get }
}
// CHECK-LABEL: sil hidden @$s14dynamic_lookup7consumeyyAA5Fruit_pF
// CHECK: bb0(%0 : @guaranteed $Fruit):
// CHECK: [[BOX:%.*]] = alloc_stack $Optional<Juice>
// CHECK: dynamic_method_br [[SELF:%.*]] : $@opened("{{.*}}") Fruit, #Fruit.juice!getter.1.foreign, bb1, bb2
// CHECK: bb1([[FN:%.*]] : @trivial $@convention(objc_method) (@opened("{{.*}}") Fruit) -> @autoreleased Juice):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]]([[SELF_COPY]]) : $@convention(objc_method) (@opened("{{.*}}") Fruit) -> @autoreleased Juice
// CHECK: [[B:%.*]] = begin_borrow [[METHOD]]
// CHECK: [[RESULT:%.*]] = apply [[B]]() : $@callee_guaranteed () -> @owned Juice
// CHECK: end_borrow [[B]]
// CHECK: [[PAYLOAD:%.*]] = init_enum_data_addr [[BOX]] : $*Optional<Juice>, #Optional.some!enumelt.1
// CHECK: store [[RESULT]] to [init] [[PAYLOAD]]
// CHECK: inject_enum_addr [[BOX]] : $*Optional<Juice>, #Optional.some!enumelt.1
// CHECK: destroy_value [[METHOD]]
// CHECK: br bb3
// CHECK: bb2:
// CHECK: inject_enum_addr [[BOX]] : $*Optional<Juice>, #Optional.none!enumelt
// CHECK: br bb3
// CHECK: bb3:
// CHECK: return
func consume(_ fruit: Fruit) {
_ = fruit.juice
}
// rdar://problem/29249513 -- looking up an IUO member through AnyObject
// produces a Foo!? type. The SIL verifier did not correctly consider Optional
// to be the lowering of IUO (which is now eliminated by SIL lowering).
@objc protocol IUORequirement {
var iuoProperty: AnyObject! { get }
}
func getIUOPropertyDynamically(x: AnyObject) -> Any {
return x.iuoProperty
}
| apache-2.0 | 9bcec98088a683431e6b55b1006547eb | 53.994413 | 229 | 0.570398 | 3.207559 | false | false | false | false |
4faramita/TweeBox | TweeBox/ResourceURL.swift | 1 | 3466 | //
// ResourceURL.swift
// TweeBox
//
// Created by 4faramita on 2017/7/28.
// Copyright © 2017年 4faramita. All rights reserved.
//
import Foundation
struct ResourceURL {
// GET
static let user_lookup = (url: "https://api.twitter.com/1.1/users/lookup.json", method: "GET")
/*
Returns fully-hydrated user objects for up to 100 users per request, as specified by comma-separated values passed to the user_id and/or screen_name parameters.
This method is especially useful when used in conjunction with collections of user IDs returned from GET friends / ids and GET followers / ids.
*/
static let user_show = (url: "https://api.twitter.com/1.1/users/show.json", method: "GET")
static let users_search = (url: "https://api.twitter.com/1.1/users/search.json", method: "GET")
static let statuses_show_id = (url: "https://api.twitter.com/1.1/statuses/show.json", method: "GET")
static let statuses_retweeters_ids = (url: "https://api.twitter.com/1.1/statuses/retweeters/ids.json", method: "GET")
static let statuses_home_timeline = (url: "https://api.twitter.com/1.1/statuses/home_timeline.json", method: "GET")
static let statuses_user_timeline = (url: "https://api.twitter.com/1.1/statuses/user_timeline.json", method: "GET")
static let statuses_mentions_timeline = (url: "https://api.twitter.com/1.1/statuses/mentions_timeline.json", method: "GET")
static let favorites_list = (url: "https://api.twitter.com/1.1/favorites/list.json", method: "GET")
static let followers_list = (url: "https://api.twitter.com/1.1/followers/list.json", method: "GET")
static let followings_list = (url: "https://api.twitter.com/1.1/friends/list.json", method: "GET")
static let search_tweets = (url: "https://api.twitter.com/1.1/search/tweets.json", method: "GET")
// POST
static let statuses_update = (url: "https://api.twitter.com/1.1/statuses/update.json", method: "POST")
static let statuses_destroy_id = (url: "https://api.twitter.com/1.1/statuses/destroy/:id.json", method: "POST")
static let statuses_unretweet_id = (url: "https://api.twitter.com/1.1/statuses/unretweet/:id.json", method: "POST")
static let statuses_retweet_id = (url: "https://api.twitter.com/1.1/statuses/retweet/:id.json", method: "POST")
static let favorites_create = (url: "https://api.twitter.com/1.1/favorites/create.json", method: "POST")
static let favorites_destroy = (url: "https://api.twitter.com/1.1/favorites/destroy.json", method: "POST")
static let friendships_create = (url: "https://api.twitter.com/1.1/friendships/create.json", method: "POST")
static let friendships_destroy = (url: "https://api.twitter.com/1.1/friendships/destroy.json", method: "POST")
static let friendships_update = (url: "https://api.twitter.com/1.1/friendships/update.json", method: "POST")
static let blocks_create = (url: "https://api.twitter.com/1.1/blocks/create.json", method: "POST")
static let blocks_destroy = (url: "https://api.twitter.com/1.1/blocks/destroy.json", method: "POST")
static let users_report_spam = (url: "https://api.twitter.com/1.1/users/report_spam.json", method: "POST")
static let media_upload = (url: "https://upload.twitter.com/1.1/media/upload.json", method: "POST")
}
| mit | afdaa30a51fb4a90feeaeae863a94d1e | 42.2875 | 165 | 0.657522 | 3.371957 | false | false | false | false |
soapyigu/Swift30Projects | Project 04 - TodoTDD/ToDoTests/Models/ToDoItemTests.swift | 1 | 1986 | //
// ToDoItemTests.swift
// ToDoTests
//
// Created by gu, yi on 9/6/18.
// Copyright © 2018 gu, yi. All rights reserved.
//
import XCTest
@testable import ToDo
class ToDoItemTests: XCTestCase {
let timestamp = 0.0
let locationName = "Location"
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func test_init_givenTitle_setsTitle() {
let toDoItem = ToDoItem(title: Foo)
XCTAssertEqual(toDoItem.title, Foo, "should set title")
}
func test_init_givenItemDescription_setsItemDescription() {
let toDoItem = ToDoItem(title: Foo, itemDescription: Bar)
XCTAssertEqual(toDoItem.title, Foo, "should set title")
XCTAssertEqual(toDoItem.itemDescription, Bar, "should set itemDescription")
}
func test_init_givenTimeStamp_setsTimeStamp() {
let toDoItem = ToDoItem(title: Foo, timeStamp: timestamp)
XCTAssertEqual(toDoItem.timestamp, timestamp, "should set timeStamp")
}
func test_init_givenLocation_setsLocation() {
let location = Location(name: locationName)
let toDoItem = ToDoItem(title: Foo, location: Location(name: locationName))
XCTAssertEqual(toDoItem.location, location, "should set location")
}
func test_init_hasPlistDictionaryProperty() {
let toDoItem = ToDoItem(title: "First")
let dictionary = toDoItem.plistDict
XCTAssertNotNil(dictionary)
}
func test_canBeCreatedFromPlistDictionary() {
let location = Location(name: "Bar")
let toDoItem = ToDoItem(title: "Foo", itemDescription: "Baz", timeStamp: 1.0, location: location)
let dict = toDoItem.plistDict
let recreatedItem = ToDoItem(dict: dict)
XCTAssertEqual(recreatedItem, toDoItem)
}
}
| apache-2.0 | 076d24763e2578bfacbf9e3372988596 | 26.957746 | 107 | 0.69471 | 4.287257 | false | true | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureKYC/Sources/FeatureKYCUI/Email/VerifyEmailPresenter.swift | 1 | 2805 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
import Localization
import PlatformKit
import PlatformUIKit
import RxSwift
import ToolKit
public protocol EmailVerificationInterface: AnyObject {
func updateLoadingViewVisibility(_ visibility: Visibility)
func showError(message: String)
func sendEmailVerificationSuccess()
}
public protocol EmailConfirmationInterface: EmailVerificationInterface {
func emailVerifiedSuccess()
}
public final class VerifyEmailPresenter {
public var email: Single<String> {
emailSettingsService.email
.observe(on: MainScheduler.instance)
}
// MARK: - Private Properties
private weak var view: EmailVerificationInterface?
private let emailVerificationService: EmailVerificationServiceAPI
private let emailSettingsService: EmailSettingsServiceAPI
private let disposeBag = DisposeBag()
// MARK: - Setup
public init(
view: EmailVerificationInterface,
emailVerificationService: EmailVerificationServiceAPI = resolve(),
emailSettingsService: EmailSettingsServiceAPI = resolve()
) {
self.view = view
self.emailVerificationService = emailVerificationService
self.emailSettingsService = emailSettingsService
}
public func waitForEmailConfirmation() {
emailVerificationService.verifyEmail()
.observe(on: MainScheduler.instance)
.subscribe(
onCompleted: { [weak view] in
guard let view = view as? EmailConfirmationInterface else {
return
}
view.emailVerifiedSuccess()
}
)
.disposed(by: disposeBag)
}
public func cancel() {
emailVerificationService.cancel()
.subscribe()
.disposed(by: disposeBag)
}
public func sendVerificationEmail(
to email: String,
contextParameter: FlowContext? = nil
) {
emailSettingsService.update(email: email, context: contextParameter)
.observe(on: MainScheduler.instance)
.do(
onSubscribed: { [weak view] in
view?.updateLoadingViewVisibility(.visible)
},
onDispose: { [weak view] in
view?.updateLoadingViewVisibility(.hidden)
}
)
.subscribe(
onCompleted: { [weak view] in
view?.sendEmailVerificationSuccess()
},
onError: { [weak view] _ in
view?.showError(message: LocalizationConstants.KYC.failedToSendVerificationEmail)
}
)
.disposed(by: disposeBag)
}
}
| lgpl-3.0 | e25217eac1bf773387ef4d238a34eb8d | 30.155556 | 101 | 0.618046 | 5.596806 | false | false | false | false |
bramkoot/chargepointsSwift | TestSwift/AppDelegate.swift | 1 | 6119 | //
// AppDelegate.swift
// TestSwift
//
// Created by Bram Koot on 29-10-14.
// Copyright (c) 2014 Bram Koot. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.yobi.TestSwift" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("TestSwift", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("TestSwift.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| mit | 06e8d5bc644d8cb689409b5d0424e068 | 54.126126 | 290 | 0.715967 | 5.74554 | false | false | false | false |
Incipia/Goalie | Goalie/TasksDataProvider.swift | 1 | 6369 | //
// GoalProvider.swift
// Goalie
//
// Created by Gregory Klein on 12/8/15.
// Copyright © 2015 Incipia. All rights reserved.
//
import Foundation
import CoreData
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
private extension TaskPriority
{
static func priorityForWeight(_ weight: Float) -> TaskPriority
{
let roundedWeight = round(weight)
switch roundedWeight
{
case 1: return .ages
case 2: return .later
case 3: return .soon
case 4: return .asap
default: return .unknown
}
}
var weight: Float {
switch self {
case .unknown: return 0
case .ages: return 1
case .later: return 2
case .soon: return 3
case .asap: return 4
}
}
}
open class TasksDataProvider: NSObject, NSFetchedResultsControllerDelegate
{
fileprivate var _moc: NSManagedObjectContext
open fileprivate(set) var tasksFRC: NSFetchedResultsController<NSFetchRequestResult>
open var contentDidChangeBlock: (() -> Void)?
init(managedObjectContext: NSManagedObjectContext)
{
_moc = managedObjectContext
tasksFRC = NSFetchedResultsController(fetchRequest: DefaultTasksFetchRequestProvider.fetchRequest, managedObjectContext: _moc, sectionNameKeyPath: nil, cacheName: nil)
super.init()
tasksFRC.delegate = self
try! tasksFRC.performFetch()
}
func updateFetchRequest()
{
NSFetchedResultsController<NSFetchRequestResult>.deleteCache(withName: tasksFRC.cacheName)
var predicate: NSPredicate? = nil
if !GoalieSettingsManager.showCompletedTasks {
predicate = NSPredicate(format: "completed == false")
}
tasksFRC.fetchRequest.predicate = predicate
try! tasksFRC.performFetch()
}
func allTasks() -> [Task]
{
return tasksFRC.fetchedObjects as? [Task] ?? []
}
func taskIsLast(_ task: Task) -> Bool
{
var isLast = false
if let tasks = tasksFRC.fetchedObjects as? [Task] {
isLast = (tasks.last == task)
}
return isLast || task.title == ""
}
func taskIsOnlyTask(_ task: Task) -> Bool
{
var isOnly = false
if let tasks = tasksFRC.fetchedObjects as? [Task] {
isOnly = tasks.count == 1
}
return isOnly
}
func taskIsFirst(_ task: Task) -> Bool
{
var isFirst = false
if let tasks = tasksFRC.fetchedObjects as? [Task] {
isFirst = (tasks.first == task)
}
return isFirst
}
func completedTasks() -> [Task]
{
var tasks: [Task] = []
if let taskArray = tasksFRC.fetchedObjects as? [Task] {
for task in taskArray {
if task.completed && task.title != "" {
tasks.append(task)
}
}
}
return tasks
}
func completedTasksWithPriority(_ priority: TaskPriority) -> [Task]
{
var tasks: [Task] = []
for task in completedTasks() {
if task.priority == priority {
tasks.append(task)
}
}
return tasks
}
func incompletedTasks() -> [Task]
{
var tasks: [Task] = []
if let taskArray = tasksFRC.fetchedObjects as? [Task] {
for task in taskArray {
if !task.completed && task.title != "" {
tasks.append(task)
}
}
}
return tasks
}
func incompletedTasksForPriority(_ priority: TaskPriority) -> [Task]
{
var tasks: [Task] = []
for task in incompletedTasks() {
if task.priority == priority {
tasks.append(task)
}
}
return tasks
}
func averagePriorityOLD() -> TaskPriority
{
var priorityDict: [TaskPriority : Int] = [.ages: 0, .later : 0, .soon : 0, .asap: 0]
if let tasks = tasksFRC.fetchedObjects as? [Task] {
for task in tasks {
if task.title != "" && !task.completed {
switch task.priority {
case .ages: priorityDict[.ages] = priorityDict[.ages]! + 1
case .later: priorityDict[.later] = priorityDict[.later]! + 1
case .soon: priorityDict[.soon] = priorityDict[.soon]! + 1
case .asap: priorityDict[.asap] = priorityDict[.asap]! + 1
default: continue
}
}
}
}
var maxPriorities: [TaskPriority] = []
var avgPriority: TaskPriority? = nil
var currentMax = 0
for pri: TaskPriority in priorityDict.keys {
let priorityCount = priorityDict[pri]!
if priorityCount > currentMax {
avgPriority = pri
currentMax = priorityCount
maxPriorities = [pri]
}
else if priorityCount == currentMax && priorityCount != 0 {
maxPriorities.append(pri)
}
}
if maxPriorities.count > 0 {
avgPriority = maxPriorities.first!
}
for pri in maxPriorities {
// fix this -- task prioriteis are ordered backwards
if pri.rawValue < avgPriority?.rawValue {
avgPriority = pri
}
}
return avgPriority ?? .unknown
}
func averagePriority() -> TaskPriority
{
var avgPriority: TaskPriority = .unknown
if let tasks = tasksFRC.fetchedObjects as? [Task] {
var count: Float = 0
var avgPriorityWeight: Float = 0
for task in tasks {
if task.priority != .unknown && !task.completed {
avgPriorityWeight += task.priority.weight
count += 1
}
}
if count > 0 {
avgPriorityWeight /= count
avgPriority = TaskPriority.priorityForWeight(avgPriorityWeight)
}
}
return avgPriority
}
}
extension TasksDataProvider
{
public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)
{
contentDidChangeBlock?()
}
}
| apache-2.0 | 3b491c5cd224a1d958566760eee78e29 | 25.644351 | 173 | 0.575691 | 4.558339 | false | false | false | false |
shawnirvin/Terminal-iOS-Swift | Terminal/Models/Program.swift | 1 | 1952 | //
// Program.swift
// Terminal
//
// Created by Shawn Irvin on 11/25/15.
// Copyright © 2015 Shawn Irvin. All rights reserved.
//
import Foundation
class Program: NSObject, Helpful {
var name: String
var completionBlock: ((response: String?) -> Void)?
private lazy var functions: [Function] = [EndFunction(), ClearFunction(), HelpFunction(programHelpText: self.help(), regisertedFunctions: [Function]())]
init(name: String) {
self.name = name
}
func registerFunction(function: Function) {
self.functions.append(function)
for function in self.functions {
if let helpFunction = function as? HelpFunction {
helpFunction.functions = self.functions
}
}
}
func unregisterFunction(functionToRemove: Function) {
for function in self.functions {
if function == functionToRemove {
self.functions.removeAtIndex(self.functions.indexOf(function)!)
}
}
}
func registeredFunctions() -> [Function] {
return self.functions
}
func runCommand(command: Command, completion: (response: String?) -> Void) {
if let function = functionForCommand(command) {
function.execute(command, completion: completion)
}
else {
completion(response: nil)
}
}
func functionForCommand(command: Command) -> Function? {
for function in functions {
if function.equals(command) {
return function
}
}
return nil
}
func help() -> String {
let help = "Each program contains it's own help menu. Type 'help' while running a program to see the help for that program.\n" +
"\tType 'help name' to find out more about the function 'name' (if available).\n\n"
return help
}
} | mit | 111b26cdab4ea64eea5fa78cd6bcc9e0 | 28.134328 | 156 | 0.582778 | 4.667464 | false | false | false | false |
uasys/swift | stdlib/public/SDK/Foundation/CharacterSet.swift | 14 | 32245 | //===----------------------------------------------------------------------===//
//
// 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 Foundation // Clang module
import CoreFoundation
import _SwiftCoreFoundationOverlayShims
import _SwiftFoundationOverlayShims
private func _utfRangeToCFRange(_ inRange : Range<Unicode.Scalar>) -> CFRange {
return CFRange(
location: Int(inRange.lowerBound.value),
length: Int(inRange.upperBound.value - inRange.lowerBound.value))
}
private func _utfRangeToCFRange(_ inRange : ClosedRange<Unicode.Scalar>) -> CFRange {
return CFRange(
location: Int(inRange.lowerBound.value),
length: Int(inRange.upperBound.value - inRange.lowerBound.value + 1))
}
// MARK: -
fileprivate final class _CharacterSetStorage : Hashable {
fileprivate enum Backing {
case immutable(CFCharacterSet)
case mutable(CFMutableCharacterSet)
}
fileprivate var _backing : Backing
@nonobjc
init(immutableReference r : CFCharacterSet) {
_backing = .immutable(r)
}
@nonobjc
init(mutableReference r : CFMutableCharacterSet) {
_backing = .mutable(r)
}
// MARK: -
fileprivate var hashValue : Int {
switch _backing {
case .immutable(let cs):
return Int(CFHash(cs))
case .mutable(let cs):
return Int(CFHash(cs))
}
}
fileprivate static func ==(_ lhs : _CharacterSetStorage, _ rhs : _CharacterSetStorage) -> Bool {
switch (lhs._backing, rhs._backing) {
case (.immutable(let cs1), .immutable(let cs2)):
return CFEqual(cs1, cs2)
case (.immutable(let cs1), .mutable(let cs2)):
return CFEqual(cs1, cs2)
case (.mutable(let cs1), .immutable(let cs2)):
return CFEqual(cs1, cs2)
case (.mutable(let cs1), .mutable(let cs2)):
return CFEqual(cs1, cs2)
}
}
// MARK: -
fileprivate func mutableCopy() -> _CharacterSetStorage {
switch _backing {
case .immutable(let cs):
return _CharacterSetStorage(mutableReference: CFCharacterSetCreateMutableCopy(nil, cs))
case .mutable(let cs):
return _CharacterSetStorage(mutableReference: CFCharacterSetCreateMutableCopy(nil, cs))
}
}
// MARK: Immutable Functions
fileprivate var bitmapRepresentation : Data {
switch _backing {
case .immutable(let cs):
return CFCharacterSetCreateBitmapRepresentation(nil, cs) as Data
case .mutable(let cs):
return CFCharacterSetCreateBitmapRepresentation(nil, cs) as Data
}
}
fileprivate func hasMember(inPlane plane: UInt8) -> Bool {
switch _backing {
case .immutable(let cs):
return CFCharacterSetHasMemberInPlane(cs, CFIndex(plane))
case .mutable(let cs):
return CFCharacterSetHasMemberInPlane(cs, CFIndex(plane))
}
}
// MARK: Mutable functions
fileprivate func insert(charactersIn range: Range<Unicode.Scalar>) {
switch _backing {
case .immutable(let cs):
let r = CFCharacterSetCreateMutableCopy(nil, cs)!
CFCharacterSetAddCharactersInRange(r, _utfRangeToCFRange(range))
_backing = .mutable(r)
case .mutable(let cs):
CFCharacterSetAddCharactersInRange(cs, _utfRangeToCFRange(range))
}
}
fileprivate func insert(charactersIn range: ClosedRange<Unicode.Scalar>) {
switch _backing {
case .immutable(let cs):
let r = CFCharacterSetCreateMutableCopy(nil, cs)!
CFCharacterSetAddCharactersInRange(r, _utfRangeToCFRange(range))
_backing = .mutable(r)
case .mutable(let cs):
CFCharacterSetAddCharactersInRange(cs, _utfRangeToCFRange(range))
}
}
fileprivate func remove(charactersIn range: Range<Unicode.Scalar>) {
switch _backing {
case .immutable(let cs):
let r = CFCharacterSetCreateMutableCopy(nil, cs)!
CFCharacterSetRemoveCharactersInRange(r, _utfRangeToCFRange(range))
_backing = .mutable(r)
case .mutable(let cs):
CFCharacterSetRemoveCharactersInRange(cs, _utfRangeToCFRange(range))
}
}
fileprivate func remove(charactersIn range: ClosedRange<Unicode.Scalar>) {
switch _backing {
case .immutable(let cs):
let r = CFCharacterSetCreateMutableCopy(nil, cs)!
CFCharacterSetRemoveCharactersInRange(r, _utfRangeToCFRange(range))
_backing = .mutable(r)
case .mutable(let cs):
CFCharacterSetRemoveCharactersInRange(cs, _utfRangeToCFRange(range))
}
}
fileprivate func insert(charactersIn string: String) {
switch _backing {
case .immutable(let cs):
let r = CFCharacterSetCreateMutableCopy(nil, cs)!
CFCharacterSetAddCharactersInString(r, string as CFString)
_backing = .mutable(r)
case .mutable(let cs):
CFCharacterSetAddCharactersInString(cs, string as CFString)
}
}
fileprivate func remove(charactersIn string: String) {
switch _backing {
case .immutable(let cs):
let r = CFCharacterSetCreateMutableCopy(nil, cs)!
CFCharacterSetRemoveCharactersInString(r, string as CFString)
_backing = .mutable(r)
case .mutable(let cs):
CFCharacterSetRemoveCharactersInString(cs, string as CFString)
}
}
fileprivate func invert() {
switch _backing {
case .immutable(let cs):
let r = CFCharacterSetCreateMutableCopy(nil, cs)!
CFCharacterSetInvert(r)
_backing = .mutable(r)
case .mutable(let cs):
CFCharacterSetInvert(cs)
}
}
// -----
// MARK: -
// MARK: SetAlgebraType
@discardableResult
fileprivate func insert(_ character: Unicode.Scalar) -> (inserted: Bool, memberAfterInsert: Unicode.Scalar) {
insert(charactersIn: character..<Unicode.Scalar(character.value + 1)!)
// TODO: This should probably return the truth, but figuring it out requires two calls into NSCharacterSet
return (true, character)
}
@discardableResult
fileprivate func update(with character: Unicode.Scalar) -> Unicode.Scalar? {
insert(character)
// TODO: This should probably return the truth, but figuring it out requires two calls into NSCharacterSet
return character
}
@discardableResult
fileprivate func remove(_ character: Unicode.Scalar) -> Unicode.Scalar? {
// TODO: Add method to CFCharacterSet to do this in one call
let result : Unicode.Scalar? = contains(character) ? character : nil
remove(charactersIn: character..<Unicode.Scalar(character.value + 1)!)
return result
}
fileprivate func contains(_ member: Unicode.Scalar) -> Bool {
switch _backing {
case .immutable(let cs):
return CFCharacterSetIsLongCharacterMember(cs, member.value)
case .mutable(let cs):
return CFCharacterSetIsLongCharacterMember(cs, member.value)
}
}
// MARK: -
// Why do these return CharacterSet instead of CharacterSetStorage?
// We want to keep the knowledge of if the returned value happened to contain a mutable or immutable CFCharacterSet as close to the creation of that instance as possible
// When the underlying collection does not have a method to return new CharacterSets with changes applied, so we will copy and apply here
private static func _apply(_ lhs : _CharacterSetStorage, _ rhs : _CharacterSetStorage, _ f : (CFMutableCharacterSet, CFCharacterSet) -> ()) -> CharacterSet {
let copyOfMe : CFMutableCharacterSet
switch lhs._backing {
case .immutable(let cs):
copyOfMe = CFCharacterSetCreateMutableCopy(nil, cs)!
case .mutable(let cs):
copyOfMe = CFCharacterSetCreateMutableCopy(nil, cs)!
}
switch rhs._backing {
case .immutable(let cs):
f(copyOfMe, cs)
case .mutable(let cs):
f(copyOfMe, cs)
}
return CharacterSet(_uncopiedStorage: _CharacterSetStorage(mutableReference: copyOfMe))
}
private func _applyMutation(_ other : _CharacterSetStorage, _ f : (CFMutableCharacterSet, CFCharacterSet) -> ()) {
switch _backing {
case .immutable(let cs):
let r = CFCharacterSetCreateMutableCopy(nil, cs)!
switch other._backing {
case .immutable(let otherCs):
f(r, otherCs)
case .mutable(let otherCs):
f(r, otherCs)
}
_backing = .mutable(r)
case .mutable(let cs):
switch other._backing {
case .immutable(let otherCs):
f(cs, otherCs)
case .mutable(let otherCs):
f(cs, otherCs)
}
}
}
fileprivate var inverted : CharacterSet {
switch _backing {
case .immutable(let cs):
return CharacterSet(_uncopiedStorage: _CharacterSetStorage(immutableReference: CFCharacterSetCreateInvertedSet(nil, cs)))
case .mutable(let cs):
// Even if input is mutable, the result is immutable
return CharacterSet(_uncopiedStorage: _CharacterSetStorage(immutableReference: CFCharacterSetCreateInvertedSet(nil, cs)))
}
}
fileprivate func union(_ other: _CharacterSetStorage) -> CharacterSet {
return _CharacterSetStorage._apply(self, other, CFCharacterSetUnion)
}
fileprivate func formUnion(_ other: _CharacterSetStorage) {
_applyMutation(other, CFCharacterSetUnion)
}
fileprivate func intersection(_ other: _CharacterSetStorage) -> CharacterSet {
return _CharacterSetStorage._apply(self, other, CFCharacterSetIntersect)
}
fileprivate func formIntersection(_ other: _CharacterSetStorage) {
_applyMutation(other, CFCharacterSetIntersect)
}
fileprivate func subtracting(_ other: _CharacterSetStorage) -> CharacterSet {
return intersection(other.inverted._storage)
}
fileprivate func subtract(_ other: _CharacterSetStorage) {
_applyMutation(other.inverted._storage, CFCharacterSetIntersect)
}
fileprivate func symmetricDifference(_ other: _CharacterSetStorage) -> CharacterSet {
return union(other).subtracting(intersection(other))
}
fileprivate func formSymmetricDifference(_ other: _CharacterSetStorage) {
// This feels like cheating
_backing = symmetricDifference(other)._storage._backing
}
fileprivate func isSuperset(of other: _CharacterSetStorage) -> Bool {
switch _backing {
case .immutable(let cs):
switch other._backing {
case .immutable(let otherCs):
return CFCharacterSetIsSupersetOfSet(cs, otherCs)
case .mutable(let otherCs):
return CFCharacterSetIsSupersetOfSet(cs, otherCs)
}
case .mutable(let cs):
switch other._backing {
case .immutable(let otherCs):
return CFCharacterSetIsSupersetOfSet(cs, otherCs)
case .mutable(let otherCs):
return CFCharacterSetIsSupersetOfSet(cs, otherCs)
}
}
}
// MARK: -
fileprivate var description: String {
switch _backing {
case .immutable(let cs):
return CFCopyDescription(cs) as String
case .mutable(let cs):
return CFCopyDescription(cs) as String
}
}
fileprivate var debugDescription: String {
return description
}
// MARK: -
public func bridgedReference() -> NSCharacterSet {
switch _backing {
case .immutable(let cs):
return cs as NSCharacterSet
case .mutable(let cs):
return cs as NSCharacterSet
}
}
}
// MARK: -
/**
A `CharacterSet` represents a set of Unicode-compliant characters. Foundation types use `CharacterSet` to group characters together for searching operations, so that they can find any of a particular set of characters during a search.
This type provides "copy-on-write" behavior, and is also bridged to the Objective-C `NSCharacterSet` class.
*/
public struct CharacterSet : ReferenceConvertible, Equatable, Hashable, SetAlgebra {
public typealias ReferenceType = NSCharacterSet
fileprivate var _storage : _CharacterSetStorage
// MARK: Init methods
/// Initialize an empty instance.
public init() {
// It's unlikely that we are creating an empty character set with no intention to mutate it
_storage = _CharacterSetStorage(mutableReference: CFCharacterSetCreateMutable(nil))
}
/// Initialize with a range of integers.
///
/// It is the caller's responsibility to ensure that the values represent valid `Unicode.Scalar` values, if that is what is desired.
public init(charactersIn range: Range<Unicode.Scalar>) {
_storage = _CharacterSetStorage(immutableReference: CFCharacterSetCreateWithCharactersInRange(nil, _utfRangeToCFRange(range)))
}
/// Initialize with a closed range of integers.
///
/// It is the caller's responsibility to ensure that the values represent valid `Unicode.Scalar` values, if that is what is desired.
public init(charactersIn range: ClosedRange<Unicode.Scalar>) {
_storage = _CharacterSetStorage(immutableReference: CFCharacterSetCreateWithCharactersInRange(nil, _utfRangeToCFRange(range)))
}
/// Initialize with the characters in the given string.
///
/// - parameter string: The string content to inspect for characters.
public init(charactersIn string: String) {
_storage = _CharacterSetStorage(immutableReference: CFCharacterSetCreateWithCharactersInString(nil, string as CFString))
}
/// Initialize with a bitmap representation.
///
/// This method is useful for creating a character set object with data from a file or other external data source.
/// - parameter data: The bitmap representation.
public init(bitmapRepresentation data: Data) {
_storage = _CharacterSetStorage(immutableReference: CFCharacterSetCreateWithBitmapRepresentation(nil, data as CFData))
}
/// Initialize with the contents of a file.
///
/// Returns `nil` if there was an error reading the file.
/// - parameter file: The file to read.
public init?(contentsOfFile file: String) {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: file), options: .mappedIfSafe)
_storage = _CharacterSetStorage(immutableReference: CFCharacterSetCreateWithBitmapRepresentation(nil, data as CFData))
} catch {
return nil
}
}
fileprivate init(_bridged characterSet: NSCharacterSet) {
_storage = _CharacterSetStorage(immutableReference: characterSet.copy() as! CFCharacterSet)
}
fileprivate init(_uncopiedImmutableReference characterSet: CFCharacterSet) {
_storage = _CharacterSetStorage(immutableReference: characterSet)
}
fileprivate init(_uncopiedStorage : _CharacterSetStorage) {
_storage = _uncopiedStorage
}
fileprivate init(_builtIn: CFCharacterSetPredefinedSet) {
_storage = _CharacterSetStorage(immutableReference: CFCharacterSetGetPredefined(_builtIn))
}
// MARK: Static functions
/// Returns a character set containing the characters in Unicode General Category Cc and Cf.
public static var controlCharacters : CharacterSet {
return CharacterSet(_builtIn: .control)
}
/// Returns a character set containing the characters in Unicode General Category Zs and `CHARACTER TABULATION (U+0009)`.
public static var whitespaces : CharacterSet {
return CharacterSet(_builtIn: .whitespace)
}
/// Returns a character set containing characters in Unicode General Category Z*, `U+000A ~ U+000D`, and `U+0085`.
public static var whitespacesAndNewlines : CharacterSet {
return CharacterSet(_builtIn: .whitespaceAndNewline)
}
/// Returns a character set containing the characters in the category of Decimal Numbers.
public static var decimalDigits : CharacterSet {
return CharacterSet(_builtIn: .decimalDigit)
}
/// Returns a character set containing the characters in Unicode General Category L* & M*.
public static var letters : CharacterSet {
return CharacterSet(_builtIn: .letter)
}
/// Returns a character set containing the characters in Unicode General Category Ll.
public static var lowercaseLetters : CharacterSet {
return CharacterSet(_builtIn: .lowercaseLetter)
}
/// Returns a character set containing the characters in Unicode General Category Lu and Lt.
public static var uppercaseLetters : CharacterSet {
return CharacterSet(_builtIn: .uppercaseLetter)
}
/// Returns a character set containing the characters in Unicode General Category M*.
public static var nonBaseCharacters : CharacterSet {
return CharacterSet(_builtIn: .nonBase)
}
/// Returns a character set containing the characters in Unicode General Categories L*, M*, and N*.
public static var alphanumerics : CharacterSet {
return CharacterSet(_builtIn: .alphaNumeric)
}
/// Returns a character set containing individual Unicode characters that can also be represented as composed character sequences (such as for letters with accents), by the definition of "standard decomposition" in version 3.2 of the Unicode character encoding standard.
public static var decomposables : CharacterSet {
return CharacterSet(_builtIn: .decomposable)
}
/// Returns a character set containing values in the category of Non-Characters or that have not yet been defined in version 3.2 of the Unicode standard.
public static var illegalCharacters : CharacterSet {
return CharacterSet(_builtIn: .illegal)
}
@available(*, unavailable, renamed: "punctuationCharacters")
public static var punctuation : CharacterSet {
return CharacterSet(_builtIn: .punctuation)
}
/// Returns a character set containing the characters in Unicode General Category P*.
public static var punctuationCharacters : CharacterSet {
return CharacterSet(_builtIn: .punctuation)
}
/// Returns a character set containing the characters in Unicode General Category Lt.
public static var capitalizedLetters : CharacterSet {
return CharacterSet(_builtIn: .capitalizedLetter)
}
/// Returns a character set containing the characters in Unicode General Category S*.
public static var symbols : CharacterSet {
return CharacterSet(_builtIn: .symbol)
}
/// Returns a character set containing the newline characters (`U+000A ~ U+000D`, `U+0085`, `U+2028`, and `U+2029`).
public static var newlines : CharacterSet {
return CharacterSet(_builtIn: .newline)
}
// MARK: Static functions, from NSURL
/// Returns the character set for characters allowed in a user URL subcomponent.
public static var urlUserAllowed : CharacterSet {
if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return CharacterSet(_uncopiedImmutableReference: _CFURLComponentsGetURLUserAllowedCharacterSet() as NSCharacterSet)
} else {
return CharacterSet(_uncopiedImmutableReference: _NSURLComponentsGetURLUserAllowedCharacterSet() as! NSCharacterSet)
}
}
/// Returns the character set for characters allowed in a password URL subcomponent.
public static var urlPasswordAllowed : CharacterSet {
if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return CharacterSet(_uncopiedImmutableReference: _CFURLComponentsGetURLPasswordAllowedCharacterSet() as NSCharacterSet)
} else {
return CharacterSet(_uncopiedImmutableReference: _NSURLComponentsGetURLPasswordAllowedCharacterSet() as! NSCharacterSet)
}
}
/// Returns the character set for characters allowed in a host URL subcomponent.
public static var urlHostAllowed : CharacterSet {
if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return CharacterSet(_uncopiedImmutableReference: _CFURLComponentsGetURLHostAllowedCharacterSet() as NSCharacterSet)
} else {
return CharacterSet(_uncopiedImmutableReference: _NSURLComponentsGetURLHostAllowedCharacterSet() as! NSCharacterSet)
}
}
/// Returns the character set for characters allowed in a path URL component.
public static var urlPathAllowed : CharacterSet {
if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return CharacterSet(_uncopiedImmutableReference: _CFURLComponentsGetURLPathAllowedCharacterSet() as NSCharacterSet)
} else {
return CharacterSet(_uncopiedImmutableReference: _NSURLComponentsGetURLPathAllowedCharacterSet() as! NSCharacterSet)
}
}
/// Returns the character set for characters allowed in a query URL component.
public static var urlQueryAllowed : CharacterSet {
if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return CharacterSet(_uncopiedImmutableReference: _CFURLComponentsGetURLQueryAllowedCharacterSet() as NSCharacterSet)
} else {
return CharacterSet(_uncopiedImmutableReference: _NSURLComponentsGetURLQueryAllowedCharacterSet() as! NSCharacterSet)
}
}
/// Returns the character set for characters allowed in a fragment URL component.
public static var urlFragmentAllowed : CharacterSet {
if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return CharacterSet(_uncopiedImmutableReference: _CFURLComponentsGetURLFragmentAllowedCharacterSet() as NSCharacterSet)
} else {
return CharacterSet(_uncopiedImmutableReference: _NSURLComponentsGetURLFragmentAllowedCharacterSet() as! NSCharacterSet)
}
}
// MARK: Immutable functions
/// Returns a representation of the `CharacterSet` in binary format.
@nonobjc
public var bitmapRepresentation: Data {
return _storage.bitmapRepresentation
}
/// Returns an inverted copy of the receiver.
@nonobjc
public var inverted : CharacterSet {
return _storage.inverted
}
/// Returns true if the `CharacterSet` has a member in the specified plane.
///
/// This method makes it easier to find the plane containing the members of the current character set. The Basic Multilingual Plane (BMP) is plane 0.
public func hasMember(inPlane plane: UInt8) -> Bool {
return _storage.hasMember(inPlane: plane)
}
// MARK: Mutable functions
/// Insert a range of integer values in the `CharacterSet`.
///
/// It is the caller's responsibility to ensure that the values represent valid `Unicode.Scalar` values, if that is what is desired.
public mutating func insert(charactersIn range: Range<Unicode.Scalar>) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.insert(charactersIn: range)
}
/// Insert a closed range of integer values in the `CharacterSet`.
///
/// It is the caller's responsibility to ensure that the values represent valid `Unicode.Scalar` values, if that is what is desired.
public mutating func insert(charactersIn range: ClosedRange<Unicode.Scalar>) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.insert(charactersIn: range)
}
/// Remove a range of integer values from the `CharacterSet`.
public mutating func remove(charactersIn range: Range<Unicode.Scalar>) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.remove(charactersIn: range)
}
/// Remove a closed range of integer values from the `CharacterSet`.
public mutating func remove(charactersIn range: ClosedRange<Unicode.Scalar>) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.remove(charactersIn: range)
}
/// Insert the values from the specified string into the `CharacterSet`.
public mutating func insert(charactersIn string: String) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.insert(charactersIn: string)
}
/// Remove the values from the specified string from the `CharacterSet`.
public mutating func remove(charactersIn string: String) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.remove(charactersIn: string)
}
/// Invert the contents of the `CharacterSet`.
public mutating func invert() {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.invert()
}
// -----
// MARK: -
// MARK: SetAlgebraType
/// Insert a `Unicode.Scalar` representation of a character into the `CharacterSet`.
///
/// `Unicode.Scalar` values are available on `Swift.String.UnicodeScalarView`.
@discardableResult
public mutating func insert(_ character: Unicode.Scalar) -> (inserted: Bool, memberAfterInsert: Unicode.Scalar) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
return _storage.insert(character)
}
/// Insert a `Unicode.Scalar` representation of a character into the `CharacterSet`.
///
/// `Unicode.Scalar` values are available on `Swift.String.UnicodeScalarView`.
@discardableResult
public mutating func update(with character: Unicode.Scalar) -> Unicode.Scalar? {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
return _storage.update(with: character)
}
/// Remove a `Unicode.Scalar` representation of a character from the `CharacterSet`.
///
/// `Unicode.Scalar` values are available on `Swift.String.UnicodeScalarView`.
@discardableResult
public mutating func remove(_ character: Unicode.Scalar) -> Unicode.Scalar? {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
return _storage.remove(character)
}
/// Test for membership of a particular `Unicode.Scalar` in the `CharacterSet`.
public func contains(_ member: Unicode.Scalar) -> Bool {
return _storage.contains(member)
}
/// Returns a union of the `CharacterSet` with another `CharacterSet`.
public func union(_ other: CharacterSet) -> CharacterSet {
return _storage.union(other._storage)
}
/// Sets the value to a union of the `CharacterSet` with another `CharacterSet`.
public mutating func formUnion(_ other: CharacterSet) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.formUnion(other._storage)
}
/// Returns an intersection of the `CharacterSet` with another `CharacterSet`.
public func intersection(_ other: CharacterSet) -> CharacterSet {
return _storage.intersection(other._storage)
}
/// Sets the value to an intersection of the `CharacterSet` with another `CharacterSet`.
public mutating func formIntersection(_ other: CharacterSet) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.formIntersection(other._storage)
}
/// Returns a `CharacterSet` created by removing elements in `other` from `self`.
public func subtracting(_ other: CharacterSet) -> CharacterSet {
return _storage.subtracting(other._storage)
}
/// Sets the value to a `CharacterSet` created by removing elements in `other` from `self`.
public mutating func subtract(_ other: CharacterSet) {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _storage.mutableCopy()
}
_storage.subtract(other._storage)
}
/// Returns an exclusive or of the `CharacterSet` with another `CharacterSet`.
public func symmetricDifference(_ other: CharacterSet) -> CharacterSet {
return _storage.symmetricDifference(other._storage)
}
/// Sets the value to an exclusive or of the `CharacterSet` with another `CharacterSet`.
public mutating func formSymmetricDifference(_ other: CharacterSet) {
self = symmetricDifference(other)
}
/// Returns true if `self` is a superset of `other`.
public func isSuperset(of other: CharacterSet) -> Bool {
return _storage.isSuperset(of: other._storage)
}
// MARK: -
public var hashValue: Int {
return _storage.hashValue
}
/// Returns true if the two `CharacterSet`s are equal.
public static func ==(lhs : CharacterSet, rhs: CharacterSet) -> Bool {
return lhs._storage == rhs._storage
}
}
// MARK: Objective-C Bridging
extension CharacterSet : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSCharacterSet.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSCharacterSet {
return _storage.bridgedReference()
}
public static func _forceBridgeFromObjectiveC(_ input: NSCharacterSet, result: inout CharacterSet?) {
result = CharacterSet(_bridged: input)
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSCharacterSet, result: inout CharacterSet?) -> Bool {
result = CharacterSet(_bridged: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSCharacterSet?) -> CharacterSet {
guard let src = source else { return CharacterSet() }
return CharacterSet(_bridged: src)
}
}
extension CharacterSet : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return _storage.description
}
public var debugDescription: String {
return _storage.debugDescription
}
}
extension NSCharacterSet : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as CharacterSet)
}
}
extension CharacterSet : Codable {
private enum CodingKeys : Int, CodingKey {
case bitmap
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let bitmap = try container.decode(Data.self, forKey: .bitmap)
self.init(bitmapRepresentation: bitmap)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.bitmapRepresentation, forKey: .bitmap)
}
}
| apache-2.0 | 7a11a8376eef866a24c77e3dd7e2bf7b | 38.084848 | 274 | 0.65818 | 5.151781 | false | false | false | false |
austinzheng/swift | stdlib/public/core/RangeReplaceableCollection.swift | 4 | 44312 | //===--- RangeReplaceableCollection.swift ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// A Collection protocol with replaceSubrange.
//
//===----------------------------------------------------------------------===//
/// A collection that supports replacement of an arbitrary subrange of elements
/// with the elements of another collection.
///
/// Range-replaceable collections provide operations that insert and remove
/// elements. For example, you can add elements to an array of strings by
/// calling any of the inserting or appending operations that the
/// `RangeReplaceableCollection` protocol defines.
///
/// var bugs = ["Aphid", "Damselfly"]
/// bugs.append("Earwig")
/// bugs.insert(contentsOf: ["Bumblebee", "Cicada"], at: 1)
/// print(bugs)
/// // Prints "["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]"
///
/// Likewise, `RangeReplaceableCollection` types can remove one or more
/// elements using a single operation.
///
/// bugs.removeLast()
/// bugs.removeSubrange(1...2)
/// print(bugs)
/// // Prints "["Aphid", "Damselfly"]"
///
/// bugs.removeAll()
/// print(bugs)
/// // Prints "[]"
///
/// Lastly, use the eponymous `replaceSubrange(_:with:)` method to replace
/// a subrange of elements with the contents of another collection. Here,
/// three elements in the middle of an array of integers are replaced by the
/// five elements of a `Repeated<Int>` instance.
///
/// var nums = [10, 20, 30, 40, 50]
/// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))
/// print(nums)
/// // Prints "[10, 1, 1, 1, 1, 1, 50]"
///
/// Conforming to the RangeReplaceableCollection Protocol
/// =====================================================
///
/// To add `RangeReplaceableCollection` conformance to your custom collection,
/// add an empty initializer and the `replaceSubrange(_:with:)` method to your
/// custom type. `RangeReplaceableCollection` provides default implementations
/// of all its other methods using this initializer and method. For example,
/// the `removeSubrange(_:)` method is implemented by calling
/// `replaceSubrange(_:with:)` with an empty collection for the `newElements`
/// parameter. You can override any of the protocol's required methods to
/// provide your own custom implementation.
public protocol RangeReplaceableCollection : Collection
where SubSequence : RangeReplaceableCollection {
// FIXME: Associated type inference requires this.
override associatedtype SubSequence
//===--- Fundamental Requirements ---------------------------------------===//
/// Creates a new, empty collection.
init()
/// Replaces the specified subrange of elements with the given collection.
///
/// This method has the effect of removing the specified range of elements
/// from the collection and inserting the new elements at the same location.
/// The number of new elements need not match the number of elements being
/// removed.
///
/// In this example, three elements in the middle of an array of integers are
/// replaced by the five elements of a `Repeated<Int>` instance.
///
/// var nums = [10, 20, 30, 40, 50]
/// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))
/// print(nums)
/// // Prints "[10, 1, 1, 1, 1, 1, 50]"
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the elements of `newElements` at `subrange.startIndex`. Calling
/// the `insert(contentsOf:at:)` method instead is preferred.
///
/// Likewise, if you pass a zero-length collection as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred.
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameters:
/// - subrange: The subrange of the collection to replace. The bounds of
/// the range must be valid indices of the collection.
/// - newElements: The new elements to add to the collection.
///
/// - Complexity: O(*n* + *m*), where *n* is length of this collection and
/// *m* is the length of `newElements`. If the call to this method simply
/// appends the contents of `newElements` to the collection, this method is
/// equivalent to `append(contentsOf:)`.
mutating func replaceSubrange<C>(
_ subrange: Range<Index>,
with newElements: __owned C
) where C : Collection, C.Element == Element
/// Prepares the collection to store the specified number of elements, when
/// doing so is appropriate for the underlying type.
///
/// If you are adding a known number of elements to a collection, use this
/// method to avoid multiple reallocations. A type that conforms to
/// `RangeReplaceableCollection` can choose how to respond when this method
/// is called. Depending on the type, it may make sense to allocate more or
/// less storage than requested, or to take no action at all.
///
/// - Parameter n: The requested number of elements to store.
mutating func reserveCapacity(_ n: Int)
//===--- Derivable Requirements -----------------------------------------===//
/// Creates a new collection containing the specified number of a single,
/// repeated value.
///
/// The following example creates an array initialized with five strings
/// containing the letter *Z*.
///
/// let fiveZs = Array(repeating: "Z", count: 5)
/// print(fiveZs)
/// // Prints "["Z", "Z", "Z", "Z", "Z"]"
///
/// - Parameters:
/// - repeatedValue: The element to repeat.
/// - count: The number of times to repeat the value passed in the
/// `repeating` parameter. `count` must be zero or greater.
init(repeating repeatedValue: Element, count: Int)
/// Creates a new instance of a collection containing the elements of a
/// sequence.
///
/// - Parameter elements: The sequence of elements for the new collection.
/// `elements` must be finite.
init<S : Sequence>(_ elements: S)
where S.Element == Element
/// Adds an element to the end of the collection.
///
/// If the collection does not have sufficient capacity for another element,
/// additional storage is allocated before appending `newElement`. The
/// following example adds a new number to an array of integers:
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.append(100)
///
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 100]"
///
/// - Parameter newElement: The element to append to the collection.
///
/// - Complexity: O(1) on average, over many calls to `append(_:)` on the
/// same collection.
mutating func append(_ newElement: __owned Element)
/// Adds the elements of a sequence or collection to the end of this
/// collection.
///
/// The collection being appended to allocates any additional necessary
/// storage to hold the new elements.
///
/// The following example appends the elements of a `Range<Int>` instance to
/// an array of integers:
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.append(contentsOf: 10...15)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"
///
/// - Parameter newElements: The elements to append to the collection.
///
/// - Complexity: O(*m*), where *m* is the length of `newElements`.
mutating func append<S : Sequence>(contentsOf newElements: __owned S)
where S.Element == Element
// FIXME(ABI)#166 (Evolution): Consider replacing .append(contentsOf) with +=
// suggestion in SE-91
/// Inserts a new element into the collection at the specified position.
///
/// The new element is inserted before the element currently at the
/// specified index. If you pass the collection's `endIndex` property as
/// the `index` parameter, the new element is appended to the
/// collection.
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.insert(100, at: 3)
/// numbers.insert(200, at: numbers.endIndex)
///
/// print(numbers)
/// // Prints "[1, 2, 3, 100, 4, 5, 200]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter newElement: The new element to insert into the collection.
/// - Parameter i: The position at which to insert the new element.
/// `index` must be a valid index into the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection. If
/// `i == endIndex`, this method is equivalent to `append(_:)`.
mutating func insert(_ newElement: __owned Element, at i: Index)
/// Inserts the elements of a sequence into the collection at the specified
/// position.
///
/// The new elements are inserted before the element currently at the
/// specified index. If you pass the collection's `endIndex` property as the
/// `index` parameter, the new elements are appended to the collection.
///
/// Here's an example of inserting a range of integers into an array of the
/// same type:
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.insert(contentsOf: 100...103, at: 3)
/// print(numbers)
/// // Prints "[1, 2, 3, 100, 101, 102, 103, 4, 5]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter newElements: The new elements to insert into the collection.
/// - Parameter i: The position at which to insert the new elements. `index`
/// must be a valid index of the collection.
///
/// - Complexity: O(*n* + *m*), where *n* is length of this collection and
/// *m* is the length of `newElements`. If `i == endIndex`, this method
/// is equivalent to `append(contentsOf:)`.
mutating func insert<S : Collection>(contentsOf newElements: __owned S, at i: Index)
where S.Element == Element
/// Removes and returns the element at the specified position.
///
/// All the elements following the specified position are moved to close the
/// gap. This example removes the middle element from an array of
/// measurements.
///
/// var measurements = [1.2, 1.5, 2.9, 1.2, 1.6]
/// let removed = measurements.remove(at: 2)
/// print(measurements)
/// // Prints "[1.2, 1.5, 1.2, 1.6]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter i: The position of the element to remove. `index` must be
/// a valid index of the collection that is not equal to the collection's
/// end index.
/// - Returns: The removed element.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@discardableResult
mutating func remove(at i: Index) -> Element
/// Removes the specified subrange of elements from the collection.
///
/// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
/// bugs.removeSubrange(1...3)
/// print(bugs)
/// // Prints "["Aphid", "Earwig"]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter bounds: The subrange of the collection to remove. The bounds
/// of the range must be valid indices of the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
mutating func removeSubrange(_ bounds: Range<Index>)
/// Customization point for `removeLast()`. Implement this function if you
/// want to replace the default implementation.
///
/// - Returns: A non-nil value if the operation was performed.
mutating func _customRemoveLast() -> Element?
/// Customization point for `removeLast(_:)`. Implement this function if you
/// want to replace the default implementation.
///
/// - Returns: `true` if the operation was performed.
mutating func _customRemoveLast(_ n: Int) -> Bool
/// Removes and returns the first element of the collection.
///
/// The collection must not be empty.
///
/// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
/// bugs.removeFirst()
/// print(bugs)
/// // Prints "["Bumblebee", "Cicada", "Damselfly", "Earwig"]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Returns: The removed element.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@discardableResult
mutating func removeFirst() -> Element
/// Removes the specified number of elements from the beginning of the
/// collection.
///
/// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
/// bugs.removeFirst(3)
/// print(bugs)
/// // Prints "["Damselfly", "Earwig"]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter k: The number of elements to remove from the collection.
/// `k` must be greater than or equal to zero and must not exceed the
/// number of elements in the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
mutating func removeFirst(_ k: Int)
/// Removes all elements from the collection.
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter keepCapacity: Pass `true` to request that the collection
/// avoid releasing its storage. Retaining the collection's storage can
/// be a useful optimization when you're planning to grow the collection
/// again. The default value is `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
mutating func removeAll(keepingCapacity keepCapacity: Bool /*= false*/)
/// Removes all the elements that satisfy the given predicate.
///
/// Use this method to remove every element in a collection that meets
/// particular criteria. The order of the remaining elements is preserved.
/// This example removes all the odd values from an
/// array of numbers:
///
/// var numbers = [5, 6, 7, 8, 9, 10, 11]
/// numbers.removeAll(where: { $0 % 2 != 0 })
/// // numbers == [6, 8, 10]
///
/// - Parameter shouldBeRemoved: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element should be removed from the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
mutating func removeAll(
where shouldBeRemoved: (Element) throws -> Bool) rethrows
// FIXME: Associated type inference requires these.
override subscript(bounds: Index) -> Element { get }
override subscript(bounds: Range<Index>) -> SubSequence { get }
}
//===----------------------------------------------------------------------===//
// Default implementations for RangeReplaceableCollection
//===----------------------------------------------------------------------===//
extension RangeReplaceableCollection {
/// Creates a new collection containing the specified number of a single,
/// repeated value.
///
/// Here's an example of creating an array initialized with five strings
/// containing the letter *Z*.
///
/// let fiveZs = Array(repeating: "Z", count: 5)
/// print(fiveZs)
/// // Prints "["Z", "Z", "Z", "Z", "Z"]"
///
/// - Parameters:
/// - repeatedValue: The element to repeat.
/// - count: The number of times to repeat the value passed in the
/// `repeating` parameter. `count` must be zero or greater.
@inlinable
public init(repeating repeatedValue: Element, count: Int) {
self.init()
if count != 0 {
let elements = Repeated(_repeating: repeatedValue, count: count)
append(contentsOf: elements)
}
}
/// Creates a new instance of a collection containing the elements of a
/// sequence.
///
/// - Parameter elements: The sequence of elements for the new collection.
@inlinable
public init<S : Sequence>(_ elements: S)
where S.Element == Element {
self.init()
append(contentsOf: elements)
}
/// Adds an element to the end of the collection.
///
/// If the collection does not have sufficient capacity for another element,
/// additional storage is allocated before appending `newElement`. The
/// following example adds a new number to an array of integers:
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.append(100)
///
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 100]"
///
/// - Parameter newElement: The element to append to the collection.
///
/// - Complexity: O(1) on average, over many calls to `append(_:)` on the
/// same collection.
@inlinable
public mutating func append(_ newElement: __owned Element) {
insert(newElement, at: endIndex)
}
/// Adds the elements of a sequence or collection to the end of this
/// collection.
///
/// The collection being appended to allocates any additional necessary
/// storage to hold the new elements.
///
/// The following example appends the elements of a `Range<Int>` instance to
/// an array of integers:
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.append(contentsOf: 10...15)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"
///
/// - Parameter newElements: The elements to append to the collection.
///
/// - Complexity: O(*m*), where *m* is the length of `newElements`.
@inlinable
public mutating func append<S : Sequence>(contentsOf newElements: __owned S)
where S.Element == Element {
let approximateCapacity = self.count +
numericCast(newElements.underestimatedCount)
self.reserveCapacity(approximateCapacity)
for element in newElements {
append(element)
}
}
/// Inserts a new element into the collection at the specified position.
///
/// The new element is inserted before the element currently at the
/// specified index. If you pass the collection's `endIndex` property as
/// the `index` parameter, the new element is appended to the
/// collection.
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.insert(100, at: 3)
/// numbers.insert(200, at: numbers.endIndex)
///
/// print(numbers)
/// // Prints "[1, 2, 3, 100, 4, 5, 200]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter newElement: The new element to insert into the collection.
/// - Parameter i: The position at which to insert the new element.
/// `index` must be a valid index into the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection. If
/// `i == endIndex`, this method is equivalent to `append(_:)`.
@inlinable
public mutating func insert(
_ newElement: __owned Element, at i: Index
) {
replaceSubrange(i..<i, with: CollectionOfOne(newElement))
}
/// Inserts the elements of a sequence into the collection at the specified
/// position.
///
/// The new elements are inserted before the element currently at the
/// specified index. If you pass the collection's `endIndex` property as the
/// `index` parameter, the new elements are appended to the collection.
///
/// Here's an example of inserting a range of integers into an array of the
/// same type:
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers.insert(contentsOf: 100...103, at: 3)
/// print(numbers)
/// // Prints "[1, 2, 3, 100, 101, 102, 103, 4, 5]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter newElements: The new elements to insert into the collection.
/// - Parameter i: The position at which to insert the new elements. `index`
/// must be a valid index of the collection.
///
/// - Complexity: O(*n* + *m*), where *n* is length of this collection and
/// *m* is the length of `newElements`. If `i == endIndex`, this method
/// is equivalent to `append(contentsOf:)`.
@inlinable
public mutating func insert<C : Collection>(
contentsOf newElements: __owned C, at i: Index
) where C.Element == Element {
replaceSubrange(i..<i, with: newElements)
}
/// Removes and returns the element at the specified position.
///
/// All the elements following the specified position are moved to close the
/// gap. This example removes the middle element from an array of
/// measurements.
///
/// var measurements = [1.2, 1.5, 2.9, 1.2, 1.6]
/// let removed = measurements.remove(at: 2)
/// print(measurements)
/// // Prints "[1.2, 1.5, 1.2, 1.6]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter position: The position of the element to remove. `position`
/// must be a valid index of the collection that is not equal to the
/// collection's end index.
/// - Returns: The removed element.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
@discardableResult
public mutating func remove(at position: Index) -> Element {
_precondition(!isEmpty, "Can't remove from an empty collection")
let result: Element = self[position]
replaceSubrange(position..<index(after: position), with: EmptyCollection())
return result
}
/// Removes the elements in the specified subrange from the collection.
///
/// All the elements following the specified position are moved to close the
/// gap. This example removes three elements from the middle of an array of
/// measurements.
///
/// var measurements = [1.2, 1.5, 2.9, 1.2, 1.5]
/// measurements.removeSubrange(1..<4)
/// print(measurements)
/// // Prints "[1.2, 1.5]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter bounds: The range of the collection to be removed. The
/// bounds of the range must be valid indices of the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func removeSubrange(_ bounds: Range<Index>) {
replaceSubrange(bounds, with: EmptyCollection())
}
/// Removes the specified number of elements from the beginning of the
/// collection.
///
/// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
/// bugs.removeFirst(3)
/// print(bugs)
/// // Prints "["Damselfly", "Earwig"]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter k: The number of elements to remove from the collection.
/// `k` must be greater than or equal to zero and must not exceed the
/// number of elements in the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func removeFirst(_ k: Int) {
if k == 0 { return }
_precondition(k >= 0, "Number of elements to remove should be non-negative")
_precondition(count >= k,
"Can't remove more items from a collection than it has")
let end = index(startIndex, offsetBy: k)
removeSubrange(startIndex..<end)
}
/// Removes and returns the first element of the collection.
///
/// The collection must not be empty.
///
/// var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
/// bugs.removeFirst()
/// print(bugs)
/// // Prints "["Bumblebee", "Cicada", "Damselfly", "Earwig"]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Returns: The removed element.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
@discardableResult
public mutating func removeFirst() -> Element {
_precondition(!isEmpty,
"Can't remove first element from an empty collection")
let firstElement = first!
removeFirst(1)
return firstElement
}
/// Removes all elements from the collection.
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter keepCapacity: Pass `true` to request that the collection
/// avoid releasing its storage. Retaining the collection's storage can
/// be a useful optimization when you're planning to grow the collection
/// again. The default value is `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
if !keepCapacity {
self = Self()
}
else {
replaceSubrange(startIndex..<endIndex, with: EmptyCollection())
}
}
/// Prepares the collection to store the specified number of elements, when
/// doing so is appropriate for the underlying type.
///
/// If you will be adding a known number of elements to a collection, use
/// this method to avoid multiple reallocations. A type that conforms to
/// `RangeReplaceableCollection` can choose how to respond when this method
/// is called. Depending on the type, it may make sense to allocate more or
/// less storage than requested or to take no action at all.
///
/// - Parameter n: The requested number of elements to store.
@inlinable
public mutating func reserveCapacity(_ n: Int) {}
}
extension RangeReplaceableCollection where SubSequence == Self {
/// Removes and returns the first element of the collection.
///
/// The collection must not be empty.
///
/// Calling this method may invalidate all saved indices of this
/// collection. Do not rely on a previously stored index value after
/// altering a collection with any operation that can change its length.
///
/// - Returns: The first element of the collection.
///
/// - Complexity: O(1)
@inlinable
@discardableResult
public mutating func removeFirst() -> Element {
_precondition(!isEmpty, "Can't remove items from an empty collection")
let element = first!
self = self[index(after: startIndex)..<endIndex]
return element
}
/// Removes the specified number of elements from the beginning of the
/// collection.
///
/// Attempting to remove more elements than exist in the collection
/// triggers a runtime error.
///
/// Calling this method may invalidate all saved indices of this
/// collection. Do not rely on a previously stored index value after
/// altering a collection with any operation that can change its length.
///
/// - Parameter k: The number of elements to remove from the collection.
/// `k` must be greater than or equal to zero and must not exceed the
/// number of elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the specified
/// number of elements.
@inlinable
public mutating func removeFirst(_ k: Int) {
if k == 0 { return }
_precondition(k >= 0, "Number of elements to remove should be non-negative")
_precondition(count >= k,
"Can't remove more items from a collection than it contains")
self = self[index(startIndex, offsetBy: k)..<endIndex]
}
}
extension RangeReplaceableCollection {
/// Replaces the specified subrange of elements with the given collection.
///
/// This method has the effect of removing the specified range of elements
/// from the collection and inserting the new elements at the same location.
/// The number of new elements need not match the number of elements being
/// removed.
///
/// In this example, three elements in the middle of an array of integers are
/// replaced by the five elements of a `Repeated<Int>` instance.
///
/// var nums = [10, 20, 30, 40, 50]
/// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))
/// print(nums)
/// // Prints "[10, 1, 1, 1, 1, 1, 50]"
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the elements of `newElements` at `subrange.startIndex`. Calling
/// the `insert(contentsOf:at:)` method instead is preferred.
///
/// Likewise, if you pass a zero-length collection as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred.
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameters:
/// - subrange: The subrange of the collection to replace. The bounds of
/// the range must be valid indices of the collection.
/// - newElements: The new elements to add to the collection.
///
/// - Complexity: O(*n* + *m*), where *n* is length of this collection and
/// *m* is the length of `newElements`. If the call to this method simply
/// appends the contents of `newElements` to the collection, the complexity
/// is O(*m*).
@inlinable
public mutating func replaceSubrange<C: Collection, R: RangeExpression>(
_ subrange: R,
with newElements: __owned C
) where C.Element == Element, R.Bound == Index {
self.replaceSubrange(subrange.relative(to: self), with: newElements)
}
/// Removes the elements in the specified subrange from the collection.
///
/// All the elements following the specified position are moved to close the
/// gap. This example removes three elements from the middle of an array of
/// measurements.
///
/// var measurements = [1.2, 1.5, 2.9, 1.2, 1.5]
/// measurements.removeSubrange(1..<4)
/// print(measurements)
/// // Prints "[1.2, 1.5]"
///
/// Calling this method may invalidate any existing indices for use with this
/// collection.
///
/// - Parameter bounds: The range of the collection to be removed. The
/// bounds of the range must be valid indices of the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func removeSubrange<R: RangeExpression>(
_ bounds: R
) where R.Bound == Index {
removeSubrange(bounds.relative(to: self))
}
}
extension RangeReplaceableCollection {
@inlinable
public mutating func _customRemoveLast() -> Element? {
return nil
}
@inlinable
public mutating func _customRemoveLast(_ n: Int) -> Bool {
return false
}
}
extension RangeReplaceableCollection
where Self : BidirectionalCollection, SubSequence == Self {
@inlinable
public mutating func _customRemoveLast() -> Element? {
let element = last!
self = self[startIndex..<index(before: endIndex)]
return element
}
@inlinable
public mutating func _customRemoveLast(_ n: Int) -> Bool {
self = self[startIndex..<index(endIndex, offsetBy: numericCast(-n))]
return true
}
}
extension RangeReplaceableCollection where Self : BidirectionalCollection {
/// Removes and returns the last element of the collection.
///
/// Calling this method may invalidate all saved indices of this
/// collection. Do not rely on a previously stored index value after
/// altering a collection with any operation that can change its length.
///
/// - Returns: The last element of the collection if the collection is not
/// empty; otherwise, `nil`.
///
/// - Complexity: O(1)
@inlinable
public mutating func popLast() -> Element? {
if isEmpty { return nil }
// duplicate of removeLast logic below, to avoid redundant precondition
if let result = _customRemoveLast() { return result }
return remove(at: index(before: endIndex))
}
/// Removes and returns the last element of the collection.
///
/// The collection must not be empty.
///
/// Calling this method may invalidate all saved indices of this
/// collection. Do not rely on a previously stored index value after
/// altering a collection with any operation that can change its length.
///
/// - Returns: The last element of the collection.
///
/// - Complexity: O(1)
@inlinable
@discardableResult
public mutating func removeLast() -> Element {
_precondition(!isEmpty, "Can't remove last element from an empty collection")
// NOTE if you change this implementation, change popLast above as well
// AND change the tie-breaker implementations in the next extension
if let result = _customRemoveLast() { return result }
return remove(at: index(before: endIndex))
}
/// Removes the specified number of elements from the end of the
/// collection.
///
/// Attempting to remove more elements than exist in the collection
/// triggers a runtime error.
///
/// Calling this method may invalidate all saved indices of this
/// collection. Do not rely on a previously stored index value after
/// altering a collection with any operation that can change its length.
///
/// - Parameter k: The number of elements to remove from the collection.
/// `k` must be greater than or equal to zero and must not exceed the
/// number of elements in the collection.
///
/// - Complexity: O(*k*), where *k* is the specified number of elements.
@inlinable
public mutating func removeLast(_ k: Int) {
if k == 0 { return }
_precondition(k >= 0, "Number of elements to remove should be non-negative")
_precondition(count >= k,
"Can't remove more items from a collection than it contains")
if _customRemoveLast(k) {
return
}
let end = endIndex
removeSubrange(index(end, offsetBy: -k)..<end)
}
}
/// Ambiguity breakers.
extension RangeReplaceableCollection
where Self : BidirectionalCollection, SubSequence == Self {
/// Removes and returns the last element of the collection.
///
/// Calling this method may invalidate all saved indices of this
/// collection. Do not rely on a previously stored index value after
/// altering a collection with any operation that can change its length.
///
/// - Returns: The last element of the collection if the collection is not
/// empty; otherwise, `nil`.
///
/// - Complexity: O(1)
@inlinable
public mutating func popLast() -> Element? {
if isEmpty { return nil }
// duplicate of removeLast logic below, to avoid redundant precondition
if let result = _customRemoveLast() { return result }
return remove(at: index(before: endIndex))
}
/// Removes and returns the last element of the collection.
///
/// The collection must not be empty.
///
/// Calling this method may invalidate all saved indices of this
/// collection. Do not rely on a previously stored index value after
/// altering a collection with any operation that can change its length.
///
/// - Returns: The last element of the collection.
///
/// - Complexity: O(1)
@inlinable
@discardableResult
public mutating func removeLast() -> Element {
_precondition(!isEmpty, "Can't remove last element from an empty collection")
// NOTE if you change this implementation, change popLast above as well
if let result = _customRemoveLast() { return result }
return remove(at: index(before: endIndex))
}
/// Removes the specified number of elements from the end of the
/// collection.
///
/// Attempting to remove more elements than exist in the collection
/// triggers a runtime error.
///
/// Calling this method may invalidate all saved indices of this
/// collection. Do not rely on a previously stored index value after
/// altering a collection with any operation that can change its length.
///
/// - Parameter k: The number of elements to remove from the collection.
/// `k` must be greater than or equal to zero and must not exceed the
/// number of elements in the collection.
///
/// - Complexity: O(*k*), where *k* is the specified number of elements.
@inlinable
public mutating func removeLast(_ k: Int) {
if k == 0 { return }
_precondition(k >= 0, "Number of elements to remove should be non-negative")
_precondition(count >= k,
"Can't remove more items from a collection than it contains")
if _customRemoveLast(k) {
return
}
let end = endIndex
removeSubrange(index(end, offsetBy: -k)..<end)
}
}
extension RangeReplaceableCollection {
/// Creates a new collection by concatenating the elements of a collection and
/// a sequence.
///
/// The two arguments must have the same `Element` type. For example, you can
/// concatenate the elements of an integer array and a `Range<Int>` instance.
///
/// let numbers = [1, 2, 3, 4]
/// let moreNumbers = numbers + 5...10
/// print(moreNumbers)
/// // Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
///
/// The resulting collection has the type of the argument on the left-hand
/// side. In the example above, `moreNumbers` has the same type as `numbers`,
/// which is `[Int]`.
///
/// - Parameters:
/// - lhs: A range-replaceable collection.
/// - rhs: A collection or finite sequence.
@inlinable
public static func + <
Other : Sequence
>(lhs: Self, rhs: Other) -> Self
where Element == Other.Element {
var lhs = lhs
// FIXME: what if lhs is a reference type? This will mutate it.
lhs.append(contentsOf: rhs)
return lhs
}
/// Creates a new collection by concatenating the elements of a sequence and a
/// collection.
///
/// The two arguments must have the same `Element` type. For example, you can
/// concatenate the elements of a `Range<Int>` instance and an integer array.
///
/// let numbers = [7, 8, 9, 10]
/// let moreNumbers = 1...6 + numbers
/// print(moreNumbers)
/// // Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
///
/// The resulting collection has the type of argument on the right-hand side.
/// In the example above, `moreNumbers` has the same type as `numbers`, which
/// is `[Int]`.
///
/// - Parameters:
/// - lhs: A collection or finite sequence.
/// - rhs: A range-replaceable collection.
@inlinable
public static func + <
Other : Sequence
>(lhs: Other, rhs: Self) -> Self
where Element == Other.Element {
var result = Self()
result.reserveCapacity(rhs.count + numericCast(lhs.underestimatedCount))
result.append(contentsOf: lhs)
result.append(contentsOf: rhs)
return result
}
/// Appends the elements of a sequence to a range-replaceable collection.
///
/// Use this operator to append the elements of a sequence to the end of
/// range-replaceable collection with same `Element` type. This example
/// appends the elements of a `Range<Int>` instance to an array of integers.
///
/// var numbers = [1, 2, 3, 4, 5]
/// numbers += 10...15
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"
///
/// - Parameters:
/// - lhs: The array to append to.
/// - rhs: A collection or finite sequence.
///
/// - Complexity: O(*m*), where *m* is the length of the right-hand-side
/// argument.
@inlinable
public static func += <
Other : Sequence
>(lhs: inout Self, rhs: Other)
where Element == Other.Element {
lhs.append(contentsOf: rhs)
}
/// Creates a new collection by concatenating the elements of two collections.
///
/// The two arguments must have the same `Element` type. For example, you can
/// concatenate the elements of two integer arrays.
///
/// let lowerNumbers = [1, 2, 3, 4]
/// let higherNumbers: ContiguousArray = [5, 6, 7, 8, 9, 10]
/// let allNumbers = lowerNumbers + higherNumbers
/// print(allNumbers)
/// // Prints "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
///
/// The resulting collection has the type of the argument on the left-hand
/// side. In the example above, `moreNumbers` has the same type as `numbers`,
/// which is `[Int]`.
///
/// - Parameters:
/// - lhs: A range-replaceable collection.
/// - rhs: Another range-replaceable collection.
@inlinable
public static func + <
Other : RangeReplaceableCollection
>(lhs: Self, rhs: Other) -> Self
where Element == Other.Element {
var lhs = lhs
// FIXME: what if lhs is a reference type? This will mutate it.
lhs.append(contentsOf: rhs)
return lhs
}
}
extension RangeReplaceableCollection {
/// Returns a new collection of the same type containing, in order, the
/// elements of the original collection that satisfy the given predicate.
///
/// In this example, `filter(_:)` is used to include only names shorter than
/// five characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let shortNames = cast.filter { $0.count < 5 }
/// print(shortNames)
/// // Prints "["Kim", "Karl"]"
///
/// - Parameter isIncluded: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element should be included in the returned collection.
/// - Returns: A collection of the elements that `isIncluded` allowed.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
@available(swift, introduced: 4.0)
public __consuming func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> Self {
return try Self(self.lazy.filter(isIncluded))
}
}
extension RangeReplaceableCollection where Self: MutableCollection {
/// Removes all the elements that satisfy the given predicate.
///
/// Use this method to remove every element in a collection that meets
/// particular criteria. The order of the remaining elements is preserved.
/// This example removes all the odd values from an
/// array of numbers:
///
/// var numbers = [5, 6, 7, 8, 9, 10, 11]
/// numbers.removeAll(where: { $0 % 2 != 0 })
/// // numbers == [6, 8, 10]
///
/// - Parameter shouldBeRemoved: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element should be removed from the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func removeAll(
where shouldBeRemoved: (Element) throws -> Bool
) rethrows {
let suffixStart = try _halfStablePartition(isSuffixElement: shouldBeRemoved)
removeSubrange(suffixStart...)
}
}
extension RangeReplaceableCollection {
/// Removes all the elements that satisfy the given predicate.
///
/// Use this method to remove every element in a collection that meets
/// particular criteria. The order of the remaining elements is preserved.
/// This example removes all the vowels from a string:
///
/// var phrase = "The rain in Spain stays mainly in the plain."
///
/// let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
/// phrase.removeAll(where: { vowels.contains($0) })
/// // phrase == "Th rn n Spn stys mnly n th pln."
///
/// - Parameter shouldBeRemoved: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element should be removed from the collection.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public mutating func removeAll(
where shouldBeRemoved: (Element) throws -> Bool
) rethrows {
// FIXME: Switch to using RRC.filter once stdlib is compiled for 4.0
// self = try filter { try !predicate($0) }
self = try Self(self.lazy.filter { try !shouldBeRemoved($0) })
}
}
| apache-2.0 | dc9688f34060a5548f9ea6bfbece60de | 37.836109 | 86 | 0.649553 | 4.30548 | false | false | false | false |
Lomotif/lomotif-ios-httprequest | Pods/Alamofire/Source/SessionDelegate.swift | 1 | 35483 | //
// SessionDelegate.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Responsible for handling all delegate callbacks for the underlying session.
open class SessionDelegate: NSObject {
// MARK: URLSessionDelegate Overrides
/// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`.
open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)?
/// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`.
open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
/// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`.
open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)?
/// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`.
open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)?
// MARK: URLSessionTaskDelegate Overrides
/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`.
open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?
/// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and
/// requires the caller to call the `completionHandler`.
open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, (URLRequest?) -> Void) -> Void)?
/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`.
open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
/// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and
/// requires the caller to call the `completionHandler`.
open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)?
/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`.
open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)?
/// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and
/// requires the caller to call the `completionHandler`.
open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, (InputStream?) -> Void) -> Void)?
/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`.
open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`.
open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)?
// MARK: URLSessionDataDelegate Overrides
/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`.
open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)?
/// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and
/// requires caller to call the `completionHandler`.
open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, (URLSession.ResponseDisposition) -> Void) -> Void)?
/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`.
open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`.
open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`.
open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
/// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and
/// requires caller to call the `completionHandler`.
open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, (CachedURLResponse?) -> Void) -> Void)?
// MARK: URLSessionDownloadDelegate Overrides
/// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`.
open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)?
/// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`.
open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`.
open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
// MARK: URLSessionStreamDelegate Overrides
#if !os(watchOS)
/// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`.
open var _streamTaskReadClosed: Any?
@available(iOS 9.0, *)
open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? {
get {
return _streamTaskReadClosed as? ((URLSession, URLSessionStreamTask) -> Void)
}
set {
_streamTaskReadClosed = newValue
}
}
/// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`.
open var _streamTaskWriteClosed: Any?
@available(iOS 9.0, *)
open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? {
get {
return _streamTaskWriteClosed as? ((URLSession, URLSessionStreamTask) -> Void)
}
set {
_streamTaskWriteClosed = newValue
}
}
/// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`.
open var _streamTaskBetterRouteDiscovered: Any?
@available(iOS 9.0, *)
open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? {
get {
return _streamTaskBetterRouteDiscovered as? ((URLSession, URLSessionStreamTask) -> Void)
}
set {
_streamTaskBetterRouteDiscovered = newValue
}
}
/// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`.
open var _streamTaskDidBecomeInputAndOutputStreams: Any?
@available(iOS 9.0, *)
open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? {
get {
return _streamTaskDidBecomeInputAndOutputStreams as? ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)
}
set {
_streamTaskDidBecomeInputAndOutputStreams = newValue
}
}
#endif
// MARK: Properties
var retrier: RequestRetrier?
weak var sessionManager: SessionManager?
private var requests: [Int: Request] = [:]
private let lock = NSLock()
/// Access the task delegate for the specified task in a thread-safe manner.
open subscript(task: URLSessionTask) -> Request? {
get {
lock.lock() ; defer { lock.unlock() }
return requests[task.taskIdentifier]
}
set {
lock.lock() ; defer { lock.unlock() }
requests[task.taskIdentifier] = newValue
}
}
// MARK: Lifecycle
/// Initializes the `SessionDelegate` instance.
///
/// - returns: The new `SessionDelegate` instance.
public override init() {
super.init()
}
// MARK: NSObject Overrides
/// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond
/// to a specified message.
///
/// - parameter selector: A selector that identifies a message.
///
/// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`.
open override func responds(to selector: Selector) -> Bool {
#if !os(OSX)
if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) {
return sessionDidFinishEventsForBackgroundURLSession != nil
}
#endif
if #available(iOS 9.0, *) {
#if !os(watchOS)
switch selector {
case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)):
return streamTaskReadClosed != nil
case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)):
return streamTaskWriteClosed != nil
case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)):
return streamTaskBetterRouteDiscovered != nil
case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)):
return streamTaskDidBecomeInputAndOutputStreams != nil
default:
break
}
#endif
} else {
// Fallback on earlier versions
}
switch selector {
case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)):
return sessionDidBecomeInvalidWithError != nil
case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)):
return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil)
case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)):
return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil)
case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)):
return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil)
default:
return type(of: self).instancesRespond(to: selector)
}
}
}
// MARK: - URLSessionDelegate
extension SessionDelegate: URLSessionDelegate {
/// Tells the delegate that the session has been invalidated.
///
/// - parameter session: The session object that was invalidated.
/// - parameter error: The error that caused invalidation, or nil if the invalidation was explicit.
open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
sessionDidBecomeInvalidWithError?(session, error)
}
/// Requests credentials from the delegate in response to a session-level authentication request from the
/// remote server.
///
/// - parameter session: The session containing the task that requested authentication.
/// - parameter challenge: An object that contains the request for authentication.
/// - parameter completionHandler: A handler that your delegate method must call providing the disposition
/// and credential.
open func urlSession(
_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
guard sessionDidReceiveChallengeWithCompletion == nil else {
sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler)
return
}
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {
(disposition, credential) = sessionDidReceiveChallenge(session, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if
let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
let serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
disposition = .useCredential
credential = URLCredential(trust: serverTrust)
} else {
disposition = .cancelAuthenticationChallenge
}
}
}
completionHandler(disposition, credential)
}
#if !os(OSX)
/// Tells the delegate that all messages enqueued for a session have been delivered.
///
/// - parameter session: The session that no longer has any outstanding requests.
open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
sessionDidFinishEventsForBackgroundURLSession?(session)
}
#endif
}
// MARK: - URLSessionTaskDelegate
extension SessionDelegate: URLSessionTaskDelegate {
/// Tells the delegate that the remote server requested an HTTP redirect.
///
/// - parameter session: The session containing the task whose request resulted in a redirect.
/// - parameter task: The task whose request resulted in a redirect.
/// - parameter response: An object containing the server’s response to the original request.
/// - parameter request: A URL request object filled out with the new location.
/// - parameter completionHandler: A closure that your handler should call with either the value of the request
/// parameter, a modified URL request object, or NULL to refuse the redirect and
/// return the body of the redirect response.
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void)
{
guard taskWillPerformHTTPRedirectionWithCompletion == nil else {
taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler)
return
}
var redirectRequest: URLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
/// Requests credentials from the delegate in response to an authentication request from the remote server.
///
/// - parameter session: The session containing the task whose request requires authentication.
/// - parameter task: The task whose request requires authentication.
/// - parameter challenge: An object that contains the request for authentication.
/// - parameter completionHandler: A handler that your delegate method must call providing the disposition
/// and credential.
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
guard taskDidReceiveChallengeWithCompletion == nil else {
taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler)
return
}
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
let result = taskDidReceiveChallenge(session, task, challenge)
completionHandler(result.0, result.1)
} else if let delegate = self[task]?.delegate {
delegate.urlSession(
session,
task: task,
didReceive: challenge,
completionHandler: completionHandler
)
} else {
urlSession(session, didReceive: challenge, completionHandler: completionHandler)
}
}
/// Tells the delegate when a task requires a new request body stream to send to the remote server.
///
/// - parameter session: The session containing the task that needs a new body stream.
/// - parameter task: The task that needs a new body stream.
/// - parameter completionHandler: A completion handler that your delegate method should call with the new body stream.
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
needNewBodyStream completionHandler: @escaping (InputStream?) -> Void)
{
guard taskNeedNewBodyStreamWithCompletion == nil else {
taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler)
return
}
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
completionHandler(taskNeedNewBodyStream(session, task))
} else if let delegate = self[task]?.delegate {
delegate.urlSession(session, task: task, needNewBodyStream: completionHandler)
}
}
/// Periodically informs the delegate of the progress of sending body content to the server.
///
/// - parameter session: The session containing the data task.
/// - parameter task: The data task.
/// - parameter bytesSent: The number of bytes sent since the last time this delegate method was called.
/// - parameter totalBytesSent: The total number of bytes sent so far.
/// - parameter totalBytesExpectedToSend: The expected length of the body data.
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else if let delegate = self[task]?.delegate as? UploadTaskDelegate {
delegate.URLSession(
session,
task: task,
didSendBodyData: bytesSent,
totalBytesSent: totalBytesSent,
totalBytesExpectedToSend: totalBytesExpectedToSend
)
}
}
#if !os(watchOS)
/// Tells the delegate that the session finished collecting metrics for the task.
///
/// - parameter session: The session collecting the metrics.
/// - parameter task: The task whose metrics have been collected.
/// - parameter metrics: The collected metrics.
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
@objc(URLSession:task:didFinishCollectingMetrics:)
open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
self[task]?.delegate.metrics = metrics
}
#endif
/// Tells the delegate that the task finished transferring data.
///
/// - parameter session: The session containing the task whose request finished transferring data.
/// - parameter task: The task whose request finished transferring data.
/// - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil.
open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
/// Executed after it is determined that the request is not going to be retried
let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in
guard let strongSelf = self else { return }
if let taskDidComplete = strongSelf.taskDidComplete {
taskDidComplete(session, task, error)
} else if let delegate = strongSelf[task]?.delegate {
delegate.urlSession(session, task: task, didCompleteWithError: error)
}
NotificationCenter.default.post(
name: Notification.Name.Task.DidComplete,
object: strongSelf,
userInfo: [Notification.Key.Task: task]
)
strongSelf[task] = nil
}
guard let request = self[task], let sessionManager = sessionManager else {
completeTask(session, task, error)
return
}
// Run all validations on the request before checking if an error occurred
request.validations.forEach { $0() }
// Determine whether an error has occurred
var error: Error? = error
if let taskDelegate = self[task]?.delegate, taskDelegate.error != nil {
error = taskDelegate.error
}
/// If an error occurred and the retrier is set, asynchronously ask the retrier if the request
/// should be retried. Otherwise, complete the task by notifying the task delegate.
if let retrier = retrier, let error = error {
retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, delay in
guard shouldRetry else { completeTask(session, task, error) ; return }
DispatchQueue.utility.after(delay) { [weak self] in
guard let strongSelf = self else { return }
let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false
if retrySucceeded, let task = request.task {
strongSelf[task] = request
return
} else {
completeTask(session, task, error)
}
}
}
} else {
completeTask(session, task, error)
}
}
}
// MARK: - URLSessionDataDelegate
extension SessionDelegate: URLSessionDataDelegate {
/// Tells the delegate that the data task received the initial reply (headers) from the server.
///
/// - parameter session: The session containing the data task that received an initial reply.
/// - parameter dataTask: The data task that received an initial reply.
/// - parameter response: A URL response object populated with headers.
/// - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a
/// constant to indicate whether the transfer should continue as a data task or
/// should become a download task.
open func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
{
guard dataTaskDidReceiveResponseWithCompletion == nil else {
dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler)
return
}
var disposition: URLSession.ResponseDisposition = .allow
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
/// Tells the delegate that the data task was changed to a download task.
///
/// - parameter session: The session containing the task that was replaced by a download task.
/// - parameter dataTask: The data task that was replaced by a download task.
/// - parameter downloadTask: The new download task that replaced the data task.
open func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didBecome downloadTask: URLSessionDownloadTask)
{
if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask {
dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask)
} else {
self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask)
}
}
/// Tells the delegate that the data task has received some of the expected data.
///
/// - parameter session: The session containing the data task that provided data.
/// - parameter dataTask: The data task that provided data.
/// - parameter data: A data object containing the transferred data.
open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate {
delegate.urlSession(session, dataTask: dataTask, didReceive: data)
}
}
/// Asks the delegate whether the data (or upload) task should store the response in the cache.
///
/// - parameter session: The session containing the data (or upload) task.
/// - parameter dataTask: The data (or upload) task.
/// - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current
/// caching policy and the values of certain received headers, such as the Pragma
/// and Cache-Control headers.
/// - parameter completionHandler: A block that your handler must call, providing either the original proposed
/// response, a modified version of that response, or NULL to prevent caching the
/// response. If your delegate implements this method, it must call this completion
/// handler; otherwise, your app leaks memory.
open func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
willCacheResponse proposedResponse: CachedURLResponse,
completionHandler: @escaping (CachedURLResponse?) -> Void)
{
guard dataTaskWillCacheResponseWithCompletion == nil else {
dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler)
return
}
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
} else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate {
delegate.urlSession(
session,
dataTask: dataTask,
willCacheResponse: proposedResponse,
completionHandler: completionHandler
)
} else {
completionHandler(proposedResponse)
}
}
}
// MARK: - URLSessionDownloadDelegate
extension SessionDelegate: URLSessionDownloadDelegate {
/// Tells the delegate that a download task has finished downloading.
///
/// - parameter session: The session containing the download task that finished.
/// - parameter downloadTask: The download task that finished.
/// - parameter location: A file URL for the temporary file. Because the file is temporary, you must either
/// open the file for reading or move it to a permanent location in your app’s sandbox
/// container directory before returning from this delegate method.
open func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL)
{
if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
} else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate {
delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location)
}
}
/// Periodically informs the delegate about the download’s progress.
///
/// - parameter session: The session containing the download task.
/// - parameter downloadTask: The download task.
/// - parameter bytesWritten: The number of bytes transferred since the last time this delegate
/// method was called.
/// - parameter totalBytesWritten: The total number of bytes transferred so far.
/// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length
/// header. If this header was not provided, the value is
/// `NSURLSessionTransferSizeUnknown`.
open func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
} else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate {
delegate.urlSession(
session,
downloadTask: downloadTask,
didWriteData: bytesWritten,
totalBytesWritten: totalBytesWritten,
totalBytesExpectedToWrite: totalBytesExpectedToWrite
)
}
}
/// Tells the delegate that the download task has resumed downloading.
///
/// - parameter session: The session containing the download task that finished.
/// - parameter downloadTask: The download task that resumed. See explanation in the discussion.
/// - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the
/// existing content, then this value is zero. Otherwise, this value is an
/// integer representing the number of bytes on disk that do not need to be
/// retrieved again.
/// - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header.
/// If this header was not provided, the value is NSURLSessionTransferSizeUnknown.
open func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
{
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate {
delegate.urlSession(
session,
downloadTask: downloadTask,
didResumeAtOffset: fileOffset,
expectedTotalBytes: expectedTotalBytes
)
}
}
}
// MARK: - URLSessionStreamDelegate
#if !os(watchOS)
extension SessionDelegate: URLSessionStreamDelegate {
/// Tells the delegate that the read side of the connection has been closed.
///
/// - parameter session: The session.
/// - parameter streamTask: The stream task.
@available(iOS 9.0, *)
open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) {
streamTaskReadClosed?(session, streamTask)
}
/// Tells the delegate that the write side of the connection has been closed.
///
/// - parameter session: The session.
/// - parameter streamTask: The stream task.
@available(iOS 9.0, *)
open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) {
streamTaskWriteClosed?(session, streamTask)
}
/// Tells the delegate that the system has determined that a better route to the host is available.
///
/// - parameter session: The session.
/// - parameter streamTask: The stream task.
@available(iOS 9.0, *)
open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) {
streamTaskBetterRouteDiscovered?(session, streamTask)
}
/// Tells the delegate that the stream task has been completed and provides the unopened stream objects.
///
/// - parameter session: The session.
/// - parameter streamTask: The stream task.
/// - parameter inputStream: The new input stream.
/// - parameter outputStream: The new output stream.
@available(iOS 9.0, *)
open func urlSession(
_ session: URLSession,
streamTask: URLSessionStreamTask,
didBecome inputStream: InputStream,
outputStream: OutputStream)
{
streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream)
}
}
#endif
| mit | 9a79afb4621901106fc55f9f10a324eb | 47.933793 | 182 | 0.673366 | 6.183894 | false | false | false | false |
hooman/swift | test/Index/Store/cross-import-overlay.swift | 8 | 5273 | // RUN: %empty-directory(%t)
// RUN: %empty-directory(%t/mcp)
// RUN: cp -r %S/../Inputs/CrossImport %t/CrossImport
// RUN: %{python} %S/../../CrossImport/Inputs/rewrite-module-triples.py %t/CrossImport %module-target-triple
// RUN: %target-swift-frontend -disable-implicit-concurrency-module-import -c -index-store-path %t/idx -module-cache-path %t/mcp -index-system-modules -index-ignore-stdlib -enable-cross-import-overlays %s -Fsystem %t/CrossImport -o %t/file1.o -module-name cross_import_overlay
// RUN: c-index-test core -print-unit %t/idx > %t/units
import A
import B
import C
fromA()
fromB()
from_ABAdditions()
from__ABAdditionsCAdditions()
// Check the overlay modules pick up the name of their underlying module.
//
// FIXME: the units are sorted by their unit name, which for the frameworks in
// this test end up just being the target triple + a hash of the output file
// path which changes depending on where this test is run. We should fix this
// properly, but for now work around it by checking for each unit in a separate
// pass and do our best to make sure we don't match across unit boundaries.
//
// RUN: %FileCheck %s --input-file %t/units --check-prefix=MAIN
// MAIN: module-name: cross_import_overlay
// MAIN: out-file: {{.*}}/file1.o
// MAIN-NEXT: target: {{.*}}
// MAIN-NEXT: is-debug: 1
// MAIN-NEXT: DEPEND START
// MAIN-NEXT: Unit | system | Swift | {{.*}}{{/|\\}}Swift.swiftmodule
// MAIN-NEXT: Unit | system | B | {{.*}}{{/|\\}}B.swiftmodule{{/|\\}}{{.*}}
// MAIN-NEXT: Unit | system | C | {{.*}}{{/|\\}}C.swiftmodule{{/|\\}}{{.*}}
// MAIN-NEXT: Unit | system | A | {{.*}}{{/|\\}}__ABAdditionsCAdditions.swiftmodule{{/|\\}}{{.*}}
// MAIN-NEXT: Record | user | {{.*}}{{/|\\}}cross-import-overlay.swift
// MAIN-NEXT: DEPEND END
//
// RUN: %FileCheck %s --input-file %t/units --check-prefix=AB_OVERLAY
// AB_OVERLAY: module-name: A
// AB_OVERLAY: out-file:{{.*}}{{/|\\}}_ABAdditions.swiftmodule{{/|\\}}{{.*}}
// AB_OVERLAY-NEXT: target: {{.*}}
// AB_OVERLAY-NEXT: is-debug: 1
// AB_OVERLAY-NEXT: DEPEND START
// AB_OVERLAY-NEXT: Unit | system | A | {{.*}}{{/|\\}}A.swiftmodule{{/|\\}}{{.*}}
// AB_OVERLAY-NEXT: Unit | system | B | {{.*}}{{/|\\}}B.swiftmodule{{/|\\}}{{.*}}
// AB_OVERLAY-NEXT: Unit | system | Swift | {{.*}}{{/|\\}}Swift.swiftmodule
// AB_OVERLAY-NEXT: Record | system | A | {{.*}}{{/|\\}}_ABAdditions.swiftmodule{{/|\\}}{{.*}}
// AB_OVERLAY-NEXT: DEPEND END
//
// RUN: %FileCheck %s --input-file %t/units --check-prefix=ABC_OVERLAY
// ABC_OVERLAY: module-name: A
// ABC_OVERLAY: out-file: {{.*}}{{/|\\}}__ABAdditionsCAdditions.swiftmodule{{/|\\}}{{.*}}
// ABC_OVERLAY-NEXT: target: {{.*}}
// ABC_OVERLAY-NEXT: is-debug: 1
// ABC_OVERLAY-NEXT: DEPEND START
// ABC_OVERLAY-NEXT: Unit | system | C | {{.*}}{{/|\\}}C.swiftmodule{{/|\\}}{{.*}}
// ABC_OVERLAY-NEXT: Unit | system | Swift | {{.*}}{{/|\\}}Swift.swiftmodule
// ABC_OVERLAY-NEXT: Unit | system | A | {{.*}}{{/|\\}}_ABAdditions.swiftmodule{{/|\\}}{{.*}}
// ABC_OVERLAY-NEXT: Record | system | A | {{.*}}{{/|\\}}__ABAdditionsCAdditions.swiftmodule{{/|\\}}{{.*}}
// ABC_OVERLAY-NEXT: DEPEND END
//
// RUN: %FileCheck %s --input-file %t/units --check-prefix=C_MODULE
// C_MODULE: module-name: C
// C_MODULE: out-file: {{.*}}{{/|\\}}C.swiftmodule{{/|\\}}{{.*}}
// C_MODULE-NEXT: target: {{.*}}
// C_MODULE-NEXT: is-debug: 1
// C_MODULE-NEXT: DEPEND START
// C_MODULE-NEXT: Unit | system | Swift | {{.*}}{{/|\\}}Swift.swiftmodule
// C_MODULE-NEXT: Record | system | C | {{.*}}{{/|\\}}C.swiftmodule{{/|\\}}{{.*}}
// C_MODULE-NEXT: DEPEND END
//
// RUN: %FileCheck %s --input-file %t/units --check-prefix=B_MODULE
// B_MODULE: module-name: B
// B_MODULE: out-file: {{.*}}{{/|\\}}B.swiftmodule{{/|\\}}{{.*}}
// B_MODULE-NEXT: target: {{.*}}
// B_MODULE-NEXT: is-debug: 1
// B_MODULE-NEXT: DEPEND START
// B_MODULE-NEXT: Unit | system | Swift | {{.*}}{{/|\\}}Swift.swiftmodule
// B_MODULE-NEXT: Record | system | B | {{.*}}{{/|\\}}B.swiftmodule{{/|\\}}{{.*}}
// B_MODULE-NEXT: DEPEND END
//
// RUN: %FileCheck %s --input-file %t/units --check-prefix=A_MODULE
// A_MODULE: module-name: A
// A_MODULE: out-file: {{.*}}{{/|\\}}A.swiftmodule{{/|\\}}{{.*}}
// A_MODULE-NEXT: target: {{.*}}
// A_MODULE-NEXT: is-debug: 1
// A_MODULE-NEXT: DEPEND START
// A_MODULE-NEXT: Unit | system | Swift | {{.*}}{{/|\\}}Swift.swiftmodule
// A_MODULE-NEXT: Record | system | A | {{.*}}{{/|\\}}A.swiftmodule{{/|\\}}{{.*}}
// A_MODULE-NEXT: DEPEND END
// Make sure there are three units with module-name 'A' (A, _ABAdditions and
// __ABAdditionsCAdditions) in case we matched across unit boundaries above
// due to the nondeterministic ordering.
//
// RUN: %FileCheck %s --input-file %t/units --check-prefix=UNITS
// UNITS-COUNT-3: module-name: A
// Make sure we aren't leaking the underscored overlay names anywhere and don't
// regress test performance by indexing the stdlib.
//
// RUN: %FileCheck %s --input-file %t/units --check-prefix=UNITS-NEGATIVE
// UNITS-NEGATIVE-NOT: Unit | {{.*}} | _ABAdditions
// UNITS-NEGATIVE-NOT: Record | {{.*}} | _ABAdditions
// UNITS-NEGATIVE-NOT: Unit | {{.*}} | __ABAdditionsCAdditions
// UNITS-NEGATIVE-NOT: Record | {{.*}} | __ABAdditionsCAdditions
// UNITS-NEGATIVE-NOT: Record | system | Swift
| apache-2.0 | d43391598e8420e5207b12078e7828d0 | 46.936364 | 276 | 0.611037 | 3.469079 | false | false | false | false |
vector-im/vector-ios | Riot/Model/WellKnown/VectorWellKnownBackupSetupMethod.swift | 1 | 1161 | //
// Copyright 2022 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// Methods to use to setup secure backup (SSSS).
@objc enum VectorWellKnownBackupSetupMethod: Int, CaseIterable {
case passphrase = 0
case key
private enum Constants {
static let setupMethodPassphrase: String = "passphrase"
static let setupMethodKey: String = "key"
}
init?(key: String) {
switch key {
case Constants.setupMethodPassphrase:
self = .passphrase
case Constants.setupMethodKey:
self = .key
default:
return nil
}
}
}
| apache-2.0 | 18aff4250e51b3da5d3b8e459aaa6a7d | 28.769231 | 75 | 0.677864 | 4.414449 | false | false | false | false |
nighthawk/ASPolygonKit | Sources/ASPolygonKit/QuickLookable.swift | 1 | 2154 | //
// QuickLookable.swift
//
// Created by Adrian Schoenig on 24/2/17.
//
//
import Foundation
#if canImport(CoreGraphics)
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif
extension Polygon {
public var quickLookPath: CGPath {
let maxLength: CGFloat = 200
let factor = maxLength / CGFloat(Double.maximum(maxX - minX, maxY - minY))
let offset = CGPoint(x: minX, y: minY) * factor
let path = CGMutablePath()
points.enumerated().forEach { index, point in
if index == 0 {
path.move(to: point.cgPoint * factor - offset)
} else {
path.addLine(to: point.cgPoint * factor - offset, transform: .identity)
}
}
path.closeSubpath()
return path
}
#if os(OSX)
public var bezierPath: NSBezierPath {
let maxLength: CGFloat = 200
let factor = maxLength / CGFloat(Double.maximum(maxX - minX, maxY - minY))
let offset = CGPoint(x: minX, y: minY) * factor
let path = NSBezierPath()
points.enumerated().forEach { index, point in
if index == 0 {
path.move(to: point.cgPoint * factor - offset)
} else {
path.line(to: point.cgPoint * factor - offset)
}
}
path.close()
return path
}
var quickLookImage: NSImage? {
let path = bezierPath
return NSImage(size: path.bounds.size, flipped: false) { rect in
let strokeColor = NSColor.green
strokeColor.setStroke()
path.stroke()
return true
}
}
public var debugQuickLookObject: Any {
return quickLookImage ?? description!
}
#endif
}
#if os(OSX)
extension Polygon: CustomPlaygroundDisplayConvertible {
public var playgroundDescription: Any {
return quickLookImage ?? description ?? "Undefined polygon"
}
}
#endif
func *(lhs: CGPoint, rhs: CGFloat) -> CGPoint {
return CGPoint(x: lhs.x * rhs, y: lhs.y * rhs)
}
func -(lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
extension Point {
var cgPoint: CGPoint {
return CGPoint(x: x, y: y)
}
}
#endif
| mit | ba6a063ada28a9b1c0814c8bc800f763 | 18.581818 | 79 | 0.608635 | 3.839572 | false | false | false | false |
CRAnimation/CRAnimation | Pod/CRWidget/RollerCoasterLayer/RollerCoasterLayer.swift | 1 | 19974 | //
// RollerCoasterLayer.swift
// RollerCoasterAnimation
//
// **************************************************
// * _____ *
// * __ _ __ ___ \ / *
// * \ \/ \/ / / __\ / / *
// * \ _ / | (__ / / *
// * \/ \/ \___/ / /__ *
// * /_____/ *
// * *
// **************************************************
// Github :https://github.com/631106979
// HomePage:http://imwcl.com
// CSDN :http://blog.csdn.net/wang631106979
//
// Created by 王崇磊 on 16/9/14.
// Copyright © 2016年 王崇磊. All rights reserved.
//
// @class RollerCoasterLayer
// @abstract RollerCoasterLayer
// @discussion RollerCoasterLayer
//
import UIKit
open class RollerCoasterLayer: CALayer {
var groundLayer:CALayer?
var yellowPath:CAShapeLayer?
var greenPath:CAShapeLayer?
public init(frame: CGRect) {
super.init()
self.frame = frame
initLayers(frame.size)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initLayers(_ size: CGSize) {
initGradientLayer(size)
initMountainLayer(size)
initGrasslandlayer(size)
groundLayer = initGroundLayer(size)
yellowPath = initYellowPathLayer(size)
greenPath = initGreenPathLayer(size)
for index in 0...4 {
addYellowCarPathAnimation(CACurrentMediaTime() + 0.07 * Double(index))
}
for index in 0...4 {
addGreenCarPathAnimation(size, beginTime: CACurrentMediaTime() + 0.085 * Double(index))
}
addCloudAnimation(size)
addTreeLayer(size)
}
func getPoint(_ pointOne:CGPoint, pointTwo:CGPoint, referenceX:CGFloat) ->CGFloat {
let x1 = pointOne.x
let y1 = pointOne.y
let x2 = pointTwo.x
let y2 = pointTwo.y
let a:CGFloat,b:CGFloat
a = (y2-y1)/(x2-x1)
b = y1-a*x1
let y = a*referenceX+b
return y
}
//初始化mountain
func initMountainLayer(_ size:CGSize) {
//第一座山
let mountainOne:CAShapeLayer = CAShapeLayer()
let pathOne:UIBezierPath = UIBezierPath()
pathOne.move(to: CGPoint(x: 0, y: size.height - 120))
pathOne.addLine(to: CGPoint(x: 100, y: 100))
pathOne.addLine(to: CGPoint(x: size.width/3, y: size.height - 100))
pathOne.addLine(to: CGPoint(x: size.width/1.5, y: size.height - 50))
pathOne.addLine(to: CGPoint(x: 0, y: size.height))
mountainOne.path = pathOne.cgPath
mountainOne.fillColor = UIColor.white.cgColor
addSublayer(mountainOne)
let mountainOneLayer:CAShapeLayer = CAShapeLayer()
let pathLayerOne:UIBezierPath = UIBezierPath()
pathLayerOne.move(to: CGPoint(x: 0, y: size.height - 120))
var pathOneHeight = getPoint(CGPoint(x: 0, y: size.height - 120), pointTwo: CGPoint(x: 100, y: 100), referenceX: 55)
var pathTwoHeight = getPoint(CGPoint(x: 100, y: 100), pointTwo: CGPoint(x: size.width/3, y: size.height - 100), referenceX: 160)
pathLayerOne.addLine(to: CGPoint(x: 55, y: pathOneHeight))
pathLayerOne.addLine(to: CGPoint(x: 70, y: pathOneHeight + 15))
pathLayerOne.addLine(to: CGPoint(x: 90, y: pathOneHeight))
pathLayerOne.addLine(to: CGPoint(x: 110, y: pathOneHeight + 25))
pathLayerOne.addLine(to: CGPoint(x: 130, y: pathOneHeight - 5))
pathLayerOne.addLine(to: CGPoint(x: 160, y: pathTwoHeight))
pathLayerOne.addLine(to: CGPoint(x: size.width/3, y: size.height - 100))
pathLayerOne.addLine(to: CGPoint(x: size.width/1.5, y: size.height - 50))
pathLayerOne.addLine(to: CGPoint(x: 0, y: size.height))
mountainOneLayer.path = pathLayerOne.cgPath
mountainOneLayer.fillColor = UIColor.init(red: 104.0/255.0, green: 92.0/255.0, blue: 157.0/255.0, alpha: 1.0).cgColor
addSublayer(mountainOneLayer)
//第二座山
let mountainTwo:CAShapeLayer = CAShapeLayer()
let pathTwo:UIBezierPath = UIBezierPath()
pathTwo.move(to: CGPoint(x: size.width/4, y: size.height - 90))
pathTwo.addLine(to: CGPoint(x: size.width/2.7, y: 200))
pathTwo.addLine(to: CGPoint(x: size.width/1.8, y: size.height - 85))
pathTwo.addLine(to: CGPoint(x: size.width/1.6, y: size.height - 125))
pathTwo.addLine(to: CGPoint(x: size.width/1.35, y: size.height - 70))
pathTwo.addLine(to: CGPoint(x: 0, y: size.height))
mountainTwo.path = pathTwo.cgPath
mountainTwo.fillColor = UIColor.white.cgColor
insertSublayer(mountainTwo, below: mountainOne)
let mountainTwoLayer:CAShapeLayer = CAShapeLayer()
let pathLayerTwo:UIBezierPath = UIBezierPath()
pathLayerTwo.move(to: CGPoint(x: 0, y: size.height))
pathLayerTwo.addLine(to: CGPoint(x: size.width/4, y: size.height - 90))
pathOneHeight = getPoint(CGPoint(x: size.width/4, y: size.height - 90), pointTwo: CGPoint(x: size.width/2.7, y: 200), referenceX: size.width/4+50)
pathTwoHeight = getPoint(CGPoint(x: size.width/1.8, y: size.height - 85), pointTwo: CGPoint(x: size.width/2.7, y: 200), referenceX: size.width/2.2)
let pathThreeHeight = getPoint(CGPoint(x: size.width/1.8, y: size.height - 85), pointTwo: CGPoint(x: size.width/1.6, y: size.height - 125), referenceX: size.width/1.67)
let pathFourHeight = getPoint(CGPoint(x: size.width/1.35, y: size.height - 70), pointTwo: CGPoint(x: size.width/1.6, y: size.height - 125), referenceX: size.width/1.50)
pathLayerTwo.addLine(to: CGPoint(x: size.width/4+50, y: pathOneHeight))
pathLayerTwo.addLine(to: CGPoint(x: size.width/4+70, y: pathOneHeight + 15))
pathLayerTwo.addLine(to: CGPoint(x: size.width/4+90, y: pathOneHeight))
pathLayerTwo.addLine(to: CGPoint(x: size.width/4+110, y: pathOneHeight + 15))
pathLayerTwo.addLine(to: CGPoint(x: size.width/2.2, y: pathTwoHeight))
pathLayerTwo.addLine(to: CGPoint(x: size.width/1.8, y: size.height - 85))
pathLayerTwo.addLine(to: CGPoint(x: size.width/1.67, y: pathThreeHeight))
pathLayerTwo.addLine(to: CGPoint(x: size.width/1.65, y: pathThreeHeight+5))
pathLayerTwo.addLine(to: CGPoint(x: size.width/1.60, y: pathThreeHeight-2))
pathLayerTwo.addLine(to: CGPoint(x: size.width/1.58, y: pathFourHeight+2))
pathLayerTwo.addLine(to: CGPoint(x: size.width/1.55, y: pathFourHeight-5))
pathLayerTwo.addLine(to: CGPoint(x: size.width/1.50, y: pathFourHeight))
pathLayerTwo.addLine(to: CGPoint(x: size.width/1.35, y: size.height - 70))
pathLayerTwo.addLine(to: CGPoint(x: 0, y: size.height))
mountainTwoLayer.path = pathLayerTwo.cgPath
mountainTwoLayer.fillColor = UIColor.init(colorLiteralRed: 75.0/255.0, green: 65.0/255.0, blue: 111.0/255.0, alpha: 1.0).cgColor
insertSublayer(mountainTwoLayer, below: mountainOne)
}
//初始化草坪
@discardableResult
func initGrasslandlayer(_ size:CGSize) -> (CAShapeLayer, CAShapeLayer) {
let grasslandOne = CAShapeLayer()
//通过UIBezierPath来绘制路径
let pathOne:UIBezierPath = UIBezierPath()
pathOne.move(to: CGPoint(x: 0, y: size.height - 20))
pathOne.addLine(to: CGPoint(x: 0, y: size.height - 100))
pathOne.addQuadCurve(to: CGPoint(x: size.width/3.0, y: size.height - 20), controlPoint: CGPoint(x: size.width/6.0, y: size.height - 100))
grasslandOne.path = pathOne.cgPath
//设置草坪的颜色
grasslandOne.fillColor = UIColor.init(colorLiteralRed: 82.0/255.0, green: 177.0/255.0, blue: 44.0/255.0, alpha: 1.0).cgColor
addSublayer(grasslandOne)
let grasslandTwo = CAShapeLayer()
let pathTwo:UIBezierPath = UIBezierPath()
pathTwo.move(to: CGPoint(x: 0, y: size.height - 20))
pathTwo.addQuadCurve(to: CGPoint(x: size.width, y: size.height - 60), controlPoint: CGPoint(x: size.width/2.0, y: size.height - 100))
pathTwo.addLine(to: CGPoint(x: size.width, y: size.height - 20))
grasslandTwo.path = pathTwo.cgPath
grasslandTwo.fillColor = UIColor.init(colorLiteralRed: 92.0/255.0, green: 195.0/255.0, blue: 52.0/255.0, alpha: 1.0).cgColor
addSublayer(grasslandTwo)
return (grasslandOne, grasslandTwo)
}
//初始化大地
func initGroundLayer(_ size:CGSize) -> CALayer {
let ground:CALayer = CALayer()
ground.frame = CGRect(x: 0, y: size.height - 20, width: size.width, height: 20)
ground.backgroundColor = UIColor.init(patternImage: imageFromBundle("ground")!).cgColor
addSublayer(ground)
return ground
}
//初始化黄色轨道
func initYellowPathLayer(_ size:CGSize) -> CAShapeLayer {
let calayer:CAShapeLayer = CAShapeLayer()
calayer.backgroundColor = UIColor.red.cgColor
calayer.lineWidth = 5
calayer.strokeColor = UIColor.init(colorLiteralRed: 210.0/255.0, green: 179.0/255.0, blue: 54.0/255.0, alpha: 1.0).cgColor
let path:UIBezierPath = UIBezierPath()
path.move(to: CGPoint(x: 0, y: size.height - 70))
path.addCurve(to: CGPoint(x: size.width/1.5, y: 200), controlPoint1: CGPoint(x: size.width/6, y: size.height - 200), controlPoint2: CGPoint(x: size.width/2.5, y: size.height+50))
path.addQuadCurve(to: CGPoint(x: size.width+10, y: size.height/3), controlPoint: CGPoint(x: size.width-100, y: 50))
path.addLine(to: CGPoint(x: size.width + 10, y: size.height+10))
path.addLine(to: CGPoint(x: 0, y: size.height+10))
calayer.fillColor = UIColor.init(patternImage: imageFromBundle("yellow")!).cgColor
calayer.path = path.cgPath
insertSublayer(calayer, below: groundLayer)
let lineLayer:CAShapeLayer = CAShapeLayer()
lineLayer.lineCap = kCALineCapRound
lineLayer.strokeColor = UIColor.white.cgColor
lineLayer.lineDashPattern = [NSNumber.init(value: 1 as Int32),NSNumber.init(value: 5 as Int32)]
lineLayer.lineWidth = 2
lineLayer.fillColor = UIColor.clear.cgColor
lineLayer.path = path.cgPath
calayer.addSublayer(lineLayer)
return calayer
}
//初始化绿色轨道
func initGreenPathLayer(_ size:CGSize) -> CAShapeLayer {
let calayer:CAShapeLayer = CAShapeLayer()
calayer.backgroundColor = UIColor.red.cgColor
calayer.lineWidth = 5
calayer.fillRule = kCAFillRuleEvenOdd
calayer.strokeColor = UIColor.init(colorLiteralRed: 0.0/255.0, green: 147.0/255.0, blue: 163.0/255.0, alpha: 1.0).cgColor
let path:UIBezierPath = UIBezierPath()
path.lineCapStyle = .round
path.lineJoinStyle = .round
path.move(to: CGPoint(x: size.width + 10, y: size.height))
path.addLine(to: CGPoint(x: size.width + 10, y: size.height - 70))
path.addQuadCurve(to: CGPoint(x: size.width/1.8, y: size.height - 70), controlPoint: CGPoint(x: size.width - 120, y: 200))
path.addArc(withCenter: CGPoint(x: size.width/1.9, y: size.height - 140), radius: 70, startAngle: CGFloat(0.5*Double.pi), endAngle: CGFloat(2.5*Double.pi), clockwise: true)
path.addCurve(to: CGPoint(x: 0, y: size.height - 100), controlPoint1: CGPoint(x: size.width/1.8 - 60, y: size.height - 60), controlPoint2: CGPoint(x: 150, y: size.height/2.3))
path.addLine(to: CGPoint(x: -100, y: size.height + 10))
calayer.fillColor = UIColor.clear.cgColor
calayer.path = path.cgPath
insertSublayer(calayer, below: groundLayer)
let greenLayer:CAShapeLayer = CAShapeLayer()
greenLayer.fillRule = kCAFillRuleEvenOdd
greenLayer.strokeColor = UIColor.init(colorLiteralRed: 0.0/255.0, green: 147.0/255.0, blue: 163.0/255.0, alpha: 1.0).cgColor
let grennPath:UIBezierPath = UIBezierPath()
grennPath.move(to: CGPoint(x: size.width + 10, y: size.height))
grennPath.addLine(to: CGPoint(x: size.width + 10, y: size.height - 70))
grennPath.addQuadCurve(to: CGPoint(x: size.width/1.8, y: size.height - 70), controlPoint: CGPoint(x: size.width - 120, y: 200))
grennPath.addCurve(to: CGPoint(x: 0, y: size.height - 100), controlPoint1: CGPoint(x: size.width/1.8 - 60, y: size.height - 60), controlPoint2: CGPoint(x: 150, y: size.height/2.3))
grennPath.addLine(to: CGPoint(x: -100, y: size.height + 10))
greenLayer.fillColor = UIColor.init(patternImage: imageFromBundle("green")!).cgColor
greenLayer.path = grennPath.cgPath
insertSublayer(greenLayer, below: calayer)
let lineLayer:CAShapeLayer = CAShapeLayer()
lineLayer.lineCap = kCALineCapRound
lineLayer.strokeColor = UIColor.white.cgColor
lineLayer.lineDashPattern = [NSNumber.init(value: 1 as Int32),NSNumber.init(value: 5 as Int32)]
lineLayer.lineWidth = 2
lineLayer.fillColor = UIColor.clear.cgColor
lineLayer.path = path.cgPath
calayer.addSublayer(lineLayer)
return calayer
}
//添加黄色轨道的动画
func addYellowCarPathAnimation(_ beginTime: CFTimeInterval) {
let carLayer:CALayer = CALayer()
carLayer.frame = CGRect(x: 0, y: 0, width: 17, height: 11)
carLayer.setAffineTransform(carLayer.affineTransform().translatedBy(x: 0, y: -7))
carLayer.contents = imageFromBundle("car")!.cgImage
let animation:CAKeyframeAnimation = CAKeyframeAnimation.init(keyPath: "position")
animation.path = yellowPath?.path
animation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionLinear)
animation.duration = 6
animation.beginTime = beginTime
animation.repeatCount = MAXFLOAT
animation.autoreverses = false
animation.calculationMode = kCAAnimationCubicPaced
animation.rotationMode = kCAAnimationRotateAuto
yellowPath?.addSublayer(carLayer)
carLayer.add(animation, forKey: "carAnimation")
}
//添加绿色轨道的动画
func addGreenCarPathAnimation(_ size:CGSize, beginTime: CFTimeInterval) {
let carLayer:CALayer = CALayer()
carLayer.frame = CGRect(x: 0, y: 0, width: 17, height: 11)
carLayer.contents = imageFromBundle("otherCar")!.cgImage
//绘制路径
let path:UIBezierPath = UIBezierPath()
path.lineCapStyle = .round
path.lineJoinStyle = .round
path.move(to: CGPoint(x: size.width + 10, y: size.height - 7))
path.addLine(to: CGPoint(x: size.width + 10, y: size.height - 77))
path.addQuadCurve(to: CGPoint(x: size.width/1.8, y: size.height - 77), controlPoint: CGPoint(x: size.width - 120, y: 193))
path.addArc(withCenter: CGPoint(x: size.width/1.9, y: size.height - 140), radius: 63, startAngle: CGFloat(0.5*Double.pi), endAngle: CGFloat(2.5*Double.pi), clockwise: true)
path.addCurve(to: CGPoint(x: 0, y: size.height - 107), controlPoint1: CGPoint(x: size.width/1.8 - 60, y: size.height - 67), controlPoint2: CGPoint(x: 150, y: size.height/2.3-7))
path.addLine(to: CGPoint(x: -100, y: size.height + 7))
//关键帧动画作用于position
let animation:CAKeyframeAnimation = CAKeyframeAnimation.init(keyPath: "position")
animation.path = path.cgPath
//动画节奏为线性动画
animation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionLinear)
//动画时间
animation.duration = 6
//动画重复次数
animation.repeatCount = MAXFLOAT
//动画是否逆转
animation.autoreverses = false
animation.calculationMode = kCAAnimationCubicPaced
animation.beginTime = beginTime
//动画角度是否调整
animation.rotationMode = kCAAnimationRotateAuto
addSublayer(carLayer)
carLayer.add(animation, forKey: "carAnimation")
}
//初始化云朵动画
@discardableResult
func addCloudAnimation(_ size:CGSize) -> CALayer {
let cloudLayer:CALayer = CALayer()
cloudLayer.contents = imageFromBundle("cloud")?.cgImage
cloudLayer.frame = CGRect(x: 0, y: 0, width: 63, height: 20)
addSublayer(cloudLayer)
let path = UIBezierPath()
path.move(to: CGPoint(x: size.width + 63, y: 40))
path.addLine(to: CGPoint(x: -63, y: 40))
let animation = CAKeyframeAnimation.init(keyPath: "position")
animation.path = path.cgPath
animation.duration = 40
animation.autoreverses = false
animation.repeatCount = MAXFLOAT
animation.calculationMode = kCAAnimationPaced
cloudLayer.add(animation, forKey: "position")
return cloudLayer
}
//添加树
func addTreeLayer(_ size:CGSize) {
let tree = imageFromBundle("tree")
for index in 0...6 {
let treeOne = CALayer()
treeOne.contents = tree?.cgImage
treeOne.frame = CGRect(x: [5,55,70,size.width/3+15,size.width/3+25,size.width-130,size.width-160][index], y: size.height - 43, width: 13, height: 23)
addSublayer(treeOne)
}
for index in 0...3 {
let treeOne = CALayer()
treeOne.contents = tree?.cgImage
treeOne.frame = CGRect(x: [10,60,size.width/3,size.width-150][index], y: size.height - 52, width: 18, height: 32)
addSublayer(treeOne)
}
for index in 0...1 {
let treeOne = CALayer()
treeOne.contents = tree?.cgImage
treeOne.frame = CGRect(x: [size.width-210,size.width-50][index], y: [size.height - 75,size.height - 80][index], width: 18, height: 32)
insertSublayer(treeOne, below: yellowPath)
}
for index in 0...2 {
let treeOne = CALayer()
treeOne.contents = tree?.cgImage
treeOne.frame = CGRect(x: [size.width-235, size.width-220, size.width-40][index], y: [size.height - 67 ,size.height - 67 , size.height - 72][index], width: 13, height: 23)
insertSublayer(treeOne, below: yellowPath)
}
}
//初始化背景
@discardableResult
func initGradientLayer(_ size:CGSize) -> CAGradientLayer {
let layer:CAGradientLayer = CAGradientLayer()
layer.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height - 20)
//设置渐变的颜色
layer.colors = [UIColor.init(colorLiteralRed: 178.0/255.0, green: 226.0/255.0, blue: 248.0/255.0, alpha: 1.0).cgColor, UIColor.init(colorLiteralRed: 232.0/255.0, green: 244.0/255.0, blue: 193.0/255.0, alpha: 1.0).cgColor]
//设置渐变的方向为从左到右
layer.startPoint = CGPoint(x: 0, y: 0)
layer.endPoint = CGPoint(x: 1, y: 1)
addSublayer(layer)
return layer
}
func imageFromBundle(_ imageName: String) -> UIImage? {
let imageName = imageName
if let path = WCLImagePickerBundle.wclBundle.path(forResource: imageName, ofType: "png") {
let image = UIImage(contentsOfFile: path)
return image
}
return nil
}
}
internal struct WCLImagePickerBundle {
// 当前的bundle
static var bundle: Bundle {
let bundle = Bundle(for: RollerCoasterLayer.self)
return bundle
}
// 存放资源的bundle
static var wclBundle: Bundle {
let bundle = Bundle(path: self.bundle.path(forResource: "RollerCoasterLayer", ofType: "bundle")!)
return bundle!
}
}
| mit | 50f1d9e79ca6b640276694ef055296f5 | 47.761787 | 229 | 0.626737 | 3.629664 | false | false | false | false |
zapdroid/RXWeather | Pods/RxTest/RxTest/Event+Equatable.swift | 1 | 3584 | //
// Event+Equatable.swift
// RxTest
//
// Created by Krunoslav Zaher on 12/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import RxSwift
import class Foundation.NSError
/// Compares two events. They are equal if they are both the same member of `Event` enumeration.
///
/// In case `Error` events are being compared, they are equal in case their `NSError` representations are equal (domain and code)
/// and their string representations are equal.
public func == <Element: Equatable>(lhs: Event<Element>, rhs: Event<Element>) -> Bool {
switch (lhs, rhs) {
case (.completed, .completed): return true
case let (.error(e1), .error(e2)):
#if os(Linux)
return "\(e1)" == "\(e2)"
#else
let error1 = e1 as NSError
let error2 = e2 as NSError
return error1.domain == error2.domain
&& error1.code == error2.code
&& "\(e1)" == "\(e2)"
#endif
case let (.next(v1), .next(v2)): return v1 == v2
default: return false
}
}
/// Compares two events. They are equal if they are both the same member of `Event` enumeration.
///
/// In case `Error` events are being compared, they are equal in case their `NSError` representations are equal (domain and code)
/// and their string representations are equal.
public func == <Element: Equatable>(lhs: SingleEvent<Element>, rhs: SingleEvent<Element>) -> Bool {
switch (lhs, rhs) {
case let (.error(e1), .error(e2)):
#if os(Linux)
return "\(e1)" == "\(e2)"
#else
let error1 = e1 as NSError
let error2 = e2 as NSError
return error1.domain == error2.domain
&& error1.code == error2.code
&& "\(e1)" == "\(e2)"
#endif
case let (.success(v1), .success(v2)): return v1 == v2
default: return false
}
}
/// Compares two events. They are equal if they are both the same member of `Event` enumeration.
///
/// In case `Error` events are being compared, they are equal in case their `NSError` representations are equal (domain and code)
/// and their string representations are equal.
public func == <Element: Equatable>(lhs: MaybeEvent<Element>, rhs: MaybeEvent<Element>) -> Bool {
switch (lhs, rhs) {
case (.completed, .completed): return true
case let (.error(e1), .error(e2)):
#if os(Linux)
return "\(e1)" == "\(e2)"
#else
let error1 = e1 as NSError
let error2 = e2 as NSError
return error1.domain == error2.domain
&& error1.code == error2.code
&& "\(e1)" == "\(e2)"
#endif
case let (.success(v1), .success(v2)): return v1 == v2
default: return false
}
}
/// Compares two events. They are equal if they are both the same member of `Event` enumeration.
///
/// In case `Error` events are being compared, they are equal in case their `NSError` representations are equal (domain and code)
/// and their string representations are equal.
public func == (lhs: CompletableEvent, rhs: CompletableEvent) -> Bool {
switch (lhs, rhs) {
case (.completed, .completed): return true
case let (.error(e1), .error(e2)):
#if os(Linux)
return "\(e1)" == "\(e2)"
#else
let error1 = e1 as NSError
let error2 = e2 as NSError
return error1.domain == error2.domain
&& error1.code == error2.code
&& "\(e1)" == "\(e2)"
#endif
default: return false
}
}
| mit | 88318e0d67aa948dc4ed25362ca46d6a | 34.83 | 129 | 0.591125 | 3.886117 | false | false | false | false |
Shashi717/ImmiGuide | ImmiGuide/ImmiGuide/GED.swift | 1 | 1190 | //
// GED.swift
// ImmiGuide
//
// Created by Cris on 2/18/17.
// Copyright © 2017 Madushani Lekam Wasam Liyanage. All rights reserved.
//
import Foundation
class GED {
let address: String
let borough: String
let contactNumber: String
let notes: String?
let siteName: String
var description: String {
return "\(address) \n\(borough), New York"
}
init?(address: String, borough: String, contactNumber: String, notes: String?, siteName: String) {
self.address = address
self.borough = borough
self.contactNumber = contactNumber
self.notes = notes
self.siteName = siteName
}
convenience init?(fromDict: [String : Any]) {
guard let address = fromDict["address"] as? String,
let borough = fromDict["borough"] as? String,
let number = fromDict["contact_number"] as? String,
let siteName = fromDict["program_site_name"] as? String else { return nil }
let notes = fromDict["notes"] as? String
self.init(address: address, borough: borough, contactNumber: number, notes: notes, siteName: siteName)
}
}
| mit | 7279ca313678f40c62726cd48d6364c7 | 27.309524 | 110 | 0.614802 | 4.1 | false | false | false | false |
clarkio/ios-favorite-movies | Favorite Movies/Favorite Movies/Movie.swift | 1 | 526 | //
// Movie.swift
// Favorite Movies
//
// Created by Brian on 12/10/16.
// Copyright © 2016 bc. All rights reserved.
//
import Foundation
class Movie {
var id: String = ""
var title: String = ""
var year: String = ""
var imageUrl: String = ""
var plot: String = ""
init(id: String, title: String, year: String, imageUrl: String, plot: String = "") {
self.id = id
self.title = title
self.year = year
self.imageUrl = imageUrl
self.plot = plot
}
}
| mit | 2d635a20d94ac2ca533755d5c988764d | 20 | 88 | 0.561905 | 3.62069 | false | false | false | false |
actorapp/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/ActorCore/Providers/Storage/FMDBList.swift | 2 | 14156 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
class FMDBList : NSObject, ARListStorageDisplayEx {
var db :FMDatabase? = nil;
var isTableChecked: Bool = false;
let databasePath: String;
let tableName: String;
let queryCreate: String;
let queryCreateIndex: String;
let queryCreateFilter: String;
let queryCount: String;
let queryEmpty: String
let queryAdd: String;
let queryItem: String;
let queryDelete: String;
let queryDeleteAll: String;
let queryForwardFirst: String;
let queryForwardMore: String;
let queryForwardFilterFirst: String;
let queryForwardFilterMore: String;
let queryBackwardFirst: String;
let queryBackwardMore: String;
let queryBackwardFilterFirst: String;
let queryBackwardFilterMore: String;
let queryCenterBackward: String;
let queryCenterForward: String;
init (databasePath: String, tableName: String){
self.databasePath = databasePath
self.tableName = tableName;
self.queryCreate = "CREATE TABLE IF NOT EXISTS " + tableName + " (" + //
"\"ID\" INTEGER NOT NULL," + // 0: id
"\"SORT_KEY\" INTEGER NOT NULL," + // 1: sortKey
"\"QUERY\" TEXT," + // 2: query
"\"BYTES\" BLOB NOT NULL," + // 3: bytes
"PRIMARY KEY(\"ID\"));";
self.queryCreateIndex = "CREATE INDEX IF NOT EXISTS IDX_ID_SORT ON " + tableName + " (\"SORT_KEY\");"
self.queryCreateFilter = "CREATE INDEX IF NOT EXISTS IDX_ID_QUERY_SORT ON " + tableName + " (\"QUERY\", \"SORT_KEY\");"
self.queryCount = "SELECT COUNT(*) FROM " + tableName + ";";
self.queryEmpty = "EXISTS (SELECT * FROM " + tableName + ");"
self.queryAdd = "REPLACE INTO " + tableName + " (\"ID\",\"QUERY\",\"SORT_KEY\",\"BYTES\") VALUES (?,?,?,?)";
self.queryItem = "SELECT \"ID\",\"QUERY\",\"SORT_KEY\",\"BYTES\" FROM " + tableName + " WHERE \"ID\" = ?;";
self.queryDeleteAll = "DELETE FROM " + tableName + ";";
self.queryDelete = "DELETE FROM " + tableName + " WHERE \"ID\"= ?;";
self.queryForwardFirst = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " ORDER BY SORT_KEY DESC LIMIT ?";
self.queryForwardMore = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " WHERE \"SORT_KEY\" < ? ORDER BY SORT_KEY DESC LIMIT ?";
self.queryBackwardFirst = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " ORDER BY SORT_KEY ASC LIMIT ?";
self.queryBackwardMore = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " WHERE \"SORT_KEY\" > ? ORDER BY SORT_KEY ASC LIMIT ?";
self.queryCenterForward = queryForwardMore
self.queryCenterBackward = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " WHERE \"SORT_KEY\" >= ? ORDER BY SORT_KEY ASC LIMIT ?";
self.queryForwardFilterFirst = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " WHERE \"QUERY\" LIKE ? OR \"QUERY\" LIKE ? ORDER BY SORT_KEY DESC LIMIT ?";
self.queryForwardFilterMore = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " WHERE (\"QUERY\" LIKE ? OR \"QUERY\" LIKE ?) AND \"SORT_KEY\" < ? ORDER BY SORT_KEY DESC LIMIT ?";
self.queryBackwardFilterFirst = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " WHERE \"QUERY\" LIKE ? OR \"QUERY\" LIKE ? ORDER BY SORT_KEY ASC LIMIT ?";
self.queryBackwardFilterMore = "SELECT \"ID\", \"QUERY\",\"SORT_KEY\", \"BYTES\" FROM " + tableName + " WHERE (\"QUERY\" LIKE ? OR \"QUERY\" LIKE ?) AND \"SORT_KEY\" > ? ORDER BY SORT_KEY ASC LIMIT ?";
}
func checkTable() {
if (isTableChecked) {
return
}
isTableChecked = true;
self.db = FMDatabase(path: databasePath)
self.db!.open()
if (!db!.tableExists(tableName)) {
db!.executeUpdate(queryCreate)
db!.executeUpdate(queryCreateIndex)
db!.executeUpdate(queryCreateFilter)
}
}
func updateOrAdd(withValue valueContainer: ARListEngineRecord!) {
checkTable();
let start = Date()
// db!.beginTransaction()
db!.executeUpdate(queryAdd, withArgumentsIn: [valueContainer.getKey().toNSNumber(), valueContainer.dbQuery(), valueContainer.getOrder().toNSNumber(),
valueContainer.getData().toNSData()])
// db!.commit()
log("updateOrAddWithValue \(tableName): \(valueContainer.getData().length()) in \(Int((Date().timeIntervalSince(start)*1000)))")
}
func updateOrAdd(with items: JavaUtilList!) {
checkTable();
db!.beginTransaction()
for i in 0..<items.size() {
let record = items.getWith(i) as! ARListEngineRecord;
db!.executeUpdate(queryAdd, record.getKey().toNSNumber(), record.dbQuery(), record.getOrder().toNSNumber(),
record.getData().toNSData() as AnyObject)
}
db!.commit()
}
func delete(withKey key: jlong) {
checkTable();
db!.beginTransaction()
db!.executeUpdate(queryDelete, key.toNSNumber());
db!.commit()
}
func delete(withKeys keys: IOSLongArray!) {
checkTable();
db!.beginTransaction()
for i in 0..<keys.length() {
let k = keys.long(at: UInt(i));
db!.executeUpdate(queryDelete, k.toNSNumber());
}
db!.commit()
}
func getCount() -> jint {
checkTable();
let result = db!.executeQuery(queryCount)
if (result == nil) {
return 0;
}
if (result!.next()) {
let res = jint(result!.int(forColumnIndex: 0))
result?.close()
return res
} else {
result?.close()
}
return 0;
}
func isEmpty() -> Bool {
checkTable();
let result = db!.executeQuery(queryEmpty)
if (result == nil) {
return false;
}
if (result!.next()) {
let res = result!.int(forColumnIndex: 0)
result?.close()
return res > 0
} else {
result?.close()
}
return false;
}
func clear() {
checkTable();
db!.beginTransaction()
db!.executeUpdate(queryDeleteAll);
db!.commit()
}
func loadItem(withKey key: jlong) -> ARListEngineRecord! {
checkTable();
let result = db!.executeQuery(queryItem, key.toNSNumber());
if (result == nil) {
return nil
}
if (result!.next()) {
var query: AnyObject! = result!.object(forColumnName: "QUERY") as AnyObject!;
if (query is NSNull){
query = nil
}
let res = ARListEngineRecord(key: jlong(result!.longLongInt(forColumn: "ID")), withOrder: jlong(result!.longLongInt(forColumn: "SORT_KEY")), withQuery: query as! String?, withData: result!.data(forColumn: "BYTES").toJavaBytes())
result?.close()
return res;
} else {
result?.close()
return nil
}
}
func loadAllItems() -> JavaUtilList! {
let res = JavaUtilArrayList()
// TODO: Implement
return res
}
func loadForward(withSortKey sortingKey: JavaLangLong!, withLimit limit: jint) -> JavaUtilList! {
checkTable();
var result : FMResultSet? = nil;
if (sortingKey == nil) {
result = db!.executeQuery(queryForwardFirst, limit.toNSNumber());
} else {
result = db!.executeQuery(queryForwardMore, sortingKey!.toNSNumber(), limit.toNSNumber());
}
if (result == nil) {
NSLog(db!.lastErrorMessage())
return nil
}
let res: JavaUtilArrayList = JavaUtilArrayList();
let queryIndex = result!.columnIndex(forName: "QUERY")
let idIndex = result!.columnIndex(forName: "ID")
let sortKeyIndex = result!.columnIndex(forName: "SORT_KEY")
let bytesIndex = result!.columnIndex(forName: "BYTES")
var dataSize = 0
var rowCount = 0
while(result!.next()) {
let key = jlong(result!.longLongInt(forColumnIndex: idIndex))
let order = jlong(result!.longLongInt(forColumnIndex: sortKeyIndex))
var query: AnyObject! = result!.object(forColumnIndex: queryIndex) as AnyObject!
if (query is NSNull) {
query = nil
}
let data = result!.data(forColumnIndex: bytesIndex).toJavaBytes()
dataSize += Int(data.length())
rowCount += 1
let record = ARListEngineRecord(key: key, withOrder: order, withQuery: query as! String?, withData: data)
res.add(withId: record)
}
result!.close()
return res;
}
func loadForward(withQuery query: String!, withSortKey sortingKey: JavaLangLong!, withLimit limit: jint) -> JavaUtilList! {
checkTable();
var result : FMResultSet? = nil;
if (sortingKey == nil) {
result = db!.executeQuery(queryForwardFilterFirst, query + "%", "% " + query + "%", limit.toNSNumber());
} else {
result = db!.executeQuery(queryForwardFilterMore, query + "%", "% " + query + "%", sortingKey!.toNSNumber(), limit.toNSNumber());
}
if (result == nil) {
NSLog(db!.lastErrorMessage())
return nil
}
let res: JavaUtilArrayList = JavaUtilArrayList();
while(result!.next()) {
var query: AnyObject! = result!.object(forColumnName: "QUERY") as AnyObject!;
if (query is NSNull) {
query = nil
}
let record = ARListEngineRecord(key: jlong(result!.longLongInt(forColumn: "ID")), withOrder: jlong(result!.longLongInt(forColumn: "SORT_KEY")), withQuery: query as! String?, withData: result!.data(forColumn: "BYTES").toJavaBytes())
res.add(withId: record)
}
result!.close()
return res;
}
func loadBackward(withSortKey sortingKey: JavaLangLong!, withLimit limit: jint) -> JavaUtilList! {
checkTable();
var result : FMResultSet? = nil;
if (sortingKey == nil) {
result = db!.executeQuery(queryBackwardFirst, limit.toNSNumber());
} else {
result = db!.executeQuery(queryBackwardMore, sortingKey!.toNSNumber(), limit.toNSNumber());
}
if (result == nil) {
NSLog(db!.lastErrorMessage())
return nil
}
let res: JavaUtilArrayList = JavaUtilArrayList();
while(result!.next()) {
var query: AnyObject! = result!.object(forColumnName: "QUERY") as AnyObject!;
if (query is NSNull) {
query = nil
}
let record = ARListEngineRecord(key: jlong(result!.longLongInt(forColumn: "ID")), withOrder: jlong(result!.longLongInt(forColumn: "SORT_KEY")), withQuery: query as! String?, withData: result!.data(forColumn: "BYTES").toJavaBytes())
res.add(withId: record)
}
result!.close()
return res;
}
func loadBackward(withQuery query: String!, withSortKey sortingKey: JavaLangLong!, withLimit limit: jint) -> JavaUtilList! {
checkTable();
var result : FMResultSet? = nil;
if (sortingKey == nil) {
result = db!.executeQuery(queryBackwardFilterFirst, query + "%", "% " + query + "%", limit.toNSNumber())
} else {
result = db!.executeQuery(queryBackwardFilterMore, query + "%", "% " + query + "%", sortingKey!.toNSNumber(), limit.toNSNumber())
}
if (result == nil) {
NSLog(db!.lastErrorMessage())
return nil
}
let res: JavaUtilArrayList = JavaUtilArrayList();
while(result!.next()) {
var query: AnyObject! = result!.object(forColumnName: "QUERY") as AnyObject!;
if (query is NSNull) {
query = nil
}
let record = ARListEngineRecord(key: jlong(result!.longLongInt(forColumn: "ID")), withOrder: jlong(result!.longLongInt(forColumn: "SORT_KEY")), withQuery: query as! String?, withData: result!.data(forColumn: "BYTES").toJavaBytes())
res.add(withId: record)
}
result!.close()
return res;
}
func loadCenter(withSortKey centerSortKey: JavaLangLong!, withLimit limit: jint) -> JavaUtilList! {
checkTable();
let res: JavaUtilArrayList = JavaUtilArrayList();
res.addAll(with: loadSlise(db!.executeQuery(queryCenterBackward, centerSortKey.toNSNumber(), limit.toNSNumber())))
res.addAll(with: loadSlise(db!.executeQuery(queryCenterForward, centerSortKey.toNSNumber(), limit.toNSNumber())))
return res
}
func loadSlise(_ result: FMResultSet?) -> JavaUtilList! {
if (result == nil) {
NSLog(db!.lastErrorMessage())
return nil
}
let res: JavaUtilArrayList = JavaUtilArrayList();
while(result!.next()) {
var query: AnyObject! = result!.object(forColumnName: "QUERY") as AnyObject!;
if (query is NSNull) {
query = nil
}
let record = ARListEngineRecord(key: jlong(result!.longLongInt(forColumn: "ID")), withOrder: jlong(result!.longLongInt(forColumn: "SORT_KEY")), withQuery: query as! String?, withData: result!.data(forColumn: "BYTES").toJavaBytes())
res.add(withId: record)
}
result!.close()
return res;
}
}
| agpl-3.0 | 3cea8d21355dfb25180480bf42ef5955 | 37.89011 | 243 | 0.561387 | 4.753526 | false | false | false | false |
onekyle/YCHPhotoKit | Source/Classes/AssetsReader/PHAsset+Extension.swift | 1 | 1739 | //
// PHAsset+Extension.swift
// YCHPhotoKit
//
// Created by Kyle on 9/7/2019.
//
import Photos
import MobileCoreServices
public let YCHTypeGIF = kUTTypeGIF as String
extension PHAsset {
public var assetMediaType: AssetMediaType {
let asset = self
var mediaType: AssetMediaType
switch asset.mediaType {
case .image:
if asset.assetIsGif() {
mediaType = .gif
} else if #available(iOS 9.1, *), asset.mediaSubtypes == PHAssetMediaSubtype.photoLive || asset.mediaSubtypes.rawValue == 10 {
mediaType = .livePhoto
} else if asset.mediaSubtypes.rawValue == 10 {
mediaType = .livePhoto
} else {
mediaType = .image
}
case .video:
mediaType = .video
case .audio:
mediaType = .audio
default:
mediaType = .unKnown
}
return mediaType
}
public func assetIsGif() -> Bool {
if let identifier = self.value(forKey: "uniformTypeIdentifier") as? String {
return identifier == YCHTypeGIF
}
return false
}
@discardableResult
public func requestImage(for size: CGSize, resizeMode: PHImageRequestOptionsResizeMode = .fast, completion: @escaping (UIImage?, [AnyHashable : Any]?) -> Swift.Void) -> PHImageRequestID {
return AssetsReader.requestImage(for: self, size: size, resizeMode: resizeMode, completion: completion)
}
public func size(for contentHeight: CGFloat) -> CGSize {
let scale = max(0.5, CGFloat(pixelWidth) / CGFloat(pixelHeight))
return CGSize(width: contentHeight * scale, height: contentHeight)
}
}
| mit | 2fb969626c98388168ea06fc4e45b1cd | 31.203704 | 191 | 0.604945 | 4.637333 | false | false | false | false |
xeecos/motionmaker | GIFMaker/AppDelegate.swift | 1 | 6300 | //
// AppDelegate.swift
// GIFMaker
//
// Created by indream on 15/9/17.
// Copyright © 2015年 indream. 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 throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.xeecos.GIFMaker" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "GIFMaker", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.landscapeRight;
}
}
| mit | 938d9ed5980399f29eee536769b9bf65 | 54.236842 | 291 | 0.719073 | 5.868593 | false | false | false | false |
thebrankoo/CryptoLab | CryptoLabDemo/CryptoLabDemo/AESViewController.swift | 1 | 2698 | //
// AESViewController.swift
// CryptoLabDemo
//
// Created by Branko Popovic on 4/11/17.
// Copyright © 2017 Branko Popovic. All rights reserved.
//
import UIKit
import CryptoLab
class AESViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var inputField: UITextView!
@IBOutlet weak var outputField: UITextView!
@IBOutlet weak var picker: UIPickerView!
@IBOutlet weak var key: UITextField!
@IBOutlet weak var iv: UITextField!
fileprivate var selectedMode = ""
fileprivate let modes = ["ecb", "cbc", "ofb", "cfb"]
override func viewDidLoad() {
super.viewDidLoad()
self.iv.text = "some02ilaslkd0309".data(using: .utf8)!.hexEncodedString()
selectedMode = modes.first!
self.picker.delegate = self
self.picker.dataSource = self
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return modes.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return modes[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedMode = modes[row]
}
fileprivate func createAES() -> AESCipher? {
var aes: AESCipher?
do {
if selectedMode == "ecb" {
aes = try AESCipher(key: key.text!.data(using: .utf8)!, iv: iv.text!.data(using: .utf8)!, blockMode: .ecb)
}
else if selectedMode == "cbc" {
aes = try AESCipher(key: key.text!.data(using: .utf8)!, iv: iv.text!.data(using: .utf8)!, blockMode: .cbc)
}
else if selectedMode == "ofb" {
aes = try AESCipher(key: key.text!.data(using: .utf8)!, iv: iv.text!.data(using: .utf8)!, blockMode: .ofb)
}
else if selectedMode == "cfb" {
aes = try AESCipher(key: key.text!.data(using: .utf8)!, iv: iv.text!.data(using: .utf8)!, blockMode: .cfb)
}
return aes
}
catch let err {
print("\(err)")
return nil
}
}
@IBAction func encryptAction(_ sender: Any) {
let toEncrypt = inputField.text!
do {
let aes = createAES()
let encrypted = try aes?.encrypt(data: toEncrypt.data(using: .utf8)!)
outputField.text = encrypted?.base64EncodedString()
}
catch let err {
print("AES Error \(err)")
}
}
@IBAction func decryptAction(_ sender: Any) {
let toDecrypt = inputField.text!
do {
let aes = createAES()
let decrypted = try aes?.decrypt(data: Data(base64Encoded: toDecrypt)!)
outputField.text = String(data: decrypted!, encoding: .utf8) //decrypted?.hexEncodedString()
}
catch let err {
print("AES Error \(err)")
}
}
}
| mit | 058117dc33e7d4db704a6d2e46228142 | 25.70297 | 110 | 0.672228 | 3.313268 | false | false | false | false |
Togira/Bubbles | Bubbles/Bubbles/Bubble.swift | 1 | 1137 | //
// Bubble.swift
// Bubbles
//
// Created by Bliss Chapman on 2/19/16.
// Copyright © 2016 Bliss Chapman. All rights reserved.
//
import Foundation
import CoreLocation
import CloudKit
final class Bubble {
var isPopped = false
var message: String
var location: CLLocation
init(withMessage message: String, andLocation location: CLLocation) {
self.message = message
self.location = location
}
func blow(completionHandler: (CKRecord?, NSError?) -> Void) {
let record = CKRecord(recordType: "BubbleRecord", recordID: CKRecordID(recordName: NSUUID().UUIDString))
record["isPopped"] = 0
record["location"] = location
record["message"] = message
let operation = CKModifyRecordsOperation(recordsToSave: [record], recordIDsToDelete: nil)
operation.perRecordCompletionBlock = completionHandler
operation.queuePriority = .VeryHigh
operation.savePolicy = .AllKeys
Cloud.database.addOperation(operation)
Cloud.database.saveRecord(record) { (record, error) -> Void in
print("NORMAL WAY")
}
}
} | mit | 6752927659d88cfcfcfb5be5b91f0f00 | 27.425 | 112 | 0.668134 | 4.617886 | false | false | false | false |
pj4533/wifimon | main.swift | 1 | 902 | import Glibc
import Foundation
func initLCD() -> HD44780LCD {
let gpios = SwiftyGPIO.getGPIOsForBoard(.RaspberryPiRev2)
let lcd = HD44780LCD(rs:gpios[.P25]!,e:gpios[.P24]!,d7:gpios[.P22]!,d6:gpios[.P27]!,d5:gpios[.P17]!,d4:gpios[.P23]!,width:20,height:4)
return lcd
}
while (true) {
print("updating...")
// weird i can't read this file directly
PiRunner().shell("cat /proc/net/wireless | tail -n1 > outfile")
do {
let text = try NSString(contentsOfFile: "outfile", encoding: NSUTF8StringEncoding)
let link = text.substringWithRange(NSRange(location: 14, length: 5))
let level = text.substringWithRange(NSRange(location: 21, length: 5))
let lcd = initLCD()
lcd.cursorHome()
lcd.clearScreen()
lcd.printString(0,y:0,what:"Link: \(link)",usCharSet:true)
lcd.printString(0,y:1,what:"Level: \(level)",usCharSet:true)
} catch (_) {
print("caught errrer")
}
sleep(1)
}
| mit | bddd95e26d1af34ac7eaafb63a6c668f | 25.529412 | 135 | 0.68847 | 2.75 | false | false | false | false |
harri121/impressions | impressions/FlickrAPI.swift | 1 | 2568 | //
// FlickrAPI.swift
// impressions
//
// Created by Daniel Hariri on 25.08.17.
// Copyright © 2017 danielhariri. All rights reserved.
//
import Foundation
import Alamofire
import CoreLocation
import SwiftyJSON
class FlickrAPI {
private let kPerPage: Int = 10
private let baseURL: String = "https://api.flickr.com/services/rest"
private let apiKey: String
private let sessionManager: SessionManager
init() {
guard let flickrKeyFilePath = Bundle.main.path(forResource: "flickr", ofType: "key") else{
fatalError("Please create a file 'flickr.key' containing the flickr API key.")
}
let apiKey = try! String(contentsOfFile: flickrKeyFilePath, encoding: String.Encoding.utf8).replacingOccurrences(of: "\n", with: "")
self.apiKey = apiKey
self.sessionManager = SessionManager()
}
func photoURLS(for location: CLLocation, completion: @escaping (Bool, [String]?) -> Void) {
let params: [String: AnyObject] = [
"method" : "flickr.photos.search" as AnyObject,
"api_key" : apiKey as AnyObject,
"lat" : location.coordinate.latitude as AnyObject,
"lon" : location.coordinate.longitude as AnyObject,
"radius" : 0.1 as AnyObject, //100 meter
"extras" : "url_l" as AnyObject,
"per_page" : kPerPage as AnyObject,
"format" : "json" as AnyObject,
"nojsoncallback" : true as AnyObject
]
let urlString = baseURL
sessionManager.request(urlString, method: .get, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON() {
response in
switch response.result {
case .success(let data):
let json = JSON(data)
guard let photoJSONArray = json["photos"]["photo"].array else {
completion(false, nil)
return
}
let photoURLS: [String] = photoJSONArray.flatMap {
guard let photoURL = $0["url_l"].string else {
return nil
}
return photoURL
}
completion(true, photoURLS)
break
case .failure(let error):
print(error.localizedDescription)
completion(false, nil)
break
}
}
}
}
| mit | 87d3566b4961f4a0ffbb89b9194d324b | 31.493671 | 140 | 0.543436 | 4.955598 | false | false | false | false |
OpenKitten/MongoKitten | Sources/MongoKitten/MongoDatabase.swift | 2 | 14477 | import MongoClient
import Logging
import Foundation
import NIO
#if canImport(NIOTransportServices) && os(iOS)
import NIOTransportServices
#endif
/// A reference to a MongoDB database, over a `Connection`.
///
/// Databases hold collections of documents.
public class MongoDatabase {
internal var transaction: MongoTransaction!
public internal(set) var session: MongoClientSession?
public var sessionId: SessionIdentifier? {
return session?.sessionId
}
public var isInTransaction: Bool {
return self.transaction != nil
}
/// The name of the database
public let name: String
public let pool: MongoConnectionPool
/// The collection to execute commands on
public var commandNamespace: MongoNamespace {
return MongoNamespace(to: "$cmd", inDatabase: self.name)
}
public private(set) var hoppedEventLoop: EventLoop?
/// The NIO event loop.
public var eventLoop: EventLoop {
return pool.eventLoop
}
internal init(named name: String, pool: MongoConnectionPool) {
self.name = name
self.pool = pool
}
public func hopped(to eventloop: EventLoop) -> MongoDatabase {
let database = MongoDatabase(named: self.name, pool: self.pool)
database.hoppedEventLoop = eventloop
return database
}
/// A helper method that uses the normal `connect` method and awaits it. It creates an event loop group for you.
///
/// It is not recommended to use `synchronousConnect` in a NIO environment (like Vapor 3), as it will create an event loop group for you.
///
/// - parameter uri: A MongoDB URI that contains at least a database component
/// - throws: Can throw for a variety of reasons, including an invalid connection string, failure to connect to the MongoDB database, etcetera.
/// - returns: A connected database instance
public static func synchronousConnect(_ uri: String) throws -> MongoDatabase {
#if canImport(NIOTransportServices) && os(iOS)
let group = NIOTSEventLoopGroup(loopCount: 1, defaultQoS: .default)
#else
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
#endif
return try self.connect(uri, on: group).wait()
}
/// A helper method that uses the normal `connect` method with the given settings and awaits it. It creates an event loop group for you.
///
/// It is not recommended to use `synchronousConnect` in a NIO environment (like Vapor 3), as it will create an event loop group for you.
///
/// - parameter settings: The connection settings, which must include a database name
/// - throws: Can throw for a variety of reasons, including an invalid connection string, failure to connect to the MongoDB database, etcetera.
/// - returns: A connected database instance
public static func synchronousConnect(settings: ConnectionSettings) throws -> MongoDatabase {
#if canImport(NIOTransportServices) && os(iOS)
let group = NIOTSEventLoopGroup(loopCount: 1, defaultQoS: .default)
#else
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
#endif
return try self.connect(settings: settings, on: group).wait()
}
/// Connect to the database at the given `uri`
///
/// Will postpone queries until initial discovery is complete. Since the cluster is lazily initialized, you'll only know of a failure in connecting (such as wrong credentials) during queries
///
/// - parameter uri: A MongoDB URI that contains at least a database component
/// - parameter loop: An EventLoop from NIO. If you want to use MongoKitten in a synchronous / non-NIO environment, use the `synchronousConnect` method.
public static func connect(_ uri: String, on group: _MongoPlatformEventLoopGroup) -> EventLoopFuture<MongoDatabase> {
do {
let settings = try ConnectionSettings(uri)
return connect(settings: settings, on: group)
} catch {
return group.next().makeFailedFuture(error)
}
}
/// Connect to the database at the given `uri`
///
/// - parameter uri: A MongoDB URI that contains at least a database component
/// - parameter loop: An EventLoop from NIO. If you want to use MongoKitten in a synchronous / non-NIO environment, use the `synchronousConnect` method.
public static func lazyConnect(_ uri: String, on loop: _MongoPlatformEventLoopGroup) throws -> MongoDatabase {
let settings = try ConnectionSettings(uri)
return try lazyConnect(settings: settings, on: loop)
}
/// Connect to the database with the given settings. You can also use `connect(_:on:)` to connect by using a connection string.
///
/// - parameter settings: The connection settings, which must include a database name
/// - parameter loop: An EventLoop from NIO. If you want to use MongoKitten in a synchronous / non-NIO environment, use the `synchronousConnect` method.
public static func connect(
settings: ConnectionSettings,
on group: _MongoPlatformEventLoopGroup,
logger: Logger = .defaultMongoCore
) -> EventLoopFuture<MongoDatabase> {
do {
guard let targetDatabase = settings.targetDatabase else {
logger.critical("Cannot connect to MongoDB: No target database specified")
throw MongoKittenError(.cannotConnect, reason: .noTargetDatabaseSpecified)
}
let cluster = try MongoCluster(lazyConnectingTo: settings, on: group, logger: logger)
return cluster.initialDiscovery.map {
return MongoDatabase(named: targetDatabase, pool: cluster)
}
} catch {
return group.next().makeFailedFuture(error)
}
}
/// Connect to the database with the given settings _lazily_. You can also use `connect(_:on:)` to connect by using a connection string.
///
/// Will postpone queries until initial discovery is complete. Since the cluster is lazily initialized, you'll only know of a failure in connecting (such as wrong credentials) during queries
///
/// - parameter settings: The connection settings, which must include a database name
/// - parameter loop: An EventLoop from NIO. If you want to use MongoKitten in a synchronous / non-NIO environment, use the `synchronousConnect` method.
public static func lazyConnect(
settings: ConnectionSettings,
on group: _MongoPlatformEventLoopGroup,
logger: Logger = .defaultMongoCore
) throws -> MongoDatabase {
guard let targetDatabase = settings.targetDatabase else {
logger.critical("Cannot connect to MongoDB: No target database specified")
throw MongoKittenError(.cannotConnect, reason: .noTargetDatabaseSpecified)
}
let cluster = try MongoCluster(lazyConnectingTo: settings, on: group)
return MongoDatabase(named: targetDatabase, pool: cluster)
}
/// Stats a new session which can be used for retryable writes, transactions and more
// public func startSession(with options: SessionOptions) -> Database {
// let newSession = session.cluster.sessionManager.next(with: options, for: session.cluster)
// return Database(named: name, session: newSession)
// }
@available(*, deprecated, message: "Change `autoCommitChanged` to `autoCommitChanges`")
public func startTransaction(
autoCommitChanged autoCommit: Bool,
with options: MongoSessionOptions = .init(),
transactionOptions: MongoTransactionOptions? = nil
) throws -> MongoTransactionDatabase {
return try startTransaction(autoCommitChanges: autoCommit, with: options, transactionOptions: transactionOptions)
}
/// Creates a new tranasction provided the SessionOptions and optional TransactionOptions
///
/// The TransactionDatabase that is created can be used like a normal Database for queries within transactions _only_
/// Creating a TransactionCollection is done the same way it's created with a normal Database.
public func startTransaction(
autoCommitChanges autoCommit: Bool,
with options: MongoSessionOptions = .init(),
transactionOptions: MongoTransactionOptions? = nil
) throws -> MongoTransactionDatabase {
guard pool.wireVersion?.supportsReplicaTransactions == true else {
pool.logger.error("MongoDB transaction not supported by the server")
throw MongoKittenError(.unsupportedFeatureByServer, reason: nil)
}
let newSession = self.pool.sessionManager.retainSession(with: options)
let transaction = newSession.startTransaction(autocommit: autoCommit)
let db = MongoTransactionDatabase(named: self.name, pool: self.pool)
db.transaction = transaction
db.hoppedEventLoop = hoppedEventLoop
db.session = newSession
return db
}
private func makeTransactionError<T>() -> EventLoopFuture<T> {
return eventLoop.makeFailedFuture(
MongoKittenError(.unsupportedFeatureByServer, reason: .transactionForUnsupportedQuery)
)
}
/// Get a `Collection` by providing a collection name as a `String`
///
/// - parameter collection: The collection/bucket to return
///
/// - returns: The requested collection in this database
public subscript(collection: String) -> MongoCollection {
let collection = MongoCollection(named: collection, in: self)
collection.session = self.session
collection.transaction = self.transaction
collection.hoppedEventLoop = self.hoppedEventLoop
return collection
}
/// Drops the current database, deleting the associated data files
///
/// - see: https://docs.mongodb.com/manual/reference/command/dropDatabase
public func drop() -> EventLoopFuture<Void> {
guard transaction == nil else {
return makeTransactionError()
}
return pool.next(for: .writable).flatMap { connection in
return connection.executeCodable(
DropDatabaseCommand(),
namespace: self.commandNamespace,
in: self.transaction,
sessionId: connection.implicitSessionId
).flatMapThrowing { reply -> Void in
try reply.assertOK()
}
}._mongoHop(to: hoppedEventLoop)
}
/// Lists all collections your user has knowledge of
///
/// Returns them as a MongoKitten Collection with you can query
public func listCollections() -> EventLoopFuture<[MongoCollection]> {
guard transaction == nil else {
return makeTransactionError()
}
return pool.next(for: .basic).flatMap { connection in
return connection.executeCodable(
ListCollections(),
namespace: self.commandNamespace,
in: self.transaction,
sessionId: connection.implicitSessionId
).flatMap { reply in
do {
let response = try MongoCursorResponse(reply: reply)
let cursor = MongoCursor(
reply: response.cursor,
in: .administrativeCommand,
connection: connection,
session: connection.implicitSession,
transaction: self.transaction
)
return cursor.decode(CollectionDescription.self).allResults().map { descriptions in
return descriptions.map { description in
return MongoCollection(named: description.name, in: self)
}
}
} catch {
return connection.eventLoop.makeFailedFuture(error)
}
}
}._mongoHop(to: hoppedEventLoop)
}
}
extension EventLoopFuture {
internal func _mongoHop(to eventLoop: EventLoop?) -> EventLoopFuture<Value> {
guard let eventLoop = eventLoop else {
return self
}
return self.hop(to: eventLoop)
}
}
internal extension MongoConnectionPoolRequest {
static var writable: MongoConnectionPoolRequest {
return MongoConnectionPoolRequest(writable: true)
}
static var basic: MongoConnectionPoolRequest {
return MongoConnectionPoolRequest(writable: false)
}
}
internal extension Decodable {
init(reply: MongoServerReply) throws {
self = try BSONDecoder().decode(Self.self, from: reply.getDocument())
}
}
extension EventLoopFuture where Value == MongoServerReply {
public func decodeReply<D: Decodable>(_ type: D.Type) -> EventLoopFuture<D> {
return flatMapThrowing { reply in
do {
let ok = try OK(reply: reply)
if ok.isSuccessful {
return try D(reply: reply)
} else {
throw try MongoGenericErrorReply(reply: reply)
}
} catch {
throw try MongoGenericErrorReply(reply: reply)
}
}
}
}
extension EventLoopFuture where Value == Optional<Document> {
public func decode<D: Decodable>(_ type: D.Type) -> EventLoopFuture<D?> {
return flatMapThrowing { document in
if let document = document {
return try BSONDecoder().decode(type, from: document)
} else {
return nil
}
}
}
}
extension MongoConnectionPool {
public subscript(db: String) -> MongoDatabase {
return MongoDatabase(named: db, pool: self)
}
public func listDatabases() -> EventLoopFuture<[MongoDatabase]> {
return next(for: .basic).flatMap { connection in
return connection.executeCodable(
ListDatabases(),
namespace: .administrativeCommand,
sessionId: connection.implicitSessionId
).flatMapThrowing { reply in
let response = try ListDatabasesResponse(reply: reply)
return response.databases.map { description in
return MongoDatabase(named: description.name, pool: self)
}
}
}
}
}
| mit | b3f8db7e35a71c74dc989775f9f8170c | 40.720461 | 194 | 0.648546 | 5.058351 | false | false | false | false |
MostafaTaghipour/mtpFontManager | Example/mtpFontManager/AppDelegate.swift | 1 | 1706 | //
// AppDelegate.swift
// mtpFontManager
//
// Created by [email protected] on 09/22/2017.
// Copyright (c) 2017 [email protected]. All rights reserved.
//
import FontBlaster
import mtpFontManager
import UIKit
let persistFontKey = "font"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
lazy var exo: AppFont = {
let font = AppFont(
id: 1,
familyName: "Exo",
defaultFont: "Exo-Regular",
ultraLight: "Exo-Thin",
thin: "Exo-ExtraLight",
light: "Exo-Light",
regular: "Exo-Regular",
medium: "Exo-Medium",
semibold: "Exo-Semibold",
bold: "Exo-Bold",
heavy: "Exo-ExtraBold",
black: "Exo-Black"
)
return font
}()
lazy var taviraj: AppFont = {
let font = AppFont(plist: "taviraj")
return font
}()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// load fonts in main bundle
FontBlaster.blast { fonts in
print(fonts)
}
UIFont.printAllFonts()
if let savedFont = UserDefaults.standard.string(forKey: persistFontKey) {
switch savedFont {
case exo.familyName:
FontManager.shared.currentFont = exo
break
case taviraj.familyName:
FontManager.shared.currentFont = taviraj
break
default:
break
}
}
return true
}
}
| mit | b7ec658e1aae832a3ca75f3a63571617 | 24.848485 | 145 | 0.559203 | 4.297229 | false | false | false | false |
mtzaquia/MTZTableViewManager | Example/Example/Converters&Maskers/AgeConverter.swift | 1 | 1787 | //
// AgeConverter.swift
// MTZTableManager
//
// Copyright (c) 2017 Mauricio Tremea Zaquia (@mtzaquia)
//
// 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 MTZTableViewManager
class AgeConverter: MTZFormConverter {
override func fromFieldValue(_ fieldValue: Any) -> Any? {
let fieldValue = fieldValue as? String ?? ""
if fieldValue.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil {
return Int(fieldValue) ?? 0
}
return nil
}
override func toFieldValue(_ complexValue: Any) -> Any? {
let complexValue = complexValue as? Int ?? 0
if (complexValue == 0) {
return ""
}
return NSString(format: "%d", complexValue)
}
}
| mit | 14e29a9f4b290935183148925e333497 | 37.021277 | 90 | 0.709569 | 4.456359 | false | false | false | false |
EvsenevDev/SmartReceiptsiOS | SmartReceipts/Models/Category/CategoryColumns.swift | 2 | 3219 | //
// CategoryColumns.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 13/01/2018.
// Copyright © 2018 Will Baumann. All rights reserved.
//
import Foundation
class CategoryColumn: Column {
class func allColumns() -> [CategoryColumn] {
return [
CategoryNameColumn(type: 0, name: WBPreferences.localized(key: "category_name_field")),
CategoryCodeColumn(type: 1, name: WBPreferences.localized(key: "category_code_field")),
CategoryPriceColumn(type: 2, name: WBPreferences.localized(key: "category_price_field")),
CategoryTaxColumn(type: 3, name: WBPreferences.localized(key: "category_tax_field")),
CategoryPriceExchnagedColumn(type: 4, name: WBPreferences.localized(key: "category_price_exchanged_field"))
]
}
override func value(fromRow row: Any!, forCSV: Bool) -> String! {
if let receipt = row as? WBReceipt {
return valueFrom(receipts: [receipt])
} else if let categorizedReceipts = row as? (_: WBCategory, receipts: [WBReceipt]) {
return valueFrom(receipts: categorizedReceipts.receipts)
}
return ""
}
func valueFrom(receipts: [WBReceipt]) -> String {
ABSTRACT_METHOD()
return ""
}
}
//MARK: Categories
class CategoryNameColumn: CategoryColumn {
override func valueFrom(receipts: [WBReceipt]) -> String {
guard let firstReceipt = receipts.first else { return "" }
return "\(firstReceipt.category?.name ?? "") [\(receipts.count)]"
}
}
class CategoryCodeColumn: CategoryColumn {
override func valueFrom(receipts: [WBReceipt]) -> String {
guard let firstReceipt = receipts.first else { return "" }
return firstReceipt.category?.code ?? ""
}
}
class CategoryPriceColumn: CategoryColumn {
override func valueFrom(receipts: [WBReceipt]) -> String {
let total = PricesCollection()
for rec in receipts {
total.addPrice(rec.price())
}
return total.currencyFormattedTotalPrice()
}
}
class CategoryTaxColumn: CategoryColumn {
override func valueFrom(receipts: [WBReceipt]) -> String {
let total = PricesCollection()
for rec in receipts {
total.addPrice(rec.tax())
}
var result = total.currencyFormattedTotalPrice()
if result.isEmpty { result = Price(amount: 0, currency: receipts.first!.trip.defaultCurrency).currencyFormattedPrice() }
return result
}
}
class CategoryPriceExchnagedColumn: CategoryColumn {
override func valueFrom(receipts: [WBReceipt]) -> String {
let otherCollection = PricesCollection()
var total = NSDecimalNumber.zero
for rec in receipts {
if let exchangedPrice = rec.exchangedPrice() {
total = total.adding(exchangedPrice.amount)
} else {
otherCollection.addPrice(rec.price())
}
}
let totalPrice = Price(amount: total, currency: receipts.first!.trip.defaultCurrency)
return "\(totalPrice.currencyFormattedPrice()); \(otherCollection.currencyFormattedTotalPrice())"
}
}
| agpl-3.0 | 37831ccdf829fe71d9d40a61943fd653 | 32.873684 | 128 | 0.637663 | 4.372283 | false | false | false | false |
contentful/contentful.swift | Tests/ContentfulTests/QueryTests.swift | 1 | 46917 | //
// QueryTests.swift
// Contentful
//
// Created by JP Wright on 06/03/2017.
// Copyright © 2017 Contentful GmbH. All rights reserved.
//
@testable import Contentful
import XCTest
import DVR
final class QueryTests: XCTestCase {
static let client: Client = {
let contentTypeClasses: [EntryDecodable.Type] = [
Cat.self,
Dog.self,
City.self
]
return TestClientFactory.testClient(withCassetteNamed: "QueryTests", contentTypeClasses: contentTypeClasses)
}()
override class func setUp() {
super.setUp()
(client.urlSession as? DVR.Session)?.beginRecording()
}
override class func tearDown() {
super.tearDown()
(client.urlSession as? DVR.Session)?.endRecording()
}
func testQueryConstruction() {
let expectedQueryParameters: [String: String] = [
"content_type": "<content_type_id>",
"fields.<field_name>.sys.id": "<entry_id>",
"include": String(
2)
]
let query = Query.where(contentTypeId: "<content_type_id>")
.where(valueAtKeyPath: "fields.<field_name>.sys.id", .equals("<entry_id>"))
.include(2)
XCTAssertEqual(query.parameters, expectedQueryParameters)
}
func testQueryReturningClientDefinedModel() {
let selections = ["bestFriend", "color", "name"]
let expectation = self.expectation(description: "Select operator expectation")
let query = try! QueryOn<Cat>.select(fieldsNamed: selections)
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
guard let cat = cats.first(where: { $0.id == "nyancat" }) else {
XCTFail("Couldn't find Nyan Cat.")
return
}
XCTAssertNotNil(cat.color)
XCTAssertEqual(cat.name, "Nyan Cat")
// Test links
XCTAssertEqual(cat.bestFriend?.name, "Happy Cat")
// Test uniqueness in memory.
XCTAssert(cat === cat.bestFriend?.bestFriend)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testQueryReturningClientDefinedModelUsingFields() {
let expectation = self.expectation(description: "Select operator expectation")
QueryTests.client.fetchArray(of: Cat.self, matching: .select(fieldsNamed: [.bestFriend, .color, .name])) { (result: Result<HomogeneousArrayResponse<Cat>, Error>) in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
guard let cat = cats.first(where: { $0.id == "happycat" }) else {
XCTFail("Couldn't find Happy Cat.")
return
}
XCTAssertNotNil(cat.color)
XCTAssertEqual(cat.name, "Happy Cat")
// Test links
XCTAssertEqual(cat.bestFriend?.name, "Nyan Cat")
// Test uniqueness in memory.
XCTAssert(cat === cat.bestFriend?.bestFriend)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testQueryReturningHeterogeneousArray() {
let expectation = self.expectation(description: "Fetch all entries expectation")
let query = try! Query.order(by: Ordering(sys: .updatedAt))
QueryTests.client.fetchArray(matching: query) { (result: Result<HeterogeneousArrayResponse, Error>) in
switch result {
case .success(let response):
let entries = response.items
// We didn't decode the "human" content type so only 9 decoded entries should be returned instead of 10
XCTAssertEqual(entries.count, 9)
if let cat = entries.last as? Cat, let bestFriend = cat.bestFriend {
XCTAssertEqual(bestFriend.name, "Nyan Cat")
} else {
XCTFail("The first entry in the heterogenous array should be a cat with a best friend named 'Nyan Cat'")
}
if let dog = entries[3] as? Dog, let image = dog.image {
XCTAssertEqual(dog.description, "Bacon pancakes, makin' bacon pancakes!")
XCTAssertEqual(image.id, "jake")
} else {
XCTFail("The 4th entry in the heterogenous array should be a dog with an image with named 'jake'")
}
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testQueryClientDefinedModelResolvesIncludes() {
let selections = ["image", "name"]
let expectation = self.expectation(description: "Select operator expectation")
let query = try! QueryOn<Dog>.select(fieldsNamed: selections)
try! query.order(by: Ordering(sys: .id))
QueryTests.client.fetchArray(of: Dog.self, matching: query) { (result: Result<HomogeneousArrayResponse<Dog>, Error>) in
switch result {
case .success(let dogsResponse):
let dogs = dogsResponse.items
let doge = dogs.first
XCTAssertEqual(doge?.name, "Doge")
// Test links
XCTAssertNotNil(doge?.image)
XCTAssertEqual(doge?.image?.id, "1x0xpXu4pSGS4OukSyWGUK")
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
// MARK: - Test Query.Operations
func testFetchingEntriesOfContentType() {
let expectation = self.expectation(description: "Equality operator expectation")
let query = Query.where(contentTypeId: "cat")
QueryTests.client.fetchArray(of: Entry.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
for cat in cats {
XCTAssertEqual(cat.sys.contentTypeId, "cat")
}
case .failure:
XCTFail("Should not throw an error")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testEqualityQuery() {
let expectation = self.expectation(description: "Equality operator expectation")
QueryTests.client.fetchArray(of: Cat.self, matching: .where(field: .color, .equals("gray"))) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertEqual(cats.count, 1)
XCTAssertEqual(cats.first?.color, "gray")
case .failure:
XCTFail("Should not throw an error")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testInequalityQuery() {
let expectation = self.expectation(description: "Inequality operator expectation")
let query = QueryOn<Cat>.where(valueAtKeyPath: "fields.color", .doesNotEqual("gray"))
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertGreaterThan(cats.count, 0)
XCTAssertNotEqual(cats.first?.color, "gray")
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testInclusionQuery() {
let expectation = self.expectation(description: "Inclusion query operator expectation")
let query = QueryOn<Cat>.where(valueAtKeyPath: "fields.likes", .includes(["rainbows"]))
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertEqual(cats.count, 1)
XCTAssertEqual(cats.first?.name, "Nyan Cat")
XCTAssertEqual(cats.first?.likes?.count, 2)
XCTAssert(cats.first!.likes!.contains("rainbows"))
XCTAssert(cats.first!.likes!.contains("fish"))
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testExclusionQuery() {
let expectation = self.expectation(description: "Exclusion query operator expectation")
let query = QueryOn<Cat>.where(valueAtKeyPath: "fields.likes", .excludes(["rainbows"]))
try! query.order(by: Ordering(sys: .createdAt))
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertEqual(cats.count, 2)
XCTAssertNotNil(cats.first)
if let happyCat = cats.first {
XCTAssertEqual(happyCat.name, "Happy Cat")
XCTAssertEqual(happyCat.likes?.count, 1)
XCTAssert(happyCat.likes!.contains("cheezburger"))
}
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testMultipleValuesQuery() {
let expectation = self.expectation(description: "Multiple values operator expectation")
let query = QueryOn<Cat>.where(valueAtKeyPath: "fields.likes", .hasAll(["rainbows","fish"]))
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertEqual(cats.count, 1)
XCTAssertEqual(cats.first?.name, "Nyan Cat")
XCTAssertEqual(cats.first?.likes?.count, 2)
XCTAssert(cats.first!.likes!.contains("rainbows"))
XCTAssert(cats.first!.likes!.contains("fish"))
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testExistenceQuery() {
let expectation = self.expectation(description: "Existence operator expectation")
let query = QueryOn<Cat>.where(valueAtKeyPath: "fields.color", .exists(true))
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertGreaterThan(cats.count, 0)
guard let cat = cats.first(where: { $0.id == "happycat" }) else {
XCTFail("Couldn't find Happy Cat.")
return
}
XCTAssertEqual(cat.color, "gray")
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testChainingQueries() {
let expectation = self.expectation(description: "Chained operator expectation")
let query = QueryOn<Cat>.where(valueAtKeyPath: "fields.color", .doesNotEqual("gray"))
query.where(valueAtKeyPath:"fields.lives", .equals("9"))
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertEqual(cats.count, 1)
XCTAssertEqual(cats.first?.lives, 9)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testChainingQueriesWithUntypedQuery() {
let expectation = self.expectation(description: "Chained operator expectation")
let query = Query.where(contentTypeId: "cat")
.where(valueAtKeyPath: "fields.color", .doesNotEqual("gray"))
.where(valueAtKeyPath: "fields.lives", .equals("9"))
QueryTests.client.fetchArray(of: Entry.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertEqual(cats.count, 1)
XCTAssertEqual(cats.first?.fields["lives"] as? Int, 9)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testQueryAssetsWithSelect() {
let expectation = self.expectation(description: "Equality operator expectation")
let query = AssetQuery.where(sys: .id, .equals("1x0xpXu4pSGS4OukSyWGUK"))
try! query.select(fieldsNamed: ["title"])
QueryTests.client.fetchArray(of: Asset.self, matching: query) { result in
switch result {
case .success(let assetsResponse):
let assets = assetsResponse.items
XCTAssertEqual(assets.count, 1)
XCTAssertEqual(assets.first?.sys.id, "1x0xpXu4pSGS4OukSyWGUK")
XCTAssertEqual(assets.first?.fields["title"] as? String, "doge")
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testQueryAssetsWithSelectUsingFields() {
let expectation = self.expectation(description: "Equality operator expectation")
let query = AssetQuery.where(sys: .id, .equals("1x0xpXu4pSGS4OukSyWGUK"))
query.select(fields: [.title])
QueryTests.client.fetchArray(of: Asset.self, matching: query) { result in
switch result {
case .success(let assetsResponse):
let assets = assetsResponse.items
XCTAssertEqual(assets.count, 1)
XCTAssertEqual(assets.first?.sys.id, "1x0xpXu4pSGS4OukSyWGUK")
XCTAssertEqual(assets.first?.fields["title"] as? String, "doge")
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testQueryValidation() {
let fieldNames = ["sys.contentType.sys.id"]
do {
let _ = try QueryOn<Dog>.select(fieldsNamed: fieldNames)
XCTFail("Query selection with depth > 2 should throw an error and not reahc here")
} catch let error as QueryError {
XCTAssertNotNil(error.message)
} catch _ {
XCTFail("Should throw a QueryError")
}
}
func testFetchEntriesOfAnyTypeWithRangeSearch() {
let expectation = self.expectation(description: "Range query")
let date = Date.fromComponents(year: 2021, month: 3, day: 20, hour: 0, minute: 0, second: 0)
let query = Query.where(valueAtKeyPath: "sys.updatedAt", .isLessThanOrEqualTo(date))
QueryTests.client.fetchArray(of: Entry.self, matching: query) { result in
switch result {
case .success(let entriesResponse):
let entries = entriesResponse.items
XCTAssertEqual(entries.count, 8)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
// MARK: - Ranges
func testFetchCatsWithRangeSearch() {
let expectation = self.expectation(description: "Range query")
let query = QueryOn<Cat>.where(valueAtKeyPath: "sys.updatedAt", .isLessThanOrEqualTo("2021-03-20T00:00:00Z"))
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertEqual(cats.count, 1)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
// MARK: - Order
func testFetchEntriesInSpecifiedOrder() {
let expectation = self.expectation(description: "Order search")
let query = try! Query.order(by: Ordering(sys: .createdAt))
QueryTests.client.fetchArray(of: Entry.self, matching: query) { result in
switch result {
case .success(let entriesResponse):
let entries = entriesResponse.items
let ids = entries.map { $0.sys.id }
XCTAssertEqual(ids, EntryTests.orderedEntries)
case .failure(let error):
XCTFail("\(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testFetchEntriesInReverseOrder() {
let expectation = self.expectation(description: "Reverese order search")
let query = try! Query.order(by: Ordering("sys.createdAt", inReverse: true))
QueryTests.client.fetchArray(of: Entry.self, matching: query) { result in
switch result {
case .success(let entriesResponse):
let entries = entriesResponse.items
let ids = entries.map { $0.sys.id }
XCTAssertEqual(ids, EntryTests.orderedEntries.reversed())
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
static let orderedCatNames = [ "happycat", "nyancat", "garfield"]
func testFetchEntriesWithTypeInOrder() {
let expectation = self.expectation(description: "Ordered search with content type specified.")
let query = try! QueryOn<Cat>.order(by: Ordering(sys: .createdAt))
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
let ids = cats.map { $0.id }
XCTAssertEqual(cats.count, 3)
XCTAssertEqual(ids, QueryTests.orderedCatNames)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testFetchEntriesOrderedByMultipleAttributes() {
let expectation = self.expectation(description: "Reverese order search")
let query = try! Query.order(by: Ordering("sys.id"), Ordering(sys: .id))
QueryTests.client.fetchArray(of: Entry.self, matching: query) { result in
switch result {
case .success(let entriesResponse):
let entries = entriesResponse.items
let ids = entries.map { $0.sys.id }
XCTAssertEqual(ids, EntryTests.orderedEntriesByMultiple)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
// MARK: - Text search
func testFetchEntriesWithFullTextSearch() {
let expectation = self.expectation(description: "Full text search")
let query = try! QueryOn<Dog>.searching(for: "bacon")
QueryTests.client.fetchArray(of: Dog.self, matching: query) { result in
switch result {
case .success(let dogsResponse):
let dogs = dogsResponse.items
XCTAssertEqual(dogs.count, 1)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testFetchEntriesWithFullTextSearchOnSpecificField() {
let expectation = self.expectation(description: "Full text search on specific field")
let query = QueryOn<Dog>.where(valueAtKeyPath: "fields.description", .matches("bacon"))
QueryTests.client.fetchArray(of: Dog.self, matching: query) { result in
switch result {
case .success(let dogsResponse):
let dogs = dogsResponse.items
XCTAssertEqual(dogs.count, 1)
XCTAssertEqual(dogs.first?.name, "Jake")
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
// MARK: - Location
// FIXME: Add another expectation
func testFetchEntriesWithLocationProximitySearch() {
let expectation = self.expectation(description: "Location proximity search")
let query = QueryOn<City>.where(valueAtKeyPath: "fields.center", .isNear(Location(latitude: 38, longitude: -122)))
QueryTests.client.fetchArray(of: City.self, matching: query) { result in
switch result {
case .success(let citiesResponse):
let cities = citiesResponse.items
XCTAssertEqual(cities.count, 4)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testFetchEntriesWithBoundingBoxLocationsSearch() {
let expectation = self.expectation(description: "Location bounding box")
let bounds = Bounds.box(bottomLeft: Location(latitude: 36, longitude: -124), topRight: Location(latitude: 40, longitude: -120))
let query = QueryOn<City>.where(valueAtKeyPath: "fields.center", .isWithin(bounds))
QueryTests.client.fetchArray(of: City.self, matching: query) { result in
switch result {
case .success(let citiesResponse):
let cities = citiesResponse.items
XCTAssertEqual(cities.count, 1)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
// MARK: - Limits, Skip, Includes
func testIncludeParameter() {
let expectation = self.expectation(description: "Includes param")
let query = Query.include(0)
QueryTests.client.fetchArray(of: Entry.self, matching: query) { result in
switch result {
case .success(let entriesResponse):
let entries = entriesResponse.items
let catEntries = entries.filter { $0.sys.contentTypeId == "cat" }
XCTAssertNotNil(catEntries.first)
// Let's just assert link is unresolved
guard let catEntry = catEntries.first(where: { $0.id == "happycat" }) else {
XCTFail("Couldn't find Happy Cat.")
return
}
if let link = catEntry.fields["image"] as? Link {
switch link {
case .unresolved: XCTAssert(true)
default: XCTFail("link should not be resolved when includes are 0:")
}
} else {
XCTFail("there should be an unresolved link at image field when includes are 0")
}
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testLimitNumberOfEntriesBeingFetched() {
let expectation = self.expectation(description: "Limit results")
let query = Query.limit(to: 5)
QueryTests.client.fetchArray(of: Entry.self, matching: query) { result in
switch result {
case .success(let entriesResponse):
let entries = entriesResponse.items
XCTAssertEqual(entries.count, 5)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testSkipEntriesInAQueryWithOrder() {
let expectation = self.expectation(description: "Skip results")
let query = Query.skip(theFirst: 9)
try! query.order(by: Ordering("sys.createdAt"))
QueryTests.client.fetchArray(of: Entry.self, matching: query) { result in
switch result {
case .success(let entriesResponse):
let entries = entriesResponse.items
XCTAssertEqual(entries.count, 1)
XCTAssertEqual(entries.first?.sys.id, "garfield")
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testSkipEntries() {
let expectation = self.expectation(description: "Skip results")
let query = Query.skip(theFirst: 9)
QueryTests.client.fetchArray(of: Entry.self, matching: query) { result in
switch result {
case .success(let entriesResponse):
let entries = entriesResponse.items
XCTAssertEqual(entriesResponse.skip, 9)
XCTAssertEqual(entries.count, 1)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
// MARK: - Search on References
func testSearchOnReferences() {
let expectation = self.expectation(description: "Search on references")
let linkQuery = LinkQuery<Cat>.where(field: .name, .matches("Happy Cat"))
QueryTests.client.fetchArray(of: Cat.self, matching: .where(linkAtField: .bestFriend, matches: linkQuery)) { result in
switch result {
case .success(let catsWithHappyCatAsBestFriendResponse):
let catsWithHappyCatAsBestFriend = catsWithHappyCatAsBestFriendResponse.items
XCTAssertEqual(catsWithHappyCatAsBestFriend.count, 1)
XCTAssertEqual(catsWithHappyCatAsBestFriend.first?.name, "Nyan Cat")
XCTAssertEqual(catsWithHappyCatAsBestFriend.first?.bestFriend?.name, "Happy Cat")
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testUntypedSearchOnReferences() {
let expectation = self.expectation(description: "Search on references")
let query = Query.where(linkAtFieldNamed: "bestFriend",
onSourceContentTypeWithId: "cat",
hasValueAtKeyPath: "fields.name",
withTargetContentTypeId: "cat",
that: .matches("Happy Cat"))
QueryTests.client.fetchArray(of: Entry.self, matching: query) { result in
switch result {
case .success(let catsWithHappyCatAsBestFriendResponse):
let catsWithHappyCatAsBestFriend = catsWithHappyCatAsBestFriendResponse.items
XCTAssertEqual(catsWithHappyCatAsBestFriend.count, 1)
XCTAssertEqual(catsWithHappyCatAsBestFriend.first?.fields["name"] as? String, "Nyan Cat")
if let happyCatsBestFriend = catsWithHappyCatAsBestFriend.first?.fields.linkedEntry(at: "bestFriend") {
XCTAssertEqual(happyCatsBestFriend.fields.string(at: "name"), "Happy Cat")
} else {
XCTFail("Should be able to get linked entry.")
}
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testLinksToEntryWithField() {
let expectation = self.expectation(description: "Search on references")
let query = QueryOn<Cat>.where(linkAtField: .bestFriend, hasTargetId: "happycat")
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsWithHappyCatAsBestFriendResponse):
let catsWithHappyCatAsBestFriend = catsWithHappyCatAsBestFriendResponse.items
XCTAssertEqual(catsWithHappyCatAsBestFriend.count, 1)
XCTAssertEqual(catsWithHappyCatAsBestFriend.first?.name, "Nyan Cat")
XCTAssertEqual(catsWithHappyCatAsBestFriend.first?.bestFriend?.name, "Happy Cat")
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testUnTypedLinksToEntryWithField() {
let expectation = self.expectation(description: "Search on references")
let query = Query.where(linkAtFieldNamed: "bestFriend",
onSourceContentTypeWithId: "cat",
hasTargetId: "happycat")
QueryTests.client.fetchArray(of: Entry.self, matching: query) { result in
switch result {
case .success(let catsWithHappyCatAsBestFriendResponse):
let catsWithHappyCatAsBestFriend = catsWithHappyCatAsBestFriendResponse.items
XCTAssertEqual(catsWithHappyCatAsBestFriend.count, 1)
XCTAssertEqual(catsWithHappyCatAsBestFriend.first?.fields["name"] as? String, "Nyan Cat")
if let happyCatsBestFriend = catsWithHappyCatAsBestFriend.first?.fields.linkedEntry(at: "bestFriend") {
XCTAssertEqual(happyCatsBestFriend.fields.string(at: "name"), "Happy Cat")
} else {
XCTFail("Should be able to get linked entry.")
}
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testLinksToEntryWithSysId() {
let expectation = self.expectation(description: "Search on sys id")
let constraints = LinkQuery<Cat>.where(sys: .id, .matches("happycat"))
let query = QueryOn<Cat>.where(linkAtField: .bestFriend, matches: constraints)
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertEqual(cats.count, 1)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
// MARK: - Asset mimetype
func testFilterAssetsByMIMETypeGroup() {
let expectation = self.expectation(description: "Fetch image from asset network expectation")
let query = AssetQuery.where(mimetypeGroup: .image)
QueryTests.client.fetchArray(of: Asset.self, matching: query) { result in
switch result {
case .success(let assetsResponse):
let assets = assetsResponse.items
XCTAssertEqual(assets.count, 4)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testQueryReturningClientDefinedModelWithMetadata() {
let expectation = self.expectation(description: "Select operator expectation")
QueryTests.client.fetchArray(of: Cat.self, matching: .where(field: .name, .equals("Nyan Cat"))) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
guard let cat = cats.first(where: { $0.id == "nyancat" }) else {
XCTFail("Couldn't find Nyan Cat.")
return
}
guard let tags = cat.metadata?.tags else {
XCTAssert(false, "Tags array could not be parsed")
return
}
XCTAssertEqual(tags.count, 0)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testQueryReturningClientDefinedModelWithMetadataAndTags() {
let expectation = self.expectation(description: "Select operator expectation")
QueryTests.client.fetchArray(of: Cat.self, matching: .where(field: .name, .equals("Garfield"))) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
guard let cat = cats.first(where: { $0.id == "garfield" }) else {
XCTFail("Couldn't find Garfield.")
return
}
guard let tags = cat.metadata?.tags else {
XCTAssert(false, "Tags array could not be parsed")
return
}
XCTAssertEqual(tags.count, 1)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testTagsExistence() {
let expectation = self.expectation(description: "Existence operator expectation")
let query = QueryOn<Cat>.where(valueAtKeyPath: "metadata.tags", .exists(true))
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertEqual(cats.count, 1)
guard let cat = cats.first(where: { $0.id == "garfield" }) else {
XCTFail("Couldn't find Garfield.")
return
}
guard let tags = cat.metadata?.tags else {
XCTFail("Could not find tags")
return
}
XCTAssertTrue(tags.count > 0)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testTagsNotExistence() {
let expectation = self.expectation(description: "Existence operator expectation")
let query = QueryOn<Cat>.where(valueAtKeyPath: "metadata.tags", .exists(false))
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertEqual(cats.count, 2)
for cat in cats {
XCTAssertTrue(cat.metadata?.tags.count == .some(0))
}
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testFetchEntriesContainingSpecificTags() {
let expectation = self.expectation(description: "Existence operator expectation")
let query = QueryOn<Cat>.where(valueAtKeyPath: "metadata.tags.sys.id", .hasAll(["garfieldTag"]))
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertEqual(cats.count, 1)
guard let garfield = cats.first(where: { $0.id == "garfield" }) else {
XCTFail("Couldn't find Garfield.")
return
}
let allTagsIds = garfield.metadata?.tags.map { $0.id } ?? []
guard !allTagsIds.isEmpty else {
XCTFail("Tags array should not be empty")
return
}
XCTAssertTrue(allTagsIds.contains("garfieldTag"))
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testFetchEntriesContainingSpecificTags2() {
let expectation = self.expectation(description: "Existence operator expectation")
let query = QueryOn<Cat>.where(valueAtKeyPath: "metadata.tags.sys.id", .includes(["garfieldTag"]))
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertEqual(cats.count, 1)
guard let garfield = cats.first(where: { $0.id == "garfield" }) else {
XCTFail("Couldn't find Garfield.")
return
}
let allTagsIds = garfield.metadata?.tags.map { $0.id } ?? []
guard !allTagsIds.isEmpty else {
XCTFail("Tags array should not be empty")
return
}
XCTAssertTrue(allTagsIds.contains("garfieldTag"))
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testTagsExistence2() {
let expectation = self.expectation(description: "Existence operator expectation")
let query = QueryOn<Cat>.where(metadata: .tags, .exists(true))
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertEqual(cats.count, 1)
guard let cat = cats.first(where: { $0.id == "garfield" }) else {
XCTFail("Couldn't find Garfield.")
return
}
guard let tags = cat.metadata?.tags else {
XCTFail("Could not find tags")
return
}
XCTAssertTrue(tags.count > 0)
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testTagsNotExistence2() {
let expectation = self.expectation(description: "Existence operator expectation")
let query = QueryOn<Cat>.where(metadata: .tags, .exists(false))
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertEqual(cats.count, 2)
for cat in cats {
XCTAssertTrue(cat.metadata?.tags.count == .some(0))
}
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testFetchEntriesContainingSpecificTags3() {
let expectation = self.expectation(description: "Existence operator expectation")
let query = QueryOn<Cat>.where(metadataTagsIds: .hasAll(["garfieldTag"]))
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertEqual(cats.count, 1)
guard let garfield = cats.first(where: { $0.id == "garfield" }) else {
XCTFail("Couldn't find Garfield.")
return
}
let allTagsIds = garfield.metadata?.tags.map { $0.id } ?? []
guard !allTagsIds.isEmpty else {
XCTFail("Tags array should not be empty")
return
}
XCTAssertTrue(allTagsIds.contains("garfieldTag"))
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testFetchEntriesContainingSpecificTags4() {
let expectation = self.expectation(description: "Existence operator expectation")
let query = QueryOn<Cat>.where(metadataTagsIds: .includes(["garfieldTag"]))
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertEqual(cats.count, 1)
guard let garfield = cats.first(where: { $0.id == "garfield" }) else {
XCTFail("Couldn't find Garfield.")
return
}
let allTagsIds = garfield.metadata?.tags.map { $0.id } ?? []
guard !allTagsIds.isEmpty else {
XCTFail("Tags array should not be empty")
return
}
XCTAssertTrue(allTagsIds.contains("garfieldTag"))
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testFetchEntriesContainingSpecificTagsChaining() {
let expectation = self.expectation(description: "Existence operator expectation")
let query = QueryOn<Cat>.where(field: .name, .includes(["Garfield"]))
.where(metadataTagsIds: .hasAll(["garfieldTag"]))
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertEqual(cats.count, 1)
guard let garfield = cats.first(where: { $0.id == "garfield" }) else {
XCTFail("Couldn't find Garfield.")
return
}
let allTagsIds = garfield.metadata?.tags.map { $0.id } ?? []
guard !allTagsIds.isEmpty else {
XCTFail("Tags array should not be empty")
return
}
XCTAssertTrue(allTagsIds.contains("garfieldTag"))
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
func testFetchEntriesContainingSpecificTags2Chaining() {
let expectation = self.expectation(description: "Existence operator expectation")
let query = QueryOn<Cat>.where(field: .name, .includes(["Garfield"]))
.where(metadataTagsIds: .includes(["garfieldTag"]))
QueryTests.client.fetchArray(of: Cat.self, matching: query) { result in
switch result {
case .success(let catsResponse):
let cats = catsResponse.items
XCTAssertEqual(cats.count, 1)
guard let garfield = cats.first(where: { $0.id == "garfield" }) else {
XCTFail("Couldn't find Garfield.")
return
}
let allTagsIds = garfield.metadata?.tags.map { $0.id } ?? []
guard !allTagsIds.isEmpty else {
XCTFail("Tags array should not be empty")
return
}
XCTAssertTrue(allTagsIds.contains("garfieldTag"))
case .failure(let error):
XCTFail("Should not throw an error \(error)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
}
}
| mit | a73dfa63a621a2a2b7b1bbcd123893f7 | 37.019449 | 172 | 0.570658 | 4.821788 | false | true | false | false |
hanhailong/practice-swift | Multitasking/Handling Network Connections in Background/Handling Network Connections in Background/AppDelegate.swift | 2 | 1542 | //
// AppDelegate.swift
// Handling Network Connections in Background
//
// Created by Domenico Solazzo on 14/05/15.
// License MIT
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
let dispatchQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(dispatchQueue, {
/* Replace this URL with the URL of a file that is
rather big in size */
let urlAsString = "http://www.apple.com"
let url = NSURL(string: urlAsString)
let urlRequest = NSURLRequest(URL: url!)
let queue = NSOperationQueue()
var error: NSError?
let data = NSURLConnection.sendSynchronousRequest(urlRequest,
returningResponse: nil,
error: &error)
if data != nil && error == nil{
/* Date did come back */
}
else if data!.length == 0 && error == nil{
/* No data came back */
}
else if error != nil{
/* Error happened. Make sure you handle this properly */
}
})
return true
}
}
| mit | b46cd2c1fd508bf17c313036c303ea0b | 30.469388 | 87 | 0.508431 | 5.753731 | false | false | false | false |
icylydia/PlayWithLeetCode | 199. Binary Tree Right Side View/solution.swift | 1 | 842 | /**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class Solution {
var ans = [Int]()
func rightSideView(root: TreeNode?) -> [Int] {
ans = [Int]()
travel(root, depth: 1)
return ans
}
func travel(root: TreeNode?, depth: Int) {
if let root = root {
if ans.count >= depth {
ans[depth - 1] = root.val
} else {
ans.append(root.val)
}
travel(root.left, depth: depth + 1)
travel(root.right, depth: depth + 1)
} else {
return
}
}
}
| mit | 2a231927be1a5bb239d1f14d7456372d | 23.764706 | 50 | 0.467933 | 3.758929 | false | false | false | false |
Pacific3/PUIKit | PUIKit/Extensions/UIImage.swift | 1 | 1984 |
public typealias Image = UIImage
extension Image {
public class func p_fromImageNameConvertible<I: ImageNameConvertible>(imageNameConvertible: I) -> Image? {
return Image(named: imageNameConvertible.imageName, inBundle: imageNameConvertible.bundle, compatibleWithTraitCollection: nil)
}
public class func p_imageWithColor(color: Color) -> Image {
let rect = CGRectMake(0, 0, 1, 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context!, color.CGColor)
CGContextFillRect(context!, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
public class func p_imageWithColor<C: ColorConvertible>(color: C) -> Image {
return p_imageWithColor(color.color())
}
public class func p_roundedImageWithColor(color: Color, size: CGSize) -> Image {
let circleBezierPath = UIBezierPath(rect: CGRectMake(0, 0, size.width, size.height))
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context!, color.CGColor)
circleBezierPath.fill()
let bezierImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return bezierImage!
}
public class func p_roundedImageWithColor<C: ColorConvertible>(color: C, size: CGSize) -> Image {
return p_roundedImageWithColor(color.color(), size: size)
}
public class func p_roundedImageWithColor(color: Color) -> Image {
return p_roundedImageWithColor(color, size: CGSizeMake(1, 1))
}
public class func p_roundedImageWithColor<C: ColorConvertible>(color: C) -> Image {
return p_roundedImageWithColor(color, size: CGSizeMake(1, 1))
}
}
| mit | 9474ba19fc2a384824c90c0a9c95aaa6 | 35.072727 | 134 | 0.668347 | 5.347709 | false | false | false | false |
snoms/FinalProject | Trip/Pods/PXGoogleDirections/PXGoogleDirections/PXGoogleDirectionsRoute.swift | 4 | 4888 | //
// PXGoogleDirectionsRoute.swift
// PXGoogleDirections
//
// Created by Romain on 04/03/2015.
// Copyright (c) 2015 RLT. All rights reserved.
//
import Foundation
import GoogleMaps
/// A route computed by the Google Directions API, following a directions request. A route consists of nested legs and steps.
public class PXGoogleDirectionsRoute: NSObject {
/// Short textual description for the route, suitable for naming and disambiguating the route from alternatives
public var summary: String?
/// Array which contains information about a leg of the route, between two locations within the given route (a separate leg will be present for each waypoint or destination specified: a route with no waypoints will contain exactly one leg within the legs array) ; each leg consists of a series of steps
public var legs: [PXGoogleDirectionsRouteLeg] = [PXGoogleDirectionsRouteLeg]()
/// Array indicating the order of any waypoints in the calculated route (waypoints may be reordered if the request was passed optimize:true within its waypoints parameter)
public var waypointsOrder: [Int] = [Int]()
/// Holds an encoded polyline representation of the route (this polyline is an approximate/smoothed path of the resulting directions)
public var overviewPolyline: String?
/// Viewport bounding box of the `overviewPolyline`
public var bounds: GMSCoordinateBounds?
/// Copyrights text to be displayed for this route
public var copyrights: String?
/// Array of warnings to be displayed when showing these directions
public var warnings: [String] = [String]()
/// Contains the total fare (that is, the total ticket costs) on this route (only valid for transit requests and routes where fare information is available for all transit legs)
public var fare: PXGoogleDirectionsRouteFare?
/// Returns the corresponding `GMSPath` object associated with this route
public var path: GMSPath? {
if let op = overviewPolyline {
return GMSPath(fromEncodedPath: op)
} else {
return nil
}
}
/**
Draws the route on the specified Google Maps map view.
- parameter map: A `GMSMapView` object on which the route should be drawn
- parameter strokeColor: The optional route stroke color
- parameter strokeWidth: The optional route stroke width
- returns: The resulting `GMSPolyline` object that was drawn to the map
*/
public func drawOnMap(map: GMSMapView, strokeColor: UIColor = UIColor.redColor(), strokeWidth: Float = 2.0) -> GMSPolyline? {
let polyline: GMSPolyline? = nil
if let p = path {
let polyline = GMSPolyline(path: p)
polyline.strokeColor = strokeColor
polyline.strokeWidth = CGFloat(strokeWidth)
polyline.map = map
}
return polyline
}
/**
Draws a marker representing the origin of the route on the specified Google Maps map view.
- parameter map: A `GMSMapView` object on which the marker should be drawn
- parameter title: An optional marker title
- parameter color: An optional marker color
- parameter opacity: An optional marker specific opacity
- parameter flat: An optional indicator to flatten the marker
- returns: The resulting `GMSMarker` object that was drawn to the map
*/
public func drawOriginMarkerOnMap(map: GMSMapView, title: String = "", color: UIColor = UIColor.redColor(), opacity: Float = 1.0, flat: Bool = false) -> GMSMarker? {
var marker: GMSMarker?
if let p = path {
if p.count() > 1 {
marker = drawMarkerWithCoordinates(p.coordinateAtIndex(0), onMap: map, title: title, color: color, opacity: opacity, flat: flat)
}
}
return marker
}
/**
Draws a marker representing the destination of the route on the specified Google Maps map view.
- parameter map: A `GMSMapView` object on which the marker should be drawn
- parameter title: An optional marker title
- parameter color: An optional marker color
- parameter opacity: An optional marker specific opacity
- parameter flat: An optional indicator to flatten the marker
- returns: The resulting `GMSMarker` object that was drawn to the map
*/
public func drawDestinationMarkerOnMap(map: GMSMapView, title: String = "", color: UIColor = UIColor.redColor(), opacity: Float = 1.0, flat: Bool = false) -> GMSMarker? {
var marker: GMSMarker?
if let p = path {
if p.count() > 1 {
marker = drawMarkerWithCoordinates(p.coordinateAtIndex(p.count() - 1), onMap: map, title: title, color: color, opacity: opacity, flat: flat)
}
}
return marker
}
// MARK: Private functions
private func drawMarkerWithCoordinates(coordinates: CLLocationCoordinate2D, onMap map: GMSMapView, title: String = "", color: UIColor = UIColor.redColor(), opacity: Float = 1.0, flat: Bool = false) -> GMSMarker {
let marker = GMSMarker(position: coordinates)
marker.title = title
marker.icon = GMSMarker.markerImageWithColor(color)
marker.opacity = opacity
marker.flat = flat
marker.map = map
return marker
}
}
| mit | 55b6d4437aaeaa032eeb6a1a54d99f29 | 43.844037 | 303 | 0.746318 | 4.059801 | false | false | false | false |
marknote/GoTao | GoTao/GoTao/Game/GobanView.swift | 1 | 4748 |
/**
*
* Copyright (c) 2015, MarkNote. (MIT Licensed)
* https://github.com/marknote/GoTao
*/
import UIKit
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
class GobanView: UIView {
var moves:[Move]?
override func draw(_ rect: CGRect) {
let ctx = UIGraphicsGetCurrentContext()
let rec = ctx?.boundingBoxOfClipPath
let w = rec?.size.width;
//back ground image
let background = UIImage(named:"board_back")
ctx?.draw(background!.cgImage!, in: rec!)
let space = w! / 20.0
drawLines(ctx!,space:space,w:w!)
drawDots(ctx!,space:space)
if (moves != nil && moves?.count > 0) {
drawMoves(ctx!, stoneSize: space)
}
}
func drawLines(_ ctx:CGContext,space:CGFloat, w:CGFloat){
ctx.setStrokeColor(red: 0, green: 0, blue: 0, alpha: 1)
ctx.setLineWidth(0.4)
ctx.beginPath()
for i in 0...18
{
ctx.move(to: CGPoint(x: (CGFloat(i + 1))*space, y: space))
ctx.addLine(to: CGPoint(x: (CGFloat(i + 1))*space, y: w - space))
ctx.strokePath()
}
for i in 0...18
{
ctx.move(to: CGPoint(x: space, y: (CGFloat(i + 1))*space));
ctx.addLine(to: CGPoint(x: w - space, y: (CGFloat(i + 1))*space));
ctx.strokePath();
}
}
func drawDots(_ ctx:CGContext,space:CGFloat){
for i in 0...2 {
for j in 0...2 {
ctx.beginPath();
let frame = CGRect(x:CGFloat(1 + 3 + 6*i) * space - 0.5 * space,
y:CGFloat(1 + 3 + 6*j) * space - 0.5 * space,
width:space,
height:space)
ctx.addEllipse(in:frame)
ctx.strokePath();
}
}
}
func drawMoves(_ ctx:CGContext,stoneSize:CGFloat ){
// chess
let imgBlack = UIImage(named: "Black.png")
let imgWhite = UIImage(named: "White.png")
let count = moves?.count
let font = UIFont(name: "Helvetica Bold", size: 8.0)
let textColor = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.8)
let textFontAttributes = [
NSAttributedString.Key.font : font!,
NSAttributedString.Key.foregroundColor: textColor
]
for i in 0..<count! {
let move = moves![i]
if move.isDead {
continue
}
let imageRect = CGRect( x: (CGFloat(move.location.x) + 0.5)*stoneSize,
y: (CGFloat(move.location.y) + 0.5)*stoneSize,
width: stoneSize,
height: stoneSize);
if move.type == .white {
ctx.draw((imgWhite?.cgImage)!, in: imageRect)
} else {
ctx.draw((imgBlack?.cgImage)!, in: imageRect)
}
if move.groupName.count > 0 {
ctx.setStrokeColor(red: 1, green: 0, blue: 0, alpha: 1)
let p = CGPoint(x: (CGFloat(move.location.x) + 0.5)*stoneSize,
y: (CGFloat(move.location.y) + 0.5)*stoneSize);
(move.groupName as NSString).draw(at: p, withAttributes:textFontAttributes)
}
}
if count > 0
{
let move = moves![count! - 1]
ctx.setLineWidth(1.8)
ctx.setStrokeColor(red: 0, green: 1, blue: 0, alpha: 1)
ctx.beginPath()
let frame = CGRect(x:CGFloat(move.location.x) * stoneSize + 0.5 * stoneSize,
y:CGFloat(move.location.y) * stoneSize + 0.5 * stoneSize,
width:stoneSize,
height:stoneSize)
ctx.addEllipse(in:frame)
ctx.strokePath()
}
}
}
| mit | 08556a0cae03a2a34bff7d38452873ad | 31.081081 | 91 | 0.487574 | 4.125109 | false | false | false | false |
almazrafi/Metatron | Sources/Tools/Extensions.swift | 1 | 5477 | //
// Extensions.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// 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
extension String {
// MARK: Instance Properties
func prefix(_ maxLength: Int) -> String {
if self.distance(from: self.startIndex, to: self.endIndex) > maxLength {
return self.substring(to: self.index(self.startIndex, offsetBy: maxLength))
}
return self
}
}
extension Sequence where Iterator.Element == String {
// MARK: Instance Properties
var revised: [String] {
var revised: [String] = []
for string in self {
if !string.isEmpty {
revised.append(string)
}
}
return revised
}
}
extension Array where Element: Equatable {
func lastIndex(of element: Element) -> Array.Index? {
for i in stride(from: self.count - 1, through: 0, by: -1) {
if self[i] == element {
return i
}
}
return nil
}
func firstOccurrence(of target: Array<Element>) -> Array.Index? {
guard (self.count >= target.count) && (target.count != 0) else {
return nil
}
if target.count == 1 {
return self.index(of: target[0])
}
let range = self.count - target.count
var start = 0
if target[0] == target[1] {
repeat {
if self[start + 1] == target[1] {
if self[start] == target[0] {
var status = true
for i in 2..<target.count {
if self[start + i] != target[i] {
status = false
break
}
}
if status {
return start
}
}
start += 1
} else {
start += 2
}
}
while start <= range
} else {
repeat {
if self[start + 1] == target[1] {
if self[start] == target[0] {
var status = true
for i in 2..<target.count {
if self[start + i] != target[i] {
status = false
break
}
}
if status {
return start
}
}
start += 2
} else {
start += 1
}
}
while start <= range
}
return nil
}
func lastOccurrence(of target: Array<Element>) -> Array.Index? {
guard (self.count >= target.count) && (target.count != 0) else {
return nil
}
if target.count == 1 {
return self.lastIndex(of: target[0])
}
var start = self.count - target.count
if target[0] == target[1] {
repeat {
if self[start] == target[0] {
var status = true
for i in 1..<target.count {
if self[start + i] != target[i] {
status = false
break
}
}
if status {
return start
}
start -= 1
} else {
start -= 2
}
}
while start >= 0
} else {
repeat {
if self[start] == target[0] {
var status = true
for i in 1..<target.count {
if self[start + i] != target[i] {
status = false
break
}
}
if status {
return start
}
start -= 2
} else {
start -= 1
}
}
while start >= 0
}
return nil
}
}
| mit | c2fcfec32df20b0eb1a6cb7b925429fa | 26.80203 | 87 | 0.433449 | 5.191469 | false | false | false | false |
gauravnijhara/ZapposCalculator | ZapposCalculator/ViewController.swift | 1 | 19867 | //
// ViewController.swift
// ZapposCalculator
//
// Created by Gaurav Nijhara on 2/6/16.
// Copyright © 2016 Gaurav Nijhara. All rights reserved.
//
import UIKit
enum OpType
{
case ADD ,
SUBSTRACT,
MULTIPLY,
DIVIDE,
PERCENTAGE,
CREATING_FLOAT,
NATURAL_LOG,
LOG_BASE10,
SIN,
SINH,
COS,
COSH,
TAN,
TANH,
POW_UNARY,
POW_BINARY,
POW_10,
POW_E,
FACTORIAL,
E,
PI,
NONE
}
enum Exceptions:ErrorType
{
case DivideByZero,
InfiniteValue,
IllegalOperation
}
class ViewController: UIViewController {
var result:NSMutableString = ""
{
didSet
{
let decimal:Double = result.doubleValue/Double(result.intValue);
if(decimal == 1 || decimal.isNaN)
{
self.mainScreenLabel.text = "\(result.intValue)";
}
else
{
self.mainScreenLabel.text = "\(result.doubleValue)";
}
}
}
var currentNum:NSMutableString = ""
{
didSet
{
self.mainScreenLabel.text = currentNum as String;
}
}
var power:Double?;
var operationStack:[OpType] = [OpType]()
var shouldUpdateResult:Bool = true;
var shouldResetNumber = false;
var shouldEmptyStack:Bool = false;
var prevResult:[NSMutableString] = [NSMutableString]();
@IBOutlet weak var landscapeLabel: UILabel!
//@IBOutlet weak var calculationsLabel: CBAutoScrollLabel!
@IBOutlet weak var mainScreenLabel: DisplayLabel!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated);
currentNum = NSMutableString(string: "0");
operationStack.append(.NONE)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
// MARK: Number Creation
@IBAction func numberPressed(sender: AnyObject) {
if (currentNum.length > 0 && currentNum.substringToIndex(1).compare("0") == .OrderedSame)
{
currentNum.deleteCharactersInRange(NSMakeRange(0,1));
}
currentNum = currentNum.stringByAppendingFormat("%d",sender.tag).mutableCopy() as! NSMutableString;
}
@IBAction func decimalPressed(sender: AnyObject) {
let str:NSString? = currentNum.componentsSeparatedByString(".")[0];
if ((str?.compare((currentNum as String)) == .OrderedSame))
{
currentNum = currentNum.stringByAppendingFormat("%@",".").mutableCopy() as! NSMutableString;
}
operationStack.append(.CREATING_FLOAT)
}
@IBAction func signChangePressed(sender: AnyObject) {
if (currentNum.length > 0 && currentNum.substringToIndex(1).compare("-") == .OrderedSame)
{
currentNum = NSString(string: currentNum.substringFromIndex(1)).mutableCopy() as! NSMutableString
}
else
{
if(currentNum.integerValue != 0)
{
currentNum = NSMutableString(format:"-%@", currentNum);
}
}
}
// MARK: Math Operations
@IBAction func addPressed(sender: AnyObject) {
if (currentNum.length > 0)
{
self.calculateResult(self)
}
if (operationStack.isEmpty || !isBinaryOperator(operationStack[operationStack.count-1]) )
{
operationStack.append(.ADD)
}
else
{
operationStack[operationStack.count-1] = .ADD
}
//self.updateResultOnLabel()
}
@IBAction func substractPressed(sender: AnyObject) {
if (currentNum.length > 0)
{
self.calculateResult(self)
}
if (operationStack.isEmpty || !isBinaryOperator(operationStack[operationStack.count-1]) )
{
operationStack.append(.SUBSTRACT)
}
else
{
operationStack[operationStack.count-1] = .SUBSTRACT
}
}
@IBAction func multiplyPressed(sender: AnyObject) {
if (currentNum.length > 0)
{
self.calculateResult(self)
}
if (operationStack.isEmpty || !isBinaryOperator(operationStack[operationStack.count-1]) )
{
operationStack.append(.MULTIPLY)
}
else
{
operationStack[operationStack.count-1] = .MULTIPLY
}
//self.updateResultOnLabel()
}
@IBAction func dividePressed(sender: AnyObject) {
if (currentNum.length > 0)
{
self.calculateResult(self)
}
if (operationStack.isEmpty || !isBinaryOperator(operationStack[operationStack.count-1]) )
{
operationStack.append(.DIVIDE)
}
else
{
operationStack[operationStack.count-1] = .DIVIDE
}
//self.updateResultOnLabel()
}
@IBAction func modulusPressed(sender: AnyObject) {
operationStack.append(.PERCENTAGE)
self.calculateResult(self)
}
@IBAction func calculateResult(sender: AnyObject) {
do
{
if(sender as! NSObject == self)
{
try self.updateResultOnLabel()
}
else
{
while(!operationStack.isEmpty)
{
try self.updateResultOnLabel();
}
}
}
catch
{
self.clearPressed(self);
self.mainScreenLabel.text = "Error";
}
}
@IBAction func factorialPressed(sender: AnyObject) {
operationStack.append(.FACTORIAL)
self.calculateResult(self)
}
@IBAction func logPressed(sender: AnyObject) {
if(sender.tag == 0)
{
operationStack.append(.NATURAL_LOG)
}
else
{
operationStack.append(.LOG_BASE10)
}
self.calculateResult(sender)
}
@IBAction func tanhPressed(sender: AnyObject) {
operationStack.append(.TANH)
self.calculateResult(self)
}
@IBAction func tanPressed(sender: AnyObject) {
operationStack.append(.TAN)
self.calculateResult(self)
}
@IBAction func coshPressed(sender: AnyObject) {
operationStack.append(.COSH)
self.calculateResult(self)
}
@IBAction func cosPressed(sender: AnyObject) {
operationStack.append(.COS)
self.calculateResult(self)
}
@IBAction func sinPressed(sender: AnyObject) {
operationStack.append(.SIN)
self.calculateResult(self)
}
@IBAction func sinhPressed(sender: AnyObject) {
operationStack.append(.SINH)
self.calculateResult(self)
}
@IBAction func ePressed(sender: AnyObject) {
operationStack.append(.E)
self.calculateResult(self)
}
@IBAction func piPressed(sender: AnyObject) {
operationStack.append(.PI)
self.calculateResult(self)
}
@IBAction func evaluatePower(sender: AnyObject) {
// many cases
power = 0;
switch(sender.tag)
{
case 0:
power = 2;
operationStack.append(.POW_UNARY)
break;
case 1:
power = 3;
operationStack.append(.POW_UNARY)
break;
case 2:
power = -1;
operationStack.append(.POW_UNARY)
break;
case 3:
power = 1/2;
operationStack.append(.POW_UNARY)
break;
case 5:
power = 1/3;
operationStack.append(.POW_UNARY)
break;
case 6:
operationStack.append(.POW_E)
break;
case 8:
operationStack.append(.POW_10)
break;
default:
power = 1;
break;
}
self.calculateResult(sender)
}
@IBAction func evaluatePowerBinary(sender: AnyObject) {
self.calculateResult(sender);
if(sender.tag == 0)
{
power = 1
}
else
{
power = -1
}
operationStack.append(.POW_BINARY)
}
// MARK: Utility
@IBAction func undoPressed(sender: AnyObject) {
if (currentNum.length > 0)
{
currentNum = NSString(string: currentNum.substringToIndex(currentNum.length-1)).mutableCopy() as! NSMutableString
}
}
@IBAction func clearPressed(sender: AnyObject) {
currentNum = NSMutableString(string: "0");
result = NSMutableString(string: "");
operationStack.removeAll();
operationStack.append(.NONE)
}
func updateResultOnLabel() throws
{
let operation:OpType = operationStack.popLast()!
switch (operation)
{
case .ADD:
let res = result.doubleValue + currentNum.doubleValue;
result = NSMutableString(format: "%lf", res)
currentNum.deleteCharactersInRange(NSMakeRange(0, currentNum.length));
break
case .SUBSTRACT:
let res = result.doubleValue - currentNum.doubleValue;
result = NSMutableString(format: "%lf", res)
currentNum.deleteCharactersInRange(NSMakeRange(0, currentNum.length));
break
case .MULTIPLY:
let res = result.doubleValue * currentNum.doubleValue;
result = NSMutableString(format: "%lf", res)
currentNum.deleteCharactersInRange(NSMakeRange(0, currentNum.length));
break
case .DIVIDE:
if currentNum.integerValue == 0
{
throw Exceptions.DivideByZero
}
let res = result.doubleValue / currentNum.doubleValue;
result = NSMutableString(format: "%lf", res)
currentNum.deleteCharactersInRange(NSMakeRange(0, currentNum.length));
break
case .PERCENTAGE:
var res:Double?
if(currentNum.length > 0)
{
if (result.doubleValue != 0.0)
{
res = (currentNum.doubleValue/100)*result.doubleValue;
}
else
{
res = (currentNum.doubleValue/100);
}
}
else
{
res = result.doubleValue/100;
}
let formatter:NSNumberFormatter = NSNumberFormatter();
formatter.numberStyle = .DecimalStyle;
currentNum = NSMutableString(string: (formatter.stringFromNumber(NSNumber(double: res!)))!)
break;
case .NONE:
result = NSMutableString(string: currentNum);
currentNum.deleteCharactersInRange(NSMakeRange(0, currentNum.length));
break
case .CREATING_FLOAT:
let str:NSString? = currentNum.componentsSeparatedByString(".")[1];
if(str?.length > 0)
{
if(operationStack.isEmpty)
{
result = NSMutableString(string: currentNum);
currentNum.deleteCharactersInRange(NSMakeRange(0, currentNum.length));
}
}
else
{
result = NSMutableString(string: "\(currentNum.intValue)")
}
break;
case .SIN:
var res:Double?
if(currentNum.length > 0)
{
res = sinh(currentNum.doubleValue*M_PI/180);
let formatter:NSNumberFormatter = NSNumberFormatter();
formatter.numberStyle = .DecimalStyle;
currentNum = NSMutableString(string: (formatter.stringFromNumber(NSNumber(double: res!)))!)
}
break;
case .SINH:
var res:Double?
if(currentNum.length > 0)
{
res = cos(currentNum.doubleValue*M_PI/180);
let formatter:NSNumberFormatter = NSNumberFormatter();
formatter.numberStyle = .DecimalStyle;
currentNum = NSMutableString(string: (formatter.stringFromNumber(NSNumber(double: res!)))!)
}
break;
case .COS:
var res:Double?
if(currentNum.length > 0)
{
res = cosh(currentNum.doubleValue*M_PI/180);
let formatter:NSNumberFormatter = NSNumberFormatter();
formatter.numberStyle = .DecimalStyle;
currentNum = NSMutableString(string: (formatter.stringFromNumber(NSNumber(double: res!)))!)
}
break;
case .COSH:
var res:Double?
if(currentNum.length > 0)
{
res = sin(currentNum.doubleValue*M_PI/180);
let formatter:NSNumberFormatter = NSNumberFormatter();
formatter.numberStyle = .DecimalStyle;
currentNum = NSMutableString(string: (formatter.stringFromNumber(NSNumber(double: res!)))!)
}
break;
case .TAN:
var res:Double?
if(currentNum.length > 0)
{
res = tan(currentNum.doubleValue*M_PI/180);
let formatter:NSNumberFormatter = NSNumberFormatter();
formatter.numberStyle = .DecimalStyle;
currentNum = NSMutableString(string: (formatter.stringFromNumber(NSNumber(double: res!)))!)
}
break;
case .TANH:
var res:Double?
if(currentNum.length > 0)
{
res = tanh(currentNum.doubleValue*M_PI/180);
let formatter:NSNumberFormatter = NSNumberFormatter();
formatter.numberStyle = .DecimalStyle;
currentNum = NSMutableString(string: (formatter.stringFromNumber(NSNumber(double: res!)))!)
}
break;
case .NATURAL_LOG:
var res:Double?
if(currentNum.length > 0)
{
res = log(currentNum.doubleValue);
let formatter:NSNumberFormatter = NSNumberFormatter();
formatter.numberStyle = .DecimalStyle;
currentNum = NSMutableString(string: (formatter.stringFromNumber(NSNumber(double: res!)))!)
}
break;
case .LOG_BASE10:
var res:Double?
if(currentNum.integerValue != 0)
{
res = log(currentNum.doubleValue)/log(10);
let formatter:NSNumberFormatter = NSNumberFormatter();
formatter.numberStyle = .DecimalStyle;
currentNum = NSMutableString(string: (formatter.stringFromNumber(NSNumber(double: res!)))!)
}
else
{
throw Exceptions.InfiniteValue;
}
break;
case .FACTORIAL:
var res:Double?
if(currentNum.integerValue > 0)
{
res = getFactorial(currentNum.doubleValue);
let formatter:NSNumberFormatter = NSNumberFormatter();
formatter.numberStyle = .DecimalStyle;
currentNum = NSMutableString(string: (formatter.stringFromNumber(NSNumber(double: res!)))!)
}
else
{
throw Exceptions.IllegalOperation;
}
break;
case .POW_UNARY:
var res:Double?
if(currentNum.integerValue >= 0)
{
if (power < 0 && currentNum.integerValue == 0)
{
throw Exceptions.DivideByZero;
}
if(power != 0)
{
res = pow(currentNum.doubleValue,power!);
}
else
{
}
currentNum = NSMutableString(format: "%lf", res!)
}
else
{
throw Exceptions.IllegalOperation
}
break;
case .POW_BINARY:
var res:Double?
if(currentNum.integerValue >= 0)
{
if(power == -1 && currentNum.integerValue == 0)
{
throw Exceptions.DivideByZero;
}
res = pow(result.doubleValue,pow(currentNum.doubleValue,power!));
result = NSMutableString(format: "%lf", res!)
}
else
{
if (currentNum.integerValue < 0)
{
throw Exceptions.IllegalOperation;
}
}
currentNum.deleteCharactersInRange(NSMakeRange(0, currentNum.length));
break;
case .POW_10:
var res:Double?
if(currentNum.length > 0)
{
res = pow(10,currentNum.doubleValue);
}
currentNum = NSMutableString(format: "%lf", res!)
break;
case .POW_E:
var res:Double?
if(currentNum.length > 0)
{
res = pow(M_E,currentNum.doubleValue)
}
currentNum = NSMutableString(format: "%lf", res!)
break;
case .E:
if(currentNum.length > 0)
{
currentNum = NSMutableString(format: "%lf", M_E)
}
break;
case .PI:
if(currentNum.length > 0)
{
currentNum = NSMutableString(format: "%lf", M_PI)
}
break;
default:
break
}
}
func isBinaryOperator( op:OpType) -> Bool
{
return op == .ADD || op == .SUBSTRACT || op == .MULTIPLY || op == .DIVIDE || op == .POW_BINARY
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getFactorial(num:Double) -> Double
{
if(num == 0)
{
return 0.0;
}
else if (num == 1)
{
return 1.0;
}
else
{
return num*getFactorial(num-1);
}
}
}
| mit | 48d68b9fd2ae8f9968c14317cee329dc | 28.257732 | 125 | 0.486761 | 5.211438 | false | false | false | false |
gkye/TheMovieDatabaseSwiftWrapper | Sources/TMDBSwift/OldModels/FindMDB.swift | 1 | 3119 | //
// FindMDB.swift
// MDBSwiftWrapper
//
// Created by George Kye on 2016-03-09.
// Copyright © 2016 George Kye. All rights reserved.
//
import Foundation
public enum ExternalIdTypes: String {
case imdb_id
case freebase_mid
case freebase_id
case tvdb_id
case tvrage_id
case id
}
public class KnownForMovie: DiscoverMovieMDB {
public var media_type: String!
enum CodingKeys: String, CodingKey {
case media_type
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
try super.init(from: decoder)
media_type = try? container.decode(String?.self, forKey: .media_type)
}
}
public class KnownForTV: DiscoverTVMDB {
public var media_type: String!
enum CodingKeys: String, CodingKey {
case media_type
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
try super.init(from: decoder)
media_type = try? container.decode(String?.self, forKey: .media_type)
}
}
public struct PersonResults: Decodable {
public var adult: Bool!
public var id: Int!
public var known_for: (tvShows: [KnownForTV]?, movies: [KnownForMovie]?)
public var name: String!
public var popularity: Double?
public var profile_path: String?
enum CodingKeys: String, CodingKey {
case adult
case id
case known_for
case name
case popularity
case profile_path
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
adult = try? container.decode(Bool?.self, forKey: .adult)
id = try? container.decode(Int?.self, forKey: .id)
name = try? container.decode(String?.self, forKey: .name)
let tv = try? container.decode([KnownForTV]?.self, forKey: .known_for)
let movie = try? container.decode([KnownForMovie]?.self, forKey: .known_for)
popularity = try? container.decode(Double?.self, forKey: .popularity)
profile_path = try? container.decode(String?.self, forKey: .profile_path)
known_for = (tv, movie)
}
}
public struct FindMDB: Decodable {
public var movie_results = [MovieMDB]()
public var person_results: [PersonResults]?
public var tv_results = [TVMDB]()
public var tv_episode_results = [TVEpisodesMDB]()
public var tv_season_results = [TVSeasonsMDB]()
/**
The find method makes it easy to search for objects in our database by an external id. For instance, an IMDB ID. This will search all objects (movies, TV shows and people) and return the results in a single response.
*/
public static func find(id: String, external_source: ExternalIdTypes, completion: @escaping (_ clientReturn: ClientReturn, _ data: FindMDB?) -> Void) {
Client.Find(external_id: id, external_source: external_source.rawValue) { apiReturn in
let data: FindMDB? = apiReturn.decode()
completion(apiReturn, data)
}
}
}
| mit | bcde41d1353c8d08bef2369f9ba97627 | 32.170213 | 221 | 0.662604 | 3.956853 | false | false | false | false |
infobip/mobile-messaging-sdk-ios | Classes/Vendor/Kingsfisher/ImageView+Kingfisher.swift | 1 | 10967 | //
// ImageView+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2018 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.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
// MARK: - Extension methods.
/**
* Set image to use from web.
*/
extension Kingfisher where Base: ImageView {
/**
Set an image with a resource, a placeholder image, options, progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter placeholder: A placeholder image when retrieving the image at URL.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
If `resource` is `nil`, the `placeholder` image will be set and
`completionHandler` will be called with both `error` and `image` being `nil`.
*/
@discardableResult
internal func setImage(with resource: Resource?,
placeholder: Placeholder? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
guard let resource = resource else {
self.placeholder = placeholder
setWebURL(nil)
completionHandler?(nil, nil, .none, nil)
return .empty
}
var options = KingfisherManager.shared.defaultOptions + (options ?? KingfisherEmptyOptionsInfo)
let noImageOrPlaceholderSet = base.image == nil && self.placeholder == nil
if !options.keepCurrentImageWhileLoading || noImageOrPlaceholderSet { // Always set placeholder while there is no image/placehoer yet.
self.placeholder = placeholder
}
let maybeIndicator = indicator
maybeIndicator?.startAnimatingView()
setWebURL(resource.downloadURL)
if base.shouldPreloadAllAnimation() {
options.append(.preloadAllAnimationData)
}
let task = KingfisherManager.shared.retrieveImage(
with: resource,
options: options,
progressBlock: { receivedSize, totalSize in
guard resource.downloadURL == self.webURL else {
return
}
if let progressBlock = progressBlock {
progressBlock(receivedSize, totalSize)
}
},
completionHandler: {[weak base] image, error, cacheType, imageURL in
DispatchQueue.main.safeAsync {
maybeIndicator?.stopAnimatingView()
guard let strongBase = base, imageURL == self.webURL else {
completionHandler?(image, error, cacheType, imageURL)
return
}
self.setImageTask(nil)
guard let image = image else {
completionHandler?(nil, error, cacheType, imageURL)
return
}
guard let transitionItem = options.lastMatchIgnoringAssociatedValue(.transition(.none)),
case .transition(let transition) = transitionItem, ( options.forceTransition || cacheType == .none) else
{
self.placeholder = nil
strongBase.image = image
completionHandler?(image, error, cacheType, imageURL)
return
}
#if !os(macOS)
UIView.transition(with: strongBase, duration: 0.0, options: [],
animations: { maybeIndicator?.stopAnimatingView() },
completion: { _ in
self.placeholder = nil
UIView.transition(with: strongBase, duration: transition.duration,
options: [transition.animationOptions, .allowUserInteraction],
animations: {
// Set image property in the animation.
transition.animations?(strongBase, image)
},
completion: { finished in
transition.completion?(finished)
completionHandler?(image, error, cacheType, imageURL)
})
})
#endif
}
})
setImageTask(task)
return task
}
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
internal func cancelDownloadTask() {
imageTask?.cancel()
}
}
// MARK: - Associated Object
private var lastURLKey: Void?
private var indicatorKey: Void?
private var indicatorTypeKey: Void?
private var placeholderKey: Void?
private var imageTaskKey: Void?
extension Kingfisher where Base: ImageView {
/// Get the image URL binded to this image view.
internal var webURL: URL? {
return objc_getAssociatedObject(base, &lastURLKey) as? URL
}
fileprivate func setWebURL(_ url: URL?) {
objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
/// Holds which indicator type is going to be used.
/// Default is .none, means no indicator will be shown.
internal var indicatorType: IndicatorType {
get {
let indicator = objc_getAssociatedObject(base, &indicatorTypeKey) as? IndicatorType
return indicator ?? .none
}
set {
switch newValue {
case .none:
indicator = nil
case .activity:
indicator = ActivityIndicator()
case .image(let data):
indicator = ImageIndicator(imageData: data)
case .custom(let anIndicator):
indicator = anIndicator
}
objc_setAssociatedObject(base, &indicatorTypeKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// Holds any type that conforms to the protocol `Indicator`.
/// The protocol `Indicator` has a `view` property that will be shown when loading an image.
/// It will be `nil` if `indicatorType` is `.none`.
internal fileprivate(set) var indicator: Indicator? {
get {
guard let box = objc_getAssociatedObject(base, &indicatorKey) as? Box<Indicator> else {
return nil
}
return box.value
}
set {
// Remove previous
if let previousIndicator = indicator {
previousIndicator.view.removeFromSuperview()
}
// Add new
if var newIndicator = newValue {
// Set default indicator frame if the view's frame not set.
if newIndicator.view.frame == .zero {
newIndicator.view.frame = base.frame
}
newIndicator.viewCenter = CGPoint(x: base.bounds.midX, y: base.bounds.midY)
newIndicator.view.isHidden = true
base.addSubview(newIndicator.view)
}
// Save in associated object
// Wrap newValue with Box to workaround an issue that Swift does not recognize
// and casting protocol for associate object correctly. https://github.com/onevcat/Kingfisher/issues/872
objc_setAssociatedObject(base, &indicatorKey, newValue.map(Box.init), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate var imageTask: RetrieveImageTask? {
return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask
}
fileprivate func setImageTask(_ task: RetrieveImageTask?) {
objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
internal fileprivate(set) var placeholder: Placeholder? {
get {
return objc_getAssociatedObject(base, &placeholderKey) as? Placeholder
}
set {
if let previousPlaceholder = placeholder {
previousPlaceholder.remove(from: base)
}
if let newPlaceholder = newValue {
newPlaceholder.add(to: base)
} else {
base.image = nil
}
objc_setAssociatedObject(base, &placeholderKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
@objc extension ImageView {
func shouldPreloadAllAnimation() -> Bool { return true }
}
| apache-2.0 | 21205b9f803d7e526b88b83c1d448448 | 40.69962 | 142 | 0.564876 | 5.839723 | false | false | false | false |
AnRanScheme/magiGlobe | magi/magiGlobe/magiGlobe/Classes/View/Home/View/ARALabel.swift | 1 | 1750 | //
// ARALabel.swift
// swift-magic
//
// Created by 安然 on 17/2/22.
// Copyright © 2017年 安然. All rights reserved.
//
import UIKit
import CoreText
let kRegexHighlightViewTypeURL = "url"
let kRegexHighlightViewTypeAccount = "account"
let kRegexHighlightViewTypeTopic = "topic"
let kRegexHighlightViewTypeEmoji = "emoji"
let URLRegular = "(http|https)://(t.cn/|weibo.com/)+(([a-zA-Z0-9/])*)"
let EmojiRegular = "(\\[\\w+\\])"
//let AccountRegular = "@[\u4e00-\u9fa5a-zA-Z0-9_-]{2,30}"
let TopicRegular = "#[^#]+#"
class ARALabel: UIView {
var text: String?
var textColor: UIColor?
var font: UIFont?
var lineSpace: NSInteger?
var textAlignment: NSTextAlignment?
/*
UIImageView *labelImageView;
UIImageView *highlightImageView;
BOOL highlighting;
BOOL btnLoaded;
BOOL emojiLoaded;
NSRange currentRange;
NSMutableDictionary *highlightColors;
NSMutableDictionary *framesDict;
NSInteger drawFlag;
*/
private var labelImageView: UIImageView?
private var highlightImageView: UIImageView?
private var highlighting: Bool?
private var btnLoaded: Bool?
private var emojiLoaded: Bool?
private var currentRange: NSRange?
private var highlightColors: NSMutableDictionary?
private var framesDict: NSMutableDictionary?
private var drawFlag: UInt32?
override init(frame: CGRect) {
super.init(frame: frame)
drawFlag = arc4random()
framesDict = NSMutableDictionary()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | caa14e5e8413ba98605029f547ab5111 | 21.881579 | 75 | 0.636573 | 4.170264 | false | false | false | false |
chrispix/swift-poloniex-portfolio | Sources/poloniex/HistoryLoader.swift | 1 | 3236 |
import Foundation
/*
[{ "globalTradeID": 25129732, "tradeID": "6325758", "date": "2016-04-05 08:08:40", "rate": "0.02565498", "amount": "0.10000000", "total": "0.00256549", "fee": "0.00200000", "orderNumber": "34225313575", "type": "sell", "category": "exchange" }, { "globalTradeID": 25129628, "tradeID": "6325741", "date": "2016-04-05 08:07:55", "rate": "0.02565499", "amount": "0.10000000", "total": "0.00256549", "fee": "0.00200000", "orderNumber": "34225195693", "type": "buy", "category": "exchange" }, ... ]
*/
class HistoryLoader {
private static let dateParser: DateFormatter = {
let parser = DateFormatter()
parser.dateFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss"
return parser
}()
static func loadOrders(_ holding: Holding, keys: APIKeys) -> [ExecutedOrder] {
let session = URLSession(configuration: URLSessionConfiguration.default)
let poloniexRequest = PoloniexRequest(params: ["command": "returnTradeHistory", "currencyPair": holding.bitcoinMarketKey, "start": "0", "end": "\(Date().timeIntervalSince1970)"], keys: keys)
let request = poloniexRequest.urlRequest
var finished = false
var orders = [ExecutedOrder]()
let historyTask = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in
guard let data = data, let responseBody = String(data: data, encoding: .utf8) else {
print("couldn't decode data")
finished = true
return
}
guard error == nil else {
print("error response")
finished = true
return
}
guard !responseBody.isEmpty else {
print("empty response")
finished = true
return
}
do {
let orderDicts: [[AnyHashable: Any?]] = try JSONSerialization.jsonObject(with: data, options: [.allowFragments]) as! [[AnyHashable: Any?]]
for order in orderDicts {
guard let typeString = order["type"] as? String,
let type = BuySell(rawValue: typeString),
let amount = JSONHelper.double(fromJsonObject: order["amount"] as? String),
let price = JSONHelper.double(fromJsonObject: order["rate"] as? String),
let total = JSONHelper.double(fromJsonObject: order["total"] as? String),
let fee = JSONHelper.double(fromJsonObject: order["fee"] as? String),
let dateString = order["date"] as? String,
let date = dateParser.date(from: dateString)
else { continue }
let thisOrder = ExecutedOrder(price: price, amount: amount, type: type, fee: fee, total: total, date: date)
orders.append(thisOrder)
}
} catch {
print("couldn't decode JSON")
finished = true
return
}
finished = true
})
historyTask.resume()
while(!finished) {}
return orders
}
}
| mit | 27f12c4eb481850c55598f3a18eb203b | 43.328767 | 494 | 0.549753 | 4.420765 | false | false | false | false |
coffee-cup/solis | SunriseSunset/Spring/DesignableLabel.swift | 1 | 2000 | // The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([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
@IBDesignable public class DesignableLabel: SpringLabel {
@IBInspectable public var lineHeight: CGFloat = 1.5 {
didSet {
let font = UIFont(name: self.font.fontName, size: self.font.pointSize)
let text = self.text
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineHeight
let attributedString = NSMutableAttributedString(string: text!)
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedString.length))
attributedString.addAttribute(NSAttributedString.Key.font, value: font!, range: NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
}
| mit | ec8f66881c3f83e47188812d9d68c89d | 45.511628 | 151 | 0.7195 | 4.987531 | false | false | false | false |
ahoppen/swift | benchmark/single-source/FloatingPointConversion.swift | 10 | 8061 | //===--- FloatingPointConversion.swift ------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let benchmarks = [
BenchmarkInfo(
name: "ConvertFloatingPoint.MockFloat64ToDouble",
runFunction: run_ConvertFloatingPoint_MockFloat64ToDouble,
tags: [.validation, .api],
setUpFunction: { blackHole(mockFloat64s) }),
BenchmarkInfo(
name: "ConvertFloatingPoint.MockFloat64Exactly",
runFunction: run_ConvertFloatingPoint_MockFloat64Exactly,
tags: [.validation, .api],
setUpFunction: { blackHole(mockFloat64s) }),
BenchmarkInfo(
name: "ConvertFloatingPoint.MockFloat64Exactly2",
runFunction: run_ConvertFloatingPoint_MockFloat64Exactly2,
tags: [.validation, .api],
setUpFunction: { blackHole(mockFloat64s) }),
BenchmarkInfo(
name: "ConvertFloatingPoint.MockFloat64ToInt64",
runFunction: run_ConvertFloatingPoint_MockFloat64ToInt64,
tags: [.validation, .api],
setUpFunction: { blackHole(mockFloat64s) }),
]
protocol MockBinaryFloatingPoint: BinaryFloatingPoint {
associatedtype _Value: BinaryFloatingPoint
var _value: _Value { get set }
init(_ _value: _Value)
}
extension MockBinaryFloatingPoint {
static var exponentBitCount: Int { _Value.exponentBitCount }
static var greatestFiniteMagnitude: Self {
Self(_Value.greatestFiniteMagnitude)
}
static var infinity: Self { Self(_Value.infinity) }
static var leastNonzeroMagnitude: Self { Self(_Value.leastNonzeroMagnitude) }
static var leastNormalMagnitude: Self { Self(_Value.leastNormalMagnitude) }
static var nan: Self { Self(_Value.nan) }
static var pi: Self { Self(_Value.pi) }
static var signalingNaN: Self { Self(_Value.signalingNaN) }
static var significandBitCount: Int { _Value.significandBitCount }
static func + (lhs: Self, rhs: Self) -> Self { Self(lhs._value + rhs._value) }
static func += (lhs: inout Self, rhs: Self) { lhs._value += rhs._value }
static func - (lhs: Self, rhs: Self) -> Self { Self(lhs._value - rhs._value) }
static func -= (lhs: inout Self, rhs: Self) { lhs._value -= rhs._value }
static func * (lhs: Self, rhs: Self) -> Self { Self(lhs._value * rhs._value) }
static func *= (lhs: inout Self, rhs: Self) { lhs._value *= rhs._value }
static func / (lhs: Self, rhs: Self) -> Self { Self(lhs._value / rhs._value) }
static func /= (lhs: inout Self, rhs: Self) { lhs._value /= rhs._value }
init(_ value: Int) { self.init(_Value(value)) }
init(_ value: Float) { self.init(_Value(value)) }
init(_ value: Double) { self.init(_Value(value)) }
#if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64))
init(_ value: Float80) { self.init(_Value(value)) }
#endif
init(integerLiteral value: _Value.IntegerLiteralType) {
self.init(_Value(integerLiteral: value))
}
init(floatLiteral value: _Value.FloatLiteralType) {
self.init(_Value(floatLiteral: value))
}
init(sign: FloatingPointSign, exponent: _Value.Exponent, significand: Self) {
self.init(
_Value(sign: sign, exponent: exponent, significand: significand._value))
}
init(
sign: FloatingPointSign,
exponentBitPattern: _Value.RawExponent,
significandBitPattern: _Value.RawSignificand
) {
self.init(
_Value(
sign: sign,
exponentBitPattern: exponentBitPattern,
significandBitPattern: significandBitPattern))
}
var binade: Self { Self(_value.binade) }
var exponent: _Value.Exponent { _value.exponent }
var exponentBitPattern: _Value.RawExponent { _value.exponentBitPattern }
var isCanonical: Bool { _value.isCanonical }
var isFinite: Bool { _value.isFinite }
var isInfinite: Bool { _value.isInfinite }
var isNaN: Bool { _value.isNaN }
var isNormal: Bool { _value.isNormal }
var isSignalingNaN: Bool { _value.isSignalingNaN }
var isSubnormal: Bool { _value.isSubnormal }
var isZero: Bool { _value.isZero }
var magnitude: Self { Self(_value.magnitude) }
var nextDown: Self { Self(_value.nextDown) }
var nextUp: Self { Self(_value.nextUp) }
var sign: FloatingPointSign { _value.sign }
var significand: Self { Self(_value.significand) }
var significandBitPattern: _Value.RawSignificand {
_value.significandBitPattern
}
var significandWidth: Int { _value.significandWidth }
var ulp: Self { Self(_value.ulp) }
mutating func addProduct(_ lhs: Self, _ rhs: Self) {
_value.addProduct(lhs._value, rhs._value)
}
func advanced(by n: _Value.Stride) -> Self { Self(_value.advanced(by: n)) }
func distance(to other: Self) -> _Value.Stride {
_value.distance(to: other._value)
}
mutating func formRemainder(dividingBy other: Self) {
_value.formRemainder(dividingBy: other._value)
}
mutating func formSquareRoot() { _value.formSquareRoot() }
mutating func formTruncatingRemainder(dividingBy other: Self) {
_value.formTruncatingRemainder(dividingBy: other._value)
}
func isEqual(to other: Self) -> Bool { _value.isEqual(to: other._value) }
func isLess(than other: Self) -> Bool { _value.isLess(than: other._value) }
func isLessThanOrEqualTo(_ other: Self) -> Bool {
_value.isLessThanOrEqualTo(other._value)
}
mutating func round(_ rule: FloatingPointRoundingRule) { _value.round(rule) }
}
struct MockFloat64: MockBinaryFloatingPoint {
var _value: Double
init(_ _value: Double) { self._value = _value }
}
struct MockFloat32: MockBinaryFloatingPoint {
var _value: Float
init(_ _value: Float) { self._value = _value }
}
let doubles = [
1.8547832857295, 26.321549267719135, 98.9544480962058, 73.70286973782363,
82.04918555938816, 76.38902969312758, 46.35647857011161, 64.0821426030317,
97.82373347320156, 55.742361037720634, 23.677941665488856, 93.7347588108058,
80.72657040828412, 32.137580733275826, 64.78192587530002, 21.459686568896863,
24.88407660280718, 85.25905561999171, 12.858847331083556, 29.418845887252864,
67.64627066438761, 68.09883494078815, 57.781587230862094, 63.38335631088038,
83.31376661495327, 87.45936846358906, 0.6757674136841918, 86.45465036820696,
84.72715137492781, 82.67894289189142, 26.1667640621554, 21.24895661442493,
65.06399183516027, 90.06549073883058, 59.2736650501005, 94.5800380563246,
84.22617424003917, 26.93158630395639, 9.069952095976841, 96.10067836567679,
62.60505762081415, 29.57878462599286, 66.06040114311294, 51.709999429326636,
64.79777579583545, 45.25948795832151, 94.31492354198335, 52.31096166433902,
]
let mockFloat64s = doubles.map { MockFloat64($0) }
// See also: test/SILOptimizer/floating_point_conversion.swift
@inline(never)
public func run_ConvertFloatingPoint_MockFloat64ToDouble(_ n: Int) {
for _ in 0..<(n * 100) {
for element in mockFloat64s {
let f = Double(identity(element))
blackHole(f)
}
}
}
@inline(__always)
func convert<
T: BinaryFloatingPoint, U: BinaryFloatingPoint
>(exactly value: T, to: U.Type) -> U? {
U(exactly: value)
}
@inline(never)
public func run_ConvertFloatingPoint_MockFloat64Exactly(_ n: Int) {
for _ in 0..<(n * 25) {
for element in mockFloat64s {
let f = convert(exactly: identity(element), to: Double.self)
blackHole(f)
}
}
}
@inline(never)
public func run_ConvertFloatingPoint_MockFloat64Exactly2(_ n: Int) {
for _ in 0..<(n * 25) {
for element in mockFloat64s {
let f = convert(exactly: identity(element), to: MockFloat32.self)
blackHole(f)
}
}
}
@inline(never)
public func run_ConvertFloatingPoint_MockFloat64ToInt64(_ n: Int) {
for _ in 0..<(n * 1000) {
for element in mockFloat64s {
let i = Int64(identity(element))
blackHole(i)
}
}
}
| apache-2.0 | af917640639a03009a85691b49491a3f | 37.023585 | 81 | 0.69309 | 3.523164 | false | false | false | false |
pixio/PXInfiniteScrollView | Example/PXInfiniteScrollView/ViewController.swift | 1 | 1771 | //
// PXSwiftViewController.swift
// PXImageView
//
// Created by Dave Heyborne on 2.17.16.
// Copyright © 2016 Dave Heyborne. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var contentView: View {
return view as! View
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
override func loadView() {
super.loadView()
view = View()
}
override func viewDidLoad() {
super.viewDidLoad()
title = "PX Infinite Scroll View"
view.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
edgesForExtendedLayout = UIRectEdge.None
let faces: [String] = ["andres", "andrew", "ben", "calvin", "daniel", "dillon", "hunsaker", "julie", "jun", "kevin", "lorenzo", "matt", "seth", "spencer", "victor", "william"]
var faceViews: [UIImageView] = []
for face in faces {
let imageView: UIImageView = UIImageView(image: UIImage(named: face))
imageView.contentMode = UIViewContentMode.ScaleAspectFit
faceViews.append(imageView)
}
let animals: [String] = ["big bird", "bear", "bugs bunny", "cat", "cow", "duck", "giraffe", "gorilla", "jumping lemur", "lemur", "lion", "penguin", "sloth", "wolf", "as it is"]
var animalViews: [UIImageView] = []
for animal in animals {
let imageView: UIImageView = UIImageView(image: UIImage(named: animal))
imageView.contentMode = UIViewContentMode.ScaleAspectFit
animalViews.append(imageView)
}
contentView.faceScrollView.pages = faceViews
contentView.bodyScrollView.pages = animalViews
}
}
| mit | 69455a6011694d94b7035a0b3958e86f | 34.4 | 184 | 0.611864 | 4.26506 | false | false | false | false |
adamkaplan/swifter | SwifterTests/PromiseTests.swift | 1 | 3280 | //
// PromiseTests.swift
// Swifter
//
// Created by Daniel Hanggi on 6/19/14.
// Copyright (c) 2014 Yahoo!. All rights reserved.
//
import XCTest
class PromiseTests: XCTestCase {
func testFold() -> () {
var onFulfilled = false
var onPending = false
let p1 = Promise<Int>()
p1.fold({ _ in onFulfilled = true }, { _ in onPending = true })
XCTAssertFalse(onFulfilled)
XCTAssertTrue(onPending)
let p2 = Promise("Hello")
p2.fold({ _ in onFulfilled = true }, { _ in onPending = false })
XCTAssertTrue(onFulfilled)
XCTAssertTrue(onPending)
}
func testTryFulfill() -> () {
let p1 = Promise<Try<Int>>()
XCTAssertTrue(p1.tryFulfill(.Success([10])))
XCTAssertEqual(p1.value!.toOption()!, 10)
XCTAssertFalse(p1.tryFulfill(.Success([11])))
XCTAssertEqual(p1.value!.unwrap(), 10)
let p2 = Promise("Hello")
XCTAssertFalse(p2.tryFulfill("Goodbye"))
XCTAssertEqual(p2.value!, "Hello")
}
func testIsFulfilled() -> () {
let p1 = Promise<Int>()
XCTAssertFalse(p1.isFulfilled())
let p2 = Promise("Hello")
XCTAssertTrue(p2.isFulfilled())
}
func testAlsoFulfill() -> () {
let p1 = Promise<Int>()
let p2 = Promise<Int>()
p1.alsoFulfill(p2)
p1.tryFulfill(10)
XCTAssertEqual(p1.value!, 10)
do {} while p2.value == nil
XCTAssertEqual(p2.value!, 10)
let p3 = Promise<String>("Hello")
let p4 = Promise<String>()
p3.alsoFulfill(p4)
XCTAssertEqual(p3.value!, "Hello")
do {} while p4.value == nil
XCTAssertEqual(p4.value!, "Hello")
}
func testExecuteOrMap() -> () {
var finishedExecuting = false
var j: Int = 0
let p1 = Promise<Int>()
let e1 = Executable<Int>(queue: NSOperationQueue()) {
_ in
sleep(1)
finishedExecuting = true
}
p1.executeOrMap(e1)
p1.tryFulfill(0)
do {} while !finishedExecuting
finishedExecuting = false
let p2 = Promise(0)
let e2 = Executable<Int>(queue: NSOperationQueue()) {
_ in
finishedExecuting = true
}
p2.executeOrMap(e2)
do {} while !finishedExecuting
}
func testOnComplete() -> () {
var onComplete = false
let p1 = Promise<Int>()
p1.onComplete { _ in onComplete = true }
XCTAssertFalse(onComplete)
p1.tryFulfill(10)
do {} while !onComplete
onComplete = false
let p2 = Promise(10)
p2.onComplete { _ in onComplete = true }
do {} while !onComplete
}
func testAwait() -> () {
var finishedExecuting = false
let p1 = Promise<Int>()
let p2 = Promise<Int>()
let e1 = Executable<Int>(queue: NSOperationQueue()) {
sleep(1)
finishedExecuting = true
_ = p2.tryFulfill($0 + 125)
}
p1.executeOrMap(e1)
p1.tryFulfill(0)
XCTAssertEqual(p2.await().value!, 125)
XCTAssertTrue(finishedExecuting)
}
}
| apache-2.0 | fbe318827f2d411a9ffb56ed20c5d42e | 27.275862 | 72 | 0.536585 | 4.162437 | false | true | false | false |
chengxianghe/MissGe | MissGe/MissGe/Class/Project/UI/Controller/Mine/MLUserEditController.swift | 1 | 3237 | //
// MLUserEditController.swift
// MissLi
//
// Created by chengxianghe on 16/7/27.
// Copyright © 2016年 cn. All rights reserved.
//
import UIKit
class MLUserEditCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var valueLabel: UILabel!
}
class MLUserEditController: BaseViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
fileprivate var dataSource = ["登录名","昵称","性别","所在地","生日"]
fileprivate var valueSource = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
let user: MLUserModel! = MLNetConfig.shareInstance.user
self.valueSource.append(user.username!)
self.valueSource.append(user.nickname!)
if user.gender == 1 {
self.valueSource.append("男")
} else if user.gender == 2 {
self.valueSource.append("女")
} else {
self.valueSource.append("保密")
}
self.valueSource.append(user.location!)
self.valueSource.append(user.birthday!)
self.valueSource.append(user.autograph!)
// Do any additional setup after loading the view.
}
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = (indexPath as NSIndexPath).section
let cell = tableView.dequeueReusableCell(withIdentifier: "MLUserEditCell") as! MLUserEditCell
if section == 0 {
cell.nameLabel.text = self.dataSource[(indexPath as NSIndexPath).row]
cell.valueLabel.text = self.valueSource[(indexPath as NSIndexPath).row]
} else {
cell.nameLabel.text = "简介"
cell.valueLabel.text = self.valueSource.last
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if (indexPath as NSIndexPath).section == 0 {
return 44
}
return max(44, ceil(self.valueSource.last!.height(UIFont.systemFont(ofSize: 16), maxWidth: kScreenWidth - 100)))
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return dataSource.count
}
return 1
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | deb658d1231be1d89881add75d7680ad | 30.663366 | 120 | 0.642276 | 4.801802 | false | false | false | false |
onekiloparsec/KPCTabsControl | KPCTabsControl/DefaultStyle.swift | 1 | 5987 | //
// DefaultStyle.swift
// KPCTabsControl
//
// Created by Christian Tietze on 10/08/16.
// Licensed under the MIT License (see LICENSE file)
//
import Cocoa
public enum TitleDefaults {
static let alignment = NSTextAlignment.center
static let lineBreakMode = NSLineBreakMode.byTruncatingMiddle
}
/// Default implementation of Themed Style
extension ThemedStyle {
// MARK: - Tab Buttons
public func tabButtonOffset(position: TabPosition) -> Offset {
return NSPoint()
}
public func tabButtonBorderMask(_ position: TabPosition) -> BorderMask? {
return BorderMask.all()
}
// MARK: - Tab Button Titles
public func iconFrames(tabRect rect: NSRect) -> IconFrames {
let verticalPadding: CGFloat = 4.0
let paddedHeight = rect.height - 2*verticalPadding
let x = rect.width / 2.0 - paddedHeight / 2.0
return (NSMakeRect(10.0, verticalPadding, paddedHeight, paddedHeight),
NSMakeRect(x, verticalPadding, paddedHeight, paddedHeight))
}
public func titleRect(title: NSAttributedString, inBounds rect: NSRect, showingIcon: Bool) -> NSRect {
let titleSize = title.size()
let fullWidthRect = NSRect(x: NSMinX(rect),
y: NSMidY(rect) - titleSize.height/2.0 - 0.5,
width: NSWidth(rect),
height: titleSize.height)
return self.paddedRectForIcon(fullWidthRect, showingIcon: showingIcon)
}
fileprivate func paddedRectForIcon(_ rect: NSRect, showingIcon: Bool) -> NSRect {
guard showingIcon else {
return rect
}
let iconRect = self.iconFrames(tabRect: rect).iconFrame
let pad = NSMaxX(iconRect)+titleMargin
return rect.offsetBy(dx: pad, dy: 0.0).shrinkBy(dx: pad, dy: 0.0)
}
public func titleEditorSettings() -> TitleEditorSettings {
return (textColor: NSColor(calibratedWhite: 1.0/6, alpha: 1.0),
font: self.theme.tabButtonTheme.titleFont,
alignment: TitleDefaults.alignment)
}
public func attributedTitle(content: String, selectionState: TabSelectionState) -> NSAttributedString {
let activeTheme = self.theme.tabButtonTheme(fromSelectionState: selectionState)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = TitleDefaults.alignment
paragraphStyle.lineBreakMode = TitleDefaults.lineBreakMode
let attributes = [NSAttributedString.Key.foregroundColor : activeTheme.titleColor,
NSAttributedString.Key.font : activeTheme.titleFont,
NSAttributedString.Key.paragraphStyle : paragraphStyle]
return NSAttributedString(string: content, attributes: attributes)
}
// MARK: - Tabs Control
public func tabsControlBorderMask() -> BorderMask? {
return BorderMask.top.union(BorderMask.bottom)
}
// MARK: - Drawing
public func drawTabsControlBezel(frame: NSRect) {
self.theme.tabsControlTheme.backgroundColor.setFill()
frame.fill()
let borderDrawing = BorderDrawing.fromMask(frame, borderMask: self.tabsControlBorderMask())
self.drawBorder(borderDrawing, color: self.theme.tabsControlTheme.borderColor)
}
public func drawTabButtonBezel(frame: NSRect, position: TabPosition, isSelected: Bool) {
let activeTheme = isSelected ? self.theme.selectedTabButtonTheme : self.theme.tabButtonTheme
activeTheme.backgroundColor.setFill()
frame.fill()
let borderDrawing = BorderDrawing.fromMask(frame, borderMask: self.tabButtonBorderMask(position))
self.drawBorder(borderDrawing, color: activeTheme.borderColor)
}
fileprivate func drawBorder(_ border: BorderDrawing, color: NSColor) {
guard case let .draw(borderRects: borderRects, rectCount: _) = border
else { return }
color.setFill()
color.setStroke()
borderRects.fill()
}
}
// MARK: -
private enum BorderDrawing {
case empty
case draw(borderRects: [NSRect], rectCount: Int)
fileprivate static func fromMask(_ sourceRect: NSRect, borderMask: BorderMask?) -> BorderDrawing {
guard let mask = borderMask else { return .empty }
var outputCount: Int = 0
var remainderRect = NSZeroRect
var borderRects: [NSRect] = [NSZeroRect, NSZeroRect, NSZeroRect, NSZeroRect]
if mask.contains(.top) {
NSDivideRect(sourceRect, &borderRects[outputCount], &remainderRect, 0.5, .minY)
outputCount += 1
}
if mask.contains(.left) {
NSDivideRect(sourceRect, &borderRects[outputCount], &remainderRect, 0.5, .minX)
outputCount += 1
}
if mask.contains(.right) {
NSDivideRect(sourceRect, &borderRects[outputCount], &remainderRect, 0.5, .maxX)
outputCount += 1
}
if mask.contains(.bottom) {
NSDivideRect(sourceRect, &borderRects[outputCount], &remainderRect, 0.5, .maxY)
outputCount += 1
}
guard outputCount > 0 else { return .empty }
return .draw(borderRects: borderRects, rectCount: outputCount)
}
}
// MARK: -
/**
* The default TabsControl style. Used with the DefaultTheme, it provides an experience similar to Apple's Numbers.app.
*/
public struct DefaultStyle: ThemedStyle {
public let theme: Theme
public let tabButtonWidth: TabWidth
public let tabsControlRecommendedHeight: CGFloat = 24.0
public init(theme: Theme = DefaultTheme(), tabButtonWidth: TabWidth = .flexible(min: 50, max: 150)) {
self.theme = theme
self.tabButtonWidth = tabButtonWidth
}
}
| mit | 654be1eb4b0a4a935532779cb5f507c1 | 33.408046 | 120 | 0.635377 | 4.87144 | false | false | false | false |
banDedo/BDModules | HarnessModules/Model/User.swift | 1 | 2328 | //
// User.swift
// BDModules
//
// Created by Patrick Hogan on 2/23/15.
// Copyright (c) 2015 bandedo. All rights reserved.
//
import Foundation
private let kUserFirstNameKey = "firstName"
private let kUserLastNameKey = "lastName"
private let kUserEmailKey = "email"
private let kUserPhoneNumberKey = "phoneNumber"
private let kUserCoverImageURLKey = "coverImageURL"
private let kUserProfileImageURLKey = "profileImageURL"
public class User: ModelObject, UserProfile {
// MARK:- Properties
private(set) public var firstName = ""
private(set) public var lastName = ""
private(set) public var email = ""
private(set) public var phoneNumber: String?
private(set) public var coverImageURL: String?
private(set) public var profileImageURL: String?
public var displayName: String {
get {
return firstName + " " + lastName
}
}
}
public let kUserFirstNameApiKeyPath = "first_name"
public let kUserLastNameApiKeyPath = "last_name"
public let kUserEmailApiKeyPath = "email"
public let kUserPhoneNumberApiKeyPath = "phone_number"
public let kUserCoverImageURLApiKeyPath = "cover_image_url"
public let kUserProfileImageURLApiKeyPath = "profile_image_url"
public class UserAPIMapper: ModelObjectAPIMapper {
// MARK:- Constructor
public override init(apiFieldMappers: [ APIFieldMapper] = [APIFieldMapper ](), delegate: APIMapperDelegate) {
super.init(apiFieldMappers: apiFieldMappers, delegate: delegate)
var apiFieldMappers = super.apiFieldMappers
apiFieldMappers += [
delegate.fieldMapper(apiKeyPath: kUserFirstNameApiKeyPath, modelKey: kUserFirstNameKey),
delegate.fieldMapper(apiKeyPath: kUserLastNameApiKeyPath, modelKey: kUserLastNameKey),
delegate.fieldMapper(apiKeyPath: kUserEmailApiKeyPath, modelKey: kUserEmailKey),
delegate.fieldMapper(apiKeyPath: kUserPhoneNumberApiKeyPath, modelKey: kUserPhoneNumberKey, required: false),
delegate.fieldMapper(apiKeyPath: kUserCoverImageURLApiKeyPath, modelKey: kUserCoverImageURLKey, required: false),
delegate.fieldMapper(apiKeyPath: kUserProfileImageURLApiKeyPath, modelKey: kUserProfileImageURLKey, required: false),
]
self.apiFieldMappers = apiFieldMappers
}
}
| apache-2.0 | 1c7057a0a76ac8c0d2b5c1d553d071ff | 36.548387 | 129 | 0.730241 | 4.619048 | false | false | false | false |
vanyaland/Californication | Californication/GoogleMapsNetworkManagerImpl.swift | 1 | 2157 | /**
* Copyright (c) 2016 Ivan Magda
*
* 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 GoogleMaps
// MARK: CannedGoogleMapsNetworkManager: GoogleMapsNetworkManager
class GoogleMapsNetworkManagerImpl: GoogleMapsNetworkManager {
// MARK: GoogleMapsNetworkManager
func place(with id: String, success: @escaping GoogleMapsNetworkPlaceResponse,
failure: @escaping GoogleMapsFailureBlock) {
GMSPlacesClient().lookUpPlaceID(id) { (place, error) in
guard let place = place else { return failure(error) }
success(place)
}
}
func places(with ids: [String], success: @escaping GoogleMapsNetworkPlacesResponse,
failure: @escaping GoogleMapsFailureBlock) {
var places = [GMSPlace]()
let client = GMSPlacesClient()
func processOnResponse(_ place: GMSPlace?, error: Error?) {
guard let place = place else { return failure(error) }
places.append(place)
if places.count == ids.count {
success(places)
}
}
ids.forEach { client.lookUpPlaceID($0, callback: processOnResponse) }
}
}
| mit | c8c200a4b2840e6bf22cd62dca3a50bb | 36.842105 | 85 | 0.722299 | 4.648707 | false | false | false | false |
ben-ng/swift | stdlib/public/core/MemoryLayout.swift | 1 | 2597 | //===----------------------------------------------------------------------===//
//
// 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// The memory layout of a type, describing its size, stride, and alignment.
public enum MemoryLayout<T> {
/// The contiguous memory footprint of `T`.
///
/// Does not include any dynamically-allocated or "remote" storage. In
/// particular, `MemoryLayout<T>.size`, when `T` is a class type, is the same
/// regardless of how many stored properties `T` has.
@_transparent
public static var size: Int {
return Int(Builtin.sizeof(T.self))
}
/// The number of bytes from the start of one instance of `T` to the start of
/// the next in an `Array<T>`.
///
/// This is the same as the number of bytes moved when an `UnsafePointer<T>`
/// is incremented. `T` may have a lower minimal alignment that trades runtime
/// performance for space efficiency. The result is always positive.
@_transparent
public static var stride: Int {
return Int(Builtin.strideof(T.self))
}
/// The default memory alignment of `T`.
@_transparent
public static var alignment: Int {
return Int(Builtin.alignof(T.self))
}
}
extension MemoryLayout {
/// Returns the contiguous memory footprint of `T`.
///
/// Does not include any dynamically-allocated or "remote" storage. In
/// particular, `MemoryLayout.size(ofValue: x)`, when `x` is a class instance,
/// is the same regardless of how many stored properties `T` has.
@_transparent
public static func size(ofValue _: T) -> Int {
return MemoryLayout.size
}
/// Returns the number of bytes from the start of one instance of `T` to the
/// start of the next in an `Array<T>`.
///
/// This is the same as the number of bytes moved when an `UnsafePointer<T>`
/// is incremented. `T` may have a lower minimal alignment that trades runtime
/// performance for space efficiency. The result is always positive.
@_transparent
public static func stride(ofValue _: T) -> Int {
return MemoryLayout.stride
}
/// Returns the default memory alignment of `T`.
@_transparent
public static func alignment(ofValue _: T) -> Int {
return MemoryLayout.alignment
}
}
| apache-2.0 | f1dc6138ad16e833517983a6efacc4ba | 36.1 | 80 | 0.651136 | 4.409168 | false | false | false | false |
DiUS/pact-consumer-swift | Tests/InteractionSpec.swift | 1 | 2704 | import Quick
import Nimble
@testable import PactConsumerSwift
class InteractionSpec: QuickSpec {
override func spec() {
var interaction: Interaction?
beforeEach { interaction = Interaction() }
describe("json payload"){
context("pact state") {
it("includes provider state in the payload") {
let payload = interaction!.given("state of awesomeness").uponReceiving("an important request is received").payload()
expect(payload["providerState"] as! String?) == "state of awesomeness"
expect(payload["description"] as! String?) == "an important request is received"
}
}
context("no provider state") {
it("doesn not include provider state when not included") {
let payload = interaction!.uponReceiving("an important request is received").payload()
expect(payload["providerState"]).to(beNil())
}
}
context("request") {
let method: PactHTTPMethod = .PUT
let path = "/path"
let headers = ["header": "value"]
let body = "blah"
it("returns expected request with specific headers and body") {
let payload = interaction!.withRequest(method: method, path: path, headers: headers, body: body).payload()
let request = payload["request"] as! [String: AnyObject]
expect(request["path"] as! String?) == path
expect(request["method"] as! String?).to(equal("put"))
expect(request["headers"] as! [String: String]?).to(equal(headers))
expect(request["body"] as! String?).to(equal(body))
}
it("returns expected request without body and headers") {
let payload = interaction!.withRequest(method:method, path: path).payload()
let request = payload["request"] as! [String: AnyObject]
expect(request["path"] as! String?) == path
expect(request["method"] as! String?).to(equal("put"))
expect(request["headers"] as! [String: String]?).to(beNil())
expect(request["body"] as! String?).to(beNil())
}
}
context("response") {
let statusCode = 200
let headers = ["header": "value"]
let body = "body"
it("returns expected response with specific headers and body") {
let payload = interaction!.willRespondWith(status: statusCode, headers: headers, body: body).payload()
let request = payload["response"] as! [String: AnyObject]
expect(request["status"] as! Int?) == statusCode
expect(request["headers"] as! [String: String]?).to(equal(headers))
expect(request["body"] as! String?).to(equal(body))
}
}
}
}
}
| mit | a1673eb6d59d1767839a5e1794af5f2b | 37.084507 | 126 | 0.607618 | 4.469421 | false | false | false | false |
colbylwilliams/Cognitive-Speech-iOS | CognitiveSpeech/CognitiveSpeech/Domain/SpeakerIdentificationReslut.swift | 1 | 826 | //
// SpeakerIdentificationReslut.swift
// CognitiveSpeech
//
// Created by Colby Williams on 6/13/17.
// Copyright © 2017 Colby Williams. All rights reserved.
//
import Foundation
class SpeakerIdentificationReslut {
private let identifiedProfileIdKey = "identifiedProfileId"
private let convenienceKey = "confidence"
var identifiedProfileId: String?
var confidence: SpeakerResultConfidence?
var confidenceString: String {
return confidence?.rawValue ?? "Unknown"
}
init(fromJson dict: [String:Any]) {
if let identifiedProfileId = dict[identifiedProfileIdKey] as? String {
self.identifiedProfileId = identifiedProfileId
}
if let confidenceString = dict[convenienceKey] as? String, let confidence = SpeakerResultConfidence(rawValue: confidenceString) {
self.confidence = confidence
}
}
}
| mit | baab5148e0b28c8d8f45fb7e680f2282 | 25.612903 | 131 | 0.761212 | 3.909953 | false | false | false | false |
enzoliu/ThemeUI | src/Style.swift | 1 | 10782 | //
// Style.swift
// ThemeUIOrigin
//
// Created by EnzoLiu on 2017/4/13.
// Copyright © 2017年 EnzoLiu. All rights reserved.
//
import Foundation
import UIKit
private var styleIDAssociationKey: UInt8 = 0
extension UIView {
/// Style ID for UIView.
public var styleID: String {
get {
return objc_getAssociatedObject(self, &styleIDAssociationKey) as? String ?? ""
}
set(newValue) {
objc_setAssociatedObject(self, &styleIDAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
/// Set style ID for the UIView object.
///
/// - Parameters:
/// - styleID: Identifier for styles.
func setStyle(styleID: String) {
self.styleID = styleID
}
}
private var btnNormalFontKey: UInt8 = 0
private var btnHighlightFontKey: UInt8 = 0
extension UIButton {
public var normalFont: UIFont {
get {
return objc_getAssociatedObject(self, &btnNormalFontKey) as? UIFont ?? UIFont.systemFont(ofSize: 12)
}
set(newValue) {
objc_setAssociatedObject(self, &btnNormalFontKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
public var highlightFont: UIFont {
get {
return objc_getAssociatedObject(self, &btnHighlightFontKey) as? UIFont ?? UIFont.systemFont(ofSize: 12)
}
set(newValue) {
objc_setAssociatedObject(self, &btnHighlightFontKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
open override var isHighlighted: Bool{
didSet {
if isHighlighted {
self.titleLabel?.font = highlightFont
} else {
self.titleLabel?.font = normalFont
}
}
}
/// Set the font for differernt states. Because 'state' is not KVO compliant, so we choose isHighlighted to observe. Thus, this method do not support the other flag of UIControlState.
///
/// - Parameters:
/// - font: UIFont, you can set font family, font size, ... etc.
/// - state: UIControlState, only support .normal & .highlight. See the description above.
func setFont(font: UIFont, for state: UIControlState) {
switch state {
case UIControlState.highlighted:
self.highlightFont = font
default:
self.normalFont = font
}
}
}
public struct StyleCollection {
var name: String
var styles: [HashableControlState: [StyleProperty]]
public init() {
name = ""
styles = [:]
}
public func setup(view: UIView, animate: Bool = true) {
DispatchQueue.main.async {
for key in self.styles.keys {
guard let styles = self.styles[key] else {
continue
}
let state = key.toControlState()
self.applyStyle(withAnimation: animate, inView: view, for: state, styles: styles)
}
}
}
private func applyStyle(withAnimation: Bool, inView view: UIView, for state: UIControlState, styles: [StyleProperty]) {
guard withAnimation else {
for style in styles {
style.apply(view: view, for: state)
}
return
}
let transStyle = styles.filter { x in return x is Font }
let viewStyle = styles.filter { x in return x is Background }
let borderStyle = styles.filter { x in return x is Border } // Border animation wont work here.
if transStyle.count > 0 {
UIView.transition(with: view, duration: 0.3, options: [.curveEaseInOut, .transitionCrossDissolve], animations: {
for style in transStyle {
style.apply(view: view, for: state)
}
}, completion: nil)
}
if viewStyle.count > 0 {
UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut], animations: {
for style in viewStyle {
style.apply(view: view, for: state)
}
}, completion: nil)
}
if borderStyle.count > 0 {
for style in borderStyle {
style.apply(view: view, for: state)
}
}
}
}
protocol StyleProperty {
func apply(view: UIView, for sate: UIControlState)
init(propSet: [String: Any])
}
//
// MARK:- Font : StyleProlerty
//
public struct Font : StyleProperty {
var family: String = "default"
var size: CGFloat = 12
var color: UIColor = UIColor.black
var bold: Bool = false // Only work for system font
var font: UIFont = UIFont.systemFont(ofSize: 12)
public init(propSet: [String: Any]) {
let keys = propSet.keys.filter{ x in x.components(separatedBy: ".").get(0)?.lowercased() == "font" }
for key in keys {
switch key.lowercased() {
case "font.color":
guard let value = propSet[key] as? String else { break }
self.setColor(valueString: value)
case "font.size" :
guard let value = propSet[key] as? CGFloat else { break }
self.setSize(value)
case "font.family" :
guard let value = propSet[key] as? String else { break }
self.setFamily(value)
case "font.bold" :
guard let value = propSet[key] as? Bool else { break }
self.setBold(value)
default:
break
}
}
if self.family.lowercased() == "default" {
self.font = self.bold ? UIFont.boldSystemFont(ofSize: self.size) : UIFont.systemFont(ofSize: self.size)
} else if let font = UIFont(name: self.family, size: self.size) {
self.font = font
}
}
public func apply(view: UIView, for state: UIControlState = UIControlState.normal) {
if view is UILabel || view is UITextView || view is UITextField {
view.setValue(self.font, forKey: "font")
view.setValue(self.color, forKey: "textColor")
} else if let btn = view as? UIButton {
btn.setFont(font: self.font, for: state)
btn.setTitleColor(self.color, for: state)
// to fire font setting.
btn.isHighlighted = false
}
}
//
// Property setter
//
private mutating func setColor(valueString: String) {
let colorSetting = valueString.components(separatedBy: ",")
var alpha: CGFloat = 1
guard let color = colorSetting.get(0) else {
return
}
if let alphaString = colorSetting.get(1) {
alpha = CGFloat(string: alphaString)
}
self.color = UIColor(hexString: color, alpha: CGFloat(alpha))
}
private mutating func setSize(_ value: CGFloat) {
self.size = value
}
private mutating func setFamily(_ value: String) {
self.family = value
}
private mutating func setBold(_ value: Bool) {
self.bold = value
}
}
//
// MARK:- Background : StyleProlerty
//
public struct Background : StyleProperty {
var color: UIColor = UIColor.clear
public init(propSet: [String: Any]) {
let keys = propSet.keys.filter{ x in x.components(separatedBy: ".").get(0)?.lowercased() == "bg" }
for key in keys {
switch key.lowercased() {
case "bg.color":
guard let value = propSet[key] as? String else { break }
self.setColor(valueString: value)
default:
break
}
}
}
public func apply(view: UIView, for state: UIControlState = UIControlState.normal) {
if let btn = view as? UIButton {
btn.setBackgroundImage(self.color.toImage(), for: state)
} else {
view.backgroundColor = self.color
}
}
//
// Property setter
//
private mutating func setColor(valueString: String) {
let colorSetting = valueString.components(separatedBy: ",")
var alpha: CGFloat = 1
guard let color = colorSetting.get(0) else {
return
}
if let alphaString = colorSetting.get(1) {
alpha = CGFloat(string: alphaString)
}
self.color = UIColor(hexString: color, alpha: CGFloat(alpha))
}
}
//
// MARK:- Border : StyleProlerty
//
public struct Border : StyleProperty {
var color: UIColor = UIColor.black
var width: CGFloat = 0
var roundCorner: CGFloat? = nil
public init(propSet: [String: Any]) {
let keys = propSet.keys.filter{ x in x.components(separatedBy: ".").get(0)?.lowercased() == "border" }
for key in keys {
switch key.lowercased() {
case "border.color":
guard let value = propSet[key] as? String else { break }
self.setColor(valueString: value)
case "border.width":
guard let value = propSet[key] as? CGFloat else { break }
self.setWidth(value: value)
case "border.roundcorner":
guard let value = propSet[key] as? CGFloat else { break }
self.setCornerRadius(value: value)
default:
break
}
}
}
public func apply(view: UIView, for sate: UIControlState = UIControlState.normal) {
if let conerRadius = self.roundCorner {
view.clipsToBounds = true
view.layer.cornerRadius = conerRadius
}
view.layer.borderColor = self.color.cgColor
view.layer.borderWidth = self.width
}
//
// Property setter
//
private mutating func setColor(valueString: String) {
let colorSetting = valueString.components(separatedBy: ",")
var alpha: CGFloat = 1
guard let color = colorSetting.get(0) else {
return
}
if let alphaString = colorSetting.get(1) {
alpha = CGFloat(string: alphaString)
}
self.color = UIColor(hexString: color, alpha: CGFloat(alpha))
}
private mutating func setWidth(value: CGFloat) {
self.width = value
}
private mutating func setCornerRadius(value: CGFloat) {
self.roundCorner = value
}
}
| mit | b74d98cad96e53d011ab06ea8be8c6a4 | 31.080357 | 187 | 0.55237 | 4.604443 | false | false | false | false |
ruslanskorb/CoreStore | CoreStoreDemo/CoreStoreDemo/MIgrations Demo/OrganismV2.swift | 1 | 644 | //
// OrganismV2.swift
// CoreStoreDemo
//
// Created by John Rommel Estropia on 2015/06/21.
// Copyright © 2018 John Rommel Estropia. All rights reserved.
//
import Foundation
import CoreData
class OrganismV2: NSManagedObject, OrganismProtocol {
@NSManaged var dna: Int64
@NSManaged var hasHead: Bool
@NSManaged var hasTail: Bool
@NSManaged var numberOfFlippers: Int32
// MARK: OrganismProtocol
func mutate() {
self.hasHead = arc4random_uniform(2) == 1
self.hasTail = arc4random_uniform(2) == 1
self.numberOfFlippers = Int32(arc4random_uniform(9) / 2 * 2)
}
}
| mit | 6bf60111d540b6eb91d8e15b0a56b50a | 22.814815 | 68 | 0.657854 | 3.592179 | false | false | false | false |
sunny-fish/AnimatedTransitionsDemos | UIViewControllerInteractiveTransitioningDemo/UIViewControllerInteractiveTransitioningDemo/InteractiveTransition.swift | 1 | 8673 | //
// InteractiveTransition.swift
// UIViewControllerInteractiveTransitioningDemo
//
// Created by Sunny Fish LLC on 11/12/15.
// This is free and unencumbered software released into the public domain.
//
// Anyone is free to copy, modify, publish, use, compile, sell, or distribute
// this software, either in source code form or as a compiled binary, for any
// purpose, commercial or non-commercial, and by any means.
//
// In jurisdictions that recognize copyright laws, the author or authors of
// this software dedicate any and all copyright interest in the software to the
// public domain. We make this dedication for the benefit of the public at
// large and to the detriment of our heirs and successors. We intend this
// dedication to be an overt act of relinquishment in perpetuity of all present
// and future rights to this software under copyright law.
//
// 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 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.
//
// This demonstrates how to use an object that complies with the
// UIViewControllerInteractiveTransitioning protocol. We just use the Apple
// supplied UIPercentDrivenInteractiveTransition implementation of the protocol.
// Maybe if we revisit this for a longer presentation, we can implement a
// custom transitioning object.
//
// The transition is driven by a pan gesture recognizer, so we create an
// interaction controller when we start handling the gesture recognizer.
// The transition is to expand or shrink a circe from large enough to cover the
// view to the size of a circular button, done with a CABasicAnimation.
import UIKit
class InteractiveTransition: NSObject, UINavigationControllerDelegate, UIViewControllerAnimatedTransitioning {
// The interaction controller.
var interactionController: UIPercentDrivenInteractiveTransition?
// The context for the transition.
weak var transitionContext: UIViewControllerContextTransitioning?
// The navigation controller. Set this in Interface Builder.
@IBOutlet weak var navigationController: UINavigationController?
// We remember the initial pan direction so we can decide to finish the
// transition or cancel the transition based on the final direction.
var panDirection: CGFloat = 0
// Install the gesture recognizer if we're hooked up to a navigation controller.
override func awakeFromNib() {
super.awakeFromNib()
guard let nc = navigationController else {
return
}
nc.view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: Selector("panned:")))
}
// Handle the pan gesture recognizer.
func panned(gestureRecognizer: UIPanGestureRecognizer) {
// Make sure the navigation controller is hooked up.
guard let nc = navigationController else {
return
}
// Decide what to do based on the state of the recognizer.
switch gestureRecognizer.state {
case .Began:
// In the beginning create the interaction transition for this pan.
self.interactionController = UIPercentDrivenInteractiveTransition();
// Save the direction.
panDirection = gestureRecognizer.velocityInView(nc.view).x
// Push or pop the view controller. In a more complex app you might ask the
// top view controller what to do, instead of assume it just wants to be popped
// if there is another view controller under it.
if nc.viewControllers.count > 1 {
nc.popViewControllerAnimated(true)
} else {
nc.topViewController!.performSegueWithIdentifier("PushSegue", sender: nil)
}
case .Changed:
// Get the percentage base on how far the pan has moved.
let translation = gestureRecognizer.translationInView(nc.view)
let completionProgress = abs(translation.x / CGRectGetWidth(nc.view.bounds))
// Tell the interaction controller to update to that percentage.
interactionController?.updateInteractiveTransition(completionProgress)
case .Ended:
// If the pan has reversed, the initial direction will be the opposite
// sign than the final direction. Multiplying two numbers of the same sign
// will always result in a positive number, so the transition should
// finish. With a negative result, one direction was the opposite of the
// other, and we should cancel the transition.
if (gestureRecognizer.velocityInView(nc.view).x * panDirection) > 0 {
self.interactionController?.finishInteractiveTransition()
} else {
self.interactionController?.cancelInteractiveTransition()
}
// Either way, we're done and can let go of the interaction controller.
self.interactionController = nil
default:
// All the other possible states mean the gesture is not active
// so we can clean up.
self.interactionController?.cancelInteractiveTransition()
self.interactionController = nil
}
}
// MARK: UINavigationControllerDelegate
// Just supply the interactive transitioning object property, as it won't exist
// when the pan gesture recognizer is inactive, so we will get a regular animated
// transition. After this object starts handling a gesture recognizer there will
// be an interactive transitioning object, so the user will see the interactive
// transition.
func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return self.interactionController
}
// Just supply this object when asked for the animated transitioning object.
// This call does give the opportunity to create more complex logic on how
// to choose an animated transitioning object.
func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self
}
// MARK: UIViewControllerAnimatedTransitioning
// This object knows the transition is short and fixed length when not interactive.
// When interactive, the UIPercentDrivenInteractiveTransition will prorate this value
// based on how much animation is left when the animation is completed or canceled.
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.5
}
// Run the actual animation. We're masking out one view with
// a growing or shrinking mask.
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
// Save the transition context for later.
self.transitionContext = transitionContext
// Setup the screen elements to animate.
let container = transitionContext.containerView()
let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! ViewController
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! ViewController
let button = fromVC.button;
container!.addSubview(toVC.view)
// Setup the big and small circle path for the animated mask.
let circleMaskPathInitial = UIBezierPath(ovalInRect: button.frame)
let extremePoint = CGPoint(x: button.center.x - 0.0, y: button.center.y - CGRectGetHeight(toVC.view.bounds))
let radius = sqrt((extremePoint.x * extremePoint.x) + (extremePoint.y * extremePoint.y))
let circleMaskPathFinal = UIBezierPath(ovalInRect: CGRectInset(button.frame, -radius, -radius))
// Add a mask layer.
let maskLayer = CAShapeLayer ()
maskLayer.path = circleMaskPathFinal.CGPath
toVC.view.layer.mask = maskLayer;
// Animate with a CABasicAnimation
let maskLayerAnimation = CABasicAnimation(keyPath: "path")
maskLayerAnimation.fromValue = circleMaskPathInitial.CGPath
maskLayerAnimation.toValue = circleMaskPathFinal.CGPath
maskLayerAnimation.duration = self.transitionDuration(transitionContext)
maskLayerAnimation.delegate = self
maskLayer.addAnimation(maskLayerAnimation, forKey: "path")
}
// Here's a chance to clean up after the animations.
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
guard let tc = transitionContext else {
return
}
tc.completeTransition(!tc.transitionWasCancelled())
tc.viewControllerForKey(UITransitionContextFromViewControllerKey)?.view.layer.mask = nil
}
}
| unlicense | 7166ece20ae2773f10840ccf243c3c08 | 44.408377 | 278 | 0.779776 | 4.749726 | false | false | false | false |
natestedman/PrettyOkayKit | PrettyOkayKit/CSRFEndpoint.swift | 1 | 4813 | // Copyright (c) 2016, Nate Stedman <[email protected]>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
import Endpoint
import Foundation
import HTMLReader
import NSErrorRepresentable
import Result
import Shirley
// MARK: - Purpose
enum CSRFEndpointPurpose
{
case Login
case Authenticated(Authentication)
}
extension CSRFEndpointPurpose
{
private var authentication: Authentication?
{
switch self
{
case .Login:
return nil
case .Authenticated(let authentication):
return authentication
}
}
private var URLString: String
{
switch self
{
case .Login:
return "https://verygoods.co/login"
case .Authenticated:
return "https://verygoods.co/"
}
}
private var request: NSURLRequest?
{
return NSURL(string: URLString).map({ URL in
let request = NSMutableURLRequest(URL: URL)
request.HTTPShouldHandleCookies = false
request.cachePolicy = .ReloadIgnoringCacheData
authentication?.applyToMutableURLRequest(request)
return request
})
}
}
// MARK: - Endpoint
struct CSRFEndpoint: EndpointType
{
let purpose: CSRFEndpointPurpose
var request: NSURLRequest? { return purpose.request }
}
extension CSRFEndpoint: ProcessingType
{
func resultForInput(message: Message<NSHTTPURLResponse, NSData>)
-> Result<(token: String, cookies: [NSHTTPCookie]), NSError>
{
// parse HTML for the CSRF token
let HTML = HTMLDocument(data: message.body, contentTypeHeader: nil)
guard let head = HTML.rootElement?.childElementNodes.lazy.filter({ element in
element.tagName.lowercaseString == "head"
}).first
else { return .Failure(CSRFError.FailedToFindHead.NSError) }
guard let meta = head.childElementNodes.lazy.filter({ element in
element.tagName.lowercaseString == "meta" && element.attributes["name"] == "csrf-token"
}).first
else { return .Failure(CSRFError.FailedToFindMeta.NSError) }
guard let csrf = meta.attributes["content"] else {
return .Failure(CSRFError.FailedToFindCSRF.NSError)
}
// extract response parameters
guard let headers = message.response.allHeaderFields as? [String:String] else {
return .Failure(CSRFError.FailedToFindHeaders.NSError)
}
guard let URL = message.response.URL else {
return .Failure(CSRFError.FailedToFindURL.NSError)
}
// create current cookies
let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(headers, forURL: URL)
return .Success((token: csrf, cookies: cookies))
}
}
// MARK: - CSRF Errors
/// The errors that may occur while finding a CSRF token.
public enum CSRFError: Int, ErrorType
{
// MARK: - Errors
/// The `<head>` tag could not be found in the response.
case FailedToFindHead
/// The required `<meta>` tag could not be found in the response.
case FailedToFindMeta
/// The CSRF token could not be found in the response.
case FailedToFindCSRF
/// The headers could not be found in the response.
case FailedToFindHeaders
/// The URL could not be found in the response.
case FailedToFindURL
}
extension CSRFError: NSErrorConvertible
{
// MARK: - Error Domain
/// The error domain for `AuthenticationCSRFError` values.
public static var domain: String { return "PrettyOkay.AuthenticationCSRFError" }
}
extension CSRFError: UserInfoConvertible
{
// MARK: - User Info
/// A description of the error.
public var localizedDescription: String?
{
switch self
{
case FailedToFindHead: return "Failed to find “head” tag."
case FailedToFindMeta: return "Failed to find “meta” tag."
case FailedToFindCSRF: return "Failed to find CSRF token."
case FailedToFindHeaders: return "Failed to find headers."
case FailedToFindURL: return "Failed to find URL."
}
}
}
| isc | d9affc8c9a60fe43106fb67bf6cf2351 | 29.605096 | 99 | 0.673257 | 4.580553 | false | false | false | false |
RunningCharles/Arithmetic | src/10SumMListInNNum.swift | 1 | 369 | #!/usr/bin/swift
func printList(_ m: Int, _ n: Int , _ list: inout [Int]) {
if m == 0 && list.count > 0 {
print(list)
return
}
if m <= 0 || n <= 0 { return }
var list1 = list.map { $0 }
printList(m, n - 1, &list)
list1.append(n)
printList(m - n, n - 1, &list1)
}
var list:[Int] = []
printList(8, 10, &list)
| bsd-3-clause | 94a0475993ad6617f660d387dcabe8cf | 17.45 | 58 | 0.468835 | 2.753731 | false | false | false | false |
cwnidog/PhotoFilters | PhotoFilters/Thumbnail.swift | 1 | 1223 | //
// Thumbnail.swift
// PhotoFilters
//
// Created by John Leonard on 1/13/15.
// Copyright (c) 2015 John Leonard. All rights reserved.
//
import UIKit
class Thumbnail {
var originalImage: UIImage?
var filteredImage: UIImage?
var filterName: String
var imageQueue: NSOperationQueue
var gpuContext: CIContext
// need a real init()
init(filterName: String, operationQueue: NSOperationQueue, context: CIContext) {
self.filterName = filterName
self.imageQueue = operationQueue
self.gpuContext = context
} // init()
// does just what its name suggests
func generateFilteredImage() {
let startImage = CIImage(image: self.originalImage)
let filter = CIFilter(name: self.filterName)
// use default values for any keys that the filter may need
filter.setDefaults()
filter.setValue(startImage, forKey: kCIInputImageKey)
// apply the filters and get the filtered image
let result = filter.valueForKey(kCIOutputImageKey) as CIImage
let extent = result.extent()
let imageRef = self.gpuContext.createCGImage(result, fromRect: extent)
self.filteredImage = UIImage(CGImage: imageRef)
} // generateFilteredImage()
} // Thumbnail
| gpl-2.0 | b70067cb357f92cad8a3df2ac8f9dc0c | 26.795455 | 82 | 0.708913 | 4.463504 | false | false | false | false |
XeresRazor/SwiftNES | SwiftNES/util/Image/png/Reader.swift | 1 | 3042 | //
// Reader.swift
// SwiftNES
//
// Created by Articulate on 6/4/15.
// Copyright (c) 2015 DigitalWorlds. All rights reserved.
//
import Swift
// Color type
let ctGrayscale = 0
let ctTrueColor = 2
let ctPaletted = 3
let ctGrayscaleAlpha = 4
let ctTrueColorAlpha = 6
enum CB: Int {
case cbInvalid = 0, cbG1, cbG2, cbG4, cbG8, cbGA8, cbTC8, cbP1, cbP2, cbP4, cbP8, cbTCA8, cbG16, cbGA16, cbTC16, cbTCA16
}
// Filter type
let ftNone = 0
let ftSub = 1
let ftUp = 2
let ftAverage = 3
let ftPaeth = 4
let nFilter = 5
// Interlace Type
let itNone: UInt8 = 0
let itAdam7: UInt8 = 1
struct InterlaceScan {
var xFactor, yFactor, xOffset, yOffset: Int
init(_ xFactor: Int, _ yFactor: Int, _ xOffset: Int, _ yOffset: Int) {
self.xFactor = xFactor
self.yFactor = yFactor
self.xOffset = xOffset
self.yOffset = yOffset
}
}
let interlacing = [
InterlaceScan(8, 8, 0, 0),
InterlaceScan(8, 8, 4, 0),
InterlaceScan(4, 8, 0, 4),
InterlaceScan(4, 4, 2, 0),
InterlaceScan(2, 4, 0, 2),
InterlaceScan(2, 2, 1, 0),
InterlaceScan(1, 2, 0, 1),
]
enum DS: Int {
case dsStart = 0, dsSeenIHDR, dsSeenPLTE, dsSeenIDAT, dsSeenIEND
}
let pngHeader = "\u{89}PNG\r\n\u{1a}\n"
class FormatError: Error {
var string: String
init(string: String) {
self.string = string
}
func Error() -> String {
return "png: invalid format: " + self.string
}
}
class UnsupportedError: Error {
var string: String
init(string: String) {
self.string = string
}
func Error() -> String {
return "png: unsupported feature: " + self.string
}
}
let chunkOrderError = FormatError(string: "Chunk out of order")
struct decoder {
var r: Reader
var img: Image
var crc: Hash32
var width, height: Int
var depth: Int
// var palette: Palette
var cb: CB
var stage: DS
var idatLength: UInt32
var tmp = Array<UInt8>(count: 3 * 256, repeatedValue: 0)
var interlace: Int
mutating func parseIHDR(length: UInt32) -> Error? {
if length != 13 {
return FormatError(string: "bad IHDR length")
}
let (_, err) = ReadFull(self.r, self.tmp[0..<13])
if err != nil {
return err
}
self.crc.Write(self.tmp[0..<13])
if self.tmp[10] != 0 {
return UnsupportedError(string: "compresson method")
}
if self.tmp[11] != 0 {
return UnsupportedError(string: "filter method")
}
if self.tmp[12] != itNone && self.tmp[12] != itAdam7 {
return FormatError(string: "invalid interlace method")
}
self.interlace = Int(self.tmp[12])
let w = Int32(bigEndian:(Int32(self.tmp[0]) | Int32(self.tmp[1] << 8) | Int32(self.tmp[2] << 16) | Int32(self.tmp[3] << 24)))
return nil
}
}
func min(a: Int, b: Int) -> Int {
if a < b {
return a
}
return b
}
func PNGDecode(r: Reader) -> Image?
{
return nil
}
| mit | 2d5c8e6576cec47415cf73105ab7339e | 21.533333 | 133 | 0.584484 | 3.094608 | false | false | false | false |
qutheory/vapor | Sources/Vapor/Passwords/Application+Passwords.swift | 2 | 1154 | extension Application {
public var passwords: Passwords {
.init(application: self)
}
public struct Passwords {
public struct Provider {
let run: (Application) -> ()
public init(_ run: @escaping (Application) -> ()) {
self.run = run
}
}
struct Key: StorageKey {
typealias Value = Storage
}
let application: Application
public func use(_ provider: Provider) {
provider.run(self.application)
}
public func use(
_ makeVerifier: @escaping (Application) -> (PasswordHasher)
) {
self.storage.makeVerifier = makeVerifier
}
final class Storage {
var makeVerifier: ((Application) -> PasswordHasher)?
init() { }
}
var storage: Storage {
if let existing = self.application.storage[Key.self] {
return existing
} else {
let new = Storage()
self.application.storage[Key.self] = new
return new
}
}
}
}
| mit | 4d03f66fbfbe601364d6b57eabf64e8c | 24.086957 | 71 | 0.494801 | 5.221719 | false | false | false | false |
whiteshadow-gr/HatForIOS | HAT/Objects/Data Debits/HATDataDebitCreation.swift | 1 | 5479 | //
/**
* 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/
*/
// MARK: Struct
public struct HATDataDebitCreation: HATObject {
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `dataDebitKey` in JSON is `dataDebitKey`
* `dateCreated` in JSON is `dateCreated`
* `permissions` in JSON is `permissions`
* `requestClientName` in JSON is `requestClientName`
* `requestClientUrl` in JSON is `requestClientUrl`
* `requestClientLogoUrl` in JSON is `requestClientLogoUrl`
* `requestDescription` in JSON is `requestDescription`
* `requestApplicationId` in JSON is `requestApplicationId`
* `isActive` in JSON is `active`
* `isAccepted` in JSON is `accepted`
* `startDate` in JSON is `start`
* `endDate` in JSON is `end`
* `activePermissions` in JSON is `permissionsLatest`
* `latestPermissions` in JSON is `requestApplicationId`
*/
private enum CodingKeys: String, CodingKey {
case dataDebitKey = "dataDebitKey"
case purpose = "purpose"
case startDate = "start"
case period = "period"
case termsUrl = "termsUrl"
case willCancelAtPeriodsEnd = "cancelAtPeriodEnd"
case requestClientName = "requestClientName"
case requestClientUrl = "requestClientUrl"
case requestClientLogoUrl = "requestClientLogoUrl"
case requestApplicationId = "requestApplicationId"
case requestDescription = "requestDescription"
case conditions = "conditions"
case bundle = "bundle"
}
// MARK: - Variables
/// Technically the ID of the `Data Debit`
public var dataDebitKey: String = ""
/// A small description, its purpose, why it exists and what it does
public var purpose: String = ""
/// The stard date as an ISO format
public var startDate: String = ""
/// The duration of the `Data Debit` in seconds
public var period: Double = 0
/// The Terms and Conditions URL for the `Data Debit`
public var termsUrl: String = ""
/// A flag indicating if the the `Data Debit` will automatically be cancelled at the period's end
public var willCancelAtPeriodsEnd: Bool = false
/// The name of the client that created this `Data Debit`
public var requestClientName: String = ""
/// A URL, like a website, of the client that created this `Data Debit`
public var requestClientUrl: String = ""
/// The logo URL of the client that created this `Data Debit` in order to load the image
public var requestClientLogoUrl: String = ""
/// The Application ID, if the `Data Debit` is attached to one. Optional
public var requestApplicationId: String? = ""
/// A short description for the `Data Debit`. What this is and why it exists. Optinal, can be nil
public var requestDescription: String? = ""
/// Some `Data Debits` can have some conditions attached to them. For example all the search for a `String` or search for a number to be `between` 2 numbers. Optional
public var conditions: HATDataDefinition?
/// The bundle attached to this `Data Debit`. The bundle holds info about the urls and the specific fields that it wants access
public var bundle: HATDataDefinition = HATDataDefinition()
// MARK: - Initializers
/**
Initializing a `DataDebitCreationObject` from all the non optional values.
- parameter dataDebitKey: The ID of the `Data Debit`
- parameter purpose: A small description, its purpose, why it exists and what it does
- parameter start: The stard date as an ISO format
- parameter period: The duration of the `Data Debit` in seconds
- parameter termsUrl: The Terms and Conditions URL for the `Data Debit`
- parameter cancelAtPeriodEnd: A flag indicating if the the `Data Debit` will automatically be cancelled at the period's end
- parameter requestClientName: The name of the client that created this `Data Debit`
- parameter requestClientUrl: A URL, like a website, of the client that created this `Data Debit`
- parameter requestClientLogoUrl: The logo URL of the client that created this `Data Debit` in order to load the image
- parameter bundle: The bundle attached to this `Data Debit`. The bundle holds info about the urls and the specific fields that it wants access
*/
public init(dataDebitKey: String, purpose: String, start: String, period: Double, termsUrl: String, cancelAtPeriodEnd: Bool, requestClientName: String, requestClientUrl: String, requestClientLogoUrl: String, bundle: HATDataDefinition) {
self.dataDebitKey = dataDebitKey
self.purpose = purpose
self.startDate = start
self.period = period
self.termsUrl = termsUrl
self.willCancelAtPeriodsEnd = cancelAtPeriodEnd
self.requestClientName = requestClientName
self.requestClientUrl = requestClientUrl
self.requestClientLogoUrl = requestClientLogoUrl
self.bundle = bundle
}
/**
Initializing an empty `DataDebitCreationObject`
*/
public init() {
}
}
| mpl-2.0 | 6b41198420515f717c4addae1e522507 | 44.280992 | 240 | 0.686074 | 4.351867 | false | false | false | false |
realm/SwiftLint | Source/SwiftLintFramework/Extensions/NSRegularExpression+SwiftLint.swift | 1 | 1769 | import Foundation
import SourceKittenFramework
private var regexCache = [RegexCacheKey: NSRegularExpression]()
private let regexCacheLock = NSLock()
private struct RegexCacheKey: Hashable {
let pattern: String
let options: NSRegularExpression.Options
func hash(into hasher: inout Hasher) {
hasher.combine(pattern)
hasher.combine(options.rawValue)
}
}
extension NSRegularExpression {
internal static func cached(pattern: String, options: Options? = nil) throws -> NSRegularExpression {
let options = options ?? [.anchorsMatchLines, .dotMatchesLineSeparators]
let key = RegexCacheKey(pattern: pattern, options: options)
regexCacheLock.lock()
defer { regexCacheLock.unlock() }
if let result = regexCache[key] {
return result
}
let result = try NSRegularExpression(pattern: pattern, options: options)
regexCache[key] = result
return result
}
internal func matches(in stringView: StringView,
options: NSRegularExpression.MatchingOptions = []) -> [NSTextCheckingResult] {
return matches(in: stringView.string, options: options, range: stringView.range)
}
internal func matches(in stringView: StringView,
options: NSRegularExpression.MatchingOptions = [],
range: NSRange) -> [NSTextCheckingResult] {
return matches(in: stringView.string, options: options, range: range)
}
internal func matches(in file: SwiftLintFile,
options: NSRegularExpression.MatchingOptions = []) -> [NSTextCheckingResult] {
return matches(in: file.stringView.string, options: options, range: file.stringView.range)
}
}
| mit | 0fbf7c12eafcd001c21130a84350601e | 36.638298 | 105 | 0.665348 | 5.202941 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.