repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
SoySauceLab/CollectionKit | Examples/CollectionKitExamples/Supporting Files/SquareView.swift | 1 | 692 | //
// SquareView.swift
// CollectionKitExample
//
// Created by Luke Zhao on 2018-06-09.
// Copyright © 2018 lkzhao. All rights reserved.
//
import UIKit
class SquareView: DynamicView {
let textLabel = UILabel()
var text: String? {
get { return textLabel.text }
set { textLabel.text = newValue }
}
public override init(frame: CGRect) {
super.init(frame: frame)
layer.cornerRadius = 4
textLabel.textColor = .white
textLabel.textAlignment = .center
addSubview(textLabel)
}
public required init?(coder aDecoder: NSCoder) {
fatalError()
}
override func layoutSubviews() {
super.layoutSubviews()
textLabel.frame = bounds
}
}
| mit | 543e116f1524e2b18009b1d30421d40d | 17.184211 | 50 | 0.668596 | 3.99422 | false | false | false | false |
angmu/SwiftPlayCode | swift练习/swift基础学习.playground/section-1.swift | 1 | 776 | // Playground - noun: a place where people can play
import Foundation
//var age = 23
let pi = 3.14
print("hello World!")
let a = 20
let b = 3.14
let c = a + Int(b)
if a > 10 {
print("a大于10!")
} else {
print("a小于10!")
}
let score = 87
if score < 60 {
print("不及格")
} else if score <= 70 {
print("及格")
} else if score <= 80 {
print("良好")
} else if score <= 90 {
print("优秀")
} else {
print("完美")
}
let age = 21
let result = age > 18 ? "可以上网" : "回家去"
func online(age : Int) -> Void {
guard age >= 18 else {
// 判断语句为假,会执行else
print("回家去")
return
}
// 如果为真,继续执行
print("可以上网")
}
online(age:23)
| mit | 746fc9a0a968e2391e26e15508e50de9 | 11.290909 | 51 | 0.52071 | 2.714859 | false | false | false | false |
ECP-CANDLE/Supervisor | workflows/async-search/obj_folder/obj_app.swift | 1 | 1984 |
// OBJ APP
() obj(string params, string run_id, int dest) {
string template = """
from __future__ import print_function
import datetime
# template args
params = '''%s'''
runid = "%s"
destination = %i
model_sh = "%s"
outdir = "%s"
num_turbine_workers = %i
import json
from mpi4py import MPI
import subprocess, sys
import os
# Init
try:
newgroup
except NameError:
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
#print("orig rank: " + str(rank))
group = comm.Get_group()
# Assumes only one adlb_server
newgroup = group.Excl([num_turbine_workers])
newcomm = comm.Create_group(newgroup,1)
rank = newcomm.Get_rank()
#print("new rank: " + str(rank))
# Call
bash = '/bin/bash'
cmd = [bash,model_sh,"keras","{}".format(params), runid]
print('{} subprocess start: {}'.format(runid, str(datetime.datetime.now())))
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
#print("just launched cmd: " + ":".join(cmd))
out,err = p.communicate()
#print("out: ", out)
#print("err: ", err)
#rc = p.returncode
#print("rc: ", rc)
print('{} subprocess end: {}'.format(runid, str(datetime.datetime.now())))
# Collect
result_file = outdir + "/result.txt"
if os.path.exists(result_file):
with open(result_file) as f:
pvalstring = f.read().strip()
else:
pvalstring = "NaN"
pval = float(pvalstring)
# Send
resDict = {}
resDict['cost'] = pval
resDict['x'] = params.strip()
newcomm.send(resDict, dest=destination)
result = str(pval)
""";
printf("params variable is: " + params);
string model_sh = getenv("MODEL_SH");
string turbine_output = getenv("TURBINE_OUTPUT");
string outdir = "%s/run/%s" % (turbine_output, run_id);
# Note: currently framework is hardcoded to "keras"
int num_turbine_workers = turbine_workers();
string code = template % (params, run_id, dest, model_sh, outdir, num_turbine_workers);
string res = python_persist(code, "result");
printf("obj() result: " + res + " (for params: " + params +")");
}
| mit | ab53811d7cb4a21fcae78fb0dec4dc6a | 23.195122 | 89 | 0.65625 | 2.926254 | false | false | false | false |
anilkumarbp/ringcentral-swiftv2.0 | src/src/Platform/Auth.swift | 2 | 6142 | //
// Auth.swift
// src
//
// Created by Anil Kumar BP on 1/21/16.
// Copyright © 2016 Anil Kumar BP. All rights reserved.
//
import Foundation
/// Authorization object for the platform.
public class Auth {
static let MAINCOMPANY = "101"
// Authorization information
var token_type: String?
var access_token: String?
var expires_in: Double = 0
var expire_time: Double = 0
var refresh_token: String?
var refresh_token_expires_in: Double = 0
var refresh_token_expire_time: Double = 0
var scope: String?
var owner_id: String?
/// Constructor for the Auth Object
///
/// - parameter appKey: The appKey of your app
/// - parameter appSecet: The appSecret of your app
/// - parameter server: Choice of PRODUCTION or SANDBOX
public init() {
self.token_type = nil
self.access_token = nil
self.expires_in = 0
self.expire_time = 0
self.refresh_token = nil
self.refresh_token_expires_in = 0
self.refresh_token_expire_time = 0
self.scope = nil
self.owner_id = nil
}
/// func setData()
///
/// - parameter data: Dictionary of Data from the ApiResposne ( token information )
/// @response: Auth Instance of Auth class
public func setData(data: Dictionary<String, AnyObject>) -> Auth {
if data.count < 0 {
return self
}
// Misc
if let token_type = data["token_type"] as? String {
self.token_type = token_type
}
if let owner_id = data["owner_id"] as? String {
self.owner_id = owner_id
}
if let scope = data["scope"] as? String {
self.scope = scope
}
// Access Token
if let access_token = data["access_token"] as? String {
self.access_token = access_token
}
if let expires_in = data["expires_in"] as? Double {
self.expires_in = expires_in
}
if data["expire_time"] == nil {
if data["expires_in"] != nil {
let time = NSDate().timeIntervalSince1970
self.expire_time = time + self.expires_in
}
} else if let expire_time = data["expire_time"] as? Double {
self.expire_time = expire_time
}
// Refresh Token
if let access_token = data["refresh_token"] as? String {
self.refresh_token = access_token
}
if let refresh_token_expires_in = data["refresh_token_expires_in"] as? Double {
self.refresh_token_expires_in = refresh_token_expires_in
}
if data["refresh_token_expire_time"] == nil {
if data["refresh_token_expires_in"] != nil {
let time = NSDate().timeIntervalSince1970
self.refresh_token_expire_time = time + self.refresh_token_expires_in
}
} else if let refresh_token_expire_time = data["refresh_token_expire_time"] as? Double {
self.refresh_token_expire_time = refresh_token_expire_time
}
return self
}
/// Reset the authentication data.
///
/// func reset()
/// @response: Void
public func reset() -> Void {
self.token_type = " ";
self.access_token = "";
self.expires_in = 0;
self.expire_time = 0;
self.refresh_token = "";
self.refresh_token_expires_in = 0;
self.refresh_token_expire_time = 0;
self.scope = "";
self.owner_id = "";
// return self
}
/// Return the authnetication data
///
/// func data()
/// @response: Return a list of authentication data ( List of Token Information )
public func data()-> [String: AnyObject] {
var data: [String: AnyObject] = [:]
data["token_type"]=self.token_type
data["access_token"]=self.access_token
data["expires_in"]=self.expires_in
data["expire_time"]=self.expire_time
data["refresh_token"]=self.refresh_token
data["refresh_token_expires_in"]=self.refresh_token_expires_in
data["refresh_token_expire_time"]=self.refresh_token_expire_time
data["scope"]=self.scope
data["owner_id"]=self.owner_id
return data
}
/// Checks whether or not the access token is valid
///
/// - returns: A boolean for validity of access token
public func isAccessTokenValid() -> Bool {
let time = NSDate().timeIntervalSince1970
if(self.expire_time > time) {
return true
}
return false
}
/// Checks for the validity of the refresh token
///
/// - returns: A boolean for validity of the refresh token
public func isRefreshTokenVald() -> Bool {
return false
}
/// Returns the 'access token'
///
/// - returns: String of 'access token'
public func accessToken() -> String {
return self.access_token!
}
/// Returns the 'refresh token'
///
/// - returns: String of 'refresh token'
public func refreshToken() -> String {
return self.refresh_token!
}
/// Returns the 'tokenType'
///
/// - returns: String of 'token Type'
public func tokenType() -> String {
return self.token_type!
}
/// Returns bool if 'accessTokenValid'
///
/// - returns: Bool if 'access token valid'
public func accessTokenValid() -> Bool {
let time = NSDate().timeIntervalSince1970
if self.expire_time > time {
return true
}
return false
}
/// Returns bool if 'refreshTokenValid'
///
/// - returns: String of 'refresh token valid'
public func refreshTokenValid() -> Bool {
let time = NSDate().timeIntervalSince1970
if self.refresh_token_expire_time > time {
return true
}
return false
}
}
| mit | 41950e68970d1997fee3706acedb0429 | 28.242857 | 97 | 0.549259 | 4.333804 | false | false | false | false |
DevHospital/GenericUI | GenericUI/TableView/DataSources/SimpleTableViewDataSource.swift | 1 | 1071 | //
// SimpleTableViewDataSource.swift
// GenericUI
//
// Created by Jakub Gert on 18.10.2015.
// Copyright © 2015 Dev-Hospital. All rights reserved.
//
import Foundation
import UIKit
public class SimpleTableViewDataSource<Cell: protocol<CellIdentifiable, ItemPresentable> where Cell: UITableViewCell>: TableViewDataSource {
let tableView: UITableView
var _items:[Cell.Item] = []
public var items:[Cell.Item] {
return _items
}
public required init( tableView: UITableView ) {
self.tableView = tableView
}
public func numberOfSections() -> Int {
return 1
}
public func numberOfRowsInSection( section: Int )->Int {
return items.count
}
public func cellForRowForIndexPath( indexPath: NSIndexPath )->UITableViewCell {
let cell:Cell = tableView.dequeueReusableCell(indexPath)
let item = items[indexPath.row]
cell.presentItem(item)
return cell
}
public func setItems(items:[Cell.Item]) {
_items = items
}
}
| mit | 3658c6f62cd22e4f595cc0da9b677b67 | 23.318182 | 140 | 0.648598 | 4.713656 | false | false | false | false |
cinco-interactive/BluetoothKit | Example/Vendor/CryptoSwift/CryptoSwiftTests/PaddingTests.swift | 3 | 1453 | //
// PaddingTests.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 27/12/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
import XCTest
@testable import CryptoSwift
final class PaddingTests: XCTestCase {
func testPKCS7_0() {
let input:[UInt8] = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6]
let expected:[UInt8] = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16]
let padded = PKCS7().add(input, blockSize: 16)
XCTAssertEqual(padded, expected, "PKCS7 failed")
let clean = PKCS7().remove(padded, blockSize: nil)
XCTAssertEqual(clean, input, "PKCS7 failed")
}
func testPKCS7_1() {
let input:[UInt8] = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5]
let expected:[UInt8] = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,1]
let padded = PKCS7().add(input, blockSize: 16)
XCTAssertEqual(padded, expected, "PKCS7 failed")
let clean = PKCS7().remove(padded, blockSize: nil)
XCTAssertEqual(clean, input, "PKCS7 failed")
}
func testPKCS7_2() {
let input:[UInt8] = [1,2,3,4,5,6,7,8,9,0,1,2,3,4]
let expected:[UInt8] = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,2,2]
let padded = PKCS7().add(input, blockSize: 16)
XCTAssertEqual(padded, expected, "PKCS7 failed")
let clean = PKCS7().remove(padded, blockSize: nil)
XCTAssertEqual(clean, input, "PKCS7 failed")
}
}
| mit | a8c94b9dda6bf5a914d2717e3ae38737 | 37.236842 | 112 | 0.596696 | 2.715888 | false | true | false | false |
ConradoMateu/Swift-Basics | Basic/Protocols.playground/Contents.swift | 1 | 1021 | // Playground - noun: a place where people can play
import UIKit
// A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.
// Any type that satisfies the requirements of a protocol is said to conform to that protocol.
protocol ExampleProtocol {
var simpleDescription: String { get }
func adjust()
}
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class. "
var anotherProperty: Int = 69394
func adjust() {
simpleDescription += "Now 100% adjusted."
}
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
class SimpleClass2: ExampleProtocol {
var simpleDescription: String = "Another simple class. "
func adjust() {
simpleDescription += "Adjusted"
}
}
var protocolArray: [ExampleProtocol] = [SimpleClass(),SimpleClass(),SimpleClass2()]
for instace in protocolArray{
instace.adjust()
}
protocolArray
| apache-2.0 | 89cab80dc4b6033b0c77777bb1367d28 | 19.42 | 136 | 0.703232 | 4.517699 | false | false | false | false |
electricobjects/FeedKit | ExampleProject/ExampleProject/MockAPIService.swift | 2 | 3030 | //
// MockAPIService.swift
// ExampleProject
//
// Created by Rob Seward on 8/12/15.
// Copyright © 2015 Electric Objects. All rights reserved.
//
import Foundation
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
}
}
class MockAPIService {
static let sharedService = MockAPIService()
var mockFeed = [PeopleFeedItem]()
var refreshItems = [PeopleFeedItem]()
init(){
_initializeMockFeed()
startFeedUdpateSimulation()
}
fileprivate func _initializeMockFeed(){
if let path = Bundle.main.path(forResource: "name_list", ofType: "txt")
{
let url = URL(fileURLWithPath: path)
do {
var feedItems = [PeopleFeedItem]()
let fileContents = try NSString(contentsOf: url, encoding: String.Encoding.utf8.rawValue)
let list = fileContents.components(separatedBy: "\n")
var count = 1
for name in list {
let item = PeopleFeedItem(name: name, id: count)
feedItems.append(item)
count += 1
}
feedItems = feedItems.reversed()
let numRefreshItems = 100
refreshItems = Array(feedItems[0...numRefreshItems-1])
mockFeed = Array(feedItems[numRefreshItems...feedItems.count-1])
} catch let error as NSError {
assert(false, "There was a problem initializing the mock feed:\n\n \(error)")
}
}
}
func startFeedUdpateSimulation(){
_delay(2, closure: { [weak self]()->() in self?._updateFeed() })
}
fileprivate func _updateFeed(){
if refreshItems.count > 0 {
let item = refreshItems.removeLast()
mockFeed.insert(item, at: 0)
_delay(4, closure: { self._updateFeed() })
}
}
func fetchFeed(_ minId: Int?, maxId: Int?, count: Int, success:@escaping ([PeopleFeedItem])->()) {
if let minId = minId {
let maxId = maxId != nil ? maxId! : Int.max
let filteredResults = mockFeed.filter({$0.id < maxId && $0.id > minId})
let limit = min(filteredResults.count-1, count-1)
var truncatedResults = [PeopleFeedItem]()
if limit > 0 {
truncatedResults = Array(filteredResults[0...limit])
}
let delayTime = Double(arc4random_uniform(100)) / 100.0
_delay(delayTime, closure: { () -> () in
success(truncatedResults)
})
}
}
fileprivate func _delay(_ delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
}
| mit | 75e2603aebc8b8ef972e79f0ae65fa6f | 31.569892 | 128 | 0.543414 | 4.345768 | false | false | false | false |
darkzero/DZ_UIKit | DZ_UIKit/Classes/Categories/UIImage+Color.swift | 1 | 2374 | //
// UIImage+Color.swift
// DZ_UIKit
//
// Created by Dora.Yuan on 2014/10/08.
// Copyright (c) 2014 Dora.Yuan All rights reserved.
//
import UIKit
public enum GradientDirection: String {
case vertical = "vertical"
case horizontal = "horizontal"
}
extension UIImage {
/// Make image from color
public class func imageWithColor( _ color:UIColor, size: CGSize? = nil) -> UIImage {
var rect:CGRect
if let _size = size {
rect = CGRect(x: 0.0, y: 0.0, width: _size.width, height: _size.height)
}
else {
rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0);
}
UIGraphicsBeginImageContext(rect.size)
let context:CGContext = UIGraphicsGetCurrentContext()!
context.setFillColor(color.cgColor)
context.fill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
/// Make image with layer
///
/// - Parameter layer: layer
/// - Returns: Image(UIImage)
public class func imageWithLayer(layer: CALayer) -> UIImage {
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, 0);
layer.render(in: UIGraphicsGetCurrentContext()!)
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return outputImage!
}
/// Make image with gradient
/// default size is 64x64
///
/// - Parameters:
/// - direction: direction(GradientDirection.horizontal or .vertical
/// - colors: colors(CGColor)
/// - Returns: UIImage
public class func imageWithGradient(direction: GradientDirection = .horizontal, colors: CGColor...) -> UIImage {
let gradient = CAGradientLayer()
gradient.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: 64, height: 64))
gradient.colors = colors
switch direction {
case .horizontal:
gradient.startPoint = CGPoint(x: 0, y: 0.5)
gradient.endPoint = CGPoint(x: 1, y: 0.5)
case .vertical:
gradient.startPoint = CGPoint(x: 0.5, y: 0)
gradient.endPoint = CGPoint(x: 0.5, y: 1)
}
let outputImage = UIImage.imageWithLayer(layer: gradient);
return outputImage;
}
}
| mit | f407cc56e859e89dc8645a7be1b5a927 | 31.520548 | 116 | 0.611626 | 4.445693 | false | false | false | false |
zzBelieve/Hello_Swift | Hello Swift/Hello Swift/ViewController7.swift | 1 | 2948 | //
// ViewController7.swift
// Hello Swift
//
// Created by ZZBelieve on 15/8/24.
// Copyright (c) 2015年 galaxy-link. All rights reserved.
//
import UIKit
class ViewController7: UIViewController,UITableViewDataSource,UITableViewDelegate {
var carsGroup: NSMutableArray = ZZCargruop.carsGroup()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
let zzTableView: UITableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.Plain)
zzTableView.dataSource = self
zzTableView.delegate = self
self.view .addSubview(zzTableView)
// Do any additional setup after loading the view.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return carsGroup.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let cars: ZZCargruop = carsGroup[section] as! ZZCargruop
return cars.cars.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier: NSString = "car"
var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(identifier as String) as? UITableViewCell
if( cell==nil){
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: identifier as String)
}
let group: ZZCargruop = carsGroup[indexPath.section] as!ZZCargruop
let car: ZZCar = group.cars[indexPath.row] as! ZZCar
cell?.imageView?.image = UIImage(named: car.icon)
cell?.textLabel?.text = car.name
return cell!
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let group: ZZCargruop = carsGroup[section] as! ZZCargruop
return group.title
}
func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! {
let array: NSArray = carsGroup.valueForKeyPath("cars.name") as! NSArray
return carsGroup.valueForKeyPath("title") as! [AnyObject]
}
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 | aa7b41011d329251ceb59768f08f27a6 | 27.326923 | 122 | 0.625933 | 5.31769 | false | false | false | false |
superpixelhq/AbairLeat-iOS | Abair Leat/View Controllers/ContactsController.swift | 1 | 1664 | //
// ContactsController.swift
// Abair Leat
//
// Created by Aaron Signorelli on 27/11/2015.
// Copyright © 2015 Superpixel. All rights reserved.
//
import UIKit
import Firebase
//
// Lists the user's facebook friends. Tapping on a friend jumps to a conversation
//
class ContactsController: FirebaseTableViewController, FirebaseTableViewControllerDatasourceDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.datasourceDelegate = self
self.firebaseRef = AbairLeat.shared.contacts.myContactsRef()!.queryOrderedByPriority()
self.firebaseRef!.keepSynced(true)
}
// MARK: - FirebaseTableViewControllerDatasourceDelegate
// note the superclass will follow links in our datasource to only give us profiles here
func deserialise(snapshot: FDataSnapshot, callback: (Any) -> Void) {
let profile = snapshot.value as! NSDictionary
callback(Profile(firebaseSnapshot: profile))
}
func cellForRow(tableView: UITableView, indexPath: NSIndexPath, item: Any) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("contact_cell", forIndexPath: indexPath) as! ContactTableViewCell
cell.setup(item as! Profile)
return cell
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?, item: Any) {
let conversationController = segue.destinationViewController as! ConversationController
conversationController.hidesBottomBarWhenPushed = true
conversationController.conversationId = AbairLeat.shared.conversations.createOneToOneConversation((item as! Profile).id)
}
} | apache-2.0 | 628353de519e8150d391945906700108 | 36.818182 | 129 | 0.728202 | 5.009036 | false | false | false | false |
zakkhoyt/ColorPicKit | ColorPicKit/Classes/CMYKA.swift | 1 | 5261 | //
// CMYKA.swift
// Throw
//
// Created by Zakk Hoyt on 10/22/16.
// Copyright © 2016 Zakk Hoyt. All rights reserved.
//
import UIKit
public struct CMYKA {
public var cyan: CGFloat
public var magenta: CGFloat
public var yellow: CGFloat
public var black: CGFloat
public var alpha: CGFloat
public init(cyan: CGFloat, magenta: CGFloat, yellow: CGFloat, black: CGFloat, alpha: CGFloat) {
self.cyan = clip(cyan)
self.magenta = clip(magenta)
self.yellow = clip(yellow)
self.black = clip(black)
self.alpha = clip(alpha)
}
public init(cyan: CGFloat, magenta: CGFloat, yellow: CGFloat, black: CGFloat) {
self.init(cyan: cyan, magenta: magenta, yellow: yellow, black: black, alpha: 1.0)
}
public func description() -> String {
return "cyan: " + String(format: "%.2f", cyan) +
"magenta: " + String(format: "%.2f", magenta) +
"yellow: " + String(format: "%.2f", yellow) +
"black: " + String(format: "%.2f", black) +
"alpha: " + String(format: "%.2f", alpha)
}
public func color() -> UIColor {
let rgba = UIColor.cmykaToRGBA(cmyka: self)
return rgba.color()
}
// MARK: Converstions
public func rgba() -> RGBA {
return UIColor.cmykaToRGBA(cmyka: self)
}
public func hsba() -> HSBA {
return UIColor.cmykaToHSBA(cmyka: self)
}
public func hsla() -> HSLA {
let rgba = UIColor.cmykaToRGBA(cmyka: self)
let hsla = UIColor.rgbaToHSLA(rgba: rgba)
return hsla
}
// MARK: Static functions
public static func colorWith(cmyka: CMYKA) -> UIColor {
return cmyka.color()
}
}
extension CMYKA: ColorString {
public func stringFor(type: ColorStringType) -> String {
let format = type.format()
let factor = type.factor()
if type == .baseOne {
let cyanString = String(format: format, (cyan * factor))
let magentaString = String(format: format, (magenta * factor))
let yellowString = String(format: format, (yellow * factor))
let blackString = String(format: format, (black * factor))
let alphaString = String(format: format, (alpha * factor))
let cmykaString = "CMYKA: (\(cyanString), \(magentaString), \(yellowString), \(blackString), \(alphaString))"
return cmykaString
} else {
let cyanString = String(format: format, Int(cyan * factor))
let magentaString = String(format: format, Int(magenta * factor))
let yellowString = String(format: format, Int(yellow * factor))
let blackString = String(format: format, Int(black * factor))
let alphaString = String(format: format, Int(alpha * factor))
let cmykaString = "CMYKA: (\(cyanString), \(magentaString), \(yellowString), \(blackString), \(alphaString))"
return cmykaString
}
}
}
public extension UIColor {
// MARK: UIColor to self
public func cmyka() -> CMYKA {
let rgba = self.rgba()
return UIColor.rgbaToCMYKA(rgba: rgba)
}
// MARK: constructors
public convenience init(cmyka: CMYKA, alpha: CGFloat = 1.0) {
let rgba = UIColor.cmykaToRGBA(cmyka: cmyka)
self.init(red: rgba.red, green: rgba.green, blue: rgba.blue, alpha: rgba.alpha)
}
public class func colorWith(cmyka: CMYKA) -> UIColor {
return cmyka.color()
}
public class func colorWith(cyan: CGFloat, magenta: CGFloat, yellow: CGFloat, black: CGFloat, alpha: CGFloat) -> UIColor {
let cmyka = CMYKA(cyan: cyan, magenta: magenta, yellow: yellow, black: black, alpha: alpha)
let rgba = UIColor.cmykaToRGBA(cmyka: cmyka)
return UIColor.colorWith(rgba: rgba)
}
// http://www.rapidtables.com/convert/color/cmyk-to-rgb.htm
public class func cmykaToRGBA(cmyka: CMYKA) -> RGBA {
let red = (1.0 - cmyka.cyan) * (1.0 - cmyka.black)
let green = (1.0 - cmyka.magenta) * (1.0 - cmyka.black)
let blue = (1.0 - cmyka.yellow) * (1.0 - cmyka.black)
return RGBA(red: red, green: green, blue: blue, alpha: cmyka.alpha)
}
public class func cmykaToHSBA(cmyka: CMYKA) -> HSBA {
let rgba = UIColor.cmykaToRGBA(cmyka: cmyka)
let color = UIColor(red: rgba.red, green: rgba.green, blue: rgba.blue, alpha: rgba.alpha)
let hsba = color.hsba()
return hsba
}
public class func cmykaToHSLA(cmyka: CMYKA) -> HSLA {
let rgba = UIColor.cmykaToRGBA(cmyka: cmyka)
let hsla = UIColor.rgbaToHSLA(rgba: rgba)
return hsla
}
public class func cmykaToYUVA(cmyka: CMYKA) -> YUVA {
let rgba = UIColor.cmykaToRGBA(cmyka: cmyka)
let yuva = UIColor.rgbaToYUVA(rgba: rgba)
return yuva
}
}
extension UIImage {
public func cmykaPixels() -> [CMYKA] {
var pixels = [CMYKA]()
for rgba in self.rgbaPixels() {
let cmyka = rgba.cmyka()
pixels.append(cmyka)
}
return pixels
}
}
| mit | a73ce1027ed041fb48439e75a5b4fed0 | 30.497006 | 126 | 0.584411 | 3.640138 | false | false | false | false |
zmarvin/EnjoyMusic | Pods/Macaw/Source/svg/SVGParserRegexHelper.swift | 1 | 2155 | import Foundation
class SVGParserRegexHelper {
fileprivate static let transformAttributePattern = "([a-z]+)\\(((\\-?\\d+\\.?\\d*\\s*,?\\s*)+)\\)"
fileprivate static let transformPattern = "\\-?\\d+\\.?\\d*"
fileprivate static let textElementPattern = "<text.*?>((?s:.*))<\\/text>"
fileprivate static let maskIdenitifierPattern = "url\\(#((?s:.*))\\)"
fileprivate static var transformMatcher: NSRegularExpression?
fileprivate static var transformAttributeMatcher: NSRegularExpression?
fileprivate static var textElementMatcher: NSRegularExpression?
fileprivate static var maskIdenitifierMatcher: NSRegularExpression?
class func getTransformAttributeMatcher() -> NSRegularExpression? {
if self.transformAttributeMatcher == nil {
do {
self.transformAttributeMatcher = try NSRegularExpression(pattern: transformAttributePattern, options: .caseInsensitive)
} catch {
}
}
return self.transformAttributeMatcher
}
class func getTransformMatcher() -> NSRegularExpression? {
if self.transformMatcher == nil {
do {
self.transformMatcher = try NSRegularExpression(pattern: transformPattern, options: .caseInsensitive)
} catch {
}
}
return self.transformMatcher
}
class func getTextElementMatcher() -> NSRegularExpression? {
if self.textElementMatcher == nil {
do {
self.textElementMatcher = try NSRegularExpression(pattern: textElementPattern, options: .caseInsensitive)
} catch {
}
}
return self.textElementMatcher
}
class func getMaskIdenitifierMatcher() -> NSRegularExpression? {
if self.maskIdenitifierMatcher == nil {
do {
self.maskIdenitifierMatcher = try NSRegularExpression(pattern: maskIdenitifierPattern, options: .caseInsensitive)
} catch {
}
}
return self.maskIdenitifierMatcher
}
}
| mit | 64f332dc193485ff4346980c74f11cb9 | 35.525424 | 135 | 0.609281 | 5.441919 | false | false | false | false |
gregomni/swift | stdlib/public/Concurrency/AsyncPrefixWhileSequence.swift | 3 | 4621 | //===----------------------------------------------------------------------===//
//
// 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 Swift
@available(SwiftStdlib 5.1, *)
extension AsyncSequence {
/// Returns an asynchronous sequence, containing the initial, consecutive
/// elements of the base sequence that satisfy the given predicate.
///
/// Use `prefix(while:)` to produce values while elements from the base
/// sequence meet a condition you specify. The modified sequence ends when
/// the predicate closure returns `false`.
///
/// In this example, an asynchronous sequence called `Counter` produces `Int`
/// values from `1` to `10`. The `prefix(while:)` method causes the modified
/// sequence to pass along values so long as they aren’t divisible by `2` and
/// `3`. Upon reaching `6`, the sequence ends:
///
/// let stream = Counter(howHigh: 10)
/// .prefix { $0 % 2 != 0 || $0 % 3 != 0 }
/// for try await number in stream {
/// print("\(number) ", terminator: " ")
/// }
/// // prints "1 2 3 4 5"
///
/// - Parameter predicate: A closure that takes an element as a parameter and
/// returns a Boolean value indicating whether the element should be
/// included in the modified sequence.
/// - Returns: An asynchronous sequence of the initial, consecutive
/// elements that satisfy `predicate`.
@preconcurrency
@inlinable
public __consuming func prefix(
while predicate: @Sendable @escaping (Element) async -> Bool
) rethrows -> AsyncPrefixWhileSequence<Self> {
return AsyncPrefixWhileSequence(self, predicate: predicate)
}
}
/// An asynchronous sequence, containing the initial, consecutive
/// elements of the base sequence that satisfy a given predicate.
@available(SwiftStdlib 5.1, *)
public struct AsyncPrefixWhileSequence<Base: AsyncSequence> {
@usableFromInline
let base: Base
@usableFromInline
let predicate: (Base.Element) async -> Bool
@usableFromInline
init(
_ base: Base,
predicate: @escaping (Base.Element) async -> Bool
) {
self.base = base
self.predicate = predicate
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncPrefixWhileSequence: AsyncSequence {
/// The type of element produced by this asynchronous sequence.
///
/// The prefix-while sequence produces whatever type of element its base
/// iterator produces.
public typealias Element = Base.Element
/// The type of iterator that produces elements of the sequence.
public typealias AsyncIterator = Iterator
/// The iterator that produces elements of the prefix-while sequence.
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var predicateHasFailed = false
@usableFromInline
var baseIterator: Base.AsyncIterator
@usableFromInline
let predicate: (Base.Element) async -> Bool
@usableFromInline
init(
_ baseIterator: Base.AsyncIterator,
predicate: @escaping (Base.Element) async -> Bool
) {
self.baseIterator = baseIterator
self.predicate = predicate
}
/// Produces the next element in the prefix-while sequence.
///
/// If the predicate hasn't yet failed, this method gets the next element
/// from the base sequence and calls the predicate with it. If this call
/// succeeds, this method passes along the element. Otherwise, it returns
/// `nil`, ending the sequence.
@inlinable
public mutating func next() async rethrows -> Base.Element? {
if !predicateHasFailed, let nextElement = try await baseIterator.next() {
if await predicate(nextElement) {
return nextElement
} else {
predicateHasFailed = true
}
}
return nil
}
}
@inlinable
public __consuming func makeAsyncIterator() -> Iterator {
return Iterator(base.makeAsyncIterator(), predicate: predicate)
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncPrefixWhileSequence: @unchecked Sendable
where Base: Sendable,
Base.Element: Sendable { }
@available(SwiftStdlib 5.1, *)
extension AsyncPrefixWhileSequence.Iterator: @unchecked Sendable
where Base.AsyncIterator: Sendable,
Base.Element: Sendable { }
| apache-2.0 | 4cc7ee6622311c8878ae8b9f7432e0ce | 33.729323 | 80 | 0.665079 | 4.727738 | false | false | false | false |
MrPudin/Skeem | IOS/Prevoir/SKMDataController.swift | 1 | 22853 | //
// SKMDataController.swift
// Skeem
//
// Created by Zhu Zhan Yan on 17/10/16.
// Copyright © 2016 SSTInc. All rights reserved.
//
import UIKit
/*
* public class SKMDataController: NSObject
* - Defines an adaptor between the database and other objects
* - Suppliments functionality provided by database
*/
public class SKMDataController: NSObject
{
//Properties
public weak var DB:SKMDatabase! /* Links SKMDataController to Database
* NOTE: Will terminate execuable if Database is missing
*/
//Methods
/*
* init(db:SKMDatabase)
* [Argument]
* db - Data to link to
*/
init(db:SKMDatabase)
{
self.DB = db
super.init()
self.pruneTask()
self.pruneVoidDuration()
}
//Data
//Data - Tasks
/*
* public func pruneTask()
* - Remove all invaild tasks
*/
public func pruneTask()
{
for (name,task) in (self.DB.retrieveAllEntry(lockey: SKMDBKey.task) as! [String:SKMTask])
{
if task.vaild() == false
{
self.DB.deleteEntry(lockey: SKMDBKey.task, key: name)
}
}
}
/*
* public func updateTask()
* - Update tasks data for subsequent task for current date
*/
public func updateTask()
{
for (name,task) in (self.DB.retrieveAllEntry(lockey: SKMDBKey.task) as! [String:SKMTask])
{
task.update(date: NSDate()) //Update for current date/time
try! self.DB.updateEntry(locKey: SKMDBKey.task, key: name, val: task)
}
}
/*
* public func createOneshotTask(name:String,subject:String,description:String,deadline:NSDate,duration:Int) -> Bool
* - Create Single time Task
* [Argument]
* name - name of the task
* subject - subject of the task
* description - description of the task
* deadline - Date/Time that the task must be completed
* duration - Duration need in seconds to complete task
* duration_affinity - User desired subtask length
* [Return]
* Bool - true if successful in creating task, false otherwise
*/
public func createOneshotTask(name:String,subject:String,description:String,deadline:NSDate,duration:Int,duration_affinity:Int) -> Bool
{
let crt_task = SKMTask(name: name, deadline: deadline, duration: duration ,duration_affinity:duration_affinity, subject: subject,description:description)
do
{
try self.DB.createEntry(locKey: SKMDBKey.task, key: crt_task.name, val: crt_task)
}
catch SKMDBError.entry_exist
{
print("ERR:SKMDataController: Failed to Create task, entry already exists in database.")
return false
}
catch
{
abort()
}
return true
}
/*
* public func createRepeativeTask(name:String,subject:String,description:String,repeat_loop:[TimeInterval],duration:Int) -> Bool
* - Create Repeatable task
* [Argument]
* name - name of the task
* subject - subject of the task
* description - description of the task
* repeat_loop - a loop of intervals of time to increment for each repeat.
* deadline = nil - Date/Time repeat stops
* duration - Duration need in seconds to complete task
* duration_affinity - User desired subtask length
* [Return]
* Bool - true if successful in creating task, false otherwise
*/
public func createRepeativeTask(name:String,subject:String,description:String,repeat_loop:[TimeInterval],repeat_deadline:NSDate?=nil,duration:Int,duration_affinity:Int,deadline:NSDate) -> Bool
{
let crt_rttask = SKMRepeatTask(name: name, duration: duration,duration_affinity:duration_affinity, repeat_loop: repeat_loop, subject: subject,description:description,deadline:deadline,repeat_deadline:repeat_deadline)
do
{
try self.DB.createEntry(locKey: SKMDBKey.task, key: crt_rttask.name, val:crt_rttask)
}
catch SKMDBError.entry_exist
{
print("ERR:SKMDataController: Failed to create task, entry already exists in database.")
return false
}
catch
{
abort()
}
return true
}
/*
* public func updateOneshotTask(name:String,subject:String?=nil,description:String?=nil,deadline:NSDate?=nil,duration:Int?=nil,duration_affinity:Int?=nil) -> Bool
* - Updates oneshot task specified by name
* [Argument]
* name - name of the task
* subject - subject of the task
* description - description of the task
* deadline - Date/Time that the task must be completed
* duration - Duration need in seconds to complete task
* duration_affinity - User desired subtask length
* [Return]
* Bool - true if successful in creating task, false otherwise
*/
public func updateOneshotTask(name:String,subject:String?=nil,description:String?=nil,deadline:NSDate?=nil,duration:Int?=nil,duration_affinity:Int?=nil) -> Bool
{
var up_task:SKMTask!
//Obtain task
do
{
up_task = (try self.DB.retrieveEntry(lockey: SKMDBKey.task, key: name) as! SKMTask)
}
catch SKMDBError.entry_not_exist
{
print("ERR:SKMDataController: Failed to update task, entry does not exist in database")
return false
}
catch
{
abort()
}
//Update Task Data
if let sub = subject
{
up_task.subject = sub
}
if let descript = description
{
up_task.descript = descript
}
if let dl = deadline
{
up_task.deadline = dl
}
if let drt = duration
{
up_task.duration = drt
}
if let drt_aft = duration_affinity
{
up_task.duration_affinity = drt_aft
}
//Update DataBase
do
{
try self.DB.updateEntry(locKey: SKMDBKey.task, key: name, val: up_task)
}
catch
{
abort()
}
return true
}
/*
* public func updateRepeativeTask(name:String,subject:String?=nil,description:String?=nil,repeat_loop:[TimeInterval]?=nil,repeat_deadline:NSDate?=nil,duration:Int?=nil,duration_affinity:Int?=nil,deadline:NSDate?=nil) -> Bool
* - Update Repeative Task Data
* name - name of the task
* subject - subject of the task
* description - description of the task
* repeat_loop - a loop of intervals of time to increment for each repeat.
* deadline = nil - Date/Time repeat stops
* duration - Duration need in seconds to complete task
* duration_affinity - User desired subtask length
* [Return]
* Bool - true if successful in creating task, false otherwise
*/
public func updateRepeativeTask(name:String,subject:String?=nil,description:String?=nil,repeat_loop:[TimeInterval]?=nil,repeat_deadline:NSDate?=nil,duration:Int?=nil,duration_affinity:Int?=nil,deadline:NSDate?=nil) -> Bool
{
var up_task:SKMRepeatTask!
//Obtain task
do
{
up_task = (try self.DB.retrieveEntry(lockey: SKMDBKey.task, key: name) as! SKMRepeatTask)
}
catch SKMDBError.entry_not_exist
{
print("ERR:SKMDataController: Failed to update task, entry does not exist in database")
return false
}
catch
{
abort()
}
//Update Task Data
if let sub = subject
{
up_task.subject = sub
}
if let descript = description
{
up_task.descript = descript
}
if let dl = deadline
{
up_task.deadline = dl
}
if let drt = duration
{
up_task.duration = drt
}
if let drt_aft = duration_affinity
{
up_task.duration_affinity = drt_aft
}
if let rpt_lp = repeat_loop
{
up_task.repeat_loop = rpt_lp
}
if let rpt_dl = repeat_deadline
{
up_task.repeat_deadline = rpt_dl
}
//Update Database
do
{
try self.DB.updateEntry(locKey: SKMDBKey.task, key: name, val: up_task)
}
catch
{
abort()
}
return false
}
/*
* public func completeTask(name:String) -> Bool
* - Mark task specified by name as complete
* [Argument]
* name - name of the task to mark as complete
* [Return]
* Bool - true if successful in marking task as complete, false if task does not exist.
*/
public func completeTask(name:String) -> Bool
{
if let comp_task = try? (self.DB.retrieveEntry(lockey: SKMDBKey.task, key: name) as! SKMTask)
{
comp_task.complete()
return true
}
else
{
print("ERR:SKMDataController: Failed to complete task, task does not exists.")
return false
}
}
/*
* public func deleteTask(name:String) -> Bool
* - Deletes task specified by name
* [Argument]
* name - name of the task to delete
* [Return]
* Bool - true if successful in deleting task, false if task does not exist.
*/
public func deleteTask(name:String) -> Bool
{
if let del_task = try? (self.DB.retrieveEntry(lockey: SKMDBKey.task, key: name) as! SKMTask)
{
del_task.complete()
self.DB.deleteEntry(lockey: SKMDBKey.task, key: name)
return true
}
else
{
print("ERR:SKMDataController: Failed to delete task, Task does not exist.")
return false
}
}
/*
* public func updateTaskStatus(name:String,duration:Int,completion:Double) -> Bool
* - Reset task duration and completion to new values
* NOTE: Will terminate execuable if unknown database error occurs
* [Argument]
* name - name of the task
* duration - duration to reset to
* completion - completion to reset to
* [Return]
* Bool - true if successful in updating task, false if task does not exist.
*/
public func updateTaskStatus(name:String,duration:Int,completion:Double) -> Bool
{
if let up_task = try? (self.DB.retrieveEntry(lockey: SKMDBKey.task, key: name) as! SKMTask)
{
up_task.duration = duration
up_task.completion = completion
do
{
try self.DB.updateEntry(locKey: SKMDBKey.task, key: name, val: up_task)
}
catch
{
//Unknown Error
abort() //Terminates executable
}
return true
}
else
{
print("ERR:SKMDataController: Failed to update task, Task does not exist.")
return false
}
}
/*
* public func adjustTaskStatus(name:String, duration:Int, completion:Double) -> Bool
* - Admend Task duration and completion relative to current values
* NOTE: Will terminate executable if unknown database error occurs
* [Argument]
* name - Name of the task
* duration - duration to be added to the current duration
* completion - completion to added to the current duration
* [Return]
* Bool - true if successful in adjusting task, false if task does not exist.
*/
public func adjustTaskStatus(name:String, duration:Int, completion:Double) -> Bool
{
if let ad_task = try? (self.DB.retrieveEntry(lockey: SKMDBKey.task, key: name) as! SKMTask)
{
ad_task.duration += duration
ad_task.completion += completion
do
{
try self.DB.updateEntry(locKey: SKMDBKey.task,key: name, val: ad_task)
}
catch
{
//Unkown Error
abort() //Terminates executable
}
return true
}
else
{
print("ERR:SKMDataController: Failed to adjust task, Task does not exist.")
return false
}
}
/*
* public func sortedTask(sorder:SKMTaskSort) -> [SKMTask]
* - Sorts task based on specifed attribute
* NOTE: Will terminate executable if unknown database error occurs
* [Argument]
* sattr - Attribute to sort by
* [Return]
* Array<SKMTask] - Sorted Array of tasks
*/
public func sortedTask(sattr:SKMTaskSort) -> [SKMTask]
{
if let task = (self.DB.retrieveAllEntry(lockey:SKMDBKey.task) as? [String:SKMTask])?.values
{
switch sattr
{
case SKMTaskSort.name:
return task.sorted(by:SKMTaskSortFunc.name)
case SKMTaskSort.deadline:
return task.sorted(by:SKMTaskSortFunc.deadline)
case SKMTaskSort.duration:
return task.sorted(by:SKMTaskSortFunc.duration)
}
}
else
{
//Task is missing, should not happen
abort() //Terminates Executable
}
}
/*
* public func pruneVoidDuration()
* - Remove all invaild Void Duration
*/
public func pruneVoidDuration()
{
for (name,voidd) in (self.DB.retrieveAllEntry(lockey: SKMDBKey.void_duration) as! [String:SKMVoidDuration])
{
if voidd.vaild() == false
{
self.DB.deleteEntry(lockey: SKMDBKey.void_duration, key: name)
}
}
}
/*
* public func updateVoidDuration()
* - Update SKMVoidDuration data for current date
*/
public func updateVoidDuration()
{
for (name,voidd) in (self.DB.retrieveAllEntry(lockey: SKMDBKey.void_duration) as! [String:SKMVoidDuration])
{
voidd.update(date: NSDate()) //Update for current date/time
try? self.DB.updateEntry(locKey: SKMDBKey.void_duration, key: name, val: voidd)
}
}
/*
* public func createVoidDuration(name:String,duration:Int,asserted:Bool) -> Bool
* - Create single time void duration
* NOTE: Will terminate executable if unknown database error occurs
* [Argument]
* name - name of Void Duration
* begin - begin date/time of void duration
* duration - duration of void duration in seconds
* asserted - Whether void duration asserts to not have task scheduled during the "Duration of Time", true if void duration asserts
* [Return]
* Bool - true if successful in creating void duration, false if entry already exists in database.
*/
public func createVoidDuration(name:String,begin:NSDate,duration:Int,asserted:Bool) -> Bool
{
let crt_voidd = SKMVoidDuration(begin: begin, duration:duration , name: name, asserted: asserted)
do
{
try self.DB.createEntry(locKey: SKMDBKey.void_duration, key: crt_voidd.name, val: crt_voidd)
}
catch SKMDBError.entry_exist
{
print("ERR:SKMDataController: Failed to create void duration, entry already exists in database.")
return false
}
catch
{
abort()
}
return true
}
/*
* public func createRepeatVoidDuration(name:Stirn,duration:Int,repeat_loop:[TimeInterval],repeat_deadline:NSDate,asserted:Bool) -> Bool
* - Create Repeatable Void Duration
* NOTE: Will terminate executable if unknown database error occurs
* [Argument]
* name - name of the void duration
* begin - begin date/time of void duration
* duration - duration of void duration in seconds
* repeat_loop - a loop of intervals of time to increment for each repeat
* deadline - date/time to stop repeat
* asserted - Whether void duration asserts to not have task scheduled during the "Duration of Time", true if void duration asserts
* [Return]
* Bool - true if successful in creating void duration, false if entry already exists in database.
*/
public func createRepeatVoidDuration(name:String,begin:NSDate,duration:Int,repeat_loop:[TimeInterval],repeat_deadline:NSDate?,asserted:Bool) -> Bool
{
let crt_rptvoidd = SKMRepeatVoidDuration(begin: begin, duration: duration, name: name, repeat_loop: repeat_loop, deadline: repeat_deadline, asserted: asserted)
do
{
try self.DB.createEntry(locKey: SKMDBKey.void_duration, key: crt_rptvoidd.name, val: crt_rptvoidd)
}
catch SKMDBError.entry_exist
{
print("ERR:SKMDataController: Failed to create void duration, entry already exists in database.")
return false
}
catch
{
abort()
}
return true
}
/*
* public func updateVoidDuration(name:String,begin:NSDate?=nil,duration:Int?=nil,asserted:Bool?=nil) -> Bool
* - Update oneshot void duration
* NOTE: Will terminate executable if unknown database error occurs
* [Argument]
* name - name of Void Duration
* begin - begin date/time of void duration
* duration - duration of void duration in seconds
* asserted - Whether void duration asserts to not have task scheduled during the "Duration of Time", true if void duration asserts
* [Return]
* Bool - true if successful in creating void duration, false if entry already exists in database.
*/
public func updateVoidDuration(name:String,begin:NSDate?=nil,duration:Int?=nil,asserted:Bool?=nil) -> Bool
{
//Obtain Void Duration
var voidd:SKMVoidDuration!
do
{
voidd = (try self.DB.retrieveEntry(lockey: SKMDBKey.void_duration, key: name) as! SKMVoidDuration)
}
catch SKMDBError.entry_not_exist
{
print("ERR:SKMDataController: Faild to update void duration, entry does not exist in database.")
return false
}
catch
{
abort()
}
//Update Void Duration Data
if let bgn = begin
{
voidd.begin = bgn
}
if let drsn = duration
{
voidd.duration = drsn
}
if let asrt = asserted
{
voidd.asserted = asrt
}
//Update Database
do
{
try self.DB.updateEntry(locKey: SKMDBKey.void_duration, key: name, val: voidd)
}
catch
{
abort()
}
return true
}
/*
* public func updateRepeatVoidDuration(name:String,begin:NSDate?=nil,duration:Int?=nil,repeat_loop:[TimeInterval]?=nil,repeat_deadline:NSDate??=nil,asserted:Bool?=nil) -> Bool
* - Create Repeatable Void Duration
* NOTE: Will terminate executable if unknown database error occurs
* [Argument]
* name - name of the void duration
* begin - begin date/time of void duration
* duration - duration of void duration in seconds
* repeat_loop - a loop of intervals of time to increment for each repeat
* deadline - date/time to stop repeat
* asserted - Whether void duration asserts to not have task scheduled during the "Duration of Time", true if void duration asserts
* [Return]
* Bool - true if successful in creating void duration, false if entry already exists in database.
*/
public func updateRepeatVoidDuration(name:String,begin:NSDate?=nil,duration:Int?=nil,repeat_loop:[TimeInterval]?=nil,repeat_deadline:NSDate??=nil,asserted:Bool?=nil) -> Bool
{
//Obtain Void Duration
var voidd:SKMRepeatVoidDuration!
do
{
voidd = (try self.DB.retrieveEntry(lockey: SKMDBKey.void_duration, key: name) as! SKMRepeatVoidDuration)
}
catch SKMDBError.entry_not_exist
{
print("ERR:SKMDataController: Faild to update void duration, entry does not exist in database.")
return false
}
catch
{
abort()
}
//Update Void Duration Data
if let bgn = begin
{
voidd.begin = bgn
}
if let drsn = duration
{
voidd.duration = drsn
}
if let asrt = asserted
{
voidd.asserted = asrt
}
if let rpt_lp = repeat_loop
{
voidd.repeat_loop = rpt_lp
}
if let rpt_dl = repeat_deadline
{
voidd.repeat_deadline = rpt_dl
}
//Update Database
do
{
try self.DB.updateEntry(locKey: SKMDBKey.void_duration, key: name, val: voidd)
}
catch
{
abort()
}
return true
}
/*
* public func deleteVoidDuration(name:String) -> Bool
* - Deletes the void duration specifed by name
* [Argument]
* name - name of the void duration
* [Return]
* Bool - true if successful in deleting void duration, false if void duration does not exist.
*/
public func deleteVoidDuration(name:String) -> Bool
{
if let _ = try? (self.DB.retrieveEntry(lockey: SKMDBKey.void_duration, key: name) as! SKMVoidDuration)
{
self.DB.deleteEntry(lockey: SKMDBKey.void_duration, key: name)
return true
}
else
{
print("ERR:SKMDataController: Failed to delete void duration, void duration does not exist.")
return false
}
}
/*
* public func sortedVoidDuration(sattr:SKMVoidDurationSort) -> [SKMVoidDuration]
* - Sorts stored Void Duration based on specifed attribute
* NOTE: Will terminate executable if unknown database error occurs
* [Argument]
* sattr - Attriute to sort by
* [Return]
* Array<SKMVoidDuration> - Sorted array of Void Duration.
*/
public func sortedVoidDuration(sattr:SKMVoidDurationSort) -> [SKMVoidDuration]
{
if let voidd = (self.DB.retrieveAllEntry(lockey: SKMDBKey.void_duration) as? [String:SKMVoidDuration])?.values
{
switch sattr
{
case SKMVoidDurationSort.name:
return voidd.sorted(by: SKMVoidDurationSortFunc.name)
case SKMVoidDurationSort.begin:
return voidd.sorted(by: SKMVoidDurationSortFunc.begin)
}
}
else
{
//Void Duration is Missing, should not happen.
abort() //Terminates executable
}
}
}
| mit | a174b3ddfd36c84660ecbfcc24086c94 | 30.827298 | 229 | 0.592071 | 4.225592 | false | false | false | false |
nathanlea/CS4153MobileAppDev | WIA/MWAI1_Lea_Nathan/MWAI1_Lea_Nathan/ViewController.swift | 1 | 2095 | //
// ViewController.swift
// MWAI1_Lea_Nathan
//
// Created by Nathan on 10/1/15.
// Copyright © 2015 Okstate. All rights reserved.
//
/********************************
*
* IMAGE NOTICE:
* ALL IMAGES ARE TAKEN FROM
* geology.com
*
********************************/
import UIKit
class ViewController: UIViewController {
var stateName = ""
var stateImagePath = ""
@IBOutlet weak var StateImageView: UIImageView!
internal var imageURLString: String = "http://geology.com/state-map/maps/"
// Create the serial queue for our web access.
var webQueue = dispatch_queue_create("Web Queue", DISPATCH_QUEUE_SERIAL)
override func viewDidLoad() {
super.viewDidLoad()
self.title = stateName
//Instead of inflating app size we are going to just load these from the web!
//This method taken from Dr. Mayfield Sept 24 handout
// Create the NSURL object for the image path.
if let url = NSURL(string: imageURLString+stateImagePath+".gif") {
dispatch_async(webQueue) { () in
// This following "if let" is a blocking call!
if let data = NSData(contentsOfURL: url) {
// Now that we have successfully retrieved the image, we need to
// create a task on the main queue to populate the image view.
dispatch_async(dispatch_get_main_queue()) { () in
// Set the content mode of the image view.
self.StateImageView.contentMode = UIViewContentMode.ScaleAspectFit
// Convert the data to an image and populate the image view.
self.StateImageView.image = UIImage(data: data)
}
}
}
}
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | d647603f2b93ae613589cd85df6e5780 | 31.215385 | 90 | 0.570201 | 4.847222 | false | false | false | false |
primetimer/PrimeFactors | PrimeFactors/Classes/BitArray.swift | 1 | 1625 | //
// BitArray.swift
// PFactors
//
// Created by Stephan Jancar on 17.10.17.
//
import Foundation
public class BitArray {
let UIntInBits : UInt64 = UInt64(MemoryLayout<UInt64>.size * 8)
private (set) var count : UInt64 = 0
private (set) var countInts : UInt64 = 0
var bitarr : [UInt64] = []
public init(count:UInt64, initval : Bool = false) {
self.count = count
self.countInts = self.count / UIntInBits + 1
var mask : UInt64 = 0
if initval {
mask = ~0
}
self.bitarr = [UInt64] (repeating: mask, count: Int(countInts))
}
private func Index(bitnr: UInt64) -> (intIndex: UInt64, bitIndex: UInt64) {
let intindex = bitnr / UIntInBits
let bitIndex = bitnr % UIntInBits
return (intindex, bitIndex)
}
public func getBit(nr : UInt64) -> Bool {
let (intIndex,bitIndex) = Index(bitnr: nr)
let intval = bitarr[Int(intIndex)]
var mask : UInt64 = UInt64(1) << UInt64(bitIndex)
mask = mask & intval
return mask != 0
}
public func setBit(nr : UInt64, value : Bool) {
let (intIndex,bitIndex) = Index(bitnr: nr)
let mask : UInt64 = UInt64(1) << UInt64(bitIndex)
if value {
bitarr[Int(intIndex)] |= mask
} else {
bitarr[Int(intIndex)] &= ~mask
}
}
/// Provides random access to individual bits using square bracket noation.
/// The index must be less than the number of items in the bit array.
/// If you attempt to get or set a bit at a greater
/// index, you’ll trigger an error.
public subscript(index: Int) -> Bool {
get {
return getBit(nr: UInt64(index))
}
set {
setBit(nr: UInt64(index), value : newValue)
}
}
}
| mit | e3032ad8d59ae3fcf8ea845f750eb77c | 21.541667 | 76 | 0.645102 | 2.940217 | false | false | false | false |
ximximik/DPTableView | DPTableView/Classes/Sections.swift | 1 | 1217 | //
// Created by Danil Pestov on 06.12.16.
// Copyright (c) 2016 HOKMT. All rights reserved.
//
import RxSwift
import RxCocoa
import RxDataSources
//MARK: -
public protocol DPSectionItemProtocol: SectionModelType {
var header: String? { get }
var items: [Item] { get }
}
public struct DPSectionModel<Identity: Hashable, ItemType: IdentifiableType & Equatable>: DPSectionItemProtocol, AnimatableSectionModelType {
public typealias Item = ItemType
public var header: String?
public var items: [Item]
public var identity: Identity
public var hashValue: Int {
return self.identity.hashValue
}
public init(identity: Identity, header: String?, items: [ItemType]) {
self.identity = identity
self.header = header
self.items = items
}
public init(original: DPSectionModel<Identity, ItemType>, items: [ItemType]) {
self.identity = original.identity
self.header = original.header
self.items = items
}
}
//MARK: -
open class DPSectionHeader: UITableViewHeaderFooterView {
@IBOutlet private weak var titleLabel: UILabel!
func set(title: String?) {
titleLabel.text = title
}
}
| mit | 89f5aa38fc00005ae2569af412b17414 | 24.354167 | 141 | 0.671323 | 4.490775 | false | false | false | false |
Nickelfox/TemplateProject | ProjectFiles/Code/Helpers/UIView+Helper.swift | 1 | 1008 | //
// UIView+Helper.swift
// TemplateProject
//
// Created by Ravindra Soni on 18/12/16.
// Copyright © 2016 Nickelfox. All rights reserved.
//
import UIKit
extension UIView {
@IBInspectable var borderWidth: CGFloat {
get {
return 1.0
} set {
self.layer.borderWidth = newValue
}
}
@IBInspectable var borderColor: UIColor {
get {
return UIColor.black
} set {
self.layer.borderColor = newValue.cgColor
}
}
@IBInspectable var cornerRadius: CGFloat {
get {
return 1.0
} set {
self.layer.cornerRadius = newValue
self.layer.masksToBounds = true
}
}
func flipView() {
let transitionOptions: UIViewAnimationOptions = [.transitionFlipFromRight, .showHideTransitionViews]
UIView.transition(with: self, duration: 1.0, options: transitionOptions, animations: {
self.isHidden = true
}, completion: nil)
UIView.transition(with: self, duration: 1.0, options: transitionOptions, animations: {
self.isHidden = false
}, completion: nil)
}
}
| mit | fab5758a1e3a979b7bf6f413da55ad2a | 19.14 | 102 | 0.689176 | 3.508711 | false | false | false | false |
jpsim/Yams | Sources/Yams/Node.Sequence.swift | 1 | 4591 | //
// Node.Sequence.swift
// Yams
//
// Created by Norio Nomura on 2/24/17.
// Copyright (c) 2016 Yams. All rights reserved.
//
// MARK: Node+Sequence
extension Node {
/// Sequence node.
public struct Sequence {
private var nodes: [Node]
/// This node's tag (its type).
public var tag: Tag
/// The style to be used when emitting this node.
public var style: Style
/// The location for this node.
public var mark: Mark?
/// The style to use when emitting a `Sequence`.
public enum Style: UInt32 {
/// Let the emitter choose the style.
case any
/// The block sequence style.
case block
/// The flow sequence style.
case flow
}
/// Create a `Node.Sequence` using the specified parameters.
///
/// - parameter nodes: The array of nodes to generate this sequence.
/// - parameter tag: This sequence's `Tag`.
/// - parameter style: The style to use when emitting this `Sequence`.
/// - parameter mark: This sequence's `Mark`.
public init(_ nodes: [Node], _ tag: Tag = .implicit, _ style: Style = .any, _ mark: Mark? = nil) {
self.nodes = nodes
self.tag = tag
self.style = style
self.mark = mark
}
}
/// Get or set the `Node.Sequence` value if this node is a `Node.sequence`.
public var sequence: Sequence? {
get {
if case let .sequence(sequence) = self {
return sequence
}
return nil
}
set {
if let newValue = newValue {
self = .sequence(newValue)
}
}
}
}
// MARK: - Node.Sequence
extension Node.Sequence: Comparable {
/// :nodoc:
public static func < (lhs: Node.Sequence, rhs: Node.Sequence) -> Bool {
return lhs.nodes < rhs.nodes
}
}
extension Node.Sequence: Equatable {
/// :nodoc:
public static func == (lhs: Node.Sequence, rhs: Node.Sequence) -> Bool {
return lhs.nodes == rhs.nodes && lhs.resolvedTag == rhs.resolvedTag
}
}
extension Node.Sequence: Hashable {
/// :nodoc:
public func hash(into hasher: inout Hasher) {
hasher.combine(nodes)
hasher.combine(resolvedTag)
}
}
extension Node.Sequence: ExpressibleByArrayLiteral {
/// :nodoc:
public init(arrayLiteral elements: Node...) {
self.init(elements)
}
}
extension Node.Sequence: MutableCollection {
// Sequence
/// :nodoc:
public func makeIterator() -> Array<Node>.Iterator {
return nodes.makeIterator()
}
// Collection
/// :nodoc:
public typealias Index = Array<Node>.Index
/// :nodoc:
public var startIndex: Index {
return nodes.startIndex
}
/// :nodoc:
public var endIndex: Index {
return nodes.endIndex
}
/// :nodoc:
public func index(after index: Index) -> Index {
return nodes.index(after: index)
}
/// :nodoc:
public subscript(index: Index) -> Node {
get {
return nodes[index]
}
// MutableCollection
set {
nodes[index] = newValue
}
}
/// :nodoc:
public subscript(bounds: Range<Index>) -> Array<Node>.SubSequence {
get {
return nodes[bounds]
}
// MutableCollection
set {
nodes[bounds] = newValue
}
}
/// :nodoc:
public var indices: Array<Node>.Indices {
return nodes.indices
}
}
extension Node.Sequence: RandomAccessCollection {
// BidirectionalCollection
/// :nodoc:
public func index(before index: Index) -> Index {
return nodes.index(before: index)
}
// RandomAccessCollection
/// :nodoc:
public func index(_ index: Index, offsetBy num: Int) -> Index {
return nodes.index(index, offsetBy: num)
}
/// :nodoc:
public func distance(from start: Index, to end: Int) -> Index {
return nodes.distance(from: start, to: end)
}
}
extension Node.Sequence: RangeReplaceableCollection {
/// :nodoc:
public init() {
self.init([])
}
/// :nodoc:
public mutating func replaceSubrange<C>(_ subrange: Range<Index>, with newElements: C)
where C: Collection, C.Iterator.Element == Node {
nodes.replaceSubrange(subrange, with: newElements)
}
}
extension Node.Sequence: TagResolvable {
static let defaultTagName = Tag.Name.seq
}
| mit | de90ce9787f1b760d7a543702e681f6d | 24.364641 | 106 | 0.564801 | 4.335222 | false | false | false | false |
tgebarowski/SwiftySettings | Source/UI/SwitchCell.swift | 1 | 3629 | //
// SettingsSwitchCell.swift
//
// SwiftySettings
// Created by Tomasz Gebarowski on 07/08/15.
// Copyright © 2015 codica Tomasz Gebarowski <gebarowski at gmail.com>.
// All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import UIKit
class SwitchCell : SettingsCell {
var item: Switch!
let switchView = UISwitch()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
override func updateConstraints() {
if !didSetupConstraints {
switchView.translatesAutoresizingMaskIntoConstraints = false
// Spacing Between Title and Selected UISwitch
contentView.addConstraint(NSLayoutConstraint(
item: textLabel!,
attribute: .right,
relatedBy: .equal,
toItem: switchView,
attribute: .left,
multiplier: 1.0,
constant: -15))
// UISwitch Constraints
contentView.addConstraint(NSLayoutConstraint(item: contentView,
attribute: .centerY,
relatedBy: .equal,
toItem: switchView,
attribute: .centerY,
multiplier: 1.0,
constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: contentView,
attribute: .trailing,
relatedBy: .equal,
toItem: switchView,
attribute: .trailing,
multiplier: 1.0,
constant: 5))
}
super.updateConstraints()
}
override func setupViews() {
super.setupViews()
contentView.addSubview(switchView)
configureAppearance()
switchView.addTarget(self, action: #selector(SwitchCell.switchChanged(_:)), for: .valueChanged)
}
override func configureAppearance() {
super.configureAppearance()
switchView.tintColor = appearance?.tintColor
switchView.onTintColor = appearance?.tintColor
}
func load(_ item: Switch) {
super.load(item)
self.item = item
DispatchQueue.main.async(execute: {
self.switchView.setOn(item.value as Bool, animated: false)
})
setNeedsUpdateConstraints()
}
func switchChanged(_ sender: AnyObject) {
item.value = switchView.isOn
}
}
| mit | 76f30ce225985ce2e47d315995d0b788 | 31.981818 | 103 | 0.643054 | 5.117066 | false | false | false | false |
brentsimmons/Evergreen | Multiplatform/iOS/AppSettings.swift | 1 | 1957 | //
// AppSettings.swift
// Multiplatform iOS
//
// Created by Stuart Breckenridge on 1/7/20.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import Foundation
enum ColorPalette: Int, CustomStringConvertible, CaseIterable {
case automatic = 0
case light = 1
case dark = 2
var description: String {
switch self {
case .automatic:
return NSLocalizedString("Automatic", comment: "Automatic")
case .light:
return NSLocalizedString("Light", comment: "Light")
case .dark:
return NSLocalizedString("Dark", comment: "Dark")
}
}
}
class AppSettings: ObservableObject {
struct Key {
static let userInterfaceColorPalette = "userInterfaceColorPalette"
static let activeExtensionPointIDs = "activeExtensionPointIDs"
static let lastImageCacheFlushDate = "lastImageCacheFlushDate"
static let firstRunDate = "firstRunDate"
static let timelineGroupByFeed = "timelineGroupByFeed"
static let refreshClearsReadArticles = "refreshClearsReadArticles"
static let timelineNumberOfLines = "timelineNumberOfLines"
static let timelineIconSize = "timelineIconSize"
static let timelineSortDirection = "timelineSortDirection"
static let articleFullscreenAvailable = "articleFullscreenAvailable"
static let articleFullscreenEnabled = "articleFullscreenEnabled"
static let confirmMarkAllAsRead = "confirmMarkAllAsRead"
static let lastRefresh = "lastRefresh"
static let addWebFeedAccountID = "addWebFeedAccountID"
static let addWebFeedFolderName = "addWebFeedFolderName"
static let addFolderAccountID = "addFolderAccountID"
}
static let isDeveloperBuild: Bool = {
if let dev = Bundle.main.object(forInfoDictionaryKey: "DeveloperEntitlements") as? String, dev == "-dev" {
return true
}
return false
}()
static let isFirstRun: Bool = {
if let _ = AppDefaults.shared.object(forKey: Key.firstRunDate) as? Date {
return false
}
firstRunDate = Date()
return true
}()
}
| mit | 7d3a5bc823e80550ac400e2933042d48 | 26.166667 | 108 | 0.75409 | 4.206452 | false | false | false | false |
darrarski/SharedShopping-iOS | SharedShoppingApp/UI/Table/ViewControllers/TableViewController.swift | 1 | 3025 | import UIKit
import RxSwift
protocol TableViewControllerInputs {
var rowViewModels: Observable<[TableRowViewModel]> { get }
}
class TableViewController: UITableViewController {
enum Update {
case insert(row: Int, inSection: Int)
case delete(row: Int, inSection: Int)
}
init(style: UITableViewStyle, inputs: TableViewControllerInputs) {
self.inputs = inputs
super.init(style: style)
}
required init?(coder aDecoder: NSCoder) {
return nil
}
// MARK: View
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView(frame: .zero)
setupBindings()
}
// MARK: UITableViewDelegate
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return rowViewModels[indexPath.row].height
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return rowViewModels[indexPath.row].estimatedHeight
}
override func tableView(_ tableView: UITableView,
editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
return rowViewModels[indexPath.row].actions
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
rowViewModels[indexPath.row].didSelect()
}
// MARK: UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0: return rowViewModels.count
default: return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = rowViewModels[indexPath.row]
row.register(in: tableView)
return row.cell(at: indexPath, in: tableView)
}
// MARK: Private
private let inputs: TableViewControllerInputs
private let disposeBag = DisposeBag()
private var rowViewModels = [TableRowViewModel]() {
didSet {
let diff = oldValue.diff(rowViewModels) { $0.isEqual(to: $1) }
let updates = diff.elements.tableViewControllerUpdates(section: 0)
if !updates.isEmpty { handleUpdates(updates) }
}
}
private func setupBindings() {
inputs.rowViewModels
.subscribe(onNext: { [weak self] in self?.rowViewModels = $0 })
.disposed(by: disposeBag)
}
private func handleUpdates(_ updates: [Update]) {
tableView.beginUpdates()
updates.forEach { update in
switch update {
case let .insert(row, section):
tableView.insertRows(at: [IndexPath(row: row, section: section)], with: .automatic)
case let .delete(row, section):
tableView.deleteRows(at: [IndexPath(row: row, section: section)], with: .automatic)
}
}
tableView.endUpdates()
}
}
| mit | a1a546ccedc3b7fc34f924e6d0ad9bd5 | 29.867347 | 112 | 0.642975 | 5.058528 | false | false | false | false |
gautier-gdx/Hexacon | Example/Pods/Hexacon/Hexacon/HexagonalItemView.swift | 1 | 2885 | //
// HexagonalItemView.swift
// Hexacon
//
// Created by Gautier Gdx on 13/02/16.
// Copyright © 2016 Gautier. All rights reserved.
//
import UIKit
protocol HexagonalItemViewDelegate: class {
func hexagonalItemViewClikedOnButton(forIndex index: Int)
}
public class HexagonalItemView: UIImageView {
// MARK: - data
public init(image: UIImage, appearance: HexagonalItemViewAppearance) {
if appearance.needToConfigureItem {
let modifiedImage = image.roundImage(color: appearance.itemBorderColor, borderWidth: appearance.itemBorderWidth)
super.init(image: modifiedImage)
} else {
super.init(image: image)
}
}
public init(view: UIView) {
let image = view.roundImage()
super.init(image: image)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public var index: Int?
weak var delegate: HexagonalItemViewDelegate?
// MARK: - event methods
override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
guard let index = index else { return }
delegate?.hexagonalItemViewClikedOnButton(forIndex: index)
}
}
internal extension UIView {
func roundImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0)
guard let context = UIGraphicsGetCurrentContext() else { return UIImage() }
self.layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!.roundImage()
}
}
internal extension UIImage {
func roundImage(color: UIColor? = nil, borderWidth: CGFloat = 0) -> UIImage {
guard self.size != .zero else { return self }
let newImage = self.copy() as! UIImage
let cornerRadius = self.size.height/2
UIGraphicsBeginImageContextWithOptions(self.size, false, 1.0)
let bounds = CGRect(origin: CGPoint.zero, size: self.size)
let path = UIBezierPath(roundedRect: bounds.insetBy(dx: borderWidth / 2, dy: borderWidth / 2), cornerRadius: cornerRadius)
let context = UIGraphicsGetCurrentContext()
context!.saveGState()
// Clip the drawing area to the path
path.addClip()
// Draw the image into the context
newImage.draw(in: bounds)
context!.restoreGState()
// Configure the stroke
color?.setStroke()
path.lineWidth = borderWidth
// Stroke the border
path.stroke()
let finalImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return finalImage ?? UIImage()
}
}
| mit | fbe543f07f2be7c54c2eaed154a1beb5 | 28.428571 | 130 | 0.636616 | 4.888136 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/SpreadsheetView-master/Framework/Tests/CellTests.swift | 2 | 2634 | //
// CellTests.swift
// SpreadsheetView
//
// Created by Kishikawa Katsumi on 5/17/17.
// Copyright © 2017 Kishikawa Katsumi. All rights reserved.
//
import XCTest
@testable import SpreadsheetView
class CellTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testViewHierarchy() {
let cell = Cell()
XCTAssertNil(cell.backgroundView)
XCTAssertNil(cell.selectedBackgroundView)
XCTAssertEqual(cell.subviews, [cell.contentView])
let backgroundView = UIView()
cell.backgroundView = backgroundView
XCTAssertEqual(cell.subviews, [backgroundView, cell.contentView])
let selectedBackgroundView = UIView()
cell.selectedBackgroundView = selectedBackgroundView
XCTAssertEqual(cell.subviews, [backgroundView, selectedBackgroundView, cell.contentView])
cell.backgroundView = nil
XCTAssertEqual(cell.subviews, [selectedBackgroundView, cell.contentView])
cell.backgroundView = backgroundView
XCTAssertEqual(cell.subviews, [backgroundView, selectedBackgroundView, cell.contentView])
cell.backgroundView = nil
cell.selectedBackgroundView = nil
XCTAssertEqual(cell.subviews, [cell.contentView])
let view = UIView()
cell.addSubview(view)
XCTAssertEqual(cell.subviews, [cell.contentView, view])
cell.selectedBackgroundView = selectedBackgroundView
XCTAssertEqual(cell.subviews, [selectedBackgroundView, cell.contentView, view])
cell.backgroundView = backgroundView
XCTAssertEqual(cell.subviews, [backgroundView, selectedBackgroundView, cell.contentView, view])
}
func testHasBorder() {
let cell = Cell()
XCTAssertEqual(cell.borders.top, .none)
XCTAssertEqual(cell.borders.bottom, .none)
XCTAssertEqual(cell.borders.left, .none)
XCTAssertEqual(cell.borders.right, .none)
XCTAssertFalse(cell.hasBorder)
cell.borders.top = .solid(width: 1, color: .black)
XCTAssertTrue(cell.hasBorder)
cell.borders.top = .none
cell.borders.bottom = .solid(width: 1, color: .black)
XCTAssertTrue(cell.hasBorder)
cell.borders.bottom = .none
cell.borders.left = .solid(width: 1, color: .black)
XCTAssertTrue(cell.hasBorder)
cell.borders.left = .none
cell.borders.right = .solid(width: 1, color: .black)
XCTAssertTrue(cell.hasBorder)
cell.borders.right = .none
XCTAssertFalse(cell.hasBorder)
}
}
| mit | bc053b3070616b2d7aa6b86ea0c5db39 | 31.109756 | 103 | 0.672617 | 4.822344 | false | true | false | false |
goktugyil/EZSwiftExtensions | EZSwiftExtensionsTests/UIImageTests.swift | 1 | 647 | //
// UIImageTests.swift
// EZSwiftExtensions
//
// Created by Goktug Yilmaz on 8/25/16.
// Copyright © 2016 Goktug Yilmaz. All rights reserved.
//
#if os(iOS) || os(tvOS)
import XCTest
@testable import EZSwiftExtensions
class UIImageTests: XCTestCase {
func testBase64() {
let testBundle = Bundle(for: type(of: self))
let imageURL = testBundle.url(forResource: "charizard", withExtension: "jpg")
let dataImage = try? Data(contentsOf: imageURL!)
let image = UIImage(data: dataImage!)
let decodedData = Data(base64Encoded: image!.base64)
XCTAssertNotNil(decodedData)
}
}
#endif
| mit | fcb0683c127340816ade33b981fded50 | 23.846154 | 85 | 0.667183 | 3.939024 | false | true | false | false |
omarojo/MyC4FW | Pods/C4/C4/UI/Image+Generator.swift | 2 | 2200 | // Copyright © 2014 C4
//
// 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 QuartzCore
import UIKit
extension Image {
/// Applies a generator to the receiver's contents.
///
/// - parameter generator: a Generator
public func generate(_ generator: Generator) {
let crop = CIFilter(name: "CICrop")!
crop.setDefaults()
crop.setValue(CIVector(cgRect:CGRect(self.bounds)), forKey: "inputRectangle")
let generatorFilter = generator.createCoreImageFilter()
crop.setValue(generatorFilter.outputImage, forKey: "inputImage")
if var outputImage = crop.outputImage {
let scale = CGAffineTransform(scaleX: 1, y: -1)
outputImage = outputImage.applying(scale)
output = outputImage
//Need to output a CGImage that matches the current image's extent, {0, -h, w, h}
let cgimg = CIContext().createCGImage(self.output, from: outputImage.extent)
self.imageView.image = UIImage(cgImage: cgimg!)
_originalSize = Size(outputImage.extent.size)
} else {
print("Failed to generate outputImage: \(#function)")
}
}
}
| mit | 01f351926873b9e917b151bc4c85e7ee | 45.787234 | 93 | 0.701228 | 4.66879 | false | false | false | false |
tectijuana/patrones | Bloque1SwiftArchivado/PracticasSwift/NayeliFlores/Problema9.swift | 1 | 623 | //Instituto Tecnologico de Tijuana
//Departamento de sistemas y computacion
//Flores Ruiz Nayeli - - - - - No. Control: 13211411
//Materia - - - - - - - - Patrones de diseño
//Hora: - - - - - - - - 4:00 pm a 5:00pm
// Capitulo 6- Problema 13
print ("Imprimir los 25 primeros terminos de la secuencia 2,5,6,25,9,125")
print("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||")
//declaracion de variables
var tres=3
var cinco=5
var cont = 1
//ciclo for
for _ in 1...13 {
//calculo
var res3 = cont * tres
cont = cont + 1
cinco = cinco * 5
//impresion de resultados
print(res3, cinco)
} | gpl-3.0 | 65e70e1a449af7dea06841148a28f480 | 26.086957 | 87 | 0.569132 | 2.538776 | false | false | false | false |
huangboju/QMUI.swift | QMUI.swift/QMUIKit/UIKitExtensions/QMUISegmentedControl.swift | 1 | 5636 | //
// QMUISegmentedControl.swift
// QMUI.swift
//
// Created by 伯驹 黄 on 2017/5/10.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
/*
* QMUISegmentedControl,继承自 UISegmentedControl
* 如果需要更大程度地修改样式,比如说字体大小,选中的 segment 的文字颜色等等,可以使用下面的第一个方法来做
* QMUISegmentedControl 也同样支持使用图片来做样式,需要五张图片。
*/
public class QMUISegmentedControl: UISegmentedControl {
var _items: [Any]?
override init(items: [Any]?) {
super.init(items: items)
_items = items
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
_items = []
}
/**
* 重新渲染 UISegmentedControl 的 UI,可以比较大程度地修改样式。比如 tintColor,selectedTextColor 等等。
*
* @param tintColor Segmented 的 tintColor,作用范围包括字体颜色和按钮 border
* @param selectedTextColor Segmented 选中状态的字体颜色
* @param fontSize Segmented 上字体的大小
*/
func updateSegmentedUI(with tintColor: UIColor, selectedTextColor: UIColor, fontSize: UIFont) {
self.tintColor = tintColor
setTitleTextAttributes(with: tintColor, selectedTextColor: selectedTextColor, fontSize: fontSize)
}
/**
* 用图片而非 tintColor 来渲染 UISegmentedControl 的 UI
*
* @param normalImage Segmented 非选中状态的背景图
* @param selectedImage Segmented 选中状态的背景图
* @param devideImage00 Segmented 在两个没有选中按钮 item 之间的分割线
* @param devideImage01 Segmented 在左边没选中右边选中两个 item 之间的分割线
* @param devideImage10 Segmented 在左边选中右边没选中两个 item 之间的分割线
* @param textColor Segmented 的字体颜色
* @param selectedTextColor Segmented 选中状态的字体颜色
* @param fontSize Segmented 的字体大小
*/
func setBackground(with normalImage: UIImage, selectedImage: UIImage, devideImage00: UIImage, devideImage01: UIImage, devideImage10: UIImage, textColor: UIColor, selectedTextColor: UIColor, fontSize: UIFont) {
setTitleTextAttributes(with: textColor, selectedTextColor: selectedTextColor, fontSize: fontSize)
setBackground(with: normalImage, selectedImage: selectedImage, devideImage00: devideImage00, devideImage01: devideImage01, devideImage10: devideImage10)
}
private func setTitleTextAttributes(with textColor: UIColor, selectedTextColor: UIColor, fontSize: UIFont) {
setTitleTextAttributes([
NSAttributedString.Key.foregroundColor: textColor,
NSAttributedString.Key.font: fontSize,
], for: .normal)
setTitleTextAttributes([
NSAttributedString.Key.foregroundColor: selectedTextColor,
NSAttributedString.Key.font: fontSize,
], for: .selected)
}
private func setBackground(with normalImage: UIImage, selectedImage: UIImage, devideImage00: UIImage, devideImage01: UIImage, devideImage10: UIImage) {
let devideImageWidth = devideImage00.size.width
setBackgroundImage(normalImage.resizableImage(withCapInsets: UIEdgeInsets(top: 12, left: 20, bottom: 12, right: 20)), for: .normal, barMetrics: .default)
setBackgroundImage(selectedImage.resizableImage(withCapInsets: UIEdgeInsets(top: 12, left: 20, bottom: 12, right: 20)), for: .selected, barMetrics: .default)
setDividerImage(devideImage00.resizableImage(withCapInsets: UIEdgeInsets(top: 12, left: 20, bottom: 12, right: 20)), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
setDividerImage(devideImage10.resizableImage(withCapInsets: UIEdgeInsets(top: 12, left: devideImageWidth / 2, bottom: 12, right: devideImageWidth / 2)), forLeftSegmentState: .selected, rightSegmentState: .normal, barMetrics: .default)
setDividerImage(devideImage01.resizableImage(withCapInsets: UIEdgeInsets(top: 12, left: devideImageWidth / 2, bottom: 12, right: devideImageWidth / 2)), forLeftSegmentState: .normal, rightSegmentState: .selected, barMetrics: .default)
setContentPositionAdjustment(UIOffset(horizontal: -(12 - devideImageWidth) / 2, vertical: 0), forSegmentType: .left, barMetrics: .default)
setContentPositionAdjustment(UIOffset(horizontal: (12 - devideImageWidth) / 2, vertical: 0), forSegmentType: .right, barMetrics: .default)
}
// MARK: - Copy Items
public override func insertSegment(withTitle title: String?, at segment: Int, animated: Bool) {
super.insertSegment(withTitle: title, at: segment, animated: animated)
_items?.insert(title as Any, at: segment)
}
public override func insertSegment(with image: UIImage?, at segment: Int, animated: Bool) {
super.insertSegment(with: image, at: segment, animated: animated)
_items?.insert(image as Any, at: segment)
}
public override func removeSegment(at segment: Int, animated: Bool) {
super.removeSegment(at: segment, animated: animated)
_items?.remove(at: segment)
}
public override func removeAllSegments() {
super.removeAllSegments()
_items?.removeAll()
_items = nil
}
/// 获取当前的所有 segmentItem,可能包括 NSString 或 UIImage。
public var segmentItems: [Any]? {
return _items
}
}
| mit | 229208377c853eb48b8b22278e0cd18c | 46.220183 | 242 | 0.697105 | 4.510955 | false | false | false | false |
AlexIzh/SearchQueryParser | SearchQueryParser/SearchQueryParser/TokensGenerator.swift | 1 | 4586 | //
// TokensGenerator.swift
// SearchQueryParser
//
// Created by Alex Severyanov on 11/07/2017.
// Copyright © 2017 alexizh. All rights reserved.
//
import Foundation
class TokensGenerator {
struct Token {
enum Kind {
case validOpeningBrackets
case validClosingBrackets
case phrase
case `default`
}
let value: String
var type: Kind = .default
init(value: String, type: Kind = .default) {
self.value = value
self.type = type
}
}
struct Group {
let opening: Character
let closing: Character
}
var brackets = Group(opening: "(", closing: ")")
var phrases = Group(opening: "\"", closing: "\"")
func makeTokens(from string: String) -> [Token] {
var brackets: [Int] = []
var tokens: [Token] = []
var value = ""
var prevChar: Character?
func isStart(index: String.Index) -> Bool {
return prevChar == " " || prevChar == self.brackets.opening || index == string.startIndex
}
func isEnd(index: String.Index, nextIndex: String.Index?) -> Bool {
let nextChar = nextIndex.map { string[$0] }
return nextChar == " " || nextChar == self.brackets.closing || index == string.index(before: string.endIndex)
}
var index = string.startIndex
var nextIndex: String.Index?
func saveValue() {
tokens.append(Token(value: value))
value = ""
}
while index != string.endIndex {
let char = string[index]
nextIndex = string.index(after: index)
if nextIndex == string.endIndex {
nextIndex = nil
}
defer {
prevChar = char
if index != string.endIndex {
index = string.index(after: index)
}
}
guard char != " " else { saveValue(); continue }
// if it's valid opening phrase character
if phrases.opening == char && isStart(index: index) {
var phrase = ""
var newIndex = string.index(after: index)
var newChar: Character? = newIndex == string.endIndex ? nil : string[newIndex]
var nextIndex: String.Index? = newIndex != string.endIndex ? string.index(after: newIndex) : nil
if nextIndex == string.endIndex { nextIndex = nil }
while newIndex != string.endIndex && (newChar != phrases.closing || !isEnd(index: newIndex, nextIndex: nextIndex)) {
phrase += String(newChar!)
newIndex = string.index(after: newIndex)
if newIndex != string.endIndex {
newChar = string[newIndex]
nextIndex = string.index(after: newIndex)
if nextIndex == string.endIndex { nextIndex = nil }
}
}
if newChar == phrases.closing {
index = newIndex
tokens.append(Token(value: phrase, type: .phrase))
value = ""
continue
}
}
if self.brackets.opening == char && isStart(index: index) {
brackets.append(tokens.count+1)
saveValue()
tokens.append(Token(value: ""))
continue
}
if self.brackets.closing == char && isEnd(index: index, nextIndex: nextIndex) {
if let i = brackets.last {
tokens[i] = Token(value: String(self.brackets.opening), type: .validOpeningBrackets)
_ = brackets.popLast()
saveValue()
tokens.append(Token(value: String(char), type: .validClosingBrackets))
continue
}
}
value.append(char)
}
tokens.append(Token(value: value))
brackets.forEach { tokens[$0+1] = Token(value: "\(self.brackets.opening)" + tokens[$0+1].value) }
brackets.removeAll()
tokens = tokens.filter({ !$0.value.isEmpty })
return tokens
}
}
| mit | c66f9c630a447120c1d35b4b3620a4e6 | 33.216418 | 132 | 0.475463 | 5.210227 | false | false | false | false |
ahayman/RxStream | RxStreamTests/MiscTests.swift | 1 | 1441 | //
// MiscTests.swift
// RxStream
//
// Created by Aaron Hayman on 5/5/17.
// Copyright © 2017 Aaron Hayman. All rights reserved.
//
import XCTest
@testable import Rx
/// For testing misc objects that don't really need separate files
class MiscTests: XCTestCase {
func testTermination() {
XCTAssertEqual(Termination.completed, Termination.completed)
XCTAssertEqual(Termination.cancelled, Termination.cancelled)
XCTAssertEqual(Termination.error(TestError()), Termination.error(TestError()))
XCTAssertNotEqual(Termination.completed, Termination.cancelled)
XCTAssertNotEqual(Termination.completed, Termination.error(TestError()))
XCTAssertNotEqual(Termination.cancelled, Termination.error(TestError()))
}
func testDebug() {
let hot = HotInput<Int>()
var logs = [String]()
hot.debugPrinter = { logs.append($0) }
hot.push(0)
XCTAssertGreaterThan(logs.count, 0)
}
func testGlobalDebug() {
let hot = HotInput<Int>()
var logs = [String]()
Hot<Int>.debugPrinter = { logs.append($0) }
hot.push(0)
XCTAssertGreaterThan(logs.count, 0)
Hot<Int>.debugPrinter = nil
}
func testNamedDebug() {
let hot = HotInput<Int>().named("Custom Name")
XCTAssertEqual(hot.debugDescription, "Custom Name")
}
func testDesccriptor() {
let hot = HotInput<Int>()
hot.descriptor = "Custom Name"
XCTAssertEqual(hot.debugDescription, "Custom Name")
}
}
| mit | b0015ad4521b90b1e69428ac644e2473 | 24.714286 | 82 | 0.697222 | 4.033613 | false | true | false | false |
SuPair/firefox-ios | Client/Frontend/Browser/Authenticator.swift | 3 | 8301 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import Deferred
private let CancelButtonTitle = NSLocalizedString("Cancel", comment: "Label for Cancel button")
private let LogInButtonTitle = NSLocalizedString("Log in", comment: "Authentication prompt log in button")
private let log = Logger.browserLogger
class Authenticator {
fileprivate static let MaxAuthenticationAttempts = 3
static func handleAuthRequest(_ viewController: UIViewController, challenge: URLAuthenticationChallenge, loginsHelper: LoginsHelper?) -> Deferred<Maybe<LoginData>> {
// If there have already been too many login attempts, we'll just fail.
if challenge.previousFailureCount >= Authenticator.MaxAuthenticationAttempts {
return deferMaybe(LoginDataError(description: "Too many attempts to open site"))
}
var credential = challenge.proposedCredential
// If we were passed an initial set of credentials from iOS, try and use them.
if let proposed = credential {
if !(proposed.user?.isEmpty ?? true) {
if challenge.previousFailureCount == 0 {
return deferMaybe(Login.createWithCredential(credential!, protectionSpace: challenge.protectionSpace))
}
} else {
credential = nil
}
}
// If we have some credentials, we'll show a prompt with them.
if let credential = credential {
return promptForUsernamePassword(viewController, credentials: credential, protectionSpace: challenge.protectionSpace, loginsHelper: loginsHelper)
}
// Otherwise, try to look them up and show the prompt.
if let loginsHelper = loginsHelper {
return findMatchingCredentialsForChallenge(challenge, fromLoginsProvider: loginsHelper.logins).bindQueue(.main) { result in
guard let credentials = result.successValue else {
return deferMaybe(result.failureValue ?? LoginDataError(description: "Unknown error when finding credentials"))
}
return self.promptForUsernamePassword(viewController, credentials: credentials, protectionSpace: challenge.protectionSpace, loginsHelper: loginsHelper)
}
}
// No credentials, so show an empty prompt.
return self.promptForUsernamePassword(viewController, credentials: nil, protectionSpace: challenge.protectionSpace, loginsHelper: nil)
}
static func findMatchingCredentialsForChallenge(_ challenge: URLAuthenticationChallenge, fromLoginsProvider loginsProvider: BrowserLogins) -> Deferred<Maybe<URLCredential?>> {
return loginsProvider.getLoginsForProtectionSpace(challenge.protectionSpace) >>== { cursor in
guard cursor.count >= 1 else {
return deferMaybe(nil)
}
let logins = cursor.asArray()
var credentials: URLCredential? = nil
// It is possible that we might have duplicate entries since we match against host and scheme://host.
// This is a side effect of https://bugzilla.mozilla.org/show_bug.cgi?id=1238103.
if logins.count > 1 {
credentials = (logins.find { login in
(login.protectionSpace.`protocol` == challenge.protectionSpace.`protocol`) && !login.hasMalformedHostname
})?.credentials
let malformedGUIDs: [GUID] = logins.compactMap { login in
if login.hasMalformedHostname {
return login.guid
}
return nil
}
loginsProvider.removeLoginsWithGUIDs(malformedGUIDs).upon { log.debug("Removed malformed logins. Success :\($0.isSuccess)") }
}
// Found a single entry but the schemes don't match. This is a result of a schemeless entry that we
// saved in a previous iteration of the app so we need to migrate it. We only care about the
// the username/password so we can rewrite the scheme to be correct.
else if logins.count == 1 && logins[0].protectionSpace.`protocol` != challenge.protectionSpace.`protocol` {
let login = logins[0]
credentials = login.credentials
let new = Login(credential: login.credentials, protectionSpace: challenge.protectionSpace)
return loginsProvider.updateLoginByGUID(login.guid, new: new, significant: true)
>>> { deferMaybe(credentials) }
}
// Found a single entry that matches the scheme and host - good to go.
else {
credentials = logins[0].credentials
}
return deferMaybe(credentials)
}
}
fileprivate static func promptForUsernamePassword(_ viewController: UIViewController, credentials: URLCredential?, protectionSpace: URLProtectionSpace, loginsHelper: LoginsHelper?) -> Deferred<Maybe<LoginData>> {
if protectionSpace.host.isEmpty {
print("Unable to show a password prompt without a hostname")
return deferMaybe(LoginDataError(description: "Unable to show a password prompt without a hostname"))
}
let deferred = Deferred<Maybe<LoginData>>()
let alert: AlertController
let title = NSLocalizedString("Authentication required", comment: "Authentication prompt title")
if !(protectionSpace.realm?.isEmpty ?? true) {
let msg = NSLocalizedString("A username and password are being requested by %@. The site says: %@", comment: "Authentication prompt message with a realm. First parameter is the hostname. Second is the realm string")
let formatted = NSString(format: msg as NSString, protectionSpace.host, protectionSpace.realm ?? "") as String
alert = AlertController(title: title, message: formatted, preferredStyle: .alert)
} else {
let msg = NSLocalizedString("A username and password are being requested by %@.", comment: "Authentication prompt message with no realm. Parameter is the hostname of the site")
let formatted = NSString(format: msg as NSString, protectionSpace.host) as String
alert = AlertController(title: title, message: formatted, preferredStyle: .alert)
}
// Add a button to log in.
let action = UIAlertAction(title: LogInButtonTitle,
style: .default) { (action) -> Void in
guard let user = alert.textFields?[0].text, let pass = alert.textFields?[1].text else { deferred.fill(Maybe(failure: LoginDataError(description: "Username and Password required"))); return }
let login = Login.createWithCredential(URLCredential(user: user, password: pass, persistence: .forSession), protectionSpace: protectionSpace)
deferred.fill(Maybe(success: login))
loginsHelper?.setCredentials(login)
}
alert.addAction(action, accessibilityIdentifier: "authenticationAlert.loginRequired")
// Add a cancel button.
let cancel = UIAlertAction(title: CancelButtonTitle, style: .cancel) { (action) -> Void in
deferred.fill(Maybe(failure: LoginDataError(description: "Save password cancelled")))
}
alert.addAction(cancel, accessibilityIdentifier: "authenticationAlert.cancel")
// Add a username textfield.
alert.addTextField { (textfield) -> Void in
textfield.placeholder = NSLocalizedString("Username", comment: "Username textbox in Authentication prompt")
textfield.text = credentials?.user
}
// Add a password textfield.
alert.addTextField { (textfield) -> Void in
textfield.placeholder = NSLocalizedString("Password", comment: "Password textbox in Authentication prompt")
textfield.isSecureTextEntry = true
textfield.text = credentials?.password
}
viewController.present(alert, animated: true) { () -> Void in }
return deferred
}
}
| mpl-2.0 | b03478ad7fb4c035dbb9161c3f35c29d | 53.254902 | 227 | 0.661125 | 5.511952 | false | false | false | false |
Harvey-CH/TEST | v2exProject/v2exProject/Controller/NodesViewController.swift | 2 | 1801 | //
// NodesViewController.swift
// v2exProject
//
// Created by 郑建文 on 16/8/4.
// Copyright © 2016年 Zheng. All rights reserved.
//
import UIKit
import SnapKit
import ObjectMapper
class NodesViewController: UIViewController {
var tableView:UITableView = {
let table = UITableView(frame: CGRectZero, style: .Plain)
table.registerNib(UINib(nibName:"NodeCell",bundle: nil), forCellReuseIdentifier: "cell")
return table
}()
var array:Array<Node>?
override func viewDidLoad() {
super.viewDidLoad()
customUI()
fetchData()
}
func customUI() {
tableView.dataSource = self
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
view.addSubview(tableView)
tableView.snp_makeConstraints { (make) in
make.size.equalTo(self.view)
make.left.equalTo(self.view)
make.top.equalTo(self.view)
}
}
func fetchData() {
NetworkManager.sharedManager.fetchDataByAlamofire(NetAPI.Nodes,parameters: [:]) { (value) in
self.array = Mapper<Node>().mapArray(value)
self.tableView.reloadData()
}
}
}
extension NodesViewController:UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (array?.count) ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as? NodeCell
cell?.node = array![indexPath.row]
return cell!
}
}
| mit | 12a0572eabb034fd0d1959c4bc6b9fbb | 29.896552 | 109 | 0.655134 | 4.740741 | false | false | false | false |
Ryan-Korteway/GVSSS | GVBandwagon/GVBandwagon/RideToTableViewController.swift | 1 | 3628 | //
// RideToTableViewController.swift
// GVBandwagon
//
// Created by Nicolas Heady on 2/12/17.
// Copyright © 2017 Nicolas Heady. All rights reserved.
//
import UIKit
class RideToTableViewController: UITableViewController {
var rideDelegate: RideSceneDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var to = "Null"
if (indexPath.section == 0) {
to = "Allendale"
} else if (indexPath.section == 1) {
to = "Meijer"
} else if (indexPath.section == 2) {
to = "Downtown"
}
self.rideDelegate?.goingTo = to
self.rideDelegate?.onToViewTapped(Any.self)
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 06222e89f282d3905f138fc3a5eb37d5 | 31.972727 | 136 | 0.655914 | 5.108451 | false | false | false | false |
kaich/CKAlertView | CKAlertView/Classes/Core/CKAlertView+Custom.swift | 1 | 2067 | //
// CKAlertView+Custom.swift
// Pods
//
// Created by mac on 16/11/2.
//
//
import UIKit
extension CKAlertView {
/// 显示自定义的alert,将自定义的视图添加到headerView, bodyView上即可, footerView为默认的button列表,如果你想自定义按钮,请直接加在bodyView上。可以只添加到任意一个视图上
///
/// - parameter buildViewBlock: headerView 头部 ,bodyView 主体 ,footerView 尾部
public convenience init(title alertTitle: CKAlertViewStringable? = nil, cancelButtonTitle :CKAlertViewStringable? = nil, otherButtonTitles :[CKAlertViewStringable]? = nil, buildViewBlock:((_ bodyView :UIView) -> Void), completeBlock :(((Int) -> Void))? = nil) {
self.init(nibName: nil, bundle: nil)
dismissCompleteBlock = completeBlock
let componentMaker = CKAlertViewComponentCustomMaker()
componentMaker.alertView = self
componentMaker.alertTitle = alertTitle
componentMaker.cancelButtonTitle = cancelButtonTitle
componentMaker.otherButtonTitles = otherButtonTitles
installComponentMaker(maker: componentMaker)
buildViewBlock(self.bodyView)
}
}
class CKAlertViewComponentCustomMaker :CKAlertViewComponentBaseMaker {
override func makeHeader() -> CKAlertViewComponent? {
let headerView = CKAlertViewHeaderView()
headerView.alertTitle = alertTitle
return headerView
}
override func makeBody() -> CKAlertViewComponent? {
let bodyView = CKAlertViewEmptyComponent()
return bodyView
}
override func makeFooter() -> CKAlertViewComponent? {
let footerView = CKAlertViewFooterView()
footerView.cancelButtonTitle = cancelButtonTitle
footerView.otherButtonTitles = otherButtonTitles
return footerView
}
}
class CKAlertViewEmptyComponent : CKAlertViewComponent {
override func setup() {
}
override func makeLayout() {
}
}
| mit | e724a517026558c463591138f632fcca | 27.101449 | 265 | 0.674059 | 4.946429 | false | false | false | false |
wrutkowski/Lucid-Weather-Clock | Pods/Charts/Charts/Classes/Data/Implementations/Standard/PieChartData.swift | 6 | 2882 | //
// PieData.swift
// Charts
//
// Created by Daniel Cohen Gindi on 24/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/Charts
//
import Foundation
open class PieChartData: ChartData
{
public override init()
{
super.init()
}
public override init(xVals: [String?]?, dataSets: [IChartDataSet]?)
{
super.init(xVals: xVals, dataSets: dataSets)
}
public override init(xVals: [NSObject]?, dataSets: [IChartDataSet]?)
{
super.init(xVals: xVals, dataSets: dataSets)
}
var dataSet: IPieChartDataSet?
{
get
{
return dataSets.count > 0 ? dataSets[0] as? IPieChartDataSet : nil
}
set
{
if (newValue != nil)
{
dataSets = [newValue!]
}
else
{
dataSets = []
}
}
}
open override func getDataSetByIndex(_ index: Int) -> IChartDataSet?
{
if (index != 0)
{
return nil
}
return super.getDataSetByIndex(index)
}
open override func getDataSetByLabel(_ label: String, ignorecase: Bool) -> IChartDataSet?
{
if (dataSets.count == 0 || dataSets[0].label == nil)
{
return nil
}
if (ignorecase)
{
if (label.caseInsensitiveCompare(dataSets[0].label!) == ComparisonResult.orderedSame)
{
return dataSets[0]
}
}
else
{
if (label == dataSets[0].label)
{
return dataSets[0]
}
}
return nil
}
open override func addDataSet(_ d: IChartDataSet!)
{
if (_dataSets == nil)
{
return
}
super.addDataSet(d)
}
/// Removes the DataSet at the given index in the DataSet array from the data object.
/// Also recalculates all minimum and maximum values.
///
/// - returns: true if a DataSet was removed, false if no DataSet could be removed.
open override func removeDataSetByIndex(_ index: Int) -> Bool
{
if (_dataSets == nil || index >= _dataSets.count || index < 0)
{
return false
}
return false
}
/// - returns: the total y-value sum across all DataSet objects the this object represents.
open var yValueSum: Double
{
guard let dataSet = dataSet else { return 0.0 }
var yValueSum: Double = 0.0
for i in 0..<dataSet.entryCount
{
yValueSum += dataSet.entryForIndex(i)?.value ?? 0.0
}
return yValueSum
}
}
| mit | 2891b960baea5b20043b06501bcd19b0 | 22.430894 | 97 | 0.514226 | 4.779436 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/Utility/Universal Links/Routes+Banners.swift | 2 | 1398 | import Foundation
/// Routes to handle WordPress.com app banner "Open in app" links.
/// Banner routes always begin https://apps.wordpress.com/get and can contain
/// an optional fragment to route to a specific part of the app. The fragment
/// will be treated like any other route. The fragment
/// can contain additional components to route more specifically:
///
/// * /get#post
/// * /get#post/discover.wordpress.com
///
struct AppBannerRoute: Route {
let path = "/get"
let section: DeepLinkSection? = nil
let source: DeepLinkSource = .banner
let shouldTrack: Bool = false
var action: NavigationAction {
return self
}
}
extension AppBannerRoute: NavigationAction {
func perform(_ values: [String: String], source: UIViewController? = nil, router: LinkRouter) {
guard let fragmentValue = values[MatchedRouteURLComponentKey.fragment.rawValue],
let fragment = fragmentValue.removingPercentEncoding else {
return
}
// Convert the fragment into a URL and ask the link router to handle
// it like a normal route.
var components = URLComponents()
components.scheme = "https"
components.host = "wordpress.com"
components.path = fragment
if let url = components.url {
router.handle(url: url, shouldTrack: true, source: .banner)
}
}
}
| gpl-2.0 | a465190f16ce663586a57fe4291bc320 | 33.097561 | 99 | 0.665236 | 4.466454 | false | false | false | false |
KenanKarakecili/PickerView_Swift | KKPickerView/KKPickerView.swift | 1 | 2582 | //
// PickerView.swift
//
// Created by Kenan Karakecili on 4/15/16.
// Copyright © 2016 Kenan Karakecili. All rights reserved.
//
import UIKit
protocol KKPickerViewDelegate {
func pickerDidSelectAction(row: Int)
}
class KKPickerView: UIPickerView {
private var array: [String] = []
var field: UITextField!
var myDelegate: KKPickerViewDelegate?
func setup(field: UITextField, array: [String]) {
self.field = field
self.array = array
backgroundColor = UIColor.groupTableViewBackgroundColor()
showsSelectionIndicator = true
delegate = self
dataSource = self
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.Default
toolBar.tintColor = UIColor.blueColor()
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "OK", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(doneButtonAction))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(cancelButtonAction))
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
field.inputView = self
field.inputAccessoryView = toolBar
field.tintColor = UIColor.clearColor()
if field.text?.characters.count > 0 {
let row = self.array.indexOf(field.text!)
selectRow(row!, inComponent: 0, animated: false)
} else {
selectRow(0, inComponent: 0, animated: false)
}
}
@objc private func doneButtonAction() {
field.resignFirstResponder()
let row = selectedRowInComponent(0)
myDelegate!.pickerDidSelectAction(row)
}
@objc private func cancelButtonAction() {
field.resignFirstResponder()
}
}
extension KKPickerView: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return array.count
}
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
let view2 = UIView(frame: CGRectMake(0, 0, 320, 44))
let label = UILabel(frame: view2.frame)
label.textAlignment = .Center
label.text = array[row]
view2.addSubview(label)
return view2
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return array[row]
}
}
| mit | 8113259535294297ebca10d3dda8ab8b | 31.2625 | 143 | 0.719101 | 4.552028 | false | false | false | false |
lorentey/swift | stdlib/public/Darwin/CoreMedia/CMTime.swift | 5 | 3653 | //===----------------------------------------------------------------------===//
//
// 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 CoreMedia // Clang module
extension CMTime {
public init(seconds: Double, preferredTimescale: CMTimeScale) {
self = CMTimeMakeWithSeconds(seconds, preferredTimescale: preferredTimescale)
}
public init(value: CMTimeValue, timescale: CMTimeScale) {
self = CMTimeMake(value: value, timescale: timescale)
}
}
// CMTIME_IS_VALID
// CMTIME_IS_INVALID
// CMTIME_IS_POSITIVEINFINITY
// CMTIME_IS_NEGATIVEINFINITY
// CMTIME_IS_INDEFINITE
// CMTIME_IS_NUMERIC
// CMTIME_HAS_BEEN_ROUNDED
// CMTimeGetSeconds
// CMTimeConvertScale
extension CMTime {
public var isValid: Bool {
return self.flags.contains(.valid)
}
public var isPositiveInfinity: Bool {
return self.isValid &&
self.flags.contains(.positiveInfinity)
}
public var isNegativeInfinity: Bool {
return self.isValid &&
self.flags.contains(.negativeInfinity)
}
public var isIndefinite: Bool {
return self.isValid &&
self.flags.contains(.indefinite)
}
public var isNumeric: Bool {
return
self.flags.intersection([.valid, .impliedValueFlagsMask]) == .valid
}
public var hasBeenRounded: Bool {
return self.isNumeric &&
self.flags.contains(.hasBeenRounded)
}
public var seconds: Double {
return CMTimeGetSeconds(self)
}
public func convertScale(_ newTimescale: Int32, method: CMTimeRoundingMethod)
-> CMTime {
return CMTimeConvertScale(self, timescale: newTimescale, method: method)
}
}
public func CMTIME_IS_VALID(_ time: CMTime) -> Bool {
return time.isValid
}
public func CMTIME_IS_INVALID(_ time: CMTime) -> Bool {
return !time.isValid
}
public func CMTIME_IS_POSITIVEINFINITY(_ time: CMTime) -> Bool {
return time.isPositiveInfinity
}
public func CMTIME_IS_NEGATIVEINFINITY(_ time: CMTime) -> Bool {
return time.isNegativeInfinity
}
public func CMTIME_IS_INDEFINITE(_ time: CMTime) -> Bool {
return time.isIndefinite
}
public func CMTIME_IS_NUMERIC(_ time: CMTime) -> Bool {
return time.isNumeric
}
public func CMTIME_HAS_BEEN_ROUNDED(_ time: CMTime) -> Bool {
return time.hasBeenRounded
}
extension CMTime {
// CMTimeAdd
public static func + (addend1: CMTime, addend2: CMTime) -> CMTime {
return CMTimeAdd(addend1, addend2)
}
// CMTimeSubtract
public static func - (minuend: CMTime, subtrahend: CMTime) -> CMTime {
return CMTimeSubtract(minuend, subtrahend)
}
}
// CMTimeCompare
extension CMTime : Equatable, Comparable {
public static func < (time1: CMTime, time2: CMTime) -> Bool {
return CMTimeCompare(time1, time2) < 0
}
public static func <= (time1: CMTime, time2: CMTime) -> Bool {
return CMTimeCompare(time1, time2) <= 0
}
public static func > (time1: CMTime, time2: CMTime) -> Bool {
return CMTimeCompare(time1, time2) > 0
}
public static func >= (time1: CMTime, time2: CMTime) -> Bool {
return CMTimeCompare(time1, time2) >= 0
}
public static func == (time1: CMTime, time2: CMTime) -> Bool {
return CMTimeCompare(time1, time2) == 0
}
public static func != (time1: CMTime, time2: CMTime) -> Bool {
return CMTimeCompare(time1, time2) != 0
}
}
| apache-2.0 | 642368f1a018420bb493fb5647c1eab5 | 26.261194 | 81 | 0.670955 | 3.82113 | false | false | false | false |
powerytg/Accented | Accented/Core/Storage/Models/UserStreamModel.swift | 1 | 643 | //
// UserStreamModel.swift
// Accented
//
// User photo stream model
//
// Created by Tiangong You on 5/31/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class UserStreamModel: StreamModel {
var userId : String
override var streamId: String {
return userId
}
init(userId : String) {
self.userId = userId
super.init(streamType: .User)
}
override func copy(with zone: NSZone? = nil) -> Any {
let clone = UserStreamModel(userId : userId)
clone.totalCount = self.totalCount
clone.items = items
return clone
}
}
| mit | ef1a2567c53c148b37afd601b4c75726 | 19.709677 | 57 | 0.609034 | 3.987578 | false | false | false | false |
pksprojects/ElasticSwift | Tests/ElasticSwiftQueryDSLTests/ScoreFunctionTests.swift | 1 | 10987 | //
// ScoreFunctionTests.swift
// ElasticSwiftQueryDSLTests
//
// Created by Prafull Kumar Soni on 9/2/19.
//
import Logging
import UnitTestSettings
import XCTest
@testable import ElasticSwiftCodableUtils
@testable import ElasticSwiftQueryDSL
class ScoreFunctionTests: XCTestCase {
let logger = Logger(label: "org.pksprojects.ElasticSwiftQueryDSLTests.ScoreFunctionTests", factory: logFactory)
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
super.setUp()
XCTAssert(isLoggingConfigured)
logger.info("====================TEST=START===============================")
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
logger.info("====================TEST=END===============================")
}
func testWeightScoreFunction_encode() throws {
let weightFunc = try WeightBuilder().set(weight: 11.234).build()
let data = try JSONEncoder().encode(weightFunc)
let dataStr = String(data: data, encoding: .utf8)!
logger.debug("WeightScoreFunction Encode test: \(dataStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: "{\"weight\":11.234}".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func testWeightScoreFunction_decode() throws {
let weightFunc = WeightScoreFunction(11.234)
let jsonStr = "{\"weight\":11.234}"
let decoded = try JSONDecoder().decode(WeightScoreFunction.self, from: jsonStr.data(using: .utf8)!)
logger.debug("WeightScoreFunction Decode test: \(decoded)")
XCTAssertEqual(weightFunc.weight, decoded.weight)
}
func testRandomScoreFunction_encode() throws {
let ranFunc = try RandomScoreFunctionBuilder()
.set(field: "_seq_no")
.set(seed: 10)
.build()
let data = try JSONEncoder().encode(ranFunc)
let dataStr = String(data: data, encoding: .utf8)!
logger.debug("RandomScoreFunction Encode test: \(dataStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: "{\"random_score\":{\"seed\":10,\"field\":\"_seq_no\"}}".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func testRandomScoreFunction_decode() throws {
let ranFunc = RandomScoreFunction(field: "_seq_no", seed: 10)
let jsonStr = "{\"random_score\":{\"seed\":10,\"field\":\"_seq_no\"}}"
let decoded = try JSONDecoder().decode(RandomScoreFunction.self, from: jsonStr.data(using: .utf8)!)
logger.debug("RandomScoreFunction Decode test: \(decoded)")
XCTAssertEqual(ranFunc.seed, decoded.seed)
XCTAssertEqual(ranFunc.field, decoded.field)
}
func testScriptScoreFunction_encode() throws {
let script = Script("Math.log(2 + doc['likes'].value)")
let ranFunc = try ScriptScoreFunctionBuilder()
.set(script: script)
.build()
let data = try JSONEncoder().encode(ranFunc)
let dataStr = String(data: data, encoding: .utf8)!
logger.debug("ScriptScoreFunction Encode test: \(dataStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: "{\"script_score\":{\"script\":\"Math.log(2 + doc['likes'].value)\"}}".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func testScriptScoreFunction_decode() throws {
let scriptFunc = ScriptScoreFunction(source: "Math.log(2 + doc['likes'].value)")
let jsonStr = "{\"script_score\":{\"script\":{\"source\":\"Math.log(2 + doc['likes'].value)\"}}}"
let decoded = try JSONDecoder().decode(ScriptScoreFunction.self, from: jsonStr.data(using: .utf8)!)
logger.debug("ScriptScoreFunction Decode test: \(decoded)")
XCTAssertEqual(scriptFunc.script.source, decoded.script.source)
}
func testFieldValueFactorScoreFunction_encode() throws {
let fvfFunc = try FieldValueFactorFunctionBuilder()
.set(field: "likes")
.set(factor: 1.2)
.set(modifier: .sqrt)
.set(missing: 1)
.build()
let data = try JSONEncoder().encode(fvfFunc)
let dataStr = String(data: data, encoding: .utf8)!
logger.debug("FieldValueFactorScoreFunction Encode test: \(dataStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: "{\"field_value_factor\":{\"missing\":1,\"factor\":1.2,\"field\":\"likes\",\"modifier\":\"sqrt\"}}".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func testFieldValueFactorScoreFunction_decode() throws {
let fvfFunc = FieldValueFactorScoreFunction(field: "likes", factor: 1.2, modifier: .sqrt, missing: 1)
let jsonStr = "{\"field_value_factor\":{\"missing\":1,\"factor\":1.2,\"field\":\"likes\",\"modifier\":\"sqrt\"}}"
let decoded = try JSONDecoder().decode(FieldValueFactorScoreFunction.self, from: jsonStr.data(using: .utf8)!)
logger.debug("FieldValueFactorScoreFunction Decode test: \(decoded)")
XCTAssertEqual(fvfFunc.field, decoded.field)
XCTAssertEqual(fvfFunc.factor, decoded.factor)
XCTAssertEqual(fvfFunc.modifier, decoded.modifier)
XCTAssertEqual(fvfFunc.missing, decoded.missing)
}
func testLinearDecayScoreFunction_encode() throws {
let linear = try LinearDecayFunctionBuilder()
.set(field: "date")
.set(origin: "2013-09-17")
.set(scale: "10d")
.set(offset: "5d")
.set(decay: 0.5)
.build()
let data = try JSONEncoder().encode(linear)
let dataStr = String(data: data, encoding: .utf8)!
logger.debug("LinearDecayScoreFunction Encode test: \(dataStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: "{\"linear\":{\"date\":{\"decay\":0.5,\"offset\":\"5d\",\"origin\":\"2013-09-17\",\"scale\":\"10d\"}}}".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func testLinearDecayScoreFunction_decode() throws {
let decayFunc = DecayScoreFunction(type: .linear, field: "date", origin: "2013-09-17", scale: "10d", offset: "5d", decay: 0.5, multiValueMode: nil)
let jsonStr = "{\"linear\":{\"date\":{\"decay\":0.5,\"offset\":\"5d\",\"origin\":\"2013-09-17\",\"scale\":\"10d\"}}}"
let decoded = try JSONDecoder().decode(LinearDecayScoreFunction.self, from: jsonStr.data(using: .utf8)!)
logger.debug("LinearDecayScoreFunction Decode test: \(decoded)")
XCTAssertEqual(decayFunc.scoreFunctionType, decoded.scoreFunctionType)
XCTAssertEqual(decayFunc.field, decoded.field)
XCTAssertEqual(decayFunc.origin, decoded.origin)
XCTAssertEqual(decayFunc.scale, decoded.scale)
XCTAssertEqual(decayFunc.offset, decoded.offset)
XCTAssertEqual(decayFunc.decay, decoded.decay)
}
func testGaussDecayScoreFunction_encode() throws {
let linear = try GaussDecayFunctionBuilder()
.set(field: "date")
.set(origin: "2013-09-17")
.set(scale: "10d")
.set(offset: "5d")
.set(decay: 0.5)
.build()
let data = try JSONEncoder().encode(linear)
let dataStr = String(data: data, encoding: .utf8)!
logger.debug("GaussScoreFunction Encode test: \(dataStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: "{\"gauss\":{\"date\":{\"decay\":0.5,\"offset\":\"5d\",\"origin\":\"2013-09-17\",\"scale\":\"10d\"}}}".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func testGaussDecayScoreFunction_decode() throws {
let decayFunc = DecayScoreFunction(type: .gauss, field: "date", origin: "2013-09-17", scale: "10d", offset: "5d", decay: 0.5, multiValueMode: nil)
let jsonStr = "{\"gauss\":{\"date\":{\"decay\":0.5,\"offset\":\"5d\",\"origin\":\"2013-09-17\",\"scale\":\"10d\"}}}"
let decoded = try JSONDecoder().decode(GaussScoreFunction.self, from: jsonStr.data(using: .utf8)!)
logger.debug("GaussScoreFunction Decode test: \(decoded)")
XCTAssertEqual(decayFunc.scoreFunctionType, decoded.scoreFunctionType)
XCTAssertEqual(decayFunc.field, decoded.field)
XCTAssertEqual(decayFunc.origin, decoded.origin)
XCTAssertEqual(decayFunc.scale, decoded.scale)
XCTAssertEqual(decayFunc.offset, decoded.offset)
XCTAssertEqual(decayFunc.decay, decoded.decay)
}
func testExponentialDecayScoreFunction_encode() throws {
let linear = try ExponentialDecayFunctionBuilder()
.set(field: "date")
.set(origin: "2013-09-17")
.set(scale: "10d")
.set(offset: "5d")
.set(decay: 0.5)
.build()
let data = try JSONEncoder().encode(linear)
let dataStr = String(data: data, encoding: .utf8)!
logger.debug("ExponentialDecayScoreFunction Encode test: \(dataStr)")
let dic = try JSONDecoder().decode([String: CodableValue].self, from: data)
let expectedDic = try JSONDecoder().decode([String: CodableValue].self, from: "{\"exp\":{\"date\":{\"decay\":0.5,\"offset\":\"5d\",\"origin\":\"2013-09-17\",\"scale\":\"10d\"}}}".data(using: .utf8)!)
XCTAssertEqual(expectedDic, dic)
}
func testExponentialDecayScoreFunction_decode() throws {
let decayFunc = DecayScoreFunction(type: .exp, field: "date", origin: "2013-09-17", scale: "10d", offset: "5d", decay: 0.5, multiValueMode: nil)
let jsonStr = "{\"exp\":{\"date\":{\"decay\":0.5,\"offset\":\"5d\",\"origin\":\"2013-09-17\",\"scale\":\"10d\"}}}"
let decoded = try JSONDecoder().decode(ExponentialDecayScoreFunction.self, from: jsonStr.data(using: .utf8)!)
logger.debug("ExponentialDecayScoreFunction Decode test: \(decoded)")
XCTAssertEqual(decayFunc.scoreFunctionType, decoded.scoreFunctionType)
XCTAssertEqual(decayFunc.field, decoded.field)
XCTAssertEqual(decayFunc.origin, decoded.origin)
XCTAssertEqual(decayFunc.scale, decoded.scale)
XCTAssertEqual(decayFunc.offset, decoded.offset)
XCTAssertEqual(decayFunc.decay, decoded.decay)
}
}
| mit | 5522ac286cd26ba28b6caf95fef22485 | 39.542435 | 210 | 0.634204 | 4.175979 | false | true | false | false |
kperryua/swift | test/IDE/coloring.swift | 1 | 22264 | // RUN: %target-swift-ide-test -syntax-coloring -source-filename %s | %FileCheck %s
// RUN: %target-swift-ide-test -syntax-coloring -typecheck -source-filename %s | %FileCheck %s
// XFAIL: broken_std_regex
#line 17 "abc.swift"
// CHECK: <kw>#line</kw> <int>17</int> <str>"abc.swift"</str>
@available(iOS 8.0, OSX 10.10, *)
// CHECK: <attr-builtin>@available</attr-builtin>(<kw>iOS</kw> <float>8.0</float>, <kw>OSX</kw> <float>10.10</float>, *)
func foo() {
// CHECK: <kw>if</kw> <kw>#available</kw> (<kw>OSX</kw> <float>10.10</float>, <kw>iOS</kw> <float>8.01</float>, *) {<kw>let</kw> <kw>_</kw> = <str>"iOS"</str>}
if #available (OSX 10.10, iOS 8.01, *) {let _ = "iOS"}
}
enum List<T> {
case Nil
// rdar://21927124
// CHECK: <attr-builtin>indirect</attr-builtin> <kw>case</kw> Cons(T, List)
indirect case Cons(T, List)
}
// CHECK: <kw>struct</kw> S {
struct S {
// CHECK: <kw>var</kw> x : <type>Int</type>
var x : Int
// CHECK: <kw>var</kw> y : <type>Int</type>.<type>Int</type>
var y : Int.Int
// CHECK: <kw>var</kw> a, b : <type>Int</type>
var a, b : Int
}
enum EnumWithDerivedEquatableConformance : Int {
// CHECK-LABEL: <kw>enum</kw> EnumWithDerivedEquatableConformance : {{(<type>)}}Int{{(</type>)?}} {
case CaseA
// CHECK-NEXT: <kw>case</kw> CaseA
case CaseB, CaseC
// CHECK-NEXT: <kw>case</kw> CaseB, CaseC
case CaseD = 30, CaseE
// CHECK-NEXT: <kw>case</kw> CaseD = <int>30</int>, CaseE
}
// CHECK-NEXT: }
// CHECK: <kw>class</kw> MyCls {
class MyCls {
// CHECK: <kw>var</kw> www : <type>Int</type>
var www : Int
// CHECK: <kw>func</kw> foo(x: <type>Int</type>) {}
func foo(x: Int) {}
// CHECK: <kw>var</kw> aaa : <type>Int</type> {
var aaa : Int {
// CHECK: <kw>get</kw> {}
get {}
// CHECK: <kw>set</kw> {}
set {}
}
// CHECK: <kw>var</kw> bbb : <type>Int</type> {
var bbb : Int {
// CHECK: <kw>set</kw> {
set {
// CHECK: <kw>var</kw> tmp : <type>Int</type>
var tmp : Int
}
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>var</kw> tmp : <type>Int</type>
var tmp : Int
}
}
// CHECK: <kw>subscript</kw> (i : <type>Int</type>, j : <type>Int</type>) -> <type>Int</type> {
subscript (i : Int, j : Int) -> Int {
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>return</kw> i + j
return i + j
}
// CHECK: <kw>set</kw>(v) {
set(v) {
// CHECK: v + i - j
v + i - j
}
}
// CHECK: <kw>func</kw> multi(<kw>_</kw> name: <type>Int</type>, otherpart x: <type>Int</type>) {}
func multi(_ name: Int, otherpart x: Int) {}
}
// CHECK-LABEL: <kw>class</kw> Attributes {
class Attributes {
// CHECK: <attr-builtin>@IBOutlet</attr-builtin> <kw>var</kw> v0: <type>Int</type>
@IBOutlet var v0: Int
// CHECK: <attr-builtin>@IBOutlet</attr-builtin> <attr-id>@IBOutlet</attr-id> <kw>var</kw> {{(<attr-builtin>)?}}v1{{(</attr-builtin>)?}}: <type>String</type>
@IBOutlet @IBOutlet var v1: String
// CHECK: <attr-builtin>@objc</attr-builtin> <attr-builtin>@IBOutlet</attr-builtin> <kw>var</kw> {{(<attr-builtin>)?}}v2{{(</attr-builtin>)?}}: <type>String</type>
@objc @IBOutlet var v2: String
// CHECK: <attr-builtin>@IBOutlet</attr-builtin> <attr-builtin>@objc</attr-builtin> <kw>var</kw> {{(<attr-builtin>)?}}v3{{(</attr-builtin>)?}}: <type>String</type>
@IBOutlet @objc var v3: String
// CHECK: <attr-builtin>@available</attr-builtin>(*, unavailable) <kw>func</kw> f1() {}
@available(*, unavailable) func f1() {}
// CHECK: <attr-builtin>@available</attr-builtin>(*, unavailable) <attr-builtin>@IBAction</attr-builtin> <kw>func</kw> f2() {}
@available(*, unavailable) @IBAction func f2() {}
// CHECK: <attr-builtin>@IBAction</attr-builtin> <attr-builtin>@available</attr-builtin>(*, unavailable) <kw>func</kw> f3() {}
@IBAction @available(*, unavailable) func f3() {}
// CHECK: <attr-builtin>mutating</attr-builtin> <kw>func</kw> func_mutating_1() {}
mutating func func_mutating_1() {}
// CHECK: <attr-builtin>nonmutating</attr-builtin> <kw>func</kw> func_mutating_2() {}
nonmutating func func_mutating_2() {}
}
func stringLikeLiterals() {
// CHECK: <kw>var</kw> us1: <type>UnicodeScalar</type> = <str>"a"</str>
var us1: UnicodeScalar = "a"
// CHECK: <kw>var</kw> us2: <type>UnicodeScalar</type> = <str>"ы"</str>
var us2: UnicodeScalar = "ы"
// CHECK: <kw>var</kw> ch1: <type>Character</type> = <str>"a"</str>
var ch1: Character = "a"
// CHECK: <kw>var</kw> ch2: <type>Character</type> = <str>"あ"</str>
var ch2: Character = "あ"
// CHECK: <kw>var</kw> s1 = <str>"abc абвгд あいうえお"</str>
var s1 = "abc абвгд あいうえお"
}
// CHECK: <kw>var</kw> globComp : <type>Int</type>
var globComp : Int {
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>return</kw> <int>0</int>
return 0
}
}
// CHECK: <comment-block>/* foo is the best */</comment-block>
/* foo is the best */
// CHECK: <kw>func</kw> foo(n: <type>Float</type>) -> <type>Int</type> {
func foo(n: Float) -> Int {
// CHECK: <kw>var</kw> fnComp : <type>Int</type>
var fnComp : Int {
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>var</kw> a: <type>Int</type>
// CHECK: <kw>return</kw> <int>0</int>
var a: Int
return 0
}
}
// CHECK: <kw>var</kw> q = {{(<type>)?}}MyCls{{(</type>)?}}()
var q = MyCls()
// CHECK: <kw>var</kw> ee = <str>"yoo"</str>;
var ee = "yoo";
// CHECK: <kw>return</kw> <int>100009</int>
return 100009
}
///- returns: single-line, no space
// CHECK: ///- <doc-comment-field>returns</doc-comment-field>: single-line, no space
/// - returns: single-line, 1 space
// CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, 1 space
/// - returns: single-line, 2 spaces
// CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, 2 spaces
/// - returns: single-line, more spaces
// CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, more spaces
// CHECK: <kw>protocol</kw> Prot {
protocol Prot {
// CHECK: <kw>typealias</kw> Blarg
typealias Blarg
// CHECK: <kw>func</kw> protMeth(x: <type>Int</type>)
func protMeth(x: Int)
// CHECK: <kw>var</kw> protocolProperty1: <type>Int</type> { <kw>get</kw> }
var protocolProperty1: Int { get }
// CHECK: <kw>var</kw> protocolProperty2: <type>Int</type> { <kw>get</kw> <kw>set</kw> }
var protocolProperty2: Int { get set }
}
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *-* : FunnyPrecedence{{$}}
infix operator *-* : FunnyPrecedence
// CHECK: <kw>precedencegroup</kw> FunnyPrecedence
// CHECK-NEXT: <kw>associativity</kw>: left{{$}}
// CHECK-NEXT: <kw>higherThan</kw>: MultiplicationPrecedence
precedencegroup FunnyPrecedence {
associativity: left
higherThan: MultiplicationPrecedence
}
// CHECK: <kw>func</kw> *-*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}}
func *-*(l: Int, r: Int) -> Int { return l }
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *-+* : FunnyPrecedence
infix operator *-+* : FunnyPrecedence
// CHECK: <kw>func</kw> *-+*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}}
func *-+*(l: Int, r: Int) -> Int { return l }
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *--*{{$}}
infix operator *--*
// CHECK: <kw>func</kw> *--*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}}
func *--*(l: Int, r: Int) -> Int { return l }
// CHECK: <kw>protocol</kw> Prot2 : <type>Prot</type> {}
protocol Prot2 : Prot {}
// CHECK: <kw>class</kw> SubCls : <type>MyCls</type>, <type>Prot</type> {}
class SubCls : MyCls, Prot {}
// CHECK: <kw>func</kw> genFn<T : <type>Prot</type> <kw>where</kw> <type>T</type>.<type>Blarg</type> : <type>Prot2</type>>(<kw>_</kw>: <type>T</type>) -> <type>Int</type> {}{{$}}
func genFn<T : Prot where T.Blarg : Prot2>(_: T) -> Int {}
func f(x: Int) -> Int {
// CHECK: <comment-line>// string interpolation is the best</comment-line>
// string interpolation is the best
// CHECK: <str>"This is string </str>\<anchor>(</anchor>genFn({(a:<type>Int</type> -> <type>Int</type>) <kw>in</kw> a})<anchor>)</anchor><str> interpolation"</str>
"This is string \(genFn({(a:Int -> Int) in a})) interpolation"
}
// CHECK: <kw>func</kw> bar(x: <type>Int</type>) -> (<type>Int</type>, <type>Float</type>) {
func bar(x: Int) -> (Int, Float) {
// CHECK: foo({{(<type>)?}}Float{{(</type>)?}}())
foo(Float())
}
class GenC<T1,T2> {}
func test() {
// CHECK: {{(<type>)?}}GenC{{(</type>)?}}<<type>Int</type>, <type>Float</type>>()
var x = GenC<Int, Float>()
}
// CHECK: <kw>typealias</kw> MyInt = <type>Int</type>
typealias MyInt = Int
func test2(x: Int) {
// CHECK: <str>"</str>\<anchor>(</anchor>x<anchor>)</anchor><str>"</str>
"\(x)"
}
// CHECK: <kw>class</kw> Observers {
class Observers {
// CHECK: <kw>var</kw> p1 : <type>Int</type> {
var p1 : Int {
// CHECK: <kw>willSet</kw>(newValue) {}
willSet(newValue) {}
// CHECK: <kw>didSet</kw> {}
didSet {}
}
// CHECK: <kw>var</kw> p2 : <type>Int</type> {
var p2 : Int {
// CHECK: <kw>didSet</kw> {}
didSet {}
// CHECK: <kw>willSet</kw> {}
willSet {}
}
}
// CHECK: <kw>func</kw> test3(o: <type>AnyObject</type>) {
func test3(o: AnyObject) {
// CHECK: <kw>let</kw> x = o <kw>as</kw>! <type>MyCls</type>
let x = o as! MyCls
}
// CHECK: <kw>func</kw> test4(inout a: <type>Int</type>) {{{$}}
func test4(inout a: Int) {
// CHECK: <kw>if</kw> <kw>#available</kw> (<kw>OSX</kw> >= <float>10.10</float>, <kw>iOS</kw> >= <float>8.01</float>) {<kw>let</kw> OSX = <str>"iOS"</str>}}{{$}}
if #available (OSX >= 10.10, iOS >= 8.01) {let OSX = "iOS"}}
// CHECK: <kw>func</kw> test4b(a: <kw>inout</kw> <type>Int</type>) {{{$}}
func test4b(a: inout Int) {
}
// CHECK: <kw>class</kw> MySubClass : <type>MyCls</type> {
class MySubClass : MyCls {
// CHECK: <attr-builtin>override</attr-builtin> <kw>func</kw> foo(x: <type>Int</type>) {}
override func foo(x: Int) {}
// CHECK: <attr-builtin>convenience</attr-builtin> <kw>init</kw>(a: <type>Int</type>) {}
convenience init(a: Int) {}
}
// CHECK: <kw>var</kw> g1 = { (x: <type>Int</type>) -> <type>Int</type> <kw>in</kw> <kw>return</kw> <int>0</int> }
var g1 = { (x: Int) -> Int in return 0 }
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> ~~ {
infix operator ~~ {}
// CHECK: <attr-builtin>prefix</attr-builtin> <kw>operator</kw> *~~ {
prefix operator *~~ {}
// CHECK: <attr-builtin>postfix</attr-builtin> <kw>operator</kw> ~~* {
postfix operator ~~* {}
func test_defer() {
defer {
// CHECK: <kw>let</kw> x : <type>Int</type> = <int>0</int>
let x : Int = 0
}
}
// FIXME: blah.
// FIXME: blah blah
// Something something, FIXME: blah
// CHECK: <comment-line>// <comment-marker>FIXME: blah.</comment-marker></comment-line>
// CHECK: <comment-line>// <comment-marker>FIXME: blah blah</comment-marker></comment-line>
// CHECK: <comment-line>// Something something, <comment-marker>FIXME: blah</comment-marker></comment-line>
/* FIXME: blah*/
// CHECK: <comment-block>/* <comment-marker>FIXME: blah*/</comment-marker></comment-block>
/*
* FIXME: blah
* Blah, blah.
*/
// CHECK: <comment-block>/*
// CHECK: * <comment-marker>FIXME: blah</comment-marker>
// CHECK: * Blah, blah.
// CHECK: */</comment-block>
// TODO: blah.
// TTODO: blah.
// MARK: blah.
// CHECK: <comment-line>// <comment-marker>TODO: blah.</comment-marker></comment-line>
// CHECK: <comment-line>// T<comment-marker>TODO: blah.</comment-marker></comment-line>
// CHECK: <comment-line>// <comment-marker>MARK: blah.</comment-marker></comment-line>
// CHECK: <kw>func</kw> test5() -> <type>Int</type> {
func test5() -> Int {
// CHECK: <comment-line>// <comment-marker>TODO: something, something.</comment-marker></comment-line>
// TODO: something, something.
// CHECK: <kw>return</kw> <int>0</int>
return 0
}
func test6<T : Prot>(x: T) {}
// CHECK: <kw>func</kw> test6<T : <type>Prot</type>>(x: <type>T</type>) {}{{$}}
// http://whatever.com?ee=2&yy=1 and radar://123456
/* http://whatever.com FIXME: see in http://whatever.com/fixme
http://whatever.com */
// CHECK: <comment-line>// <comment-url>http://whatever.com?ee=2&yy=1</comment-url> and <comment-url>radar://123456</comment-url></comment-line>
// CHECK: <comment-block>/* <comment-url>http://whatever.com</comment-url> <comment-marker>FIXME: see in <comment-url>http://whatever.com/fixme</comment-url></comment-marker>
// CHECK: <comment-url>http://whatever.com</comment-url> */</comment-block>
// CHECK: <comment-line>// <comment-url>http://whatever.com/what-ever</comment-url></comment-line>
// http://whatever.com/what-ever
// CHECK: <kw>func</kw> <placeholder><#test1#></placeholder> () {}
func <#test1#> () {}
/// Brief.
///
/// Simple case.
///
/// - parameter x: A number
/// - parameter y: Another number
/// - PaRamEteR z-hyphen-q: Another number
/// - parameter : A strange number...
/// - parameternope1: Another number
/// - parameter nope2
/// - parameter: nope3
/// -parameter nope4: Another number
/// * parameter nope5: Another number
/// - parameter nope6: Another number
/// - Parameters: nope7
/// - seealso: yes
/// - seealso: yes
/// - seealso:
/// -seealso: nope
/// - seealso : nope
/// - seealso nope
/// - returns: `x + y`
func foo(x: Int, y: Int) -> Int { return x + y }
// CHECK: <doc-comment-line>/// Brief.
// CHECK: </doc-comment-line><doc-comment-line>///
// CHECK: </doc-comment-line><doc-comment-line>/// Simple case.
// CHECK: </doc-comment-line><doc-comment-line>///
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> x: A number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> y: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>PaRamEteR</doc-comment-field> z-hyphen-q: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> : A strange number...
// CHECK: </doc-comment-line><doc-comment-line>/// - parameternope1: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - parameter nope2
// CHECK: </doc-comment-line><doc-comment-line>/// - parameter: nope3
// CHECK: </doc-comment-line><doc-comment-line>/// -parameter nope4: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// * parameter nope5: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - parameter nope6: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - Parameters: nope7
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>: yes
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>: yes
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>:
// CHECK: </doc-comment-line><doc-comment-line>/// -seealso: nope
// CHECK: </doc-comment-line><doc-comment-line>/// - seealso : nope
// CHECK: </doc-comment-line><doc-comment-line>/// - seealso nope
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>returns</doc-comment-field>: `x + y`
// CHECK: </doc-comment-line><kw>func</kw> foo(x: <type>Int</type>, y: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> x + y }
/// Brief.
///
/// Simple case.
///
/// - Parameters:
/// - x: A number
/// - y: Another number
///
///- note: NOTE1
///
/// - NOTE: NOTE2
/// - note: Not a Note field (not at top level)
/// - returns: `x + y`
func bar(x: Int, y: Int) -> Int { return x + y }
// CHECK: <doc-comment-line>/// Brief.
// CHECK: </doc-comment-line><doc-comment-line>///
// CHECK: </doc-comment-line><doc-comment-line>/// Simple case.
// CHECK: </doc-comment-line><doc-comment-line>///
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>Parameters</doc-comment-field>:
// CHECK: </doc-comment-line><doc-comment-line>/// - x: A number
// CHECK: </doc-comment-line><doc-comment-line>/// - y: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>returns</doc-comment-field>: `x + y`
// CHECK: </doc-comment-line><kw>func</kw> bar(x: <type>Int</type>, y: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> x + y }
/**
Does pretty much nothing.
Not a parameter list: improper indentation.
- Parameters: sdfadsf
- WARNING: - WARNING: Should only have one field
- $$$: Not a field.
Empty field, OK:
*/
func baz() {}
// CHECK: <doc-comment-block>/**
// CHECK: Does pretty much nothing.
// CHECK: Not a parameter list: improper indentation.
// CHECK: - Parameters: sdfadsf
// CHECK: - <doc-comment-field>WARNING</doc-comment-field>: - WARNING: Should only have one field
// CHECK: - $$$: Not a field.
// CHECK: Empty field, OK:
// CHECK: */</doc-comment-block>
// CHECK: <kw>func</kw> baz() {}
/***/
func emptyDocBlockComment() {}
// CHECK: <doc-comment-block>/***/</doc-comment-block>
// CHECK: <kw>func</kw> emptyDocBlockComment() {}
/**
*/
func emptyDocBlockComment2() {}
// CHECK: <doc-comment-block>/**
// CHECK: */
// CHECK: <kw>func</kw> emptyDocBlockComment2() {}
/** */
func emptyDocBlockComment3() {}
// CHECK: <doc-comment-block>/** */
// CHECK: <kw>func</kw> emptyDocBlockComment3() {}
/**/
func malformedBlockComment(f : () throws -> ()) rethrows {}
// CHECK: <doc-comment-block>/**/</doc-comment-block>
// CHECK: <kw>func</kw> malformedBlockComment(f : () <kw>throws</kw> -> ()) <attr-builtin>rethrows</attr-builtin> {}
//: playground doc comment line
func playgroundCommentLine(f : () throws -> ()) rethrows {}
// CHECK: <comment-line>//: playground doc comment line</comment-line>
/*:
playground doc comment multi-line
*/
func playgroundCommentMultiLine(f : () throws -> ()) rethrows {}
// CHECK: <comment-block>/*:
// CHECK: playground doc comment multi-line
// CHECK: */</comment-block>
/// [strict weak ordering](http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings)
// CHECK: <doc-comment-line>/// [strict weak ordering](<comment-url>http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings</comment-url>
func funcTakingFor(for internalName: Int) {}
// CHECK: <kw>func</kw> funcTakingFor(for internalName: <type>Int</type>) {}
func funcTakingIn(in internalName: Int) {}
// CHECK: <kw>func</kw> funcTakingIn(in internalName: <type>Int</type>) {}
_ = 123
// CHECK: <int>123</int>
_ = -123
// CHECK: <int>-123</int>
_ = -1
// CHECK: <int>-1</int>
_ = -0x123
// CHECK: <int>-0x123</int>
_ = -3.1e-5
// CHECK: <float>-3.1e-5</float>
/** aaa
- returns: something
*/
// CHECK: - <doc-comment-field>returns</doc-comment-field>: something
let filename = #file
// CHECK: <kw>let</kw> filename = <kw>#file</kw>
let line = #line
// CHECK: <kw>let</kw> line = <kw>#line</kw>
let column = #column
// CHECK: <kw>let</kw> column = <kw>#column</kw>
let function = #function
// CHECK: <kw>let</kw> function = <kw>#function</kw>
let image = #imageLiteral(resourceName: "cloud.png")
// CHECK: <kw>let</kw> image = <object-literal>#imageLiteral(resourceName: "cloud.png")</object-literal>
let file = #fileLiteral(resourceName: "cloud.png")
// CHECK: <kw>let</kw> file = <object-literal>#fileLiteral(resourceName: "cloud.png")</object-literal>
let black = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
// CHECK: <kw>let</kw> black = <object-literal>#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)</object-literal>
let rgb = [#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1),
#colorLiteral(red: 0, green: 1, blue: 0, alpha: 1),
#colorLiteral(red: 0, green: 0, blue: 1, alpha: 1)]
// CHECK: <kw>let</kw> rgb = [<object-literal>#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)</object-literal>,
// CHECK: <object-literal>#colorLiteral(red: 0, green: 1, blue: 0, alpha: 1)</object-literal>,
// CHECK: <object-literal>#colorLiteral(red: 0, green: 0, blue: 1, alpha: 1)</object-literal>]
"--\"\(x) --"
// CHECK: <str>"--\"</str>\<anchor>(</anchor>x<anchor>)</anchor><str> --"</str>
func keywordAsLabel1(in: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel1(in: <type>Int</type>) {}
func keywordAsLabel2(for: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel2(for: <type>Int</type>) {}
func keywordAsLabel3(if: Int, for: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel3(if: <type>Int</type>, for: <type>Int</type>) {}
func keywordAsLabel4(_: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel4(<kw>_</kw>: <type>Int</type>) {}
func keywordAsLabel5(_: Int, for: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel5(<kw>_</kw>: <type>Int</type>, for: <type>Int</type>) {}
func keywordAsLabel6(if let: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel6(if <kw>let</kw>: <type>Int</type>) {}
func foo1() {
// CHECK: <kw>func</kw> foo1() {
keywordAsLabel1(in: 1)
// CHECK: keywordAsLabel1(in: <int>1</int>)
keywordAsLabel2(for: 1)
// CHECK: keywordAsLabel2(for: <int>1</int>)
keywordAsLabel3(if: 1, for: 2)
// CHECK: keywordAsLabel3(if: <int>1</int>, for: <int>2</int>)
keywordAsLabel5(1, for: 2)
// CHECK: keywordAsLabel5(<int>1</int>, for: <int>2</int>)
_ = (if: 0, for: 2)
// CHECK: <kw>_</kw> = (if: <int>0</int>, for: <int>2</int>)
_ = (_: 0, _: 2)
// CHECK: <kw>_</kw> = (<kw>_</kw>: <int>0</int>, <kw>_</kw>: <int>2</int>)
}
func foo2(O1 : Int?, O2: Int?, O3: Int?) {
guard let _ = O1, var _ = O2, let _ = O3 else { }
// CHECK: <kw>guard</kw> <kw>let</kw> <kw>_</kw> = O1, <kw>var</kw> <kw>_</kw> = O2, <kw>let</kw> <kw>_</kw> = O3 <kw>else</kw> { }
if let _ = O1, var _ = O2, let _ = O3 {}
// CHECK: <kw>if</kw> <kw>let</kw> <kw>_</kw> = O1, <kw>var</kw> <kw>_</kw> = O2, <kw>let</kw> <kw>_</kw> = O3 {}
}
// Keep this as the last test
/**
Trailing off ...
func unterminatedBlockComment() {}
// CHECK: <comment-line>// Keep this as the last test</comment-line>
// CHECK: <doc-comment-block>/**
// CHECK: Trailing off ...
// CHECK: func unterminatedBlockComment() {}
// CHECK: </doc-comment-block>
| apache-2.0 | d8575e65d0862668a15843623a2a21e8 | 36.48398 | 178 | 0.606217 | 2.890131 | false | false | false | false |
xedin/swift | test/type/subclass_composition.swift | 1 | 19753 | // RUN: %target-typecheck-verify-swift
protocol P1 {
typealias DependentInConcreteConformance = Self
}
class Base<T> : P1 {
typealias DependentClass = T
required init(classInit: ()) {}
func classSelfReturn() -> Self {}
}
protocol P2 {
typealias FullyConcrete = Int
typealias DependentProtocol = Self
init(protocolInit: ())
func protocolSelfReturn() -> Self
}
typealias BaseAndP2<T> = Base<T> & P2
typealias BaseIntAndP2 = BaseAndP2<Int>
class Derived : Base<Int>, P2 {
required init(protocolInit: ()) {
super.init(classInit: ())
}
required init(classInit: ()) {
super.init(classInit: ())
}
func protocolSelfReturn() -> Self {}
}
class Other : Base<Int> {}
typealias OtherAndP2 = Other & P2
protocol P3 : class {}
struct Unrelated {}
//
// If a class conforms to a protocol concretely, the resulting protocol
// composition type should be equivalent to the class type.
//
// FIXME: Not implemented yet.
//
func alreadyConforms<T>(_: Base<T>) {} // expected-note {{'alreadyConforms' previously declared here}}
func alreadyConforms<T>(_: Base<T> & P1) {} // expected-note {{'alreadyConforms' previously declared here}}
func alreadyConforms<T>(_: Base<T> & AnyObject) {} // expected-error {{invalid redeclaration of 'alreadyConforms'}}
func alreadyConforms<T>(_: Base<T> & P1 & AnyObject) {} // expected-error {{invalid redeclaration of 'alreadyConforms'}}
func alreadyConforms(_: P3) {}
func alreadyConforms(_: P3 & AnyObject) {}
// SE-0156 stipulates that a composition can contain multiple classes, as long
// as they are all the same.
func basicDiagnostics(
_: Base<Int> & Base<Int>,
_: Base<Int> & Derived, // expected-error{{protocol-constrained type cannot contain class 'Derived' because it already contains class 'Base<Int>'}}
// Invalid typealias case
_: Derived & OtherAndP2, // expected-error{{protocol-constrained type cannot contain class 'Other' because it already contains class 'Derived'}}
// Valid typealias case
_: OtherAndP2 & P3) {}
// A composition containing only a single class is actually identical to
// the class type itself.
struct Box<T : Base<Int>> {}
func takesBox(_: Box<Base<Int>>) {}
func passesBox(_ b: Box<Base<Int> & Base<Int>>) {
takesBox(b)
}
// Test that subtyping behaves as you would expect.
func basicSubtyping(
base: Base<Int>,
baseAndP1: Base<Int> & P1,
baseAndP2: Base<Int> & P2,
baseAndP2AndAnyObject: Base<Int> & P2 & AnyObject,
baseAndAnyObject: Base<Int> & AnyObject,
derived: Derived,
derivedAndP2: Derived & P2,
derivedAndP3: Derived & P3,
derivedAndAnyObject: Derived & AnyObject,
p1AndAnyObject: P1 & AnyObject,
p2AndAnyObject: P2 & AnyObject,
anyObject: AnyObject) {
// Errors
let _: Base & P2 = base // expected-error {{value of type 'Base<Int>' does not conform to specified type 'P2'}}
let _: Base<Int> & P2 = base // expected-error {{value of type 'Base<Int>' does not conform to specified type 'P2'}}
let _: P3 = baseAndP1 // expected-error {{value of type 'Base<Int> & P1' does not conform to specified type 'P3'}}
let _: P3 = baseAndP2 // expected-error {{value of type 'Base<Int> & P2' does not conform to specified type 'P3'}}
let _: Derived = baseAndP1 // expected-error {{cannot convert value of type 'Base<Int> & P1' to specified type 'Derived'}}
let _: Derived = baseAndP2 // expected-error {{cannot convert value of type 'Base<Int> & P2' to specified type 'Derived'}}
let _: Derived & P2 = baseAndP2 // expected-error {{value of type 'Base<Int> & P2' does not conform to specified type 'Derived & P2'}}
let _ = Unrelated() as Derived & P2 // expected-error {{value of type 'Unrelated' does not conform to 'Derived & P2' in coercion}}
let _ = Unrelated() as? Derived & P2 // expected-warning {{always fails}}
let _ = baseAndP2 as Unrelated // expected-error {{cannot convert value of type 'Base<Int> & P2' to type 'Unrelated' in coercion}}
let _ = baseAndP2 as? Unrelated // expected-warning {{always fails}}
// Different behavior on Linux vs Darwin because of id-as-Any.
// let _ = Unrelated() as AnyObject
// let _ = Unrelated() as? AnyObject
let _ = anyObject as Unrelated // expected-error {{'AnyObject' is not convertible to 'Unrelated'; did you mean to use 'as!' to force downcast?}}
let _ = anyObject as? Unrelated
// No-ops
let _: Base & P1 = base
let _: Base<Int> & P1 = base
let _: Base & AnyObject = base
let _: Base<Int> & AnyObject = base
let _: Derived & AnyObject = derived
let _ = base as Base<Int> & P1
let _ = base as Base<Int> & AnyObject
let _ = derived as Derived & AnyObject
let _ = base as? Base<Int> & P1 // expected-warning {{always succeeds}}
let _ = base as? Base<Int> & AnyObject // expected-warning {{always succeeds}}
let _ = derived as? Derived & AnyObject // expected-warning {{always succeeds}}
// Erasing superclass constraint
let _: P1 = baseAndP1
let _: P1 & AnyObject = baseAndP1
let _: P1 = derived
let _: P1 & AnyObject = derived
let _: AnyObject = baseAndP1
let _: AnyObject = baseAndP2
let _: AnyObject = derived
let _: AnyObject = derivedAndP2
let _: AnyObject = derivedAndP3
let _: AnyObject = derivedAndAnyObject
let _ = baseAndP1 as P1
let _ = baseAndP1 as P1 & AnyObject
let _ = derived as P1
let _ = derived as P1 & AnyObject
let _ = baseAndP1 as AnyObject
let _ = derivedAndAnyObject as AnyObject
let _ = baseAndP1 as? P1 // expected-warning {{always succeeds}}
let _ = baseAndP1 as? P1 & AnyObject // expected-warning {{always succeeds}}
let _ = derived as? P1 // expected-warning {{always succeeds}}
let _ = derived as? P1 & AnyObject // expected-warning {{always succeeds}}
let _ = baseAndP1 as? AnyObject // expected-warning {{always succeeds}}
let _ = derivedAndAnyObject as? AnyObject // expected-warning {{always succeeds}}
// Erasing conformance constraint
let _: Base = baseAndP1
let _: Base<Int> = baseAndP1
let _: Base = derivedAndP3
let _: Base<Int> = derivedAndP3
let _: Derived = derivedAndP2
let _: Derived = derivedAndAnyObject
let _ = baseAndP1 as Base<Int>
let _ = derivedAndP3 as Base<Int>
let _ = derivedAndP2 as Derived
let _ = derivedAndAnyObject as Derived
let _ = baseAndP1 as? Base<Int> // expected-warning {{always succeeds}}
let _ = derivedAndP3 as? Base<Int> // expected-warning {{always succeeds}}
let _ = derivedAndP2 as? Derived // expected-warning {{always succeeds}}
let _ = derivedAndAnyObject as? Derived // expected-warning {{always succeeds}}
// Upcasts
let _: Base & P2 = derived
let _: Base<Int> & P2 = derived
let _: Base & P2 & AnyObject = derived
let _: Base<Int> & P2 & AnyObject = derived
let _: Base & P3 = derivedAndP3
let _: Base<Int> & P3 = derivedAndP3
let _ = derived as Base<Int> & P2
let _ = derived as Base<Int> & P2 & AnyObject
let _ = derivedAndP3 as Base<Int> & P3
let _ = derived as? Base<Int> & P2 // expected-warning {{always succeeds}}
let _ = derived as? Base<Int> & P2 & AnyObject // expected-warning {{always succeeds}}
let _ = derivedAndP3 as? Base<Int> & P3 // expected-warning {{always succeeds}}
// Calling methods with Self return
let _: Base & P2 = baseAndP2.classSelfReturn()
let _: Base<Int> & P2 = baseAndP2.classSelfReturn()
let _: Base & P2 = baseAndP2.protocolSelfReturn()
let _: Base<Int> & P2 = baseAndP2.protocolSelfReturn()
// Downcasts
let _ = baseAndP2 as Derived // expected-error {{did you mean to use 'as!' to force downcast?}}
let _ = baseAndP2 as? Derived
let _ = baseAndP2 as Derived & P3 // expected-error {{did you mean to use 'as!' to force downcast?}}
let _ = baseAndP2 as? Derived & P3
let _ = base as Derived & P2 // expected-error {{did you mean to use 'as!' to force downcast?}}
let _ = base as? Derived & P2
// Invalid cases
let _ = derived as Other & P2 // expected-error {{value of type 'Derived' does not conform to 'Other & P2' in coercion}}
let _ = derived as? Other & P2 // expected-warning {{always fails}}
let _ = derivedAndP3 as Other // expected-error {{cannot convert value of type 'Derived & P3' to type 'Other' in coercion}}
let _ = derivedAndP3 as? Other // expected-warning {{always fails}}
let _ = derivedAndP3 as Other & P3 // expected-error {{value of type 'Derived & P3' does not conform to 'Other & P3' in coercion}}
let _ = derivedAndP3 as? Other & P3 // expected-warning {{always fails}}
let _ = derived as Other // expected-error {{cannot convert value of type 'Derived' to type 'Other' in coercion}}
let _ = derived as? Other // expected-warning {{always fails}}
}
// Test conversions in return statements
func eraseProtocolInReturn(baseAndP2: Base<Int> & P2) -> Base<Int> {
return baseAndP2
}
func eraseProtocolInReturn(baseAndP2: (Base<Int> & P2)!) -> Base<Int> {
return baseAndP2
}
func eraseProtocolInReturn(baseAndP2: Base<Int> & P2) -> Base<Int>? {
return baseAndP2
}
func eraseClassInReturn(baseAndP2: Base<Int> & P2) -> P2 {
return baseAndP2
}
func eraseClassInReturn(baseAndP2: (Base<Int> & P2)!) -> P2 {
return baseAndP2
}
func eraseClassInReturn(baseAndP2: Base<Int> & P2) -> P2? {
return baseAndP2
}
func upcastToExistentialInReturn(derived: Derived) -> Base<Int> & P2 {
return derived
}
func upcastToExistentialInReturn(derived: Derived!) -> Base<Int> & P2 {
return derived
}
func upcastToExistentialInReturn(derived: Derived) -> (Base<Int> & P2)? {
return derived
}
func takesBase<T>(_: Base<T>) {}
func takesP2(_: P2) {}
func takesBaseMetatype<T>(_: Base<T>.Type) {}
func takesP2Metatype(_: P2.Type) {}
func takesBaseIntAndP2(_ x: Base<Int> & P2) {
takesBase(x)
takesP2(x)
}
func takesBaseIntAndP2Metatype(_ x: (Base<Int> & P2).Type) {
takesBaseMetatype(x)
takesP2Metatype(x)
}
func takesDerived(x: Derived) {
takesBaseIntAndP2(x)
}
func takesDerivedMetatype(x: Derived.Type) {
takesBaseIntAndP2Metatype(x)
}
//
// Looking up member types of subclass existentials.
//
func dependentMemberTypes<T : BaseIntAndP2>(
_: T.DependentInConcreteConformance,
_: T.DependentProtocol,
_: T.DependentClass,
_: T.FullyConcrete,
_: BaseIntAndP2.DependentInConcreteConformance, // FIXME expected-error {{}}
_: BaseIntAndP2.DependentProtocol, // expected-error {{type alias 'DependentProtocol' can only be used with a concrete type or generic parameter base}}
_: BaseIntAndP2.DependentClass,
_: BaseIntAndP2.FullyConcrete) {}
func conformsToAnyObject<T : AnyObject>(_: T) {}
func conformsToP1<T : P1>(_: T) {}
func conformsToP2<T : P2>(_: T) {}
func conformsToBaseIntAndP2<T : Base<Int> & P2>(_: T) {}
// expected-note@-1 2 {{where 'T' = 'Base<String>'}}
// expected-note@-2 {{where 'T' = 'Base<Int>'}}
func conformsToBaseIntAndP2WithWhereClause<T>(_: T) where T : Base<Int> & P2 {}
// expected-note@-1 {{where 'T' = 'Base<String>'}}
// expected-note@-2 {{where 'T' = 'Base<Int>'}}
class FakeDerived : Base<String>, P2 {
required init(classInit: ()) {
super.init(classInit: ())
}
required init(protocolInit: ()) {
super.init(classInit: ())
}
func protocolSelfReturn() -> Self { return self }
}
//
// Metatype subtyping.
//
func metatypeSubtyping(
base: Base<Int>.Type,
derived: Derived.Type,
derivedAndAnyObject: (Derived & AnyObject).Type,
baseIntAndP2: (Base<Int> & P2).Type,
baseIntAndP2AndAnyObject: (Base<Int> & P2 & AnyObject).Type) {
// Erasing conformance constraint
let _: Base<Int>.Type = baseIntAndP2
let _: Base<Int>.Type = baseIntAndP2AndAnyObject
let _: Derived.Type = derivedAndAnyObject
let _: BaseAndP2<Int>.Type = baseIntAndP2AndAnyObject
let _ = baseIntAndP2 as Base<Int>.Type
let _ = baseIntAndP2AndAnyObject as Base<Int>.Type
let _ = derivedAndAnyObject as Derived.Type
let _ = baseIntAndP2AndAnyObject as BaseAndP2<Int>.Type
let _ = baseIntAndP2 as? Base<Int>.Type // expected-warning {{always succeeds}}
let _ = baseIntAndP2AndAnyObject as? Base<Int>.Type // expected-warning {{always succeeds}}
let _ = derivedAndAnyObject as? Derived.Type // expected-warning {{always succeeds}}
let _ = baseIntAndP2AndAnyObject as? BaseAndP2<Int>.Type // expected-warning {{always succeeds}}
// Upcast
let _: BaseAndP2<Int>.Type = derived
let _: BaseAndP2<Int>.Type = derivedAndAnyObject
let _ = derived as BaseAndP2<Int>.Type
let _ = derivedAndAnyObject as BaseAndP2<Int>.Type
let _ = derived as? BaseAndP2<Int>.Type // expected-warning {{always succeeds}}
let _ = derivedAndAnyObject as? BaseAndP2<Int>.Type // expected-warning {{always succeeds}}
// Erasing superclass constraint
let _: P2.Type = baseIntAndP2
let _: P2.Type = derived
let _: P2.Type = derivedAndAnyObject
let _: (P2 & AnyObject).Type = derived
let _: (P2 & AnyObject).Type = derivedAndAnyObject
let _ = baseIntAndP2 as P2.Type
let _ = derived as P2.Type
let _ = derivedAndAnyObject as P2.Type
let _ = derived as (P2 & AnyObject).Type
let _ = derivedAndAnyObject as (P2 & AnyObject).Type
let _ = baseIntAndP2 as? P2.Type // expected-warning {{always succeeds}}
let _ = derived as? P2.Type // expected-warning {{always succeeds}}
let _ = derivedAndAnyObject as? P2.Type // expected-warning {{always succeeds}}
let _ = derived as? (P2 & AnyObject).Type // expected-warning {{always succeeds}}
let _ = derivedAndAnyObject as? (P2 & AnyObject).Type // expected-warning {{always succeeds}}
// Initializers
let _: Base<Int> & P2 = baseIntAndP2.init(classInit: ())
let _: Base<Int> & P2 = baseIntAndP2.init(protocolInit: ())
let _: Base<Int> & P2 & AnyObject = baseIntAndP2AndAnyObject.init(classInit: ())
let _: Base<Int> & P2 & AnyObject = baseIntAndP2AndAnyObject.init(protocolInit: ())
let _: Derived = derived.init(classInit: ())
let _: Derived = derived.init(protocolInit: ())
let _: Derived & AnyObject = derivedAndAnyObject.init(classInit: ())
let _: Derived & AnyObject = derivedAndAnyObject.init(protocolInit: ())
}
//
// Conformance relation.
//
func conformsTo<T1 : P2, T2 : Base<Int> & P2>(
anyObject: AnyObject,
p1: P1,
p2: P2,
p3: P3,
base: Base<Int>,
badBase: Base<String>,
derived: Derived,
fakeDerived: FakeDerived,
p2Archetype: T1,
baseAndP2Archetype: T2) {
// FIXME: Uninformative diagnostics
// Errors
conformsToAnyObject(p1)
// expected-error@-1 {{cannot invoke 'conformsToAnyObject' with an argument list of type '(P1)'}}
// expected-note@-2 {{expected an argument list of type '(T)'}}
conformsToP1(p1)
// expected-error@-1 {{protocol type 'P1' cannot conform to 'P1' because only concrete types can conform to protocols}}
// FIXME: Following diagnostics are not great because when
// `conformsTo*` methods are re-typechecked, they loose information
// about `& P2` in generic parameter.
conformsToBaseIntAndP2(base)
// expected-error@-1 {{argument type 'Base<Int>' does not conform to expected type 'P2'}}
conformsToBaseIntAndP2(badBase)
// expected-error@-1 {{global function 'conformsToBaseIntAndP2' requires that 'Base<String>' inherit from 'Base<Int>'}}
// expected-error@-2 {{argument type 'Base<String>' does not conform to expected type 'P2'}}
conformsToBaseIntAndP2(fakeDerived)
// expected-error@-1 {{global function 'conformsToBaseIntAndP2' requires that 'Base<String>' inherit from 'Base<Int>'}}
conformsToBaseIntAndP2WithWhereClause(fakeDerived)
// expected-error@-1 {{global function 'conformsToBaseIntAndP2WithWhereClause' requires that 'Base<String>' inherit from 'Base<Int>'}}
conformsToBaseIntAndP2(p2Archetype)
// expected-error@-1 {{global function 'conformsToBaseIntAndP2' requires that 'Base<Int>' conform to 'P2'}}
conformsToBaseIntAndP2WithWhereClause(p2Archetype)
// expected-error@-1 {{global function 'conformsToBaseIntAndP2WithWhereClause' requires that 'Base<Int>' conform to 'P2'}}
// Good
conformsToAnyObject(anyObject)
conformsToAnyObject(baseAndP2Archetype)
conformsToP1(derived)
conformsToP1(baseAndP2Archetype)
conformsToP2(derived)
conformsToP2(baseAndP2Archetype)
conformsToBaseIntAndP2(derived)
conformsToBaseIntAndP2(baseAndP2Archetype)
conformsToBaseIntAndP2WithWhereClause(derived)
conformsToBaseIntAndP2WithWhereClause(baseAndP2Archetype)
}
// Subclass existentials inside inheritance clauses
class CompositionInClassInheritanceClauseAlias : BaseIntAndP2 {
required init(classInit: ()) {
super.init(classInit: ())
}
required init(protocolInit: ()) {
super.init(classInit: ())
}
func protocolSelfReturn() -> Self { return self }
func asBase() -> Base<Int> { return self }
}
class CompositionInClassInheritanceClauseDirect : Base<Int> & P2 {
required init(classInit: ()) {
super.init(classInit: ())
}
required init(protocolInit: ()) {
super.init(classInit: ())
}
func protocolSelfReturn() -> Self { return self }
func asBase() -> Base<Int> { return self }
}
protocol CompositionInAssociatedTypeInheritanceClause {
associatedtype A : BaseIntAndP2
}
// Members of metatypes and existential metatypes
protocol ProtocolWithStaticMember {
static func staticProtocolMember()
func instanceProtocolMember()
}
class ClassWithStaticMember {
static func staticClassMember() {}
func instanceClassMember() {}
}
func staticMembers(
m1: (ProtocolWithStaticMember & ClassWithStaticMember).Protocol,
m2: (ProtocolWithStaticMember & ClassWithStaticMember).Type) {
_ = m1.staticProtocolMember() // expected-error {{static member 'staticProtocolMember' cannot be used on protocol metatype '(ClassWithStaticMember & ProtocolWithStaticMember).Protocol'}}
_ = m1.staticProtocolMember // expected-error {{static member 'staticProtocolMember' cannot be used on protocol metatype '(ClassWithStaticMember & ProtocolWithStaticMember).Protocol'}}
_ = m1.staticClassMember() // expected-error {{static member 'staticClassMember' cannot be used on protocol metatype '(ClassWithStaticMember & ProtocolWithStaticMember).Protocol'}}
_ = m1.staticClassMember // expected-error {{static member 'staticClassMember' cannot be used on protocol metatype '(ClassWithStaticMember & ProtocolWithStaticMember).Protocol'}}
_ = m1.instanceProtocolMember
_ = m1.instanceClassMember
_ = m2.staticProtocolMember()
_ = m2.staticProtocolMember
_ = m2.staticClassMember()
_ = m2.staticClassMember
_ = m2.instanceProtocolMember // expected-error {{instance member 'instanceProtocolMember' cannot be used on type 'ClassWithStaticMember & ProtocolWithStaticMember'}}
_ = m2.instanceClassMember // expected-error {{instance member 'instanceClassMember' cannot be used on type 'ClassWithStaticMember & ProtocolWithStaticMember'}}
}
// Make sure we correctly form subclass existentials in expression context.
func takesBaseIntAndPArray(_: [Base<Int> & P2]) {}
func passesBaseIntAndPArray() {
takesBaseIntAndPArray([Base<Int> & P2]())
}
//
// Superclass constrained generic parameters
//
struct DerivedBox<T : Derived> {}
// expected-note@-1 {{requirement specified as 'T' : 'Derived' [with T = Derived & P3]}}
func takesBoxWithP3(_: DerivedBox<Derived & P3>) {}
// expected-error@-1 {{'DerivedBox' requires that 'Derived & P3' inherit from 'Derived'}}
// A bit of a tricky setup -- the real problem is that matchTypes() did the
// wrong thing when solving a Bind constraint where both sides were protocol
// compositions, but one of them had a superclass constraint containing type
// variables. We were checking type equality in this case, which is not
// correct; we have to do a 'deep equality' check, recursively matching the
// superclass types.
struct Generic<T> {
var _x: (Base<T> & P2)!
var x: (Base<T> & P2)? {
get { return _x }
set { _x = newValue }
_modify {
yield &_x
}
}
} | apache-2.0 | b47c47d42b857c7f8133941c4922f79d | 34.916364 | 188 | 0.700299 | 3.643793 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Priority Queue/759_Employee Free Time.swift | 1 | 2644 | // 759_Employee Free Time
// https://leetcode.com/problems/employee-free-time/
//
// Created by HongHao Zhang on 10/10/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// We are given a list schedule of employees, which represents the working time for each employee.
//
//Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order.
//
//Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order.
//
//Example 1:
//
//Input: schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]]
//Output: [[3,4]]
//Explanation:
//There are a total of three employees, and all common
//free time intervals would be [-inf, 1], [3, 4], [10, inf].
//We discard any intervals that contain inf as they aren't finite.
//
//
//Example 2:
//
//Input: schedule = [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]]
//Output: [[5,6],[7,9]]
//
//
//(Even though we are representing Intervals in the form [x, y], the objects inside are Intervals, not lists or arrays. For example, schedule[0][0].start = 1, schedule[0][0].end = 2, and schedule[0][0][0] is not defined.)
//
//Also, we wouldn't include intervals like [5, 5] in our answer, as they have zero length.
//
//Note:
//
//schedule and schedule[i] are lists with lengths in range [1, 50].
//0 <= schedule[i].start < schedule[i].end <= 10^8.
//NOTE: input types have been changed on June 17, 2019. Please reset to default code definition to get new method signature.
//
import Foundation
class Num759 {
// MARK: - Priority Queue
// 存入end time,dequeue前检查size是否为0
// MARK: - 从左到右扫描,用balance来记录是否free
// 当free的时候,保存interval
// """
// # Definition for an Interval.
// class Interval(object):
// def __init__(self, start, end):
// self.start = start
// self.end = end
// """
// class Solution(object):
// def employeeFreeTime(self, avails):
// """
// :type schedule: list<list<Interval>>
// :rtype: list<Interval>
// """
// OPEN, CLOSE = 0, 1
//
// events = []
// for emp in avails:
// for iv in emp:
// events.append((iv.start, OPEN))
// events.append((iv.end, CLOSE))
//
// events.sort()
// ans = []
// prev = None
// bal = 0
// for t, cmd in events:
// if bal == 0 and prev is not None:
// ans.append(Interval(prev, t))
//
// bal += 1 if cmd is OPEN else -1
// prev = t
//
// return ans
}
| mit | 14478e3a6b298c6409fa978b865296d5 | 30.144578 | 221 | 0.586847 | 3.370274 | false | false | false | false |
airspeedswift/swift | test/IRGen/abitypes.swift | 3 | 46960 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/abi %s -emit-ir -enable-objc-interop | %FileCheck -check-prefix=%target-cpu-%target-os %s
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux, windows, openbsd
import gadget
import Foundation
@objc protocol P1 {}
@objc protocol P2 {}
@objc protocol Work {
func doStuff(_ x: Int64)
}
// armv7s-ios: [[ARMV7S_MYRECT:%.*]] = type { float, float, float, float }
// arm64-ios: [[ARM64_MYRECT:%.*]] = type { float, float, float, float }
// arm64e-ios: [[ARM64E_MYRECT:%.*]] = type { float, float, float, float }
// arm64-tvos: [[ARM64_MYRECT:%.*]] = type { float, float, float, float }
// armv7k-watchos: [[ARMV7K_MYRECT:%.*]] = type { float, float, float, float }
// arm64-macosx: [[ARM64_MYRECT:%.*]] = type { float, float, float, float }
class Foo {
// x86_64-macosx: define hidden swiftcc { float, float, float, float } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} {
// x86_64-macosx: define hidden { <2 x float>, <2 x float> } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1) {{[#0-9]*}} {
// x86_64-ios: define hidden swiftcc { float, float, float, float } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} {
// x86_64-ios: define hidden { <2 x float>, <2 x float> } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1) {{[#0-9]*}} {
// i386-ios: define hidden swiftcc void @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%TSo6MyRectV* noalias nocapture sret %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// i386-ios: define hidden void @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(%TSo6MyRectV* noalias nocapture sret %0, i8* %1, i8* %2) {{[#0-9]*}} {
// armv7-ios: define hidden swiftcc { float, float, float, float } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} {
// armv7-ios: define hidden void @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(%TSo6MyRectV* noalias nocapture sret %0, i8* %1, i8* %2) {{[#0-9]*}} {
// armv7s-ios: define hidden swiftcc { float, float, float, float } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} {
// armv7s-ios: define hidden void @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(%TSo6MyRectV* noalias nocapture sret %0, i8* %1, i8* %2) {{[#0-9]*}} {
// arm64-ios: define hidden swiftcc { float, float, float, float } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} {
// arm64-ios: define hidden [[ARM64_MYRECT]] @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1) {{[#0-9]*}} {
// x86_64-tvos: define hidden swiftcc { float, float, float, float } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} {
// x86_64-tvos: define hidden { <2 x float>, <2 x float> } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1) {{[#0-9]*}} {
// arm64-tvos: define hidden swiftcc { float, float, float, float } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} {
// arm64-tvos: define hidden [[ARM64_MYRECT]] @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1) {{[#0-9]*}} {
// i386-watchos: define hidden swiftcc void @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%TSo6MyRectV* noalias nocapture sret %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// i386-watchos: define hidden void @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(%TSo6MyRectV* noalias nocapture sret %0, i8* %1, i8* %2) {{[#0-9]*}} {
// armv7k-watchos: define hidden swiftcc { float, float, float, float } @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} {
// armv7k-watchos: define hidden [[ARMV7K_MYRECT]] @"$s8abitypes3FooC3bar{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1) {{[#0-9]*}} {
@objc dynamic func bar() -> MyRect {
return MyRect(x: 1, y: 2, width: 3, height: 4)
}
// x86_64-macosx: define hidden swiftcc double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F"(double %0, double %1, double %2, double %3, %T8abitypes3FooC* swiftself %4) {{.*}} {
// x86_64-macosx: define hidden double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, %TSo6CGRectV* byval align 8 %2) {{[#0-9]*}} {
// armv7-ios: define hidden swiftcc double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} {
// armv7-ios: define hidden double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, [4 x i32] %2) {{[#0-9]*}} {
// armv7s-ios: define hidden swiftcc double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} {
// armv7s-ios: define hidden double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, [4 x i32] %2) {{[#0-9]*}} {
// armv7k-watchos: define hidden swiftcc double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} {
// armv7k-watchos: define hidden double @"$s8abitypes3FooC14getXFromNSRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, [4 x float] %2) {{[#0-9]*}} {
@objc dynamic func getXFromNSRect(_ r: NSRect) -> Double {
return Double(r.origin.x)
}
// x86_64-macosx: define hidden swiftcc float @"$s8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} {
// x86_64-macosx: define hidden float @"$s8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, <2 x float> %2, <2 x float> %3) {{[#0-9]*}} {
// armv7-ios: define hidden swiftcc float @"$s8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} {
// armv7-ios: define hidden float @"$s8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, [4 x i32] %2) {{[#0-9]*}} {
// armv7s-ios: define hidden swiftcc float @"$s8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} {
// armv7s-ios: define hidden float @"$s8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, [4 x i32] %2) {{[#0-9]*}} {
// armv7k-watchos: define hidden swiftcc float @"$s8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} {
// armv7k-watchos: define hidden float @"$s8abitypes3FooC12getXFromRect{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, [4 x float] %2) {{[#0-9]*}} {
@objc dynamic func getXFromRect(_ r: MyRect) -> Float {
return r.x
}
// Call from Swift entrypoint with exploded Rect to @objc entrypoint
// with unexploded ABI-coerced type.
// x86_64-macosx: define hidden swiftcc float @"$s8abitypes3FooC17getXFromRectSwift{{.*}}"(float %0, float %1, float %2, float %3, [[SELF:%.*]]* swiftself %4) {{.*}} {
// x86_64-macosx: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 8
// x86_64-macosx: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 8
// x86_64-macosx: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to { <2 x float>, <2 x float> }*
// x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 0
// x86_64-macosx: [[FIRST_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]]
// x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 1
// x86_64-macosx: [[SECOND_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]]
// x86_64-macosx: [[SELFCAST:%.*]] = bitcast [[SELF]]* %4 to i8*
// x86_64-macosx: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, <2 x float>, <2 x float>)*)(i8* [[SELFCAST]], i8* [[SEL]], <2 x float> [[FIRST_HALF]], <2 x float> [[SECOND_HALF]])
// armv7-ios: define hidden swiftcc float @"$s8abitypes3FooC17getXFromRectSwift{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, [[SELF:%.*]]* swiftself %4) {{.*}} {
// armv7-ios: [[DEBUGVAR:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4
// armv7-ios: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4
// armv7-ios: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 4
// armv7-ios: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to [4 x i32]*
// armv7-ios: [[LOADED:%.*]] = load [4 x i32], [4 x i32]* [[CAST]]
// armv7-ios: [[SELFCAST:%.*]] = bitcast [[SELF]]* %4 to i8*
// armv7-ios: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, [4 x i32])*)(i8* [[SELFCAST]], i8* [[SEL]], [4 x i32] [[LOADED]])
// armv7s-ios: define hidden swiftcc float @"$s8abitypes3FooC17getXFromRectSwift{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, [[SELF:%.*]]* swiftself %4) {{.*}} {
// armv7s-ios: [[DEBUGVAR:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4
// armv7s-ios: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4
// armv7s-ios: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 4
// armv7s-ios: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to [4 x i32]*
// armv7s-ios: [[LOADED:%.*]] = load [4 x i32], [4 x i32]* [[CAST]]
// armv7s-ios: [[SELFCAST:%.*]] = bitcast [[SELF]]* %4 to i8*
// armv7s-ios: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, [4 x i32])*)(i8* [[SELFCAST]], i8* [[SEL]], [4 x i32] [[LOADED]])
// armv7k-watchos: define hidden swiftcc float @"$s8abitypes3FooC17getXFromRectSwift{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, [[SELF:%.*]]* swiftself %4) {{.*}} {
// armv7k-watchos: [[DEBUGVAR:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4
// armv7k-watchos: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4
// armv7k-watchos: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 4
// armv7k-watchos: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to [4 x float]*
// armv7k-watchos: [[LOADED:%.*]] = load [4 x float], [4 x float]* [[CAST]]
// armv7k-watchos: [[SELFCAST:%.*]] = bitcast [[SELF]]* %4 to i8*
// armv7k-watchos: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, [4 x float])*)(i8* [[SELFCAST]], i8* [[SEL]], [4 x float] [[LOADED]])
func getXFromRectSwift(_ r: MyRect) -> Float {
return getXFromRect(r)
}
// Ensure that MyRect is passed as an indirect-byval on x86_64 because we run out of registers for direct arguments
// x86_64-macosx: define hidden float @"$s8abitypes3FooC25getXFromRectIndirectByVal{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, float %2, float %3, float %4, float %5, float %6, float %7, float %8, %TSo6MyRectV* byval align 8 %9) {{[#0-9]*}} {
@objc dynamic func getXFromRectIndirectByVal(_: Float, second _: Float,
third _: Float, fourth _: Float,
fifth _: Float, sixth _: Float,
seventh _: Float, withRect r: MyRect)
-> Float {
return r.x
}
// Make sure the caller-side from Swift also uses indirect-byval for the argument
// x86_64-macosx: define hidden swiftcc float @"$s8abitypes3FooC25getXFromRectIndirectSwift{{[_0-9a-zA-Z]*}}F"(float %0, float %1, float %2, float %3, %T8abitypes3FooC* swiftself %4) {{.*}} {
func getXFromRectIndirectSwift(_ r: MyRect) -> Float {
let f : Float = 1.0
// x86_64-macosx: alloca
// x86_64-macosx: alloca
// x86_64-macosx: [[TEMP:%.*]] = alloca [[TEMPTYPE:%.*]], align 8
// x86_64-macosx: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, float, float, float, float, float, float, float, [[TEMPTYPE]]*)*)(i8* %{{.*}}, i8* %{{.*}}, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, [[TEMPTYPE]]* byval align 8 [[TEMP]])
// x86_64-macosx: ret float [[RESULT]]
return getXFromRectIndirectByVal(f, second: f, third: f, fourth: f, fifth: f, sixth: f, seventh: f, withRect: r);
}
// x86_64 returns an HA of four floats directly in two <2 x float>
// x86_64-macosx: define hidden swiftcc float @"$s8abitypes3FooC4barc{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// x86_64-macosx: load i8*, i8** @"\01L_selector(newRect)", align 8
// x86_64-macosx: [[RESULT:%.*]] = call { <2 x float>, <2 x float> } bitcast (void ()* @objc_msgSend
// x86_64-macosx: store { <2 x float>, <2 x float> } [[RESULT]]
// x86_64-macosx: [[CAST:%.*]] = bitcast { <2 x float>, <2 x float> }*
// x86_64-macosx: load { float, float, float, float }, { float, float, float, float }* [[CAST]]
// x86_64-macosx: ret float
//
// armv7 returns an HA of four floats indirectly
// armv7-ios: define hidden swiftcc float @"$s8abitypes3FooC4barc{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// armv7-ios: [[RESULT:%.*]] = alloca [[RECTTYPE:%.*MyRect.*]], align 4
// armv7-ios: load i8*, i8** @"\01L_selector(newRect)", align 4
// armv7-ios: call void bitcast (void ()* @objc_msgSend_stret to void ([[RECTTYPE]]*, [[RECEIVER:.*]]*, i8*)*)([[RECTTYPE]]* noalias nocapture sret %call.aggresult
// armv7-ios: [[GEP1:%.*]] = getelementptr inbounds [[RECTTYPE]], [[RECTTYPE]]* [[RESULT]], i32 0, i32 1
// armv7-ios: [[GEP2:%.*]] = getelementptr inbounds {{.*}}, {{.*}}* [[GEP1]], i32 0, i32 0
// armv7-ios: [[RETVAL:%.*]] = load float, float* [[GEP2]], align 4
// armv7-ios: ret float [[RETVAL]]
//
// armv7s returns an HA of four floats indirectly
// armv7s-ios: define hidden swiftcc float @"$s8abitypes3FooC4barc{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// armv7s-ios: [[RESULT:%.*]] = alloca [[RECTTYPE:%.*MyRect.*]], align 4
// armv7s-ios: load i8*, i8** @"\01L_selector(newRect)", align 4
// armv7s-ios: call void bitcast (void ()* @objc_msgSend_stret to void ([[RECTTYPE]]*, [[RECEIVER:.*]]*, i8*)*)([[RECTTYPE]]* noalias nocapture sret %call.aggresult
// armv7s-ios: [[GEP1:%.*]] = getelementptr inbounds [[RECTTYPE]], [[RECTTYPE]]* [[RESULT]], i32 0, i32 1
// armv7s-ios: [[GEP2:%.*]] = getelementptr inbounds {{.*}}, {{.*}}* [[GEP1]], i32 0, i32 0
// armv7s-ios: [[RETVAL:%.*]] = load float, float* [[GEP2]], align 4
// armv7s-ios: ret float [[RETVAL]]
//
// armv7k returns an HA of four floats directly
// armv7k-watchos: define hidden swiftcc float @"$s8abitypes3FooC4barc{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// armv7k-watchos: load i8*, i8** @"\01L_selector(newRect)", align 4
// armv7k-watchos: [[RESULT:%.*]] = call [[ARMV7K_MYRECT]] bitcast (void ()* @objc_msgSend
// armv7k-watchos: store [[ARMV7K_MYRECT]] [[RESULT]]
// armv7k-watchos: [[CAST:%.*]] = bitcast [[ARMV7K_MYRECT]]*
// armv7k-watchos: load { float, float, float, float }, { float, float, float, float }* [[CAST]]
// armv7k-watchos: ret float
func barc(_ p: StructReturns) -> Float {
return p.newRect().y
}
// x86_64-macosx: define hidden swiftcc { double, double, double } @"$s8abitypes3FooC3baz{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} {
// x86_64-macosx: define hidden void @"$s8abitypes3FooC3baz{{[_0-9a-zA-Z]*}}FTo"(%TSo4TrioV* noalias nocapture sret %0, i8* %1, i8* %2) {{[#0-9]*}} {
@objc dynamic func baz() -> Trio {
return Trio(i: 1.0, j: 2.0, k: 3.0)
}
// x86_64-macosx: define hidden swiftcc double @"$s8abitypes3FooC4bazc{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// x86_64-macosx: load i8*, i8** @"\01L_selector(newTrio)", align 8
// x86_64-macosx: [[CAST:%[0-9]+]] = bitcast {{%.*}}* %0
// x86_64-macosx: call void bitcast (void ()* @objc_msgSend_stret to void (%TSo4TrioV*, [[OPAQUE:.*]]*, i8*)*)
func bazc(_ p: StructReturns) -> Double {
return p.newTrio().j
}
// x86_64-macosx: define hidden swiftcc i64 @"$s8abitypes3FooC7getpair{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// x86_64-macosx: [[RESULT:%.*]] = call i64 bitcast (void ()* @objc_msgSend to i64 ([[OPAQUE:.*]]*, i8*)*)
// x86_64-macosx: [[GEP1:%.*]] = getelementptr inbounds { i64 }, { i64 }* {{.*}}, i32 0, i32 0
// x86_64-macosx: store i64 [[RESULT]], i64* [[GEP1]]
// x86_64-macosx: [[GEP2:%.*]] = getelementptr inbounds { i64 }, { i64 }* {{.*}}, i32 0, i32 0
// x86_64-macosx: load i64, i64* [[GEP2]]
// x86_64-macosx: ret i64
func getpair(_ p: StructReturns) -> IntPair {
return p.newPair()
}
// x86_64-macosx: define hidden i64 @"$s8abitypes3FooC8takepair{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i64 %2) {{[#0-9]*}} {
@objc dynamic func takepair(_ p: IntPair) -> IntPair {
return p
}
// x86_64-macosx: define hidden swiftcc i64 @"$s8abitypes3FooC9getnested{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// x86_64-macosx: call i64 bitcast (void ()* @objc_msgSend to i64 ([[OPAQUE:.*]]*, i8*)*)
// x86_64-macosx: bitcast
// x86_64-macosx: call void @llvm.lifetime.start
// x86_64-macosx: store i32 {{.*}}
// x86_64-macosx: store i32 {{.*}}
// x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { i64 }, { i64 }
// x86_64-macosx: load i64, i64* [[T0]], align 8
// x86_64-macosx: bitcast
// x86_64-macosx: call void @llvm.lifetime.end
// x86_64-macosx: ret i64
func getnested(_ p: StructReturns) -> NestedInts {
return p.newNestedInts()
}
// x86_64-macosx: define hidden i8* @"$s8abitypes3FooC9copyClass{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8* %2) {{[#0-9]*}} {
// x86_64-macosx: [[VALUE:%[0-9]+]] = call swiftcc [[TYPE:%.*]]* @"$s8abitypes3FooC9copyClass{{[_0-9a-zA-Z]*}}F"
// x86_64-macosx: [[T0:%.*]] = call [[OBJC:%objc_class]]* @swift_getObjCClassFromMetadata([[TYPE]]* [[VALUE]])
// x86_64-macosx: [[RESULT:%[0-9]+]] = bitcast [[OBJC]]* [[T0]] to i8*
// x86_64-macosx: ret i8* [[RESULT]]
@objc dynamic func copyClass(_ a: AnyClass) -> AnyClass {
return a
}
// x86_64-macosx: define hidden i8* @"$s8abitypes3FooC9copyProto{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8* %2) {{[#0-9]*}} {
// x86_64-macosx: [[VALUE:%[0-9]+]] = call swiftcc [[TYPE:%.*]] @"$s8abitypes3FooC9copyProto{{[_0-9a-zA-Z]*}}F"
// x86_64-macosx: [[RESULT:%[0-9]+]] = bitcast [[TYPE]] [[VALUE]] to i8*
// x86_64-macosx: ret i8* [[RESULT]]
@objc dynamic func copyProto(_ a: AnyObject) -> AnyObject {
return a
}
// x86_64-macosx: define hidden i8* @"$s8abitypes3FooC13copyProtoComp{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8* %2) {{[#0-9]*}} {
// x86_64-macosx: [[VALUE:%[0-9]+]] = call swiftcc [[TYPE:%.*]] @"$s8abitypes3FooC13copyProtoComp{{[_0-9a-zA-Z]*}}F"
// x86_64-macosx: [[RESULT:%[0-9]+]] = bitcast [[TYPE]] [[VALUE]] to i8*
// x86_64-macosx: ret i8* [[RESULT]]
@objc dynamic func copyProtoComp(_ a: P1 & P2) -> P1 & P2 {
return a
}
// x86_64-macosx: define hidden swiftcc i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// x86_64-macosx: define hidden signext i8 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8 signext %2) {{[#0-9]*}} {
// x86_64-macosx: [[R1:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"
// x86_64-macosx: [[R2:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"
// x86_64-macosx: [[R3:%[0-9]+]] = call swiftcc i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[R2]]
// x86_64-macosx: ret i8 [[R3]]
//
// x86_64-ios-fixme: define hidden i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* %1) {{.*}} {
// x86_64-ios-fixme: define internal zeroext i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"
// x86_64-ios-fixme: [[R1:%[0-9]+]] = call i1 @"$s10ObjectiveC22_convertObjCBoolToBoolSbAA0cD0V1x_tF"(i1 %2)
// x86_64-ios-fixme: [[R2:%[0-9]+]] = call i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 [[R1]]
// x86_64-ios-fixme: [[R3:%[0-9]+]] = call i1 @"$s10ObjectiveC22_convertBoolToObjCBoolAA0eF0VSb1x_tF"(i1 [[R2]])
// x86_64-ios-fixme: ret i1 [[R3]]
//
// armv7-ios-fixme: define hidden i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* %1) {{.*}} {
// armv7-ios-fixme: define internal signext i8 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8 signext %2) {{[#0-9]*}} {
// armv7-ios-fixme: [[R1:%[0-9]+]] = call i1 @"$s10ObjectiveC22_convertObjCBoolToBool1xSbAA0cD0V_tF"
// armv7-ios-fixme: [[R2:%[0-9]+]] = call i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 [[R1]]
// armv7-ios-fixme: [[R3:%[0-9]+]] = call i8 @"$s10ObjectiveC22_convertBoolToObjCBoolAA0eF0VSb1x_tF"(i1 [[R2]]
// armv7-ios-fixme: ret i8 [[R3]]
//
// armv7s-ios-fixme: define hidden i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} {
// armv7s-ios-fixme: define internal signext i8 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i8 signext) {{[#0-9]*}} {
// armv7s-ios-fixme: [[R1:%[0-9]+]] = call i1 @"$s10ObjectiveC22_convertObjCBoolToBool1xSbAA0cD0V_tF"
// armv7s-ios-fixme: [[R2:%[0-9]+]] = call i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 [[R1]]
// armv7s-ios-fixme: [[R3:%[0-9]+]] = call i8 @"$s10ObjectiveC22_convertBoolToObjCBoolAA0eF0VSb1x_tF"(i1 [[R2]]
// armv7s-ios-fixme: ret i8 [[R3]]
//
// arm64-ios-fixme: define hidden i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} {
// arm64-ios-fixme: define internal zeroext i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"
// arm64-ios-fixme: [[R2:%[0-9]+]] = call i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"
// arm64-ios-fixme: ret i1 [[R2]]
//
// arm64e-ios-fixme: define hidden i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} {
// arm64e-ios-fixme: define internal zeroext i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"
// arm64e-ios-fixme: [[R2:%[0-9]+]] = call i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"
// arm64e-ios-fixme: ret i1 [[R2]]
//
// i386-ios-fixme: define hidden i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} {
// i386-ios-fixme: define internal signext i8 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"(i8*, i8*, i8 signext) {{[#0-9]*}} {
// i386-ios-fixme: [[R1:%[0-9]+]] = call i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"
// i386-ios-fixme: [[R2:%[0-9]+]] = call i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 [[R1]]
// i386-ios-fixme: [[R3:%[0-9]+]] = call i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[R2]]
// i386-ios-fixme: ret i8 [[R3]]
//
// x86_64-tvos-fixme: define hidden i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} {
// x86_64-tvos-fixme: define internal zeroext i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"
// x86_64-tvos-fixme: [[R1:%[0-9]+]] = call i1 @"$s10ObjectiveC22_convertObjCBoolToBoolSbAA0cD0V1x_tF"(i1 %2)
// x86_64-tvos-fixme: [[R2:%[0-9]+]] = call i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 [[R1]]
// x86_64-tvos-fixme: [[R3:%[0-9]+]] = call i1 @"$s10ObjectiveC22_convertBoolToObjCBoolAA0eF0VSb1x_tF"(i1 [[R2]])
// x86_64-tvos-fixme: ret i1 [[R3]]
//
// arm64-tvos-fixme: define hidden i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1, %T8abitypes3FooC*) {{.*}} {
// arm64-tvos-fixme: define internal zeroext i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"
// arm64-tvos-fixme: [[R2:%[0-9]+]] = call i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"
// arm64-tvos-fixme: ret i1 [[R2]]
// i386-watchos: define hidden swiftcc i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1)
// i386-watchos: define hidden zeroext i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}FTo"
// i386-watchos: [[R1:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBoolySbAA0cD0VF"(i1 %2)
// i386-watchos: [[R2:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC6negate{{[_0-9a-zA-Z]*}}F"(i1 [[R1]]
// i386-watchos: [[R3:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertBoolToObjCBoolyAA0eF0VSbF"(i1 [[R2]])
// i386-watchos: ret i1 [[R3]]
@objc dynamic func negate(_ b: Bool) -> Bool {
return !b
}
// x86_64-macosx: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// x86_64-macosx: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 %0)
// x86_64-macosx: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// x86_64-macosx: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]])
// x86_64-macosx: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"(i8 [[NEG]])
// x86_64-macosx: ret i1 [[TOBOOL]]
//
// x86_64-macosx: define hidden signext i8 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8 signext %2)
// x86_64-macosx: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"
// x86_64-macosx: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 [[TOBOOL]]
// x86_64-macosx: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// x86_64-macosx: ret i8 [[TOOBJCBOOL]]
//
// x86_64-ios: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// x86_64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// x86_64-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// x86_64-ios: ret i1 [[NEG]]
//
// x86_64-ios: define hidden zeroext i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i1 zeroext %2)
// x86_64-ios: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1
// x86_64-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// x86_64-ios: ret i1 [[TOOBJCBOOL]]
//
// armv7-ios: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// armv7-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 %0)
// armv7-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// armv7-ios: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]])
// armv7-ios: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"(i8 [[NEG]])
// armv7-ios: ret i1 [[TOBOOL]]
//
// armv7-ios: define hidden signext i8 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8 signext %2)
// armv7-ios: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"
// armv7-ios: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 [[TOBOOL]]
// armv7-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// armv7-ios: ret i8 [[TOOBJCBOOL]]
//
// armv7s-ios: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// armv7s-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 %0)
// armv7s-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// armv7s-ios: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]])
// armv7s-ios: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"(i8 [[NEG]])
// armv7s-ios: ret i1 [[TOBOOL]]
//
// armv7s-ios: define hidden signext i8 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8 signext %2)
// armv7s-ios: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"
// armv7s-ios: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 [[TOBOOL]]
// armv7s-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// armv7s-ios: ret i8 [[TOOBJCBOOL]]
//
// arm64-ios: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// arm64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// arm64-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// arm64-ios: ret i1 [[NEG]]
//
// arm64-ios: define hidden zeroext i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i1 zeroext %2)
// arm64-ios: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1
// arm64-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// arm64-ios: ret i1 [[TOOBJCBOOL]]
//
// arm64e-ios: define hidden zeroext i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i1 zeroext %2)
// arm64e-ios: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1
// arm64e-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// arm64e-ios: ret i1 [[TOOBJCBOOL]]
//
// i386-ios: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// i386-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 %0)
// i386-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// i386-ios: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]])
// i386-ios: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"(i8 [[NEG]])
// i386-ios: ret i1 [[TOBOOL]]
//
// i386-ios: define hidden signext i8 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8 signext %2)
// i386-ios: [[TOBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertObjCBoolToBool{{[_0-9a-zA-Z]*}}F"
// i386-ios: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 [[TOBOOL]]
// i386-ios: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i8 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// i386-ios: ret i8 [[TOOBJCBOOL]]
//
// x86_64-tvos: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// x86_64-tvos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// x86_64-tvos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// x86_64-tvos: ret i1 [[NEG]]
//
// x86_64-tvos: define hidden zeroext i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i1 zeroext %2)
// x86_64-tvos: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1
// x86_64-tvos: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// x86_64-tvos: ret i1 [[TOOBJCBOOL]]
//
// arm64-tvos: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// arm64-tvos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// arm64-tvos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// arm64-tvos: ret i1 [[NEG]]
//
// arm64-tvos: define hidden zeroext i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i1 zeroext %2)
// arm64-tvos: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1
// arm64-tvos: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// arm64-tvos: ret i1 [[TOOBJCBOOL]]
// i386-watchos: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// i386-watchos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// i386-watchos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// i386-watchos: ret i1 [[NEG]]
//
// i386-watchos: define hidden zeroext i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i1 zeroext %2)
// i386-watchos: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1
// i386-watchos: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// i386-watchos: ret i1 [[TOOBJCBOOL]]
//
// armv7k-watchos: define hidden swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// armv7k-watchos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// armv7k-watchos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// armv7k-watchos: ret i1 [[NEG]]
//
// armv7k-watchos: define hidden zeroext i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i1 zeroext %2)
// armv7k-watchos: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1
// armv7k-watchos: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// armv7k-watchos: ret i1 [[TOOBJCBOOL]]
//
// arm64-macosx: define hidden zeroext i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i1 zeroext %2)
// arm64-macosx: [[NEG:%[0-9]+]] = call swiftcc i1 @"$s8abitypes3FooC7negate2{{[_0-9a-zA-Z]*}}F"(i1
// arm64-macosx: [[TOOBJCBOOL:%[0-9]+]] = call swiftcc i1 @"$s10ObjectiveC22_convertBoolToObjCBool{{[_0-9a-zA-Z]*}}F"(i1 [[NEG]])
// arm64-macosx: ret i1 [[TOOBJCBOOL]]
@objc dynamic func negate2(_ b: Bool) -> Bool {
var g = Gadget()
return g.negate(b)
}
// x86_64-macosx: define hidden swiftcc i1 @"$s8abitypes3FooC7negate3yS2bF"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// x86_64-macosx: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(invert:)", align 8
// x86_64-macosx: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1)*)(%1* [[RECEIVER:%[0-9]+]], i8* [[SEL]], i1 zeroext %0)
// x86_64-macosx: ret i1 [[NEG]]
// x86_64-macosx: }
// x86_64-ios: define hidden swiftcc i1 @"$s8abitypes3FooC7negate3yS2bF"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// x86_64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(invert:)", align 8
// x86_64-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1)*)(%1* [[RECEIVER:%[0-9]+]], i8* [[SEL]], i1 zeroext %0)
// x86_64-ios: ret i1 [[NEG]]
// x86_64-ios: }
// i386-ios: define hidden swiftcc i1 @"$s8abitypes3FooC7negate3yS2bF"(i1 %0, %T8abitypes3FooC* swiftself %1) {{.*}} {
// i386-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(invert:)", align 4
// i386-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1)*)(%1* [[RECEIVER:%[0-9]+]], i8* [[SEL]], i1 zeroext %0)
// i386-ios: ret i1 [[NEG]]
// i386-ios: }
@objc dynamic func negate3(_ b: Bool) -> Bool {
var g = Gadget()
return g.invert(b)
}
// x86_64-macosx: define hidden swiftcc void @"$s8abitypes3FooC10throwsTestyySbKF"(i1 %0, %T8abitypes3FooC* swiftself %1, %swift.error** noalias nocapture swifterror dereferenceable(8) %2) {{.*}} {
// x86_64-macosx: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negateThrowing:error:)", align 8
// x86_64-macosx: call signext i8 bitcast (void ()* @objc_msgSend to i8 (%1*, i8*, i8, %2**)*)(%1* {{%[0-9]+}}, i8* [[SEL]], i8 signext {{%[0-9]+}}, %2** {{%[0-9]+}})
// x86_64-macosx: }
// x86_64-ios: define hidden swiftcc void @"$s8abitypes3FooC10throwsTestyySbKF"(i1 %0, %T8abitypes3FooC* swiftself %1, %swift.error** noalias nocapture swifterror dereferenceable(8) %2) {{.*}} {
// x86_64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negateThrowing:error:)", align 8
// x86_64-ios: call zeroext i1 bitcast (void ()* @objc_msgSend to i1 (%1*, i8*, i1, %2**)*)(%1* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext {{%[0-9]+}}, %2** {{%[0-9]+}})
// x86_64-ios: }
// i386-ios: define hidden swiftcc void @"$s8abitypes3FooC10throwsTestyySbKF"(i1 %0, %T8abitypes3FooC* swiftself %1, %swift.error** noalias nocapture dereferenceable(4) %2) {{.*}} {
// i386-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negateThrowing:error:)", align 4
// i386-ios: call signext i8 bitcast (void ()* @objc_msgSend to i8 (%1*, i8*, i8, %2**)*)(%1* {{%[0-9]+}}, i8* [[SEL]], i8 signext {{%[0-9]+}}, %2** {{%[0-9]+}})
// i386-ios: }
@objc dynamic func throwsTest(_ b: Bool) throws {
var g = Gadget()
try g.negateThrowing(b)
}
// x86_64-macosx: define hidden i32* @"$s8abitypes3FooC24copyUnsafeMutablePointer{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i32* %2) {{[#0-9]*}} {
@objc dynamic func copyUnsafeMutablePointer(_ p: UnsafeMutablePointer<Int32>) -> UnsafeMutablePointer<Int32> {
return p
}
// x86_64-macosx: define hidden i64 @"$s8abitypes3FooC17returnNSEnumValue{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1) {{[#0-9]*}} {
@objc dynamic func returnNSEnumValue() -> ByteCountFormatter.CountStyle {
return .file
}
// x86_64-macosx: define hidden zeroext i16 @"$s8abitypes3FooC20returnOtherEnumValue{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i16 zeroext %2) {{[#0-9]*}} {
@objc dynamic func returnOtherEnumValue(_ choice: ChooseTo) -> ChooseTo {
switch choice {
case .takeIt: return .leaveIt
case .leaveIt: return .takeIt
}
}
// x86_64-macosx: define hidden swiftcc i32 @"$s8abitypes3FooC10getRawEnum{{[_0-9a-zA-Z]*}}F"(%T8abitypes3FooC* swiftself %0) {{.*}} {
// x86_64-macosx: define hidden i32 @"$s8abitypes3FooC10getRawEnum{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1) {{[#0-9]*}} {
@objc dynamic func getRawEnum() -> RawEnum {
return Intergalactic
}
var work : Work
init (work: Work) {
self.work = work
}
// x86_64-macosx: define hidden void @"$s8abitypes3FooC13testArchetype{{[_0-9a-zA-Z]*}}FTo"(i8* %0, i8* %1, i8* %2) {{[#0-9]*}} {
@objc dynamic func testArchetype(_ work: Work) {
work.doStuff(1)
// x86_64-macosx: [[OBJCPTR:%.*]] = bitcast i8* %2 to %objc_object*
// x86_64-macosx: call swiftcc void @"$s8abitypes3FooC13testArchetype{{[_0-9a-zA-Z]*}}F"(%objc_object* [[OBJCPTR]], %T8abitypes3FooC* swiftself %{{.*}})
}
@objc dynamic func foo(_ x: @convention(block) (Int) -> Int) -> Int {
// FIXME: calling blocks is currently unimplemented
// return x(5)
return 1
}
// x86_64-macosx: define hidden swiftcc void @"$s8abitypes3FooC20testGenericTypeParam{{[_0-9a-zA-Z]*}}F"(%objc_object* %0, %swift.type* %T, %T8abitypes3FooC* swiftself %1) {{.*}} {
func testGenericTypeParam<T: Pasta>(_ x: T) {
// x86_64-macosx: [[CAST:%.*]] = bitcast %objc_object* %0 to i8*
// x86_64-macosx: call void bitcast (void ()* @objc_msgSend to void (i8*, i8*)*)(i8* [[CAST]], i8* %{{.*}})
x.alDente()
}
// arm64-ios: define hidden swiftcc { i64, i64, i64, i64 } @"$s8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, i64 %1, i64 %2, i64 %3, i64 %4, %T8abitypes3FooC* swiftself %5) {{.*}} {
// arm64-ios: define hidden void @"$s8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}FTo"(%TSo9BigStructV* noalias nocapture sret %0, i8* %1, i8* %2, [[OPAQUE:.*]]* %3, %TSo9BigStructV* %4) {{[#0-9]*}} {
//
// arm64e-ios: define hidden swiftcc { i64, i64, i64, i64 } @"$s8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, i64 %1, i64 %2, i64 %3, i64 %4, %T8abitypes3FooC* swiftself %5) {{.*}} {
// arm64e-ios: define hidden void @"$s8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}FTo"(%TSo9BigStructV* noalias nocapture sret %0, i8* %1, i8* %2, [[OPAQUE:.*]]* %3, %TSo9BigStructV* %4) {{.*}} {
//
// arm64-tvos: define hidden swiftcc { i64, i64, i64, i64 } @"$s8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, i64 %1, i64 %2, i64 %3, i64 %4, %T8abitypes3FooC* swiftself %5) {{.*}} {
// arm64-tvos: define hidden void @"$s8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}FTo"(%TSo9BigStructV* noalias nocapture sret %0, i8* %1, i8* %2, [[OPAQUE:.*]]* %3, %TSo9BigStructV* %4) {{[#0-9]*}} {
// arm64-macosx: define hidden swiftcc { i64, i64, i64, i64 } @"$s8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}F"(%TSo13StructReturnsC* %0, i64 %1, i64 %2, i64 %3, i64 %4, %T8abitypes3FooC* swiftself %5) {{.*}} {
// arm64-macosx: define hidden void @"$s8abitypes3FooC14callJustReturn{{[_0-9a-zA-Z]*}}FTo"(%TSo9BigStructV* noalias nocapture sret %0, i8* %1, i8* %2, [[OPAQUE:.*]]* %3, %TSo9BigStructV* %4) {{.*}} {
@objc dynamic func callJustReturn(_ r: StructReturns, with v: BigStruct) -> BigStruct {
return r.justReturn(v)
}
// Test that the makeOne() that we generate somewhere below doesn't
// use arm_aapcscc for armv7.
func callInline() -> Float {
return makeOne(3,5).second
}
}
// armv7-ios: define internal void @makeOne(%struct.One* noalias sret align 4 %agg.result, float %f, float %s)
// armv7s-ios: define internal void @makeOne(%struct.One* noalias sret align 4 %agg.result, float %f, float %s)
// armv7k-watchos: define internal %struct.One @makeOne(float %f, float %s)
// rdar://17631440 - Expand direct arguments that are coerced to aggregates.
// x86_64-macosx: define{{( protected)?}} swiftcc float @"$s8abitypes13testInlineAggySfSo6MyRectVF"(float %0, float %1, float %2, float %3) {{.*}} {
// x86_64-macosx: [[COERCED:%.*]] = alloca %TSo6MyRectV, align 8
// x86_64-macosx: store float %0,
// x86_64-macosx: store float %1,
// x86_64-macosx: store float %2,
// x86_64-macosx: store float %3,
// x86_64-macosx: [[CAST:%.*]] = bitcast %TSo6MyRectV* [[COERCED]] to { <2 x float>, <2 x float> }*
// x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 0
// x86_64-macosx: [[FIRST_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]], align 8
// x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 1
// x86_64-macosx: [[SECOND_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]], align 8
// x86_64-macosx: [[RESULT:%.*]] = call float @MyRect_Area(<2 x float> [[FIRST_HALF]], <2 x float> [[SECOND_HALF]])
// x86_64-macosx: ret float [[RESULT]]
public func testInlineAgg(_ rect: MyRect) -> Float {
return MyRect_Area(rect)
}
// We need to allocate enough memory on the stack to hold the argument value we load.
// arm64-ios: define swiftcc void @"$s8abitypes14testBOOLStructyyF"()
// arm64-ios: [[COERCED:%.*]] = alloca i64
// arm64-ios: [[STRUCTPTR:%.*]] = bitcast i64* [[COERCED]] to %TSo14FiveByteStructV
// arm64-ios: [[PTR0:%.*]] = getelementptr inbounds %TSo14FiveByteStructV, %TSo14FiveByteStructV* [[STRUCTPTR]], {{i.*}} 0, {{i.*}} 0
// arm64-ios: [[PTR1:%.*]] = getelementptr inbounds %T10ObjectiveC8ObjCBoolV, %T10ObjectiveC8ObjCBoolV* [[PTR0]], {{i.*}} 0, {{i.*}} 0
// arm64-ios: [[PTR2:%.*]] = getelementptr inbounds %TSb, %TSb* [[PTR1]], {{i.*}} 0, {{i.*}} 0
// arm64-ios: store i1 false, i1* [[PTR2]], align 8
// arm64-ios: [[ARG:%.*]] = load i64, i64* [[COERCED]]
// arm64-ios: call void bitcast (void ()* @objc_msgSend to void (i8*, i8*, i64)*)(i8* {{.*}}, i8* {{.*}}, i64 [[ARG]])
//
// arm64e-ios: define swiftcc void @"$s8abitypes14testBOOLStructyyF"()
// arm64e-ios: [[COERCED:%.*]] = alloca i64
// arm64e-ios: [[STRUCTPTR:%.*]] = bitcast i64* [[COERCED]] to %TSo14FiveByteStructV
// arm64e-ios: [[PTR0:%.*]] = getelementptr inbounds %TSo14FiveByteStructV, %TSo14FiveByteStructV* [[STRUCTPTR]], {{i.*}} 0, {{i.*}} 0
// arm64e-ios: [[PTR1:%.*]] = getelementptr inbounds %T10ObjectiveC8ObjCBoolV, %T10ObjectiveC8ObjCBoolV* [[PTR0]], {{i.*}} 0, {{i.*}} 0
// arm64e-ios: [[PTR2:%.*]] = getelementptr inbounds %TSb, %TSb* [[PTR1]], {{i.*}} 0, {{i.*}} 0
// arm64e-ios: store i1 false, i1* [[PTR2]], align 8
// arm64e-ios: [[ARG:%.*]] = load i64, i64* [[COERCED]]
// arm64e-ios: call void bitcast (void ()* @objc_msgSend to void (i8*, i8*, i64)*)(i8* {{.*}}, i8* {{.*}}, i64 [[ARG]])
// arm64-macosx: define swiftcc void @"$s8abitypes14testBOOLStructyyF"()
// arm64-macosx: [[COERCED:%.*]] = alloca i64
// arm64-macosx: [[STRUCTPTR:%.*]] = bitcast i64* [[COERCED]] to %TSo14FiveByteStructV
// arm64-macosx: [[PTR0:%.*]] = getelementptr inbounds %TSo14FiveByteStructV, %TSo14FiveByteStructV* [[STRUCTPTR]], {{i.*}} 0, {{i.*}} 0
// arm64-macosx: [[PTR1:%.*]] = getelementptr inbounds %T10ObjectiveC8ObjCBoolV, %T10ObjectiveC8ObjCBoolV* [[PTR0]], {{i.*}} 0, {{i.*}} 0
// arm64-macosx: [[PTR2:%.*]] = getelementptr inbounds %TSb, %TSb* [[PTR1]], {{i.*}} 0, {{i.*}} 0
// arm64-macosx: store i1 false, i1* [[PTR2]], align 8
// arm64-macosx: [[ARG:%.*]] = load i64, i64* [[COERCED]]
// arm64-macosx: call void bitcast (void ()* @objc_msgSend to void (i8*, i8*, i64)*)(i8* {{.*}}, i8* {{.*}}, i64 [[ARG]])
public func testBOOLStruct() {
let s = FiveByteStruct()
MyClass.mymethod(s)
}
| apache-2.0 | 71e26a7e6748c0c2b10e675b7342bc4f | 76.236842 | 371 | 0.598914 | 2.681896 | false | false | false | false |
AshishKapoor/cex-graphs | cex-graphs/CGExtensions.swift | 1 | 1924 | //
// CGExtensions.swift
// cex-graphs
//
// Created by Ashish Kapoor on 20/06/17.
// Copyright © 2017 Ashish Kapoor. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
class func barGraphChartColor() -> UIColor {
return UIColor(red: 230/255, green: 126/255, blue: 34/255, alpha: 1)
}
class func barGraphBackColor() -> UIColor {
return UIColor(red: 189/255, green: 195/255, blue: 199/255, alpha: 1)
}
}
extension Date {
static func unixTimestampToString(timeStamp: Date) -> String {
return DateFormatter.localizedString(from: timeStamp as Date, dateStyle: DateFormatter.Style.none, timeStyle: DateFormatter.Style.short)
}
}
extension Double {
static func stringToDouble(stringValue: String) -> Double {
return (stringValue as NSString).doubleValue
}
}
extension UIView {
func layerGradient() {
let layer : CAGradientLayer = CAGradientLayer()
layer.frame.size = self.frame.size
layer.frame.origin = CGPoint(x: 0.0, y: 0.0)
// layer.cornerRadius = CGFloat(frame.width / 20)
let color0 = UIColor(red:250.0/255, green:250.0/255, blue:250.0/255, alpha:0.5).cgColor
let color1 = UIColor(red:200.0/255, green:200.0/255, blue: 200.0/255, alpha:0.1).cgColor
let color2 = UIColor(red:150.0/255, green:150.0/255, blue: 150.0/255, alpha:0.1).cgColor
let color3 = UIColor(red:100.0/255, green:100.0/255, blue: 100.0/255, alpha:0.1).cgColor
let color4 = UIColor(red:50.0/255, green:50.0/255, blue:50.0/255, alpha:0.1).cgColor
let color5 = UIColor(red:0.0/255, green:0.0/255, blue:0.0/255, alpha:0.1).cgColor
let color6 = UIColor(red:150.0/255, green:150.0/255, blue:150.0/255, alpha:0.1).cgColor
layer.colors = [color0,color1,color2,color3,color4,color5,color6]
self.layer.insertSublayer(layer, at: 0)
}
}
| apache-2.0 | 95c2124f54612196c2efd3947cb15ec1 | 35.980769 | 144 | 0.655746 | 3.210351 | false | false | false | false |
Shivol/Swift-CS333 | assignments/task5/schedule/schedule/DataLoader.swift | 2 | 2607 | //
// DataLoader.swift
// schedule
//
// Created by Илья Лошкарёв on 30.03.17.
// Copyright © 2017 mmcs. All rights reserved.
//
import Foundation
import UIKit
protocol DataLoader: class {
func loadData()
var source: URL { get }
weak var delegate: DataLoaderDelegate? { get set }
}
protocol DataLoaderDelegate: class {
func dataLoader(_ dataLoader: DataLoader, didFinishLoadingWith data: Any?)
func dataLoader(_ dataLoader: DataLoader, didFinishLoadingWith error: NSError)
}
class JSONDataLoader<T>: DataLoader {
let source: URL
weak var delegate: DataLoaderDelegate?
private(set) var parsedData: T? = nil
init(with url: URL) {
source = url
}
func errorFor(response: URLResponse?, with data: Data?, error: Error?) -> NSError? {
if let error = error as? NSError {
return error
}
guard data != nil else {
return NSError(domain: "Empty Response", code: 0, userInfo: ["response": response as Any])
}
guard
let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200
else {
return NSError(domain: "Unexpected Response", code: 0, userInfo: ["response": response as Any])
}
return nil
}
func loadData() {
let task = URLSession.shared.dataTask(with: source) {
(data, response, error) in
if let error = self.errorFor(response: response, with: data, error: error) {
DispatchQueue.main.async {
self.delegate?.dataLoader(self, didFinishLoadingWith: error)
}
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
self.parsedData = try self.parseJSON(json)
DispatchQueue.main.async {
self.delegate?.dataLoader(self, didFinishLoadingWith: self.parsedData)
}
} catch let error as NSError {
DispatchQueue.main.async {
self.delegate?.dataLoader(self, didFinishLoadingWith: error)
}
}
}
task.resume()
}
func parseJSON(_ json: [String : Any] ) throws -> T {
let typename = String(describing: T.self)
guard let result = json[typename] as? T else {
throw NSError(domain: "JSON Error", code: 0, userInfo: ["json" : json])
}
return result
}
}
| mit | 5816d33faf8c516f3bfd5b3740587b97 | 30.634146 | 115 | 0.570933 | 4.707804 | false | false | false | false |
PGSSoft/AutoMate | AutoMate/XCTest extensions/XCTestCase.swift | 1 | 4902 | //
// XCTestCase.swift
// AutoMate
//
// Created by Pawel Szot on 03/08/16.
// Copyright © 2016 PGS Software. All rights reserved.
//
import Foundation
import XCTest
public extension XCTestCase {
// MARK: Properties
/// Default timeout used in `wait` methods.
/// By default set to 10 seconds.
class var defaultTimeOut: TimeInterval { return 10 }
// MARK: Methods
/// Wait for an UI element to fulfill the predicate. After given time, if the predicate is not fulfilled for a given element, test fails.
///
/// **Example:**
///
/// ```swift
/// let button = view.buttons["appearingButton"]
/// let existancePredicate = NSPredicate(format: "exists == true")
/// wait(forFulfillmentOf: existancePredicate, for: button)
/// ```
///
/// - Parameters:
/// - predicate: NSPredicate to fulfill.
/// - element: XCUIElement to wait for.
/// - message: String as format for failing message. You must use %@ for predicate value, %@ for element value and %f for timeout value.
/// - timeout: Waiting time in seconds (default: 10 seconds).
/// - file: Current source file.
/// - line: Current source line.
func wait(forFulfillmentOf predicate: NSPredicate,
for element: XCUIElement,
withFailingMessage message: String = "Failed to fulfill predicate %@ for %@ within %.2f seconds.",
timeout: TimeInterval = XCTestCase.defaultTimeOut,
file: StaticString = #file,
line: UInt = #line) {
expectation(for: predicate, evaluatedWith: element, handler: nil)
waitForExpectations(timeout: timeout) { (error) -> Void in
guard error != nil else {
return
}
let failingMessage = String(format: message, arguments: [predicate, element, timeout])
self.recordFailure(withDescription: failingMessage, inFile: String(describing: file), atLine: Int(clamping: line), expected: true)
}
}
// MARK: Methods
/// Wait for an UI element to exist in a view hierarchy. After given time, if element is not found, test fails.
///
/// **Example:**
///
/// ```swift
/// let button = view.buttons["appearingButton"]
/// wait(forExistanceOf: button)
/// ```
///
/// - Parameters:
/// - element: XCUIElement to wait for.
/// - timeout: Waiting time in seconds (default: 10 seconds).
/// - file: Current source file.
/// - line: Current source line.
func wait(forExistanceOf element: XCUIElement, timeout: TimeInterval = XCTestCase.defaultTimeOut, file: StaticString = #file, line: UInt = #line) {
let existancePredicate = NSPredicate(format: "exists == true")
wait(forFulfillmentOf: existancePredicate, for: element, withFailingMessage: "Failed to find %2$@ within %3$.2f seconds. Predicate was: %1$@.", timeout: timeout, file: file, line: line)
}
/// Wait for an UI element to be visible in a view hierarchy. After given time, if the element is still not visible, test fails.
///
/// **Example:**
///
/// ```swift
/// let button = view.buttons["appearingButton"]
/// wait(forVisibilityOf: button)
/// ```
///
/// - Parameters:
/// - element: XCUIElement to wait for.
/// - timeout: Waiting time in seconds (default: 10 seconds).
/// - file: Current source file.
/// - line: Current source line.
func wait(forVisibilityOf element: XCUIElement, timeout: TimeInterval = XCTestCase.defaultTimeOut, file: StaticString = #file, line: UInt = #line) {
let visibilityPredicate = NSPredicate(format: "exists == true && hittable == true")
wait(forFulfillmentOf: visibilityPredicate, for: element, withFailingMessage: "Failed to find %2$@ as visible within %3$.2f seconds. Predicate was: %1$@.", timeout: timeout, file: file, line: line)
}
/// Wait for an UI element to be not visible in a view hierarchy. After given time, if the element is still visible, test fails.
///
/// **Example:**
///
/// ```swift
/// let button = view.buttons["appearingButton"]
/// wait(forInvisibilityOf: button)
/// ```
///
/// - Parameters:
/// - element: XCUIElement to wait for.
/// - timeout: Waiting time in seconds (default: 10 seconds).
/// - file: Current source file.
/// - line: Current source line.
func wait(forInvisibilityOf element: XCUIElement, timeout: TimeInterval = XCTestCase.defaultTimeOut, file: StaticString = #file, line: UInt = #line) {
let invisibilityPredicate = NSPredicate(format: "hittable == false")
wait(forFulfillmentOf: invisibilityPredicate, for: element, withFailingMessage: "Failed to find %2$@ as invisible within %3$.2f seconds. Predicate was: %1$@.", timeout: timeout, file: file, line: line)
}
}
| mit | 53e8bd260eb4d6c4b56de9a8cabe069c | 42.758929 | 209 | 0.63028 | 4.295355 | false | true | false | false |
jtbandes/swift | stdlib/public/core/LifetimeManager.swift | 2 | 6815 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Evaluates a closure while ensuring that the given instance is not destroyed
/// before the closure returns.
///
/// - Parameters:
/// - x: An instance to preserve until the execution of `body` is completed.
/// - body: A closure to execute that depends on the lifetime of `x` being
/// extended.
/// - Returns: The return value of `body`, if any.
@_inlineable
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: () throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try body()
}
/// Evaluates a closure while ensuring that the given instance is not destroyed
/// before the closure returns.
///
/// - Parameters:
/// - x: An instance to preserve until the execution of `body` is completed.
/// - body: A closure to execute that depends on the lifetime of `x` being
/// extended.
/// - Returns: The return value of `body`, if any.
@_inlineable
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: (T) throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try body(x)
}
extension String {
/// Calls the given closure with a pointer to the contents of the string,
/// represented as a null-terminated sequence of UTF-8 code units.
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withCString(_:)`. Do not store or return the pointer for
/// later use.
///
/// - Parameter body: A closure with a pointer parameter that points to a
/// null-terminated sequence of UTF-8 code units. If `body` has a return
/// value, it is used as the return value for the `withCString(_:)`
/// method. The pointer argument is valid only for the duration of the
/// method's execution.
/// - Returns: The return value of the `body` closure parameter, if any.
@_inlineable
public func withCString<Result>(
_ body: (UnsafePointer<Int8>) throws -> Result
) rethrows -> Result {
return try self.utf8CString.withUnsafeBufferPointer {
try body($0.baseAddress!)
}
}
}
// Fix the lifetime of the given instruction so that the ARC optimizer does not
// shorten the lifetime of x to be before this point.
@_transparent
public func _fixLifetime<T>(_ x: T) {
Builtin.fixLifetime(x)
}
/// Calls the given closure with a mutable pointer to the given argument.
///
/// The `withUnsafeMutablePointer(to:_:)` function is useful for calling
/// Objective-C APIs that take in/out parameters (and default-constructible
/// out parameters) by pointer.
///
/// The pointer argument to `body` is valid only during the execution of
/// `withUnsafeMutablePointer(to:_:)`. Do not store or return the pointer for
/// later use.
///
/// - Parameters:
/// - arg: An instance to temporarily use via pointer.
/// - body: A closure that takes a mutable pointer to `arg` as its sole
/// argument. If the closure has a return value, it is used as the return
/// value of the `withUnsafeMutablePointer(to:_:)` function. The pointer
/// argument is valid only for the duration of the function's execution.
/// - Returns: The return value of the `body` closure, if any.
///
/// - SeeAlso: `withUnsafePointer(to:_:)`
@_inlineable
public func withUnsafeMutablePointer<T, Result>(
to arg: inout T,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafeMutablePointer<T>(Builtin.addressof(&arg)))
}
/// Invokes the given closure with a pointer to the given argument.
///
/// The `withUnsafePointer(to:_:)` function is useful for calling Objective-C
/// APIs that take in/out parameters (and default-constructible out
/// parameters) by pointer.
///
/// The pointer argument to `body` is valid only during the execution of
/// `withUnsafePointer(to:_:)`. Do not store or return the pointer for later
/// use.
///
/// - Parameters:
/// - arg: An instance to temporarily use via pointer.
/// - body: A closure that takes a pointer to `arg` as its sole argument. If
/// the closure has a return value, it is used as the return value of the
/// `withUnsafePointer(to:_:)` function. The pointer argument is valid
/// only for the duration of the function's execution.
/// - Returns: The return value of the `body` closure, if any.
///
/// - SeeAlso: `withUnsafeMutablePointer(to:_:)`
@_inlineable
public func withUnsafePointer<T, Result>(
to arg: inout T,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafePointer<T>(Builtin.addressof(&arg)))
}
@available(*, unavailable, renamed: "withUnsafeMutablePointer(to:_:)")
public func withUnsafeMutablePointer<T, Result>(
_ arg: inout T,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result
{
Builtin.unreachable()
}
@available(*, unavailable, renamed: "withUnsafePointer(to:_:)")
public func withUnsafePointer<T, Result>(
_ arg: inout T,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafeMutablePointer(to:_:) instead")
public func withUnsafeMutablePointers<A0, A1, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ body: (
UnsafeMutablePointer<A0>, UnsafeMutablePointer<A1>) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafeMutablePointer(to:_:) instead")
public func withUnsafeMutablePointers<A0, A1, A2, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ arg2: inout A2,
_ body: (
UnsafeMutablePointer<A0>,
UnsafeMutablePointer<A1>,
UnsafeMutablePointer<A2>
) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafePointer(to:_:) instead")
public func withUnsafePointers<A0, A1, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ body: (UnsafePointer<A0>, UnsafePointer<A1>) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
@available(*, unavailable, message:"use nested withUnsafePointer(to:_:) instead")
public func withUnsafePointers<A0, A1, A2, Result>(
_ arg0: inout A0,
_ arg1: inout A1,
_ arg2: inout A2,
_ body: (
UnsafePointer<A0>,
UnsafePointer<A1>,
UnsafePointer<A2>
) throws -> Result
) rethrows -> Result {
Builtin.unreachable()
}
| apache-2.0 | c1dcd440ddfc0b5177774c0a701e6af8 | 33.770408 | 88 | 0.676742 | 4.095553 | false | false | false | false |
JovannyEspinal/Checklists-iOS | Checklists/ChecklistItem.swift | 1 | 2531 | //
// ChecklistItem.swift
// Checklists
//
// Created by Jovanny Espinal on 12/20/15.
// Copyright © 2015 Jovanny Espinal. All rights reserved.
//
import UIKit
import Foundation
class ChecklistItem: NSObject, NSCoding {
var text = ""
var checked = false
var dueDate = NSDate()
var shouldRemind = false
var itemID: Int
override init() {
itemID = DataModel.nextChecklistItemID()
super.init()
}
func toggleChecked() {
checked = !checked
}
required init?(coder aDecoder: NSCoder) {
text = aDecoder.decodeObjectForKey("Text") as! String
checked = aDecoder.decodeBoolForKey("Checked")
dueDate = aDecoder.decodeObjectForKey("DueDate") as! NSDate
shouldRemind = aDecoder.decodeBoolForKey("ShouldRemind")
itemID = aDecoder.decodeIntegerForKey("ItemID")
super.init()
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(text, forKey: "Text")
aCoder.encodeBool(checked, forKey: "Checked")
aCoder.encodeObject(dueDate, forKey: "DueDate")
aCoder.encodeBool(shouldRemind, forKey: "ShouldRemind")
aCoder.encodeInteger(itemID, forKey: "ItemID")
}
func scheduleNotification() {
let existingNotification = notificationForThisItem()
if let notification = existingNotification {
UIApplication.sharedApplication().cancelLocalNotification(notification)
}
if shouldRemind && dueDate.compare(NSDate()) != .OrderedAscending {
let localNotification = UILocalNotification()
localNotification.fireDate = dueDate
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.alertBody = text
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.userInfo = ["ItemID": itemID]
}
}
func notificationForThisItem() -> UILocalNotification? {
let allNotifications = UIApplication.sharedApplication().scheduledLocalNotifications!
for notification in allNotifications {
if let number = notification.userInfo?["ItemID"] as? Int where number == itemID {
return notification
}
}
return nil
}
deinit {
if let notification = notificationForThisItem() {
UIApplication.sharedApplication().cancelLocalNotification(notification)
}
}
} | mit | a86864f474dd297a4d34b4d278624bfb | 31.037975 | 93 | 0.640316 | 5.597345 | false | false | false | false |
wireapp/wire-ios-sync-engine | Tests/Source/Integration/ConversationTests+OTR.swift | 1 | 32430 | //
// Wire
// Copyright (C) 2020 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
class ConversationTestsOTR_Swift: ConversationTestsBase {
func testThatItSendsFailedOTRMessageAfterMisingClientsAreFetchedButSessionIsNotCreated() {
// GIVEN
XCTAssertTrue(self.login())
let conv = conversation(for: selfToUser1Conversation)
mockTransportSession.responseGeneratorBlock = { [weak self] request -> ZMTransportResponse? in
guard let `self` = self,
let path = (request.path as NSString?),
path.pathComponents.contains("prekeys") else { return nil }
let payload: NSDictionary = [
self.user1.identifier: [
(self.user1.clients.anyObject() as? MockUserClient)?.identifier: [
"id": 0,
"key": "invalid key".data(using: .utf8)!.base64String()
]
]
]
return ZMTransportResponse(payload: payload, httpStatus: 201, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue)
}
// WHEN
var message: ZMConversationMessage?
mockTransportSession.resetReceivedRequests()
performIgnoringZMLogError {
self.userSession?.perform {
message = try! conv?.appendText(content: "Hello World")
}
_ = self.waitForAllGroupsToBeEmpty(withTimeout: 0.5)
}
// THEN
let expectedPath = "/conversations/\(conv!.remoteIdentifier!.transportString())/otr"
// then we expect it to receive a bomb message
// when resending after fetching the (faulty) prekeys
var messagesReceived = 0
for request in mockTransportSession.receivedRequests() {
guard request.path.hasPrefix(expectedPath), let data = request.binaryData else { continue }
guard let otrMessage = try? Proteus_NewOtrMessage(serializedData: data) else { return XCTFail("otrMessage was nil") }
let userEntries = otrMessage.recipients
let clientEntry = userEntries.first?.clients.first
if clientEntry?.text == "💣".data(using: .utf8) {
messagesReceived += 1
}
}
XCTAssertEqual(messagesReceived, 1)
XCTAssertEqual(message?.deliveryState, ZMDeliveryState.sent)
}
func testThatItSendsFailedSessionOTRMessageAfterMissingClientsAreFetchedButSessionIsNotCreated() {
// GIVEN
XCTAssertTrue(self.login())
let conv = conversation(for: selfToUser1Conversation)
var message: ZMAssetClientMessage?
mockTransportSession.responseGeneratorBlock = { [weak self] request -> ZMTransportResponse? in
guard let `self` = self,
let path = request.path as NSString?,
path.pathComponents.contains("prekeys") else { return nil }
let payload: NSDictionary = [
self.user1.identifier: [
(self.user1.clients.anyObject() as? MockUserClient)?.identifier: [
"id": 0,
"key": "invalid key".data(using: .utf8)!.base64String()
]
]
]
return ZMTransportResponse(payload: payload, httpStatus: 201, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue)
}
// WHEN
mockTransportSession.resetReceivedRequests()
performIgnoringZMLogError {
self.userSession?.perform {
message = try! conv?.appendImage(from: self.verySmallJPEGData(), nonce: NSUUID.create()) as? ZMAssetClientMessage
}
_ = self.waitForAllGroupsToBeEmpty(withTimeout: 0.5)
}
// THEN
let expectedPath = "/conversations/\(conv!.remoteIdentifier!.transportString())/otr/messages"
// then we expect it to receive a bomb medium
// when resending after fetching the (faulty) prekeys
var bombsReceived = 0
for request in mockTransportSession.receivedRequests() {
guard request.path.hasPrefix(expectedPath), let data = request.binaryData else { continue }
guard let otrMessage = try? Proteus_NewOtrMessage(serializedData: data) else { return XCTFail() }
let userEntries = otrMessage.recipients
let clientEntry = userEntries.first?.clients.first
if clientEntry?.text == "💣".data(using: .utf8) {
bombsReceived += 1
}
}
XCTAssertEqual(bombsReceived, 1)
XCTAssertEqual(message?.deliveryState, ZMDeliveryState.sent)
}
func testThatItAppendsOTRMessages() {
// GIVEN
let expectedText1 = "The sky above the port was the color of "
let expectedText2 = "television, tuned to a dead channel."
let nonce1 = UUID.create()
let nonce2 = UUID.create()
let genericMessage1 = GenericMessage(content: Text(content: expectedText1), nonce: nonce1)
let genericMessage2 = GenericMessage(content: Text(content: expectedText2), nonce: nonce2)
// WHEN
testThatItAppendsMessage(
to: groupConversation,
with: { _ in
guard
let user2Client = self.user2.clients.anyObject() as? MockUserClient,
let user3Client = self.user3.clients.anyObject() as? MockUserClient,
let selfClient = self.selfUser.clients.anyObject() as? MockUserClient,
let data1 = try? genericMessage1.serializedData(),
let data2 = try? genericMessage2.serializedData() else {
XCTFail()
return []
}
self.groupConversation.encryptAndInsertData(from: user2Client, to: selfClient, data: data1)
self.groupConversation.encryptAndInsertData(from: user3Client, to: selfClient, data: data2)
return [nonce1, nonce2]
}, verify: { conversation in
// THEN
// check that we successfully decrypted messages
XCTAssert(conversation?.allMessages.count > 0)
if conversation?.allMessages.count < 2 {
XCTFail("message count is too low")
} else {
let lastMessages = conversation?.lastMessages(limit: 2) as? [ZMClientMessage]
let message1 = lastMessages?[1]
XCTAssertEqual(message1?.nonce, nonce1)
XCTAssertEqual(message1?.underlyingMessage?.text.content, expectedText1)
let message2 = lastMessages?[0]
XCTAssertEqual(message2?.nonce, nonce2)
XCTAssertEqual(message2?.underlyingMessage?.text.content, expectedText2)
}
}
)
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
}
func testThatItDeliversOTRMessageIfNoMissingClients() {
// GIVEN
XCTAssertTrue(login())
let messageText = "Hey!"
var message: ZMClientMessage?
let conversation = self.conversation(for: selfToUser1Conversation)
userSession?.perform {
message = try! conversation?.appendText(content: "Bonsoir, je voudrais un croissant", mentions: [], fetchLinkPreview: true, nonce: .create()) as? ZMClientMessage
}
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
// WHEN
userSession?.perform {
message = try! conversation?.appendText(content: messageText, mentions: [], fetchLinkPreview: true, nonce: .create()) as? ZMClientMessage
}
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
// THEN
let lastEvent = selfToUser1Conversation.events.lastObject as? MockEvent
XCTAssertEqual(lastEvent?.eventType, ZMUpdateEventType.conversationOtrMessageAdd)
XCTAssertEqual(message?.deliveryState, ZMDeliveryState.sent)
guard let data = lastEvent?.decryptedOTRData else {
return XCTFail()
}
let genericMessage = try? GenericMessage(serializedData: data)
XCTAssertEqual(genericMessage?.text.content, messageText)
}
func testThatItDeliversOTRMessageAfterMissingClientsAreFetched() {
// GIVEN
let messageText = "Hey!"
var message: ZMClientMessage?
XCTAssertTrue(login())
let conversation = self.conversation(for: selfToUser1Conversation)
// WHEN
userSession?.perform {
message = try! conversation?.appendText(content: messageText, mentions: [], fetchLinkPreview: true, nonce: .create()) as? ZMClientMessage
}
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
// THEN
let lastEvent = selfToUser1Conversation.events.lastObject as? MockEvent
XCTAssertEqual(lastEvent?.eventType, ZMUpdateEventType.conversationOtrMessageAdd)
XCTAssertEqual(message?.deliveryState, ZMDeliveryState.sent)
guard let data = lastEvent?.decryptedOTRData else {
return XCTFail()
}
let genericMessage = try? GenericMessage(serializedData: data)
XCTAssertEqual(genericMessage?.text.content, messageText)
}
func testThatItOTRMessagesCanBeResentAndItIsMovedToTheEndOfTheConversation() {
// GIVEN
XCTAssertTrue(login())
let defaultExpirationTime = ZMMessage.defaultExpirationTime()
ZMMessage.setDefaultExpirationTime(0.3)
mockTransportSession.doNotRespondToRequests = true
let conversation = self.conversation(for: selfToUser1Conversation)
var message: ZMClientMessage?
// fail to send
userSession?.perform {
message = try! conversation?.appendText(content: "Where's everyone", mentions: [], fetchLinkPreview: true, nonce: .create()) as? ZMClientMessage
}
XCTAssertTrue(waitOnMainLoop(until: {
return message?.isExpired ?? false
}, timeout: 0.5))
XCTAssertEqual(message?.deliveryState, ZMDeliveryState.failedToSend)
ZMMessage.setDefaultExpirationTime(defaultExpirationTime)
mockTransportSession.doNotRespondToRequests = false
Thread.sleep(forTimeInterval: 0.1) // advance timestamp
// WHEN receiving a new message
let otherUserMessageText = "Are you still there?"
mockTransportSession.performRemoteChanges { _ in
let genericMessage = GenericMessage(content: Text(content: otherUserMessageText), nonce: .create())
guard
let fromClient = self.user1.clients.anyObject() as? MockUserClient,
let toClient = self.selfUser.clients.anyObject() as? MockUserClient,
let data = try? genericMessage.serializedData() else {
return XCTFail()
}
self.selfToUser1Conversation.encryptAndInsertData(from: fromClient, to: toClient, data: data)
}
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
// THEN
let lastMessage = conversation?.lastMessage
XCTAssertEqual(lastMessage?.textMessageData?.messageText, otherUserMessageText)
// WHEN resending
userSession?.perform {
message?.resend()
}
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
// THEN
XCTAssertEqual(conversation?.lastMessage as? ZMMessage, message)
XCTAssertEqual(message?.deliveryState, ZMDeliveryState.sent)
}
func testThatItSendsANotificationWhenRecievingAOtrMessageThroughThePushChannel() {
// GIVEN
XCTAssertTrue(login())
let expectedText = "The sky above the port was the color of "
let message = GenericMessage(content: Text(content: expectedText), nonce: .create())
let conversation = self.conversation(for: groupConversation)
// WHEN
let observer = ConversationChangeObserver(conversation: conversation)
observer?.clearNotifications()
mockTransportSession.performRemoteChanges { _ in
guard
let selfClient = self.selfUser.clients.anyObject() as? MockUserClient,
let senderClient = self.user1.clients.anyObject() as? MockUserClient,
let data = try? message.serializedData() else {
return XCTFail()
}
self.groupConversation.encryptAndInsertData(from: senderClient, to: selfClient, data: data)
}
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
// THEN
let changes: [ConversationChangeInfo]? = observer?.notifications.compactMap({ $0 as? ConversationChangeInfo})
let note = changes?.first(where: { $0.messagesChanged == true})
XCTAssertNotNil(note)
XCTAssertTrue(note?.messagesChanged ?? false)
XCTAssertTrue(note?.lastModifiedDateChanged ?? false)
let msg = conversation?.lastMessage as? ZMClientMessage
XCTAssertEqual(msg?.underlyingMessage?.text.content, expectedText)
}
func testThatItSendsANotificationWhenReceivingAnOtrAssetMessageThroughThePushChannel(_ format: ZMImageFormat) {
// GIVEN
XCTAssertTrue(login())
let conversation = self.conversation(for: groupConversation)
// WHEN
let observer = ConversationChangeObserver(conversation: conversation)
observer?.clearNotifications()
remotelyInsertOTRImage(into: groupConversation, imageFormat: format)
// THEN
let changes: [ConversationChangeInfo]? = observer?.notifications.compactMap({ $0 as? ConversationChangeInfo})
let note = changes?.first(where: { $0.messagesChanged == true})
XCTAssertTrue(note?.messagesChanged ?? false)
XCTAssertTrue(note?.lastModifiedDateChanged ?? false)
}
func testThatItSendsANotificationWhenReceivingAnOtrMediumAssetMessageThroughThePushChannel() {
testThatItSendsANotificationWhenReceivingAnOtrAssetMessageThroughThePushChannel(.medium)
}
func testThatItSendsANotificationWhenReceivingAnOtrPreviewAssetMessageThroughThePushChannel() {
testThatItSendsANotificationWhenReceivingAnOtrAssetMessageThroughThePushChannel(.preview)
}
func testThatItUnarchivesAnArchivedConversationWhenReceivingAnEncryptedMessage() {
// GIVEN
XCTAssertTrue(login())
let conversation = self.conversation(for: groupConversation)
userSession?.perform {
conversation?.isArchived = true
}
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
XCTAssertNotNil(conversation)
XCTAssertTrue(conversation!.isArchived)
// WHEN
let message = GenericMessage(content: Text(content: "Foo"), nonce: .create())
mockTransportSession.performRemoteChanges { _ in
guard
let selfClient = self.selfUser.clients.anyObject() as? MockUserClient,
let senderClient = self.user1.clients.anyObject() as? MockUserClient,
let data = try? message.serializedData() else {
return XCTFail()
}
self.groupConversation.encryptAndInsertData(from: senderClient, to: selfClient, data: data)
}
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
// THEN
XCTAssertNotNil(conversation)
XCTAssertFalse(conversation!.isArchived)
}
func testThatItCreatesAnExternalMessageIfThePayloadIsTooLargeAndAddsTheGenericMessageAsDataBlob() {
// GIVEN
var text = "Very Long Text!"
while UInt(text.data(using: .utf8)!.count) < ZMClientMessage.byteSizeExternalThreshold {
text.append(text)
}
XCTAssertTrue(login())
// register other users clients
let conversation = self.conversation(for: selfToUser1Conversation)
var message: ZMClientMessage?
// WHEN
userSession?.perform {
message = try! conversation?.appendText(content: text, mentions: [], fetchLinkPreview: true, nonce: .create()) as? ZMClientMessage
}
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
// THEN
let lastEvent = selfToUser1Conversation.events.lastObject as? MockEvent
XCTAssertEqual(lastEvent?.eventType, ZMUpdateEventType.conversationOtrMessageAdd)
XCTAssertEqual(message?.deliveryState, ZMDeliveryState.sent)
guard let data = lastEvent?.decryptedOTRData else {
return XCTFail()
}
let genericMessage = try? GenericMessage(serializedData: data)
XCTAssertNotNil(genericMessage)
}
func testThatAssetMediumIsRedownloadedIfNothingIsStored(for useCase: AssetMediumTestUseCase) {
// GIVEN
XCTAssertTrue(login())
var encryptedImageData = Data()
let imagedata = verySmallJPEGData()
let genericMessage = otrAssetGenericMessage(format: .medium, imageData: imagedata, encryptedData: &encryptedImageData)
let assetId = UUID.create()
mockTransportSession.performRemoteChanges { session in
guard
let selfClient = self.selfUser.clients.anyObject() as? MockUserClient,
let senderClient = self.user1.clients.anyObject() as? MockUserClient,
let data = try? genericMessage.serializedData() else {
return XCTFail()
}
let messageData = MockUserClient.encrypted(data: data, from: senderClient, to: selfClient)
self.groupConversation.insertOTRAsset(from: senderClient, to: selfClient, metaData: messageData, imageData: encryptedImageData, assetId: assetId, isInline: false)
session.createAsset(with: encryptedImageData, identifier: assetId.transportString(), contentType: "", forConversation: self.groupConversation.identifier)
}
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
let conversation = self.conversation(for: groupConversation)
guard let assetMessage = conversation?.lastMessage as? ZMAssetClientMessage else {
return XCTFail()
}
// WHEN
switch useCase {
case .cacheCleared:
// remove all stored data, like cache is cleared
userSession?.managedObjectContext.zm_fileAssetCache.deleteAssetData(assetMessage, format: .medium, encrypted: true)
case .decryptionCrash:
// remove decrypted data, but keep encrypted, like we crashed during decryption
userSession?.managedObjectContext.zm_fileAssetCache.storeAssetData(assetMessage, format: .medium, encrypted: true, data: encryptedImageData)
}
userSession?.managedObjectContext.zm_fileAssetCache.deleteAssetData(assetMessage, format: .medium, encrypted: false)
// We no longer process incoming V2 assets so we need to manually set some properties to simulate having received the asset
userSession?.perform {
assetMessage.version = 2
assetMessage.assetId = assetId
}
// THEN
XCTAssertNil(assetMessage.imageMessageData?.imageData)
userSession?.perform {
assetMessage.imageMessageData?.requestFileDownload()
}
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
XCTAssertNotNil(assetMessage.imageMessageData?.imageData)
}
func testThatAssetMediumIsRedownloadedIfNoDecryptedMessageDataIsStored() {
testThatAssetMediumIsRedownloadedIfNothingIsStored(for: .decryptionCrash)
}
func testThatAssetMediumIsRedownloadedIfNoMessageDataIsStored() {
testThatAssetMediumIsRedownloadedIfNothingIsStored(for: .cacheCleared)
}
// MARK: ConversationTestsOTR (Trust)
func testThatItChangesTheSecurityLevelIfMessageArrivesFromPreviouslyUnknownUntrustedParticipant() {
// GIVEN
XCTAssertTrue(login())
// register other users clients
establishSession(with: user1)
establishSession(with: user2)
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
// make conversation secure
let conversation = self.conversation(for: groupConversationWithOnlyConnected)
makeConversationSecured(conversation)
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
XCTAssertEqual(conversation?.securityLevel, ZMConversationSecurityLevel.secure)
// WHEN
// silently add user to conversation
performRemoteChangesExludedFromNotificationStream { _ in
self.groupConversationWithOnlyConnected.addUsers(by: self.user1, addedUsers: [self.user5!])
}
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
// send a message from silently added user
mockTransportSession.performRemoteChanges { _ in
let message = GenericMessage(content: Text(content: "Test 123"), nonce: .create())
guard
let mockSelfClient = self.selfUser.clients.anyObject() as? MockUserClient,
let mockUser5Client = self.user5.clients.anyObject() as? MockUserClient,
let data = try? message.serializedData() else {
return XCTFail()
}
let messageData = MockUserClient.encrypted(data: data, from: mockUser5Client, to: mockSelfClient)
self.groupConversationWithOnlyConnected.insertOTRMessage(from: mockUser5Client, to: mockSelfClient, data: messageData)
}
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
// THEN
var containsParticipantAddedMessage = false
var containsNewClientMessage = true
for message in conversation!.lastMessages(limit: 50) {
guard let systemMessageType = (message as? ZMSystemMessage)?.systemMessageData?.systemMessageType else {
continue
}
switch systemMessageType {
case .participantsAdded:
containsParticipantAddedMessage = true
case .newClient:
containsNewClientMessage = true
default:
break
}
}
XCTAssertEqual(conversation?.securityLevel, ZMConversationSecurityLevel.secureWithIgnored)
XCTAssertTrue(containsParticipantAddedMessage)
XCTAssertTrue(containsNewClientMessage)
}
func testThatItChangesSecurityLevelToSecureWithIgnoredWhenOtherClientTriesToSendMessageAndDegradesConversation() {
// GIVEN
XCTAssertTrue(login())
establishSession(with: user1)
let conversation = self.conversation(for: selfToUser1Conversation)
makeConversationSecured(conversation)
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
// WHEN
let message = GenericMessage(content: Text(content: "Test"), nonce: .create())
mockTransportSession.performRemoteChanges { session in
guard
let selfClient = self.selfUser.clients.anyObject() as? MockUserClient,
let data = try? message.serializedData() else {
return XCTFail()
}
let newClient = session.registerClient(for: self.user1)
self.selfToUser1Conversation.encryptAndInsertData(from: newClient, to: selfClient, data: data)
}
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
// THEN
let lastMessage = conversation?.lastMessages(limit: 10)[1] as? ZMSystemMessage
XCTAssertEqual(conversation?.securityLevel, ZMConversationSecurityLevel.secureWithIgnored)
XCTAssertEqual(conversation?.allMessages.count, 3) // 2x system message (secured & new client) + appended client message
XCTAssertEqual(lastMessage?.systemMessageData?.systemMessageType, ZMSystemMessageType.newClient)
}
func checkThatItShouldInsertSecurityLevelSystemMessageAfterSendingMessage(
shouldInsert: Bool,
shouldChangeSecurityLevel: Bool,
initialSecurityLevel: ZMConversationSecurityLevel,
expectedSecurityLevel: ZMConversationSecurityLevel) {
// GIVEN
let expectedText = "The sky above the port was the color of "
let message = GenericMessage(content: Text(content: expectedText), nonce: .create())
XCTAssertTrue(login())
establishSession(with: user1)
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
let conversation = self.conversation(for: selfToUser1Conversation)
setupInitialSecurityLevel(initialSecurityLevel, in: conversation)
// WHEN
let previousMessageCount = conversation?.allMessages.count
mockTransportSession.performRemoteChanges { session in
guard
let selfClient = self.selfUser.clients.anyObject() as? MockUserClient,
let data = try? message.serializedData() else {
return XCTFail()
}
let newUser1Client = session.registerClient(for: self.user1)
self.selfToUser1Conversation.encryptAndInsertData(from: newUser1Client, to: selfClient, data: data)
}
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
// THEN
XCTAssertEqual(conversation?.securityLevel, expectedSecurityLevel)
let messageAddedCount = conversation!.allMessages.count - previousMessageCount!
if shouldInsert {
XCTAssertEqual(messageAddedCount, 2)
let lastMessage = conversation?.lastMessages(limit: 10)[1] // second to last
XCTAssertNotNil(lastMessage)
guard let lastSystemMessage = lastMessage as? ZMSystemMessage else {
return XCTFail()
}
let expectedUsers = [user(for: user1)]
let users = Array(lastSystemMessage.users)
assertArray(users, hasSameElementsAs: expectedUsers as [Any], name1: "users", name2: "expectedUsers", failureRecorder: ZMTFailureRecorder())
XCTAssertEqual(lastSystemMessage.systemMessageType, ZMSystemMessageType.newClient)
} else {
XCTAssertEqual(messageAddedCount, 1) // only the added client message
}
}
func testThatItInsertsNewClientSystemMessageWhenReceivingMessageFromNewClientInSecuredConversation() {
checkThatItShouldInsertSecurityLevelSystemMessageAfterSendingMessage(
shouldInsert: true,
shouldChangeSecurityLevel: true,
initialSecurityLevel: .secure,
expectedSecurityLevel: .secureWithIgnored)
}
func testThatItInsertsNewClientSystemMessageWhenReceivingMessageFromNewClientInPartialSecureConversation() {
checkThatItShouldInsertSecurityLevelSystemMessageAfterSendingMessage(
shouldInsert: false,
shouldChangeSecurityLevel: false,
initialSecurityLevel: .secureWithIgnored,
expectedSecurityLevel: .secureWithIgnored)
}
func testThatItDoesNotInsertNewClientSystemMessageWhenReceivingMessageFromNewClientInNotSecuredConversation() {
checkThatItShouldInsertSecurityLevelSystemMessageAfterSendingMessage(
shouldInsert: false,
shouldChangeSecurityLevel: false,
initialSecurityLevel: .notSecure,
expectedSecurityLevel: .notSecure)
}
// MARK: - Unable to decrypt message
func testThatItDoesNotInsertASystemMessageWhenItDecryptsADuplicatedMessage() {
// GIVEN
XCTAssertTrue(login())
var conversation = self.conversation(for: selfToUser1Conversation)
var firstMessageData = Data()
let firstMessageText = "Testing duplication"
// WHEN sending the first message
let firstMessage = GenericMessage(content: Text(content: firstMessageText), nonce: .create())
guard
let mockSelfClient = selfUser.clients.anyObject() as? MockUserClient,
let mockUser1Client = user1.clients.anyObject() as? MockUserClient,
let data = try? firstMessage.serializedData() else {
return XCTFail()
}
mockTransportSession.performRemoteChanges { _ in
firstMessageData = MockUserClient.encrypted(data: data, from: mockUser1Client, to: mockSelfClient)
self.selfToUser1Conversation.insertOTRMessage(from: mockUser1Client, to: mockSelfClient, data: firstMessageData)
}
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
// THEN
let previousNumberOfMessages = conversation?.allMessages.count
var lastMessage = conversation?.lastMessage
XCTAssertNil(lastMessage?.systemMessageData)
XCTAssertEqual(lastMessage?.textMessageData?.messageText, firstMessageText)
// Log out
recreateSessionManager()
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
performIgnoringZMLogError {
// and when resending the same data (CBox should return DUPLICATED error)
self.mockTransportSession.performRemoteChanges { _ in
self.selfToUser1Conversation.insertOTRMessage(from: mockUser1Client, to: mockSelfClient, data: firstMessageData)
}
_ = self.waitForAllGroupsToBeEmpty(withTimeout: 0.5)
}
// THEN
conversation = self.conversation(for: selfToUser1Conversation)
let newNumberOfMessages = conversation?.allMessages.count
lastMessage = conversation?.lastMessage
XCTAssertNil(lastMessage?.systemMessageData)
XCTAssertEqual(lastMessage?.textMessageData?.messageText, firstMessageText)
XCTAssertEqual(newNumberOfMessages!, previousNumberOfMessages!)
}
enum AssetMediumTestUseCase {
case cacheCleared
case decryptionCrash
}
@discardableResult
func remotelyInsertOTRImage(into conversation: MockConversation, imageFormat format: ZMImageFormat) -> GenericMessage {
var encryptedImageData = Data()
let imageData = self.verySmallJPEGData()
let message = otrAssetGenericMessage(format: format, imageData: imageData, encryptedData: &encryptedImageData)
mockTransportSession.performRemoteChanges { session in
guard
let selfClient = self.selfUser.clients.anyObject() as? MockUserClient,
let senderClient = self.user1.clients.anyObject() as? MockUserClient,
let data = try? message.serializedData() else {
return XCTFail()
}
let messageData = MockUserClient.encrypted(data: data, from: senderClient, to: selfClient)
let assetId = UUID.create()
session.createAsset(with: encryptedImageData, identifier: assetId.transportString(), contentType: "", forConversation: conversation.identifier)
conversation.insertOTRAsset(from: senderClient, to: selfClient, metaData: messageData, imageData: encryptedImageData, assetId: assetId, isInline: format == .preview)
}
_ = waitForAllGroupsToBeEmpty(withTimeout: 0.5)
return message
}
func otrAssetGenericMessage(format: ZMImageFormat, imageData: Data, encryptedData: inout Data) -> GenericMessage {
let properties = ZMIImageProperties(size: ZMImagePreprocessor.sizeOfPrerotatedImage(with: imageData), length: UInt(imageData.count), mimeType: "image/jpeg")
let otrKey = Data.randomEncryptionKey()
encryptedData = imageData.zmEncryptPrefixingPlainTextIV(key: otrKey)
let sha = encryptedData.zmSHA256Digest()
let keys = ZMImageAssetEncryptionKeys(otrKey: otrKey, sha256: sha)
let imageAsset = ImageAsset(mediumProperties: properties, processedProperties: properties, encryptionKeys: keys, format: format)
let message = GenericMessage(content: imageAsset, nonce: .create())
return message
}
}
| gpl-3.0 | c6dccb90578449ac789ebacbb21395a6 | 42.28972 | 177 | 0.66531 | 5.30671 | false | false | false | false |
lucasangelon/swift-csvexport | csv-export/MasterViewController.swift | 1 | 3590 | //
// MasterViewController.swift
// csv-export
//
// Created by Lucas Angelon Arouca on 4/12/2015.
// Copyright © 2015 Lucas Angelon Arouca. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
objects.insert(NSDate(), atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row] as! NSDate
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = objects[indexPath.row] as! NSDate
cell.textLabel!.text = object.description
return cell
}
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 func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeAtIndex(indexPath.row)
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.
}
}
}
| apache-2.0 | a7576492e8399c8e51179ea7b1838f76 | 37.180851 | 157 | 0.694344 | 5.705882 | false | false | false | false |
gregomni/swift | test/decl/protocol/protocol_with_superclass_where_clause.swift | 2 | 11212 | // RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=on -requirement-machine-inferred-signatures=on
// Protocols with superclass-constrained Self.
class Concrete {
typealias ConcreteAlias = String
func concreteMethod(_: ConcreteAlias) {}
}
class Generic<T> : Concrete { // expected-note 6 {{arguments to generic parameter 'T' ('Int' and 'String') are expected to be equal}}
typealias GenericAlias = (T, T)
func genericMethod(_: GenericAlias) {}
}
protocol BaseProto {}
protocol ProtoRefinesClass where Self : Generic<Int>, Self : BaseProto {
func requirementUsesClassTypes(_: ConcreteAlias, _: GenericAlias)
// expected-note@-1 {{protocol requires function 'requirementUsesClassTypes' with type '(Generic<Int>.ConcreteAlias, Generic<Int>.GenericAlias) -> ()' (aka '(String, (Int, Int)) -> ()'); do you want to add a stub?}}
}
func duplicateOverload<T : ProtoRefinesClass>(_: T) {}
// expected-note@-1 {{'duplicateOverload' previously declared here}}
func duplicateOverload<T : ProtoRefinesClass & Generic<Int>>(_: T) {}
// expected-error@-1 {{invalid redeclaration of 'duplicateOverload'}}
// expected-warning@-2 {{redundant superclass constraint 'T' : 'Generic<Int>'}}
extension ProtoRefinesClass {
func extensionMethodUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) {
_ = ConcreteAlias.self
_ = GenericAlias.self
concreteMethod(x)
genericMethod(y)
let _: Generic<Int> = self
let _: Concrete = self
let _: BaseProto = self
let _: BaseProto & Generic<Int> = self
let _: BaseProto & Concrete = self
let _: Generic<String> = self
// expected-error@-1 {{cannot assign value of type 'Generic<Int>' to type 'Generic<String>'}}
}
}
func usesProtoRefinesClass1(_ t: ProtoRefinesClass) {
let x: ProtoRefinesClass.ConcreteAlias = "hi"
_ = ProtoRefinesClass.ConcreteAlias.self
t.concreteMethod(x)
let y: ProtoRefinesClass.GenericAlias = (1, 2)
_ = ProtoRefinesClass.GenericAlias.self
t.genericMethod(y)
t.requirementUsesClassTypes(x, y)
let _: Generic<Int> = t
let _: Concrete = t
let _: BaseProto = t
let _: BaseProto & Generic<Int> = t
let _: BaseProto & Concrete = t
let _: Generic<String> = t
// expected-error@-1 {{cannot assign value of type 'Generic<Int>' to type 'Generic<String>'}}
}
func usesProtoRefinesClass2<T : ProtoRefinesClass>(_ t: T) {
let x: T.ConcreteAlias = "hi"
_ = T.ConcreteAlias.self
t.concreteMethod(x)
let y: T.GenericAlias = (1, 2)
_ = T.GenericAlias.self
t.genericMethod(y)
t.requirementUsesClassTypes(x, y)
let _: Generic<Int> = t
let _: Concrete = t
let _: BaseProto = t
let _: BaseProto & Generic<Int> = t
let _: BaseProto & Concrete = t
let _: Generic<String> = t
// expected-error@-1 {{cannot assign value of type 'Generic<Int>' to type 'Generic<String>'}}
}
class BadConformingClass1 : ProtoRefinesClass {
// expected-error@-1 {{type 'BadConformingClass1' does not conform to protocol 'ProtoRefinesClass'}}
// expected-error@-2 {{'ProtoRefinesClass' requires that 'BadConformingClass1' inherit from 'Generic<Int>'}}
// expected-note@-3 {{requirement specified as 'Self' : 'Generic<Int>' [with Self = BadConformingClass1]}}
func requirementUsesClassTypes(_: ConcreteAlias, _: GenericAlias) {
// expected-error@-1 {{cannot find type 'ConcreteAlias' in scope}}
// expected-error@-2 {{cannot find type 'GenericAlias' in scope}}
_ = ConcreteAlias.self
// expected-error@-1 {{cannot find 'ConcreteAlias' in scope}}
_ = GenericAlias.self
// expected-error@-1 {{cannot find 'GenericAlias' in scope}}
}
}
class BadConformingClass2 : Generic<String>, ProtoRefinesClass {
// expected-error@-1 {{'ProtoRefinesClass' requires that 'BadConformingClass2' inherit from 'Generic<Int>'}}
// expected-note@-2 {{requirement specified as 'Self' : 'Generic<Int>' [with Self = BadConformingClass2]}}
// expected-error@-3 {{type 'BadConformingClass2' does not conform to protocol 'ProtoRefinesClass'}}
// expected-note@+1 {{candidate has non-matching type '(BadConformingClass2.ConcreteAlias, BadConformingClass2.GenericAlias) -> ()' (aka '(String, (String, String)) -> ()')}}
func requirementUsesClassTypes(_: ConcreteAlias, _: GenericAlias) {
_ = ConcreteAlias.self
_ = GenericAlias.self
}
}
class GoodConformingClass : Generic<Int>, ProtoRefinesClass {
func requirementUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) {
_ = ConcreteAlias.self
_ = GenericAlias.self
concreteMethod(x)
genericMethod(y)
}
}
protocol ProtoRefinesProtoWithClass where Self : ProtoRefinesClass {}
extension ProtoRefinesProtoWithClass {
func anotherExtensionMethodUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) {
_ = ConcreteAlias.self
_ = GenericAlias.self
concreteMethod(x)
genericMethod(y)
let _: Generic<Int> = self
let _: Concrete = self
let _: BaseProto = self
let _: BaseProto & Generic<Int> = self
let _: BaseProto & Concrete = self
let _: Generic<String> = self
// expected-error@-1 {{cannot assign value of type 'Generic<Int>' to type 'Generic<String>'}}
}
}
func usesProtoRefinesProtoWithClass1(_ t: ProtoRefinesProtoWithClass) {
let x: ProtoRefinesProtoWithClass.ConcreteAlias = "hi"
_ = ProtoRefinesProtoWithClass.ConcreteAlias.self
t.concreteMethod(x)
let y: ProtoRefinesProtoWithClass.GenericAlias = (1, 2)
_ = ProtoRefinesProtoWithClass.GenericAlias.self
t.genericMethod(y)
t.requirementUsesClassTypes(x, y)
let _: Generic<Int> = t
let _: Concrete = t
let _: BaseProto = t
let _: BaseProto & Generic<Int> = t
let _: BaseProto & Concrete = t
let _: Generic<String> = t
// expected-error@-1 {{cannot assign value of type 'Generic<Int>' to type 'Generic<String>'}}
}
func usesProtoRefinesProtoWithClass2<T : ProtoRefinesProtoWithClass>(_ t: T) {
let x: T.ConcreteAlias = "hi"
_ = T.ConcreteAlias.self
t.concreteMethod(x)
let y: T.GenericAlias = (1, 2)
_ = T.GenericAlias.self
t.genericMethod(y)
t.requirementUsesClassTypes(x, y)
let _: Generic<Int> = t
let _: Concrete = t
let _: BaseProto = t
let _: BaseProto & Generic<Int> = t
let _: BaseProto & Concrete = t
let _: Generic<String> = t
// expected-error@-1 {{cannot assign value of type 'Generic<Int>' to type 'Generic<String>'}}
}
class ClassWithInits<T> {
init(notRequiredInit: ()) {}
// expected-note@-1 6{{selected non-required initializer 'init(notRequiredInit:)'}}
required init(requiredInit: ()) {}
}
protocol ProtocolWithClassInits where Self : ClassWithInits<Int> {}
func useProtocolWithClassInits1() {
_ = ProtocolWithClassInits(notRequiredInit: ())
// expected-error@-1 {{type 'any ProtocolWithClassInits' cannot be instantiated}}
_ = ProtocolWithClassInits(requiredInit: ())
// expected-error@-1 {{type 'any ProtocolWithClassInits' cannot be instantiated}}
}
func useProtocolWithClassInits2(_ t: ProtocolWithClassInits.Type) {
_ = t.init(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'any ProtocolWithClassInits' with a metatype value must use a 'required' initializer}}
let _: ProtocolWithClassInits = t.init(requiredInit: ())
}
func useProtocolWithClassInits3<T : ProtocolWithClassInits>(_ t: T.Type) {
_ = T(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'T' with a metatype value must use a 'required' initializer}}
let _: T = T(requiredInit: ())
_ = t.init(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'T' with a metatype value must use a 'required' initializer}}
let _: T = t.init(requiredInit: ())
}
protocol ProtocolRefinesClassInits : ProtocolWithClassInits {}
func useProtocolRefinesClassInits1() {
_ = ProtocolRefinesClassInits(notRequiredInit: ())
// expected-error@-1 {{type 'any ProtocolRefinesClassInits' cannot be instantiated}}
_ = ProtocolRefinesClassInits(requiredInit: ())
// expected-error@-1 {{type 'any ProtocolRefinesClassInits' cannot be instantiated}}
}
func useProtocolRefinesClassInits2(_ t: ProtocolRefinesClassInits.Type) {
_ = t.init(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'any ProtocolRefinesClassInits' with a metatype value must use a 'required' initializer}}
let _: ProtocolRefinesClassInits = t.init(requiredInit: ())
}
func useProtocolRefinesClassInits3<T : ProtocolRefinesClassInits>(_ t: T.Type) {
_ = T(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'T' with a metatype value must use a 'required' initializer}}
let _: T = T(requiredInit: ())
_ = t.init(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'T' with a metatype value must use a 'required' initializer}}
let _: T = t.init(requiredInit: ())
}
// Make sure that we don't require 'mutating' when the protocol has a superclass
// constraint.
protocol HasMutableProperty : Concrete {
var mutableThingy: Any? { get set }
}
extension HasMutableProperty {
func mutateThingy() {
mutableThingy = nil
}
}
// Some pathological examples -- just make sure they don't crash.
protocol RecursiveSelf where Self : Generic<Self> {}
protocol RecursiveAssociatedType where Self : Generic<Self.X> {
associatedtype X
}
protocol BaseProtocol {
typealias T = Int
}
class BaseClass : BaseProtocol {}
protocol RefinedProtocol where Self : BaseClass {
func takesT(_: T)
}
class RefinedClass : BaseClass, RefinedProtocol {
func takesT(_: T) {
_ = T.self
}
}
func takesBaseProtocol(_: BaseProtocol) {}
func passesRefinedProtocol(_ r: RefinedProtocol) {
takesBaseProtocol(r)
}
class LoopClass : LoopProto {}
protocol LoopProto where Self : LoopClass {}
class FirstClass {}
protocol FirstProtocol where Self : FirstClass {}
class SecondClass : FirstClass {}
protocol SecondProtocol where Self : SecondClass, Self : FirstProtocol {}
class FirstConformer : FirstClass, SecondProtocol {}
// expected-error@-1 {{type 'FirstConformer' does not conform to protocol 'SecondProtocol'}}
// expected-error@-2 {{'SecondProtocol' requires that 'FirstConformer' inherit from 'SecondClass'}}
// expected-note@-3 {{requirement specified as 'Self' : 'SecondClass' [with Self = FirstConformer]}}
class SecondConformer : SecondClass, SecondProtocol {}
// Duplicate superclass
// FIXME: Should be an error here too
protocol DuplicateSuper1 : Concrete where Self : Concrete {}
// expected-warning@-1 {{redundant superclass constraint 'Self' : 'Concrete'}}
protocol DuplicateSuper2 where Self : Concrete, Self : Concrete {}
// expected-warning@-1 {{redundant superclass constraint 'Self' : 'Concrete'}}
// Ambiguous name lookup situation
protocol Amb where Self : Concrete {}
// expected-note@-1 {{'Amb' previously declared here}}
// expected-note@-2 {{found this candidate}}
protocol Amb where Self : Concrete {}
// expected-error@-1 {{invalid redeclaration of 'Amb'}}
// expected-note@-2 {{found this candidate}}
extension Amb { // expected-error {{'Amb' is ambiguous for type lookup in this context}}
func extensionMethodUsesClassTypes() {
_ = ConcreteAlias.self
}
}
| apache-2.0 | 8460cb6d0c502573f9e8ecd924f52b96 | 31.688047 | 217 | 0.709418 | 3.871547 | false | false | false | false |
hejunbinlan/swiftmi-app | swiftmi/swiftmi/RefreshBaseView.swift | 4 | 5537 | //
// RefreshBaseView.swift
// RefreshExample
//
// Created by SunSet on 14-6-23.
// Copyright (c) 2014 zhaokaiyuan. All rights reserved.
//
import UIKit
//控件的刷新状态
enum RefreshState {
case Pulling // 松开就可以进行刷新的状态
case Normal // 普通状态
case Refreshing // 正在刷新中的状态
case WillRefreshing
}
//控件的类型
enum RefreshViewType {
case TypeHeader // 头部控件
case TypeFooter // 尾部控件
}
let RefreshLabelTextColor:UIColor = UIColor(red: 150.0/255, green: 150.0/255.0, blue: 150.0/255.0, alpha: 1)
class RefreshBaseView: UIView {
// 父控件
var scrollView:UIScrollView!
var scrollViewOriginalInset:UIEdgeInsets!
// 内部的控件
var statusLabel:UILabel!
var arrowImage:UIImageView!
var activityView:UIActivityIndicatorView!
//回调
var beginRefreshingCallback:(()->Void)?
// 交给子类去实现 和 调用
var oldState:RefreshState?
var State:RefreshState = RefreshState.Normal{
willSet{
}
didSet{
}
}
func setState(newValue:RefreshState){
if self.State != RefreshState.Refreshing {
scrollViewOriginalInset = self.scrollView.contentInset;
}
if self.State == newValue {
return
}
switch newValue {
case .Normal:
self.arrowImage.hidden = false
self.activityView.stopAnimating()
break
case .Pulling:
break
case .Refreshing:
self.arrowImage.hidden = true
activityView.startAnimating()
beginRefreshingCallback!()
break
default:
break
}
}
//控件初始化
override init(frame: CGRect) {
super.init(frame: frame)
//状态标签
statusLabel = UILabel()
statusLabel.autoresizingMask = UIViewAutoresizing.FlexibleWidth
statusLabel.font = UIFont.boldSystemFontOfSize(13)
statusLabel.textColor = RefreshLabelTextColor
statusLabel.backgroundColor = UIColor.clearColor()
statusLabel.textAlignment = NSTextAlignment.Center
self.addSubview(statusLabel)
//箭头图片
arrowImage = UIImageView(image: UIImage(named: "arrow_up"))
arrowImage.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin
self.addSubview(arrowImage)
//状态标签
activityView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
activityView.bounds = self.arrowImage.bounds
activityView.autoresizingMask = self.arrowImage.autoresizingMask
self.addSubview(activityView)
//自己的属性
self.autoresizingMask = UIViewAutoresizing.FlexibleWidth
self.backgroundColor = UIColor.clearColor()
//设置默认状态
self.State = RefreshState.Normal;
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
//箭头
let arrowX:CGFloat = self.frame.size.width * 0.5 - 100
self.arrowImage.center = CGPointMake(arrowX, self.frame.size.height * 0.5)
//指示器
self.activityView.center = self.arrowImage.center
}
override func willMoveToSuperview(newSuperview: UIView!) {
super.willMoveToSuperview(newSuperview)
// 旧的父控件
if (self.superview != nil) {
self.superview?.removeObserver(self, forKeyPath: RefreshContentSize, context: nil)
}
// 新的父控件
if (newSuperview != nil) {
newSuperview.addObserver(self, forKeyPath: RefreshContentOffset, options: NSKeyValueObservingOptions.New, context: nil)
var rect:CGRect = self.frame
// 设置宽度 位置
rect.size.width = newSuperview.frame.size.width
rect.origin.x = 0
self.frame = frame;
//UIScrollView
scrollView = newSuperview as! UIScrollView
scrollViewOriginalInset = scrollView.contentInset;
}
}
//显示到屏幕上
override func drawRect(rect: CGRect) {
superview?.drawRect(rect);
if self.State == RefreshState.WillRefreshing {
self.State = RefreshState.Refreshing
}
}
// 刷新相关
// 是否正在刷新
func isRefreshing()->Bool{
return RefreshState.Refreshing == self.State;
}
// 开始刷新
func beginRefreshing(){
// self.State = RefreshState.Refreshing;
if (self.window != nil) {
self.State = RefreshState.Refreshing;
} else {
//不能调用set方法
State = RefreshState.WillRefreshing;
super.setNeedsDisplay()
}
}
//结束刷新
func endRefreshing(){
let delayInSeconds:Double = 0.3
var popTime:dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds));
dispatch_after(popTime, dispatch_get_main_queue(), {
self.State = RefreshState.Normal;
})
}
}
| mit | cd4d7091757e853b35b6a2126c5aa1ef | 25.654822 | 131 | 0.592078 | 5.020076 | false | false | false | false |
LeoMobileDeveloper/MDTable | MDTableExample/ChannelItemView.swift | 1 | 1601 | //
// CollectionViewCell.swift
// MDTableExample
//
// Created by Leo on 2017/7/10.
// Copyright © 2017年 Leo Huang. All rights reserved.
//
import UIKit
class ChannelItemView:AvatarItemView{
var coverImageview: UIImageView!
var podcasterNameLabel: UILabel!
var describeLabel: UILabel!
func config(_ channel:NMChannel){
podcasterNameLabel.text = channel.podcasterName
avatarImageView.asyncSetImage(channel.avatar)
describeLabel.text = channel.describe
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
func commonInit(){
coverImageview = UIImageView().added(to: self)
describeLabel = UILabel.title().added(to: self)
describeLabel.numberOfLines = 2
podcasterNameLabel = UILabel.title().added(to: self)
podcasterNameLabel.textColor = UIColor.white
}
override func layoutSubviews() {
super.layoutSubviews()
avatarImageView.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.width)
coverImageview.frame = avatarImageView.frame
describeLabel.frame = CGRect(x: 4.0, y: avatarImageView.maxY + 4.0, width: self.frame.width - 8.0, height: 30.0)
podcasterNameLabel.sizeToFit()
podcasterNameLabel.frame = CGRect(x: 4.0, y: coverImageview.maxY - 2.0 - podcasterNameLabel.frame.height, width: describeLabel.frame.width, height: podcasterNameLabel.frame.height)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 6d85d66c025b1467b071846c641ad539 | 35.318182 | 188 | 0.677722 | 4.107969 | false | false | false | false |
chweihan/Weibo | Weibo/Weibo/Classes/Home/Status.swift | 1 | 1402 | //
// Status.swift
// Weibo
//
// Created by 陈伟涵 on 2016/10/24.
// Copyright © 2016年 cweihan. All rights reserved.
//
import UIKit
class Status: NSObject {
///微博创建时间
var created_at : String?
///字符串型的微博id
var idstr : String?
///微博信息
var text : String?
///微博来源
var source : String?
///用户
var user : User?
///图片数组
var pic_urls : [[String : Any]]?
///转发微博
var retweeted_status : Status?
init(_ dict : [String : Any]) {
super.init()
setValuesForKeys(dict)
}
//kvc的setValuesForKeys的内部会调用setValue
override func setValue(_ value: Any?, forKey key: String) {
//拦截user赋值操作
if key == "user" {
user = User(value as! [String : Any])
return
}
if key == "retweeted_status" {
retweeted_status = Status(value as! [String : Any])
return
}
super.setValue(value, forKey: key)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
override var description: String {
let property = ["created_at", "idstr", "text", "source","user","retweeted_status"]
let dict = dictionaryWithValues(forKeys: property)
return "\(dict)"
}
}
| mit | 18d3a1f46a82ad3c715bfb6be4bc3e05 | 21.5 | 90 | 0.537165 | 4.003067 | false | false | false | false |
luisfcofv/rasgos-geometricos | rasgos-geometricos/Classes/Utilities/TanimotoDistance.swift | 1 | 1151 | //
// TanimotoDistance.swift
// rasgos-geometricos
//
// Created by Luis Flores on 3/7/15.
// Copyright (c) 2015 Luis Flores. All rights reserved.
//
import UIKit
class TanimotoDistance: NSObject {
class func tanimotoDistance(objectA:BinaryObject, objectB:BinaryObject) -> Double {
var sharedPixels = 0
var diff = Coordinate(x: objectB.centerOfMass.x - objectA.centerOfMass.x,
y: objectB.centerOfMass.y - objectA.centerOfMass.y)
for row in 0..<objectB.rows {
for col in 0..<objectB.columns {
if row - diff.y < 0 || row - diff.y >= objectA.rows
|| col - diff.x < 0 || col - diff.y >= objectA.columns {
continue
}
if objectA.grid[row - diff.y][col - diff.x] == 1
&& objectB.grid[row][col] == 1 {
sharedPixels++
}
}
}
var activePixels = objectA.activePixels + objectB.activePixels
return Double(activePixels - 2 * sharedPixels) / Double(activePixels - sharedPixels)
}
}
| mit | 692846d07a35085f90153bc8b7ca989e | 30.972222 | 92 | 0.538662 | 3.862416 | false | false | false | false |
jokechat/swift3-novel | swift_novels/Pods/Kingfisher/Sources/ImageView+Kingfisher.swift | 13 | 13320 | //
// ImageView+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2016 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.
*/
@discardableResult
public func setImage(with resource: Resource?,
placeholder: Image? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
base.image = placeholder
guard let resource = resource else {
completionHandler?(nil, nil, .none, nil)
return .empty
}
let maybeIndicator = indicator
maybeIndicator?.startAnimatingView()
setWebURL(resource.downloadURL)
var options = options ?? KingfisherEmptyOptionsInfo
if shouldPreloadAllGIF() {
options.append(.preloadAllGIFData)
}
let task = KingfisherManager.shared.retrieveImage(
with: resource,
options: options,
progressBlock: { receivedSize, totalSize in
if let progressBlock = progressBlock {
progressBlock(receivedSize, totalSize)
}
},
completionHandler: {[weak base] image, error, cacheType, imageURL in
DispatchQueue.main.safeAsync {
guard let strongBase = base, imageURL == self.webURL else {
return
}
self.setImageTask(nil)
guard let image = image else {
maybeIndicator?.stopAnimatingView()
completionHandler?(nil, error, cacheType, imageURL)
return
}
guard let transitionItem = options.firstMatchIgnoringAssociatedValue(.transition(.none)),
case .transition(let transition) = transitionItem, ( options.forceTransition || cacheType == .none) else
{
maybeIndicator?.stopAnimatingView()
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
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.
*/
public func cancelDownloadTask() {
imageTask?.downloadTask?.cancel()
}
func shouldPreloadAllGIF() -> Bool {
return true
}
}
// MARK: - Associated Object
private var lastURLKey: Void?
private var indicatorKey: Void?
private var indicatorTypeKey: Void?
private var imageTaskKey: Void?
extension Kingfisher where Base: ImageView {
/// Get the image URL binded to this image view.
public 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.
public var indicatorType: IndicatorType {
get {
let indicator = (objc_getAssociatedObject(base, &indicatorTypeKey) as? Box<IndicatorType?>)?.value
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, Box(value: 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`.
public fileprivate(set) var indicator: Indicator? {
get {
return (objc_getAssociatedObject(base, &indicatorKey) as? Box<Indicator?>)?.value
}
set {
// Remove previous
if let previousIndicator = indicator {
previousIndicator.view.removeFromSuperview()
}
// Add new
if var newIndicator = newValue {
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
objc_setAssociatedObject(base, &indicatorKey, Box(value: newValue), .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)
}
}
// MARK: - Deprecated. Only for back compatibility.
/**
* Set image to use from web. Deprecated. Use `kf` namespacing instead.
*/
extension 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.
*/
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.setImage` instead.", renamed: "kf.setImage")
@discardableResult
public func kf_setImage(with resource: Resource?,
placeholder: Image? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
return kf.setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler)
}
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.cancelDownloadTask` instead.", renamed: "kf.cancelDownloadTask")
public func kf_cancelDownloadTask() { kf.cancelDownloadTask() }
/// Get the image URL binded to this image view.
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.webURL` instead.", renamed: "kf.webURL")
public var kf_webURL: URL? { return kf.webURL }
/// Holds which indicator type is going to be used.
/// Default is .none, means no indicator will be shown.
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicatorType` instead.", renamed: "kf.indicatorType")
public var kf_indicatorType: IndicatorType {
get { return kf.indicatorType }
set {
var holder = kf
holder.indicatorType = newValue
}
}
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicator` instead.", renamed: "kf.indicator")
/// 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 `kf_indicatorType` is `.none`.
public private(set) var kf_indicator: Indicator? {
get { return kf.indicator }
set {
var holder = kf
holder.indicator = newValue
}
}
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.imageTask")
fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask }
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setImageTask")
fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task) }
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setWebURL")
fileprivate func kf_setWebURL(_ url: URL) { kf.setWebURL(url) }
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.shouldPreloadAllGIF")
func shouldPreloadAllGIF() -> Bool { return kf.shouldPreloadAllGIF() }
}
| apache-2.0 | 184796682303bae0092c936290d42e65 | 44.616438 | 173 | 0.602252 | 5.596639 | false | false | false | false |
shinhithi/google-services | ios/analytics/AnalyticsExampleSwift/PatternTabBarController.swift | 46 | 1530 | //
// Copyright (c) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/**
* PatternTabBarController exists as a subclass of UITabBarConttroller that
* supports a 'share' action. This will trigger a custom event to Analytics and
* display a dialog.
*/
@objc(PatternTabBarController) // match the ObjC symbol name inside Storyboard
class PatternTabBarController: UITabBarController {
@IBAction func didTapShare(sender: AnyObject) {
// [START custom_event_swift]
var tracker = GAI.sharedInstance().defaultTracker
var event = GAIDictionaryBuilder.createEventWithCategory("Action", action: "Share", label: nil, value: nil)
tracker.send(event.build() as [NSObject : AnyObject])
// [END custom_event_swift]
var title = "Share: \(self.selectedViewController!.title!)"
var message = "Share is not implemented in this quickstart"
var alert = UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
} | apache-2.0 | e33d96a1b44d14d332ccfd007a59d552 | 37.275 | 111 | 0.733333 | 4.203297 | false | false | false | false |
ahoppen/swift | test/Generics/sr12120.swift | 2 | 1434 | // RUN: %target-typecheck-verify-swift -debug-generic-signatures -warn-redundant-requirements 2>&1 | %FileCheck %s
// CHECK: sr12120.(file).Swappable1@
// CHECK-NEXT: Requirement signature: <Self where Self == Self.[Swappable1]Swapped.[Swappable1]Swapped, Self.[Swappable1]B == Self.[Swappable1]Swapped.[Swappable1]A, Self.[Swappable1]Swapped : Swappable1>
protocol Swappable1 {
associatedtype A
associatedtype B
associatedtype Swapped : Swappable1
where Swapped.B == A, // expected-warning {{redundant same-type constraint 'Self.Swapped.B' == 'Self.A'}}
Swapped.A == B,
Swapped.Swapped == Self
}
// CHECK: sr12120.(file).Swappable2@
// CHECK-NEXT: Requirement signature: <Self where Self == Self.[Swappable2]Swapped.[Swappable2]Swapped, Self.[Swappable2]B == Self.[Swappable2]Swapped.[Swappable2]A, Self.[Swappable2]Swapped : Swappable2>
protocol Swappable2 {
associatedtype A
associatedtype B
associatedtype Swapped : Swappable2
where Swapped.B == A,
Swapped.Swapped == Self
}
// CHECK: sr12120.(file).Swappable3@
// CHECK-NEXT: Requirement signature: <Self where Self == Self.[Swappable3]Swapped.[Swappable3]Swapped, Self.[Swappable3]B == Self.[Swappable3]Swapped.[Swappable3]A, Self.[Swappable3]Swapped : Swappable3>
protocol Swappable3 {
associatedtype A
associatedtype B
associatedtype Swapped : Swappable3
where Swapped.A == B,
Swapped.Swapped == Self
}
| apache-2.0 | 67d56921134e3b8e44c57eb16a0c95fb | 43.8125 | 204 | 0.725941 | 3.514706 | false | false | false | false |
kissybnts/v-project | Sources/App/Constant/PropertyKey.swift | 1 | 328 | internal struct PropertyKey {
internal static let id = "id"
internal static let name = "name"
internal static let email = "email"
internal static let password = "password"
internal static let title = "title"
internal static let updatedAt = "updated_at"
internal static let createdAt = "created_at"
}
| mit | f77a7264fdcbec388bed532353b2837b | 35.444444 | 48 | 0.695122 | 4.432432 | false | false | false | false |
JeremyJacquemont/SchoolProjects | IUT/iOS-Projects/Locations/Locations/LocationManager.swift | 1 | 2878 | //
// LocationManager.swift
// Locations
//
// Created by iem on 02/04/2015.
// Copyright (c) 2015 JeremyJacquemont. All rights reserved.
//
import CoreData
import Foundation
class LocationManager: EntityManager {
//MARK: - Override sharedManager
override class var sharedManager: LocationManager {
struct Singleton {
static let instance = LocationManager()
}
return Singleton.instance
}
//MARK: - Override Abstract functions
override func add(informations: Dictionary<String, AnyObject>) -> NSManagedObject? {
var dict = informations as NSDictionary
let entity = NSEntityDescription.entityForName(Location.TABLE_NAME, inManagedObjectContext: LocationManager.managedObjectContext)
let location = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: LocationManager.managedObjectContext) as Location
location.name = dict.valueForKey(Location.FIELD_NAME)! as String
location.latitude = dict.valueForKey(Location.FIELD_LATITUDE)! as NSNumber
location.longitude = dict.valueForKey(Location.FIELD_LONGITUDE)! as NSNumber
location.radius = dict.valueForKey(Location.FIELD_RADIUS)! as NSNumber
var error : NSError?
LocationManager.managedObjectContext.save(&error)
if error != nil {
println("Not save Location: \(error?.description)")
}
return location
}
override func update(entity: NSManagedObject?, informations: Dictionary<String, AnyObject>) -> NSManagedObject? {
var dict = informations as NSDictionary
let location = entity as Location
location.name = dict.valueForKey(Location.FIELD_NAME)! as String
location.latitude = dict.valueForKey(Location.FIELD_LATITUDE)! as NSNumber
location.longitude = dict.valueForKey(Location.FIELD_LONGITUDE)! as NSNumber
location.radius = dict.valueForKey(Location.FIELD_RADIUS)! as NSNumber
var error : NSError?
LocationManager.managedObjectContext.save(&error)
if error != nil {
println("Not update Location: \(error?.description)")
}
return location
}
override func delete(entity: NSManagedObject?) {
if let entityDelete = entity {
EntityManager.managedObjectContext.deleteObject(entityDelete)
EntityManager.managedObjectContext.save(nil)
}
}
override func getAll() -> [NSManagedObject]? {
var error: NSError?
var request = NSFetchRequest(entityName: Location.TABLE_NAME)
if let objects = LocationManager.managedObjectContext.executeFetchRequest(request, error: &error) as? [Location] {
return objects
}
return nil
}
} | apache-2.0 | cd2b3bc994ca0dd7b205c41b2c2916d0 | 35.443038 | 137 | 0.659138 | 5.409774 | false | false | false | false |
shu223/watchOS-2-Sampler | watchOS2Sampler WatchKit Extension/DrawPathsInterfaceController.swift | 1 | 3164 | //
// DrawPathsInterfaceController.swift
// watchOS2Sampler
//
// Created by Shuichi Tsutsumi on 2015/07/14.
// Copyright © 2015 Shuichi Tsutsumi. All rights reserved.
//
import WatchKit
import Foundation
class DrawPathsInterfaceController: WKInterfaceController {
@IBOutlet weak var image: WKInterfaceImage!
override func awake(withContext context: Any?) {
super.awake(withContext: context)
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
super.didDeactivate()
}
// =========================================================================
// MARK: - Actions
@IBAction func strokeBtnTapped() {
// Create a graphics context
let size = CGSize(width: 100, height: 100)
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()!
// Setup for the path appearance
context.setStrokeColor(UIColor.white.cgColor)
context.setLineWidth(4.0)
// Draw lines
context.beginPath()
context.move(to: CGPoint(x: 0, y: 0))
context.addLine(to: CGPoint(x: 100, y: 100))
context.move(to: CGPoint(x: 0, y: 100))
context.addLine(to: CGPoint(x: 100, y: 0))
context.strokePath()
// Convert to UIImage
let cgimage = context.makeImage()
let uiimage = UIImage(cgImage: cgimage!)
// End the graphics context
UIGraphicsEndImageContext()
image.setImage(uiimage)
}
@IBAction func bezierBtnTapped() {
// Create a graphics context
let size = CGSize(width: 100, height: 100)
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()!
// Setup for the path appearance
UIColor.green.setStroke()
UIColor.white.setFill()
// Draw an oval
let rect = CGRect(x: 2, y: 2, width: 96, height: 96)
let path = UIBezierPath(ovalIn: rect)
path.lineWidth = 4.0
path.fill()
path.stroke()
// Convert to UIImage
let cgimage = context.makeImage()
let uiimage = UIImage(cgImage: cgimage!)
// End the graphics context
UIGraphicsEndImageContext()
image.setImage(uiimage)
}
@IBAction func svgBtnTapped() {
// Create a graphics context
let size = CGSize(width: 512, height: 512)
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()!
// Setup for the path appearance
UIColor.yellow.setFill()
// Convert SVG -> CGPath -> UIBezierPath
let pocketSvg = PocketSVG(fromSVGFileNamed: "sample")!
let path = pocketSvg.bezier!
print(path)
path.fill()
// Convert to UIImage
let cgimage = context.makeImage()
let uiimage = UIImage(cgImage: cgimage!)
// End the graphics context
UIGraphicsEndImageContext()
image.setImage(uiimage)
}
}
| mit | ebfda6efb6f4c203d26d1db45ab0ae2f | 26.267241 | 80 | 0.576984 | 5.151466 | false | false | false | false |
ochococo/Design-Patterns-In-Swift | source-cn/behavioral/command.swift | 2 | 1343 | /*:
👫 命令(Command)
------------
命令模式是一种设计模式,它尝试以对象来代表实际行动。命令对象可以把行动(action) 及其参数封装起来,于是这些行动可以被:
* 重复多次
* 取消(如果该对象有实现的话)
* 取消后又再重做
### 示例:
*/
protocol DoorCommand {
func execute() -> String
}
final class OpenCommand: DoorCommand {
let doors:String
required init(doors: String) {
self.doors = doors
}
func execute() -> String {
return "Opened \(doors)"
}
}
final class CloseCommand: DoorCommand {
let doors:String
required init(doors: String) {
self.doors = doors
}
func execute() -> String {
return "Closed \(doors)"
}
}
final class HAL9000DoorsOperations {
let openCommand: DoorCommand
let closeCommand: DoorCommand
init(doors: String) {
self.openCommand = OpenCommand(doors:doors)
self.closeCommand = CloseCommand(doors:doors)
}
func close() -> String {
return closeCommand.execute()
}
func open() -> String {
return openCommand.execute()
}
}
/*:
### 用法
*/
let podBayDoors = "Pod Bay Doors"
let doorModule = HAL9000DoorsOperations(doors:podBayDoors)
doorModule.open()
doorModule.close()
| gpl-3.0 | 313bc5e74f0a6ec39e655a155d64cd7c | 17.774194 | 64 | 0.616838 | 3.224377 | false | false | false | false |
katryo/MiniBond | Example/Tests/Tests.swift | 1 | 1175 | // https://github.com/Quick/Quick
import Quick
import Nimble
import MiniBond
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit | 357a3f644b48c94fc0eabc7f88ee576e | 22.38 | 63 | 0.362703 | 5.462617 | false | false | false | false |
evering7/iSpeak8 | Pods/FeedKit/Sources/FeedKit/Models/RSS/RSSPath.swift | 2 | 14780 | //
// RSSPath.swift
//
// Copyright (c) 2017 Nuno Manuel Dias
//
// 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
/// Describes the individual path for each XML DOM element of an RSS feed
///
/// See http://web.resource.org/rss/1.0/modules/content/
enum RSSPath: String {
case rss = "/rss"
case rssChannel = "/rss/channel"
case rssChannelTitle = "/rss/channel/title"
case rssChannelLink = "/rss/channel/link"
case rssChannelDescription = "/rss/channel/description"
case rssChannelLanguage = "/rss/channel/language"
case rssChannelCopyright = "/rss/channel/copyright"
case rssChannelManagingEditor = "/rss/channel/managingEditor"
case rssChannelWebMaster = "/rss/channel/webMaster"
case rssChannelPubDate = "/rss/channel/pubDate"
case rssChannelLastBuildDate = "/rss/channel/lastBuildDate"
case rssChannelCategory = "/rss/channel/category"
case rssChannelGenerator = "/rss/channel/generator"
case rssChannelDocs = "/rss/channel/docs"
case rssChannelCloud = "/rss/channel/cloud"
case rssChannelRating = "/rss/channel/rating"
case rssChannelTTL = "/rss/channel/ttl"
case rssChannelImage = "/rss/channel/image"
case rssChannelImageURL = "/rss/channel/image/url"
case rssChannelImageTitle = "/rss/channel/image/title"
case rssChannelImageLink = "/rss/channel/image/link"
case rssChannelImageWidth = "/rss/channel/image/width"
case rssChannelImageHeight = "/rss/channel/image/height"
case rssChannelImageDescription = "/rss/channel/image/description"
case rssChannelTextInput = "/rss/channel/textInput"
case rssChannelTextInputTitle = "/rss/channel/textInput/title"
case rssChannelTextInputDescription = "/rss/channel/textInput/description"
case rssChannelTextInputName = "/rss/channel/textInput/name"
case rssChannelTextInputLink = "/rss/channel/textInput/link"
case rssChannelSkipHours = "/rss/channel/skipHours"
case rssChannelSkipHoursHour = "/rss/channel/skipHours/hour"
case rssChannelSkipDays = "/rss/channel/skipDays"
case rssChannelSkipDaysDay = "/rss/channel/skipDays/day"
case rssChannelItem = "/rss/channel/item"
case rssChannelItemTitle = "/rss/channel/item/title"
case rssChannelItemLink = "/rss/channel/item/link"
case rssChannelItemDescription = "/rss/channel/item/description"
case rssChannelItemAuthor = "/rss/channel/item/author"
case rssChannelItemCategory = "/rss/channel/item/category"
case rssChannelItemComments = "/rss/channel/item/comments"
case rssChannelItemEnclosure = "/rss/channel/item/enclosure"
case rssChannelItemGUID = "/rss/channel/item/guid"
case rssChannelItemPubDate = "/rss/channel/item/pubDate"
case rssChannelItemSource = "/rss/channel/item/source"
// Content
case rssChannelItemContentEncoded = "/rss/channel/item/content:encoded"
// Syndication
case rssChannelSyndicationUpdatePeriod = "/rss/channel/sy:updatePeriod"
case rssChannelSyndicationUpdateFrequency = "/rss/channel/sy:updateFrequency"
case rssChannelSyndicationUpdateBase = "/rss/channel/sy:updateBase"
// Dublin Core
case rssChannelDublinCoreTitle = "/rss/channel/dc:title"
case rssChannelDublinCoreCreator = "/rss/channel/dc:creator"
case rssChannelDublinCoreSubject = "/rss/channel/dc:subject"
case rssChannelDublinCoreDescription = "/rss/channel/dc:description"
case rssChannelDublinCorePublisher = "/rss/channel/dc:publisher"
case rssChannelDublinCoreContributor = "/rss/channel/dc:contributor"
case rssChannelDublinCoreDate = "/rss/channel/dc:date"
case rssChannelDublinCoreType = "/rss/channel/dc:type"
case rssChannelDublinCoreFormat = "/rss/channel/dc:format"
case rssChannelDublinCoreIdentifier = "/rss/channel/dc:identifier"
case rssChannelDublinCoreSource = "/rss/channel/dc:source"
case rssChannelDublinCoreLanguage = "/rss/channel/dc:language"
case rssChannelDublinCoreRelation = "/rss/channel/dc:relation"
case rssChannelDublinCoreCoverage = "/rss/channel/dc:coverage"
case rssChannelDublinCoreRights = "/rss/channel/dc:rights"
case rssChannelItemDublinCoreTitle = "/rss/channel/item/dc:title"
case rssChannelItemDublinCoreCreator = "/rss/channel/item/dc:creator"
case rssChannelItemDublinCoreSubject = "/rss/channel/item/dc:subject"
case rssChannelItemDublinCoreDescription = "/rss/channel/item/dc:description"
case rssChannelItemDublinCorePublisher = "/rss/channel/item/dc:publisher"
case rssChannelItemDublinCoreContributor = "/rss/channel/item/dc:contributor"
case rssChannelItemDublinCoreDate = "/rss/channel/item/dc:date"
case rssChannelItemDublinCoreType = "/rss/channel/item/dc:type"
case rssChannelItemDublinCoreFormat = "/rss/channel/item/dc:format"
case rssChannelItemDublinCoreIdentifier = "/rss/channel/item/dc:identifier"
case rssChannelItemDublinCoreSource = "/rss/channel/item/dc:source"
case rssChannelItemDublinCoreLanguage = "/rss/channel/item/dc:language"
case rssChannelItemDublinCoreRelation = "/rss/channel/item/dc:relation"
case rssChannelItemDublinCoreCoverage = "/rss/channel/item/dc:coverage"
case rssChannelItemDublinCoreRights = "/rss/channel/item/dc:rights"
// iTunes Podcasting Tags
case rssChannelItunesAuthor = "/rss/channel/itunes:author"
case rssChannelItunesBlock = "/rss/channel/itunes:block"
case rssChannelItunesCategory = "/rss/channel/itunes:category"
case rssChannelItunesSubcategory = "/rss/channel/itunes:category/itunes:category"
case rssChannelItunesImage = "/rss/channel/itunes:image"
case rssChannelItunesExplicit = "/rss/channel/itunes:explicit"
case rssChannelItunesComplete = "/rss/channel/itunes:complete"
case rssChannelItunesNewFeedURL = "/rss/channel/itunes:new-feed-url"
case rssChannelItunesOwner = "/rss/channel/itunes:owner"
case rssChannelItunesOwnerEmail = "/rss/channel/itunes:owner/itunes:email"
case rssChannelItunesOwnerName = "/rss/channel/itunes:owner/itunes:name"
case rssChannelItunesSubtitle = "/rss/channel/itunes:subtitle"
case rssChannelItunesSummary = "/rss/channel/itunes:summary"
case rssChannelItunesKeywords = "/rss/channel/itunes:keywords"
case rssChannelItemItunesAuthor = "/rss/channel/item/itunes:author"
case rssChannelItemItunesBlock = "/rss/channel/item/itunes:block"
case rssChannelItemItunesImage = "/rss/channel/item/itunes:image"
case rssChannelItemItunesDuration = "/rss/channel/item/itunes:duration"
case rssChannelItemItunesExplicit = "/rss/channel/item/itunes:explicit"
case rssChannelItemItunesIsClosedCaptioned = "/rss/channel/item/itunes:isClosedCaptioned"
case rssChannelItemItunesOrder = "/rss/channel/item/itunes:order"
case rssChannelItemItunesSubtitle = "/rss/channel/item/itunes:subtitle"
case rssChannelItemItunesSummary = "/rss/channel/item/itunes:summary"
case rssChannelItemItunesKeywords = "/rss/channel/item/itunes:keywords"
// MARK: Media
case rssChannelItemMediaThumbnail = "/rss/channel/item/media:thumbnail"
case rssChannelItemMediaContent = "/rss/channel/item/media:content"
case rssChannelItemMediaCommunity = "/rss/channel/item/media:community"
case rssChannelItemMediaCommunityMediaStarRating = "/rss/channel/item/media:community/media:starRating"
case rssChannelItemMediaCommunityMediaStatistics = "/rss/channel/item/media:community/media:statistics"
case rssChannelItemMediaCommunityMediaTags = "/rss/channel/item/media:community/media:tags"
case rssChannelItemMediaComments = "/rss/channel/item/media:comments"
case rssChannelItemMediaCommentsMediaComment = "/rss/channel/item/media:comments/media:comment"
case rssChannelItemMediaEmbed = "/rss/channel/item/media:embed"
case rssChannelItemMediaEmbedMediaParam = "/rss/channel/item/media:embed/media:param"
case rssChannelItemMediaResponses = "/rss/channel/item/media:responses"
case rssChannelItemMediaResponsesMediaResponse = "/rss/channel/item/media:responses/media:response"
case rssChannelItemMediaBackLinks = "/rss/channel/item/media:backLinks"
case rssChannelItemMediaBackLinksBackLink = "/rss/channel/item/media:backLinks/media:backLink"
case rssChannelItemMediaStatus = "/rss/channel/item/media:status"
case rssChannelItemMediaPrice = "/rss/channel/item/media:price"
case rssChannelItemMediaLicense = "/rss/channel/item/media:license"
case rssChannelItemMediaSubTitle = "/rss/channel/item/media:subTitle"
case rssChannelItemMediaPeerLink = "/rss/channel/item/media:peerLink"
case rssChannelItemMediaLocation = "/rss/channel/item/media:location"
case rssChannelItemMediaLocationPosition = "/rss/channel/item/media:location/georss:where/gml:Point/gml:pos"
case rssChannelItemMediaRestriction = "/rss/channel/item/media:restriction"
case rssChannelItemMediaScenes = "/rss/channel/item/media:scenes"
case rssChannelItemMediaScenesMediaScene = "/rss/channel/item/media:scenes/media:scene"
case rssChannelItemMediaScenesMediaSceneSceneTitle = "/rss/channel/item/media:scenes/media:scene/sceneTitle"
case rssChannelItemMediaScenesMediaSceneSceneDescription = "/rss/channel/item/media:scenes/media:scene/sceneDescription"
case rssChannelItemMediaScenesMediaSceneSceneStartTime = "/rss/channel/item/media:scenes/media:scene/sceneStartTime"
case rssChannelItemMediaScenesMediaSceneSceneEndTime = "/rss/channel/item/media:scenes/media:scene/sceneEndTime"
case rssChannelItemMediaGroup = "/rss/channel/item/media:group"
case rssChannelItemMediaGroupMediaCredit = "/rss/channel/item/media:group/media:credit"
case rssChannelItemMediaGroupMediaCategory = "/rss/channel/item/media:group/media:category"
case rssChannelItemMediaGroupMediaRating = "/rss/channel/item/media:group/media:rating"
case rssChannelItemMediaGroupMediaContent = "/rss/channel/item/media:group/media:content"
}
| mit | 534ba0a9bb1b1eacd23b0f986e9e726e | 79.326087 | 131 | 0.574222 | 4.954744 | false | false | false | false |
tavultesoft/keymanweb | ios/engine/KMEI/KeymanEngine/Classes/LanguageLMDetailViewController.swift | 1 | 7654 | //
// LanguageLMDetailViewController.swift
// KeymanEngine
//
// Created by Randy Boring on 7/19/19.
// Copyright © 2019 SIL International. All rights reserved.
//
import UIKit
private let toolbarButtonTag = 100
private let toolbarLabelTag = 101
private let toolbarActivityIndicatorTag = 102
class LanguageLMDetailViewController: UITableViewController, UIAlertViewDelegate {
private var userLexicalModels: [String: InstallableLexicalModel] = [:]
private var isUpdate = false // unused currently, may be used when we switch to HTTPDownloader
private let language: Language
public var packages: [(InstallableLexicalModel, URL)]
private var lexicalModelDownloadStartedObserver: NotificationObserver?
//NOTE: there is no need for a CompletedObserver, as our parent LexicalModelPickerViewController
// is registered for that and deals with it by popping us out to root.
private var lexicalModelDownloadFailedObserver: NotificationObserver?
private var onSuccessClosure: ((InstallableLexicalModel) -> Void)?
init(language: Language, packages: [(InstallableLexicalModel, URL)], onSuccess: ((InstallableLexicalModel) -> Void)?) {
self.language = language
self.packages = packages
self.onSuccessClosure = onSuccess
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
super.loadView()
loadUserLexicalModels()
tableView.dataSource = self
}
override func viewDidLoad() {
super.viewDidLoad()
lexicalModelDownloadStartedObserver = NotificationCenter.default.addObserver(
forName: Notifications.packageDownloadStarted,
observer: self,
function: LanguageLMDetailViewController.lexicalModelDownloadStarted)
lexicalModelDownloadFailedObserver = NotificationCenter.default.addObserver(
forName: Notifications.packageDownloadFailed,
observer: self,
function: LanguageLMDetailViewController.lexicalModelDownloadFailed)
log.info("viewDidLoad: LanguageLMDetailViewController (registered for lexicalModelDownloadStarted)")
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
log.info("willAppear: LanguageLMDetailViewController")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
log.info("didAppear: LanguageLMDetailViewController")
navigationController?.setToolbarHidden(true, animated: true)
}
// MARK: - Table view data source UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return packages.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
if let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) {
return cell
}
let cell = KeyboardNameTableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier)
let selectionColor = UIView()
selectionColor.backgroundColor = Colors.selectionPrimary
cell.selectedBackgroundView = selectionColor
return cell
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let lexicalModel = packages[indexPath.section].0
let cell = cell as! KeyboardNameTableViewCell
cell.indexPath = indexPath
cell.textLabel?.text = lexicalModel.name
if isAdded(languageID: language.id, lexicalModelID: lexicalModel.id) {
cell.accessoryType = .checkmark
cell.isUserInteractionEnabled = false
cell.textLabel?.isEnabled = false
cell.detailTextLabel?.isEnabled = false
} else {
cell.accessoryType = .none
cell.isUserInteractionEnabled = true
cell.textLabel?.isEnabled = true
cell.detailTextLabel?.isEnabled = true
}
let state = ResourceFileManager.shared.installState(forPackage: KeymanPackage.Key(id: lexicalModel.id, type: .lexicalModel))
cell.setInstallState(state, selected: false, defaultAccessoryType: cell.accessoryType)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.cellForRow(at: indexPath)?.isSelected = false
let lexicalModelIndex = indexPath.section
let lexicalModel = packages[lexicalModelIndex].0
let state = ResourceFileManager.shared.installState(forPackage: KeymanPackage.Key(id: lexicalModel.id, type: .lexicalModel))
if state != .downloading {
if state == .none {
isUpdate = false
} else {
isUpdate = true
}
let format = NSLocalizedString("menu-lexical-model-install-title", bundle: engineBundle, comment: "")
let alertController = UIAlertController(title: String.localizedStringWithFormat(format, language.name, lexicalModel.name),
message: NSLocalizedString("menu-lexical-model-install-message", bundle: engineBundle, comment: ""),
preferredStyle: UIAlertController.Style.alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("command-cancel", bundle: engineBundle, comment: ""),
style: UIAlertAction.Style.cancel,
handler: nil))
alertController.addAction(UIAlertAction(title: NSLocalizedString("command-install", bundle: engineBundle, comment: ""),
style: UIAlertAction.Style.default,
handler: {_ in self.downloadHandler(lexicalModelIndex)} ))
self.present(alertController, animated: true, completion: nil)
}
}
func downloadHandler(_ lexicalModelIndex: Int) {
let package = packages[lexicalModelIndex]
let lmFullID = package.0.fullID
let completionClosure: ResourceDownloadManager.CompletionHandler<LexicalModelKeymanPackage> = { package, error in
try? ResourceDownloadManager.shared.standardLexicalModelInstallCompletionBlock(forFullID: lmFullID)(package, error)
if let lm = package?.findResource(withID: lmFullID) {
self.onSuccessClosure?(lm)
}
}
ResourceDownloadManager.shared.downloadPackage(withKey: package.0.packageKey, from: package.1, withNotifications: true, completionBlock: completionClosure)
}
private func lexicalModelDownloadStarted() {
log.info("lexicalModelDownloadStarted: LanguageLMDetailViewController")
view.isUserInteractionEnabled = false
navigationItem.setHidesBackButton(true, animated: true)
navigationController?.setToolbarHidden(false, animated: true)
}
private func lexicalModelDownloadFailed() {
log.info("lexicalModelDownloadFailed: LanguageLMDetailViewController")
view.isUserInteractionEnabled = true
navigationItem.setHidesBackButton(false, animated: true)
}
private func loadUserLexicalModels() {
guard let userLmList = Storage.active.userDefaults.userLexicalModels, !userLmList.isEmpty else {
userLexicalModels = [:]
return
}
userLexicalModels = [:]
for lm in userLmList {
let dictKey = "\(lm.languageID)_\(lm.id)"
userLexicalModels[dictKey] = lm
}
}
private func isAdded(languageID: String?, lexicalModelID: String?) -> Bool {
guard let languageID = languageID, let lexicalModelID = lexicalModelID else {
return false
}
return userLexicalModels["\(languageID)_\(lexicalModelID)"] != nil
}
}
| apache-2.0 | 8d441d8861ddc4c1994b4fa5b3d67ffc | 39.068063 | 159 | 0.725206 | 5.160486 | false | false | false | false |
tkremenek/swift | test/SILOptimizer/access_enforcement_options.swift | 21 | 1854 | // RUN: %target-swift-frontend -Onone -emit-sil -parse-as-library %s | %FileCheck %s --check-prefix=CHECK --check-prefix=NONE
// RUN: %target-swift-frontend -Osize -emit-sil -parse-as-library %s | %FileCheck %s --check-prefix=CHECK --check-prefix=OPT
// RUN: %target-swift-frontend -O -emit-sil -parse-as-library %s | %FileCheck %s --check-prefix=CHECK --check-prefix=OPT
// RUN: %target-swift-frontend -Ounchecked -emit-sil -parse-as-library %s | %FileCheck %s --check-prefix=CHECK --check-prefix=UNCHECKED
@inline(never)
func takesInoutAndEscaping(_: inout Int, _ f: @escaping () -> ()) {
f()
}
@inline(never)
func escapeClosure(_ f: @escaping () -> ()) -> () -> () {
return f
}
public func accessIntTwice() {
var x = 0
takesInoutAndEscaping(&x, escapeClosure({ x = 3 }))
}
// accessIntTwice()
// CHECK-LABEL: sil @$s26access_enforcement_options0A8IntTwiceyyF : $@convention(thin) () -> () {
// CHECK: [[BOX:%.*]] = alloc_box ${ var Int }, var, name "x"
// CHECK: [[PROJ:%.*]] = project_box [[BOX]] : ${ var Int }, 0
// NONE: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[PROJ]] : $*Int
// OPT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[PROJ]] : $*Int
// UNCHECKED-NOT: = begin_access
// CHECK-LABEL: } // end sil function '$s26access_enforcement_options0A8IntTwiceyyF'
// closure #1 in accessIntTwice()
// CHECK-LABEL: sil private @$s26access_enforcement_options0A8IntTwiceyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () {
// CHECK: bb0(%0 : ${ var Int }):
// CHECK: [[PROJ:%.*]] = project_box %0 : ${ var Int }, 0
// NONE: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[PROJ]] : $*Int
// OPT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[PROJ]] : $*Int
// UNCHECKED-NOT: = begin_access
// CHECK-LABEL: } // end sil function '$s26access_enforcement_options0A8IntTwiceyyFyycfU_'
| apache-2.0 | 19c4f95eca7bb85594993ef9eecff4cb | 49.108108 | 135 | 0.641855 | 3.115966 | false | false | false | false |
Cereopsis/swift-bowling | functional_game_tests.swift | 1 | 3340 | /*
The MIT License (MIT)
Copyright (c) 2015 Cereopsis
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 XCTest
class FunctionalGameTests: XCTestCase {
func testFrameTuple() {
let frame: Frame = (10, 0, nil)
XCTAssertEqual(frame.t1, 10)
XCTAssertEqual(frame.t2, 0)
XCTAssertNil(frame.filler)
}
/**
example score taken from
http://bowling.about.com/od/rulesofthegame/a/bowlingscoring.htm
Frame: 1 2 3 4 5 6 7 8 9 10
Result: X 7/ 7 2 9/ X X X 2 3 6/ 7/3
Frame Score: 20 17 9 20 30 22 15 5 17 13
Running Total: 20 37 46 66 96 118 133 138 155 168
*/
func testImperfectGameScore() {
var game = Game()
game.add((10, 0, nil))
game.add((7,3,nil))
game.add((7,2,nil))
game.add((9,1,nil))
game.add((10,0,nil))
game.add((10,0,nil))
game.add((10,0,nil))
game.add((2,3,nil))
game.add((6,4,nil))
game.add((7,3,3))
XCTAssertTrue(game.isComplete)
let scores = game.scores()
XCTAssertEqual(scores.count, 10)
var result = scores.map{ $0.0 }.joinWithSeparator(" ")
var expected = "X 7/ 7 2 9/ X X X 2 3 6/ 7/3"
XCTAssertEqual(result, expected)
result = scores.map{ "\($0.1)" }.joinWithSeparator(" ")
expected = "20 17 9 20 30 22 15 5 17 13"
XCTAssertEqual(result, expected)
result = scores.map{ "\($0.2)" }.joinWithSeparator(" ")
expected = "20 37 46 66 96 118 133 138 155 168"
XCTAssertEqual(result, expected)
}
func testPerfectGameScore() {
var game = Game()
for _ in 0..<9 {
game.add((10,0,nil))
}
game.add((10,10,10))
XCTAssertTrue(game.isComplete)
let scores = game.scores()
XCTAssertEqual(scores.count, 10)
var result = scores.map{ $0.0 }.joinWithSeparator(" ")
var expected = "X X X X X X X X X X"
XCTAssertEqual(result, expected)
result = scores.map{ "\($0.1)" }.joinWithSeparator(" ")
expected = "30 30 30 30 30 30 30 30 30 30"
XCTAssertEqual(result, expected)
result = scores.map{ "\($0.2)" }.joinWithSeparator(" ")
expected = "30 60 90 120 150 180 210 240 270 300"
XCTAssertEqual(result, expected)
}
}
| mit | 31679dfc89e569cb0431c71f45b056f7 | 36.111111 | 78 | 0.631138 | 3.75703 | false | true | false | false |
Allow2CEO/browser-ios | brave/src/frontend/tabsbar/TabsBarViewController.swift | 1 | 17942 | /* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import SnapKit
import Shared
enum TabsBarShowPolicy : Int {
case never
case always
case landscapeOnly
}
let kRearangeTabNotification = Notification.Name("kRearangeTabNotification")
let kPrefKeyTabsBarShowPolicy = "kPrefKeyTabsBarShowPolicy"
let kPrefKeyTabsBarOnDefaultValue = TabsBarShowPolicy.always
let minTabWidth = UIDevice.current.userInterfaceIdiom == .pad ? CGFloat(180) : CGFloat(160)
let tabHeight = TabsBarHeight
protocol TabBarCellDelegate: class {
func tabClose(_ tab: Browser?)
}
class TabBarCell: UICollectionViewCell {
let title = UILabel()
let close = UIButton()
let separatorLineRight = UIView()
var currentIndex: Int = -1 {
didSet {
isSelected = currentIndex == getApp().tabManager.currentDisplayedIndex
}
}
weak var browser: Browser? {
didSet {
if let wv = self.browser?.webView {
wv.delegatesForPageState.append(BraveWebView.Weak_WebPageStateDelegate(value: self))
}
}
}
weak var delegate: TabBarCellDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
close.addTarget(self, action: #selector(closeTab), for: .touchUpInside)
[close, title, separatorLineRight].forEach { contentView.addSubview($0) }
title.textAlignment = .center
title.snp.makeConstraints({ (make) in
make.top.bottom.equalTo(self)
make.left.equalTo(self).inset(16)
make.right.equalTo(close.snp.left)
})
close.setImage(UIImage(named: "close")?.withRenderingMode(.alwaysTemplate), for: .normal)
close.snp.makeConstraints({ (make) in
make.top.bottom.equalTo(self)
make.right.equalTo(self).inset(2)
make.width.equalTo(30)
})
close.tintColor = PrivateBrowsing.singleton.isOn ? BraveUX.GreyG : BraveUX.GreyI
// Close button is a bit wider to increase tap area, this aligns 'X' image closer to the right.
close.imageEdgeInsets.left = 6
separatorLineRight.isHidden = true
separatorLineRight.snp.makeConstraints { (make) in
make.right.equalTo(self)
make.width.equalTo(0.5)
make.height.equalTo(self)
make.centerY.equalTo(self.snp.centerY)
}
isSelected = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var isSelected: Bool {
didSet(selected) {
if selected {
title.font = UIFont.systemFont(ofSize: 12, weight: UIFontWeightSemibold)
title.textColor = PrivateBrowsing.singleton.isOn ? BraveUX.GreyA : BraveUX.GreyJ
close.isHidden = false
close.tintColor = PrivateBrowsing.singleton.isOn ? BraveUX.GreyF : BraveUX.GreyI
separatorLineRight.isHidden = true
backgroundColor = PrivateBrowsing.singleton.isOn ? BraveUX.DarkToolbarsBackgroundSolidColor : BraveUX.ToolbarsBackgroundSolidColor
}
else if currentIndex != getApp().tabManager.currentDisplayedIndex {
// prevent swipe and release outside- deselects cell.
title.font = UIFont.systemFont(ofSize: 12)
title.textColor = PrivateBrowsing.singleton.isOn ? BraveUX.GreyG : BraveUX.GreyG
close.isHidden = true
separatorLineRight.isHidden = false
separatorLineRight.backgroundColor = PrivateBrowsing.singleton.isOn ? BraveUX.GreyJ : BraveUX.GreyD
backgroundColor = UIColor.clear
}
}
}
func closeTab() {
delegate?.tabClose(browser)
}
fileprivate var titleUpdateScheduled = false
func updateTitle_throttled() {
if titleUpdateScheduled {
return
}
titleUpdateScheduled = true
postAsyncToMain(0.2) { [weak self] in
self?.titleUpdateScheduled = false
self?.title.text = self?.browser?.displayTitle
}
}
}
extension TabBarCell: WebPageStateDelegate {
func webView(_ webView: UIWebView, urlChanged: String) {
title.text = browser?.displayTitle
updateTitle_throttled()
}
func webView(_ webView: UIWebView, progressChanged: Float) {
updateTitle_throttled()
}
func webView(_ webView: UIWebView, isLoading: Bool) {}
func webView(_ webView: UIWebView, canGoBack: Bool) {}
func webView(_ webView: UIWebView, canGoForward: Bool) {}
}
class TabsBarViewController: UIViewController {
var plusButton = UIButton()
var leftOverflowIndicator : CAGradientLayer = CAGradientLayer()
var rightOverflowIndicator : CAGradientLayer = CAGradientLayer()
var collectionLayout: UICollectionViewFlowLayout!
var collectionView: UICollectionView!
fileprivate var tabList = WeakList<Browser>()
var isVisible:Bool {
return self.view.alpha > 0
}
override func viewDidLoad() {
super.viewDidLoad()
collectionLayout = UICollectionViewFlowLayout()
collectionLayout.scrollDirection = .horizontal
collectionLayout.itemSize = CGSize(width: minTabWidth, height: view.frame.height)
collectionLayout.minimumInteritemSpacing = 0
collectionLayout.minimumLineSpacing = 0
collectionView = UICollectionView(frame: view.frame, collectionViewLayout: collectionLayout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.bounces = false
collectionView.delegate = self
collectionView.dataSource = self
collectionView.allowsSelection = true
collectionView.decelerationRate = UIScrollViewDecelerationRateNormal
collectionView.register(TabBarCell.self, forCellWithReuseIdentifier: "TabCell")
view.addSubview(collectionView)
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongGesture(gesture:)))
longPressGesture.minimumPressDuration = 0.2
collectionView.addGestureRecognizer(longPressGesture)
if UIDevice.current.userInterfaceIdiom == .pad {
plusButton.setImage(UIImage(named: "add")!.withRenderingMode(.alwaysTemplate), for: .normal)
plusButton.imageEdgeInsets = UIEdgeInsetsMake(6, 10, 6, 10)
plusButton.tintColor = BraveUX.GreyI
plusButton.contentMode = .scaleAspectFit
plusButton.addTarget(self, action: #selector(addTabPressed), for: .touchUpInside)
plusButton.backgroundColor = UIColor(white: 0.0, alpha: 0.075)
view.addSubview(plusButton)
plusButton.snp.makeConstraints { (make) in
make.right.top.bottom.equalTo(view)
make.width.equalTo(BraveUX.TabsBarPlusButtonWidth)
}
}
collectionView.snp.makeConstraints { (make) in
make.bottom.top.left.equalTo(view)
make.right.equalTo(view).inset(BraveUX.TabsBarPlusButtonWidth)
}
getApp().tabManager.addDelegate(self)
NotificationCenter.default.addObserver(self, selector: #selector(updateData), name: kRearangeTabNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
updateData()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// ensure the selected tab is visible after rotations
if let index = getApp().tabManager.currentDisplayedIndex {
let indexPath = IndexPath(item: index, section: 0)
// since bouncing is disabled, centering horizontally
// will not overshoot the edges for the bookend tabs
collectionView?.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
}
postAsyncToMain(0.1) {
self.reloadDataAndRestoreSelectedTab()
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func orientationChanged() {
overflowIndicators()
}
func updateData() {
tabList = WeakList<Browser>()
getApp().tabManager.tabs.displayedTabsForCurrentPrivateMode.forEach {
tabList.insert($0)
}
overflowIndicators()
reloadDataAndRestoreSelectedTab()
}
func reloadDataAndRestoreSelectedTab() {
collectionView.reloadData()
if let selectedTab = getApp().tabManager.selectedTab {
let selectedIndex = tabList.index(of: selectedTab) ?? 0
if selectedIndex < tabList.count() {
collectionView.selectItem(at: IndexPath(row: selectedIndex, section: 0), animated: (!getApp().tabManager.isRestoring), scrollPosition: .centeredHorizontally)
}
}
}
func handleLongGesture(gesture: UILongPressGestureRecognizer) {
switch(gesture.state) {
case UIGestureRecognizerState.began:
guard let selectedIndexPath = self.collectionView.indexPathForItem(at: gesture.location(in: self.collectionView)) else {
break
}
collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
case UIGestureRecognizerState.changed:
collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
case UIGestureRecognizerState.ended:
collectionView.endInteractiveMovement()
default:
collectionView.cancelInteractiveMovement()
}
}
func addTabPressed() {
getApp().tabManager.addTabAndSelect()
}
func tabOverflowWidth(_ tabCount: Int) -> CGFloat {
let overflow = CGFloat(tabCount) * minTabWidth - collectionView.frame.width
return overflow > 0 ? overflow : 0
}
func overflowIndicators() {
// super lame place to put this, need to find a better solution.
plusButton.tintColor = PrivateBrowsing.singleton.isOn ? BraveUX.GreyF : BraveUX.GreyI
collectionView.backgroundColor = PrivateBrowsing.singleton.isOn ? BraveUX.Black : BraveUX.GreyB
scrollHints()
if tabOverflowWidth(getApp().tabManager.tabCount) < 1 {
leftOverflowIndicator.opacity = 0
rightOverflowIndicator.opacity = 0
return
}
let offset = Float(collectionView.contentOffset.x)
let startFade = Float(30)
if offset < startFade {
leftOverflowIndicator.opacity = offset / startFade
} else {
leftOverflowIndicator.opacity = 1
}
// all the way scrolled right
let offsetFromRight = collectionView.contentSize.width - CGFloat(offset) - collectionView.frame.width
if offsetFromRight < CGFloat(startFade) {
rightOverflowIndicator.opacity = Float(offsetFromRight) / startFade
} else {
rightOverflowIndicator.opacity = 1
}
}
func scrollHints() {
addLeftRightScrollHint(false, maskLayer: leftOverflowIndicator)
addLeftRightScrollHint(true, maskLayer: rightOverflowIndicator)
}
func addLeftRightScrollHint(_ isRightSide: Bool, maskLayer: CAGradientLayer) {
maskLayer.removeFromSuperlayer()
let colors = PrivateBrowsing.singleton.isOn ? [BraveUX.DarkToolbarsBackgroundSolidColor.withAlphaComponent(0).cgColor, BraveUX.DarkToolbarsBackgroundSolidColor.cgColor] : [BraveUX.ToolbarsBackgroundSolidColor.withAlphaComponent(0).cgColor, BraveUX.ToolbarsBackgroundSolidColor.cgColor]
let locations = [0.9, 1.0]
maskLayer.startPoint = CGPoint(x: isRightSide ? 0 : 1.0, y: 0.5)
maskLayer.endPoint = CGPoint(x: isRightSide ? 1.0 : 0, y: 0.5)
maskLayer.opacity = 0
maskLayer.colors = colors;
maskLayer.locations = locations as [NSNumber];
maskLayer.bounds = CGRect(x: 0, y: 0, width: collectionView.frame.width, height: tabHeight)
maskLayer.anchorPoint = CGPoint.zero;
// you must add the mask to the root view, not the scrollView, otherwise the masks will move as the user scrolls!
view.layer.addSublayer(maskLayer)
}
}
extension TabsBarViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
overflowIndicators()
}
}
extension TabsBarViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tabList.count()
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: TabBarCell = collectionView.dequeueReusableCell(withReuseIdentifier: "TabCell", for: indexPath) as! TabBarCell
guard let tab = tabList.at(indexPath.row) else { return cell }
cell.delegate = self
cell.browser = tab
cell.title.text = tab.displayTitle
cell.currentIndex = indexPath.row
debugPrint("index: \(getApp().tabManager.currentDisplayedIndex ?? -1)")
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let tab = tabList.at(indexPath.row)
getApp().tabManager.selectTab(tab)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if tabList.count() == 1 {
return CGSize(width: view.frame.width, height: view.frame.height)
}
let newTabButtonWidth = CGFloat(UIDevice.current.userInterfaceIdiom == .pad ? BraveUX.TabsBarPlusButtonWidth : 0)
let tabsAndButtonWidth = CGFloat(tabList.count()) * minTabWidth
if tabsAndButtonWidth < collectionView.frame.width - newTabButtonWidth {
let maxWidth = (collectionView.frame.width - newTabButtonWidth) / CGFloat(tabList.count())
return CGSize(width: maxWidth, height: view.frame.height)
}
return CGSize(width: minTabWidth, height: view.frame.height)
}
func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
return true
}
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
guard let tab = tabList.at(sourceIndexPath.row) else { return }
// Find original from/to index... we need to target the full list not partial.
guard let tabManager = getApp().tabManager else { return }
guard let from = tabManager.tabs.tabs.index(where: {$0 === tab}) else { return }
let toTab = tabList.at(destinationIndexPath.row)
guard let to = tabManager.tabs.tabs.index(where: {$0 === toTab}) else { return }
tabManager.move(tab: tab, from: from, to: to)
updateData()
guard let selectedTab = tabList.at(destinationIndexPath.row) else { return }
tabManager.selectTab(selectedTab)
}
}
extension TabsBarViewController: TabBarCellDelegate {
func tabClose(_ tab: Browser?) {
guard let tab = tab else { return }
guard let tabManager = getApp().tabManager else { return }
guard let previousIndex = tabList.index(of: tab) else { return }
tabManager.removeTab(tab, createTabIfNoneLeft: true)
updateData()
let previousOrNext = max(0, previousIndex - 1)
tabManager.selectTab(tabList.at(previousOrNext))
collectionView.selectItem(at: IndexPath(row: previousOrNext, section: 0), animated: true, scrollPosition: .centeredHorizontally)
}
}
extension TabsBarViewController: TabManagerDelegate {
func tabManagerDidEnterPrivateBrowsingMode(_ tabManager: TabManager) {
assert(Thread.current.isMainThread)
updateData()
}
func tabManagerDidExitPrivateBrowsingMode(_ tabManager: TabManager) {
assert(Thread.current.isMainThread)
updateData()
}
func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Browser?) {
assert(Thread.current.isMainThread)
updateData()
}
func tabManager(_ tabManager: TabManager, didCreateWebView tab: Browser, url: URL?, at: Int?) {
updateData()
getApp().browserViewController.urlBar.updateTabsBarShowing()
}
func tabManager(_ tabManager: TabManager, didAddTab tab: Browser) {
updateData()
}
func tabManager(_ tabManager: TabManager, didRemoveTab tab: Browser) {
assert(Thread.current.isMainThread)
updateData()
getApp().browserViewController.urlBar.updateTabsBarShowing()
}
func tabManagerDidRestoreTabs(_ tabManager: TabManager) {
assert(Thread.current.isMainThread)
updateData()
getApp().browserViewController.urlBar.updateTabsBarShowing()
}
func tabManagerDidAddTabs(_ tabManager: TabManager) {}
}
| mpl-2.0 | 9ef0906fa32ad46ba5a48c611dc968d4 | 38.959911 | 293 | 0.663861 | 5.143922 | false | false | false | false |
Finb/V2ex-Swift | View/MemberHeaderCell.swift | 1 | 2984 | //
// MemberHeaderCell.swift
// V2ex-Swift
//
// Created by huangfeng on 2/1/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
class MemberHeaderCell: UITableViewCell {
/// 头像
var avatarImageView: UIImageView = {
let avatarImageView = UIImageView()
avatarImageView.backgroundColor = UIColor(white: 0.9, alpha: 0.3)
avatarImageView.layer.borderWidth = 1.5
avatarImageView.layer.borderColor = UIColor(white: 1, alpha: 0.6).cgColor
avatarImageView.layer.masksToBounds = true
avatarImageView.layer.cornerRadius = 38
return avatarImageView
}()
/// 用户名
var userNameLabel: UILabel = {
let userNameLabel = UILabel()
userNameLabel.textColor = UIColor(white: 0.85, alpha: 1)
userNameLabel.font = v2Font(16)
userNameLabel.text = "Hello"
return userNameLabel
}()
/// 签名
var introduceLabel: UILabel = {
let introduceLabel = UILabel()
introduceLabel.textColor = UIColor(white: 0.75, alpha: 1)
introduceLabel.font = v2Font(16)
introduceLabel.numberOfLines = 2
introduceLabel.textAlignment = .center
return introduceLabel
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier);
self.setup();
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setup()->Void{
self.backgroundColor = UIColor.clear
self.selectionStyle = .none
self.contentView.addSubview(self.avatarImageView)
self.contentView.addSubview(self.userNameLabel)
self.contentView.addSubview(self.introduceLabel)
self.setupLayout()
}
func setupLayout(){
self.avatarImageView.snp.makeConstraints{ (make) -> Void in
make.centerX.equalTo(self.contentView)
make.centerY.equalTo(self.contentView).offset(-15)
make.width.height.equalTo(self.avatarImageView.layer.cornerRadius * 2)
}
self.userNameLabel.snp.makeConstraints{ (make) -> Void in
make.top.equalTo(self.avatarImageView.snp.bottom).offset(10)
make.centerX.equalTo(self.avatarImageView)
}
self.introduceLabel.snp.makeConstraints{ (make) -> Void in
make.top.equalTo(self.userNameLabel.snp.bottom).offset(5)
make.centerX.equalTo(self.avatarImageView)
make.left.equalTo(self.contentView).offset(15)
make.right.equalTo(self.contentView).offset(-15)
}
}
func bind(_ model:MemberModel?){
if let model = model {
if let avata = model.avata?.avatarString {
self.avatarImageView.kf.setImage(with: URL(string: avata)!)
}
self.userNameLabel.text = model.userName;
self.introduceLabel.text = model.introduce;
}
}
}
| mit | ba2386cf404ce87e9d16cffbff6e166c | 34.345238 | 82 | 0.637588 | 4.539755 | false | false | false | false |
nahive/location-spoofer | source/location-spoofer/MapViewController.swift | 1 | 4481 | //
// MapViewController.swift
// location-spoofer
//
// Created by Szymon Maslanka on 13/07/16.
// Copyright © 2016 Szymon Maslanka. All rights reserved.
//
import Cocoa
import MapKit
let knownLocations = ["smt" : CLLocation(latitude: 51.102411, longitude: 17.032319)]
protocol MapViewControllerDelegate: class {
func mapViewController(controller: MapViewController, mapView: MKMapView, didClickAtLocation location: CLLocationCoordinate2D)
}
class MapViewController: NSViewController {
weak var delegate: MapViewControllerDelegate?
@IBOutlet weak var mapView: MKMapView!
var startAnnotation: Annotation?
var currentAnnotation: Annotation?
var endAnnotation: Annotation?
var routePolyline: MKPolyline?
override func viewDidLoad() {
super.viewDidLoad()
setupMapView()
}
private func setupMapView(){
mapView.delegate = self
mapView.showsCompass = false
mapView.showsUserLocation = true
mapView.addGestureRecognizer(NSClickGestureRecognizer(target: self, action: #selector(mouseClick(_:))))
let region = MKCoordinateRegionMakeWithDistance(knownLocations["smt"]!.coordinate, 500, 500)
let adjRegion = mapView.regionThatFits(region)
mapView.setRegion(adjRegion, animated: true)
}
func mouseClick(_ recognizer: NSClickGestureRecognizer){
let point = recognizer.location(in: mapView)
let coordinate = mapView.convert(point, toCoordinateFrom: mapView)
delegate?.mapViewController(controller: self, mapView: mapView, didClickAtLocation: coordinate)
}
func drawStartAnnotation(location: CLLocationCoordinate2D){
if startAnnotation == nil {
startAnnotation = Annotation(title: "Starting location", coordinate: CLLocationCoordinate2D())
mapView.addAnnotation(startAnnotation!)
}
startAnnotation?.coordinate = location
mapView.removeOverlays(mapView.overlays)
}
func drawCurrentLocation(location: CLLocationCoordinate2D){
if currentAnnotation == nil {
currentAnnotation = Annotation(title: "Current location", coordinate: CLLocationCoordinate2D())
mapView.addAnnotation(self.currentAnnotation!)
}
currentAnnotation?.coordinate = location
}
func drawEndLocation(location: CLLocationCoordinate2D){
if endAnnotation == nil {
endAnnotation = Annotation(title: "End location", coordinate: CLLocationCoordinate2D())
mapView.addAnnotation(endAnnotation!)
}
endAnnotation?.coordinate = location
mapView.removeOverlays(mapView.overlays)
}
func drawRoute(locations: [CLLocationCoordinate2D]?) {
guard var locations = locations else {
return print("can't draw nil route 🤔")
}
if let routePolyline = routePolyline {
mapView.remove(routePolyline)
}
routePolyline = MKPolyline(coordinates: &locations, count: locations.count)
mapView.add((routePolyline!), level: MKOverlayLevel.aboveRoads)
}
func clearMap(){
if let route = routePolyline {
mapView.remove(route)
}
if let start = startAnnotation {
mapView.removeAnnotation(start)
}
if let current = currentAnnotation {
mapView.removeAnnotation(current)
}
if let end = endAnnotation {
mapView.removeAnnotation(end)
}
}
}
//MARK: MKMapViewDelegate
extension MapViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = NSColor.purple()
renderer.lineWidth = 4.0
return renderer
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let pinView = MKPinAnnotationView()
if annotation.isEqual(startAnnotation) {
pinView.pinTintColor = .green()
} else if annotation.isEqual(currentAnnotation) {
pinView.pinTintColor = .purple()
} else if annotation.isEqual(endAnnotation) {
pinView.pinTintColor = .red()
}
pinView.centerOffset = CGPoint(x: 8, y: -16)
return pinView
}
}
//MARK: help class for annotation
class Annotation: NSObject, MKAnnotation {
var title: String?
dynamic var coordinate: CLLocationCoordinate2D
var location: CLLocation {
return CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
}
init(title: String, coordinate: CLLocationCoordinate2D){
self.title = title
self.coordinate = coordinate
}
}
| unlicense | 43f1f343df103fa8e04005e22e9007d8 | 29.455782 | 128 | 0.723029 | 4.78312 | false | false | false | false |
jondwillis/ReactiveReSwift-Router | ReactiveReSwiftRouter/NavigationReducer.swift | 1 | 1565 | //
// NavigationReducer.swift
// Meet
//
// Created by Benjamin Encz on 11/11/15.
// Copyright © 2015 DigiTales. All rights reserved.
//
import ReactiveReSwift
/**
The Navigation Reducer handles the state slice concerned with storing the current navigation
information. Note, that this reducer is **not** a *top-level* reducer, you need to use it within
another reducer and pass in the relevant state slice. Take a look at the specs to see an
example set up.
*/
public struct NavigationReducer {
public static func handleAction(_ action: Action, state: NavigationState?) -> NavigationState {
let state = state ?? NavigationState()
switch action {
case let action as SetRouteAction:
return setRoute(state, setRouteAction: action)
case let action as SetRouteSpecificData:
return setRouteSpecificData(state, route: action.route, data: action.data)
default:
break
}
return state
}
static func setRoute(_ state: NavigationState, setRouteAction: SetRouteAction) -> NavigationState {
var state = state
state.route = setRouteAction.route
state.changeRouteAnimated = setRouteAction.animated
return state
}
static func setRouteSpecificData(
_ state: NavigationState,
route: Route,
data: Any) -> NavigationState{
let routeHash = RouteHash(route: route)
var state = state
state.routeSpecificState[routeHash] = data
return state
}
}
| mit | c2c61328641c72f1aa1063f91ca269b5 | 26.928571 | 103 | 0.659847 | 4.812308 | false | false | false | false |
kickstarter/ios-oss | Library/ViewModels/MostPopularSearchProjectCellViewModel.swift | 1 | 4485 | import KsApi
import Prelude
import ReactiveSwift
import UIKit
public protocol MostPopularSearchProjectCellViewModelInputs {
func configureWith(project: Project)
}
public protocol MostPopularSearchProjectCellViewModelOutputs {
/// Emits text for metadata label.
var metadataText: Signal<String, Never> { get }
/// Emits the attributed string for the percent funded label.
var percentFundedText: Signal<NSAttributedString, Never> { get }
/// Emits the project's funding progress amount to be displayed.
var progress: Signal<Float, Never> { get }
/// Emits a color for the progress bar.
var progressBarColor: Signal<UIColor, Never> { get }
/// Emits the project's photo URL to be displayed.
var projectImageUrl: Signal<URL?, Never> { get }
/// Emits project name to be displayed.
var projectName: Signal<NSAttributedString, Never> { get }
}
public protocol MostPopularSearchProjectCellViewModelType {
var inputs: MostPopularSearchProjectCellViewModelInputs { get }
var outputs: MostPopularSearchProjectCellViewModelOutputs { get }
}
public final class MostPopularSearchProjectCellViewModel: MostPopularSearchProjectCellViewModelType,
MostPopularSearchProjectCellViewModelInputs, MostPopularSearchProjectCellViewModelOutputs {
public init() {
let project = self.projectProperty.signal.skipNil()
self.projectImageUrl = project.map { URL(string: $0.photo.full) }
self.projectName = project.map(titleString(for:))
self.progress = project.map { $0.stats.fundingProgress }
self.progressBarColor = project.map(progressBarColorForProject)
self.percentFundedText = project.map(percentFundedString(for:))
self.metadataText = project.map(metadataString(for:))
}
fileprivate let projectProperty = MutableProperty<Project?>(nil)
public func configureWith(project: Project) {
self.projectProperty.value = project
}
public let metadataText: Signal<String, Never>
public let percentFundedText: Signal<NSAttributedString, Never>
public let progress: Signal<Float, Never>
public let progressBarColor: Signal<UIColor, Never>
public let projectImageUrl: Signal<URL?, Never>
public let projectName: Signal<NSAttributedString, Never>
public var inputs: MostPopularSearchProjectCellViewModelInputs { return self }
public var outputs: MostPopularSearchProjectCellViewModelOutputs { return self }
}
private func metadataString(for project: Project) -> String {
switch project.state {
case .live:
let duration = Format.duration(secondsInUTC: project.dates.deadline, abbreviate: true, useToGo: false)
return "\(duration.time) \(duration.unit)"
default:
return stateString(for: project)
}
}
private func percentFundedString(for project: Project) -> NSAttributedString {
let percentage = Format.percentage(project.stats.percentFunded)
switch project.state {
case .live, .successful:
return NSAttributedString(string: percentage, attributes: [
NSAttributedString.Key.font: UIFont.ksr_caption1().bolded,
NSAttributedString.Key.foregroundColor: UIColor.ksr_create_700
])
default:
return NSAttributedString(string: percentage, attributes: [
NSAttributedString.Key.font: UIFont.ksr_caption1().bolded,
NSAttributedString.Key.foregroundColor: UIColor.ksr_support_400
])
}
}
private func progressBarColorForProject(_ project: Project) -> UIColor {
switch project.state {
case .live, .successful:
return .ksr_create_700
default:
return .ksr_support_400
}
}
private func titleString(for project: Project) -> NSAttributedString {
switch project.state {
case .live, .successful:
return NSAttributedString(string: project.name, attributes: [
NSAttributedString.Key.font: UIFont.ksr_caption1(size: 13),
NSAttributedString.Key.foregroundColor: UIColor.ksr_support_700
])
default:
return NSAttributedString(string: project.name, attributes: [
NSAttributedString.Key.font: UIFont.ksr_caption1(size: 13),
NSAttributedString.Key.foregroundColor: UIColor.ksr_support_400
])
}
}
private func stateString(for project: Project) -> String {
switch project.state {
case .canceled:
return Strings.profile_projects_status_canceled()
case .successful:
return Strings.profile_projects_status_successful()
case .suspended:
return Strings.profile_projects_status_suspended()
case .failed:
return Strings.profile_projects_status_unsuccessful()
default:
return ""
}
}
| apache-2.0 | 737be28a630dffbe8aecc5d0d08d3afe | 32.721805 | 106 | 0.756076 | 4.379883 | false | false | false | false |
fhchina/SnapKit | Source/Constraint.swift | 2 | 19921 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// 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(iOS)
import UIKit
#else
import AppKit
#endif
/**
Used to expose API's for a Constraint
*/
public class Constraint {
public func install() -> [LayoutConstraint] { fatalError("Must be implemented by Concrete subclass.") }
public func uninstall() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func activate() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func deactivate() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: Float) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: Double) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: CGFloat) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: Int) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: UInt) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: CGPoint) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: CGSize) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: EdgeInsets) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateInsets(amount: EdgeInsets) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriority(priority: Float) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriority(priority: Double) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriority(priority: CGFloat) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriority(priority: UInt) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriority(priority: Int) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriorityRequired() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") }
internal var makerFile: String = "Unknown"
internal var makerLine: UInt = 0
}
/**
Used internally to implement a ConcreteConstraint
*/
internal class ConcreteConstraint: Constraint {
internal override func updateOffset(amount: Float) -> Void {
self.constant = amount
}
internal override func updateOffset(amount: Double) -> Void {
self.updateOffset(Float(amount))
}
internal override func updateOffset(amount: CGFloat) -> Void {
self.updateOffset(Float(amount))
}
internal override func updateOffset(amount: Int) -> Void {
self.updateOffset(Float(amount))
}
internal override func updateOffset(amount: UInt) -> Void {
self.updateOffset(Float(amount))
}
internal override func updateOffset(amount: CGPoint) -> Void {
self.constant = amount
}
internal override func updateOffset(amount: CGSize) -> Void {
self.constant = amount
}
internal override func updateOffset(amount: EdgeInsets) -> Void {
self.constant = amount
}
internal override func updateInsets(amount: EdgeInsets) -> Void {
self.constant = EdgeInsets(top: amount.top, left: amount.left, bottom: -amount.bottom, right: -amount.right)
}
internal override func updatePriority(priority: Float) -> Void {
self.priority = priority
}
internal override func updatePriority(priority: Double) -> Void {
self.updatePriority(Float(priority))
}
internal override func updatePriority(priority: CGFloat) -> Void {
self.updatePriority(Float(priority))
}
internal override func updatePriority(priority: UInt) -> Void {
self.updatePriority(Float(priority))
}
internal override func updatePriority(priority: Int) -> Void {
self.updatePriority(Float(priority))
}
internal override func updatePriorityRequired() -> Void {
self.updatePriority(Float(1000.0))
}
internal override func updatePriorityHigh() -> Void {
self.updatePriority(Float(750.0))
}
internal override func updatePriorityMedium() -> Void {
#if os(iOS)
self.updatePriority(Float(500.0))
#else
self.updatePriority(Float(501.0))
#endif
}
internal override func updatePriorityLow() -> Void {
self.updatePriority(Float(250.0))
}
internal override func install() -> [LayoutConstraint] {
return self.installOnView(updateExisting: false, file: self.makerFile, line: self.makerLine)
}
internal override func uninstall() -> Void {
self.uninstallFromView()
}
internal override func activate() -> Void {
guard #available(iOS 8.0, OSX 10.10, *), self.installInfo != nil else {
self.install()
return
}
let layoutConstraints = self.installInfo!.layoutConstraints.allObjects as! [LayoutConstraint]
if layoutConstraints.count > 0 {
NSLayoutConstraint.activateConstraints(layoutConstraints)
}
}
internal override func deactivate() -> Void {
guard #available(iOS 8.0, OSX 10.10, *), self.installInfo != nil else {
self.install()
return
}
let layoutConstraints = self.installInfo!.layoutConstraints.allObjects as! [LayoutConstraint]
if layoutConstraints.count > 0 {
NSLayoutConstraint.deactivateConstraints(layoutConstraints)
}
}
private let fromItem: ConstraintItem
private let toItem: ConstraintItem
private let relation: ConstraintRelation
private let multiplier: Float
private var constant: Any {
didSet {
if let installInfo = self.installInfo {
for layoutConstraint in installInfo.layoutConstraints.allObjects as! [LayoutConstraint] {
let attribute = (layoutConstraint.secondAttribute == .NotAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute
layoutConstraint.constant = attribute.snp_constantForValue(self.constant)
}
}
}
}
private var priority: Float {
didSet {
if let installInfo = self.installInfo {
for layoutConstraint in installInfo.layoutConstraints.allObjects as! [LayoutConstraint] {
layoutConstraint.priority = self.priority
}
}
}
}
private var installInfo: ConcreteConstraintInstallInfo? = nil
internal init(fromItem: ConstraintItem, toItem: ConstraintItem, relation: ConstraintRelation, constant: Any, multiplier: Float, priority: Float) {
self.fromItem = fromItem
self.toItem = toItem
self.relation = relation
self.constant = constant
self.multiplier = multiplier
self.priority = priority
}
internal func installOnView(updateExisting updateExisting: Bool = false, file: String? = nil, line: UInt? = nil) -> [LayoutConstraint] {
var installOnView: View? = nil
if self.toItem.view != nil {
installOnView = closestCommonSuperviewFromView(self.fromItem.view, toView: self.toItem.view)
if installOnView == nil {
NSException(name: "Cannot Install Constraint", reason: "No common superview between views (@\(self.makerFile)#\(self.makerLine))", userInfo: nil).raise()
return []
}
} else {
if self.fromItem.attributes.isSubsetOf(ConstraintAttributes.Width.union(.Height)) {
installOnView = self.fromItem.view
} else {
installOnView = self.fromItem.view?.superview
if installOnView == nil {
NSException(name: "Cannot Install Constraint", reason: "Missing superview (@\(self.makerFile)#\(self.makerLine))", userInfo: nil).raise()
return []
}
}
}
if let installedOnView = self.installInfo?.view {
if installedOnView != installOnView {
NSException(name: "Cannot Install Constraint", reason: "Already installed on different view. (@\(self.makerFile)#\(self.makerLine))", userInfo: nil).raise()
return []
}
return self.installInfo?.layoutConstraints.allObjects as? [LayoutConstraint] ?? []
}
var newLayoutConstraints = [LayoutConstraint]()
let layoutFromAttributes = self.fromItem.attributes.layoutAttributes
let layoutToAttributes = self.toItem.attributes.layoutAttributes
// get layout from
let layoutFrom: View? = self.fromItem.view
// get layout relation
let layoutRelation: NSLayoutRelation = self.relation.layoutRelation
for layoutFromAttribute in layoutFromAttributes {
// get layout to attribute
let layoutToAttribute = (layoutToAttributes.count > 0) ? layoutToAttributes[0] : layoutFromAttribute
// get layout constant
let layoutConstant: CGFloat = layoutToAttribute.snp_constantForValue(self.constant)
// get layout to
var layoutTo: View? = self.toItem.view
if layoutTo == nil && layoutToAttribute != .Width && layoutToAttribute != .Height {
layoutTo = installOnView
}
// create layout constraint
let layoutConstraint = LayoutConstraint(
item: layoutFrom!,
attribute: layoutFromAttribute,
relatedBy: layoutRelation,
toItem: layoutTo,
attribute: layoutToAttribute,
multiplier: CGFloat(self.multiplier),
constant: layoutConstant)
// set priority
layoutConstraint.priority = self.priority
// set constraint
layoutConstraint.snp_constraint = self
newLayoutConstraints.append(layoutConstraint)
}
// special logic for updating
if updateExisting {
// get existing constraints for this view
let existingLayoutConstraints = layoutFrom!.snp_installedLayoutConstraints.reverse()
// array that will contain only new layout constraints to keep
var newLayoutConstraintsToKeep = [LayoutConstraint]()
// begin looping
for layoutConstraint in newLayoutConstraints {
// layout constraint that should be updated
var updateLayoutConstraint: LayoutConstraint? = nil
// loop through existing and check for match
for existingLayoutConstraint in existingLayoutConstraints {
if existingLayoutConstraint == layoutConstraint {
updateLayoutConstraint = existingLayoutConstraint
break
}
}
// if we have existing one lets just update the constant
if updateLayoutConstraint != nil {
updateLayoutConstraint!.constant = layoutConstraint.constant
}
// otherwise add this layout constraint to new keep list
else {
newLayoutConstraintsToKeep.append(layoutConstraint)
}
}
// set constraints to only new ones
newLayoutConstraints = newLayoutConstraintsToKeep
}
// add constraints
installOnView!.addConstraints(newLayoutConstraints)
// set install info
self.installInfo = ConcreteConstraintInstallInfo(view: installOnView, layoutConstraints: NSHashTable.weakObjectsHashTable())
// store which layout constraints are installed for this constraint
for layoutConstraint in newLayoutConstraints {
self.installInfo!.layoutConstraints.addObject(layoutConstraint)
}
// store the layout constraints against the layout from view
layoutFrom!.snp_installedLayoutConstraints += newLayoutConstraints
// return the new constraints
return newLayoutConstraints
}
internal func uninstallFromView() {
if let installInfo = self.installInfo,
let installedLayoutConstraints = installInfo.layoutConstraints.allObjects as? [LayoutConstraint] {
if installedLayoutConstraints.count > 0 {
if let installedOnView = installInfo.view {
// remove the constraints from the UIView's storage
installedOnView.removeConstraints(installedLayoutConstraints)
}
// remove the constraints from the from item view
if let fromView = self.fromItem.view {
fromView.snp_installedLayoutConstraints = fromView.snp_installedLayoutConstraints.filter {
return !installedLayoutConstraints.contains($0)
}
}
}
}
self.installInfo = nil
}
}
private struct ConcreteConstraintInstallInfo {
weak var view: View? = nil
let layoutConstraints: NSHashTable
}
private extension NSLayoutAttribute {
private func snp_constantForValue(value: Any?) -> CGFloat {
// Float
if let float = value as? Float {
return CGFloat(float)
}
// Double
else if let double = value as? Double {
return CGFloat(double)
}
// UInt
else if let int = value as? Int {
return CGFloat(int)
}
// Int
else if let uint = value as? UInt {
return CGFloat(uint)
}
// CGFloat
else if let float = value as? CGFloat {
return float
}
// CGSize
else if let size = value as? CGSize {
if self == .Width {
return size.width
} else if self == .Height {
return size.height
}
}
// CGPoint
else if let point = value as? CGPoint {
#if os(iOS)
switch self {
case .Left, .CenterX, .LeftMargin, .CenterXWithinMargins: return point.x
case .Top, .CenterY, .TopMargin, .CenterYWithinMargins, .Baseline, .FirstBaseline: return point.y
case .Right, .RightMargin: return point.x
case .Bottom, .BottomMargin: return point.y
case .Leading, .LeadingMargin: return point.x
case .Trailing, .TrailingMargin: return point.x
case .Width, .Height, .NotAnAttribute: return CGFloat(0)
}
#else
switch self {
case .Left, .CenterX: return point.x
case .Top, .CenterY, .Baseline: return point.y
case .Right: return point.x
case .Bottom: return point.y
case .Leading: return point.x
case .Trailing: return point.x
case .Width, .Height, .NotAnAttribute: return CGFloat(0)
case .FirstBaseline: return point.y
}
#endif
}
// EdgeInsets
else if let insets = value as? EdgeInsets {
#if os(iOS)
switch self {
case .Left, .CenterX, .LeftMargin, .CenterXWithinMargins: return insets.left
case .Top, .CenterY, .TopMargin, .CenterYWithinMargins, .Baseline, .FirstBaseline: return insets.top
case .Right, .RightMargin: return insets.right
case .Bottom, .BottomMargin: return insets.bottom
case .Leading, .LeadingMargin: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.left : -insets.right
case .Trailing, .TrailingMargin: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.right : -insets.left
case .Width, .Height, .NotAnAttribute: return CGFloat(0)
}
#else
switch self {
case .Left, .CenterX: return insets.left
case .Top, .CenterY, .Baseline: return insets.top
case .Right: return insets.right
case .Bottom: return insets.bottom
case .Leading: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.left : -insets.right
case .Trailing: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.right : -insets.left
case .Width, .Height, .NotAnAttribute: return CGFloat(0)
case .FirstBaseline: return insets.bottom
}
#endif
}
return CGFloat(0);
}
}
private func closestCommonSuperviewFromView(fromView: View?, toView: View?) -> View? {
var views = Set<View>()
var fromView = fromView
var toView = toView
repeat {
if let view = toView {
if views.contains(view) {
return view
}
views.insert(view)
toView = view.superview
}
if let view = fromView {
if views.contains(view) {
return view
}
views.insert(view)
fromView = view.superview
}
} while (fromView != nil || toView != nil)
return nil
}
private func ==(left: ConcreteConstraint, right: ConcreteConstraint) -> Bool {
return (left.fromItem == right.fromItem &&
left.toItem == right.toItem &&
left.relation == right.relation &&
left.multiplier == right.multiplier &&
left.priority == right.priority)
}
| mit | e582dac78175e862c81485d698f66393 | 41.47548 | 172 | 0.61006 | 5.438438 | false | false | false | false |
stephentyrone/swift | test/SILGen/keypaths_objc.swift | 6 | 3691 | // RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/keypaths_objc.h %s | %FileCheck %s
// RUN: %target-swift-emit-ir(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/keypaths_objc.h %s
// REQUIRES: objc_interop
import Foundation
struct NonObjC {
var x: Int
var y: NSObject
}
class Foo: NSObject {
@objc var int: Int { fatalError() }
@objc var bar: Bar { fatalError() }
var nonobjc: NonObjC { fatalError() }
@objc(thisIsADifferentName) var differentName: Bar { fatalError() }
@objc subscript(x: Int) -> Foo { return self }
@objc subscript(x: Bar) -> Foo { return self }
@objc dynamic var dyn: String { fatalError() }
}
class Bar: NSObject {
@objc var foo: Foo { fatalError() }
}
// CHECK-LABEL: sil hidden [ossa] @$s13keypaths_objc0B8KeypathsyyF
func objcKeypaths() {
// CHECK: keypath $WritableKeyPath<NonObjC, Int>, (root
_ = \NonObjC.x
// CHECK: keypath $WritableKeyPath<NonObjC, NSObject>, (root
_ = \NonObjC.y
// CHECK: keypath $KeyPath<Foo, Int>, (objc "int"
_ = \Foo.int
// CHECK: keypath $KeyPath<Foo, Bar>, (objc "bar"
_ = \Foo.bar
// CHECK: keypath $KeyPath<Foo, Foo>, (objc "bar.foo"
_ = \Foo.bar.foo
// CHECK: keypath $KeyPath<Foo, Bar>, (objc "bar.foo.bar"
_ = \Foo.bar.foo.bar
// CHECK: keypath $KeyPath<Foo, NonObjC>, (root
_ = \Foo.nonobjc
// CHECK: keypath $KeyPath<Foo, NSObject>, (root
_ = \Foo.bar.foo.nonobjc.y
// CHECK: keypath $KeyPath<Foo, Bar>, (objc "thisIsADifferentName"
_ = \Foo.differentName
}
// CHECK-LABEL: sil hidden [ossa] @$s13keypaths_objc0B18KeypathIdentifiersyyF
func objcKeypathIdentifiers() {
// CHECK: keypath $KeyPath<ObjCFoo, String>, (objc "objcProp"; {{.*}} id #ObjCFoo.objcProp!getter.foreign
_ = \ObjCFoo.objcProp
// CHECK: keypath $KeyPath<Foo, String>, (objc "dyn"; {{.*}} id #Foo.dyn!getter.foreign
_ = \Foo.dyn
// CHECK: keypath $KeyPath<Foo, Int>, (objc "int"; {{.*}} id #Foo.int!getter :
_ = \Foo.int
}
struct X {}
extension NSObject {
var x: X { return X() }
@objc var objc: Int { return 0 }
@objc dynamic var dynamic: Int { return 0 }
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}nonobjcExtensionOfObjCClass
func nonobjcExtensionOfObjCClass() {
// Should be treated as a statically-dispatch property
// CHECK: keypath $KeyPath<NSObject, X>, ({{.*}} id @
_ = \NSObject.x
// CHECK: keypath $KeyPath<NSObject, Int>, ({{.*}} id #NSObject.objc!getter.foreign
_ = \NSObject.objc
// CHECK: keypath $KeyPath<NSObject, Int>, ({{.*}} id #NSObject.dynamic!getter.foreign
_ = \NSObject.dynamic
}
@objc protocol ObjCProto {
var objcRequirement: Int { get set }
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}ProtocolRequirement
func objcProtocolRequirement<T: ObjCProto>(_: T) {
// CHECK: keypath {{.*}} id #ObjCProto.objcRequirement!getter.foreign
_ = \T.objcRequirement
// CHECK: keypath {{.*}} id #ObjCProto.objcRequirement!getter.foreign
_ = \ObjCProto.objcRequirement
}
// CHECK-LABEL: sil hidden [ossa] @{{.*}}externalObjCProperty
func externalObjCProperty() {
// Pure ObjC-dispatched properties do not have external descriptors.
// CHECK: keypath $KeyPath<NSObject, String>,
// CHECK-NOT: external #NSObject.description
_ = \NSObject.description
}
func sharedCProperty() {
// CHECK: keypath $WritableKeyPath<c_union, some_struct>
// CHECK-NOT: external #c_union.some_field
let dataKeyPath: WritableKeyPath<c_union, some_struct>? = \c_union.some_field
}
class OverrideFrameworkObjCProperty: A {
override var counter: Int32 {
get { return 0 }
set { }
}
}
func overrideFrameworkObjCProperty() {
let _ = \OverrideFrameworkObjCProperty.counter
}
| apache-2.0 | bcd6ee26100dbe3f61ad2eac72c9103a | 31.095652 | 129 | 0.671634 | 3.427112 | false | false | false | false |
TCA-Team/iOS | TUM Campus App/DetailPersonWithTitleCell.swift | 1 | 1551 | //
// DetailPersonWithTitleCell.swift
// TUM Campus App
//
// This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS
// Copyright (c) 2018 TCA
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
class DetailPersonWithTitleCell: CardTableViewCell {
var binding: ImageViewBinding?
override func setElement(_ element: DataElement) {
if let user = element as? UserData {
binding = user.avatar.bind(to: avatarView, default: #imageLiteral(resourceName: "avatar"))
nameLabel.text = user.name
titleLabel.text = user.title
}
}
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel! {
didSet {
titleLabel.text = nil
}
}
@IBOutlet weak var avatarView: UIImageView! {
didSet {
avatarView.clipsToBounds = true
avatarView.layer.cornerRadius = avatarView.frame.width / 2
}
}
}
| gpl-3.0 | 0d3e35632c6d4e95404bd4bf104419f9 | 30.653061 | 102 | 0.665377 | 4.356742 | false | false | false | false |
gu704823/ofo | ofo/roundbutton.swift | 1 | 950 | //
// roundbutton.swift
// ofo
//
// Created by swift on 2017/5/17.
// Copyright © 2017年 swift. All rights reserved.
//
import UIKit
class roundbutton: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//设置button的圆角
self.clipsToBounds = true
self.layer.cornerRadius = self.frame.size.width/2
//buttond的边距大小和颜色
self.layer.borderWidth = 4
self.layer.borderColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.7).cgColor
}
//buttonde 转动
func onrotation(){
let animation = CABasicAnimation(keyPath: "transform.rotation")
animation.fromValue = 0
animation.toValue = Double.pi * 2
animation.duration = 20
animation.repeatCount = MAXFLOAT
self.layer.add(animation, forKey: "heihei")
}
func pause(){
self.layer.removeAllAnimations()
}
}
| mit | 6d65d001d29062d816c574023b081e98 | 25.2 | 93 | 0.622683 | 3.83682 | false | false | false | false |
shu223/iOS-9-Sampler | iOS9Sampler/SampleViewControllers/AudioUnitComponentManagerViewController.swift | 2 | 4880 | //
// AudioUnitComponentManagerViewController.swift
// iOS9Sampler
//
// Created by Shuichi Tsutsumi on 2015/06/21.
// Copyright © 2015 Shuichi Tsutsumi. All rights reserved.
//
import UIKit
import AVFoundation
import CoreAudioKit
extension AudioComponent {
static func anyEffectDescription() -> AudioComponentDescription {
var anyEffectDescription = AudioComponentDescription()
anyEffectDescription.componentType = kAudioUnitType_Effect
anyEffectDescription.componentSubType = 0
anyEffectDescription.componentManufacturer = 0
anyEffectDescription.componentFlags = 0
anyEffectDescription.componentFlagsMask = 0
return anyEffectDescription
}
}
class AudioUnitComponentManagerViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak fileprivate var tableView: UITableView!
fileprivate var viewBtn: UIBarButtonItem!
fileprivate var items = [AVAudioUnitComponent]()
fileprivate var engine = AudioEngine()
override func viewDidLoad() {
super.viewDidLoad()
viewBtn = UIBarButtonItem(
title: "ShowAUVC",
style: UIBarButtonItem.Style.plain,
target: self, action: #selector(AudioUnitComponentManagerViewController.viewBtnTapped(_:)))
navigationItem.setRightBarButton(viewBtn, animated: false)
viewBtn.isEnabled = false
// extract available effects
items = AVAudioUnitComponentManager.shared()
.components(matching: AudioComponent.anyEffectDescription())
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
engine.start()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
engine.stop()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// =========================================================================
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
if indexPath.row == 0 {
cell.textLabel!.text = "No Effect"
cell.detailTextLabel!.text = ""
} else {
let auComponent = items[indexPath.row - 1]
cell.textLabel!.text = auComponent.name
cell.detailTextLabel!.text = auComponent.manufacturerName
}
return cell
}
// =========================================================================
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let auComponent: AVAudioUnitComponent?
if indexPath.row == 0 {
// no effect
auComponent = nil
} else {
auComponent = items[indexPath.row - 1]
}
engine.selectEffectWithComponentDescription(auComponent?.audioComponentDescription) { [unowned self] () -> Void in
self.engine.requestViewControllerWithCompletionHandler { viewController in
self.viewBtn.isEnabled = viewController != nil ? true : false
}
}
tableView.deselectRow(at: indexPath, animated: true)
}
// =========================================================================
// MARK: - Actions
@objc func viewBtnTapped(_ sender: AnyObject) {
// close
if children.count > 0 {
let childViewController = children.first!
childViewController.willMove(toParent: nil)
childViewController.view.removeFromSuperview()
childViewController.removeFromParent()
viewBtn.title = "ShowAUVC"
return
}
// open
engine.requestViewControllerWithCompletionHandler { [weak self] viewController in
guard let strongSelf = self else { return }
guard let viewController = viewController, let view = viewController.view else { return }
strongSelf.addChild(viewController)
let parentRect = strongSelf.view.bounds
view.frame = CGRect(
x: 0,
y: parentRect.size.height / 2,
width: parentRect.size.width,
height: parentRect.size.height / 2)
strongSelf.view.addSubview(view)
viewController.didMove(toParent: self)
strongSelf.viewBtn.title = "CloseAUVC"
}
}
}
| mit | 7b6d7850ba53045ca629d1d5cfad72a1 | 32.190476 | 122 | 0.601148 | 5.85012 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKit/helpers/TKParserHelper.swift | 1 | 1757 | //
// TKParserHelper.swift
// TripKit
//
// Created by Adrian Schoenig on 27/9/16.
//
//
import Foundation
import CoreLocation
import MapKit
enum TKParserHelper {
static func parseDate(_ object: Any?) -> Date? {
if let string = object as? String {
if let interval = TimeInterval(string), interval > 1000000000, interval < 2000000000 {
return Date(timeIntervalSince1970: interval)
}
return try? Date(iso8601: string)
} else if let interval = object as? TimeInterval, interval > 0 {
return Date(timeIntervalSince1970: interval)
} else {
return nil
}
}
static func requestString(for coordinate: CLLocationCoordinate2D) -> String {
return String(format: "(%f,%f)", coordinate.latitude, coordinate.longitude)
}
static func requestString(for annotation: MKAnnotation) -> String {
let named = TKNamedCoordinate.namedCoordinate(for: annotation)
guard annotation.coordinate.isValid, let address = named.address else {
return requestString(for: annotation.coordinate)
}
return String(format: "(%f,%f)\"%@\"", named.coordinate.latitude, named.coordinate.longitude, address)
}
/// Inverse of `TKParserHelper.requestString(for:)`
static func coordinate(forRequest string: String) -> CLLocationCoordinate2D? {
let pruned = string
.replacingOccurrences(of: "(", with: "")
.replacingOccurrences(of: ")", with: "")
let numbers = pruned.components(separatedBy: ",")
if numbers.count != 2 {
return nil
}
guard
let lat = CLLocationDegrees(numbers[0]),
let lng = CLLocationDegrees(numbers[1])
else { return nil }
return CLLocationCoordinate2D(latitude: lat, longitude: lng)
}
}
| apache-2.0 | 8ae9057475f36864513530d4366a0ee8 | 28.283333 | 106 | 0.666477 | 4.381546 | false | false | false | false |
tahseen0amin/TZSegmentedControl | Example/TZSegmentedControl/ViewController.swift | 1 | 6308 | //
// ViewController.swift
// TZSegmentedControl
//
// Created by [email protected] on 05/05/2017.
// Copyright (c) 2017 [email protected]. All rights reserved.
//
import UIKit
import TZSegmentedControl
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let titleCont = TZSegmentedControl(sectionTitles: ["SEGMENT","ALIGNMENT", "FEATURE" ])
titleCont.frame = CGRect(x: 0, y: 50, width: self.view.frame.width, height: 50)
titleCont.indicatorWidthPercent = 0.8
let whitishColor = UIColor(white: 0.75, alpha: 1.0)
titleCont.backgroundColor = UIColor.white
titleCont.borderType = .none
titleCont.borderColor = whitishColor
titleCont.borderWidth = 0.5
titleCont.segmentAlignment = .center
titleCont.segmentWidthStyle = .dynamic
titleCont.verticalDividerEnabled = false
titleCont.verticalDividerWidth = 0.5
titleCont.verticalDividerColor = whitishColor
titleCont.selectionStyle = .fullWidth
titleCont.selectionIndicatorLocation = .down
titleCont.selectionIndicatorColor = UIColor.blue
titleCont.selectionIndicatorHeight = 2.0
titleCont.edgeInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
titleCont.selectedTitleTextAttributes = [NSAttributedString.Key.foregroundColor :UIColor.blue]
titleCont.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.darkGray,
NSAttributedString.Key.font:UIFont(name: "Tahoma", size: 10.0) ?? UIFont.systemFont(ofSize: 13)]
self.view.addSubview(titleCont)
let imageCon = TZSegmentedControl(sectionImages: [UIImage(named: "1")!,
UIImage(named: "2")!,
UIImage(named: "3")!,
UIImage(named: "4")!],
selectedImages: [UIImage(named: "1-selected")!,
UIImage(named: "2-selected")!,
UIImage(named: "3-selected")!,
UIImage(named: "4-selected")!])
imageCon.frame = CGRect(x: 0, y: 120, width: self.view.frame.width, height: 50)
imageCon.verticalDividerEnabled = false
imageCon.indicatorWidthPercent = 0.8
imageCon.selectionIndicatorColor = UIColor.gray
imageCon.backgroundColor = UIColor.white
self.view.addSubview(imageCon)
let imageCon2 = TZSegmentedControl(sectionTitles: ["TRENDING","EDITOR'S PICKS", "FOR YOU", "VIDEOS", "LANGUAGE"], sectionImages: [UIImage(named: "1")!,
UIImage(named: "2")!,
UIImage(named: "3")!,
UIImage(named: "4")!,
UIImage(named: "3")!],
selectedImages: [UIImage(named: "1-selected")!,
UIImage(named: "2-selected")!,
UIImage(named: "3-selected")!,
UIImage(named: "4-selected")!,
UIImage(named: "3-selected")!])
imageCon2.frame = CGRect(x: 0, y: 180, width: self.view.frame.width, height: 90)
imageCon2.verticalDividerEnabled = false
imageCon2.indicatorWidthPercent = 0.8
imageCon2.selectionIndicatorColor = UIColor.gray
imageCon2.backgroundColor = UIColor.white
imageCon2.selectedTitleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.blue]
imageCon2.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.darkGray,
NSAttributedString.Key.font:UIFont(name: "Tahoma", size: 10.0) ?? UIFont.systemFont(ofSize: 13)]
imageCon2.indicatorWidthPercent = 0.0
self.view.addSubview(imageCon2)
let titleCont1 = TZSegmentedControl(sectionTitles: ["TRENDING","EDITOR'S PICKS", "FOR YOU", "VIDEOS", "LANGUAGE" ])
titleCont1.frame = CGRect(x: 0, y: 280, width: self.view.frame.width, height: 50)
titleCont1.indicatorWidthPercent = 0.0
titleCont1.backgroundColor = UIColor.white
titleCont1.borderColor = whitishColor
titleCont1.borderWidth = 0.5
titleCont1.segmentWidthStyle = .dynamic
titleCont1.verticalDividerEnabled = true
titleCont1.verticalDividerWidth = 0.5
titleCont1.verticalDividerColor = whitishColor
titleCont1.selectionStyle = .box
titleCont1.selectionIndicatorLocation = .down
titleCont1.selectionIndicatorColor = UIColor.green
titleCont1.selectionIndicatorHeight = 2.0
titleCont1.borderType = .top
titleCont1.edgeInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
titleCont1.selectedTitleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
titleCont1.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.darkGray,
NSAttributedString.Key.font:UIFont(name: "Tahoma", size: 10.0) ?? UIFont.systemFont(ofSize: 13)]
self.view.addSubview(titleCont1)
self.view.backgroundColor = UIColor(red: 0.3, green: 0.4, blue: 0.7, alpha: 0.7)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.init(uptimeNanoseconds: 30000)) {
self.segControlFromNib!.sectionTitles = ["TRENDING","EDITOR'S PICKS", "FOR YOU", "VIDEOS", "LANGUAGE" ]
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet var segControlFromNib : TZSegmentedControl!
}
| mit | 88b11aec9e85ad569d5c91b9113f1f78 | 54.333333 | 159 | 0.583228 | 4.916602 | false | false | false | false |
subinspathilettu/SJRefresh | SJRefresh/Classes/RefreshViewAnimation.swift | 1 | 2588 | //
// RefreshViewAnimationDelegate.swift
// Pods
//
// Created by Subins Jose on 03/11/16.
// Copyright © 2016 Subins Jose. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
// the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
// AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
extension RefreshView {
func startAnimation(_ callback: AnimationCompleteCallback?) {
animationCompletion = callback
let animation = CAKeyframeAnimation()
animation.keyPath = "contents"
animation.values = getAnimationImages(percentage)
animation.repeatCount = isDefinite ? 0.0 : Float.infinity
animation.duration = animationDuration
animation.delegate = self
animationView.layer.add(animation, forKey: "contents")
var index = getAnimationEndIndex(percentage)
index = index > 0 ? index - 1 : index
animationView.image = animationView.animationImages?[index]
animationPercentage = percentage
}
func stopAnimating() {
animationPercentage = 0.0
percentage = 0.0
animationView.isHidden = true
animationView.stopAnimating()
pullImageView.isHidden = false
guard let scrollView = superview as? UIScrollView else {
return
}
scrollView.bounces = self.scrollViewBounces
UIView.animate(withDuration: animationDuration,
animations: {
scrollView.contentInset = self.scrollViewInsets
self.pullImageView.transform = CGAffineTransform.identity
}, completion: { _ in
self.state = .pulling
})
}
}
extension RefreshView: CAAnimationDelegate {
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
animationCompletion?(animationPercentage)
}
}
| mit | 4ff50efeefbd46c9aa19b2bfb00bb9d2 | 35.43662 | 99 | 0.751063 | 4.429795 | false | false | false | false |
QuarkX/Quark | Sources/Quark/HTTP/Message/Body.swift | 1 | 2594 | public enum Body {
case buffer(Data)
case reader(InputStream)
case writer((OutputStream) throws -> Void)
}
extension Body {
public var isBuffer: Bool {
switch self {
case .buffer: return true
default: return false
}
}
public var isReader: Bool {
switch self {
case .reader: return true
default: return false
}
}
public var isWriter: Bool {
switch self {
case .writer: return true
default: return false
}
}
}
extension Body {
public mutating func becomeBuffer(deadline: Double = .never) throws -> Data {
switch self {
case .buffer(let data):
return data
case .reader(let reader):
let data = Drain(stream: reader, deadline: deadline).data
self = .buffer(data)
return data
case .writer(let writer):
let drain = Drain()
try writer(drain)
let data = drain.data
self = .buffer(data)
return data
}
}
public mutating func becomeReader() throws -> InputStream {
switch self {
case .reader(let reader):
return reader
case .buffer(let buffer):
let stream = Drain(buffer: buffer)
self = .reader(stream)
return stream
case .writer(let writer):
let stream = Drain()
try writer(stream)
self = .reader(stream)
return stream
}
}
public mutating func becomeWriter(deadline: Double = .never) throws -> ((OutputStream) throws -> Void) {
switch self {
case .buffer(let data):
let closure: ((OutputStream) throws -> Void) = { writer in
try writer.write(data, deadline: deadline)
try writer.flush()
}
self = .writer(closure)
return closure
case .reader(let reader):
let closure: ((OutputStream) throws -> Void) = { writer in
let data = Drain(stream: reader, deadline: deadline).data
try writer.write(data, deadline: deadline)
try writer.flush()
}
self = .writer(closure)
return closure
case .writer(let writer):
return writer
}
}
}
extension Body : Equatable {}
public func == (lhs: Body, rhs: Body) -> Bool {
switch (lhs, rhs) {
case let (.buffer(l), .buffer(r)) where l == r: return true
default: return false
}
}
| mit | 19cac427c3d7431b2b810dc77b9285e4 | 26.305263 | 108 | 0.528913 | 4.640429 | false | false | false | false |
apple/swift-corelibs-foundation | Tests/Foundation/Tests/TestDateFormatter.swift | 1 | 27934 | // 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
//
class TestDateFormatter: XCTestCase {
let DEFAULT_LOCALE = "en_US_POSIX"
let DEFAULT_TIMEZONE = "GMT"
static var allTests : [(String, (TestDateFormatter) -> () throws -> Void)] {
return [
("test_BasicConstruction", test_BasicConstruction),
("test_dateStyleShort", test_dateStyleShort),
//("test_dateStyleMedium", test_dateStyleMedium),
("test_dateStyleLong", test_dateStyleLong),
("test_dateStyleFull", test_dateStyleFull),
("test_customDateFormat", test_customDateFormat),
("test_setLocalizedDateFormatFromTemplate", test_setLocalizedDateFormatFromTemplate),
("test_dateFormatString", test_dateFormatString),
("test_setLocaleToNil", test_setLocaleToNil),
("test_setTimeZoneToNil", test_setTimeZoneToNil),
("test_setTimeZone", test_setTimeZone),
("test_expectedTimeZone", test_expectedTimeZone),
("test_dateFrom", test_dateFrom),
("test_dateParseAndFormatWithJapaneseCalendar", test_dateParseAndFormatWithJapaneseCalendar),
("test_orderOfPropertySetters", test_orderOfPropertySetters),
("test_copy_sr14108", test_copy_sr14108),
]
}
func test_BasicConstruction() {
let symbolDictionaryOne = ["eraSymbols" : ["BC", "AD"],
"monthSymbols" : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
"shortMonthSymbols" : ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
"weekdaySymbols" : ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
"shortWeekdaySymbols" : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
"longEraSymbols" : ["Before Christ", "Anno Domini"],
"veryShortMonthSymbols" : ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"],
"standaloneMonthSymbols" : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
"shortStandaloneMonthSymbols" : ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
"veryShortStandaloneMonthSymbols" : ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]]
let symbolDictionaryTwo = ["veryShortWeekdaySymbols" : ["S", "M", "T", "W", "T", "F", "S"],
"standaloneWeekdaySymbols" : ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
"shortStandaloneWeekdaySymbols" : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
"veryShortStandaloneWeekdaySymbols" : ["S", "M", "T", "W", "T", "F", "S"],
"quarterSymbols" : ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"],
"shortQuarterSymbols" : ["Q1", "Q2", "Q3", "Q4"],
"standaloneQuarterSymbols" : ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"],
"shortStandaloneQuarterSymbols" : ["Q1", "Q2", "Q3", "Q4"]]
let f = DateFormatter()
XCTAssertNotNil(f.timeZone)
XCTAssertNotNil(f.locale)
f.timeZone = TimeZone(identifier: DEFAULT_TIMEZONE)
f.locale = Locale(identifier: DEFAULT_LOCALE)
// Assert default values are set properly
XCTAssertFalse(f.generatesCalendarDates)
XCTAssertNotNil(f.calendar)
XCTAssertFalse(f.isLenient)
XCTAssertEqual(f.twoDigitStartDate!, Date(timeIntervalSince1970: -631152000))
XCTAssertNil(f.defaultDate)
XCTAssertEqual(f.eraSymbols, symbolDictionaryOne["eraSymbols"]!)
XCTAssertEqual(f.monthSymbols, symbolDictionaryOne["monthSymbols"]!)
XCTAssertEqual(f.shortMonthSymbols, symbolDictionaryOne["shortMonthSymbols"]!)
XCTAssertEqual(f.weekdaySymbols, symbolDictionaryOne["weekdaySymbols"]!)
XCTAssertEqual(f.shortWeekdaySymbols, symbolDictionaryOne["shortWeekdaySymbols"]!)
XCTAssertEqual(f.amSymbol, "AM")
XCTAssertEqual(f.pmSymbol, "PM")
XCTAssertEqual(f.longEraSymbols, symbolDictionaryOne["longEraSymbols"]!)
XCTAssertEqual(f.veryShortMonthSymbols, symbolDictionaryOne["veryShortMonthSymbols"]!)
XCTAssertEqual(f.standaloneMonthSymbols, symbolDictionaryOne["standaloneMonthSymbols"]!)
XCTAssertEqual(f.shortStandaloneMonthSymbols, symbolDictionaryOne["shortStandaloneMonthSymbols"]!)
XCTAssertEqual(f.veryShortStandaloneMonthSymbols, symbolDictionaryOne["veryShortStandaloneMonthSymbols"]!)
XCTAssertEqual(f.veryShortWeekdaySymbols, symbolDictionaryTwo["veryShortWeekdaySymbols"]!)
XCTAssertEqual(f.standaloneWeekdaySymbols, symbolDictionaryTwo["standaloneWeekdaySymbols"]!)
XCTAssertEqual(f.shortStandaloneWeekdaySymbols, symbolDictionaryTwo["shortStandaloneWeekdaySymbols"]!)
XCTAssertEqual(f.veryShortStandaloneWeekdaySymbols, symbolDictionaryTwo["veryShortStandaloneWeekdaySymbols"]!)
XCTAssertEqual(f.quarterSymbols, symbolDictionaryTwo["quarterSymbols"]!)
XCTAssertEqual(f.shortQuarterSymbols, symbolDictionaryTwo["shortQuarterSymbols"]!)
XCTAssertEqual(f.standaloneQuarterSymbols, symbolDictionaryTwo["standaloneQuarterSymbols"]!)
XCTAssertEqual(f.shortStandaloneQuarterSymbols, symbolDictionaryTwo["shortStandaloneQuarterSymbols"]!)
XCTAssertEqual(f.gregorianStartDate, Date(timeIntervalSince1970: -12219292800))
XCTAssertFalse(f.doesRelativeDateFormatting)
}
// ShortStyle
// locale stringFromDate example
// ------ -------------- --------
// en_US M/d/yy h:mm a 12/25/15 12:00 AM
func test_dateStyleShort() {
let timestamps = [
-31536000 : "1/1/69, 12:00 AM" , 0.0 : "1/1/70, 12:00 AM", 31536000 : "1/1/71, 12:00 AM",
2145916800 : "1/1/38, 12:00 AM", 1456272000 : "2/24/16, 12:00 AM", 1456358399 : "2/24/16, 11:59 PM",
1452574638 : "1/12/16, 4:57 AM", 1455685038 : "2/17/16, 4:57 AM", 1458622638 : "3/22/16, 4:57 AM",
1459745838 : "4/4/16, 4:57 AM", 1462597038 : "5/7/16, 4:57 AM", 1465534638 : "6/10/16, 4:57 AM",
1469854638 : "7/30/16, 4:57 AM", 1470718638 : "8/9/16, 4:57 AM", 1473915438 : "9/15/16, 4:57 AM",
1477285038 : "10/24/16, 4:57 AM", 1478062638 : "11/2/16, 4:57 AM", 1482641838 : "12/25/16, 4:57 AM"
]
let f = DateFormatter()
f.dateStyle = .short
f.timeStyle = .short
// ensure tests give consistent results by setting specific timeZone and locale
f.timeZone = TimeZone(identifier: DEFAULT_TIMEZONE)
f.locale = Locale(identifier: DEFAULT_LOCALE)
for (timestamp, stringResult) in timestamps {
let testDate = Date(timeIntervalSince1970: timestamp)
let sf = f.string(from: testDate)
XCTAssertEqual(sf, stringResult)
}
}
// MediumStyle
// locale stringFromDate example
// ------ -------------- ------------
// en_US MMM d, y, h:mm:ss a Dec 25, 2015, 12:00:00 AM
func test_dateStyleMedium() {
let timestamps = [
-31536000 : "Jan 1, 1969, 12:00:00 AM" , 0.0 : "Jan 1, 1970, 12:00:00 AM", 31536000 : "Jan 1, 1971, 12:00:00 AM",
2145916800 : "Jan 1, 2038, 12:00:00 AM", 1456272000 : "Feb 24, 2016, 12:00:00 AM", 1456358399 : "Feb 24, 2016, 11:59:59 PM",
1452574638 : "Jan 12, 2016, 4:57:18 AM", 1455685038 : "Feb 17, 2016, 4:57:18 AM", 1458622638 : "Mar 22, 2016, 4:57:18 AM",
1459745838 : "Apr 4, 2016, 4:57:18 AM", 1462597038 : "May 7, 2016, 4:57:18 AM", 1465534638 : "Jun 10, 2016, 4:57:18 AM",
1469854638 : "Jul 30, 2016, 4:57:18 AM", 1470718638 : "Aug 9, 2016, 4:57:18 AM", 1473915438 : "Sep 15, 2016, 4:57:18 AM",
1477285038 : "Oct 24, 2016, 4:57:18 AM", 1478062638 : "Nov 2, 2016, 4:57:18 AM", 1482641838 : "Dec 25, 2016, 4:57:18 AM"
]
let f = DateFormatter()
f.dateStyle = .medium
f.timeStyle = .medium
f.timeZone = TimeZone(identifier: DEFAULT_TIMEZONE)
f.locale = Locale(identifier: DEFAULT_LOCALE)
for (timestamp, stringResult) in timestamps {
let testDate = Date(timeIntervalSince1970: timestamp)
let sf = f.string(from: testDate)
XCTAssertEqual(sf, stringResult)
}
}
// LongStyle
// locale stringFromDate example
// ------ -------------- -----------------
// en_US MMMM d, y 'at' h:mm:ss a zzz December 25, 2015 at 12:00:00 AM GMT
func test_dateStyleLong() {
let timestamps = [
-31536000 : "January 1, 1969 at 12:00:00 AM GMT" , 0.0 : "January 1, 1970 at 12:00:00 AM GMT", 31536000 : "January 1, 1971 at 12:00:00 AM GMT",
2145916800 : "January 1, 2038 at 12:00:00 AM GMT", 1456272000 : "February 24, 2016 at 12:00:00 AM GMT", 1456358399 : "February 24, 2016 at 11:59:59 PM GMT",
1452574638 : "January 12, 2016 at 4:57:18 AM GMT", 1455685038 : "February 17, 2016 at 4:57:18 AM GMT", 1458622638 : "March 22, 2016 at 4:57:18 AM GMT",
1459745838 : "April 4, 2016 at 4:57:18 AM GMT", 1462597038 : "May 7, 2016 at 4:57:18 AM GMT", 1465534638 : "June 10, 2016 at 4:57:18 AM GMT",
1469854638 : "July 30, 2016 at 4:57:18 AM GMT", 1470718638 : "August 9, 2016 at 4:57:18 AM GMT", 1473915438 : "September 15, 2016 at 4:57:18 AM GMT",
1477285038 : "October 24, 2016 at 4:57:18 AM GMT", 1478062638 : "November 2, 2016 at 4:57:18 AM GMT", 1482641838 : "December 25, 2016 at 4:57:18 AM GMT"
]
let f = DateFormatter()
f.dateStyle = .long
f.timeStyle = .long
f.timeZone = TimeZone(identifier: DEFAULT_TIMEZONE)
f.locale = Locale(identifier: DEFAULT_LOCALE)
for (timestamp, stringResult) in timestamps {
let testDate = Date(timeIntervalSince1970: timestamp)
let sf = f.string(from: testDate)
XCTAssertEqual(sf, stringResult)
}
}
// FullStyle
// locale stringFromDate example
// ------ -------------- -------------------------
// en_US EEEE, MMMM d, y 'at' h:mm:ss a zzzz Friday, December 25, 2015 at 12:00:00 AM Greenwich Mean Time
func test_dateStyleFull() {
#if os(macOS) // timestyle .full is currently broken on Linux, the timezone should be 'Greenwich Mean Time' not 'GMT'
let timestamps: [TimeInterval:String] = [
// Negative time offsets are still buggy on macOS
-31536000 : "Wednesday, January 1, 1969 at 12:00:00 AM GMT", 0.0 : "Thursday, January 1, 1970 at 12:00:00 AM Greenwich Mean Time",
31536000 : "Friday, January 1, 1971 at 12:00:00 AM Greenwich Mean Time", 2145916800 : "Friday, January 1, 2038 at 12:00:00 AM Greenwich Mean Time",
1456272000 : "Wednesday, February 24, 2016 at 12:00:00 AM Greenwich Mean Time", 1456358399 : "Wednesday, February 24, 2016 at 11:59:59 PM Greenwich Mean Time",
1452574638 : "Tuesday, January 12, 2016 at 4:57:18 AM Greenwich Mean Time", 1455685038 : "Wednesday, February 17, 2016 at 4:57:18 AM Greenwich Mean Time",
1458622638 : "Tuesday, March 22, 2016 at 4:57:18 AM Greenwich Mean Time", 1459745838 : "Monday, April 4, 2016 at 4:57:18 AM Greenwich Mean Time",
1462597038 : "Saturday, May 7, 2016 at 4:57:18 AM Greenwich Mean Time", 1465534638 : "Friday, June 10, 2016 at 4:57:18 AM Greenwich Mean Time",
1469854638 : "Saturday, July 30, 2016 at 4:57:18 AM Greenwich Mean Time", 1470718638 : "Tuesday, August 9, 2016 at 4:57:18 AM Greenwich Mean Time",
1473915438 : "Thursday, September 15, 2016 at 4:57:18 AM Greenwich Mean Time", 1477285038 : "Monday, October 24, 2016 at 4:57:18 AM Greenwich Mean Time",
1478062638 : "Wednesday, November 2, 2016 at 4:57:18 AM Greenwich Mean Time", 1482641838 : "Sunday, December 25, 2016 at 4:57:18 AM Greenwich Mean Time"
]
let f = DateFormatter()
f.dateStyle = .full
f.timeStyle = .full
f.timeZone = TimeZone(identifier: DEFAULT_TIMEZONE)
f.locale = Locale(identifier: DEFAULT_LOCALE)
for (timestamp, stringResult) in timestamps {
let testDate = Date(timeIntervalSince1970: timestamp)
let sf = f.string(from: testDate)
XCTAssertEqual(sf, stringResult)
}
#endif
}
// Custom Style
// locale stringFromDate example
// ------ -------------- -------------------------
// en_US EEEE, MMMM d, y 'at' hh:mm:ss a zzzz Friday, December 25, 2015 at 12:00:00 AM Greenwich Mean Time
func test_customDateFormat() {
let timestamps = [
// Negative time offsets are still buggy on macOS
-31536000 : "Wednesday, January 1, 1969 at 12:00:00 AM GMT", 0.0 : "Thursday, January 1, 1970 at 12:00:00 AM Greenwich Mean Time",
31536000 : "Friday, January 1, 1971 at 12:00:00 AM Greenwich Mean Time", 2145916800 : "Friday, January 1, 2038 at 12:00:00 AM Greenwich Mean Time",
1456272000 : "Wednesday, February 24, 2016 at 12:00:00 AM Greenwich Mean Time", 1456358399 : "Wednesday, February 24, 2016 at 11:59:59 PM Greenwich Mean Time",
1452574638 : "Tuesday, January 12, 2016 at 04:57:18 AM Greenwich Mean Time", 1455685038 : "Wednesday, February 17, 2016 at 04:57:18 AM Greenwich Mean Time",
1458622638 : "Tuesday, March 22, 2016 at 04:57:18 AM Greenwich Mean Time", 1459745838 : "Monday, April 4, 2016 at 04:57:18 AM Greenwich Mean Time",
1462597038 : "Saturday, May 7, 2016 at 04:57:18 AM Greenwich Mean Time", 1465534638 : "Friday, June 10, 2016 at 04:57:18 AM Greenwich Mean Time",
1469854638 : "Saturday, July 30, 2016 at 04:57:18 AM Greenwich Mean Time", 1470718638 : "Tuesday, August 9, 2016 at 04:57:18 AM Greenwich Mean Time",
1473915438 : "Thursday, September 15, 2016 at 04:57:18 AM Greenwich Mean Time", 1477285038 : "Monday, October 24, 2016 at 04:57:18 AM Greenwich Mean Time",
1478062638 : "Wednesday, November 2, 2016 at 04:57:18 AM Greenwich Mean Time", 1482641838 : "Sunday, December 25, 2016 at 04:57:18 AM Greenwich Mean Time"
]
let f = DateFormatter()
f.timeZone = TimeZone(identifier: DEFAULT_TIMEZONE)
f.locale = Locale(identifier: DEFAULT_LOCALE)
f.dateFormat = "EEEE, MMMM d, y 'at' hh:mm:ss a zzzz"
for (timestamp, stringResult) in timestamps {
let testDate = Date(timeIntervalSince1970: timestamp)
let sf = f.string(from: testDate)
XCTAssertEqual(sf, stringResult)
}
let quarterTimestamps: [Double : String] = [
1451679712 : "1", 1459542112 : "2", 1467404512 : "3", 1475353312 : "4"
]
f.dateFormat = "Q"
for (timestamp, stringResult) in quarterTimestamps {
let testDate = Date(timeIntervalSince1970: timestamp)
let sf = f.string(from: testDate)
XCTAssertEqual(sf, stringResult)
}
// Check .dateFormat resets when style changes
let testDate = Date(timeIntervalSince1970: 1457738454)
// Fails on High Sierra
//f.dateStyle = .medium
//f.timeStyle = .medium
//XCTAssertEqual(f.string(from: testDate), "Mar 11, 2016, 11:20:54 PM")
//XCTAssertEqual(f.dateFormat, "MMM d, y, h:mm:ss a")
f.dateFormat = "dd-MM-yyyy"
XCTAssertEqual(f.string(from: testDate), "11-03-2016")
}
func test_setLocalizedDateFormatFromTemplate() {
let locale = Locale(identifier: DEFAULT_LOCALE)
let template = "EEEE MMMM d y hhmmss a zzzz"
let f = DateFormatter()
f.locale = locale
f.setLocalizedDateFormatFromTemplate(template)
let dateFormat = DateFormatter.dateFormat(fromTemplate: template, options: 0, locale: locale)
XCTAssertEqual(f.dateFormat, dateFormat)
}
func test_dateFormatString() {
let f = DateFormatter()
f.locale = Locale(identifier: DEFAULT_LOCALE)
f.timeZone = TimeZone(abbreviation: DEFAULT_TIMEZONE)
// .medium cases fail for the date part on Linux and so have been commented out.
let formats: [String: (DateFormatter.Style, DateFormatter.Style)] = [
"": (.none, .none),
"h:mm a": (.none, .short),
"h:mm:ss a": (.none, .medium),
"h:mm:ss a z": (.none, .long),
"h:mm:ss a zzzz": (.none, .full),
"M/d/yy": (.short, .none),
"M/d/yy, h:mm a": (.short, .short),
"M/d/yy, h:mm:ss a": (.short, .medium),
"M/d/yy, h:mm:ss a z": (.short, .long),
"M/d/yy, h:mm:ss a zzzz": (.short, .full),
"MMM d, y": (.medium, .none),
//"MMM d, y 'at' h:mm a": (.medium, .short),
//"MMM d, y 'at' h:mm:ss a": (.medium, .medium),
//"MMM d, y 'at' h:mm:ss a z": (.medium, .long),
//"MMM d, y 'at' h:mm:ss a zzzz": (.medium, .full),
"MMMM d, y": (.long, .none),
"MMMM d, y 'at' h:mm a": (.long, .short),
"MMMM d, y 'at' h:mm:ss a": (.long, .medium),
"MMMM d, y 'at' h:mm:ss a z": (.long, .long),
"MMMM d, y 'at' h:mm:ss a zzzz": (.long, .full),
"EEEE, MMMM d, y": (.full, .none),
"EEEE, MMMM d, y 'at' h:mm a": (.full, .short),
"EEEE, MMMM d, y 'at' h:mm:ss a": (.full, .medium),
"EEEE, MMMM d, y 'at' h:mm:ss a z": (.full, .long),
"EEEE, MMMM d, y 'at' h:mm:ss a zzzz": (.full, .full),
]
for (dateFormat, styles) in formats {
f.dateStyle = styles.0
f.timeStyle = styles.1
XCTAssertEqual(f.dateFormat, dateFormat)
}
}
func test_setLocaleToNil() {
let f = DateFormatter()
// Locale should be the current one by default
XCTAssertEqual(f.locale, .current)
f.locale = nil
// Locale should go back to current.
XCTAssertEqual(f.locale, .current)
// A nil locale should not crash a subsequent operation
let result: String? = f.string(from: Date())
XCTAssertNotNil(result)
}
func test_setTimeZoneToNil() {
let f = DateFormatter()
// Time zone should be the system one by default.
XCTAssertEqual(f.timeZone, NSTimeZone.system)
f.timeZone = nil
// Time zone should go back to the system one.
XCTAssertEqual(f.timeZone, NSTimeZone.system)
}
func test_setTimeZone() {
// Test two different time zones. Should ensure that if one
// happens to be TimeZone.current, we still get a valid test.
let newYork = TimeZone(identifier: "America/New_York")!
let losAngeles = TimeZone(identifier: "America/Los_Angeles")!
XCTAssertNotEqual(newYork, losAngeles)
// Case 1: New York
let f = DateFormatter()
f.timeZone = newYork
XCTAssertEqual(f.timeZone, newYork)
// Case 2: Los Angeles
f.timeZone = losAngeles
XCTAssertEqual(f.timeZone, losAngeles)
}
func test_expectedTimeZone() {
let newYork = TimeZone(identifier: "America/New_York")!
let losAngeles = TimeZone(identifier: "America/Los_Angeles")!
XCTAssertNotEqual(newYork, losAngeles)
let now = Date()
let f = DateFormatter()
f.dateFormat = "z"
f.locale = Locale(identifier: "en_US_POSIX")
// Case 1: TimeZone.current
// This case can catch some issues that cause TimeZone.current to be
// treated like GMT, but it doesn't work if TimeZone.current is GMT.
// If you do find an issue like this caused by this first case,
// it would benefit from a more specific test that fails when
// TimeZone.current is GMT as well.
// (ex. TestTimeZone.test_systemTimeZoneName)
f.timeZone = TimeZone.current
XCTAssertEqual(f.string(from: now), TimeZone.current.abbreviation())
// Case 2: New York
f.timeZone = newYork
XCTAssertEqual(f.string(from: now), newYork.abbreviation())
// Case 3: Los Angeles
f.timeZone = losAngeles
XCTAssertEqual(f.string(from: now), losAngeles.abbreviation())
}
func test_dateFrom() throws {
let formatter = DateFormatter()
formatter.timeZone = TimeZone(identifier: "UTC")
formatter.dateFormat = "yyyy-MM-dd"
XCTAssertNil(formatter.date(from: "2018-03-09T10:25:16+01:00"))
let d1 = try XCTUnwrap(formatter.date(from: "2018-03-09"))
XCTAssertEqual(d1.description, "2018-03-09 00:00:00 +0000")
// DateFormatter should allow any kind of whitespace before and after parsed content
let whitespaces = " \t\u{00a0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200a}\u{202f}\u{205f}\u{3000}"
let d1Prefix = try XCTUnwrap(formatter.date(from: "\(whitespaces)2018-03-09"))
XCTAssertEqual(d1.description, d1Prefix.description)
let d1PrefixSuffix = try XCTUnwrap(formatter.date(from: "\(whitespaces)2018-03-09\(whitespaces)"))
XCTAssertEqual(d1.description, d1PrefixSuffix.description)
let d1Suffix = try XCTUnwrap(formatter.date(from: "2018-03-09\(whitespaces)"))
XCTAssertEqual(d1.description, d1Suffix.description)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
XCTAssertNil(formatter.date(from: "2018-03-09"))
let d2 = try XCTUnwrap(formatter.date(from: "2018-03-09T10:25:16+01:00"))
XCTAssertEqual(d2.description, "2018-03-09 09:25:16 +0000")
}
func test_dateParseAndFormatWithJapaneseCalendar() throws {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "ja_JP")
formatter.calendar = Calendar(identifier: .japanese)
formatter.dateFormat = "Gy年M月d日 HH:mm"
formatter.timeZone = TimeZone(abbreviation: "JST")
do {
// Parse test
let parsed = formatter.date(from: "平成31年4月30日 23:10")
XCTAssertEqual(parsed?.timeIntervalSince1970, 1556633400) // April 30, 2019, 11:10 PM (JST)
// Format test
let dateString = formatter.string(from: Date(timeIntervalSince1970: 1556633400)) // April 30, 2019, 11:10 PM (JST)
XCTAssertEqual(dateString, "平成31年4月30日 23:10")
}
// Test for new Japanese era (starting from May 1, 2019)
do {
// Parse test
let parsed = formatter.date(from: "令和1年5月1日 23:10")
XCTAssertEqual(parsed?.timeIntervalSince1970, 1556719800) // May 1st, 2019, 11:10 PM (JST)
// Test for 元年(Gannen) representation of 1st year
let parsedAlt = formatter.date(from: "令和元年5月1日 23:10")
XCTAssertEqual(parsedAlt?.timeIntervalSince1970, 1556719800) // May 1st, 2019, 11:10 PM (JST)
// Format test
let dateString = formatter.string(from: Date(timeIntervalSince1970: 1556719800)) // May 1st, 2019, 11:10 PM (JST)
XCTAssertEqual(dateString, "令和元年5月1日 23:10")
}
}
func test_orderOfPropertySetters() throws {
// This produces a .count factorial number of arrays
func combinations<T>(of a: [T]) -> [[T]] {
precondition(!a.isEmpty)
if a.count == 1 { return [a] }
if a.count == 2 { return [ [a[0], a[1]], [ a[1], a[0]] ] }
var result: [[T]] = []
for idx in a.startIndex..<a.endIndex {
let x = a[idx]
var b: [T] = a
b.remove(at: idx)
for var c in combinations(of: b) {
c.append(x)
result.append(c)
}
}
return result
}
let formatter = DateFormatter()
formatter.timeZone = TimeZone(identifier: "CET")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date = try XCTUnwrap(formatter.date(from: "2019-05-05T12:52:10"))
let applySettings: [(String, (DateFormatter) -> Void)] =
[(".timeZone", {
$0.timeZone = TimeZone(identifier: "Europe/Oslo")
}),
(".calendar", {
$0.calendar = Calendar(identifier: .gregorian)
}),
(".locale", {
$0.locale = Locale(identifier: "nb")
}),
(".dateStyle", {
$0.dateStyle = .medium
}),
(".timeStyle", {
$0.timeStyle = .medium
})
]
// Test all of the combinations of setting the properties produces the same output
let expected = "5. mai 2019, 12:52:10"
for settings in combinations(of: applySettings) {
let f = DateFormatter()
settings.forEach { $0.1(f) }
XCTAssertEqual(f.dateFormat, "d. MMM y, HH:mm:ss")
let formattedString = f.string(from: date)
if formattedString != expected {
let applied = settings.map { $0.0 }.joined(separator: ",")
XCTFail("\(formattedString) != \(expected) using settings applied in order \(applied)")
}
}
}
// Confirm that https://bugs.swift.org/browse/SR-14108 is fixed.
func test_copy_sr14108() throws {
let date = Date(timeIntervalSinceReferenceDate: 0)
let original = DateFormatter()
original.timeZone = TimeZone(identifier: DEFAULT_TIMEZONE)
original.locale = Locale(identifier: DEFAULT_LOCALE)
original.dateFormat = "yyyy-MM-dd HH:mm:ss z"
XCTAssertEqual(original.string(from: date), "2001-01-01 00:00:00 GMT")
let copied = try XCTUnwrap(original.copy() as? DateFormatter)
XCTAssertEqual(original.timeZone, copied.timeZone)
XCTAssertEqual(original.locale, copied.locale)
XCTAssertEqual(copied.string(from: date), "2001-01-01 00:00:00 GMT")
copied.timeZone = TimeZone(abbreviation: "JST")
copied.locale = Locale(identifier: "ja_JP")
copied.dateFormat = "yyyy/MM/dd hh:mm:ssxxxxx"
XCTAssertNotEqual(original.timeZone, copied.timeZone)
XCTAssertNotEqual(original.locale, copied.locale)
XCTAssertEqual(original.string(from: date), "2001-01-01 00:00:00 GMT")
XCTAssertEqual(copied.string(from: date), "2001/01/01 09:00:00+09:00")
}
}
| apache-2.0 | d72c9b80c37f7a525a93ed9c34e3d4ea | 49.125899 | 178 | 0.586652 | 4.03796 | false | true | false | false |
jfosterdavis/Charles | Charles/DataViewController+GameSoundsAndFeedback.swift | 1 | 11083 | //
// DataViewController+GameSoundsAndFeedback.swift
// Charles
//
// Created by Jacob Foster Davis on 5/29/17.
// Copyright © 2017 Zero Mu, LLC. All rights reserved.
//
import Foundation
import AVFoundation
import UIKit
/******************************************************/
/*******************///MARK: Extension for non-character game sounds and other feedback to user
/******************************************************/
extension DataViewController {
enum ProgressSituation {
case increaseLevel
case decreaseLevel
case increaseProgress
case decreaseProgress
case wonGame
}
/******************************************************/
/*******************///MARK: Game Audio
/******************************************************/
func resetAudioEngineAndPlayer() {
//audioPlayer.stop()
audioEngine.stop()
audioPlayerNode.stop()
audioEngine.disconnectNodeOutput(audioPlayerNode)
audioEngine.disconnectNodeOutput(synesthesiaDistortion)
audioEngine.disconnectNodeOutput(synesthesiaReverb)
//audioEngine.reset()
}
func resetAudioEngineAndPlayerGameSounds() {
audioEngineGameSounds.stop()
audioPlayerNodeGameSounds.stop()
}
func speak(subphrase: Subphrase){
textUtterance = AVSpeechUtterance(string: subphrase.words)
textUtterance.rate = 0.3
//textUtterance.pitchMultiplier = toneToSpeak
//speak
synth.speak(textUtterance)
}
/******************************************************/
/*******************///MARK: Sounds
/******************************************************/
///plays appropriate game sound for the given situation
func playGameSound(forProgressSituation : ProgressSituation) {
var audioFilePath: String?
var gameSoundPitchModifier: Float
switch forProgressSituation {
case .increaseLevel:
audioFilePath = Bundle.main.path(forResource: "LevelUp", ofType: "m4a", inDirectory: "Audio/GameSounds")
gameSoundPitchModifier = 300
case .decreaseLevel:
audioFilePath = Bundle.main.path(forResource: "LevelDown", ofType: "m4a", inDirectory: "Audio/GameSounds")
gameSoundPitchModifier = -350
case .increaseProgress:
audioFilePath = Bundle.main.path(forResource: "ProgressUp", ofType: "m4a", inDirectory: "Audio/GameSounds")
gameSoundPitchModifier = 180
case .decreaseProgress:
audioFilePath = Bundle.main.path(forResource: "ProgressDown", ofType: "m4a", inDirectory: "Audio/GameSounds")
gameSoundPitchModifier = -300
case .wonGame:
audioFilePath = Bundle.main.path(forResource: "LevelUp", ofType: "m4a", inDirectory: "Audio/GameSounds")
gameSoundPitchModifier = 500
// default:
// audioFilePath = nil
}
if let audioFilePath = audioFilePath {
do{
let url = URL(fileURLWithPath: audioFilePath)
try audioPlayerGameSounds = AVAudioPlayer(contentsOf: url)
audioPlayerGameSounds.enableRate = true
resetAudioEngineAndPlayerGameSounds()
// try audioPlayer = AVAudioPlayer(contentsOf: url)
let audioFile = try AVAudioFile(forReading: url)
changePitchEffectGameSounds.pitch = gameSoundPitchModifier
audioPlayerNodeGameSounds.scheduleFile(audioFile, at: nil, completionHandler: nil)
try audioEngineGameSounds.start()
audioPlayerNodeGameSounds.play()
} catch {
print("Error when attempting to play audio file.")
}
} else {
print ("Could not play audio file. file not found")
}
}
///checks baselines and plays sounds if appropriate
func compareLevelAndProgressAndPlaySounds(given currentLevelAndProgress: (Level, Int)) {
let currentLevel = currentLevelAndProgress.0
//get all the stuff you need to determine if the player won
let userXP = calculateUserXP()
let userLevelAndProgress = Levels.getLevelAndProgress(from: userXP)
let userCurrentProgress = userLevelAndProgress.1
let didPlayerProgressToGetHere = didPlayer(magnitudeDirection: .increase, in: .progress, byAchieving: userCurrentProgress)
if isPlayerAtHighestLevelAndProgress() && didPlayerProgressToGetHere { //player has won so play the final sounds
playGameSound(forProgressSituation: .wonGame)
} else { //player did not win the game yet
//determine if the player just increased in level
let didProgressInLevel = didPlayer(magnitudeDirection: .increase, in: .level, byAchieving: currentLevel.level)
let didDecreaseInLevel = didPlayer(magnitudeDirection: .decrease, in: .level, byAchieving: currentLevel.level)
if didProgressInLevel {
//the user progressed in level, play appropriate sound
playGameSound(forProgressSituation: .increaseLevel)
} else if didDecreaseInLevel {
//the user decreased in level, play appropriate sound
playGameSound(forProgressSituation: .decreaseLevel)
} else { //didn't progress in level, check baseline progress
let currentProgress = currentLevelAndProgress.1
//determine if the player just increased in progress
let didProgressInProgress = didPlayer(magnitudeDirection: .increase, in: .progress, byAchieving: currentProgress)
let didDecreaseInProgress = didPlayer(magnitudeDirection: .decrease, in: .progress, byAchieving: currentProgress)
if didProgressInProgress {
playGameSound(forProgressSituation: .increaseProgress)
} else if didDecreaseInProgress {
playGameSound(forProgressSituation: .decreaseProgress)
}
//if none of the above triggered, there is no sound to play
}
}
}
/******************************************************/
/*******************///MARK: User Feedback
/******************************************************/
///flashes the amount of points the user just scored to the screen
func presentJustScoredFeedback(justScored: Int) {
//make invisible in case in the middle of a feedback
justScoredLabel.alpha = 0
var scoreModifier = "+"
var presentableScoreValue = justScored
//check if the score is negative to appropriate color
if justScored < 0 {
scoreModifier = "-"
justScoredLabel.textColor = UIColor.red
presentableScoreValue = presentableScoreValue * -1
} else {
justScoredLabel.textColor = feedbackColorMoss.textColor
}
justScoredLabel.text = "\(scoreModifier)\(String(describing: presentableScoreValue.formattedWithSeparator))"
self.justScoredLabel.isHidden = false
UIView.animate(withDuration: 0.2, animations: {
self.justScoredLabel.alpha = 1.0
}, completion: { (finished:Bool) in
//now fade away again
UIView.animate(withDuration: 2.7, animations: {
self.justScoredLabel.alpha = 0.0
}, completion: { (finished:Bool) in
//self.justScoredLabel.isHidden = true
})
})
}
///flashes the a message about the score the screen
func presentJustScoredMessageFeedback(message: String, isGoodMessage: Bool = true) {
//make invisible in case in the middle of a feedback
justScoredMessageLabel.alpha = 0
//color the message based on good or bad
if isGoodMessage {
justScoredMessageLabel.textColor = feedbackColorMoss.textColor
} else { //color if the message is bad!
justScoredMessageLabel.textColor = UIColor.red
}
justScoredMessageLabel.text = "\(message)"
self.justScoredMessageLabel.isHidden = false
UIView.animate(withDuration: 0.4,
delay: 0.0,
animations: {
self.justScoredMessageLabel.alpha = 1.0
}, completion: { (finished:Bool) in
//now fade away again
UIView.animate(withDuration: 2.0,
delay: 0.5,
animations: {
self.justScoredMessageLabel.alpha = 0.0
}, completion: { (finished:Bool) in
//self.justScoredLabel.isHidden = true
})
})
}
func presentTaxFeedback(taxAmount: Int) {
presentJustScoredFeedback(justScored: -1 * taxAmount)
let message = "Tax"
presentJustScoredMessageFeedback(message: message, isGoodMessage: false)
}
//sets the backgorund based on the level
func setBackground(from level:Level, animate: Bool = true) {
let userCurrentLevel = level
let levelProgress = Levels.getLevelPhaseAndProgress(level: userCurrentLevel)
let phase = levelProgress.0
let progress = levelProgress.1
var newAlpha: CGFloat = 1
switch phase {
case .training:
//during training, the background is always normal
//newAlpha = CGFloat(1 - progress)
newAlpha = 1
case .emergeFromDarkness:
//during this phase, the background starts as black and slowly fades to the background color
newAlpha = CGFloat(progress)
case .returnToDarkness:
//in this phase the background goes from normal color back to black
newAlpha = CGFloat(1 - progress)
case .returnToLight:
//fade from black to normal color
newAlpha = CGFloat(progress)
default:
newAlpha = 1
}
let newTopBackgroundAlpha = 1 - (0.35 * newAlpha + 0.65) //y=mx+b top half will only ever be half as dark as the other part
if animate {
backgroundView.fade(.inOrOut, resultAlpha: newAlpha, withDuration: 5)
topBackgroundView.fade(.inOrOut, resultAlpha: newTopBackgroundAlpha, withDuration: 5)
} else {
backgroundView.alpha = newAlpha
topBackgroundView.alpha = newTopBackgroundAlpha
}
}
}
| apache-2.0 | 8f913206e2fc5b6d914c3a6ea5f768cc | 38.297872 | 132 | 0.569753 | 5.292264 | false | false | false | false |
maximbilan/ios_crosswords_generator | crosswords_generator/Sources/CrosswordsGenerator.swift | 1 | 9596 | //
// CrosswordsGenerator.swift
// crosswords_generator
//
// Created by Maxim Bilan on 9/11/15.
// Copyright © 2015 Maxim Bilan. All rights reserved.
//
import UIKit
open class CrosswordsGenerator {
// MARK: - Additional types
public struct Word {
public var word = ""
public var column = 0
public var row = 0
public var direction: WordDirection = .vertical
}
public enum WordDirection {
case vertical
case horizontal
}
// MARK: - Public properties
open var columns: Int = 0
open var rows: Int = 0
open var maxLoops: Int = 2000
open var words: Array<String> = Array()
open var result: Array<Word> {
get {
return resultData
}
}
// MARK: - Public additional properties
open var fillAllWords = false
open var emptySymbol = "-"
open var debug = true
open var orientationOptimization = false
// MARK: - Logic properties
fileprivate var grid: Array2D<String>?
fileprivate var currentWords: Array<String> = Array()
fileprivate var resultData: Array<Word> = Array()
// MARK: - Initialization
public init() {
}
public init(columns: Int, rows: Int, maxLoops: Int = 2000, words: Array<String>) {
self.columns = columns
self.rows = rows
self.maxLoops = maxLoops
self.words = words
}
// MARK: - Crosswords generation
open func generate() {
self.grid = nil
self.grid = Array2D(columns: columns, rows: rows, defaultValue: emptySymbol)
currentWords.removeAll()
resultData.removeAll()
words.sort(by: {$0.lengthOfBytes(using: String.Encoding.utf8) > $1.lengthOfBytes(using: String.Encoding.utf8)})
if debug {
print("--- Words ---")
print(words)
}
for word in words {
if !currentWords.contains(word) {
_ = fitAndAdd(word)
}
}
if debug {
print("--- Result ---")
printGrid()
}
if fillAllWords {
var remainingWords = Array<String>()
for word in words {
if !currentWords.contains(word) {
remainingWords.append(word)
}
}
var moreLikely = Set<String>()
var lessLikely = Set<String>()
for word in remainingWords {
var hasSameLetters = false
for comparingWord in remainingWords {
if word != comparingWord {
let letters = CharacterSet(charactersIn: comparingWord)
let range = word.rangeOfCharacter(from: letters)
if let _ = range {
hasSameLetters = true
break
}
}
}
if hasSameLetters {
moreLikely.insert(word)
}
else {
lessLikely.insert(word)
}
}
remainingWords.removeAll()
remainingWords.append(contentsOf: moreLikely)
remainingWords.append(contentsOf: lessLikely)
for word in remainingWords {
if !fitAndAdd(word) {
fitInRandomPlace(word)
}
}
if debug {
print("--- Fill All Words ---")
printGrid()
}
}
}
fileprivate func suggestCoord(_ word: String) -> Array<(Int, Int, Int, Int, Int)> {
var coordlist = Array<(Int, Int, Int, Int, Int)>()
var glc = -1
for letter in word {
glc += 1
var rowc = 0
for row: Int in 0 ..< rows {
rowc += 1
var colc = 0
for column: Int in 0 ..< columns {
colc += 1
let cell = grid![column, row]
if String(letter) == cell {
if rowc - glc > 0 {
if ((rowc - glc) + word.lengthOfBytes(using: String.Encoding.utf8)) <= rows {
coordlist.append((colc, rowc - glc, 1, colc + (rowc - glc), 0))
}
}
if colc - glc > 0 {
if ((colc - glc) + word.lengthOfBytes(using: String.Encoding.utf8)) <= columns {
coordlist.append((colc - glc, rowc, 0, rowc + (colc - glc), 0))
}
}
}
}
}
}
let newCoordlist = sortCoordlist(coordlist, word: word)
return newCoordlist
}
fileprivate func sortCoordlist(_ coordlist: Array<(Int, Int, Int, Int, Int)>, word: String) -> Array<(Int, Int, Int, Int, Int)> {
var newCoordlist = Array<(Int, Int, Int, Int, Int)>()
for var coord in coordlist {
let column = coord.0
let row = coord.1
let direction = coord.2
coord.4 = checkFitScore(column, row: row, direction: direction, word: word)
if coord.4 > 0 {
newCoordlist.append(coord)
}
}
newCoordlist.shuffle()
newCoordlist.sort(by: {$0.4 > $1.4})
return newCoordlist
}
fileprivate func fitAndAdd(_ word: String) -> Bool {
var fit = false
var count = 0
var coordlist = suggestCoord(word)
while !fit && count < maxLoops {
if currentWords.count == 0 {
let direction = randomValue()
// +1 offset for the first word, so more likely intersections for short words
let column = 1 + 1
let row = 1 + 1
if checkFitScore(column, row: row, direction: direction, word: word) > 0 {
fit = true
setWord(column, row: row, direction: direction, word: word, force: true)
}
}
else {
if count >= 0 && count < coordlist.count {
let column = coordlist[count].0
let row = coordlist[count].1
let direction = coordlist[count].2
if coordlist[count].4 > 0 {
fit = true
setWord(column, row: row, direction: direction, word: word, force: true)
}
}
else {
return false
}
}
count += 1
}
return true
}
fileprivate func fitInRandomPlace(_ word: String) {
let value = randomValue()
let directions = [value, value == 0 ? 1 : 0]
var bestScore = 0
var bestColumn = 0
var bestRow = 0
var bestDirection = 0
for direction in directions {
for i: Int in 1 ..< rows - 1 {
for j: Int in 1 ..< columns - 1 {
if grid![j, i] == emptySymbol {
let c = j + 1
let r = i + 1
let score = checkFitScore(c, row: r, direction: direction, word: word)
if score > bestScore {
bestScore = score
bestColumn = c
bestRow = r
bestDirection = direction
}
}
}
}
}
if bestScore > 0 {
setWord(bestColumn, row: bestRow, direction: bestDirection, word: word, force: true)
}
}
fileprivate func checkFitScore(_ column: Int, row: Int, direction: Int, word: String) -> Int {
var c = column
var r = row
if c < 1 || r < 1 || c >= columns || r >= rows {
return 0
}
var count = 1
var score = 1
for letter in word {
let activeCell = getCell(c, row: r)
if activeCell == emptySymbol || activeCell == String(letter) {
if activeCell == String(letter) {
score += 1
}
if direction == 0 {
if activeCell != String(letter) {
if !checkIfCellClear(c, row: r - 1) {
return 0
}
if !checkIfCellClear(c, row: r + 1) {
return 0
}
}
if count == 1 {
if !checkIfCellClear(c - 1, row: r) {
return 0
}
}
if count == word.lengthOfBytes(using: String.Encoding.utf8) {
if !checkIfCellClear(c + 1, row: row) {
return 0
}
}
}
else {
if activeCell != String(letter) {
if !checkIfCellClear(c + 1, row: r) {
return 0
}
if !checkIfCellClear(c - 1, row: r) {
return 0
}
}
if count == 1 {
if !checkIfCellClear(c, row: r - 1) {
return 0
}
}
if count == word.lengthOfBytes(using: String.Encoding.utf8) {
if !checkIfCellClear(c, row: r + 1) {
return 0
}
}
}
if direction == 0 {
c += 1
}
else {
r += 1
}
if (c >= columns || r >= rows) {
return 0
}
count += 1
}
else {
return 0
}
}
return score
}
func setCell(_ column: Int, row: Int, value: String) {
grid![column - 1, row - 1] = value
}
func getCell(_ column: Int, row: Int) -> String{
return grid![column - 1, row - 1]
}
func checkIfCellClear(_ column: Int, row: Int) -> Bool {
if column > 0 && row > 0 && column < columns && row < rows {
return getCell(column, row: row) == emptySymbol ? true : false
}
else {
return true
}
}
fileprivate func setWord(_ column: Int, row: Int, direction: Int, word: String, force: Bool = false) {
if force {
let w = Word(word: word, column: column, row: row, direction: (direction == 0 ? .horizontal : .vertical))
resultData.append(w)
currentWords.append(word)
var c = column
var r = row
for letter in word {
setCell(c, row: r, value: String(letter))
if direction == 0 {
c += 1
}
else {
r += 1
}
}
}
}
// MARK: - Public info methods
open func maxColumn() -> Int {
var column = 0
for i in 0 ..< rows {
for j in 0 ..< columns {
if grid![j, i] != emptySymbol {
if j > column {
column = j
}
}
}
}
return column + 1
}
open func maxRow() -> Int {
var row = 0
for i in 0 ..< rows {
for j in 0 ..< columns {
if grid![j, i] != emptySymbol {
if i > row {
row = i
}
}
}
}
return row + 1
}
open func lettersCount() -> Int {
var count = 0
for i in 0 ..< rows {
for j in 0 ..< columns {
if grid![j, i] != emptySymbol {
count += 1
}
}
}
return count
}
// MARK: - Misc
fileprivate func randomValue() -> Int {
if orientationOptimization {
return UIDevice.current.orientation.isLandscape ? 1 : 0
}
else {
return randomInt(0, max: 1)
}
}
fileprivate func randomInt(_ min: Int, max:Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
// MARK: - Debug
func printGrid() {
for i in 0 ..< rows {
var s = ""
for j in 0 ..< columns {
s += grid![j, i]
}
print(s)
}
}
}
| mit | 72e6288dffe1f1b1c90c5f15d0e649ad | 19.414894 | 130 | 0.569463 | 3.160408 | false | false | false | false |
practicalswift/swift | stdlib/public/core/StringCharacterView.swift | 1 | 9339 | //===--- StringCharacterView.swift - String's Collection of Characters ----===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// String is-not-a Sequence or Collection, but it exposes a
// collection of characters.
//
//===----------------------------------------------------------------------===//
// FIXME(ABI)#70 : The character string view should have a custom iterator type
// to allow performance optimizations of linear traversals.
import SwiftShims
extension String: BidirectionalCollection {
/// A type that represents the number of steps between two `String.Index`
/// values, where one value is reachable from the other.
///
/// In Swift, *reachability* refers to the ability to produce one value from
/// the other through zero or more applications of `index(after:)`.
public typealias IndexDistance = Int
public typealias SubSequence = Substring
public typealias Element = Character
/// The position of the first character in a nonempty string.
///
/// In an empty string, `startIndex` is equal to `endIndex`.
@inlinable
public var startIndex: Index {
@inline(__always) get { return _guts.startIndex }
}
/// A string's "past the end" position---that is, the position one greater
/// than the last valid subscript argument.
///
/// In an empty string, `endIndex` is equal to `startIndex`.
@inlinable
public var endIndex: Index {
@inline(__always) get { return _guts.endIndex }
}
/// The number of characters in a string.
public var count: Int {
@inline(__always) get {
return distance(from: startIndex, to: endIndex)
}
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Index) -> Index {
_precondition(i < endIndex, "String index is out of bounds")
// TODO: known-ASCII fast path, single-scalar-grapheme fast path, etc.
let stride = _characterStride(startingAt: i)
let nextOffset = i._encodedOffset &+ stride
let nextStride = _characterStride(
startingAt: Index(_encodedOffset: nextOffset))
return Index(
encodedOffset: nextOffset, characterStride: nextStride)
}
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
/// - Returns: The index value immediately before `i`.
public func index(before i: Index) -> Index {
_precondition(i > startIndex, "String index is out of bounds")
// TODO: known-ASCII fast path, single-scalar-grapheme fast path, etc.
let stride = _characterStride(endingAt: i)
let priorOffset = i._encodedOffset &- stride
return Index(encodedOffset: priorOffset, characterStride: stride)
}
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
///
/// let s = "Swift"
/// let i = s.index(s.startIndex, offsetBy: 4)
/// print(s[i])
/// // Prints "t"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - Complexity: O(*n*), where *n* is the absolute value of `n`.
@inlinable @inline(__always)
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
// TODO: known-ASCII and single-scalar-grapheme fast path, etc.
return _index(i, offsetBy: n)
}
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
/// The operation doesn't require going beyond the limiting `s.endIndex`
/// value, so it succeeds.
///
/// let s = "Swift"
/// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
/// print(s[i])
/// }
/// // Prints "t"
///
/// The next example attempts to retrieve an index six positions from
/// `s.startIndex` but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the absolute value of `n`.
@inlinable @inline(__always)
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
// TODO: known-ASCII and single-scalar-grapheme fast path, etc.
return _index(i, offsetBy: n, limitedBy: limit)
}
/// Returns the distance between two indices.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`.
///
/// - Complexity: O(*n*), where *n* is the resulting distance.
@inlinable @inline(__always)
public func distance(from start: Index, to end: Index) -> IndexDistance {
// TODO: known-ASCII and single-scalar-grapheme fast path, etc.
return _distance(from: start, to: end)
}
/// Accesses the character at the given position.
///
/// You can use the same indices for subscripting a string and its substring.
/// For example, this code finds the first letter after the first space:
///
/// let str = "Greetings, friend! How are you?"
/// let firstSpace = str.firstIndex(of: " ") ?? str.endIndex
/// let substr = str[firstSpace...]
/// if let nextCapital = substr.firstIndex(where: { $0 >= "A" && $0 <= "Z" }) {
/// print("Capital after a space: \(str[nextCapital])")
/// }
/// // Prints "Capital after a space: H"
///
/// - Parameter i: A valid index of the string. `i` must be less than the
/// string's end index.
@inlinable
public subscript(i: Index) -> Character {
@inline(__always) get {
_boundsCheck(i)
let i = _guts.scalarAlign(i)
let distance = _characterStride(startingAt: i)
return _guts.errorCorrectedCharacter(
startingAt: i._encodedOffset, endingAt: i._encodedOffset &+ distance)
}
}
@inlinable @inline(__always)
internal func _characterStride(startingAt i: Index) -> Int {
// Fast check if it's already been measured, otherwise check resiliently
if let d = i.characterStride { return d }
if i == endIndex { return 0 }
return _guts._opaqueCharacterStride(startingAt: i._encodedOffset)
}
@inlinable @inline(__always)
internal func _characterStride(endingAt i: Index) -> Int {
if i == startIndex { return 0 }
return _guts._opaqueCharacterStride(endingAt: i._encodedOffset)
}
}
extension String {
@_fixed_layout
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var _guts: _StringGuts
@usableFromInline
internal var _position: Int = 0
@usableFromInline
internal var _end: Int
@inlinable
internal init(_ guts: _StringGuts) {
self._end = guts.count
self._guts = guts
}
@inlinable
public mutating func next() -> Character? {
guard _fastPath(_position < _end) else { return nil }
let len = _guts._opaqueCharacterStride(startingAt: _position)
let nextPosition = _position &+ len
let result = _guts.errorCorrectedCharacter(
startingAt: _position, endingAt: nextPosition)
_position = nextPosition
return result
}
}
@inlinable
public __consuming func makeIterator() -> Iterator {
return Iterator(_guts)
}
}
| apache-2.0 | 327862ad65f5ce7e3b798a454dc4b021 | 35.057915 | 85 | 0.639148 | 4.159911 | false | false | false | false |
mozilla/Deferred | Deferred/ReadWriteLock.swift | 1 | 4599 | //
// ReadWriteLock.swift
// ReadWriteLock
//
// Created by John Gallagher on 7/17/14.
// Copyright (c) 2014 Big Nerd Ranch. All rights reserved.
//
import Foundation
public protocol ReadWriteLock: class {
func withReadLock<T>(block: () -> T) -> T
func withWriteLock<T>(block: () -> T) -> T
}
public final class GCDReadWriteLock: ReadWriteLock {
private let queue = dispatch_queue_create("GCDReadWriteLock", DISPATCH_QUEUE_CONCURRENT)
public init() {}
public func withReadLock<T>(block: () -> T) -> T {
var result: T!
dispatch_sync(queue) {
result = block()
}
return result
}
public func withWriteLock<T>(block: () -> T) -> T {
var result: T!
dispatch_barrier_sync(queue) {
result = block()
}
return result
}
}
public final class SpinLock: ReadWriteLock {
private var lock: UnsafeMutablePointer<Int32>
public init() {
lock = UnsafeMutablePointer.alloc(1)
lock.memory = OS_SPINLOCK_INIT
}
deinit {
lock.dealloc(1)
}
public func withReadLock<T>(block: () -> T) -> T {
OSSpinLockLock(lock)
let result = block()
OSSpinLockUnlock(lock)
return result
}
public func withWriteLock<T>(block: () -> T) -> T {
OSSpinLockLock(lock)
let result = block()
OSSpinLockUnlock(lock)
return result
}
}
/// Test comment 2
public final class CASSpinLock: ReadWriteLock {
private struct Masks {
static let WRITER_BIT: Int32 = 0x40000000
static let WRITER_WAITING_BIT: Int32 = 0x20000000
static let MASK_WRITER_BITS = WRITER_BIT | WRITER_WAITING_BIT
static let MASK_READER_BITS = ~MASK_WRITER_BITS
}
private var _state: UnsafeMutablePointer<Int32>
public init() {
_state = UnsafeMutablePointer.alloc(1)
_state.memory = 0
}
deinit {
_state.dealloc(1)
}
public func withWriteLock<T>(block: () -> T) -> T {
// spin until we acquire write lock
repeat {
let state = _state.memory
// if there are no readers and no one holds the write lock, try to grab the write lock immediately
if (state == 0 || state == Masks.WRITER_WAITING_BIT) &&
OSAtomicCompareAndSwap32Barrier(state, Masks.WRITER_BIT, _state) {
break
}
// If we get here, someone is reading or writing. Set the WRITER_WAITING_BIT if
// it isn't already to block any new readers, then wait a bit before
// trying again. Ignore CAS failure - we'll just try again next iteration
if state & Masks.WRITER_WAITING_BIT == 0 {
OSAtomicCompareAndSwap32Barrier(state, state | Masks.WRITER_WAITING_BIT, _state)
}
} while true
// write lock acquired - run block
let result = block()
// unlock
repeat {
let state = _state.memory
// clear everything except (possibly) WRITER_WAITING_BIT, which will only be set
// if another writer is already here and waiting (which will keep out readers)
if OSAtomicCompareAndSwap32Barrier(state, state & Masks.WRITER_WAITING_BIT, _state) {
break
}
} while true
return result
}
public func withReadLock<T>(block: () -> T) -> T {
// spin until we acquire read lock
repeat {
let state = _state.memory
// if there is no writer and no writer waiting, try to increment reader count
if (state & Masks.MASK_WRITER_BITS) == 0 &&
OSAtomicCompareAndSwap32Barrier(state, state + 1, _state) {
break
}
} while true
// read lock acquired - run block
let result = block()
// decrement reader count
repeat {
let state = _state.memory
// sanity check that we have a positive reader count before decrementing it
assert((state & Masks.MASK_READER_BITS) > 0, "unlocking read lock - invalid reader count")
// desired new state: 1 fewer reader, preserving whether or not there is a writer waiting
let newState = ((state & Masks.MASK_READER_BITS) - 1) |
(state & Masks.WRITER_WAITING_BIT)
if OSAtomicCompareAndSwap32Barrier(state, newState, _state) {
break
}
} while true
return result
}
} | mit | 76bec45d030925f51164d657fdbbfe9d | 28.87013 | 110 | 0.575125 | 4.359242 | false | false | false | false |
nriley/LBOfficeMRU | Office 14 MRU.playground/Contents.swift | 1 | 1475 | // MRU list generator for Mac Office 14 (2011)
import Foundation
func getMRUList(forApp: String) -> [String]? {
guard let defaults = NSUserDefaults.standardUserDefaults().persistentDomainForName("com.microsoft.office") else {
NSLog("Unable to find Office defaults")
return nil
}
guard let mruList = defaults["14\\File MRU\\" + forApp ] as? [NSDictionary] else {
NSLog("Unable to find recent documents for Office application \(forApp)")
return nil
}
return mruList.flatMap { (mruItem: NSDictionary) in
guard let mruFileAliasData = mruItem["File Alias"] as? NSData else {
NSLog("Unable to extract file alias from MRU item \(mruItem)")
return nil
}
do {
let mruFileBookmarkData = CFURLCreateBookmarkDataFromAliasRecord(nil, mruFileAliasData).takeRetainedValue()
let mruFileURL = try NSURL.init(byResolvingBookmarkData: mruFileBookmarkData, options: NSURLBookmarkResolutionOptions(), relativeToURL: nil, bookmarkDataIsStale: nil)
return mruFileURL.path
} catch let error as NSError {
NSLog("Unable to resolve file alias for MRU item \(mruFileAliasData): \(error.localizedDescription)")
return nil
}
}
}
if let mruList = getMRUList("MSWD") {
print(NSString.init(data: try! NSJSONSerialization.dataWithJSONObject(mruList, options: NSJSONWritingOptions()), encoding: NSUTF8StringEncoding)!)
}
| apache-2.0 | ecebe0cffd1f0195ce3c0e3e4aa3947c | 42.382353 | 178 | 0.684068 | 4.483283 | false | false | false | false |
the-grid/Portal | PortalTests/Models/Extensions/NSURLSpec.swift | 1 | 799 | import Argo
import Foundation
import Nimble
import Ogra
import Portal
import Quick
import XCTest
class NSURLSpec: QuickSpec {
override func spec() {
let urlString = "https://thegrid.io"
let json: JSON = .String(urlString)
let url = NSURL(string: urlString)
describe("decoding") {
it("should produce an NSURL") {
guard let decoded = NSURL.decode(json).value else {
return XCTFail("Unable to decode JSON: \(json)")
}
expect(decoded).to(equal(url))
}
}
describe("encoding") {
it("should produce JSON") {
let encoded = url.encode()
expect(encoded).to(equal(json))
}
}
}
}
| mit | f20cb7082eb24ac00801f5f566c791c2 | 24.774194 | 68 | 0.516896 | 4.784431 | false | false | false | false |
StYaphet/firefox-ios | Client/Frontend/AuthenticationManager/RequirePasscodeIntervalViewController.swift | 7 | 3097 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import SwiftKeychainWrapper
/// Screen presented to the user when selecting the time interval before requiring a passcode
class RequirePasscodeIntervalViewController: UITableViewController {
let intervalOptions: [PasscodeInterval] = [
.immediately,
.oneMinute,
.fiveMinutes,
.tenMinutes,
.fifteenMinutes,
.oneHour
]
fileprivate let BasicCheckmarkCell = "BasicCheckmarkCell"
fileprivate var authenticationInfo: AuthenticationKeychainInfo?
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = AuthenticationStrings.requirePasscode
tableView.accessibilityIdentifier = "AuthenticationManager.passcodeIntervalTableView"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: BasicCheckmarkCell)
tableView.backgroundColor = UIColor.theme.tableView.headerBackground
let headerFooterFrame = CGRect(width: self.view.frame.width, height: SettingsUX.TableViewHeaderFooterHeight)
let headerView = ThemedTableSectionHeaderFooterView(frame: headerFooterFrame)
headerView.showBorder(for: .bottom, true)
let footerView = ThemedTableSectionHeaderFooterView(frame: headerFooterFrame)
footerView.showBorder(for: .top, true)
tableView.tableHeaderView = headerView
tableView.tableFooterView = footerView
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.authenticationInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo()
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: BasicCheckmarkCell, for: indexPath)
let option = intervalOptions[indexPath.row]
let intervalTitle = NSAttributedString.tableRowTitle(option.settingTitle, enabled: true)
cell.textLabel?.attributedText = intervalTitle
cell.accessoryType = authenticationInfo?.requiredPasscodeInterval == option ? .checkmark : .none
cell.backgroundColor = UIColor.theme.tableView.rowBackground
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return intervalOptions.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
authenticationInfo?.updateRequiredPasscodeInterval(intervalOptions[indexPath.row])
KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authenticationInfo)
tableView.reloadData()
}
}
| mpl-2.0 | fb5b5a92b3c6c3be6c9e0de7fcab7b6e | 39.75 | 116 | 0.733936 | 5.65146 | false | false | false | false |
Trevi-Swift/Trevi-lime | Sources/Response.swift | 1 | 4644 | ////
//// Response.swift
//// Trevi
////
//// Created by LeeYoseob on 2015. 11. 23..
//// Copyright © 2015 Trevi Community. All rights reserved.
////
//
// Response.swift
// Trevi
//
// Created by LeeYoseob on 2015. 11. 23..
// Copyright © 2015년 LeeYoseob. All rights reserved.
//
import Foundation
import TreviSys
import Trevi
// Currently, you don't use this class, but will use the next.
public protocol Sender{
func send(data: AnyObject?) -> Bool
func end () -> Bool
func template() -> Bool
func render ( filename: String, args: AnyObject? ) -> Bool
}
public class Response{
private let response: ServerResponse
public var req: Request!
public let startTime: NSDate
public var onFinished : ((Response) -> Void)?
var socket: Socket!{
get{
return response.socket
}
set{
response.socket = newValue
}
}
public var connection: Socket!{
get{
return response.connection
}
set{
response.connection = newValue
}
}
public var header: [String: String]!{
get{
return response.header
}
set{
response.header = newValue
}
}
public var shouldKeepAlive: Bool{
get{
return response.shouldKeepAlive
}
set{
response.shouldKeepAlive = newValue
}
}
public var chunkEncoding: Bool {
get{
return response.chunkEncoding
}
set{
response.chunkEncoding = newValue
}
}
public var statusCode: Int!{
set{
response.statusCode = newValue
}
get{
return response.statusCode
}
}
init(response: ServerResponse) {
startTime = NSDate ()
onFinished = nil
self.response = response
}
// Lime recommend using that send rather than using write
public func send(data: String, encoding: String! = nil, type: String! = ""){
response.write(data, encoding: encoding, type: type)
endReuqstAndClean()
}
public func send(data: NSData, encoding: String! = nil, type: String! = ""){
response.write(data, encoding: encoding, type: type)
endReuqstAndClean()
}
public func send(data: [String : String], encoding: String! = nil, type: String! = ""){
response.write(data, encoding: encoding, type: type)
endReuqstAndClean()
}
public func end(){
response.end()
}
public func writeHead(statusCode: Int, headers: [String:String] = [:]){
response.writeHead(statusCode, headers: headers)
}
public func write(data: String, encoding: String! = nil, type: String! = ""){
response.write(data,encoding: encoding ,type: type)
}
public func write(data: NSData, encoding: String! = nil, type: String! = ""){
response.write(data,encoding: encoding ,type: type)
}
public func write(data: [String : String], encoding: String! = nil, type: String! = ""){
response.write(data,encoding: encoding ,type: type)
}
private func endReuqstAndClean(){
response.end()
onFinished?(self)
if req.files != nil {
for file in self.req.files.values{
FSBase.unlink(path: file.path)
}
}
}
public func render(path: String, args: [String:String]? = nil) {
if let app = req.app as? Lime, let render = app.setting["view engine"] as? Render {
var entirePath = path
#if os(Linux)
if let abpath = app.setting["views"] as? StringWrapper {
entirePath = "\(abpath.string)/\(entirePath)"
}
#else
if let bundlePath = NSBundle.mainBundle().pathForResource(NSURL(fileURLWithPath: path).lastPathComponent!, ofType: nil) {
entirePath = bundlePath
}
#endif
if args != nil {
render.render(entirePath, args: args!) { data in
self.response.write(data)
}
} else {
render.render(entirePath) { data in
self.response.write(data)
}
}
}
onFinished?(self)
response.end()
}
public func redirect(url: String){
response.writeHead(302, headers: [Location:url])
onFinished?(self)
response.end()
}
}
| apache-2.0 | d7c28b752a5cedc99dd339036706fdc3 | 24.635359 | 137 | 0.541379 | 4.465833 | false | false | false | false |
trinhlbk1991/DemoBasiciOSControls | DemoBasiciOSControls/DemoBasiciOSControls/ViewController.swift | 1 | 2502 | //
// ViewController.swift
// DemoBasiciOSControls
//
// Created by TrinhLBK on 6/21/15.
// Copyright (c) 2015 TrinhLBK. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var containerLogin: UIView!
@IBOutlet weak var containerSurvey: UIView!
@IBOutlet weak var tfName: UITextField!
@IBOutlet weak var tfPhone: UITextField!
@IBOutlet weak var lbSliderValue: UILabel!
@IBOutlet weak var sliderSurvey: UISlider!
@IBAction func onSegmentValueChanged(sender: UISegmentedControl) {
let selectedSegment = sender.selectedSegmentIndex
switch selectedSegment{
case 0:
containerLogin.hidden = false
containerSurvey.hidden = true
break;
case 1:
containerLogin.hidden = true
containerSurvey.hidden = false
break;
default:
//Do nothing
break;
}
}
@IBAction func onTextFieldDoneEdit(sender: UITextField) {
sender.resignFirstResponder()
}
@IBAction func onSliderValueChanged(sender: UISlider) {
let sliderValue = sender.value
lbSliderValue.text = "\(sliderValue)"
}
@IBAction func onSwitchSurveyValueChanged(sender: UISwitch) {
sliderSurvey.enabled = sender.on
}
@IBAction func onBtnLoginClicked(sender: UIButton) {
let controllerLoginDialog = UIAlertController(title: "Login", message: "Do you want to log in?", preferredStyle: UIAlertControllerStyle.ActionSheet)
let actionYes = UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default, handler: { action in
let controllerLoginSuccessDialog = UIAlertController(title: "Login", message: "Logged in successfully!", preferredStyle: UIAlertControllerStyle.Alert)
let actionOk = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
controllerLoginSuccessDialog.addAction(actionOk)
self.presentViewController(controllerLoginSuccessDialog, animated: true, completion: nil)
})
let actionNo = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Destructive, handler: nil)
controllerLoginDialog.addAction(actionYes)
controllerLoginDialog.addAction(actionNo)
presentViewController(controllerLoginDialog, animated: true, completion: nil)
}
}
| mit | c95c2ba9892531406f0436a28a3dcd40 | 32.810811 | 162 | 0.661071 | 5.190871 | false | false | false | false |
cactis/SwiftEasyKit | Source/Classes/SelectionViewController/SWKInput.swift | 1 | 2748 | //
// SWKInput.swift
// SwiftEasyKit
//
// Created by ctslin on 2016/11/25.
// Copyright © 2016年 airfont. All rights reserved.
//
import UIKit
open class SWKDateInput: SWKInput {
let datePicker = UIDatePicker()
override open func layoutUI() {
super.layoutUI()
datePicker.datePickerMode = .date
let toolbar = UIToolbar()
toolbar.sizeToFit()
let flex = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let done = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneTapped))
toolbar.items = [flex, done]
value.inputAccessoryView = toolbar
value.inputView = datePicker
}
override open func bindUI() {
super.bindUI()
value.addTarget(self, action: #selector(valueTapped), for: .editingDidBegin)
}
@objc func valueTapped() {
datePicker.date = (value.text!.toDate("yyyy/MM/dd") ?? Date()) as Date
}
@objc func doneTapped() {
value.endEditing(true)
value.texted(datePicker.date.toString())
}
}
open class SWKInput: DefaultView {
public var label = UILabel()
open var value = UITextField()
public var data: String? { didSet { value.texted(data) } }
public var text: String? { get { return value.text } set { value.text = newValue } }
public var prefix: String!
public func valued(_ text: String?) { value.texted(text) }
public init(label: String, value: String = "", prefix: String = "輸入") {
super.init(frame: .zero)
self.label.texted(label)
self.prefix = prefix
if self.value.placeholder == nil {self.value.placeholder = "\(prefix)\(label)" }
({self.data = value})()
}
public init(label: String, placeholder: String) {
super.init(frame: .zero)
self.label.texted(label)
self.value.placeholder = placeholder
}
public init(label: String, placeholder: String, secureText: Bool) {
super.init(frame: .zero)
value.isSecureTextEntry = secureText
self.label.texted(label)
self.value.placeholder = placeholder
}
override open func layoutUI() {
super.layoutUI()
layout([label, value])
}
override open func styleUI() {
super.styleUI()
label.styled()
value.styled().bold()
value.colored(K.Color.Text.strong).aligned(.right)
}
public func estimateHeight() -> CGFloat {
return 40 + label.textHeight()
}
override open func layoutSubviews() {
super.layoutSubviews()
label.anchorAndFillEdge(.left, xPad: 0, yPad: 0, otherSize: label.textWidth())
value.align(toTheRightOf: label, matchingCenterWithLeftPadding: 10, width: width - label.rightEdge() - 30, height: label.height)
}
required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}
| mit | 156aaeb51dd1a80241257dd28907b722 | 26.969388 | 132 | 0.679679 | 3.833566 | false | false | false | false |
kenwilcox/TaskIt-Swift | TaskIt/AddTaskViewController.swift | 1 | 2339 | //
// AddTaskViewController.swift
// TaskIt
//
// Created by Kenneth Wilcox on 1/29/15.
// Copyright (c) 2015 Kenneth Wilcox. All rights reserved.
//
import UIKit
import CoreData
protocol AddTaskViewControllerDelegate {
func addTask(message: String)
func addTaskCanceled(message: String)
}
class AddTaskViewController: UIViewController {
@IBOutlet weak var taskTextField: UITextField!
@IBOutlet weak var subtaskTextField: UITextField!
@IBOutlet weak var dueDatePicker: UIDatePicker!
var delegate: AddTaskViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "Background")!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cancelButtonTapped(sender: UIButton) {
self.dismissViewControllerAnimated(true, completion: nil)
delegate?.addTaskCanceled("Task was not added!")
}
@IBAction func addTaskButtonTapped(sender: UIButton) {
let appDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let managedObjectContext = ModelManager.instance.managedObjectContext
let entityDescription = NSEntityDescription.entityForName("TaskModel", inManagedObjectContext: managedObjectContext!)
let task = TaskModel(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext!)
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.boolForKey(kShouldCapitalizeTaskKey) == true {
task.task = taskTextField.text.capitalizedString
} else {
task.task = taskTextField.text
}
task.subtask = subtaskTextField.text
task.date = dueDatePicker.date
task.completed = defaults.boolForKey(kShouldCompleteNewTodoKey)
ModelManager.instance.saveContext()
// Dump what has been saved
var request = NSFetchRequest(entityName: "TaskModel")
var error:NSError? = nil
var results:NSArray = managedObjectContext!.executeFetchRequest(request, error: &error)!
for res in results {
println(res)
}
self.dismissViewControllerAnimated(true, completion: nil)
delegate?.addTask("Task Added")
}
}
| mit | f94f635cf18c25273d4dd2d38531ee7c | 31.041096 | 121 | 0.73835 | 5.008565 | false | false | false | false |
casbeebc/InstancedDrawing | InstancedDrawing/Renderer.swift | 1 | 15726 | //
// Renderer.swift
// InstancedDrawing
//
// Created by brett on 7/23/15.
// Copyright (c) 2015 DataMingle. All rights reserved.
//
import Foundation
import Metal
import simd
import QuartzCore.CAMetalLayer
class Renderer : NSObject {
var angularVelocity: Float = 0
var velocity: Float = 0
var frameDuration: Float = 0
let cowCount: Int = 80;
let cowSpeed: Float = 0.75;
let cowTurnDamping: Float = 0.95;
let terrainSize: Float = 40;
let terrainHeight: Float = 1.5;
let terrainSmoothness: Float = 0.95;
let cameraHeight: Float = 1;
let Y: vector_float3 = [ 0, 1, 0 ];
func random_unit_float() -> Float {
return Float(arc4random()) / Float(UInt32.max);
}
var layer: CAMetalLayer?
// Long-lived Metal objects
var device: MTLDevice?
var commandQueue: MTLCommandQueue?
var renderPipeline: MTLRenderPipelineState?
var depthState: MTLDepthStencilState?
var depthTexture: MTLTexture?
var sampler: MTLSamplerState?
// Resources
var terrainMesh: TerrainMesh?
var terrainTexture: MTLTexture?
var cowMesh: ObjectMesh?
var cowTexture: MTLTexture?
var sharedUniformBuffer: MTLBuffer?
var terrainUniformBuffer: MTLBuffer?
var cowUniformBuffer: MTLBuffer?
// Parameters
var cameraPosition: vector_float3 = []
var cameraHeading: Float = 0
var cameraPitch: Float = 0
var cows: [Cow] = []
var frameCount: Int = 0
init(layer: CAMetalLayer) {
super.init()
self.frameDuration = 1 / 60.0
self.layer = layer
self.buildMetal()
self.buildPipelines()
self.buildCows()
self.buildResources()
}
func buildMetal() {
self.device = MTLCreateSystemDefaultDevice()
self.layer!.device = self.device
self.layer!.pixelFormat = MTLPixelFormat.BGRA8Unorm
}
func buildPipelines() {
self.commandQueue = self.device!.newCommandQueue()
let library: MTLLibrary = self.device!.newDefaultLibrary()!
let vertexDescriptor: MTLVertexDescriptor = MTLVertexDescriptor()
vertexDescriptor.attributes[0].format = MTLVertexFormat.Float4;
vertexDescriptor.attributes[0].offset = 0;
vertexDescriptor.attributes[0].bufferIndex = 0;
vertexDescriptor.attributes[1].format = MTLVertexFormat.Float4;
vertexDescriptor.attributes[1].offset = sizeof(vector_float4);
vertexDescriptor.attributes[1].bufferIndex = 0;
vertexDescriptor.attributes[2].format = MTLVertexFormat.Float2;
vertexDescriptor.attributes[2].offset = sizeof(vector_float4) * 2;
vertexDescriptor.attributes[2].bufferIndex = 0;
vertexDescriptor.layouts[0].stepFunction = MTLVertexStepFunction.PerVertex;
vertexDescriptor.layouts[0].stride = sizeof(Vertex);
let pipelineDescriptor: MTLRenderPipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.vertexFunction = library.newFunctionWithName("vertex_project")
pipelineDescriptor.fragmentFunction = library.newFunctionWithName("fragment_texture")
pipelineDescriptor.vertexDescriptor = vertexDescriptor;
pipelineDescriptor.colorAttachments[0].pixelFormat = MTLPixelFormat.BGRA8Unorm;
pipelineDescriptor.depthAttachmentPixelFormat = MTLPixelFormat.Depth32Float;
do {
self.renderPipeline = try self.device!.newRenderPipelineStateWithDescriptor(pipelineDescriptor)
} catch {
NSLog("Failed to create render pipeline state")
}
let depthDescriptor: MTLDepthStencilDescriptor = MTLDepthStencilDescriptor()
depthDescriptor.depthWriteEnabled = true
depthDescriptor.depthCompareFunction = MTLCompareFunction.Less
self.depthState = self.device!.newDepthStencilStateWithDescriptor(depthDescriptor)
let samplerDescriptor: MTLSamplerDescriptor = MTLSamplerDescriptor()
samplerDescriptor.minFilter = MTLSamplerMinMagFilter.Nearest
samplerDescriptor.magFilter = MTLSamplerMinMagFilter.Linear
samplerDescriptor.sAddressMode = MTLSamplerAddressMode.Repeat
samplerDescriptor.tAddressMode = MTLSamplerAddressMode.Repeat
self.sampler = self.device!.newSamplerStateWithDescriptor(samplerDescriptor)
}
func buildCows() {
for (var i = 0; i < cowCount; ++i)
{
let cow: Cow = Cow()
// Situate the cow somewhere in the internal 80% part of the terrain patch
let x: Float = (random_unit_float() - 0.5) * terrainSize * 0.8
let z: Float = (random_unit_float() - 0.5) * terrainSize * 0.8
let y: Float = self.terrainMesh!.heightAtPositionX(x, z: z)
cow.position = [ x, y, z ]
cow.heading = 2 * Float(M_PI) * random_unit_float();
cow.targetHeading = cow.heading;
self.cows.append(cow)
}
}
func loadMeshes() {
self.terrainMesh = TerrainMesh(width: self.terrainSize, height: self.terrainHeight, iterations: 4, smoothness: terrainSmoothness, device: self.device!)
let modelURL: NSURL? = NSBundle.mainBundle().URLForResource("spot", withExtension: "obj")
let cowModel: Model = Model(fileURL: modelURL!, generateNormals: true)
let spotGroup: Group? = cowModel.groupForName("spot")
self.cowMesh = ObjectMesh(group: spotGroup!, device: self.device!)
}
func loadTextures() {
self.terrainTexture = TextureLoader.texture2DWithImageNamed("grass", device: self.device!)
self.terrainTexture!.label = "Terrain Texture"
self.cowTexture = TextureLoader.texture2DWithImageNamed("spot", device: self.device!)
self.cowTexture!.label = "Cow Texture"
}
func buildUniformBuffers() {
self.sharedUniformBuffer = self.device!.newBufferWithLength(sizeof(Uniforms), options: MTLResourceOptions.CPUCacheModeDefaultCache)
self.sharedUniformBuffer!.label = "Shared Uniforms"
self.terrainUniformBuffer = self.device!.newBufferWithLength(sizeof(PerInstanceUniforms), options: MTLResourceOptions.CPUCacheModeDefaultCache)
self.terrainUniformBuffer!.label = "Terrain Uniforms"
self.cowUniformBuffer = self.device!.newBufferWithLength(sizeof(PerInstanceUniforms), options: MTLResourceOptions.CPUCacheModeDefaultCache)
self.cowUniformBuffer!.label = "Cow Uniforms"
}
func buildResources() {
self.loadMeshes()
self.loadTextures()
self.buildUniformBuffers()
}
func buildDepthTexture() {
let drawableSize: CGSize = self.layer!.drawableSize
let descriptor: MTLTextureDescriptor = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat(MTLPixelFormat.Depth32Float, width: Int(drawableSize.width), height: Int(drawableSize.height), mipmapped: false)
self.depthTexture = self.device!.newTextureWithDescriptor(descriptor)
self.depthTexture!.label = "Depth Texture"
}
func positionConstrainedToTerrainForPosition(position:vector_float3) -> vector_float3
{
var newPosition: vector_float3 = position
// limit x and z extent to terrain patch boundaries
let halfWidth = self.terrainMesh!.width * 0.5
let halfDepth = self.terrainMesh!.depth * 0.5
if (newPosition.x < -halfWidth) {
newPosition.x = -halfWidth
} else if (newPosition.x > halfWidth) {
newPosition.x = halfWidth
}
if (newPosition.z < -halfDepth) {
newPosition.z = -halfDepth
} else if (newPosition.z > halfDepth) {
newPosition.z = halfDepth
}
newPosition.y = self.terrainMesh!.heightAtPositionX(newPosition.x, z:newPosition.z)
return newPosition
}
func updateTerrain() {
var terrainUniforms: PerInstanceUniforms = PerInstanceUniforms()
terrainUniforms.modelMatrix = MatrixUtilities.matrix_identity()
terrainUniforms.normalMatrix = MatrixUtilities.matrix_upper_left3x3(terrainUniforms.modelMatrix!)
memcpy(self.terrainUniformBuffer!.contents(), &terrainUniforms, sizeof(PerInstanceUniforms));
}
func updateCamera() {
var cameraPosition: vector_float3 = self.cameraPosition
self.cameraHeading += self.angularVelocity * self.frameDuration
// update camera location based on current heading
cameraPosition.x += -sin(self.cameraHeading) * self.velocity * self.frameDuration
cameraPosition.z += -cos(self.cameraHeading) * self.velocity * self.frameDuration
cameraPosition = self.positionConstrainedToTerrainForPosition(cameraPosition)
cameraPosition.y += cameraHeight
self.cameraPosition = cameraPosition
}
func updateCows() {
for (var i = 0; i < cowCount; ++i) {
let cow: Cow = self.cows[i]
// all cows select a new heading every ~4 seconds
if (self.frameCount % 240 == 0) {
cow.targetHeading = 2 * Float(M_PI) * random_unit_float()
}
// smooth between the current and intended direction
cow.heading = (cowTurnDamping * cow.heading) + ((1 - cowTurnDamping) * cow.targetHeading)
// update cow position based on its orientation, constraining to terrain
var position: vector_float3 = cow.position;
position.x += sin(cow.heading) * cowSpeed * self.frameDuration
position.z += cos(cow.heading) * cowSpeed * self.frameDuration
position = self.positionConstrainedToTerrainForPosition(position)
cow.position = position;
// build model matrix for cow
let rotation: matrix_float4x4 = MatrixUtilities.matrix_rotation(Y, angle: -cow.heading);
let translation: matrix_float4x4 = MatrixUtilities.matrix_translation(cow.position);
// copy matrices into uniform buffers
var uniforms: PerInstanceUniforms = PerInstanceUniforms()
uniforms.modelMatrix = MatrixUtilities.matrix_multiply(translation, right: rotation);
uniforms.normalMatrix = MatrixUtilities.matrix_upper_left3x3(uniforms.modelMatrix!);
memcpy(self.cowUniformBuffer!.contents() + sizeof(PerInstanceUniforms) * i, &uniforms, sizeof(PerInstanceUniforms));
}
}
func updateSharedUniforms() {
let viewMatrix: matrix_float4x4 = MatrixUtilities.matrix_multiply(MatrixUtilities.matrix_rotation(Y, angle: self.cameraHeading),
right: MatrixUtilities.matrix_translation(-self.cameraPosition))
let aspect: Float = Float(self.layer!.drawableSize.width) / Float(self.layer!.drawableSize.height);
let fov: Float = (aspect > 1) ? (Float(M_PI) / 4) : (Float(M_PI) / 3)
let projectionMatrix: matrix_float4x4 = MatrixUtilities.matrix_perspective_projection(aspect, fovy: fov, near: 0.1, far: 100);
var uniforms: Uniforms = Uniforms()
uniforms.viewProjectionMatrix = MatrixUtilities.matrix_multiply(projectionMatrix, right: viewMatrix);
memcpy(self.sharedUniformBuffer!.contents(), &uniforms, sizeof(Uniforms));
}
func updateUniforms() {
self.updateTerrain()
self.updateCows()
self.updateCamera()
self.updateSharedUniforms()
}
func createRenderPassWithColorAttachmentTexture(texture: MTLTexture) -> MTLRenderPassDescriptor {
let renderPass: MTLRenderPassDescriptor = MTLRenderPassDescriptor()
renderPass.colorAttachments[0].texture = texture
renderPass.colorAttachments[0].loadAction = MTLLoadAction.Clear
renderPass.colorAttachments[0].storeAction = MTLStoreAction.Store
renderPass.colorAttachments[0].clearColor = MTLClearColorMake(0.2, 0.5, 0.95, 1.0)
renderPass.depthAttachment.texture = self.depthTexture
renderPass.depthAttachment.loadAction = MTLLoadAction.Clear
renderPass.depthAttachment.storeAction = MTLStoreAction.Store
renderPass.depthAttachment.clearDepth = 1.0
return renderPass
}
func drawTerrainWithCommandEncoder(commandEncoder: MTLRenderCommandEncoder) {
commandEncoder.setVertexBuffer(self.terrainMesh!.vertexBuffer, offset:0, atIndex:0)
commandEncoder.setVertexBuffer(self.sharedUniformBuffer, offset:0, atIndex:1)
commandEncoder.setVertexBuffer(self.terrainUniformBuffer, offset:0, atIndex:2)
commandEncoder.setFragmentTexture(self.terrainTexture, atIndex:0)
commandEncoder.setFragmentSamplerState(self.sampler, atIndex:0)
commandEncoder.drawIndexedPrimitives(MTLPrimitiveType.Triangle, indexCount:self.terrainMesh!.indexBuffer!.length / sizeof(IndexType), indexType:MTLIndexType.UInt16, indexBuffer:self.terrainMesh!.indexBuffer!, indexBufferOffset:0, instanceCount: self.cowCount)
}
func drawCowsWithCommandEncoder(commandEncoder: MTLRenderCommandEncoder) {
commandEncoder.setVertexBuffer(self.cowMesh!.vertexBuffer, offset:0, atIndex:0)
commandEncoder.setVertexBuffer(self.sharedUniformBuffer, offset:0, atIndex:1)
commandEncoder.setVertexBuffer(self.cowUniformBuffer, offset:0, atIndex:2)
commandEncoder.setFragmentTexture(self.cowTexture, atIndex:0)
commandEncoder.setFragmentSamplerState(self.sampler, atIndex:0)
commandEncoder.drawIndexedPrimitives(MTLPrimitiveType.Triangle,
indexCount:self.cowMesh!.indexBuffer.length / sizeof(IndexType),
indexType:MTLIndexType.UInt16,
indexBuffer:self.cowMesh!.indexBuffer,
indexBufferOffset:0,
instanceCount:self.cowCount
)
}
func draw() {
self.updateUniforms()
let drawable: CAMetalDrawable? = self.layer!.nextDrawable()
if drawable != nil {
if(CGFloat(self.depthTexture!.width) != self.layer!.drawableSize.width || CGFloat(self.depthTexture!.height) != self.layer!.drawableSize.height) {
self.buildDepthTexture()
}
let renderPass: MTLRenderPassDescriptor = self.createRenderPassWithColorAttachmentTexture(drawable!.texture)
let commandBuffer: MTLCommandBuffer = self.commandQueue!.commandBuffer()
let commandEncoder: MTLRenderCommandEncoder = commandBuffer.renderCommandEncoderWithDescriptor(renderPass)
commandEncoder.setRenderPipelineState(self.renderPipeline!)
commandEncoder.setDepthStencilState(self.depthState)
commandEncoder.setFrontFacingWinding(MTLWinding.CounterClockwise)
commandEncoder.setCullMode(MTLCullMode.Back)
self.drawTerrainWithCommandEncoder(commandEncoder)
self.drawCowsWithCommandEncoder(commandEncoder)
commandEncoder.endEncoding()
commandBuffer.presentDrawable(drawable!)
commandBuffer.commit()
++self.frameCount
}
}
} | mit | 2cd5c1f3022a4e393b5c9551d0fc2bb5 | 39.429306 | 267 | 0.657764 | 5.076178 | false | false | false | false |
silence0201/Swift-Study | AdvancedSwift/协议/Slices/Slices.playgroundpage/Contents.swift | 1 | 4623 | /*:
## Slices
All collections get a default implementation of the slicing operation and have
an overload for `subscript` that takes a `Range<Index>`. This is the equivalent
of `list.dropFirst()`:
*/
//#-hidden-code
/// Private implementation detail of the List collection
fileprivate enum ListNode<Element> {
case end
indirect case node(Element, next: ListNode<Element>)
func cons(_ x: Element) -> ListNode<Element> {
return .node(x, next: self)
}
}
//#-end-hidden-code
//#-hidden-code
public struct ListIndex<Element>: CustomStringConvertible {
fileprivate let node: ListNode<Element>
fileprivate let tag: Int
public var description: String {
return "ListIndex(\(tag))"
}
}
//#-end-hidden-code
//#-hidden-code
extension ListIndex: Comparable {
public static func == <T>(lhs: ListIndex<T>, rhs: ListIndex<T>) -> Bool {
return lhs.tag == rhs.tag
}
public static func < <T>(lhs: ListIndex<T>, rhs: ListIndex<T>) -> Bool {
// startIndex has the highest tag, endIndex the lowest
return lhs.tag > rhs.tag
}
}
//#-end-hidden-code
//#-hidden-code
public struct List<Element>: Collection {
// Index's type could be inferred, but it helps make the rest of
// the code clearer:
public typealias Index = ListIndex<Element>
public let startIndex: Index
public let endIndex: Index
public subscript(position: Index) -> Element {
switch position.node {
case .end: fatalError("Subscript out of range")
case let .node(x, _): return x
}
}
public func index(after idx: Index) -> Index {
switch idx.node {
case .end: fatalError("Subscript out of range")
case let .node(_, next): return Index(node: next, tag: idx.tag - 1)
}
}
}
//#-end-hidden-code
//#-hidden-code
extension List: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Element...) {
startIndex = ListIndex(node: elements.reversed().reduce(.end) {
partialList, element in
partialList.cons(element)
}, tag: elements.count)
endIndex = ListIndex(node: .end, tag: 0)
}
}
//#-end-hidden-code
//#-hidden-code
extension List: CustomStringConvertible {
public var description: String {
let elements = self.map { String(describing: $0) }
.joined(separator: ", ")
return "List: (\(elements))"
}
}
//#-end-hidden-code
//#-editable-code
let list: List = [1,2,3,4,5]
let onePastStart = list.index(after: list.startIndex)
let firstDropped = list[onePastStart..<list.endIndex]
Array(firstDropped)
//#-end-editable-code
/*:
Since operations like `list[somewhere..<list.endIndex]` (slice from a specific
point to the end) and `list[list.startIndex..<somewhere]` (slice from the start
to a specific point) are very common, there are default operations in the
standard library that do this in a more readable way:
*/
//#-editable-code
let firstDropped2 = list.suffix(from: onePastStart)
//#-end-editable-code
/*:
By default, the type of `firstDropped` won't be a list — it'll be a
`Slice<List<String>>`. `Slice` is a lightweight wrapper on top of any
collection. The implementation looks something like this:
*/
//#-editable-code
struct Slice_sample_impl<Base: Collection>: Collection {
typealias Index = Base.Index
typealias IndexDistance = Base.IndexDistance
let collection: Base
var startIndex: Index
var endIndex: Index
init(base: Base, bounds: Range<Index>) {
collection = base
startIndex = bounds.lowerBound
endIndex = bounds.upperBound
}
func index(after i: Index) -> Index {
return collection.index(after: i)
}
subscript(position: Index) -> Base.Iterator.Element {
return collection[position]
}
typealias SubSequence = Slice_sample_impl<Base>
subscript(bounds: Range<Base.Index>) -> Slice_sample_impl<Base> {
return Slice_sample_impl(base: collection, bounds: bounds)
}
}
//#-end-editable-code
/*:
In addition to a reference to the original collection, `Slice` stores the start
and end index of the slice's bounds. This makes it twice as big as it needs to
be in `List`'s case, because the storage of a list itself consists of two
indices:
*/
//#-editable-code
// Size of a list is size of two nodes, the start and end:
MemoryLayout.size(ofValue: list)
// Size of a list slice is size of a list, plus size of the slice's
// start and end index, which in List's case are also list nodes.
MemoryLayout.size(ofValue: list.dropFirst())
//#-end-editable-code
| mit | 6b34e125ec5b3d53248aa732d6996355 | 26.670659 | 79 | 0.668686 | 3.936116 | false | false | false | false |
kesun421/firefox-ios | Shared/Extensions/StringExtensions.swift | 3 | 4251 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
public extension String {
public func startsWith(_ other: String) -> Bool {
// rangeOfString returns nil if other is empty, destroying the analogy with (ordered) sets.
if other.isEmpty {
return true
}
if let range = self.range(of: other,
options: NSString.CompareOptions.anchored) {
return range.lowerBound == self.startIndex
}
return false
}
public func endsWith(_ other: String) -> Bool {
// rangeOfString returns nil if other is empty, destroying the analogy with (ordered) sets.
if other.isEmpty {
return true
}
if let range = self.range(of: other,
options: [NSString.CompareOptions.anchored, NSString.CompareOptions.backwards]) {
return range.upperBound == self.endIndex
}
return false
}
func escape() -> String? {
// We can't guaruntee that strings have a valid string encoding, as this is an entry point for tainted data,
// we should be very careful about forcefully dereferencing optional types.
// https://stackoverflow.com/questions/33558933/why-is-the-return-value-of-string-addingpercentencoding-optional#33558934
let queryItemDividers = CharacterSet(charactersIn: "?=&")
let allowedEscapes = CharacterSet.urlQueryAllowed.symmetricDifference(queryItemDividers)
return self.addingPercentEncoding(withAllowedCharacters: allowedEscapes)
}
func unescape() -> String? {
return self.removingPercentEncoding
}
/**
Ellipsizes a String only if it's longer than `maxLength`
"ABCDEF".ellipsize(4)
// "AB…EF"
:param: maxLength The maximum length of the String.
:returns: A String with `maxLength` characters or less
*/
func ellipsize(maxLength: Int) -> String {
if (maxLength >= 2) && (self.characters.count > maxLength) {
let index1 = self.characters.index(self.startIndex, offsetBy: (maxLength + 1) / 2) // `+ 1` has the same effect as an int ceil
let index2 = self.characters.index(self.endIndex, offsetBy: maxLength / -2)
return self.substring(to: index1) + "…\u{2060}" + self.substring(from: index2)
}
return self
}
private var stringWithAdditionalEscaping: String {
return self.replacingOccurrences(of: "|", with: "%7C", options: NSString.CompareOptions(), range: nil)
}
public var asURL: URL? {
// Firefox and NSURL disagree about the valid contents of a URL.
// Let's escape | for them.
// We'd love to use one of the more sophisticated CFURL* or NSString.* functions, but
// none seem to be quite suitable.
return URL(string: self) ??
URL(string: self.stringWithAdditionalEscaping)
}
/// Returns a new string made by removing the leading String characters contained
/// in a given character set.
public func stringByTrimmingLeadingCharactersInSet(_ set: CharacterSet) -> String {
var trimmed = self
while trimmed.rangeOfCharacter(from: set)?.lowerBound == trimmed.startIndex {
trimmed.remove(at: trimmed.startIndex)
}
return trimmed
}
/// Adds a newline at the closest space from the middle of a string.
/// Example turning "Mark as Read" into "Mark as\n Read"
public func stringSplitWithNewline() -> String {
let mid = self.characters.count/2
let arr: [Int] = self.characters.indices.flatMap {
if self.characters[$0] == " " {
return self.distance(from: startIndex, to: $0)
}
return nil
}
guard let closest = arr.enumerated().min(by: { abs($0.1 - mid) < abs($1.1 - mid) }) else {
return self
}
var newString = self
newString.insert("\n", at: newString.characters.index(newString.characters.startIndex, offsetBy: closest.element))
return newString
}
}
| mpl-2.0 | 8d07d73a9ebd7985ccf08b477c4c0bf5 | 38.691589 | 138 | 0.634095 | 4.461134 | false | false | false | false |
darrarski/DRNet | DRNet/DRNet/RequestParameters/RequestJSONParameters.swift | 1 | 1377 | //
// RequestJSONParameters.swift
// DRNet
//
// Created by Dariusz Rybicki on 21/10/14.
// Copyright (c) 2014 Darrarski. All rights reserved.
//
import Foundation
public class RequestJSONParameters: RequestParameters {
public let parameters: [String: AnyObject]
public init(_ parameters: [String: AnyObject]) {
self.parameters = parameters
}
// MARK: - RequestParameters protocol
public func setParametersInRequest(request: NSURLRequest) -> NSURLRequest {
var mutableURLRequest: NSMutableURLRequest! = request.mutableCopy() as NSMutableURLRequest
setParametersInRequest(mutableURLRequest)
return request.copy() as NSURLRequest
}
public func setParametersInRequest(request: NSMutableURLRequest) {
assert(request.HTTPMethod != "GET", "Submitting HTTP Body with JSON parameters is not supported for GET requests")
var error: NSError?
if let data = NSJSONSerialization.dataWithJSONObject(parameters, options: .allZeros, error: &error) {
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = data
}
if let error = error {
assertionFailure("Unable to set JSON parameters in request due to error: \(error.localizedDescription)")
}
}
} | mit | a679c51041c9f9182d48a45e521c95b2 | 31.809524 | 122 | 0.669572 | 5.0625 | false | false | false | false |
jaunesarmiento/Shuffle | Shuffle/Shuffle.swift | 1 | 12223 | //
// Shuffle.swift
// Shuffle
//
// Created by Jaune Sarmiento on 5/25/15.
// Copyright (c) 2015 Jaune Sarmiento. All rights reserved.
//
import Foundation
// MARK: - CardViewSwipeDirection
@objc public enum CardViewSwipeDirection: NSInteger {
case Up = 0
case Right = 1
case Down = 2
case Left = 3
}
// MARK: - CardManagerDelegate
@objc public protocol CardManagerDelegate {
optional func cardManagerDidTapCardView(cardView: CardView)
optional func cardManagerDidPushCardView(cardView: CardView)
optional func cardManagerDidPopCardView(cardView: CardView, withDirection: CardViewSwipeDirection)
optional func cardManagerShouldCommitSwipeForDirection(direction: CardViewSwipeDirection, completed: (commit: Bool) -> Void)
optional func cardView(cardView: CardView, didChangePositionToPoint poing: CGPoint)
func generateCardView() -> CardView
}
// MARK: - CardManager
public class CardManager {
// The distance needed before the card manager detects a swipe.
public var actionMargin = UIScreen.mainScreen().bounds.width / 3
// The maximum number of cards loaded in the card stack.
public var maximumNumberOfCardLoadedSimultaneously = 3
// The root view controller where this card manager is attached to.
public var rootViewController: UIViewController?
// The card manager delegate handling push, pop, and swipe-related delegate callbacks.
public var delegate: CardManagerDelegate?
private var cardStack = NSMutableArray()
// Singleton instance
public class func sharedManager() -> CardManager {
struct Singleton {
static let instance = CardManager()
}
return Singleton.instance
}
// CardManager constructor
required public init() {
}
public func reloadData() {
var i = cardStack.count
while i < maximumNumberOfCardLoadedSimultaneously {
let cardView = delegate?.generateCardView() as CardView!
cardView.delegate = self
UIView.animateWithDuration(0.2,
animations: { () -> Void in
self.push(cardView)
}
)
i++
}
}
func push(cardView: CardView) {
cardView.alpha = 1
if cardStack.count == 0 {
rootViewController?.view.addSubview(cardView)
} else {
rootViewController?.view.insertSubview(cardView, belowSubview: self.cardStack[self.cardStack.count - 1] as! UIView)
}
cardStack.addObject(cardView)
// Tell the delegate that we just pushed a cardView
delegate?.cardManagerDidPushCardView?(cardView)
}
func pop() {
if cardStack.count > 0 {
// No need to remove it from the superview since the CardView handles that, just remove it from the stack.
cardStack.removeObjectAtIndex(0)
}
}
}
extension CardManager: CardViewDelegate {
@objc public func cardViewShouldCommitSwipe(cardView: CardView, withDirection direction: CardViewSwipeDirection, completed: (completed: Bool) -> Void) {
delegate?.cardManagerShouldCommitSwipeForDirection?(direction, completed: { (commit) -> Void in
completed(completed: commit)
})
}
@objc public func didSwipeCardView(cardView: CardView, withDirection direction: CardViewSwipeDirection) {
delegate?.cardManagerDidPopCardView?(cardView, withDirection: direction)
pop()
}
@objc public func didTapCardView(cardView: CardView) {
delegate?.cardManagerDidTapCardView?(cardView)
}
@objc public func cardView(cardView: CardView, didChangePositionToPoint point: CGPoint) {
delegate?.cardView?(cardView, didChangePositionToPoint: point)
}
}
// MARK: - CardViewDelegate
@objc public protocol CardViewDelegate {
optional func cardView(cardView: CardView, didChangePositionToPoint point: CGPoint)
optional func didTapCardView(cardView: CardView)
optional func didSwipeCardView(cardView: CardView, withDirection direction: CardViewSwipeDirection)
optional func didResetCardViewPosition()
func cardViewShouldCommitSwipe(cardView: CardView, withDirection direction: CardViewSwipeDirection, completed: (completed: Bool) -> Void)
}
// MARK: - CardView
public class CardView: UIView {
public var scaleStrength = 4.0
public var scaleMax = 0.98
public var rotationStrength = 240
public var rotationMax = 1
public var rotationAngle = M_PI / 16
private var panGestureRecognizer: UIPanGestureRecognizer!
private var tapGestureRecognizer: UITapGestureRecognizer!
private var originalPoint: CGPoint!
private var deltaX: CGFloat!
private var deltaY: CGFloat!
public var delegate: CardViewDelegate?
@IBOutlet public weak var shadowView: UIView?
@IBOutlet public weak var contentView: UIView?
@IBOutlet public weak var view: UIView!
override public init(frame: CGRect) {
super.init(frame: frame)
// Initialize the gesture recognizer so we can swipe the view
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "beingDragged:")
addGestureRecognizer(panGestureRecognizer)
// Initialize the tap gesture recognizer
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tapped:")
addGestureRecognizer(tapGestureRecognizer)
originalPoint = center
self.backgroundColor = UIColor.clearColor()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override func layoutSubviews() {
super.layoutSubviews()
// shadowView?.backgroundColor = UIColor.clearColor()
shadowView?.layer.cornerRadius = 2
shadowView?.layer.shadowRadius = 4
shadowView?.layer.shadowOpacity = 0.1
shadowView?.layer.shadowOffset = CGSizeMake(0, 2)
shadowView?.layer.shouldRasterize = true
contentView?.layer.cornerRadius = 2
contentView?.clipsToBounds = true
}
internal func didStartDraggingCardView() {
self.originalPoint = center
}
internal func didChangePositionToPoint(point: CGPoint) {
deltaX = point.x
deltaY = point.y
// Compute the rotation and scale of the cardView at its current position
let rotationFromDistance = min(deltaX / CGFloat(rotationStrength), CGFloat(rotationMax))
let rotationAngleFromDistance = CGFloat(rotationAngle) * CGFloat(rotationFromDistance)
let scale = max(1 - fabs(rotationFromDistance) / CGFloat(scaleStrength), CGFloat(scaleMax))
let xCurrent = originalPoint!.x + deltaX
let yCurrent = originalPoint!.y + deltaY
center = CGPointMake(xCurrent, yCurrent)
let transform: CGAffineTransform = CGAffineTransformMakeRotation(CGFloat(rotationAngleFromDistance))
let scaleTransform: CGAffineTransform = CGAffineTransformScale(transform, scale, scale)
// Transform the cardView
self.view.transform = scaleTransform
// Notify the delegate that the cardView has changed position
delegate?.cardView?(self, didChangePositionToPoint: point)
}
internal func didEndDraggingCardViewToPoint(point: CGPoint) {
let distance = sqrt(pow(point.x, 2) + pow(point.y, 2))
if distance > CardManager.sharedManager().actionMargin {
let direction = swipeDirectionForAngle(angleForPoint(point))
delegate?.cardViewShouldCommitSwipe(self, withDirection: direction, completed: { (completed) -> Void in
if completed {
self.didSwipeCardViewWithDirection(direction)
} else {
self.reset()
}
})
} else {
self.reset()
}
}
internal func didSwipeCardViewWithDirection(direction: CardViewSwipeDirection) {
var finishPoint: CGPoint!
switch direction {
case .Right:
finishPoint = CGPointMake(UIScreen.mainScreen().bounds.width + self.frame.width, originalPoint!.y + 56)
case .Left:
finishPoint = CGPointMake(-(UIScreen.mainScreen().bounds.width + self.frame.width), originalPoint!.y + 56)
case .Down:
finishPoint = CGPointMake(originalPoint!.x, UIScreen.mainScreen().bounds.height + self.frame.height)
default:
finishPoint = originalPoint!
}
UIView.animateWithDuration(0.2,
animations: { () -> Void in
self.center = finishPoint
},
completion: { (complete) -> Void in
self.delegate?.didSwipeCardView?(self, withDirection: direction)
self.removeFromSuperview()
}
)
}
internal func forceSwipeToPoint(point: CGPoint) {
originalPoint = center
deltaX = point.x
deltaY = point.y
let rotation: CGFloat = originalPoint!.x > deltaX ? -0.4 : 0.4
UIView.animateWithDuration(0.2,
animations: { () -> Void in
self.center = point
self.view.transform = CGAffineTransformMakeRotation(rotation)
}, completion: { (complete) -> Void in
self.didEndDraggingCardViewToPoint(point)
}
)
}
internal func angleForPoint(point: CGPoint) -> Float {
// Determine the angle of point
let radians = Float(atan2(point.y, point.x))
let degrees = Float(radians * 180.0 / Float(M_PI))
if degrees < 0 {
return fabsf(degrees)
} else {
return 360.0 - degrees
}
}
internal func swipeDirectionForAngle(angle: Float) -> CardViewSwipeDirection {
if angle >= 60 && angle < 120 {
return .Up
} else if angle >= 120 && angle < 240 {
return .Left
} else if angle >= 240 && angle < 300 {
return .Down
} else {
return .Right
}
}
internal func beingDragged(gestureRecognizer: UIPanGestureRecognizer) {
switch (gestureRecognizer.state) {
case UIGestureRecognizerState.Began:
didStartDraggingCardView()
case .Changed:
didChangePositionToPoint(gestureRecognizer.translationInView(self))
case .Ended:
didEndDraggingCardViewToPoint(gestureRecognizer.translationInView(self))
default:
break
}
}
public func swipeRight() {
let point = CGPointMake(UIScreen.mainScreen().bounds.width + self.frame.width, self.center.y)
forceSwipeToPoint(point)
}
public func swipeLeft() {
let point = CGPointMake(-(UIScreen.mainScreen().bounds.width + self.frame.width), self.center.y)
forceSwipeToPoint(point)
}
public func swipeDown() {
let point = CGPointMake(self.center.x, UIScreen.mainScreen().bounds.height + self.frame.height)
forceSwipeToPoint(point)
}
public func tapped(gestureRecognizer: UITapGestureRecognizer) {
delegate?.didTapCardView?(self)
}
public func reset() {
// Reset the card to original position
UIView.animateWithDuration(0.3,
animations: { () -> Void in
self.center = self.originalPoint!
let rotation: CGAffineTransform = CGAffineTransformMakeRotation(0)
self.view.transform = rotation
},
completion: { (completed) -> Void in
}
)
}
}
| mit | 65584a97feca543d4e759e37bbd3760c | 30.748052 | 156 | 0.620061 | 5.309731 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.