repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
xuzhuoxi/SearchKit | Source/cs/search/SearchResult.swift | 1 | 2977 | //
// SearchResult.swift
// SearchKit
//
// Created by 许灼溪 on 15/12/21.
//
//
import Foundation
/**
* 检索总结果
*
* @author xuzhuoxi
*
*/
public struct SearchResult {
fileprivate var keyResultMap = Dictionary<String, SearchKeyResult>()
/**
* 取得当前键结果数量<br>
*
* @return 结果数量
*/
public var resultsSize: Int {
return keyResultMap.count
}
/**
* 取得当前全部的键结果数组<br>
* 未经排序<br>
*
* @return SearchKeyResult数组{@link SearchKeyResult}
*/
public var results: [SearchKeyResult] {
return [SearchKeyResult](keyResultMap.values)
}
/**
* 取得当前全部键结果数组<br>
* 已排序,匹配度大在前
*
* @return 按匹配度从大到小的数组
*/
public var sortedResults: [SearchKeyResult] {
return [SearchKeyResult](keyResultMap.values).sorted(by: >)
}
/**
* 与别一个检索结果相加<br>
* 相加方式:遍历全部SearchKeyResult进行合并<br>
* 1.有key相同的:{@link SearchKeyResult#addSearchKeyResult(SearchKeyResult)}<br>
* 2.没有key相同的:直接存起来<br>
*
* @param searchResult
* 另一个检索结果
*/
mutating public func addResult(_ searchResult:SearchResult) {
for result in searchResult.results {
tryAddKeyResult(result)
}
}
/**
* 与SearchKeyResult实例相加<br>
* 1.有key相同的:{@link SearchKeyResult#addSearchKeyResult(SearchKeyResult)}<br>
* 2.没有key相同的:直接存起来<br>
*
* @param keyResult
* 键结果
*/
mutating public func addKeyResult(_ keyResult:SearchKeyResult) {
tryAddKeyResult(keyResult);
}
/**
* 进行正则过滤,当输入包含中文时才能使用<br>
* 与正则表达式不匹配的键结果会被清除<br>
* {@link String#matches(String)}{@link SearchInfo#getChineseWordsRegexp()}
*
* @param regexp
* 正则表达式
*/
mutating public func chineseRegexpMatchingClear(_ regexp:String) {
var remove: [String] = []
let sPattern: SimplePattern = SimplePattern(regexp)
for key in keyResultMap.keys {
if !sPattern.isMatch(key) {
remove.append(key)
}
}
for removeKey in remove {
keyResultMap.removeValue(forKey: removeKey)
}
}
/**
* 把一个键结果合并进来
*
* @param keyResult
* 键结果{@link SearchKeyResult}
*/
mutating fileprivate func tryAddKeyResult(_ keyResult:SearchKeyResult) {
if keyResultMap.has(keyResult.key) {
keyResultMap[keyResult.key]!.addSearchKeyResult(keyResult)
}else{
keyResultMap[keyResult.key] = keyResult
}
}
}
| mit |
RoRoche/iOSSwiftStarter | iOSSwiftStarter/Pods/CoreStore/CoreStore/Migrating/MigrationType.swift | 2 | 3905 | //
// MigrationType.swift
// CoreStore
//
// Copyright © 2015 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
// MARK: - MigrationType
/**
The `MigrationType` specifies the type of migration required for a store.
*/
public enum MigrationType: BooleanType {
/**
Indicates that the persistent store matches the latest model version and no migration is needed
*/
case None(version: String)
/**
Indicates that the persistent store does not match the latest model version but Core Data can infer the mapping model, so a lightweight migration is needed
*/
case Lightweight(sourceVersion: String, destinationVersion: String)
/**
Indicates that the persistent store does not match the latest model version and Core Data could not infer a mapping model, so a custom migration is needed
*/
case Heavyweight(sourceVersion: String, destinationVersion: String)
/**
Returns the source model version for the migration type. If no migration is required, `sourceVersion` will be equal to the `destinationVersion`.
*/
public var sourceVersion: String {
switch self {
case .None(let version):
return version
case .Lightweight(let sourceVersion, _):
return sourceVersion
case .Heavyweight(let sourceVersion, _):
return sourceVersion
}
}
/**
Returns the destination model version for the migration type. If no migration is required, `destinationVersion` will be equal to the `sourceVersion`.
*/
public var destinationVersion: String {
switch self {
case .None(let version):
return version
case .Lightweight(_, let destinationVersion):
return destinationVersion
case .Heavyweight(_, let destinationVersion):
return destinationVersion
}
}
/**
Returns `true` if the `MigrationType` is a lightweight migration. Used as syntactic sugar.
*/
public var isLightweightMigration: Bool {
if case .Lightweight = self {
return true
}
return false
}
/**
Returns `true` if the `MigrationType` is a heavyweight migration. Used as syntactic sugar.
*/
public var isHeavyweightMigration: Bool {
if case .Heavyweight = self {
return true
}
return false
}
// MARK: BooleanType
public var boolValue: Bool {
switch self {
case .None: return false
case .Lightweight: return true
case .Heavyweight: return true
}
}
}
| apache-2.0 |
superk589/DereGuide | DereGuide/Common/BaseRequest.swift | 2 | 5819 | //
// BaseRequest.swift
// DereGuide
//
// Created by zzk on 2017/1/25.
// Copyright © 2017 zzk. All rights reserved.
//
import Foundation
import SwiftyJSON
class BaseRequest {
static let `default` = BaseRequest()
var session = BaseSession.shared.session
func getWith(urlStr:String, params:[String:String]?, callback:@escaping (_ data:Data?, _ response: HTTPURLResponse?, _ error: Error?) -> Void) {
var newStr = urlStr
if params != nil {
newStr.append(encodeUnicode(string: paramsToString(params: params!)))
}
var request = URLRequest.init(url: URL.init(string: newStr)!)
request.httpMethod = "GET"
dataTask(with: request, completionHandler: callback)
}
func postWith(urlStr:String, params:[String:String]?, callback:@escaping (_ data:Data?, _ response: HTTPURLResponse?, _ error: Error?) -> Void) {
var newStr = ""
if params != nil {
newStr.append(encodeUnicode(string: paramsToString(params: params!)))
}
var request = URLRequest.init(url: URL.init(string: urlStr)!)
request.httpMethod = "POST"
request.httpBody = newStr.data(using: .utf8)
dataTask(with: request, completionHandler: callback)
}
func postWith(request:inout URLRequest, params:[String:String]?, callback:@escaping (_ data:Data?, _ response: HTTPURLResponse?, _ error: Error?) -> Void) {
var newStr = ""
if params != nil {
newStr.append(encodeUnicode(string: paramsToString(params: params!)))
}
request.httpMethod = "POST"
request.httpBody = newStr.data(using: .utf8)
dataTask(with: request, completionHandler: callback)
}
func getWith(request:inout URLRequest, params: [String :String]? = nil, callback:@escaping (_ data:Data?, _ response: HTTPURLResponse?, _ error: Error?) -> Void) {
var newStr = ""
if params != nil {
newStr.append(encodeUnicode(string: paramsToString(params: params!)))
}
request.httpMethod = "GET"
request.httpBody = newStr.data(using: .utf8)
dataTask(with: request, completionHandler: callback)
}
func getWith(urlString:String, params: [String :String]? = nil, callback:@escaping (_ data:Data?, _ response: HTTPURLResponse?, _ error: Error?) -> Void) {
var newStr = ""
if params != nil {
newStr.append("?")
newStr.append(encodeUnicode(string: paramsToString(params: params!)))
}
var request = URLRequest.init(url: URL.init(string: urlString + newStr)!)
request.httpMethod = "GET"
dataTask(with: request, completionHandler: callback)
}
fileprivate func paramsToString(params:[String:String]) -> String {
if params.count == 0 {
return ""
}
var paraStr = ""
var paraArr = [String]()
for (key, value) in params {
paraArr.append("\(key)=\(value)")
}
paraStr.append(paraArr.joined(separator: "&"))
return String(paraStr)
}
/// construct multipart url request
///
/// - Parameters:
/// - urlStr: string of remote api
/// - params: params of the multipart form
/// - fileNames: file names of params with file data
/// - Returns: the constructed request
fileprivate func constructMultipartRequest(urlStr:String, params:[String:Any?], fileNames: [String:String]?) -> URLRequest {
var request = URLRequest.init(url: URL.init(string: urlStr)!)
let boundary = "Boundary+BFFF11CB6FF1E452"
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var data = Data()
for (k, v) in params {
data.append("--\(boundary)\r\n".data(using: .utf8)!)
if v is UIImage {
data.append("Content-Disposition: form-data; name=\"\(k)\"; filename=\"\(fileNames?[k] ?? "")\"\r\n".data(using: .utf8)!)
data.append("Content-Type: image/png\r\n\r\n".data(using: .utf8)!)
let imageData = (v as? UIImage ?? UIImage()).pngData() ?? Data()
data.append(imageData)
data.append("\r\n".data(using: .utf8)!)
} else if v is String {
data.append("Content-Disposition: form-data; name=\"\(k)\"\r\n\r\n".data(using: .utf8)!)
data.append("\(v!)\r\n".data(using: .utf8, allowLossyConversion: true)!)
}
}
data.append("--\(boundary)--\r\n".data(using: .utf8)!)
request.httpBody = data
return request
}
func dataTask(with request:URLRequest, completionHandler: @escaping (Data?, HTTPURLResponse?, Error?) -> Void) {
#if DEBUG
print("request the url: ", request.url?.absoluteString ?? "")
#endif
let task = session?.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
if error != nil {
} else {
#if DEBUG
print("response code is ", (response as? HTTPURLResponse)?.statusCode ?? 0)
#endif
}
completionHandler(data, response as? HTTPURLResponse, error)
}
UIApplication.shared.isNetworkActivityIndicatorVisible = true
task?.resume()
}
func encodeUnicode(string:String) -> String {
var cs = CharacterSet.urlQueryAllowed
cs.remove(UnicodeScalar.init("+"))
let newStr = (string as NSString).addingPercentEncoding(withAllowedCharacters: cs)
return newStr ?? ""
}
}
| mit |
apple/swift-tools-support-core | Tests/TSCBasicTests/JSONMapperTests.swift | 1 | 4491 | /*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import TSCBasic
fileprivate struct Bar: JSONMappable, JSONSerializable, Equatable {
let str: String
let bool: Bool
init(json: JSON) throws {
self.str = try json.get("str")
self.bool = try json.get("bool")
}
func toJSON() -> JSON {
return .dictionary([
"str": .string(str),
"bool": .bool(bool),
])
}
init(str: String, bool: Bool) {
self.str = str
self.bool = bool
}
public static func ==(lhs: Bar, rhs: Bar) -> Bool {
return lhs.str == rhs.str && lhs.bool == rhs.bool
}
}
fileprivate struct Foo: JSONMappable, JSONSerializable {
let str: String
let int: Int
let optStr: String?
let bar: Bar
let barOp: Bar?
let barArray: [Bar]
let dict: [String: Double]
init(json: JSON) throws {
self.str = try json.get("str")
self.int = try json.get("int")
self.optStr = json.get("optStr")
self.bar = try json.get("bar")
self.barOp = json.get("barOp")
self.barArray = try json.get("barArray")
self.dict = try json.get("dict")
}
func toJSON() -> JSON {
return .dictionary([
"str": .string(str),
"int": .int(int),
"optStr": optStr.flatMap(JSON.string) ?? .null,
"bar": bar.toJSON(),
"barOp": barOp.flatMap{$0.toJSON()} ?? .null,
"barArray": .array(barArray.map{$0.toJSON()}),
"dict": .dictionary(Dictionary(uniqueKeysWithValues: dict.map{($0.0, .double($0.1))})),
])
}
init(str: String, int: Int, optStr: String?, bar: Bar, barArray: [Bar], dict: [String: Double]) {
self.str = str
self.int = int
self.optStr = optStr
self.bar = bar
self.barOp = nil
self.barArray = barArray
self.dict = dict
}
}
class JSONMapperTests: XCTestCase {
func testBasics() throws {
let bar = Bar(str: "bar", bool: false)
let bar1 = Bar(str: "bar1", bool: true)
let dict = ["a": 1.0, "b": 2.923]
let foo = Foo(
str: "foo", int: 1, optStr: "k", bar: bar, barArray: [bar, bar1], dict: dict)
let foo1 = try Foo(json: foo.toJSON())
XCTAssertEqual(foo.str, foo1.str)
XCTAssertEqual(foo.int, foo1.int)
XCTAssertEqual(foo.optStr, foo1.optStr)
XCTAssertEqual(foo.bar, bar)
XCTAssertNil(foo.barOp)
XCTAssertEqual(foo.barArray, [bar, bar1])
XCTAssertEqual(foo.dict, dict)
}
func testErrors() throws {
let foo = JSON.dictionary(["foo": JSON.string("Hello")])
do {
let string: String = try foo.get("bar")
XCTFail("unexpected string: \(string)")
} catch JSON.MapError.missingKey(let key) {
XCTAssertEqual(key, "bar")
}
do {
let int: Int = try foo.get("foo")
XCTFail("unexpected int: \(int)")
} catch JSON.MapError.custom(let key, let msg) {
XCTAssertNil(key)
XCTAssertEqual(msg, "expected int, got \"Hello\"")
}
do {
let bool: Bool = try foo.get("foo")
XCTFail("unexpected bool: \(bool)")
} catch JSON.MapError.custom(let key, let msg) {
XCTAssertNil(key)
XCTAssertEqual(msg, "expected bool, got \"Hello\"")
}
do {
let foo = JSON.string("Hello")
let string: String = try foo.get("bar")
XCTFail("unexpected string: \(string)")
} catch JSON.MapError.typeMismatch(let key, let expected, let json) {
XCTAssertEqual(key, "bar")
XCTAssert(expected == Dictionary<String, JSON>.self)
XCTAssertEqual(json, .string("Hello"))
}
do {
let string: [String] = try foo.get("foo")
XCTFail("unexpected string: \(string)")
} catch JSON.MapError.typeMismatch(let key, let expected, let json) {
XCTAssertEqual(key, "foo")
XCTAssert(expected == Array<JSON>.self)
XCTAssertEqual(json, .string("Hello"))
}
}
}
| apache-2.0 |
makma/cloud-sdk-swift | KenticoCloud/Classes/DeliveryService/Taxonomies/TaxonomyTerm.swift | 1 | 853 | //
// TaxonomyTerm.swift
// Pods
//
// Created by Martin Makarsky on 21/09/2017.
//
//
import ObjectMapper
/// Represents taxonomy term. Taxonomy term is a node of the taxonomy tree.
public class TaxonomyTerm: Mappable {
/// Name of taxonomy term.
public private(set) var name: String?
// Codename of taxonomy term.
public private(set) var codename: String?
// Taxonomy terms.
public private(set) var terms: [TaxonomyTerm]?
/// Maps response's json instance of the taxonomy term into strongly typed object representation.
public required init?(map: Map){
}
/// Maps response's json instance of the taxonomy term into strongly typed object representation.
public func mapping(map: Map) {
name <- map["name"]
codename <- map["codename"]
terms <- map["terms"]
}
}
| mit |
haawa799/WaniKani-Kanji-Strokes | Pods/WaniKit/Pod/Classes/WaniKit operations/KanjiList/DownloadKanjiListOperation.swift | 1 | 321 | //
// DownloadUserInfoOperation.swift
// Pods
//
// Created by Andriy K. on 12/14/15.
//
//
import UIKit
public class DownloadKanjiListOperation: DownloadOperation {
override init(url: NSURL, cacheFile: NSURL) {
super.init(url: url, cacheFile: cacheFile)
name = "Download Kanji info data"
}
} | mit |
JetBrains/kotlin-native | backend.native/tests/framework/multiple/multiple.swift | 4 | 3497 | /*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
import First
import Second
func testClashingNames() throws {
try assertEquals(actual: "first", expected: First.TestKt.name)
try assertEquals(actual: "second", expected: Second.TestKt.name)
let c1 = First.C()
let c2 = Second.C()
try assertTrue(type(of: c1) == First.C.self)
try assertTrue(type(of: c2) == Second.C.self)
try assertTrue(First.C.self != Second.C.self)
try assertTrue(objc_getClass(class_getName(First.C.self)) as AnyObject === First.C.self)
try assertTrue(objc_getClass(class_getName(Second.C.self)) as AnyObject === Second.C.self)
}
extension I1Impl : I2 {}
func testInteraction() throws {
try assertEquals(actual: SecondKt.getFortyTwoFrom(i2: I1Impl()), expected: 42)
}
func testIsolation1() throws {
try assertFalse(SecondKt.isUnit(obj: FirstKt.getUnit()))
// Ensure frameworks don't share the same runtime (state):
try assertFalse(First.RuntimeState().consumeChange())
try assertFalse(Second.RuntimeState().consumeChange())
Second.RuntimeState().produceChange()
try assertFalse(First.RuntimeState().consumeChange())
try assertTrue(Second.RuntimeState().consumeChange())
}
func testIsolation2() throws {
try assertEquals(actual: FirstKt.getI1().getFortyTwo(), expected: 42)
try assertEquals(actual: SecondKt.getI2().getFortyTwo(), expected: 42)
}
func testIsolation3() throws {
#if false // Disabled for now to avoid depending on platform libs.
FirstKt.getAnonymousObject()
SecondKt.getAnonymousObject()
FirstKt.getNamedObject()
SecondKt.getNamedObject()
#endif
}
// https://youtrack.jetbrains.com/issue/KT-34261
// When First and Second are static frameworks with caches, this test fails due to bad cache isolation:
// Caches included into both frameworks have 'ktypew' globals (with same name, hidden visibility and common linkage)
// for writable part of this "unexposed stdlib class" TypeInfo.
// ld ignores hidden visibility and merges common globals, so two independent frameworks happen to share
// the same global instead of two different globals. Things go wrong at runtime then: this writable TypeInfo part
// is used to store Obj-C class for this Kotlin class. So after the first object is obtained in Swift, both TypeInfos
// have its class, and the second object is wrong then.
func testIsolation4() throws {
let obj1: Any = First.SharedKt.getUnexposedStdlibClassInstance()
try assertTrue(obj1 is First.KotlinBase)
try assertFalse(obj1 is Second.KotlinBase)
let obj2: Any = Second.SharedKt.getUnexposedStdlibClassInstance()
try assertFalse(obj2 is First.KotlinBase)
try assertTrue(obj2 is Second.KotlinBase)
}
class MultipleTests : TestProvider {
var tests: [TestCase] = []
init() {
tests = [
TestCase(name: "TestClashingNames", method: withAutorelease(testClashingNames)),
TestCase(name: "TestInteraction", method: withAutorelease(testInteraction)),
TestCase(name: "TestIsolation1", method: withAutorelease(testIsolation1)),
TestCase(name: "TestIsolation2", method: withAutorelease(testIsolation2)),
TestCase(name: "TestIsolation3", method: withAutorelease(testIsolation3)),
TestCase(name: "TestIsolation4", method: withAutorelease(testIsolation4)),
]
providers.append(self)
}
} | apache-2.0 |
icanzilb/EventBlankApp | EventBlank/EventBlank/ViewControllers/Speakers/SpeakersDetailsViewController+TableView.swift | 2 | 8327 | //
// SpeakersDetailsViewController+TableView.swift
// EventBlank
//
// Created by Marin Todorov on 9/22/15.
// Copyright (c) 2015 Underplot ltd. All rights reserved.
//
import UIKit
import SQLite
//MARK: table view methods
extension SpeakerDetailsViewController {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if let twitterHandle = speaker[Speaker.twitter] where count(twitterHandle) > 0 {
return 2
}
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0: return 1;
case 1 where tweets == nil: return 1
case 1 where tweets != nil && tweets!.count == 0: return 0
case 1 where tweets != nil && tweets!.count > 0: return tweets!.count
default: return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
//speaker details
let cell = tableView.dequeueReusableCellWithIdentifier("SpeakerDetailsCell") as! SpeakerDetailsCell
//configure
cell.isFavoriteSpeaker = speakers.isFavorite(speakerId: speaker[Speaker.idColumn])
cell.indexPath = indexPath
//populate
cell.populateFromSpeaker(speaker, twitter: twitter)
//tap handlers
if let twitterHandle = speaker[Speaker.twitter] where count(twitterHandle) > 0 {
cell.didTapTwitter = {
let twitterUrl = NSURL(string: "https://twitter.com/" + twitterHandle)!
let webVC = self.storyboard?.instantiateViewControllerWithIdentifier("WebViewController") as! WebViewController
webVC.initialURL = twitterUrl
self.navigationController!.pushViewController(webVC, animated: true)
}
cell.didTapFollow = {
self.twitter.authorize({success in
if success {
cell.btnIsFollowing.followState = .SendingRequest
self.twitter.followUser(twitterHandle, completion: {following in
cell.btnIsFollowing.followState = following ? .Following : .Follow
cell.btnIsFollowing.animateSelect(scale: 0.8, completion: nil)
})
} else {
cell.btnIsFollowing.hidden = true
}
})
}
}
cell.didSetIsFavoriteTo = {setIsFavorite, indexPath in
//TODO: update all this to Swift 2.0
let id = self.speaker[Speaker.idColumn]
let isInFavorites = self.speakers.isFavorite(speakerId: id)
if setIsFavorite && !isInFavorites {
self.speakers.addFavorite(speakerId: id)
} else if !setIsFavorite && isInFavorites {
self.speakers.removeFavorite(speakerId: id)
}
delay(seconds: 0.1, {
self.notification(kFavoritesChangedNotification, object: self.speakers)
})
}
cell.didTapURL = {tappedUrl in
let webVC = self.storyboard?.instantiateViewControllerWithIdentifier("WebViewController") as! WebViewController
webVC.initialURL = tappedUrl
self.navigationController!.pushViewController(webVC, animated: true)
}
//work on the user photo
backgroundQueue({
if self.speaker[Speaker.photo]?.imageValue == nil {
self.userCtr.lookupUserImage(self.speaker, completion: {userImage in
userImage?.asyncToSize(.FillSize(cell.userImage.bounds.size), cornerRadius: 5, completion: {result in
cell.userImage.image = result
})
if let userImage = userImage {
cell.didTapPhoto = {
PhotoPopupView.showImage(userImage, inView: self.view)
}
}
})
} else {
cell.didTapPhoto = {
PhotoPopupView.showImage(self.speaker[Speaker.photo]!.imageValue!, inView: self.view)
}
}
})
return cell
}
if indexPath.section == 1, let tweets = tweets where tweets.count > 0 {
let cell = self.tableView.dequeueReusableCellWithIdentifier("TweetCell") as! TweetCell
let row = indexPath.row
let tweet = tweets[indexPath.row]
cell.message.text = tweet.text
cell.timeLabel.text = tweet.created.relativeTimeToString()
cell.message.selectedRange = NSRange(location: 0, length: 0)
if let attachmentUrl = tweet.imageUrl {
cell.attachmentImage.hnk_setImageFromURL(attachmentUrl, placeholder: nil, format: nil, failure: nil, success: {image in
image.asyncToSize(.Fill(cell.attachmentImage.bounds.width, 150), cornerRadius: 5.0, completion: {result in
cell.attachmentImage.image = result
})
})
cell.didTapAttachment = {
PhotoPopupView.showImageWithUrl(attachmentUrl, inView: self.view)
}
cell.attachmentHeight.constant = 148.0
}
cell.nameLabel.text = speaker[Speaker.name]
if user == nil {
let usersTable = database[UserConfig.tableName]
user = usersTable.filter(User.idColumn == tweet.userId).first
}
if let userImage = user?[User.photo]?.imageValue {
userImage.asyncToSize(.FillSize(cell.userImage.bounds.size), cornerRadius: 5, completion: {result in
cell.userImage.image = result
})
} else {
if !fetchingUserImage {
fetchUserImage()
}
cell.userImage.image = UIImage(named: "empty")
}
cell.didTapURL = {tappedUrl in
let webVC = self.storyboard?.instantiateViewControllerWithIdentifier("WebViewController") as! WebViewController
webVC.initialURL = tappedUrl
self.navigationController!.pushViewController(webVC, animated: true)
}
return cell
}
if indexPath.section == 1 && tweets == nil {
return tableView.dequeueReusableCellWithIdentifier("LoadingCell") as! UITableViewCell
}
return tableView.dequeueReusableCellWithIdentifier("") as! UITableViewCell
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0: return "Speaker Details"
case 1: return (tweets?.count < 1) ? "No tweets available" : "Latest tweets"
default: return nil
}
}
func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if section == 1, let tweets = tweets where tweets.count == 0 {
return "We couldn't load any tweets"
} else {
return nil
}
}
//add some space at the end of the tweet list
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
switch section {
case 1: return 50
default: return 0
}
}
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
switch section {
case 1: return UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
default: return nil
}
}
}
| mit |
frtlupsvn/Vietnam-To-Go | VietNamToGo/CustomView/ZCCView/ZCCView.swift | 1 | 361 | //
// ZCCView.swift
// Fuot
//
// Created by Zoom Nguyen on 1/2/16.
// Copyright © 2016 Zoom Nguyen. All rights reserved.
//
import UIKit
@IBDesignable
class ZCCView: UIView {
override func drawRect(rect: CGRect) {
// Drawing code
self.layer.cornerRadius = self.frame.size.height/2
self.layer.masksToBounds = true
}
}
| mit |
razvn/swiftserver-vapordemo | Sources/App/Models/User.swift | 1 | 1025 | import Foundation
import Vapor
struct User: Model {
var exists: Bool = false
var id: Node?
let name: String
let beer: Int?
init(name: String, beer: Int?) {
self.name = name
self.beer = beer
}
//Intializable from a Node
init(node: Node, in context: Context) throws {
id = try node.extract("id")
name = try node.extract("name")
beer = try node.extract("beer")
}
//Node represantable
func makeNode(context: Context) throws -> Node {
return try Node(node: ["id": id,
"name": name,
"beer": beer])
}
//Database preparation
static func prepare(_ database: Database) throws {
try database.create("users") {users in
users.id()
users.string("name")
users.int("beer", optional: true)
}
}
static func revert(_ database: Database) throws {
try database.delete("users")
}
}
| mit |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Tests/PlatformUIKitTests/Cards/AnnouncementDismissRecorderTests.swift | 1 | 2208 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import XCTest
@testable import PlatformKit
@testable import PlatformUIKit
@testable import PlatformUIKitMock
@testable import ToolKit
@testable import ToolKitMock
extension AnnouncementRecord.DisplayState {
var isHidden: Bool {
switch self {
case .show, .conditional:
return false
case .hide:
return true
}
}
var isShown: Bool {
switch self {
case .hide, .conditional:
return false
case .show:
return true
}
}
var isConditional: Bool {
switch self {
case .conditional:
return true
case .show, .hide:
return false
}
}
}
final class AnnouncementRecorderTests: XCTestCase {
private var cache: MemoryCacheSuite!
private var dismissRecorder: AnnouncementRecorder!
private var entry: AnnouncementRecorder.Entry!
private let key = AnnouncementRecord.Key.applePay
override func setUp() {
super.setUp()
cache = MemoryCacheSuite()
dismissRecorder = AnnouncementRecorder(cache: cache, errorRecorder: MockErrorRecorder())
entry = dismissRecorder[key]
}
func testOnTimeRecordIsDismissedInCacheSuite() {
XCTAssertTrue(entry.displayState.isShown)
entry.markDismissed(category: .oneTime)
XCTAssertTrue(entry.displayState.isHidden)
}
func testPeriodicRecordIsDismissedInCacheSuite() {
XCTAssertTrue(entry.displayState.isShown)
entry.markDismissed(category: .periodic)
XCTAssertTrue(entry.displayState.isConditional)
}
}
final class AnnouncementTests: XCTestCase {
func testAnnouncementQueue() {
let cache = MemoryCacheSuite()
let oneTimeAnnouncements = [
MockOneTimeAnnouncement(type: .applePay, cacheSuite: cache, dismiss: {}),
MockOneTimeAnnouncement(type: .resubmitDocuments, cacheSuite: cache, dismiss: {})
]
oneTimeAnnouncements[1].markRemoved()
XCTAssertFalse(oneTimeAnnouncements[0].isDismissed)
XCTAssertTrue(oneTimeAnnouncements[1].isDismissed)
}
}
| lgpl-3.0 |
Lweek/Formulary | Formulary/Input/Validation.swift | 1 | 2383 | //
// Validation.swift
// Formulary
//
// Created by Fabian Canas on 1/21/15.
// Copyright (c) 2015 Fabian Canas. All rights reserved.
//
import Foundation
public typealias Validation = (String?) -> (valid: Bool, reason: String)
public let PermissiveValidation: Validation = { _ in (true, "")}
public let RequiredString: (String) -> Validation = { name in
{ value in
if value == nil {
return (false, "\(name) can't be empty")
}
if let text = value {
if text.isEmpty {
return (false, "\(name) can't be empty")
}
return (true, "")
}
return (false, "\(name) must be a String")
}
}
private extension String {
func toDouble() -> Double? {
let trimmedValue = (self as NSString).stringByTrimmingCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)
return self == trimmedValue ? (self as NSString).doubleValue : nil
}
}
public let MinimumNumber: (String, Int) -> Validation = { name, min in
{ value in
if let value = value {
if let number = value.toDouble() {
if number < Double(min) {
return (false, "\(name) must be at least \(min)")
}
return (true, "")
}
} else {
return (false, "\(name) must be at least \(min)")
}
return (false, "\(name) must be a number")
}
}
public let MaximumNumber: (String, Int) -> Validation = { name, max in
{ value in
if let value = value {
if let number = value.toDouble() {
if number > Double(max) {
return (false, "\(name) must be at most \(max)")
}
return (true, "")
}
} else {
return (false, "\(name) must be at most \(max)")
}
return (false, "\(name) must be a number")
}
}
public func && (lhs: Validation, rhs: Validation) -> Validation {
return { value in
let lhsr = lhs(value)
if !lhsr.valid {
return lhsr
}
let rhsr = rhs(value)
if !rhsr.valid {
return rhsr
}
return (true, "")
}
}
| mit |
Authman2/Pix | Pix/ProfilePage.swift | 1 | 12696 | //
// ProfilePage.swift
// Pix
//
// Created by Adeola Uthman on 12/23/16.
// Copyright © 2016 Adeola Uthman. All rights reserved.
//
import UIKit
import Foundation
import SnapKit
import Firebase
import PullToRefreshSwift
import OneSignal
import IGListKit
class ProfilePage: ProfileDisplayPage, IGListAdapterDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
/********************************
*
* VARIABLES
*
********************************/
/* The adapter. */
lazy var adapter: IGListAdapter = {
return IGListAdapter(updater: IGListAdapterUpdater(), viewController: self, workingRangeSize: 1);
}();
/* The collection view. */
let collectionView: IGListCollectionView = {
let layout = IGListGridCollectionViewLayout();
let view = IGListCollectionView(frame: CGRect.zero, collectionViewLayout: layout);
view.alwaysBounceVertical = true;
return view;
}();
/* The image view that displays the profile picture. */
let profilePicture: CircleImageView = {
let i = CircleImageView();
i.translatesAutoresizingMaskIntoConstraints = false;
i.isUserInteractionEnabled = true;
i.backgroundColor = UIColor.gray;
return i;
}();
/* A label to display whether or not this user is private. */
let privateLabel: UILabel = {
let a = UILabel();
a.translatesAutoresizingMaskIntoConstraints = false;
a.isUserInteractionEnabled = false;
a.font = UIFont(name: a.font.fontName, size: 15);
a.numberOfLines = 0;
a.textColor = UIColor(red: 21/255, green: 180/255, blue: 133/255, alpha: 1).lighter();
a.textAlignment = .center;
a.isHidden = true;
return a;
}();
/* Label that shows the user's name. */
let nameLabel: UILabel = {
let n = UILabel();
n.translatesAutoresizingMaskIntoConstraints = false;
n.isUserInteractionEnabled = false;
n.font = UIFont(name: n.font.fontName, size: 20);
n.textColor = UIColor.black;
n.textAlignment = .center;
return n;
}();
/* Label that shows the number of followers this user has. */
let followersLabel: UILabel = {
let n = UILabel();
n.translatesAutoresizingMaskIntoConstraints = false;
n.isUserInteractionEnabled = false;
n.font = UIFont(name: n.font.fontName, size: 15);
n.textColor = UIColor.black;
n.textAlignment = .center;
return n;
}();
/* Label that shows the number of people this user is following. */
let followingLabel: UILabel = {
let n = UILabel();
n.translatesAutoresizingMaskIntoConstraints = false;
n.isUserInteractionEnabled = false;
n.font = UIFont(name: n.font.fontName, size: 15);
n.textColor = UIColor.black;
n.textAlignment = .center;
return n;
}();
/* The button used for editing the profile. */
var editProfileButton: UIBarButtonItem!;
/* Image picker */
let imgPicker = UIImagePickerController();
var canChangeProfilePic = false;
var tap: UITapGestureRecognizer!;
/* Firebase reference. */
let fireRef: FIRDatabaseReference = FIRDatabase.database().reference();
/********************************
*
* METHODS
*
********************************/
override func viewDidLoad() {
super.viewDidLoad();
view.backgroundColor = UIColor(red: 239/255, green: 255/255, blue:245/255, alpha: 1);
navigationController?.navigationBar.isHidden = false;
navigationItem.hidesBackButton = true;
navigationItem.title = "Profile";
viewcontrollerName = "Profile";
setupCollectionView();
view.addSubview(collectionView)
/* Setup/Layout the view. */
view.addSubview(privateLabel);
view.addSubview(profilePicture);
view.addSubview(nameLabel);
view.addSubview(followersLabel);
view.addSubview(followingLabel);
profilePicture.snp.makeConstraints { (maker: ConstraintMaker) in
maker.centerX.equalTo(view.snp.centerX);
maker.bottom.equalTo(view.snp.centerY).offset(-100);
maker.width.equalTo(90);
maker.height.equalTo(90);
}
privateLabel.snp.makeConstraints { (maker: ConstraintMaker) in
maker.centerX.equalTo(view.snp.centerX);
maker.bottom.equalTo(profilePicture.snp.top).offset(-10);
maker.width.equalTo(view.width);
maker.height.equalTo(50);
}
nameLabel.snp.makeConstraints { (maker: ConstraintMaker) in
maker.centerX.equalTo(view.snp.centerX);
maker.width.equalTo(view.width);
maker.height.equalTo(25);
maker.top.equalTo(profilePicture.snp.bottom).offset(20);
}
followersLabel.snp.makeConstraints { (maker: ConstraintMaker) in
maker.centerX.equalTo(view.snp.centerX);
maker.width.equalTo(view.width);
maker.height.equalTo(20);
maker.top.equalTo(nameLabel.snp.bottom).offset(10);
}
followingLabel.snp.makeConstraints { (maker: ConstraintMaker) in
maker.centerX.equalTo(view.snp.centerX);
maker.width.equalTo(view.width);
maker.height.equalTo(20);
maker.top.equalTo(followersLabel.snp.bottom).offset(5);
}
collectionView.snp.makeConstraints({ (maker: ConstraintMaker) in
maker.width.equalTo(view.frame.width);
maker.centerX.equalTo(view);
maker.top.equalTo(followingLabel.snp.bottom).offset(10);
maker.bottom.equalTo(view.snp.bottom);
})
/* Add the pull to refresh function. */
var options = PullToRefreshOption();
options.fixedSectionHeader = false;
collectionView.addPullRefresh(options: options, refreshCompletion: { (Void) in
//self.adapter.performUpdates(animated: true, completion: nil);
self.adapter.reloadData(completion: { (b: Bool) in
self.reloadLabels();
self.collectionView.stopPullRefreshEver();
})
});
/* Bar button item. */
editProfileButton = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editProfile));
editProfileButton.tintColor = .white;
navigationItem.rightBarButtonItem = editProfileButton;
/* Profile pic image picker. */
imgPicker.delegate = self;
imgPicker.sourceType = .photoLibrary;
tap = UITapGestureRecognizer(target: self, action: #selector(uploadProfilePic));
profilePicture.addGestureRecognizer(tap);
} // End of viewDidLoad().
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated);
lastProfile = self;
self.adapter.reloadData(completion: nil);
editProfileButton.isEnabled = true;
editProfileButton.tintColor = .white;
self.reloadLabels();
profilePicture.addGestureRecognizer(tap);
} // End of viewDidAppear().
func reloadLabels() {
if let cUser = Networking.currentUser {
nameLabel.text = "\(cUser.firstName) \(cUser.lastName)";
followersLabel.text = "Followers: \(cUser.followers.count)";
followingLabel.text = "Following: \(cUser.following.count)";
profilePicture.image = cUser.profilepic;
privateLabel.text = "\(cUser.username) is private. Send a follow request to see their photos.";
privateLabel.isHidden = true;
collectionView.isHidden = false;
profilePicture.image = cUser.profilepic;
}
}
@objc func logout() {
do {
try FIRAuth.auth()?.signOut();
Networking.currentUser = nil;
feedPage.followingUsers.removeAll();
feedPage.postFeed.removeAll();
explorePage.listOfUsers.removeAll();
explorePage.listOfUsers_fb.removeAllObjects();
let _ = navigationController?.popToRootViewController(animated: true);
self.debug(message: "Signed out!");
self.debug(message: "Logged out!");
} catch {
self.debug(message: "There was a problem signing out.");
}
}
@objc func editProfile() {
navigationController?.pushViewController(EditProfilePage(), animated: true);
}
/********************************
*
* IMAGE PICKER
*
********************************/
@objc func uploadProfilePic() {
show(imgPicker, sender: self);
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let photo = info[UIImagePickerControllerOriginalImage] as? UIImage {
// Set the picture on the image view and also on the actual user object.
profilePicture.image = photo;
let id = Networking.currentUser!.profilePicName;
Networking.currentUser!.profilepic = photo;
// Delete the old picture from firebase, and replace it with the new one, but keep the same id.
let storageRef = FIRStorageReference().child("\(Networking.currentUser!.uid)/\(id!).jpg");
storageRef.delete { error in
// If there's an error.
if let error = error {
self.debug(message: "There was an error deleting the image: \(error)");
} else {
// Save the new image.
let data = UIImageJPEGRepresentation(photo, 100) as NSData?;
let _ = storageRef.put(data! as Data, metadata: nil) { (metaData, error) in
if (error == nil) {
let post = Post(photo: photo, caption: "", Uploader: Networking.currentUser!, ID: id!);
post.isProfilePicture = true;
let postObj = post.toDictionary();
Networking.saveObject(object: postObj, path: "Photos/\(Networking.currentUser!.uid)/\(id!)", success: {
}, failure: { (err: Error) in
});
// self.fireRef.child("Photos").child("\(Networking.currentUser!.uid)").child("\(id!)").setValue(postObj);
self.debug(message: "Old profile picture was removed; replace with new one.");
} else {
print(error.debugDescription);
}
}
}
}
// Dismiss view controller.
imgPicker.dismiss(animated: true, completion: nil);
}
}
/********************************
*
* COLLECTION VIEW
*
********************************/
func setupCollectionView() {
collectionView.register(ProfilePageCell.self, forCellWithReuseIdentifier: "Cell");
collectionView.backgroundColor = view.backgroundColor;
adapter.collectionView = collectionView;
adapter.dataSource = self;
}
func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] {
if let cUser = Networking.currentUser {
return cUser.posts;
} else {
return [];
}
}
func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController {
return ProfileSectionController(vc: self);
}
func emptyView(for listAdapter: IGListAdapter) -> UIView? {
return EmptyPhotoView(place: .top);
}
}
| gpl-3.0 |
Ethenyl/JAMFKit | JamfKit/Tests/Models/ScriptTests.swift | 1 | 4797 | //
// Copyright © 2017-present JamfKit. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
import XCTest
@testable import JamfKit
class ScriptTests: XCTestCase {
// MARK: - Constants
let subfolder = "Script/"
let defaultIdentifier: UInt = 12345
let defaultName = "Script"
let defaultCategory = "None"
let defaultFilename = "filename"
let defaultInformation = "Script information"
let defaultNotes = "Script to decrypt FV2 encrypted drives"
let defaultPriority = "Before"
let defaultParameters: [String: String] = [
"parameter4": "string",
"parameter5": "string",
"parameter6": "string",
"parameter7": "string",
"parameter8": "string",
"parameter9": "string",
"parameter10": "string",
"parameter11": "string"
]
let defaultOsRequirements = "requirements"
let defaultScriptContents = "echo \"Sample script\""
let defaultScriptEncodedContents = "encoded"
// MARK: - Tests
func testShouldInstantiate() {
let actualValue = Script(identifier: defaultIdentifier, name: defaultName)
XCTAssertNotNil(actualValue)
XCTAssertEqual(actualValue?.identifier, defaultIdentifier)
XCTAssertEqual(actualValue?.name, defaultName)
}
func testShouldNotInstantiateWithInvalidParameters() {
let actualValue = Script(identifier: defaultIdentifier, name: "")
XCTAssertNil(actualValue)
}
func testShouldInitializeFromJSON() {
let payload = self.payload(for: "script_valid", subfolder: subfolder)!
let actualValue = Script(json: payload)
XCTAssertNotNil(actualValue)
XCTAssertEqual(actualValue?.identifier, defaultIdentifier)
XCTAssertEqual(actualValue?.name, defaultName)
XCTAssertEqual(actualValue?.description, "[Script][\(defaultIdentifier) - \(defaultName)]")
XCTAssertEqual(actualValue?.category, defaultCategory)
XCTAssertEqual(actualValue?.filename, defaultFilename)
XCTAssertEqual(actualValue?.information, defaultInformation)
XCTAssertEqual(actualValue?.notes, defaultNotes)
XCTAssertEqual(actualValue?.priority, defaultPriority)
XCTAssertEqual(actualValue?.parameters.count, defaultParameters.count)
XCTAssertEqual(actualValue?.osRequirements, defaultOsRequirements)
XCTAssertEqual(actualValue?.scriptContents, defaultScriptContents)
XCTAssertEqual(actualValue?.scriptEncodedContents, defaultScriptEncodedContents)
}
func testShouldInitializeFromIncompleteJSON() {
let payload = self.payload(for: "script_incomplete", subfolder: subfolder)!
let actualValue = Script(json: payload)
XCTAssertNotNil(actualValue)
XCTAssertEqual(actualValue?.identifier, defaultIdentifier)
XCTAssertEqual(actualValue?.name, defaultName)
XCTAssertEqual(actualValue?.description, "[Script][\(defaultIdentifier) - \(defaultName)]")
XCTAssertEqual(actualValue?.category, "")
XCTAssertEqual(actualValue?.filename, "")
XCTAssertEqual(actualValue?.information, "")
XCTAssertEqual(actualValue?.notes, "")
XCTAssertEqual(actualValue?.priority, "")
XCTAssertEqual(actualValue?.parameters.count, 0)
XCTAssertEqual(actualValue?.osRequirements, "")
XCTAssertEqual(actualValue?.scriptContents, "")
XCTAssertEqual(actualValue?.scriptEncodedContents, "")
}
func testShouldNotInitializeFromInvalidJSON() {
let payload = self.payload(for: "script_invalid", subfolder: subfolder)!
let actualValue = Script(json: payload)
XCTAssertNil(actualValue)
}
func testShouldEncodeToJSON() {
let payload = self.payload(for: "script_valid", subfolder: subfolder)!
let actualValue = Script(json: payload)
let encodedObject = actualValue?.toJSON()
XCTAssertNotNil(encodedObject)
XCTAssertEqual(encodedObject?.count, 11)
XCTAssertNotNil(encodedObject?[BaseObject.CodingKeys.identifier.rawValue])
XCTAssertNotNil(encodedObject?[BaseObject.CodingKeys.name.rawValue])
XCTAssertNotNil(encodedObject?[Script.CategoryKey])
XCTAssertNotNil(encodedObject?[Script.FilenameKey])
XCTAssertNotNil(encodedObject?[Script.InfoKey])
XCTAssertNotNil(encodedObject?[Script.NotesKey])
XCTAssertNotNil(encodedObject?[Script.PriorityKey])
XCTAssertNotNil(encodedObject?[Script.ParametersKey])
XCTAssertNotNil(encodedObject?[Script.OSRequirementsKey])
XCTAssertNotNil(encodedObject?[Script.ScriptContentsKey])
XCTAssertNotNil(encodedObject?[Script.ScriptContentsEncodedKey])
}
}
| mit |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/LayerContainers/AnimationContainer.swift | 1 | 6066 | //
// AnimationContainer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/24/19.
//
import Foundation
import QuartzCore
/**
The base animation container.
This layer holds a single composition container and allows for animation of
the currentFrame property.
*/
final class AnimationContainer: CALayer {
/// The animatable Current Frame Property
@NSManaged var currentFrame: CGFloat
var imageProvider: AnimationImageProvider {
get {
return layerImageProvider.imageProvider
}
set {
layerImageProvider.imageProvider = newValue
}
}
func reloadImages() {
layerImageProvider.reloadImages()
}
var renderScale: CGFloat = 1 {
didSet {
animationLayers.forEach({ $0.renderScale = renderScale })
}
}
public var respectAnimationFrameRate: Bool = false
/// Forces the view to update its drawing.
func forceDisplayUpdate() {
animationLayers.forEach( { $0.displayWithFrame(frame: currentFrame, forceUpdates: true) })
}
func logHierarchyKeypaths() {
print("Lottie: Logging Animation Keypaths")
animationLayers.forEach({ $0.logKeypaths(for: nil) })
}
func setValueProvider(_ valueProvider: AnyValueProvider, keypath: AnimationKeypath) {
for layer in animationLayers {
if let foundProperties = layer.nodeProperties(for: keypath) {
for property in foundProperties {
property.setProvider(provider: valueProvider)
}
layer.displayWithFrame(frame: presentation()?.currentFrame ?? currentFrame, forceUpdates: true)
}
}
}
func getValue(for keypath: AnimationKeypath, atFrame: CGFloat?) -> Any? {
for layer in animationLayers {
if let foundProperties = layer.nodeProperties(for: keypath),
let first = foundProperties.first {
return first.valueProvider.value(frame: atFrame ?? currentFrame)
}
}
return nil
}
func layer(for keypath: AnimationKeypath) -> CALayer? {
for layer in animationLayers {
if let foundLayer = layer.layer(for: keypath) {
return foundLayer
}
}
return nil
}
func animatorNodes(for keypath: AnimationKeypath) -> [AnimatorNode]? {
var results = [AnimatorNode]()
for layer in animationLayers {
if let nodes = layer.animatorNodes(for: keypath) {
results.append(contentsOf: nodes)
}
}
if results.count == 0 {
return nil
}
return results
}
var textProvider: AnimationTextProvider {
get { return layerTextProvider.textProvider }
set { layerTextProvider.textProvider = newValue }
}
var animationLayers: ContiguousArray<CompositionLayer>
fileprivate let layerImageProvider: LayerImageProvider
fileprivate let layerTextProvider: LayerTextProvider
init(animation: Animation, imageProvider: AnimationImageProvider, textProvider: AnimationTextProvider) {
self.layerImageProvider = LayerImageProvider(imageProvider: imageProvider, assets: animation.assetLibrary?.imageAssets)
self.layerTextProvider = LayerTextProvider(textProvider: textProvider)
self.animationLayers = []
super.init()
bounds = animation.bounds
let layers = animation.layers.initializeCompositionLayers(assetLibrary: animation.assetLibrary, layerImageProvider: layerImageProvider, textProvider: textProvider, frameRate: CGFloat(animation.framerate))
var imageLayers = [ImageCompositionLayer]()
var textLayers = [TextCompositionLayer]()
var mattedLayer: CompositionLayer? = nil
for layer in layers.reversed() {
layer.bounds = bounds
animationLayers.append(layer)
if let imageLayer = layer as? ImageCompositionLayer {
imageLayers.append(imageLayer)
}
if let textLayer = layer as? TextCompositionLayer {
textLayers.append(textLayer)
}
if let matte = mattedLayer {
/// The previous layer requires this layer to be its matte
matte.matteLayer = layer
mattedLayer = nil
continue
}
if let matte = layer.matteType,
(matte == .add || matte == .invert) {
/// We have a layer that requires a matte.
mattedLayer = layer
}
addSublayer(layer)
}
layerImageProvider.addImageLayers(imageLayers)
layerImageProvider.reloadImages()
layerTextProvider.addTextLayers(textLayers)
layerTextProvider.reloadTexts()
setNeedsDisplay()
}
/// For CAAnimation Use
public override init(layer: Any) {
self.animationLayers = []
self.layerImageProvider = LayerImageProvider(imageProvider: BlankImageProvider(), assets: nil)
self.layerTextProvider = LayerTextProvider(textProvider: DefaultTextProvider())
super.init(layer: layer)
guard let animationLayer = layer as? AnimationContainer else { return }
currentFrame = animationLayer.currentFrame
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: CALayer Animations
override public class func needsDisplay(forKey key: String) -> Bool {
if key == "currentFrame" {
return true
}
return super.needsDisplay(forKey: key)
}
override public func action(forKey event: String) -> CAAction? {
if event == "currentFrame" {
let animation = CABasicAnimation(keyPath: event)
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
animation.fromValue = self.presentation()?.currentFrame
return animation
}
return super.action(forKey: event)
}
public override func display() {
guard Thread.isMainThread else { return }
var newFrame: CGFloat = self.presentation()?.currentFrame ?? self.currentFrame
if respectAnimationFrameRate {
newFrame = floor(newFrame)
}
animationLayers.forEach( { $0.displayWithFrame(frame: newFrame, forceUpdates: false) })
}
}
fileprivate class BlankImageProvider: AnimationImageProvider {
func imageForAsset(asset: ImageAsset) -> CGImage? {
return nil
}
}
| mit |
zmian/xcore.swift | Sources/Xcore/Cocoa/Animations/TransitionAnimator.swift | 1 | 2729 | //
// Xcore
// Copyright © 2016 Xcore
// MIT license, see LICENSE file for details
//
import UIKit
public enum AnimationDirection {
case `in`
case out
}
public enum AnimationState {
case began
case cancelled
case ended
}
open class TransitionContext {
public let context: UIViewControllerContextTransitioning
public let to: UIViewController
public let from: UIViewController
public let containerView: UIView
public init?(transitionContext: UIViewControllerContextTransitioning) {
guard
let to = transitionContext.viewController(forKey: .to),
let from = transitionContext.viewController(forKey: .from)
else {
return nil
}
self.context = transitionContext
self.to = to
self.from = from
self.containerView = transitionContext.containerView
}
open func completeTransition() {
context.completeTransition(!context.transitionWasCancelled)
}
}
open class TransitionAnimator: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
open var direction: AnimationDirection = .in
// MARK: - UIViewControllerTransitioningDelegate
open func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
direction = .in
return self
}
open func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
direction = .out
return self
}
// MARK: - UIViewControllerAnimatedTransitioning
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let context = TransitionContext(transitionContext: transitionContext) else {
return transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
// Orientation bug fix
// SeeAlso: http://stackoverflow.com/a/20061872/351305
context.from.view.frame = context.containerView.bounds
context.to.view.frame = context.containerView.bounds
if direction == .in {
// Add destination view to container
context.containerView.addSubview(context.to.view)
}
transition(context: context, direction: direction)
}
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
fatalError(because: .subclassMustImplement)
}
open func transition(context: TransitionContext, direction: AnimationDirection) {
fatalError(because: .subclassMustImplement)
}
}
| mit |
rickzonhagos/CirrenaFramework | Pod/Classes/BaseViewController/BaseViewController.swift | 1 | 502 | //
// BaseViewController.swift
// CirrenaFramewok
//
// Created by Cirrena on 19/10/2015.
// Copyright © 2015 Cirrena. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
moosichu/hac-website | Sources/HaCWebsiteLib/Views/Workshops/WorkshopsIndexPage/WorkshopsIndexArchive.swift | 2 | 684 | import HaCTML
/// Above-the-fold for the WorkshopsIndexPage
struct WorkshopsIndexArchive: Nodeable {
let workshops: [Workshop]
var node: Node {
return El.Div[Attr.className => "WorkshopsIndexPage__archive"].containing(
El.H2[Attr.className => "Text--sectionHeading"].containing("Browse Workshops"),
El.Ul[Attr.className => "WorkshopsIndexPage__archive__list"].containing(
workshops.map { workshop in
El.Li.containing(
El.A[Attr.href => "/workshops/\(workshop.workshopId)", Attr.className => "WorkshopsIndexPage__archive__list__item"].containing(
workshop.title
)
)
}
)
)
}
}
| mit |
rafalwojcik/WRUserSettings | WRUserSettings/WRUserSettings.swift | 1 | 6512 | //
// Copyright (c) 2019 Chilli Coder - Rafał Wójcik
//
// 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
public protocol SharedInstanceType: class {
init(classType: AnyClass)
func clearInstances()
}
private var userSettingsSingletons = [String: SharedInstanceType]()
extension SharedInstanceType {
public static var shared: Self {
let className = String(describing: self)
guard let singleton = userSettingsSingletons[className] as? Self else {
let singleton = Self.init(classType: self)
userSettingsSingletons[className] = singleton
return singleton
}
return singleton
}
public func clearInstances() {
userSettingsSingletons = [:]
}
}
@objcMembers
open class WRUserSettings: NSObject, SharedInstanceType {
typealias Property = String
private var migrationUserDefaultKey: String { return "MigrationKey-\(uniqueIdentifierKey)" }
private let childClassName: String
private var uniqueIdentifierKey: String { return "\(childClassName)-WRUserSettingsIdentifier" }
private var userDefaults = UserDefaults.standard
private var defaultValues: [String: Data] = [:]
required public init(classType: AnyClass) {
childClassName = String(describing: classType)
super.init()
if let suiteName = suiteName(), let newUserDefaults = UserDefaults(suiteName: suiteName) {
migrateIfNeeded(from: userDefaults, to: newUserDefaults)
userDefaults = newUserDefaults
}
let mirror = Mirror(reflecting: self)
for attr in mirror.children {
guard let property = attr.label else { continue }
saveDefaultValue(property)
fillProperty(property)
observe(property: property)
}
}
deinit {
let mirror = Mirror(reflecting: self)
for attr in mirror.children {
guard let property = attr.label else { continue }
self.removeObserver(self, forKeyPath: property)
}
}
private func userDefaultsKey(forProperty property: Property) -> String {
return "\(uniqueIdentifierKey).\(property)"
}
private func saveDefaultValue(_ property: Property) {
guard let object = self.value(forKeyPath: property) else { return }
let archivedObject = try? NSKeyedArchiver.data(object: object)
defaultValues[property] = archivedObject
}
private func fillProperty(_ property: Property) {
if let data = userDefaults.object(forKey: userDefaultsKey(forProperty: property)) as? Data {
let value = NSKeyedUnarchiver.object(data: data)
self.setValue(value, forKey: property)
}
}
private func observe(property: Property) {
self.addObserver(self, forKeyPath: property, options: [.new], context: nil)
}
open func suiteName() -> String? { return nil }
private func migrateIfNeeded(from: UserDefaults, to: UserDefaults) {
guard !from.bool(forKey: migrationUserDefaultKey) else { return }
for (key, value) in from.dictionaryRepresentation() where key.hasPrefix(uniqueIdentifierKey) {
to.set(value, forKey: key)
from.removeObject(forKey: key)
}
guard to.synchronize() else { return }
from.set(true, forKey: migrationUserDefaultKey)
from.synchronize()
}
}
// MARK: Public methods
extension WRUserSettings {
public func reset() {
for (property, defaultValue) in defaultValues {
let value = NSKeyedUnarchiver.object(data: defaultValue)
self.setValue(value, forKey: property)
}
}
}
// MARK: Description
extension WRUserSettings {
override open var description: String {
var settings = [String: Any]()
for (key, value) in userDefaults.dictionaryRepresentation() where key.hasPrefix(uniqueIdentifierKey) {
guard let data = value as? Data else { continue }
let newKey = key.replacingOccurrences(of: "\(uniqueIdentifierKey).", with: "")
let object = NSKeyedUnarchiver.object(data: data)
settings[newKey] = object
}
return settings.description
}
}
// MARK: KVO
extension WRUserSettings {
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let keyPath = keyPath else { return }
let usKey = userDefaultsKey(forProperty: keyPath)
guard let object = self.value(forKeyPath: keyPath) else {
userDefaults.removeObject(forKey: usKey)
return
}
let archivedObject = try? NSKeyedArchiver.data(object: object)
userDefaults.set(archivedObject, forKey: usKey)
userDefaults.synchronize()
}
}
private extension NSKeyedUnarchiver {
class func object(data: Data) -> Any? {
if #available(iOS 11.0, macOS 10.12, *) {
return (try? self.unarchiveTopLevelObjectWithData(data)) ?? nil
} else {
return self.unarchiveObject(with: data)
}
}
}
private extension NSKeyedArchiver {
class func data(object: Any) throws -> Data {
if #available(iOS 11.0, macOS 10.12, *) {
return try self.archivedData(withRootObject: object, requiringSecureCoding: false)
} else {
return self.archivedData(withRootObject: object)
}
}
}
| mit |
ozgur/AutoLayoutAnimation | UserDataSource.swift | 1 | 2156 | //
// UserDataSource.swift
// AutoLayoutAnimation
//
// Created by Ozgur Vatansever on 10/25/15.
// Copyright © 2015 Techshed. All rights reserved.
//
import UIKit
import AddressBook
class UserDataSource {
fileprivate var users = [User]()
var count: Int {
return users.count
}
subscript(index: Int) -> User {
return users[index]
}
func addUser(_ user: User) -> Bool {
if users.contains(user) {
return false
}
users.append(user)
return true
}
func removeUser(_ user: User) -> Bool {
guard let index = users.index(of: user) else {
return false
}
users.remove(at: index)
return true
}
func loadUsersFromPlist(named: String) -> [User]? {
let mainBundle = Bundle.main
guard let path = mainBundle.path(forResource: named, ofType: "plist"),
content = NSArray(contentsOfFile: path) as? [[String: String]] else {
return nil
}
users = content.map { (dict) -> User in
return User(data: dict)
}
return users
}
}
class User: NSObject {
var firstName: String
var lastName: String
var userId: Int
var city: String
var fullName: String {
let record = ABPersonCreate().takeRetainedValue() as ABRecordRef
ABRecordSetValue(record, kABPersonFirstNameProperty, firstName, nil)
ABRecordSetValue(record, kABPersonLastNameProperty, lastName, nil)
guard let name = ABRecordCopyCompositeName(record)?.takeRetainedValue() else {
return ""
}
return name as String
}
override var description: String {
return "<User: \(fullName)>"
}
init(firstName: String, lastName: String, userId: Int, city: String) {
self.firstName = firstName
self.lastName = lastName
self.userId = userId
self.city = city
}
convenience init(data: [String: String]) {
let firstName = data["firstname"]!
let lastName = data["lastname"]!
let userId = Int(data["id"]!)!
let city = data["city"]!
self.init(firstName: firstName, lastName: lastName, userId: userId, city: city)
}
}
func ==(lhs: User, rhs: User) -> Bool {
return lhs.userId == rhs.userId
}
| mit |
chrisjmendez/swift-exercises | Walkthroughs/MyPresentation/Carthage/Checkouts/Presentation/Source/PresentationController.swift | 1 | 5229 | import UIKit
import Pages
@objc public protocol PresentationControllerDelegate {
func presentationController(
presentationController: PresentationController,
didSetViewController viewController: UIViewController,
atPage page: Int)
}
public class PresentationController: PagesController {
public weak var presentationDelegate: PresentationControllerDelegate?
public var maxAnimationDelay: Double = 3
private var backgroundContents = [Content]()
private var slides = [SlideController]()
private var animationsForPages = [Int : [Animatable]]()
private var animationIndex = 0
private weak var scrollView: UIScrollView?
var animationTimer: NSTimer?
public convenience init(pages: [UIViewController]) {
self.init(
transitionStyle: .Scroll,
navigationOrientation: .Horizontal,
options: nil)
add(pages)
}
// MARK: - View lifecycle
public override func viewDidLoad() {
pagesDelegate = self
super.viewDidLoad()
}
public override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
for subview in view.subviews{
if subview.isKindOfClass(UIScrollView) {
scrollView = subview as? UIScrollView
scrollView?.delegate = self
}
}
animateAtIndex(0, perform: { animation in
animation.play()
})
}
// MARK: - Public methods
public override func goTo(index: Int) {
startAnimationTimer()
super.goTo(index)
if index >= 0 && index < pagesCount {
let reverse = index < animationIndex
if !reverse {
animationIndex = index
}
for slide in slides {
if reverse {
slide.goToLeft()
} else {
slide.goToRight()
}
}
scrollView?.delegate = nil
animateAtIndex(animationIndex, perform: { animation in
if reverse {
animation.playBack()
} else {
animation.play()
}
})
}
}
// MARK: - Animation Timer
func startAnimationTimer() {
stopAnimationTimer()
scrollView?.userInteractionEnabled = false
if animationTimer == nil {
dispatch_async(dispatch_get_main_queue()) {
self.animationTimer = NSTimer.scheduledTimerWithTimeInterval(self.maxAnimationDelay,
target: self,
selector: "updateAnimationTimer:",
userInfo: nil,
repeats: false)
NSRunLoop.currentRunLoop().addTimer(self.animationTimer!, forMode: NSRunLoopCommonModes)
}
}
}
func stopAnimationTimer() {
animationTimer?.invalidate()
animationTimer = nil
}
func updateAnimationTimer(timer: NSTimer) {
stopAnimationTimer()
scrollView?.userInteractionEnabled = true
}
}
// MARK: - Content
extension PresentationController {
public override func add(viewControllers: [UIViewController]) {
for controller in viewControllers {
if controller is SlideController {
slides.append((controller as! SlideController))
}
}
super.add(viewControllers)
}
public func addToBackground(elements: [Content]) {
for content in elements {
backgroundContents.append(content)
view.addSubview(content.view)
view.sendSubviewToBack(content.view)
content.layout()
}
}
}
// MARK: - Animations
extension PresentationController {
public func addAnimations(animations: [Animatable], forPage page: Int) {
for animation in animations {
addAnimation(animation, forPage: page)
}
}
public func addAnimation(animation: Animatable, forPage page: Int) {
if animationsForPages[page] == nil {
animationsForPages[page] = []
}
animationsForPages[page]?.append(animation)
}
private func animateAtIndex(index: Int, perform: (animation: Animatable) -> Void) {
if let animations = animationsForPages[index] {
for animation in animations {
perform(animation: animation)
}
}
}
}
// MARK: - PagesControllerDelegate
extension PresentationController: PagesControllerDelegate {
public func pageViewController(pageViewController: UIPageViewController,
setViewController viewController: UIViewController, atPage page: Int) {
animationIndex = page
scrollView?.delegate = self
presentationDelegate?.presentationController(self,
didSetViewController: viewController,
atPage: page)
}
}
// MARK: - UIScrollViewDelegate
extension PresentationController: UIScrollViewDelegate {
public func scrollViewDidScroll(scrollView: UIScrollView) {
let offset = scrollView.contentOffset.x - CGRectGetWidth(view.frame)
let offsetRatio = offset / CGRectGetWidth(view.frame)
var index = animationIndex
if offsetRatio > 0.0 || index == 0 {
index++
}
let canMove = offsetRatio != 0.0 &&
!(animationIndex == 0 && offsetRatio < 0.0) &&
!(index == pagesCount)
if canMove {
animateAtIndex(index, perform: { animation in
animation.moveWith(offsetRatio)
})
for slide in slides {
if index <= animationIndex {
slide.goToLeft()
} else {
slide.goToRight()
}
}
}
scrollView.layoutIfNeeded()
view.layoutIfNeeded()
}
}
| mit |
mbrandonw/learn-transducers-playground | transducers.playground/section-18.swift | 2 | 716 | func map_from_reduce <A, B> (f: A -> B) -> [A] -> [B] {
return {xs in
return xs.reduce([]) { accum, x in accum + [f(x)] }
}
}
func filter_from_reduce <A> (p: A -> Bool) -> [A] -> [A] {
return {xs in
return xs.reduce([]) { accum, x in
if p(x) {
return accum + [x]
} else {
return accum
}
}
}
}
func take_from_reduce <A> (n: Int) -> [A] -> [A] {
return {xs in
return xs.reduce([]) { accum, x in
if accum.count < n {
return accum + [x]
} else {
return accum
}
}
}
}
[1.0, 2.0, 3.0] |> map_from_reduce(sqrt)
[1.0, 2.0, 3.0, 1.0/0.0] |> filter_from_reduce(isfinite)
[1, 2, 3, 4, 5, 6, 7, 8] |> take_from_reduce(5)
| mit |
LearningSwift2/LearningApps | SimpleSegue/SimpleSegue/ViewController.swift | 1 | 1108 | //
// ColorViewController.swift
// SimpleSegue
//
// Created by Phil Wright on 3/1/16.
// Copyright © 2016 The Iron Yard. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
@IBAction func redButtonTapped(sender: AnyObject) {
label.text = "Red"
performSegueWithIdentifier("ShowColor", sender: UIColor.redColor())
}
@IBAction func greenButtonTapped(sender: AnyObject) {
label.text = "Green"
performSegueWithIdentifier("ShowColor", sender: UIColor.greenColor())
}
@IBAction func blueButtonTapped(sender: AnyObject) {
label.text = "Blue"
performSegueWithIdentifier("ShowColor", sender: UIColor.blueColor())
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowColor" {
if let destinationController = segue.destinationViewController as? ColorViewController {
destinationController.color = sender as? UIColor
}
}
}
}
| apache-2.0 |
JanNash/Swango | DjaftTests/Tests/NSManagedObjectExtensionTests/ObjectCreationTests.swift | 2 | 425 | //
// ObjectCreationTests.swift
// Djaft
//
// Created by Jan Nash on 3/10/16.
// Copyright © 2016 Jan Nash. All rights reserved.
//
import XCTest
import CoreData
@testable import Djaft
// MARK: Object Creation Tests
class ObjectCreationTests: DjaftTest {
func testCreateZoo() {
// let zoo: Zoo = Zoo.objects.create()
// XCTAssertNotNil(zoo)
// XCTAssert(zoo.dynamicType == Zoo.self)
}
}
| mit |
sammyd/Concurrency-VideoSeries | projects/006_NSOperationInPractice/006_DemoStarter/TiltShift/TiltShift/Compressor.swift | 4 | 1659 | /*
* Copyright (c) 2015 Razeware LLC
*
* 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
public struct Compressor {
public static func loadCompressedFile(path: String) -> NSData? {
return NSData(contentsOfArchive: path, compression: .LZMA)
}
public static func decompressData(data: NSData) -> NSData? {
return data.uncompressedDataUsingCompression(.LZMA)
}
public static func saveDataAsCompressedFile(data: NSData, path: String) -> Bool {
guard let compressedData = data.compressedDataUsingCompression(.LZMA) else { return false
}
return compressedData.writeToFile(path, atomically: true)
}
} | mit |
trujillo138/MyExpenses | MyExpenses/MyExpenses/Common/UI/Controls/AddExpenseButton.swift | 1 | 3873 | //
// AddExpenseButton.swift
// MyExpenses
//
// Created by Tomas Trujillo on 10/18/17.
// Copyright © 2017 TOMApps. All rights reserved.
//
import UIKit
protocol AddExpenseButtonDelegate {
func buttonWasTapped()
}
class AddExpenseButton: UIView {
//MARK: Properties
var delegate: AddExpenseButtonDelegate?
private var buttonPath: CAShapeLayer?
private var plusHorizontalPath: CAShapeLayer?
private var plusVerticalPath: CAShapeLayer?
private var strokeColor: UIColor {
return UIColor.ME_ButtonColor
}
//MARK Drawing
override func draw(_ rect: CGRect) {
buttonPath = CAShapeLayer()
plusHorizontalPath = CAShapeLayer()
plusVerticalPath = CAShapeLayer()
var buttonRect = self.bounds
buttonRect = buttonRect.insetBy(dx: 0.95, dy: 0.95)
let path = UIBezierPath(ovalIn: buttonRect)
let center = CGPoint(x: bounds.midX, y: bounds.midY)
let length = bounds.width * 2 / 3
let horizontalPath = UIBezierPath()
horizontalPath.move(to: CGPoint(x: center.x - length / 2, y: center.y))
horizontalPath.addLine(to: CGPoint(x: center.x + length / 2, y: center.y))
let verticalPath = UIBezierPath()
verticalPath.move(to: CGPoint(x: center.x, y: center.y - length / 2))
verticalPath.addLine(to: CGPoint(x: center.x, y: center.y + length / 2))
path.addClip()
buttonPath?.path = path.cgPath
plusHorizontalPath?.path = horizontalPath.cgPath
plusVerticalPath?.path = verticalPath.cgPath
buttonPath?.strokeColor = strokeColor.cgColor
buttonPath?.fillColor = UIColor.white.cgColor
buttonPath?.lineWidth = 5.0
buttonPath?.lineCap = kCALineCapRound
plusHorizontalPath?.strokeColor = strokeColor.cgColor
plusHorizontalPath?.fillColor = UIColor.clear.cgColor
plusHorizontalPath?.lineWidth = 5.0
plusHorizontalPath?.lineCap = kCALineCapRound
plusVerticalPath?.strokeColor = strokeColor.cgColor
plusVerticalPath?.fillColor = UIColor.clear.cgColor
plusVerticalPath?.lineWidth = 5.0
plusVerticalPath?.lineCap = kCALineCapRound
self.layer.addSublayer(buttonPath!)
self.layer.addSublayer(plusHorizontalPath!)
self.layer.addSublayer(plusVerticalPath!)
}
private func animateButton(){
// guard let button = buttonPath, let horizontalPath = plusHorizontalPath,
// let verticalPath = plusVerticalPath else { return }
// let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
// scaleAnimation.fromValue = 1.0
// scaleAnimation.toValue = 1.25
// scaleAnimation.isRemovedOnCompletion = true
// scaleAnimation.duration = 0.4
// button.add(scaleAnimation, forKey: "scale animation")
// horizontalPath.add(scaleAnimation, forKey: "scale animation")
// verticalPath.add(scaleAnimation, forKey: "scale animation")
}
func show() {
UIView.animate(withDuration: 0.4) {
self.alpha = 1.0
}
}
func hide() {
UIView.animate(withDuration: 0.4) {
self.alpha = 0.0
}
}
//MARK: Intialization
private func setup() {
backgroundColor = UIColor.clear
isOpaque = false
contentMode = .redraw
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tappedButton)))
}
@objc func tappedButton(tapGesture: UITapGestureRecognizer) {
animateButton()
delegate?.buttonWasTapped()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
}
| apache-2.0 |
carabina/TapGestureGenerater | TapGestureGeneraterExample/TapGestureGenerater/ViewController.swift | 1 | 7850 | //
// ViewController.swift
// TapGestureGenerater
//
// Created by ikemai on 08/21/2015.
// Copyright (c) 2015 ikemai. All rights reserved.
//
import UIKit
import TapGestureGenerater
class ViewController: UIViewController {
@IBOutlet weak var labelView: UILabel!
@IBOutlet weak var summaryLabelView: UILabel!
@IBOutlet weak var tapButton: UIButton!
@IBOutlet weak var touchButton: UIButton!
@IBOutlet weak var pinchingButton: UIButton!
@IBOutlet weak var pinchInOutButton: UIButton!
@IBOutlet weak var SwipButton: UIButton!
private var tapGestureView: TapGestureGenerater!
private let tapColor = UIColor.greenColor()
private let touchColor = UIColor.magentaColor()
private let pinchColor = UIColor.blueColor()
private let swipColor = UIColor.orangeColor()
override func viewDidLoad() {
super.viewDidLoad()
tapGestureView = TapGestureGenerater(frame: view.frame)
tapGestureView.backgroundColor = UIColor.whiteColor()
view.addSubview(tapGestureView)
view.sendSubviewToBack(tapGestureView)
labelView.text = ""
summaryLabelView.text = ""
setButton(tapButton, color: tapColor)
setButton(touchButton, color: touchColor)
setButton(pinchingButton, color: pinchColor)
setButton(pinchInOutButton, color: pinchColor)
setButton(SwipButton, color: swipColor)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func tapButtonDidDown(sender: AnyObject) {
tapGestureView.reset()
setTapGestures()
}
@IBAction func touchButtonDidDown(sender: AnyObject) {
tapGestureView.reset()
setTouchesAndDrag()
}
@IBAction func pinchingButtonDidDown(sender: AnyObject) {
tapGestureView.reset()
setPinchingGesture()
}
@IBAction func pinchInOutButtonDidDown(sender: AnyObject) {
tapGestureView.reset()
setPinchInOutGesture()
}
@IBAction func SwipButtonDidDown(sender: AnyObject) {
tapGestureView.reset()
setSwipGesture()
}
private func setButton(button: UIButton, color: UIColor) {
button.backgroundColor = color
button.layer.cornerRadius = tapButton.bounds.width / 2
button.layer.masksToBounds = true
button.layer.borderWidth = 1.0
button.layer.borderColor = UIColor.whiteColor().CGColor
}
}
//
// MARK:- Set tap gestures
//
extension ViewController {
private func setTapGestures() {
// Tap
tapGestureView.setTapGesture({[weak self] tapGestureView in
if let me = self {
me.tapGestureView.backgroundColor = me.tapColor
me.labelView.text = "Tap Gesture"
me.summaryLabelView.text = ""
}
})
// Double tap
tapGestureView.setDoubleTapGesture({[weak self] tapGestureView in
if let me = self {
me.tapGestureView.backgroundColor = me.tapColor
me.labelView.text = "Double Tap Gesture"
me.summaryLabelView.text = ""
}
})
// Triple tap
tapGestureView.setTripleTapGesture({[weak self] tapGestureView in
if let me = self {
me.tapGestureView.backgroundColor = me.tapColor
me.labelView.text = "Triple Tap Gesture"
me.summaryLabelView.text = ""
}
})
}
}
//
// MARK:- Set touches and dragging
//
extension ViewController {
private func setTouchesAndDrag() {
// Touches began
tapGestureView.setTouchesBegan({[weak self] tapGestureView, point in
if let me = self {
me.tapGestureView.backgroundColor = me.touchColor
me.labelView.text = "Touches Began"
me.summaryLabelView.text = "point = \(point)"
}
})
// Touches cancelled
tapGestureView.setTouchesCancelled({[weak self] tapGestureView, point in
if let me = self {
me.tapGestureView.backgroundColor = me.touchColor
me.labelView.text = "Touches Cancelled"
me.summaryLabelView.text = "point = \(point)"
}
})
// Touches ended
tapGestureView.setTouchesEnded({[weak self] tapGestureView, point in
if let me = self {
me.tapGestureView.backgroundColor = me.touchColor
me.labelView.text = "Touches Ended"
me.summaryLabelView.text = "point = \(point)"
}
})
// Dragging
tapGestureView.setDraggingGesture({[weak self] tapGestureView, deltaPoint in
if let me = self {
me.tapGestureView.backgroundColor = me.touchColor
me.labelView.text = "Dragging"
me.summaryLabelView.text = "deltaPoint = \(deltaPoint)"
}
})
}
}
//
// MARK:- Set pinch gestures
//
extension ViewController {
private func setPinchingGesture() {
// Pinching
tapGestureView.setPinchingGesture({[weak self] tapGestureView, sender in
if let me = self {
me.tapGestureView.backgroundColor = me.pinchColor
me.labelView.text = "Pinching Gesture"
me.summaryLabelView.text = "sender = \(sender)"
}
})
}
private func setPinchInOutGesture() {
// Pinch in
tapGestureView.setPinchInGesture({[weak self] tapGestureView, sender in
if let me = self {
me.tapGestureView.backgroundColor = me.pinchColor
me.labelView.text = "Pinch In Gesture"
me.summaryLabelView.text = "sender = \(sender)"
}
})
// Pinch out
tapGestureView.setPinchOutGesture({[weak self] tapGestureView, sender in
if let me = self {
me.tapGestureView.backgroundColor = me.pinchColor
me.labelView.text = "Pinch Out Gesture"
me.summaryLabelView.text = "sender = \(sender)"
}
})
}
}
//
// MARK:- Set swip gestures
//
extension ViewController {
private func setSwipGesture() {
// Swip to left
tapGestureView.setSwipToLeftGesture({[weak self] tapGestureView, gesture in
if let me = self {
me.tapGestureView.backgroundColor = me.swipColor
me.labelView.text = "Swip To Left"
me.summaryLabelView.text = "gesture = \(gesture)"
}
})
// Swip to right
tapGestureView.setSwipToRightGesture({[weak self] tapGestureView, gesture in
if let me = self {
me.tapGestureView.backgroundColor = me.swipColor
me.labelView.text = "Swip To Right"
me.summaryLabelView.text = "gesture = \(gesture)"
}
})
// Swip to top
tapGestureView.setSwipToUpGesture({[weak self] tapGestureView, gesture in
if let me = self {
me.tapGestureView.backgroundColor = me.swipColor
me.labelView.text = "Swip To Up"
me.summaryLabelView.text = "gesture = \(gesture)"
}
})
// Swip to down
tapGestureView.setSwipToDownGesture({[weak self] tapGestureView, gesture in
if let me = self {
me.tapGestureView.backgroundColor = me.swipColor
me.labelView.text = "Swip To Down"
me.summaryLabelView.text = "gesture = \(gesture)"
}
})
}
}
| mit |
farezhalim/learning-swift-1stormviewer | Project1StormViewer/AppDelegate.swift | 1 | 2186 | //
// AppDelegate.swift
// Project1StormViewer
//
// Created by Farez Halim on 2017-01-15.
// Copyright © 2017 Farez Halim. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
NoryCao/zhuishushenqi | zhuishushenqi/NewVersion/Comment/ZSPostReviewBook.swift | 1 | 505 | //
// Book.swift
//
// Create by 农运 on 7/8/2019
// Copyright © 2019. All rights reserved.
// 模型生成器(小波汉化)JSONExport: https://github.com/Ahmed-Ali/JSONExport
import Foundation
import HandyJSON
struct ZSPostReviewBook :HandyJSON{
var id : String = ""
var allowFree : Bool = false
var apptype : [Int] = []
var author : String = ""
var cover : String = ""
var latelyFollower : AnyObject?
var retentionRatio : AnyObject?
var safelevel : Int = 0
var title : String = ""
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/15090-swift-sourcemanager-getmessage.swift | 11 | 242 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct A {
extension Array {
var b {
end as S ( {
if true {
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/03055-swift-parser-skipsingle.swift | 11 | 264 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
case c,
let a {
{
}
}
static let h = [Void{
class
case c,
{
(([Void{
(((([Void{
((([Void{
((
| mit |
eurofurence/ef-app_ios | Packages/EurofurenceApplication/Sources/EurofurenceApplication/Application/Components/News/Component/NewsComponentFactory.swift | 1 | 537 | import EurofurenceModel
import UIKit.UIViewController
public protocol NewsComponentFactory {
func makeNewsComponent(_ delegate: any NewsComponentDelegate) -> UIViewController
}
public protocol NewsComponentDelegate {
func newsModuleDidRequestShowingPrivateMessages()
func newsModuleDidSelectAnnouncement(_ announcement: AnnouncementIdentifier)
func newsModuleDidSelectEvent(_ event: EventIdentifier)
func newsModuleDidRequestShowingAllAnnouncements()
func newsModuleDidRequestShowingSettings(sender: Any)
}
| mit |
austinzheng/swift-compiler-crashes | fixed/26777-swift-typechecker-resolveidentifiertype.swift | 7 | 207 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class C<P{let d=a func a(let a
func a
| mit |
lstanii-magnet/ChatKitSample-iOS | ChatMessenger/Pods/ChatKit/ChatKit/source/src/Helpers/Utils/Utils.swift | 1 | 13147 | /*
* Copyright (c) 2016 Magnet Systems, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import UIKit
import MagnetMax
extension UIImage {
convenience init(view: UIView) {
UIGraphicsBeginImageContext(view.frame.size)
view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.init(CGImage: image.CGImage!)
}
}
class UtilsImageOperation : MMAsyncBlockOperation {
//Mark: Public variables
var url : NSURL?
weak var imageView : UIImageView?
}
public class UtilsImageCache : UtilsCache {
//Mark: Public variables
public var maxImageCacheSize : Int = 4194304 //2^22 = 4mb
public static var sharedCache : UtilsImageCache = {
let cache = UtilsImageCache()
return cache
}()
public func setImage(image : UIImage, forURL : NSURL) {
let data = UIImagePNGRepresentation(image)
var size = 0
if let len = data?.length {
size = len
}
self.setObject(image, forURL: forURL, cost:size)
}
public func imageForUrl(url : NSURL) -> UIImage? {
return self.objectForURL(url) as? UIImage
}
}
public class Utils: NSObject {
//MARK: Private Properties
private static var queue : NSOperationQueue = {
let queue = NSOperationQueue()
queue.underlyingQueue = dispatch_queue_create("operation - images", nil)
queue.maxConcurrentOperationCount = 10
return queue
}()
//MARK: Image Loading
public static func loadImageWithUrl(url : NSURL?, toImageView: UIImageView, placeholderImage:UIImage?) {
loadImageWithUrl(url, toImageView: toImageView, placeholderImage: placeholderImage, completion: nil)
}
public static func loadImageWithUrl(url : NSURL?, toImageView: UIImageView, placeholderImage:UIImage?, onlyShowAfterDownload:Bool) {
loadImageWithUrl(url, toImageView: toImageView, placeholderImage: placeholderImage, onlyShowAfterDownload:onlyShowAfterDownload, completion: nil)
}
public static func loadImageWithUrl(url : NSURL?, toImageView: UIImageView, placeholderImage:UIImage?, completion : ((image : UIImage?)->Void)?) {
loadImageWithUrl(url, toImageView: toImageView, placeholderImage: placeholderImage, onlyShowAfterDownload: placeholderImage == nil, completion: completion)
}
public static func loadImageWithUrl(url : NSURL?, toImageView: UIImageView, placeholderImage:UIImage?, onlyShowAfterDownload:Bool, completion : ((image : UIImage?)->Void)?) {
imageWithUrl(url, toImageView: toImageView, placeholderImage: placeholderImage, onlyShowAfterDownload: onlyShowAfterDownload, completion: completion)
}
public static func loadUserAvatar(user : MMUser, toImageView: UIImageView, placeholderImage:UIImage?) {
loadImageWithUrl(user.avatarURL(), toImageView: toImageView, placeholderImage: placeholderImage)
}
public static func loadUserAvatarByUserID(userID : String, toImageView: UIImageView, placeholderImage:UIImage?) {
toImageView.image = placeholderImage
MMUser.usersWithUserIDs([userID], success: { (users) -> Void in
let user = users.first
if (user != nil) {
Utils.loadUserAvatar(user!, toImageView: toImageView, placeholderImage: placeholderImage)
}
}) { (error) -> Void in
//print("error getting users \(error)")
}
}
//MARK: User Avatar Generation
public static func firstCharacterInString(s: String) -> String {
if s == "" {
return ""
}
return s.substringWithRange(Range<String.Index>(start: s.startIndex, end: s.endIndex.advancedBy(-(s.characters.count - 1))))
}
public class func name(name: AnyClass) -> String {
let ident:String = NSStringFromClass(name).componentsSeparatedByString(".").last!
return ident
}
public static func noAvatarImageForUser(user : MMUser) -> UIImage {
return Utils.noAvatarImageForUser(user.firstName, lastName: user.lastName ?? "")
}
public static func noAvatarImageForUser(firstName : String?, lastName:String?) -> UIImage {
var fName = ""
var lName = ""
if let firstName = firstName{
fName = firstName
}
if let lastName = lastName {
lName = lastName
}
let diameter : CGFloat = 30.0 * 3
let view : UIView = UIView(frame: CGRect(x: 0, y: 0, width: diameter, height: diameter))
let lbl : UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: diameter, height: diameter))
lbl.backgroundColor = MagnetControllerAppearance.tintColor
let f = firstCharacterInString(fName).uppercaseString
let l = firstCharacterInString(lName).uppercaseString
lbl.font = UIFont.systemFontOfSize(diameter * 0.5)
lbl.text = "\(f)\(l)"
lbl.textAlignment = NSTextAlignment.Center
lbl.textColor = UIColor.whiteColor()
view.addSubview(lbl)
let image:UIImage = UIImage.init(view: view)
return image
}
public class func resizeImage(image:UIImage, toSize:CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(toSize, false, 0.0);
image.drawInRect(CGRect(x: 0, y: 0, width: toSize.width, height: toSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
//MARK: User Naming
public class func displayNameForUser(user : MMUser) -> String {
//create username
var name : String = ""
if user.firstName != nil {
name = "\(user.firstName)"
}
if user.lastName != nil {
name += (name.characters.count > 0 ? " " : "") + user.lastName
}
if name.characters.count == 0 {
name = user.userName
}
return name
}
public class func nameForUser(user : MMUser) -> String {
//create username
var name = user.userName
if user.lastName != nil {
name = user.lastName
} else if user.firstName != nil {
name = user.firstName
}
return name
}
//MARK: Private Methods
private static func imageWithUrl(url : NSURL?, toImageView: UIImageView, placeholderImage:UIImage?, onlyShowAfterDownload:Bool, completion : ((image : UIImage?)->Void)?) {
for operation in queue.operations {
if let imageOperation = operation as? UtilsImageOperation {
if imageOperation.imageView === toImageView {
imageOperation.cancel()
}
}
}
guard let imageUrl = url else {
//print("no url content data")
if !onlyShowAfterDownload {
toImageView.image = placeholderImage
}
completion?(image: nil)
return
}
if let image = UtilsImageCache.sharedCache.imageForUrl(imageUrl) {
toImageView.image = image
return
}
if !onlyShowAfterDownload {
toImageView.image = placeholderImage
}
let imageOperation = UtilsImageOperation(with: { operation in
if let imageOperation = operation as? UtilsImageOperation {
if let image = UtilsImageCache.sharedCache.imageForUrl(imageUrl) {
toImageView.image = image
return
}
var image : UIImage?
if let imageData = NSData(contentsOfURL: imageUrl) {
image = UIImage(data: imageData)
}
dispatch_async(dispatch_get_main_queue(), {
let image = imageForImageView(imageOperation, image: image, placeholderImage: placeholderImage)
completion?(image: image)
})
imageOperation.finish()
}
})
imageOperation.imageView = toImageView
imageOperation.url = url
self.queue.addOperation(imageOperation)
}
static func imageForImageView(operation : UtilsImageOperation, image : UIImage?, placeholderImage : UIImage? ) -> UIImage? {
if let url = operation.url, let img = image {
UtilsImageCache.sharedCache.setImage(img, forURL: url)
}
if !operation.cancelled {
if let img = image {
operation.imageView?.image = img
} else {
operation.imageView?.image = placeholderImage
}
}
return operation.imageView?.image
}
}
extension Array {
func findInsertionIndexForSortedArray<T : Comparable>(mappedObject : ((obj : Generator.Element) -> T), object : T) -> Int {
return self.findInsertionIndexForSortedArrayWithBlock() { (haystack) -> Bool in
return mappedObject(obj: haystack) > object
}
}
func findInsertionIndexForSortedArrayWithBlock(greaterThan GR_TH : (Generator.Element) -> Bool) -> Int {
return Array.findInsertionIndex(self) { (haystack) -> Bool in
return GR_TH(haystack)
}
}
func searchrSortedArrayWithBlock(greaterThan GR_TH : (Generator.Element) -> Bool?) -> Int? {
return Array.find(self) { (haystack) -> Bool? in
return GR_TH(haystack)
}
}
func searchrSortedArray<T : Comparable>(mappedObject : ((obj : Generator.Element) -> T), object : T) -> Int? {
return self.searchrSortedArrayWithBlock() { (haystack) -> Bool? in
let mapped = mappedObject(obj: haystack)
if mapped == object {
return nil
}
return mapped > object
}
}
static private func find(haystack : Array<Element>, greaterThan : (haystack : Generator.Element) -> Bool?) -> Int? {
//search for index of user group based on letter
if haystack.count == 0 {
return nil
}
let index = haystack.count >> 0x1
let compare = haystack[index]
let isGreater = greaterThan(haystack: compare)
if isGreater == nil {//if equal
return index
} else if let greater = isGreater where greater == true { //if greater
return find(Array(haystack[0..<index]), greaterThan : greaterThan)
}
if let rightIndex = find(Array(haystack[index + 1..<haystack.count]), greaterThan : greaterThan) {
return rightIndex + index + 1
}
return nil
}
static private func findInsertionIndex(haystack : Array<Element>, greaterThan : ((haystack : Generator.Element) -> Bool)) -> Int {
if haystack.count == 0 {
return 0
}
let index = haystack.count >> 0x1
let compare = haystack[index]
if greaterThan(haystack: compare) {
return findInsertionIndex(Array(haystack[0..<index]), greaterThan : greaterThan)
}
return findInsertionIndex(Array(haystack[index + 1..<haystack.count]), greaterThan : greaterThan) + 1 + index
}
}
extension Array where Element : Comparable {
func findInsertionIndexForSortedArray(obj : Generator.Element) -> Int {
return self.findInsertionIndexForSortedArrayWithBlock() { (haystack) -> Bool in
return haystack > obj
}
}
func searchrSortedArray(obj : Generator.Element) -> Int? {
return self.searchrSortedArrayWithBlock() { (haystack) -> Bool? in
if haystack == obj {
return nil
}
return haystack > obj
}
}
}
public class MagnetControllerAppearance {
public static var tintColor : UIColor = UIColor(hue: 210.0 / 360.0, saturation: 0.94, brightness: 1.0, alpha: 1.0)
public var tintColor : UIColor {
set {
self.dynamicType.tintColor = newValue
}
get {
return self.dynamicType.tintColor
}
}
}
| apache-2.0 |
austinzheng/swift-compiler-crashes | crashes-duplicates/08921-swift-typechecker-checksubstitutions.swift | 11 | 241 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
extension A {
}
protocol A {
var b : A
class A<S : B
class B<T : A<Int>
| mit |
WirecardMobileServices/SuprAcceptSDK-iOS | Example/Tests/SpireTests.swift | 1 | 10768 | //
// StatsTests.swift
// DemoAcceptSDK
//
// Created by Fortes, Francisco on 7/25/17.
// Copyright © 2017 Wirecard. All rights reserved.
//
import Foundation
import XCTest
import Accept
class SpireTestsSwift: BaseTestsSwift, WDAcceptManagerDelegate
{
var configCompletionStatus : AcceptUpdateConfigurationStatus!
/*
IMPORTANT NOTE:
-This test requires an actual iOS device (not simulator).
-You have to have a Spire terminal paired through your iOS device settings.
-Your terminal must have been provided by Wirecard, and be turned on.
-If your backend settings include cash management with mandatory cash registers, you will need to run CashTests first (to have valid ids)
*/
override func setUp()
{
super.setUp()
}
func testSpire()
{
#if arch(i386) || arch(x86_64)
let file:NSString = (#file as NSString).lastPathComponent as NSString
NSLog("\n\t\t [%@ %@] Not runnable on simulator 📱",file.deletingPathExtension , #function);
return
#endif
//PART 1: We log-in and request user data
//--------------------------------------
expectation = self.expectation(description: "Requesting User Data")
self.loginAndGetUserData()
self.waitForExpectations(timeout: 100, handler: nil)
if (loggedUser == nil || (loggedUser?.isKind(of: WDAcceptMerchantUser.self)) == false)
{
XCTFail("Error, did not return Merchant User. Are your credentials correct? Try login into the backend through internet browser.")
}
else
{
UserHelper.sharedInstance().setUser(loggedUser)
}
//PART 2: We discover Spire terminals
//paired to your iOS device.
//--------------------------------------
expectation = self.expectation(description: "Discovering devices")
self.discoverDevices(.WDAPosMateExtensionUUID)
self.waitForExpectations(timeout: 100, handler: nil)
if (self.selectedDevice == nil)
{
XCTFail("No paired terminal found. Make sure your terminal is paired in your iOS device settings and that the terminal is in stand-by mode (ie. by switching off and then on and waiting until the screen lights off).")
}
else
{
sdk.terminalManager.add(self, forDevice: selectedDevice!)
}
//PART 3: We check for updates on the terminal
//---------------------------------------------
expectation = self.expectation(description: "Checking for terminal update")
self.checkingForTerminalConfigUpdates()
self.waitForExpectations(timeout: 300, handler: nil)
if (self.configCompletionStatus == .failure)
{
XCTFail("Error when updating the terminal. Make sure your terminal is paired in your iOS device settings and that the terminal is in stand-by mode (ie. by switching off and then on and waiting until the screen lights off).")
}
//PART 4: We do a card sale using Spire terminal
//---------------------------------------------
expectation = self.expectation(description: "Card sale")
self.doCardPayment()
self.waitForExpectations(timeout: 300, handler: nil)
if (self.saleResponse == nil)
{
XCTFail("Sale did not succeed. Make sure your terminal is paired in your iOS device settings and that the terminal is in stand-by mode (ie. by switching off and then on and waiting until the screen lights off).")
}
else
{
SaleHelper.sharedInstance().saleToSaveId(from:self.saleResponse)
}
//PART 5: We refund the sale we just did
//(for testing purposes; this is important if you develop using an actual credit card)
//Algo note that refunds are allowed only for some period of time (ie: midnight on current time, or next 24 hours, etc) and after that, only reversals are allowed. But refunds are for free, while reversals actually cost money (so use reversals responsibly!)
//-------------------------------------------
expectation = self.expectation(description: "Refund sale")
self.refundTransaction()
self.waitForExpectations(timeout: 300, handler: nil)
if (self.saleResponse == nil || self.saleResponse?.status != .returned)
{
XCTFail("Sale did not succeed. Make sure your terminal is paired in your iOS device settings and that the terminal is in stand-by mode (ie. by switching off and then on and waiting until the screen lights off).")
}
}
func checkingForTerminalConfigUpdates()
{
let completionUpdate : UpdateTerminalCompletion = {[weak self](updStatus : AcceptUpdateConfigurationStatus?, updError : Error?) in
//Note that completion here will happen when:
// 1- The update has been completed, but also the terminal has fully restarted and entered stand-by (this may take a couple of minutes in the case of firmware)
// 2- There was no response from terminal (something went wrong) for several seconds, meaning update failed.
self?.returnedErr = updError
self?.configCompletionStatus = updStatus
self?.expectation.fulfill()
}
let progress : UpdateConfigurationProgress = {(progressUpdate : AcceptUpdateConfigurationProgressUpdate) in
print("Terminal update progress: \(progressUpdate.rawValue)")
}
//Note: You may update the firmware too using AcceptTerminalUpdateTypeFirmware
//Note: The accept SDK will keep track of what version was previously installed, and decide if an update is required by comparing with the latest in backend.
//This means, the first time you run this test, the configuration will be updated on the terminal. A second time will tell you "AcceptUpdateConfigurationStatusUnnecessary"
//To force the actual update again you will have to remove the demo app from your iOS device and re-run the test.
sdk.terminalManager.update(selectedDevice!,
updateType:AcceptTerminalUpdateTypeMaskConfiguration,
progress:progress,
completion:completionUpdate)
}
func doCardPayment()
{
let paymentConfiguration : WDAcceptPaymentConfig = WDAcceptPaymentConfig.init()
guard let sale = SaleHelper.sharedInstance().newSale() else
{
XCTFail("Something went really wrong - doCardPayment")
self.expectation.fulfill()
return
}
self.aSale = sale
self.aSale.addSaleItem(NSDecimalNumber(value: 3.4),
quantity:5,
taxRate:UserHelper.sharedInstance().preferredSaleItemTax(),
itemDescription:"Red Apple",
productId:"Dummy ID 1")
self.aSale.addSaleItem(NSDecimalNumber(value: 2.25),
quantity:3,
taxRate:UserHelper.sharedInstance().preferredSaleItemTax(),
itemDescription:"Orange",
productId:"Dummy ID 2")
//You can add a service charge to the whole basket -- but this is optional
self.aSale.addServiceCharge(UserHelper.sharedInstance().serviceChargeRate(),
taxRate:UserHelper.sharedInstance().serviceChargeTax())
//You can add a tip of any value you want. Notice that backend validate taxes, so their values should match the ones your merchant has defined in setup.
self.aSale.addGratuity(NSDecimalNumber(value: 1.0),
taxRate:UserHelper.sharedInstance().tipTax())
//You can add a discount for the whole basket when productId is nil, or per productId otherwise. Below, a discount of 6%
self.aSale.addDiscount(NSDecimalNumber(value: 6.0),
productId:nil)
paymentConfiguration.sale = self.aSale
paymentConfiguration.sale.cashRegisterId = UserHelper.sharedInstance().selectedCashRegisterId() //Note: if your backend settings have cash mgmt enabled in backend, you will need to run cash tests first to get this value as well as shiftId below
paymentConfiguration.sale.shiftId = UserHelper.sharedInstance().lastShiftId()
paymentConfiguration.sale.resetPayments()
paymentConfiguration.sale.addCardPayment(paymentConfiguration.sale.totalToPay() ?? NSDecimalNumber.init(value:0),
terminal:self.selectedDevice!)
sdk.terminalManager.setActive(self.selectedDevice, completion:{[weak self]() in
self?.sdk.saleManager.pay(paymentConfiguration, delegate: (self?.paymentHandler)!)
})
}
func refundTransaction()
{
guard let saleToBeRefunded = self.saleResponse!.saleReturn() else
{
XCTFail("Something went really wrong - refundTransaction saleReturn")
self.expectation.fulfill()
return
}
//This is an example of full refund: all items are refunded, EXCEPT SERVICE CHARGE
saleToBeRefunded.removeServiceCharge()
guard let totalToPay = saleToBeRefunded.totalToPay() else
{
XCTFail("Something went really wrong - refundTransaction totalToPay")
self.expectation.fulfill()
return
}
saleToBeRefunded.cashRegisterId = UserHelper.sharedInstance().selectedCashRegisterId()
saleToBeRefunded.cashierId = self.aSale.cashierId
saleToBeRefunded.customerId = self.aSale.customerId
//This is an example of full refund: all items are refunded, EXCEPT SERVICE CHARGE
saleToBeRefunded.removeServiceCharge()
//For partial refund, see CashTests example
saleToBeRefunded.addCardPayment(totalToPay, terminal:WDAcceptTerminal.init()) //terminal is unnecessary here
self.saleResponse = nil
sdk.saleManager.refundSale(saleToBeRefunded, message:"Refunded in demo app for testing reasons", completion:{[weak self](acceptSale : WDAcceptSaleResponse?, error : Error?) in
self?.returnedErr = error
self?.saleResponse = acceptSale
self?.expectation.fulfill()
})
}
func device(_ device: WDAcceptTerminal, connectionStatusDidChange status:AcceptExtensionConnectionStatus)
{
print("Connection status changed \(status)")
}
}
| mit |
MoralAlberto/SlackWebAPIKit | Example/Tests/Integration/Groups/FindGroupAndSendMessageSpec.swift | 1 | 2503 | import Quick
import Nimble
import Alamofire
import RxSwift
@testable import SlackWebAPIKit
class FindGroupAndSendMessageSpec: QuickSpec {
class MockGroupAPIClient: APIClientProtocol {
func execute(withURL url: URL?) -> Observable<[String: Any]> {
let json = readJSON(name: "apiclient.list.groups.succeed") as? [String: Any]
return Observable.from(optional: json)
}
}
class MockChatAPIClient: APIClientProtocol {
func execute(withURL url: URL?) -> Observable<[String: Any]> {
let json = readJSON(name: "apiclient.postmessage.group.succeed") as? [String: Any]
return Observable.from(optional: json)
}
}
override func spec() {
describe("\(String(describing: FindGroupAndPostMessageUseCase.self)) Spec") {
context("list user use case") {
var sut: FindGroupAndPostMessageUseCaseProtocol!
let mockGroupAPIClient = MockGroupAPIClient()
let mockChatAPIClient = MockChatAPIClient()
let groupRemoteDatasource = GroupDatasource(apiClient: mockGroupAPIClient)
let chatRemoteDatasource = ChatDatasource(apiClient: mockChatAPIClient)
let groupRepository = GroupRepository(remoteDatasource: groupRemoteDatasource)
let chatRepository = ChatRepository(remoteDatasource: chatRemoteDatasource)
let disposeBag = DisposeBag()
beforeEach {
let findGroupUseCase = FindGroupUseCase(repository: groupRepository)
let postMessageUseCase = PostMessageUseCase(repository: chatRepository)
sut = FindGroupAndPostMessageUseCase(findGroupUseCase: findGroupUseCase, postMessageUseCase: postMessageUseCase)
}
it("send message") {
sut.execute(text: "Hello", group: "secret").subscribe(onNext: { isSent in
expect(isSent).to(equal(true))
}).addDisposableTo(disposeBag)
}
it("group NOT found") {
sut.execute(text: "Hello", group: "channel-five").subscribe(onError: { error in
expect(error as? GroupDatasourceError).to(equal(GroupDatasourceError.groupNotFound))
}).addDisposableTo(disposeBag)
}
}
}
}
}
| mit |
tndatacommons/Compass-iOS | Compass/src/Model/UserCategory.swift | 1 | 695 | //
// UserCategory.swift
// Compass
//
// Created by Ismael Alonso on 5/31/16.
// Copyright © 2016 Tennessee Data Commons. All rights reserved.
//
import ObjectMapper
class UserCategory: UserContent{
var category: CategoryContent? = nil;
required init?(_ map: Map){
super.init(map);
}
override func mapping(map: Map){
super.mapping(map);
category <- map["category"];
}
func getCategory() -> CategoryContent?{
return category;
}
func getIconUrl() -> String{
return category!.getIconUrl();
}
func getImageUrl() -> String{
return category!.getImageUrl();
}
}
| mit |
GitHubStuff/SwiftIntervals | SwiftEventsTests/CloudManagerTests.swift | 1 | 1106 | //
// CloudManagerTests.swift
// SwiftEvents
//
// Created by Steven Smith on 1/23/17.
// Copyright © 2017 LTMM. All rights reserved.
//
import XCTest
@testable import SwiftEvents
class CloudManagerTests: XCTestCase {
fileprivate let managerKey : String = "testKey"
override func setUp() {
super.setUp()
let cloudManager = CloudManager()
cloudManager.deleteEvents(withKey: managerKey)
}
override func tearDown() {
let cloudManager = CloudManager()
cloudManager.deleteEvents(withKey: managerKey)
super.tearDown()
}
func testGetEvents() {
let cloudManager = CloudManager()
let events = cloudManager.getEvents(withKey: managerKey)
XCTAssertNotNil(events)
let saved = cloudManager.save(events: events!, withKey: managerKey)
XCTAssertTrue(saved)
XCTAssertNotNil(events)
let recalled = cloudManager.getEvents(withKey: managerKey)
XCTAssertNotNil(recalled)
print("event:\(events?.toJSON())")
print("recall:\(recalled?.toJSON())")
}
}
| unlicense |
ifeherva/HSTracker | HSTracker/Importers/Handlers/HearthstoneTopDeck.swift | 1 | 2202 | //
// HearthstoneTopDeck.swift
// HSTracker
//
// Created by Benjamin Michotte on 11/10/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import Kanna
import RegexUtil
struct HearthstoneTopDeck: HttpImporter {
var siteName: String {
return "Hearthstonetopdeck"
}
var handleUrl: RegexPattern {
return "hearthstonetopdeck\\.com\\/deck"
}
var preferHttps: Bool {
return false
}
func loadDeck(doc: HTMLDocument, url: String) -> (Deck, [Card])? {
guard let nameNode = doc.at_xpath("//h1[contains(@class, 'panel-title')]"),
let deckName = nameNode.text?.replace("\\s+", with: " ").trim() else {
logger.error("Deck name not found")
return nil
}
logger.verbose("Got deck name \(deckName)")
let xpath = "//div[contains(@class, 'deck_banner_description')]"
+ "//span[contains(@class, 'midlarge')]/span"
let nodeInfos = doc.xpath(xpath)
guard let className = nodeInfos[1].text?.trim(),
let playerClass = CardClass(rawValue: className.lowercased()) else {
logger.error("Class not found")
return nil
}
logger.verbose("Got class \(playerClass)")
let deck = Deck()
deck.playerClass = playerClass
deck.name = deckName
var cards: [Card] = []
let cardNodes = doc.xpath("//div[contains(@class, 'cardname')]/span")
for cardNode in cardNodes {
guard let nameStr = cardNode.text else { continue }
let matches = nameStr.matches("^\\s*(\\d+)\\s+(.*)\\s*$")
logger.verbose("\(nameStr) \(matches)")
if let countStr = matches.first?.value,
let count = Int(countStr),
let cardName = matches.last?.value,
let card = Cards.by(englishNameCaseInsensitive: cardName) {
card.count = count
logger.verbose("Got card \(card)")
cards.append(card)
}
}
logger.verbose("is valid : \(deck.isValid()) \(deck.countCards())")
return (deck, cards)
}
}
| mit |
newtonstudio/cordova-plugin-device | imgly-sdk-ios-master/imglyKit/Frontend/Editor/IMGLYNavigationController.swift | 1 | 503 | //
// IMGLYNavigationController.swift
// imglyKit
//
// Created by Sascha Schwabbauer on 13/04/15.
// Copyright (c) 2015 9elements GmbH. All rights reserved.
//
import UIKit
public class IMGLYNavigationController: UINavigationController {
// MARK: - UIViewController
override public func shouldAutorotate() -> Bool {
return false
}
override public func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
return .Portrait
}
}
| apache-2.0 |
material-components/material-components-ios | catalog/MDCCatalog/MDCDebugSafeAreaInsetsView.swift | 2 | 2161 | // Copyright 2017-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
class MDCDebugSafeAreaInsetsView: UIView {
fileprivate var edgeViews = [UIView]()
override init(frame: CGRect) {
super.init(frame: frame)
isUserInteractionEnabled = false
backgroundColor = .clear
for _ in 0...3 {
let view = UIView()
view.backgroundColor = UIColor.red.withAlphaComponent(0.15)
view.isUserInteractionEnabled = false
edgeViews.append(view)
addSubview(view)
}
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func safeAreaInsetsDidChange() {
setNeedsLayout()
layoutIfNeeded()
}
override func layoutSubviews() {
var safeAreaInsets = UIEdgeInsets.zero
safeAreaInsets = self.safeAreaInsets
let width = frame.width
let height = frame.height
let insetHeight = height - safeAreaInsets.top - safeAreaInsets.bottom
// top
edgeViews[0].frame = CGRect(x: 0, y: 0, width: width, height: safeAreaInsets.top)
// left
edgeViews[1].frame = CGRect(
x: 0,
y: safeAreaInsets.top,
width: safeAreaInsets.left,
height: insetHeight)
// bottom
edgeViews[2].frame = CGRect(
x: 0,
y: height - safeAreaInsets.bottom,
width: width,
height: safeAreaInsets.bottom)
// right
edgeViews[3].frame = CGRect(
x: width - safeAreaInsets.right,
y: safeAreaInsets.top,
width: safeAreaInsets.right,
height: insetHeight)
}
}
| apache-2.0 |
zambelz48/swift-sample-dependency-injection | SampleDI/App/User/ViewModels/LoginViewModel.swift | 1 | 2361 | //
// LoginViewModel.swift
// SampleDI
//
// Created by Nanda Julianda Akbar on 8/23/17.
// Copyright © 2017 Nanda Julianda Akbar. All rights reserved.
//
import Foundation
import RxSwift
final class LoginViewModel {
// MARK: Dependencies
private var userService: UserServiceProtocol
private var userModel: UserModelProtocol
// MARK: Private properties
private let minUsernameLength: Int = 5
private let minPasswordLength: Int = 8
private let loginSuccessSubject = PublishSubject<Void>()
private let loginFailedSubject = PublishSubject<NSError>()
private let disposeBag = DisposeBag()
// MARK: Public properties
var username = Variable<String>("")
var password = Variable<String>("")
var loginSuccessObservable: Observable<Void> {
return loginSuccessSubject.asObservable()
}
var loginFailedObservable: Observable<NSError> {
return loginFailedSubject.asObservable()
}
init(userService: UserServiceProtocol,
userModel: UserModelProtocol) {
self.userService = userService
self.userModel = userModel
configureUserDataChangesObservable()
}
// MARK: Private methods
private func configureUserDataChangesObservable() {
userModel.userDataSuccessfullyChangedObservable
.bind(to: loginSuccessSubject)
.disposed(by: disposeBag)
userModel.userDataFailChangedObservable
.bind(to: loginFailedSubject)
.disposed(by: disposeBag)
}
// MARK: Public methods
func isUsernameValid() -> Observable<Bool> {
return username.asObservable()
.map { $0.count >= self.minUsernameLength }
}
func isPasswordValid() -> Observable<Bool> {
return password.asObservable()
.map { $0.count >= self.minPasswordLength }
}
func isUsernameAndPasswordValid() -> Observable<Bool> {
return Observable
.combineLatest(isUsernameValid(), isPasswordValid()) {
$0 && $1
}
.distinctUntilChanged()
}
func performLogin() {
userService.performLogin(
username: username.value,
password: password.value
)
.subscribe(
onNext: { [weak self] user in
self?.userModel.storeUserData(with: user)
},
onError: { [weak self] error in
let nsError = error as NSError
self?.loginFailedSubject.onNext(nsError)
}
)
.disposed(by: disposeBag)
}
deinit {
loginSuccessSubject.onCompleted()
loginFailedSubject.onCompleted()
}
}
| mit |
xasos/Puns | App/Puns/Puns/AppDelegate.swift | 1 | 2221 | //
// AppDelegate.swift
// Puns
//
// Created by Niraj on 11/27/14.
// Copyright (c) 2014 Niraj Pant. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
application.setStatusBarStyle(UIStatusBarStyle.LightContent, animated: false)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
codestergit/swift | benchmark/utils/main.swift | 2 | 23763 | //===--- main.swift -------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
////////////////////////////////////////////////////////////////////////////////
// WARNING: This file is automatically generated from templates and should not
// be directly modified. Instead, make changes to
// scripts/generate_harness/main.swift_template and run
// scripts/generate_harness/generate_harness.py to regenerate this file.
////////////////////////////////////////////////////////////////////////////////
// This is just a driver for performance overview tests.
import TestsUtils
import DriverUtils
import Ackermann
import AngryPhonebook
import AnyHashableWithAClass
import Array2D
import ArrayAppend
import ArrayInClass
import ArrayLiteral
import ArrayOfGenericPOD
import ArrayOfGenericRef
import ArrayOfPOD
import ArrayOfRef
import ArraySubscript
import BitCount
import ByteSwap
import CString
import Calculator
import CaptureProp
import CharacterLiteralsLarge
import CharacterLiteralsSmall
import Chars
import ClassArrayGetter
import DeadArray
import DictTest
import DictTest2
import DictTest3
import DictionaryBridge
import DictionaryLiteral
import DictionaryRemove
import DictionarySwap
import DropLast
import ErrorHandling
import ExistentialPerformance
import Fibonacci
import GlobalClass
import Hanoi
import Hash
import HashQuadratic
import Histogram
import Integrate
import IterateData
import Join
import LazyFilter
import LinkedList
import MapReduce
import Memset
import MonteCarloE
import MonteCarloPi
import NSDictionaryCastToSwift
import NSError
import NSStringConversion
import NopDeinit
import ObjectAllocation
import ObjectiveCBridging
import ObjectiveCBridgingStubs
import ObjectiveCNoBridgingStubs
import ObserverClosure
import ObserverForwarderStruct
import ObserverPartiallyAppliedMethod
import ObserverUnappliedMethod
import OpenClose
import Phonebook
import PolymorphicCalls
import PopFront
import PopFrontGeneric
import Prims
import ProtocolDispatch
import ProtocolDispatch2
import RC4
import RGBHistogram
import RangeAssignment
import RecursiveOwnedParameter
import ReversedCollections
import SetTests
import SevenBoom
import Sim2DArray
import SortLettersInPlace
import SortStrings
import StackPromo
import StaticArray
import StrComplexWalk
import StrToInt
import StringBuilder
import StringEdits
import StringInterpolation
import StringMatch
import StringTests
import StringWalk
import Suffix
import SuperChars
import TwoSum
import TypeFlood
import UTF8Decode
import Walsh
import XorLoop
precommitTests = [
"AngryPhonebook": run_AngryPhonebook,
"AnyHashableWithAClass": run_AnyHashableWithAClass,
"Array2D": run_Array2D,
"ArrayAppend": run_ArrayAppend,
"ArrayAppendArrayOfInt": run_ArrayAppendArrayOfInt,
"ArrayAppendAscii": run_ArrayAppendAscii,
"ArrayAppendFromGeneric": run_ArrayAppendFromGeneric,
"ArrayAppendGenericStructs": run_ArrayAppendGenericStructs,
"ArrayAppendLatin1": run_ArrayAppendLatin1,
"ArrayAppendLazyMap": run_ArrayAppendLazyMap,
"ArrayAppendOptionals": run_ArrayAppendOptionals,
"ArrayAppendRepeatCol": run_ArrayAppendRepeatCol,
"ArrayAppendReserved": run_ArrayAppendReserved,
"ArrayAppendSequence": run_ArrayAppendSequence,
"ArrayAppendStrings": run_ArrayAppendStrings,
"ArrayAppendToFromGeneric": run_ArrayAppendToFromGeneric,
"ArrayAppendToGeneric": run_ArrayAppendToGeneric,
"ArrayAppendUTF16": run_ArrayAppendUTF16,
"ArrayInClass": run_ArrayInClass,
"ArrayLiteral": run_ArrayLiteral,
"ArrayOfGenericPOD": run_ArrayOfGenericPOD,
"ArrayOfGenericRef": run_ArrayOfGenericRef,
"ArrayOfPOD": run_ArrayOfPOD,
"ArrayOfRef": run_ArrayOfRef,
"ArrayPlusEqualArrayOfInt": run_ArrayPlusEqualArrayOfInt,
"ArrayPlusEqualFiveElementCollection": run_ArrayPlusEqualFiveElementCollection,
"ArrayPlusEqualSingleElementCollection": run_ArrayPlusEqualSingleElementCollection,
"ArraySubscript": run_ArraySubscript,
"ArrayValueProp": run_ArrayValueProp,
"ArrayValueProp2": run_ArrayValueProp2,
"ArrayValueProp3": run_ArrayValueProp3,
"ArrayValueProp4": run_ArrayValueProp4,
"BitCount": run_BitCount,
"ByteSwap": run_ByteSwap,
"CStringLongAscii": run_CStringLongAscii,
"CStringLongNonAscii": run_CStringLongNonAscii,
"CStringShortAscii": run_CStringShortAscii,
"Calculator": run_Calculator,
"CaptureProp": run_CaptureProp,
"CharacterLiteralsLarge": run_CharacterLiteralsLarge,
"CharacterLiteralsSmall": run_CharacterLiteralsSmall,
"Chars": run_Chars,
"ClassArrayGetter": run_ClassArrayGetter,
"DeadArray": run_DeadArray,
"Dictionary": run_Dictionary,
"Dictionary2": run_Dictionary2,
"Dictionary2OfObjects": run_Dictionary2OfObjects,
"Dictionary3": run_Dictionary3,
"Dictionary3OfObjects": run_Dictionary3OfObjects,
"DictionaryBridge": run_DictionaryBridge,
"DictionaryLiteral": run_DictionaryLiteral,
"DictionaryOfObjects": run_DictionaryOfObjects,
"DictionaryRemove": run_DictionaryRemove,
"DictionaryRemoveOfObjects": run_DictionaryRemoveOfObjects,
"DictionarySwap": run_DictionarySwap,
"DictionarySwapOfObjects": run_DictionarySwapOfObjects,
"DropLastAnySequence": run_DropLastAnySequence,
"DropLastArray": run_DropLastArray,
"DropLastCountableRange": run_DropLastCountableRange,
"DropLastSequence": run_DropLastSequence,
"ErrorHandling": run_ErrorHandling,
"ExistentialTestArrayConditionalShift_ClassValueBuffer1": run_ExistentialTestArrayConditionalShift_ClassValueBuffer1,
"ExistentialTestArrayConditionalShift_ClassValueBuffer2": run_ExistentialTestArrayConditionalShift_ClassValueBuffer2,
"ExistentialTestArrayConditionalShift_ClassValueBuffer3": run_ExistentialTestArrayConditionalShift_ClassValueBuffer3,
"ExistentialTestArrayConditionalShift_ClassValueBuffer4": run_ExistentialTestArrayConditionalShift_ClassValueBuffer4,
"ExistentialTestArrayConditionalShift_IntValueBuffer0": run_ExistentialTestArrayConditionalShift_IntValueBuffer0,
"ExistentialTestArrayConditionalShift_IntValueBuffer1": run_ExistentialTestArrayConditionalShift_IntValueBuffer1,
"ExistentialTestArrayConditionalShift_IntValueBuffer2": run_ExistentialTestArrayConditionalShift_IntValueBuffer2,
"ExistentialTestArrayConditionalShift_IntValueBuffer3": run_ExistentialTestArrayConditionalShift_IntValueBuffer3,
"ExistentialTestArrayConditionalShift_IntValueBuffer4": run_ExistentialTestArrayConditionalShift_IntValueBuffer4,
"ExistentialTestArrayMutating_ClassValueBuffer1": run_ExistentialTestArrayMutating_ClassValueBuffer1,
"ExistentialTestArrayMutating_ClassValueBuffer2": run_ExistentialTestArrayMutating_ClassValueBuffer2,
"ExistentialTestArrayMutating_ClassValueBuffer3": run_ExistentialTestArrayMutating_ClassValueBuffer3,
"ExistentialTestArrayMutating_ClassValueBuffer4": run_ExistentialTestArrayMutating_ClassValueBuffer4,
"ExistentialTestArrayMutating_IntValueBuffer0": run_ExistentialTestArrayMutating_IntValueBuffer0,
"ExistentialTestArrayMutating_IntValueBuffer1": run_ExistentialTestArrayMutating_IntValueBuffer1,
"ExistentialTestArrayMutating_IntValueBuffer2": run_ExistentialTestArrayMutating_IntValueBuffer2,
"ExistentialTestArrayMutating_IntValueBuffer3": run_ExistentialTestArrayMutating_IntValueBuffer3,
"ExistentialTestArrayMutating_IntValueBuffer4": run_ExistentialTestArrayMutating_IntValueBuffer4,
"ExistentialTestArrayOneMethodCall_ClassValueBuffer1": run_ExistentialTestArrayOneMethodCall_ClassValueBuffer1,
"ExistentialTestArrayOneMethodCall_ClassValueBuffer2": run_ExistentialTestArrayOneMethodCall_ClassValueBuffer2,
"ExistentialTestArrayOneMethodCall_ClassValueBuffer3": run_ExistentialTestArrayOneMethodCall_ClassValueBuffer3,
"ExistentialTestArrayOneMethodCall_ClassValueBuffer4": run_ExistentialTestArrayOneMethodCall_ClassValueBuffer4,
"ExistentialTestArrayOneMethodCall_IntValueBuffer0": run_ExistentialTestArrayOneMethodCall_IntValueBuffer0,
"ExistentialTestArrayOneMethodCall_IntValueBuffer1": run_ExistentialTestArrayOneMethodCall_IntValueBuffer1,
"ExistentialTestArrayOneMethodCall_IntValueBuffer2": run_ExistentialTestArrayOneMethodCall_IntValueBuffer2,
"ExistentialTestArrayOneMethodCall_IntValueBuffer3": run_ExistentialTestArrayOneMethodCall_IntValueBuffer3,
"ExistentialTestArrayOneMethodCall_IntValueBuffer4": run_ExistentialTestArrayOneMethodCall_IntValueBuffer4,
"ExistentialTestArrayShift_ClassValueBuffer1": run_ExistentialTestArrayShift_ClassValueBuffer1,
"ExistentialTestArrayShift_ClassValueBuffer2": run_ExistentialTestArrayShift_ClassValueBuffer2,
"ExistentialTestArrayShift_ClassValueBuffer3": run_ExistentialTestArrayShift_ClassValueBuffer3,
"ExistentialTestArrayShift_ClassValueBuffer4": run_ExistentialTestArrayShift_ClassValueBuffer4,
"ExistentialTestArrayShift_IntValueBuffer0": run_ExistentialTestArrayShift_IntValueBuffer0,
"ExistentialTestArrayShift_IntValueBuffer1": run_ExistentialTestArrayShift_IntValueBuffer1,
"ExistentialTestArrayShift_IntValueBuffer2": run_ExistentialTestArrayShift_IntValueBuffer2,
"ExistentialTestArrayShift_IntValueBuffer3": run_ExistentialTestArrayShift_IntValueBuffer3,
"ExistentialTestArrayShift_IntValueBuffer4": run_ExistentialTestArrayShift_IntValueBuffer4,
"ExistentialTestArrayTwoMethodCalls_ClassValueBuffer1": run_ExistentialTestArrayTwoMethodCalls_ClassValueBuffer1,
"ExistentialTestArrayTwoMethodCalls_ClassValueBuffer2": run_ExistentialTestArrayTwoMethodCalls_ClassValueBuffer2,
"ExistentialTestArrayTwoMethodCalls_ClassValueBuffer3": run_ExistentialTestArrayTwoMethodCalls_ClassValueBuffer3,
"ExistentialTestArrayTwoMethodCalls_ClassValueBuffer4": run_ExistentialTestArrayTwoMethodCalls_ClassValueBuffer4,
"ExistentialTestArrayTwoMethodCalls_IntValueBuffer0": run_ExistentialTestArrayTwoMethodCalls_IntValueBuffer0,
"ExistentialTestArrayTwoMethodCalls_IntValueBuffer1": run_ExistentialTestArrayTwoMethodCalls_IntValueBuffer1,
"ExistentialTestArrayTwoMethodCalls_IntValueBuffer2": run_ExistentialTestArrayTwoMethodCalls_IntValueBuffer2,
"ExistentialTestArrayTwoMethodCalls_IntValueBuffer3": run_ExistentialTestArrayTwoMethodCalls_IntValueBuffer3,
"ExistentialTestArrayTwoMethodCalls_IntValueBuffer4": run_ExistentialTestArrayTwoMethodCalls_IntValueBuffer4,
"ExistentialTestMutatingAndNonMutating_ClassValueBuffer1": run_ExistentialTestMutatingAndNonMutating_ClassValueBuffer1,
"ExistentialTestMutatingAndNonMutating_ClassValueBuffer2": run_ExistentialTestMutatingAndNonMutating_ClassValueBuffer2,
"ExistentialTestMutatingAndNonMutating_ClassValueBuffer3": run_ExistentialTestMutatingAndNonMutating_ClassValueBuffer3,
"ExistentialTestMutatingAndNonMutating_ClassValueBuffer4": run_ExistentialTestMutatingAndNonMutating_ClassValueBuffer4,
"ExistentialTestMutatingAndNonMutating_IntValueBuffer0": run_ExistentialTestMutatingAndNonMutating_IntValueBuffer0,
"ExistentialTestMutatingAndNonMutating_IntValueBuffer1": run_ExistentialTestMutatingAndNonMutating_IntValueBuffer1,
"ExistentialTestMutatingAndNonMutating_IntValueBuffer2": run_ExistentialTestMutatingAndNonMutating_IntValueBuffer2,
"ExistentialTestMutatingAndNonMutating_IntValueBuffer3": run_ExistentialTestMutatingAndNonMutating_IntValueBuffer3,
"ExistentialTestMutatingAndNonMutating_IntValueBuffer4": run_ExistentialTestMutatingAndNonMutating_IntValueBuffer4,
"ExistentialTestMutating_ClassValueBuffer1": run_ExistentialTestMutating_ClassValueBuffer1,
"ExistentialTestMutating_ClassValueBuffer2": run_ExistentialTestMutating_ClassValueBuffer2,
"ExistentialTestMutating_ClassValueBuffer3": run_ExistentialTestMutating_ClassValueBuffer3,
"ExistentialTestMutating_ClassValueBuffer4": run_ExistentialTestMutating_ClassValueBuffer4,
"ExistentialTestMutating_IntValueBuffer0": run_ExistentialTestMutating_IntValueBuffer0,
"ExistentialTestMutating_IntValueBuffer1": run_ExistentialTestMutating_IntValueBuffer1,
"ExistentialTestMutating_IntValueBuffer2": run_ExistentialTestMutating_IntValueBuffer2,
"ExistentialTestMutating_IntValueBuffer3": run_ExistentialTestMutating_IntValueBuffer3,
"ExistentialTestMutating_IntValueBuffer4": run_ExistentialTestMutating_IntValueBuffer4,
"ExistentialTestOneMethodCall_ClassValueBuffer1": run_ExistentialTestOneMethodCall_ClassValueBuffer1,
"ExistentialTestOneMethodCall_ClassValueBuffer2": run_ExistentialTestOneMethodCall_ClassValueBuffer2,
"ExistentialTestOneMethodCall_ClassValueBuffer3": run_ExistentialTestOneMethodCall_ClassValueBuffer3,
"ExistentialTestOneMethodCall_ClassValueBuffer4": run_ExistentialTestOneMethodCall_ClassValueBuffer4,
"ExistentialTestOneMethodCall_IntValueBuffer0": run_ExistentialTestOneMethodCall_IntValueBuffer0,
"ExistentialTestOneMethodCall_IntValueBuffer1": run_ExistentialTestOneMethodCall_IntValueBuffer1,
"ExistentialTestOneMethodCall_IntValueBuffer2": run_ExistentialTestOneMethodCall_IntValueBuffer2,
"ExistentialTestOneMethodCall_IntValueBuffer3": run_ExistentialTestOneMethodCall_IntValueBuffer3,
"ExistentialTestOneMethodCall_IntValueBuffer4": run_ExistentialTestOneMethodCall_IntValueBuffer4,
"ExistentialTestPassExistentialOneMethodCall_ClassValueBuffer1": run_ExistentialTestPassExistentialOneMethodCall_ClassValueBuffer1,
"ExistentialTestPassExistentialOneMethodCall_ClassValueBuffer2": run_ExistentialTestPassExistentialOneMethodCall_ClassValueBuffer2,
"ExistentialTestPassExistentialOneMethodCall_ClassValueBuffer3": run_ExistentialTestPassExistentialOneMethodCall_ClassValueBuffer3,
"ExistentialTestPassExistentialOneMethodCall_ClassValueBuffer4": run_ExistentialTestPassExistentialOneMethodCall_ClassValueBuffer4,
"ExistentialTestPassExistentialOneMethodCall_IntValueBuffer0": run_ExistentialTestPassExistentialOneMethodCall_IntValueBuffer0,
"ExistentialTestPassExistentialOneMethodCall_IntValueBuffer1": run_ExistentialTestPassExistentialOneMethodCall_IntValueBuffer1,
"ExistentialTestPassExistentialOneMethodCall_IntValueBuffer2": run_ExistentialTestPassExistentialOneMethodCall_IntValueBuffer2,
"ExistentialTestPassExistentialOneMethodCall_IntValueBuffer3": run_ExistentialTestPassExistentialOneMethodCall_IntValueBuffer3,
"ExistentialTestPassExistentialOneMethodCall_IntValueBuffer4": run_ExistentialTestPassExistentialOneMethodCall_IntValueBuffer4,
"ExistentialTestPassExistentialTwoMethodCalls_ClassValueBuffer1": run_ExistentialTestPassExistentialTwoMethodCalls_ClassValueBuffer1,
"ExistentialTestPassExistentialTwoMethodCalls_ClassValueBuffer2": run_ExistentialTestPassExistentialTwoMethodCalls_ClassValueBuffer2,
"ExistentialTestPassExistentialTwoMethodCalls_ClassValueBuffer3": run_ExistentialTestPassExistentialTwoMethodCalls_ClassValueBuffer3,
"ExistentialTestPassExistentialTwoMethodCalls_ClassValueBuffer4": run_ExistentialTestPassExistentialTwoMethodCalls_ClassValueBuffer4,
"ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer0": run_ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer0,
"ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer1": run_ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer1,
"ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer2": run_ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer2,
"ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer3": run_ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer3,
"ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer4": run_ExistentialTestPassExistentialTwoMethodCalls_IntValueBuffer4,
"ExistentialTestTwoMethodCalls_ClassValueBuffer1": run_ExistentialTestTwoMethodCalls_ClassValueBuffer1,
"ExistentialTestTwoMethodCalls_ClassValueBuffer2": run_ExistentialTestTwoMethodCalls_ClassValueBuffer2,
"ExistentialTestTwoMethodCalls_ClassValueBuffer3": run_ExistentialTestTwoMethodCalls_ClassValueBuffer3,
"ExistentialTestTwoMethodCalls_ClassValueBuffer4": run_ExistentialTestTwoMethodCalls_ClassValueBuffer4,
"ExistentialTestTwoMethodCalls_IntValueBuffer0": run_ExistentialTestTwoMethodCalls_IntValueBuffer0,
"ExistentialTestTwoMethodCalls_IntValueBuffer1": run_ExistentialTestTwoMethodCalls_IntValueBuffer1,
"ExistentialTestTwoMethodCalls_IntValueBuffer2": run_ExistentialTestTwoMethodCalls_IntValueBuffer2,
"ExistentialTestTwoMethodCalls_IntValueBuffer3": run_ExistentialTestTwoMethodCalls_IntValueBuffer3,
"ExistentialTestTwoMethodCalls_IntValueBuffer4": run_ExistentialTestTwoMethodCalls_IntValueBuffer4,
"GlobalClass": run_GlobalClass,
"Hanoi": run_Hanoi,
"HashQuadratic": run_HashQuadratic,
"HashTest": run_HashTest,
"Histogram": run_Histogram,
"Integrate": run_Integrate,
"IterateData": run_IterateData,
"Join": run_Join,
"LazilyFilteredArrays": run_LazilyFilteredArrays,
"LazilyFilteredRange": run_LazilyFilteredRange,
"LinkedList": run_LinkedList,
"MapReduce": run_MapReduce,
"MapReduceAnyCollection": run_MapReduceAnyCollection,
"MapReduceAnyCollectionShort": run_MapReduceAnyCollectionShort,
"MapReduceClass": run_MapReduceClass,
"MapReduceClassShort": run_MapReduceClassShort,
"MapReduceLazyCollection": run_MapReduceLazyCollection,
"MapReduceLazyCollectionShort": run_MapReduceLazyCollectionShort,
"MapReduceLazySequence": run_MapReduceLazySequence,
"MapReduceSequence": run_MapReduceSequence,
"MapReduceShort": run_MapReduceShort,
"MapReduceShortString": run_MapReduceShortString,
"MapReduceString": run_MapReduceString,
"Memset": run_Memset,
"MonteCarloE": run_MonteCarloE,
"MonteCarloPi": run_MonteCarloPi,
"NSDictionaryCastToSwift": run_NSDictionaryCastToSwift,
"NSError": run_NSError,
"NSStringConversion": run_NSStringConversion,
"NopDeinit": run_NopDeinit,
"ObjectAllocation": run_ObjectAllocation,
"ObjectiveCBridgeFromNSArrayAnyObject": run_ObjectiveCBridgeFromNSArrayAnyObject,
"ObjectiveCBridgeFromNSArrayAnyObjectForced": run_ObjectiveCBridgeFromNSArrayAnyObjectForced,
"ObjectiveCBridgeFromNSArrayAnyObjectToString": run_ObjectiveCBridgeFromNSArrayAnyObjectToString,
"ObjectiveCBridgeFromNSArrayAnyObjectToStringForced": run_ObjectiveCBridgeFromNSArrayAnyObjectToStringForced,
"ObjectiveCBridgeFromNSDictionaryAnyObject": run_ObjectiveCBridgeFromNSDictionaryAnyObject,
"ObjectiveCBridgeFromNSDictionaryAnyObjectForced": run_ObjectiveCBridgeFromNSDictionaryAnyObjectForced,
"ObjectiveCBridgeFromNSDictionaryAnyObjectToString": run_ObjectiveCBridgeFromNSDictionaryAnyObjectToString,
"ObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced": run_ObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced,
"ObjectiveCBridgeFromNSSetAnyObject": run_ObjectiveCBridgeFromNSSetAnyObject,
"ObjectiveCBridgeFromNSSetAnyObjectForced": run_ObjectiveCBridgeFromNSSetAnyObjectForced,
"ObjectiveCBridgeFromNSSetAnyObjectToString": run_ObjectiveCBridgeFromNSSetAnyObjectToString,
"ObjectiveCBridgeFromNSSetAnyObjectToStringForced": run_ObjectiveCBridgeFromNSSetAnyObjectToStringForced,
"ObjectiveCBridgeFromNSString": run_ObjectiveCBridgeFromNSString,
"ObjectiveCBridgeFromNSStringForced": run_ObjectiveCBridgeFromNSStringForced,
"ObjectiveCBridgeStubDataAppend": run_ObjectiveCBridgeStubDataAppend,
"ObjectiveCBridgeStubDateAccess": run_ObjectiveCBridgeStubDateAccess,
"ObjectiveCBridgeStubDateMutation": run_ObjectiveCBridgeStubDateMutation,
"ObjectiveCBridgeStubFromArrayOfNSString": run_ObjectiveCBridgeStubFromArrayOfNSString,
"ObjectiveCBridgeStubFromNSDate": run_ObjectiveCBridgeStubFromNSDate,
"ObjectiveCBridgeStubFromNSDateRef": run_ObjectiveCBridgeStubFromNSDateRef,
"ObjectiveCBridgeStubFromNSString": run_ObjectiveCBridgeStubFromNSString,
"ObjectiveCBridgeStubFromNSStringRef": run_ObjectiveCBridgeStubFromNSStringRef,
"ObjectiveCBridgeStubNSDataAppend": run_ObjectiveCBridgeStubNSDataAppend,
"ObjectiveCBridgeStubNSDateMutationRef": run_ObjectiveCBridgeStubNSDateMutationRef,
"ObjectiveCBridgeStubNSDateRefAccess": run_ObjectiveCBridgeStubNSDateRefAccess,
"ObjectiveCBridgeStubToArrayOfNSString": run_ObjectiveCBridgeStubToArrayOfNSString,
"ObjectiveCBridgeStubToNSDate": run_ObjectiveCBridgeStubToNSDate,
"ObjectiveCBridgeStubToNSDateRef": run_ObjectiveCBridgeStubToNSDateRef,
"ObjectiveCBridgeStubToNSString": run_ObjectiveCBridgeStubToNSString,
"ObjectiveCBridgeStubToNSStringRef": run_ObjectiveCBridgeStubToNSStringRef,
"ObjectiveCBridgeStubURLAppendPath": run_ObjectiveCBridgeStubURLAppendPath,
"ObjectiveCBridgeStubURLAppendPathRef": run_ObjectiveCBridgeStubURLAppendPathRef,
"ObjectiveCBridgeToNSArray": run_ObjectiveCBridgeToNSArray,
"ObjectiveCBridgeToNSDictionary": run_ObjectiveCBridgeToNSDictionary,
"ObjectiveCBridgeToNSSet": run_ObjectiveCBridgeToNSSet,
"ObjectiveCBridgeToNSString": run_ObjectiveCBridgeToNSString,
"ObserverClosure": run_ObserverClosure,
"ObserverForwarderStruct": run_ObserverForwarderStruct,
"ObserverPartiallyAppliedMethod": run_ObserverPartiallyAppliedMethod,
"ObserverUnappliedMethod": run_ObserverUnappliedMethod,
"OpenClose": run_OpenClose,
"Phonebook": run_Phonebook,
"PolymorphicCalls": run_PolymorphicCalls,
"PopFrontArray": run_PopFrontArray,
"PopFrontArrayGeneric": run_PopFrontArrayGeneric,
"PopFrontUnsafePointer": run_PopFrontUnsafePointer,
"Prims": run_Prims,
"ProtocolDispatch": run_ProtocolDispatch,
"ProtocolDispatch2": run_ProtocolDispatch2,
"RC4": run_RC4,
"RGBHistogram": run_RGBHistogram,
"RGBHistogramOfObjects": run_RGBHistogramOfObjects,
"RangeAssignment": run_RangeAssignment,
"RecursiveOwnedParameter": run_RecursiveOwnedParameter,
"ReversedArray": run_ReversedArray,
"ReversedBidirectional": run_ReversedBidirectional,
"ReversedDictionary": run_ReversedDictionary,
"SetExclusiveOr": run_SetExclusiveOr,
"SetExclusiveOr_OfObjects": run_SetExclusiveOr_OfObjects,
"SetIntersect": run_SetIntersect,
"SetIntersect_OfObjects": run_SetIntersect_OfObjects,
"SetIsSubsetOf": run_SetIsSubsetOf,
"SetIsSubsetOf_OfObjects": run_SetIsSubsetOf_OfObjects,
"SetUnion": run_SetUnion,
"SetUnion_OfObjects": run_SetUnion_OfObjects,
"SevenBoom": run_SevenBoom,
"Sim2DArray": run_Sim2DArray,
"SortLettersInPlace": run_SortLettersInPlace,
"SortSortedStrings": run_SortSortedStrings,
"SortStrings": run_SortStrings,
"SortStringsUnicode": run_SortStringsUnicode,
"StackPromo": run_StackPromo,
"StaticArray": run_StaticArray,
"StrComplexWalk": run_StrComplexWalk,
"StrToInt": run_StrToInt,
"StringAdder": run_StringAdder,
"StringBuilder": run_StringBuilder,
"StringBuilderLong": run_StringBuilderLong,
"StringEdits": run_StringEdits,
"StringEqualPointerComparison": run_StringEqualPointerComparison,
"StringHasPrefix": run_StringHasPrefix,
"StringHasPrefixUnicode": run_StringHasPrefixUnicode,
"StringHasSuffix": run_StringHasSuffix,
"StringHasSuffixUnicode": run_StringHasSuffixUnicode,
"StringInterpolation": run_StringInterpolation,
"StringMatch": run_StringMatch,
"StringUTF16Builder": run_StringUTF16Builder,
"StringWalk": run_StringWalk,
"StringWithCString": run_StringWithCString,
"SuffixAnySequence": run_SuffixAnySequence,
"SuffixArray": run_SuffixArray,
"SuffixCountableRange": run_SuffixCountableRange,
"SuffixSequence": run_SuffixSequence,
"SuperChars": run_SuperChars,
"TwoSum": run_TwoSum,
"TypeFlood": run_TypeFlood,
"UTF8Decode": run_UTF8Decode,
"Walsh": run_Walsh,
"XorLoop": run_XorLoop,
]
otherTests = [
"Ackermann": run_Ackermann,
"Fibonacci": run_Fibonacci,
]
main()
| apache-2.0 |
dunkelstern/unchained | Unchained/router.swift | 1 | 9781 | //
// router.swift
// unchained
//
// Created by Johannes Schriewer on 30/11/15.
// Copyright © 2015 Johannes Schriewer. All rights reserved.
//
import TwoHundred
import UnchainedString
import UnchainedLogger
import SwiftyRegex
/// Unchained route entry
public struct Route {
/// Router errors
public enum Error: ErrorType {
/// No route with that name exists
case NoRouteWithThatName(name: String)
/// Route contains mix of numbered and named parameters
case MixedNumberedAndNamedParameters
/// Missing parameter of `name` to call that route
case MissingParameterForRoute(name: String)
/// Wrong parameter count for a route with unnamed parameters
case WrongParameterCountForRoute
}
/// A route request handler, takes `request`, numbered `parameters` and `namedParameters`, returns `HTTPResponseBase`
public typealias RequestHandler = ((request: HTTPRequest, parameters: [String], namedParameters: [String:String]) -> HTTPResponseBase)
/// Name of the route (used for route reversing)
public var name: String
private var re: RegEx?
private var handler:RequestHandler
/// Initialize a route
///
/// - parameter regex: Regex to match
/// - parameter handler: handler callback to run if route matches
/// - parameter name: (optional) name of this route to `reverse`
public init(_ regex: String, handler:RequestHandler, name: String? = nil) {
do {
self.re = try RegEx(pattern: regex)
} catch RegEx.Error.InvalidPattern(let offset, let message) {
Log.error("Route: Pattern parse error for pattern \(regex) at character \(offset): \(message)")
} catch {
// unused
}
self.handler = handler
if let name = name {
self.name = name
} else {
self.name = "r'\(regex)'"
}
}
/// execute a route on a request
///
/// - parameter request: the request on which to execute this route
/// - returns: response to the request or nil if the route does not match
public func execute(request: HTTPRequest) -> HTTPResponseBase? {
guard let re = self.re else {
return nil
}
let matches = re.match(request.header.url)
if matches.numberedParams.count > 0 {
return self.handler(request: request, parameters: matches.numberedParams, namedParameters: matches.namedParams)
}
return nil
}
// MARK: - Internal
enum RouteComponentType {
case Text(String)
case NamedPattern(String)
case NumberedPattern(Int)
}
/// split a route regex into components for route reversal
///
/// - returns: Array of route components
func splitIntoComponents() -> [RouteComponentType]? {
guard let pattern = self.re?.pattern else {
return nil
}
var patternNum = 0
var openBrackets = 0
var components = [RouteComponentType]()
var currentComponent = ""
currentComponent.reserveCapacity(pattern.characters.count)
var gen = pattern.characters.generate()
while let c = gen.next() {
switch c {
case "(":
if openBrackets == 0 {
// split point
if currentComponent.characters.count > 0 {
patternNum += 1
components.append(.Text(currentComponent))
currentComponent.removeAll()
}
}
break
case ")":
if openBrackets == 0 {
// split point
if currentComponent.characters.count > 0 {
var found = false
for (name, idx) in self.re!.namedCaptureGroups {
if idx == patternNum {
components.append(.NamedPattern(name))
currentComponent.removeAll()
found = true
break
}
}
if !found {
components.append(.NumberedPattern(patternNum))
}
}
}
case "[":
openBrackets += 1
case "]":
openBrackets -= 1
case "\\":
// skip next char
gen.next()
default:
currentComponent.append(c)
}
}
if currentComponent.characters.count > 0 {
components.append(.Text(currentComponent))
}
// strip ^ on start
if case .Text(let text) = components.first! {
if text.characters.first! == "^" {
components[0] = .Text(text.subString(fromIndex: text.startIndex.advancedBy(1)))
}
}
// strip $ on end
if case .Text(let text) = components.last! {
if text.characters.last! == "$" {
components.removeLast()
if text.characters.count > 1 {
components.append(.Text(text.subString(toIndex: text.startIndex.advancedBy(text.characters.count - 2))))
}
}
}
return components
}
}
/// Route reversion
public extension UnchainedResponseHandler {
/// reverse a route with named parameters
///
/// - parameter name: the name of the route URL to produce
/// - parameter parameters: the parameters to substitute
/// - parameter absolute: (optional) return relative path (from root, default) or absolute URL with hostname
/// - returns: URL of route with parameters
///
/// - throws: Throws errors if route could not be reversed
public func reverseRoute(name: String, parameters:[String:String], absolute: Bool = false) throws -> String {
guard let route = self.fetchRoute(name) else {
throw Route.Error.NoRouteWithThatName(name: name)
}
var result = ""
if absolute {
result.appendContentsOf(self.request.config.externalServerURL)
}
// Build route string
for item in route {
switch item {
case .NumberedPattern:
throw Route.Error.MixedNumberedAndNamedParameters
case .NamedPattern(let name):
if let param = parameters[name] {
result.appendContentsOf(param)
} else {
throw Route.Error.MissingParameterForRoute(name: name)
}
case .Text(let text):
result.appendContentsOf(text)
}
}
return result
}
/// reverse a route with numbered parameters
///
/// - parameter name: the name of the route URL to produce
/// - parameter parameters: the parameters to substitute
/// - parameter absolute: (optional) return relative path (from root, default) or absolute URL with hostname
/// - returns: URL of route with parameters
///
/// - throws: Throws errors if route could not be reversed
public func reverseRoute(name: String, parameters:[String], absolute: Bool = false) throws -> String {
guard let route = self.fetchRoute(name) else {
throw Route.Error.NoRouteWithThatName(name: name)
}
var result = ""
if absolute {
result.appendContentsOf(self.request.config.externalServerURL)
}
// Build route string
for item in route {
switch item {
case .NumberedPattern(let num):
if parameters.count > num - 1 {
result.appendContentsOf(parameters[num - 1])
} else {
throw Route.Error.WrongParameterCountForRoute
}
case .NamedPattern:
throw Route.Error.MixedNumberedAndNamedParameters
case .Text(let text):
result.appendContentsOf(text)
}
}
return result
}
/// reverse a route without parameters
///
/// - parameter name: the name of the route URL to produce
/// - parameter absolute: (optional) return relative path (from root, default) or absolute URL with hostname
/// - returns: URL of route with parameters
///
/// - throws: Throws errors if route could not be reversed
public func reverseRoute(name: String, absolute: Bool = false) throws -> String {
guard let route = self.fetchRoute(name) else {
throw Route.Error.NoRouteWithThatName(name: name)
}
var result = ""
if absolute {
result.appendContentsOf(self.request.config.externalServerURL)
}
// Build route string
for item in route {
switch item {
case .NumberedPattern:
throw Route.Error.WrongParameterCountForRoute
case .NamedPattern(let name):
throw Route.Error.MissingParameterForRoute(name: name)
case .Text(let text):
result.appendContentsOf(text)
}
}
return result
}
/// Fetch a route by name
///
/// - parameter name: Name to search
/// - returns: Route instance or nil if not found
private func fetchRoute(name: String) -> [Route.RouteComponentType]? {
for route in self.request.config.routes {
if route.name == name {
return route.splitIntoComponents()
}
}
return nil
}
}
| bsd-3-clause |
cnoon/swift-compiler-crashes | crashes-duplicates/07105-getselftypeforcontainer.swift | 11 | 446 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol b {
protocol c : b {
}
protocol b { func b: AnyObject, g<b
func a<b.b
class c {
}
class c {
}
typealias b: a {
class c : S<Int>(")
}
typealias b.h == b: e(f(f(v: A : a {
class c : AnyObject, b : AnyObject, b { func b: e(")
}
struct S<b: S(")
import CoreData
S<b
proto
| mit |
Holmusk/HMRequestFramework-iOS | HMRequestFramework-Demo/DemoSingleton.swift | 1 | 396 | //
// DemoSingleton.swift
// HMRequestFramework-Demo
//
// Created by Hai Pham on 28/8/17.
// Copyright © 2017 Holmusk. All rights reserved.
//
import HMRequestFramework
public final class DemoSingleton {
public static let cdManager = Singleton.coreDataManager(.background, .SQLite)
public static let dbProcessor = Singleton.dbProcessor(DemoSingleton.cdManager)
private init() {}
}
| apache-2.0 |
wibosco/CoreDataMigration-Example | CoreDataMigration-Example/Application/main.swift | 1 | 567 | //
// main.swift
// CoreDataMigration-Example
//
// Created by William Boles on 15/09/2017.
// Copyright © 2017 William Boles. All rights reserved.
//
import Foundation
import UIKit
let isRunningTests = NSClassFromString("XCTestCase") != nil
let appDelegateClass : AnyClass = isRunningTests ? TestingAppDelegate.self : AppDelegate.self
let args = UnsafeMutableRawPointer(CommandLine.unsafeArgv).bindMemory(to: UnsafeMutablePointer<Int8>.self, capacity: Int(CommandLine.argc))
UIApplicationMain(CommandLine.argc, args, nil, NSStringFromClass(appDelegateClass))
| mit |
SuPair/firefox-ios | Client/Frontend/Browser/ScreenshotHelper.swift | 16 | 2146 | /* 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
/**
* Handles screenshots for a given tab, including pages with non-webview content.
*/
class ScreenshotHelper {
var viewIsVisible = false
fileprivate weak var controller: BrowserViewController?
init(controller: BrowserViewController) {
self.controller = controller
}
func takeScreenshot(_ tab: Tab) {
var screenshot: UIImage?
if let url = tab.url {
if url.isAboutHomeURL {
if let homePanel = controller?.homePanelController {
screenshot = homePanel.view.screenshot(quality: UIConstants.ActiveScreenshotQuality)
}
} else {
let offset = CGPoint(x: 0, y: -(tab.webView?.scrollView.contentInset.top ?? 0))
screenshot = tab.webView?.screenshot(offset: offset, quality: UIConstants.ActiveScreenshotQuality)
}
}
tab.setScreenshot(screenshot)
}
/// Takes a screenshot after a small delay.
/// Trying to take a screenshot immediately after didFinishNavigation results in a screenshot
/// of the previous page, presumably due to an iOS bug. Adding a brief delay fixes this.
func takeDelayedScreenshot(_ tab: Tab) {
let time = DispatchTime.now() + Double(Int64(100 * NSEC_PER_MSEC)) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time) {
// If the view controller isn't visible, the screenshot will be blank.
// Wait until the view controller is visible again to take the screenshot.
guard self.viewIsVisible else {
tab.pendingScreenshot = true
return
}
self.takeScreenshot(tab)
}
}
func takePendingScreenshots(_ tabs: [Tab]) {
for tab in tabs where tab.pendingScreenshot {
tab.pendingScreenshot = false
takeDelayedScreenshot(tab)
}
}
}
| mpl-2.0 |
kousun12/RxSwift | RxTests/RxSwiftTests/Tests/Observable+SubscriptionTest.swift | 7 | 6290 | //
// Observable+SubscriptionTest.swift
// RxTests
//
// Created by Krunoslav Zaher on 10/13/15.
//
//
import Foundation
import RxSwift
import XCTest
class ObservableSubscriptionTests : RxTest {
func testSubscribeOnNext() {
let publishSubject = PublishSubject<Int>()
var onNextCalled = 0
var onErrorCalled = 0
var onCompletedCalled = 0
var onDisposedCalled = 0
var lastElement: Int? = nil
var lastError: ErrorType? = nil
let subscription = publishSubject.subscribe(onNext: { n in
lastElement = n
onNextCalled++
}, onError: { e in
lastError = e
onErrorCalled++
}, onCompleted: {
onCompletedCalled++
}, onDisposed: {
onDisposedCalled++
})
XCTAssertTrue(lastElement == nil)
XCTAssertTrue(lastError == nil)
XCTAssertTrue(onNextCalled == 0)
XCTAssertTrue(onErrorCalled == 0)
XCTAssertTrue(onCompletedCalled == 0)
XCTAssertTrue(onDisposedCalled == 0)
publishSubject.on(.Next(1))
XCTAssertTrue(lastElement == 1)
XCTAssertTrue(lastError == nil)
XCTAssertTrue(onNextCalled == 1)
XCTAssertTrue(onErrorCalled == 0)
XCTAssertTrue(onCompletedCalled == 0)
XCTAssertTrue(onDisposedCalled == 0)
subscription.dispose()
publishSubject.on(.Next(2))
XCTAssertTrue(lastElement == 1)
XCTAssertTrue(lastError == nil)
XCTAssertTrue(onNextCalled == 1)
XCTAssertTrue(onErrorCalled == 0)
XCTAssertTrue(onCompletedCalled == 0)
XCTAssertTrue(onDisposedCalled == 1)
}
func testSubscribeOnError() {
let publishSubject = PublishSubject<Int>()
var onNextCalled = 0
var onErrorCalled = 0
var onCompletedCalled = 0
var onDisposedCalled = 0
var lastElement: Int? = nil
var lastError: ErrorType? = nil
let subscription = publishSubject.subscribe(onNext: { n in
lastElement = n
onNextCalled++
}, onError: { e in
lastError = e
onErrorCalled++
}, onCompleted: {
onCompletedCalled++
}, onDisposed: {
onDisposedCalled++
})
XCTAssertTrue(lastElement == nil)
XCTAssertTrue(lastError == nil)
XCTAssertTrue(onNextCalled == 0)
XCTAssertTrue(onErrorCalled == 0)
XCTAssertTrue(onCompletedCalled == 0)
XCTAssertTrue(onDisposedCalled == 0)
publishSubject.on(.Error(testError))
XCTAssertTrue(lastElement == nil)
XCTAssertTrue((lastError as? NSError) === testError)
XCTAssertTrue(onNextCalled == 0)
XCTAssertTrue(onErrorCalled == 1)
XCTAssertTrue(onCompletedCalled == 0)
XCTAssertTrue(onDisposedCalled == 1)
subscription.dispose()
publishSubject.on(.Next(2))
publishSubject.on(.Completed)
XCTAssertTrue(lastElement == nil)
XCTAssertTrue((lastError as? NSError) === testError)
XCTAssertTrue(onNextCalled == 0)
XCTAssertTrue(onErrorCalled == 1)
XCTAssertTrue(onCompletedCalled == 0)
XCTAssertTrue(onDisposedCalled == 1)
}
func testSubscribeOnCompleted() {
let publishSubject = PublishSubject<Int>()
var onNextCalled = 0
var onErrorCalled = 0
var onCompletedCalled = 0
var onDisposedCalled = 0
var lastElement: Int? = nil
var lastError: ErrorType? = nil
let subscription = publishSubject.subscribe(onNext: { n in
lastElement = n
onNextCalled++
}, onError: { e in
lastError = e
onErrorCalled++
}, onCompleted: {
onCompletedCalled++
}, onDisposed: {
onDisposedCalled++
})
XCTAssertTrue(lastElement == nil)
XCTAssertTrue(lastError == nil)
XCTAssertTrue(onNextCalled == 0)
XCTAssertTrue(onErrorCalled == 0)
XCTAssertTrue(onCompletedCalled == 0)
XCTAssertTrue(onDisposedCalled == 0)
publishSubject.on(.Completed)
XCTAssertTrue(lastElement == nil)
XCTAssertTrue(lastError == nil)
XCTAssertTrue(onNextCalled == 0)
XCTAssertTrue(onErrorCalled == 0)
XCTAssertTrue(onCompletedCalled == 1)
XCTAssertTrue(onDisposedCalled == 1)
subscription.dispose()
publishSubject.on(.Next(2))
publishSubject.on(.Error(testError))
XCTAssertTrue(lastElement == nil)
XCTAssertTrue(lastError == nil)
XCTAssertTrue(onNextCalled == 0)
XCTAssertTrue(onErrorCalled == 0)
XCTAssertTrue(onCompletedCalled == 1)
XCTAssertTrue(onDisposedCalled == 1)
}
func testDisposed() {
let publishSubject = PublishSubject<Int>()
var onNextCalled = 0
var onErrorCalled = 0
var onCompletedCalled = 0
var onDisposedCalled = 0
var lastElement: Int? = nil
var lastError: ErrorType? = nil
let subscription = publishSubject.subscribe(onNext: { n in
lastElement = n
onNextCalled++
}, onError: { e in
lastError = e
onErrorCalled++
}, onCompleted: {
onCompletedCalled++
}, onDisposed: {
onDisposedCalled++
})
XCTAssertTrue(lastElement == nil)
XCTAssertTrue(lastError == nil)
XCTAssertTrue(onNextCalled == 0)
XCTAssertTrue(onErrorCalled == 0)
XCTAssertTrue(onCompletedCalled == 0)
XCTAssertTrue(onDisposedCalled == 0)
publishSubject.on(.Next(1))
subscription.dispose()
publishSubject.on(.Next(2))
publishSubject.on(.Error(testError))
publishSubject.on(.Completed)
XCTAssertTrue(lastElement == 1)
XCTAssertTrue(lastError == nil)
XCTAssertTrue(onNextCalled == 1)
XCTAssertTrue(onErrorCalled == 0)
XCTAssertTrue(onCompletedCalled == 0)
XCTAssertTrue(onDisposedCalled == 1)
}
} | mit |
brokenhandsio/SteamPress | Sources/SteamPress/Models/Contexts/Admin/CreatePostPageContext.swift | 1 | 422 | struct CreatePostPageContext: Encodable {
let title: String
let editing: Bool
let post: BlogPost?
let draft: Bool
let errors: [String]?
let titleSupplied: String?
let contentsSupplied: String?
let tagsSupplied: [String]?
let slugURLSupplied: String?
let titleError: Bool
let contentsError: Bool
let postPathPrefix: String
let pageInformation: BlogAdminPageInformation
}
| mit |
SmallElephant/FESwiftDemo | 1-CGSizeExtension/1-CGSizeExtensionUITests/__CGSizeExtensionUITests.swift | 1 | 1278 | //
// __CGSizeExtensionUITests.swift
// 1-CGSizeExtensionUITests
//
// Created by FlyElephant on 16/12/16.
// Copyright © 2016年 FlyElephant. All rights reserved.
//
import XCTest
class __CGSizeExtensionUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
airbnb/lottie-ios | Sources/Private/MainThread/NodeRenderSystem/NodeProperties/Protocols/KeypathSearchable.swift | 3 | 565 | //
// KeypathSettable.swift
// lottie-swift
//
// Created by Brandon Withrow on 2/4/19.
//
import Foundation
import QuartzCore
/// Protocol that provides keypath search functionality. Returns all node properties associated with a keypath.
protocol KeypathSearchable {
/// The name of the Keypath
var keypathName: String { get }
/// A list of properties belonging to the keypath.
var keypathProperties: [String: AnyNodeProperty] { get }
/// Children Keypaths
var childKeypaths: [KeypathSearchable] { get }
var keypathLayer: CALayer? { get }
}
| apache-2.0 |
amantaneja/PTEventView | Demo/PTEventViewDemo/PTEventView/PTEventViewCell.swift | 1 | 549 | //
// PTEventViewCellTableViewCell.swift
// PTEventViewDemo
//
// Created by Vinay Kharb on 9/1/17.
// Copyright © 2017 Aman Taneja. All rights reserved.
//
import UIKit
class PTEventViewCell: UITableViewCell {
@IBOutlet weak var cellLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
kzaher/RxSwift | RxExample/RxExample/Examples/UIPickerViewExample/CustomPickerViewAdapterExampleViewController.swift | 2 | 2050 | //
// CustomPickerViewAdapterExampleViewController.swift
// RxExample
//
// Created by Sergey Shulga on 12/07/2017.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
final class CustomPickerViewAdapterExampleViewController: ViewController {
@IBOutlet weak var pickerView: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
Observable.just([[1, 2, 3], [5, 8, 13], [21, 34]])
.bind(to: pickerView.rx.items(adapter: PickerViewViewAdapter()))
.disposed(by: disposeBag)
pickerView.rx.modelSelected(Int.self)
.subscribe(onNext: { models in
print(models)
})
.disposed(by: disposeBag)
}
}
final class PickerViewViewAdapter
: NSObject
, UIPickerViewDataSource
, UIPickerViewDelegate
, RxPickerViewDataSourceType
, SectionedViewDataSourceType {
typealias Element = [[CustomStringConvertible]]
private var items: [[CustomStringConvertible]] = []
func model(at indexPath: IndexPath) throws -> Any {
items[indexPath.section][indexPath.row]
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
items.count
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
items[component].count
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let label = UILabel()
label.text = items[component][row].description
label.textColor = UIColor.orange
label.font = UIFont.preferredFont(forTextStyle: .headline)
label.textAlignment = .center
return label
}
func pickerView(_ pickerView: UIPickerView, observedEvent: Event<Element>) {
Binder(self) { (adapter, items) in
adapter.items = items
pickerView.reloadAllComponents()
}.on(observedEvent)
}
}
| mit |
cdmx/MiniMancera | miniMancera/View/Store/VStoreHeader.swift | 1 | 4399 | import UIKit
class VStoreHeader:UICollectionReusableView
{
private weak var imageView:UIImageView!
private weak var label:UILabel!
private weak var layoutLabelHeight:NSLayoutConstraint!
private let attrTitle:[String:Any]
private let attrDescr:[String:Any]
private let labelMargin2:CGFloat
private let kImageHeight:CGFloat = 150
private let kLabelMargin:CGFloat = 10
private let kBorderHeight:CGFloat = 1
override init(frame:CGRect)
{
attrTitle = [
NSFontAttributeName:UIFont.bold(size:17),
NSForegroundColorAttributeName:UIColor.white]
attrDescr = [
NSFontAttributeName:UIFont.regular(size:14),
NSForegroundColorAttributeName:UIColor.white]
labelMargin2 = kLabelMargin + kLabelMargin
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
isUserInteractionEnabled = false
let imageView:UIImageView = UIImageView()
imageView.isUserInteractionEnabled = false
imageView.contentMode = UIViewContentMode.center
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
self.imageView = imageView
let label:UILabel = UILabel()
label.isUserInteractionEnabled = false
label.backgroundColor = UIColor.clear
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
self.label = label
let border:VBorder = VBorder(color:UIColor(white:1, alpha:0.3))
addSubview(label)
addSubview(border)
addSubview(imageView)
NSLayoutConstraint.topToTop(
view:imageView,
toView:self)
NSLayoutConstraint.height(
view:imageView,
constant:kImageHeight)
NSLayoutConstraint.equalsHorizontal(
view:imageView,
toView:self)
NSLayoutConstraint.topToBottom(
view:label,
toView:imageView)
layoutLabelHeight = NSLayoutConstraint.height(
view:label)
NSLayoutConstraint.equalsHorizontal(
view:label,
toView:self,
margin:kLabelMargin)
NSLayoutConstraint.bottomToBottom(
view:border,
toView:self)
NSLayoutConstraint.height(
view:border,
constant:kBorderHeight)
NSLayoutConstraint.equalsHorizontal(
view:border,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
guard
let attributedText:NSAttributedString = label.attributedText
else
{
return
}
let width:CGFloat = bounds.maxX
let height:CGFloat = bounds.maxY
let usableWidth:CGFloat = width - labelMargin2
let usableSize:CGSize = CGSize(width:usableWidth, height:height)
let boundingRect:CGRect = attributedText.boundingRect(
with:usableSize,
options:NSStringDrawingOptions([
NSStringDrawingOptions.usesLineFragmentOrigin,
NSStringDrawingOptions.usesFontLeading]),
context:nil)
layoutLabelHeight.constant = ceil(boundingRect.size.height)
super.layoutSubviews()
}
//MARK: public
func config(model:MStoreItem)
{
imageView.image = model.option.thumbnail
guard
let title:String = model.option.title,
let descr:String = model.option.descr
else
{
label.attributedText = nil
return
}
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
let stringTitle:NSAttributedString = NSAttributedString(
string:title,
attributes:attrTitle)
let stringDescr:NSAttributedString = NSAttributedString(
string:descr,
attributes:attrDescr)
mutableString.append(stringTitle)
mutableString.append(stringDescr)
label.attributedText = mutableString
setNeedsLayout()
}
}
| mit |
adelang/DoomKit | Sources/Texture.swift | 1 | 3579 | //
// Texture.swift
// DoomKit
//
// Created by Arjan de Lang on 04-01-15.
// Copyright (c) 2015 Blue Depths Media. All rights reserved.
//
import Cocoa
open class Texture {
class PatchDescriptor {
var patchName: String
var xOffset: Int16 = 0
var yOffset: Int16 = 0
init(data: Data, dataOffset: inout Int, patchNames: [String]) {
(data as NSData).getBytes(&xOffset, range: NSMakeRange(dataOffset, MemoryLayout<Int16>.size))
dataOffset += MemoryLayout<Int16>.size
(data as NSData).getBytes(&yOffset, range: NSMakeRange(dataOffset, MemoryLayout<Int16>.size))
dataOffset += MemoryLayout<Int16>.size
var patchNumber: Int16 = 0
(data as NSData).getBytes(&patchNumber, range: NSMakeRange(dataOffset, MemoryLayout<Int16>.size))
patchName = patchNames[Int(patchNumber)]
dataOffset += MemoryLayout<Int16>.size
// Ignore next two shorts
dataOffset += 2 * MemoryLayout<Int16>.size
}
}
var _name: String
open var name: String { get { return _name } }
var _width: Int16 = 0
open var width: Int16 { get { return _width } }
var _height: Int16 = 0
open var height: Int16 { get { return _height } }
var patchDescriptors = [PatchDescriptor]()
var _cachedImage: NSImage?
init(data: Data, dataOffset: inout Int, patchNames: [String]) {
_name = String(data: data.subdata(in: (dataOffset ..< dataOffset + 8)), encoding: .ascii)!.trimmingCharacters(in: CharacterSet(charactersIn: "\0"))
dataOffset += 8
// Ignore next two shorts
dataOffset += 2 * MemoryLayout<Int16>.size
(data as NSData).getBytes(&_width, range: NSMakeRange(dataOffset, MemoryLayout<Int16>.size))
dataOffset += MemoryLayout<Int16>.size
(data as NSData).getBytes(&_height, range: NSMakeRange(dataOffset, MemoryLayout<Int16>.size))
dataOffset += MemoryLayout<Int16>.size
// Ignore next two shorts
dataOffset += 2 * MemoryLayout<Int16>.size
var numberOfPatchDescriptors: Int16 = 0
(data as NSData).getBytes(&numberOfPatchDescriptors, range: NSMakeRange(dataOffset, MemoryLayout<Int16>.size))
dataOffset += MemoryLayout<Int16>.size
for _ in (0 ..< Int(numberOfPatchDescriptors)) {
let patchDescriptor = PatchDescriptor(data: data, dataOffset: &dataOffset, patchNames: patchNames)
patchDescriptors.append(patchDescriptor)
}
}
open func imageWithPalette(_ palette: Palette, usingPatchesFromWad wad: Wad) -> NSImage {
if let image = _cachedImage {
return image
}
let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(_width), pixelsHigh: Int(_height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: Int(4 * width), bitsPerPixel: 32)
NSGraphicsContext.setCurrent(NSGraphicsContext(bitmapImageRep: bitmap!))
// Flip coordinate system
var transform = AffineTransform.identity
transform.translate(x: 0, y: CGFloat(_height))
transform.scale(x: 1, y: -1)
(transform as NSAffineTransform).concat()
let image = NSImage()
image.addRepresentation(bitmap!)
for patchDescriptor in patchDescriptors {
if let patchGraphic = Graphic.graphicWithLumpName(patchDescriptor.patchName, inWad: wad) {
let patchImage = patchGraphic.imageWithPalette(palette)
let patchBitmap = patchImage.representations.first as! NSBitmapImageRep
patchBitmap.draw(at: NSMakePoint(CGFloat(patchDescriptor.xOffset), CGFloat(patchDescriptor.yOffset)))
} else {
print("Unable to find path with name '\(patchDescriptor.patchName)' for texture '\(_name)'")
}
}
_cachedImage = image
return image
}
}
| mit |
zakkhoyt/ColorPicKit | ColorPicKit/Classes/SpectrumView.swift | 1 | 3860 | //
// SpectrumView.swift
// ColorPicKitExample
//
// Created by Zakk Hoyt on 10/25/16.
// Copyright © 2016 Zakk Hoyt. All rights reserved.
//
import UIKit
class SpectrumView: UIView {
// MARK: Variables
private var _borderColor: UIColor = .lightGray
@IBInspectable public var borderColor: UIColor{
get {
return _borderColor
}
set {
if _borderColor != newValue {
_borderColor = newValue
self.layer.borderColor = newValue.cgColor
}
}
}
private var _borderWidth: CGFloat = 0.5
@IBInspectable public var borderWidth: CGFloat{
get {
return _borderWidth
}
set {
if _borderWidth != newValue {
_borderWidth = newValue
self.layer.borderWidth = newValue
}
}
}
fileprivate var imageData: [GradientData] = [GradientData]()
fileprivate var imageDataLength: Int = 0
fileprivate var radialImage: CGImage? = nil
// MARK: Private methods
override open func layoutSubviews() {
super.layoutSubviews()
updateGradient()
}
override open func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {
print("no context")
return
}
context.saveGState()
let borderFrame = bounds.insetBy(dx: -borderWidth / 2.0, dy: -borderWidth / 2.0)
if borderWidth > 0 {
context.setLineWidth(borderWidth)
context.setStrokeColor(borderColor.cgColor)
context.addRect(borderFrame)
context.strokePath()
}
context.addRect(bounds)
context.clip()
if let radialImage = radialImage {
// CGContextDrawImage(context, wheelFrame, radialImage)
context.draw(radialImage, in: bounds)
}
context.restoreGState()
}
fileprivate func updateGradient() {
if bounds.width == 0 || bounds.height == 0 {
return
}
radialImage = nil
let width = Int(bounds.width)
let height = Int(bounds.height)
let dataLength = MemoryLayout<GradientData>.size * width * height
imageData.removeAll()
self.imageDataLength = dataLength
for y in 0 ..< height {
for x in 0 ..< width {
let point = CGPoint(x: CGFloat(x), y: CGFloat(y))
let rgb = rgbaFor(point: point)
let gradientData = GradientData(red: UInt8(rgb.red * CGFloat(255)),
green: UInt8(rgb.green * CGFloat(255)),
blue: UInt8(rgb.blue * CGFloat(255)))
imageData.append(gradientData)
}
}
let bitmapInfo: CGBitmapInfo = []
let callback: CGDataProviderReleaseDataCallback = { _,_,_ in
}
if let dataProvider = CGDataProvider(dataInfo: nil, data: &imageData, size: dataLength, releaseData: callback) {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let renderingIntent = CGColorRenderingIntent.defaultIntent
radialImage = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 24, bytesPerRow: width * 3, space: colorSpace, bitmapInfo: bitmapInfo, provider: dataProvider, decode: nil, shouldInterpolate: true, intent: renderingIntent)
}
setNeedsDisplay()
}
// MARK: Public methods
func rgbaFor(point: CGPoint) -> RGBA {
print("child class must implement")
return UIColor.clear.rgba()
}
}
| mit |
WeltN24/Carlos | Sources/Carlos/Transformers/ConditionedValueTransformation.swift | 1 | 1496 | import Combine
import Foundation
extension CacheLevel {
/**
Applies a conditional transformation to the cache level
The transformation works by changing the type of the value the cache returns when succeeding
Use this transformation when you store a value type but want to mount the cache in a pipeline that works with other value types
- parameter conditionedTransformer: The conditioned transformer that will be applied to every successful result of the method get or (inverse transform) set called on the cache level. The object gets the key used for the get request (where it can apply its condition on) and the fetched value, and returns the transformed value.
- returns: A new cache result of the transformation of the original cache
*/
public func conditionedValueTransformation<A: ConditionedTwoWayTransformer>(transformer: A) -> BasicCache<KeyType, A.TypeOut> where OutputType == A.TypeIn, A.KeyType == KeyType {
BasicCache(
getClosure: { key -> AnyPublisher<A.TypeOut, Error> in
self.get(key)
.flatMap { transformer.conditionalTransform(key: key, value: $0) }
.eraseToAnyPublisher()
},
setClosure: { value, key in
transformer.conditionalInverseTransform(key: key, value: value)
.flatMap { transformedValue in
self.set(transformedValue, forKey: key)
}
.eraseToAnyPublisher()
},
clearClosure: clear,
memoryClosure: onMemoryWarning
)
}
}
| mit |
wireapp/wire-ios | Wire-iOS Tests/AudioButtonOverlayTests.swift | 1 | 2608 | //
// Wire
// Copyright (C) 2016 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/.
//
@testable import Wire
class AudioButtonOverlayTests: ZMSnapshotTestCase {
var sut: AudioButtonOverlay!
var buttonTapHistory: [AudioButtonOverlay.AudioButtonOverlayButtonType]!
override func setUp() {
super.setUp()
buttonTapHistory = []
sut = AudioButtonOverlay()
sut.buttonHandler = { self.buttonTapHistory.append($0) }
}
override func tearDown() {
buttonTapHistory = []
sut = nil
super.tearDown()
}
func testThatItRendersTheButtonOverlayCorrectInitially_Recording() {
sut.setOverlayState(.default)
verify(view: sut)
}
func testThatItRendersTheButtonOverlayCorrectInitially_FinishedRecording() {
sut.recordingState = .finishedRecording
sut.setOverlayState(.default)
verify(view: sut)
}
func testThatItRendersTheButtonOverlayCorrectInitially_FinishedRecording_PlayingAudio() {
sut.recordingState = .finishedRecording
sut.playingState = .playing
sut.setOverlayState(.default)
verify(view: sut)
}
func testThatItChangesItsSize_Expanded() {
sut.setOverlayState(.expanded(0))
verify(view: sut)
}
func testThatItChangesItsSize_Expanded_Half() {
sut.setOverlayState(.expanded(0.5))
verify(view: sut)
}
func testThatItChangesItsSize_Expanded_Full() {
sut.setOverlayState(.expanded(1))
verify(view: sut)
}
func testThatItCallsTheButtonHandlerWithTheCorrectButtonType() {
sut.playButton.sendActions(for: .touchUpInside)
XCTAssertArrayEqual(buttonTapHistory, [AudioButtonOverlay.AudioButtonOverlayButtonType.play])
sut.sendButton.sendActions(for: .touchUpInside)
XCTAssertArrayEqual(buttonTapHistory, [AudioButtonOverlay.AudioButtonOverlayButtonType.play, AudioButtonOverlay.AudioButtonOverlayButtonType.send])
}
}
| gpl-3.0 |
armadsen/ORSSerialPort | Examples/PacketParsingDemo/Swift/Sources/AppDelegate.swift | 2 | 248 | //
// AppDelegate.swift
// PacketParsingDemo
//
// Created by Andrew Madsen on 8/10/15.
// Copyright (c) 2015 Open Reel Software. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
}
| mit |
turekj/ReactiveTODO | ReactiveTODOTests/Classes/Mocks/PriorityImageNameFormatterMock.swift | 1 | 261 | @testable import ReactiveTODOFramework
import Foundation
class PriorityImageNameFormatterMock: PriorityImageNameFormatterProtocol {
var formatReturnValue = ""
func format(priority: Priority) -> String {
return self.formatReturnValue
}
}
| mit |
benlangmuir/swift | validation-test/compiler_crashers_fixed/28103-swift-parser-parsetoken.swift | 65 | 441 | // 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
// RUN: not %target-swift-frontend %s -typecheck
import A}{{func b<T:T.g
let{enum S{func b{
| apache-2.0 |
mrdepth/EVEOnlineAPI | Playground.playground/Contents.swift | 1 | 93 | //: Playground - noun: a place where people can play
import UIKit
import PlaygroundSupport
| mit |
bigscreen/mangindo-ios | Mangindo/Modules/Contents/ContentsViewController.swift | 1 | 2250 | //
// ContentsViewController.swift
// Mangindo
//
// Created by Gallant Pratama on 8/30/17.
// Copyright © 2017 Gallant Pratama. All rights reserved.
//
import UIKit
import iCarousel
class ContentsViewController: UIViewController {
@IBOutlet weak var carousel: iCarousel!
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
var pageTitle = "Manga Content"
var presenter: IContentsPresenter!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = presenter.getDisplayedNavTitle(pageTitle)
carousel.delegate = self
carousel.dataSource = self
carousel.isPagingEnabled = true
carousel.bounces = false
carousel.isScrollEnabled = true
presenter.fetchContents()
}
}
extension ContentsViewController: IContentsView {
func startLoading() {
loadingIndicator.startAnimating()
}
func stopLoading() {
loadingIndicator.stopAnimating()
}
func showData() {
carousel.reloadData()
}
func showAlert(message: String) {
let alert = UIAlertController(title: "Oops!", message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Back", style: UIAlertActionStyle.default, handler: { _ in
if let navController = self.navigationController {
navController.popViewController(animated: true)
}
}))
alert.addAction(UIAlertAction(title: "Reload", style: UIAlertActionStyle.default, handler: { _ in
self.presenter.fetchContents()
}))
self.present(alert, animated: true, completion: nil)
}
}
extension ContentsViewController: iCarouselDelegate, iCarouselDataSource {
func numberOfItems(in carousel: iCarousel) -> Int {
return presenter.contents.count
}
func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
let pageView = ContentZoomableView(frame: CGRect(x: 0, y: 0, width: carousel.frame.width, height: carousel.frame.height))
pageView.imageUrl = presenter.contents[index].imageUrl
return pageView
}
}
| mit |
WPO-Foundation/iTether | app/tether/AppDelegate.swift | 1 | 2114 | //
// AppDelegate.swift
// tether
//
// Created by Patrick Meenan on 8/7/17.
// Copyright © 2017 WebPageTest LLC. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 |
jtbandes/swift-compiler-crashes | crashes-fuzzing/28102-swift-parser-parseidentifier.swift | 2 | 231 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class n{class A<T where h:a{enum e{{}class A{let a{func a<{A{
| mit |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Models/BloggingPromptSettingsReminderDays+CoreDataClass.swift | 1 | 1056 | import Foundation
import CoreData
import WordPressKit
public class BloggingPromptSettingsReminderDays: NSManagedObject {
func configure(with remoteReminderDays: RemoteBloggingPromptsSettings.ReminderDays) {
self.monday = remoteReminderDays.monday
self.tuesday = remoteReminderDays.tuesday
self.wednesday = remoteReminderDays.wednesday
self.thursday = remoteReminderDays.thursday
self.friday = remoteReminderDays.friday
self.saturday = remoteReminderDays.saturday
self.sunday = remoteReminderDays.sunday
}
func getActiveWeekdays() -> [BloggingRemindersScheduler.Weekday] {
return [
sunday,
monday,
tuesday,
wednesday,
thursday,
friday,
saturday
].enumerated().compactMap { (index: Int, isReminderActive: Bool) in
guard isReminderActive else {
return nil
}
return BloggingRemindersScheduler.Weekday(rawValue: index)
}
}
}
| gpl-2.0 |
gffny/rgbycch | ios/coachapp/coachapp/coachapp/views/FieldView.swift | 1 | 1798 | //
// FieldView.swift
// coachapp
//
// Created by John D. Gaffney on 7/8/15.
// Copyright (c) 2015 gffny.com. All rights reserved.
//
import UIKit
@IBDesignable class FieldView: UIView {
// Our custom view from the XIB file
weak var view: UIView!
@IBOutlet weak var actionLabel: UILabel!
override init(frame: CGRect) {
// 1. setup any properties here
// 2. call super.init(frame:)
super.init(frame: frame)
// 3. Setup view from .xib file
xibSetup()
}
required init(coder aDecoder: NSCoder) {
// 1. setup any properties here
// 2. call super.init(coder:)
super.init(coder: aDecoder)
// 3. Setup view from .xib file
xibSetup()
}
func xibSetup() {
view = loadViewFromNib()
// use bounds not frame or it'll be offset
view.frame = bounds
// Make the view stretch with containing view
view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
renderKickOffDisplay()
// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "FieldRepresentation", bundle: bundle)
// Assumes UIView is top level and only object in CustomView.xib file
let view = nib.instantiateWithOwner(self, options: nil)[0] as UIView
return view
}
func renderKickOffDisplay() {
// hide any none used controls
actionLabel.hidden = false
actionLabel.text = "Tap for Kick Off"
}
func clearDisplay() {
actionLabel.hidden = true
}
}
| mit |
ibm-bluemix-omnichannel-iclabs/ICLab-OmniChannelAppDev | iOS/Pods/BluemixAppID/Source/BluemixAppID/internal/SecurityUtils.swift | 2 | 10311 | /* * Copyright 2016, 2017 IBM Corp.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
internal class SecurityUtils {
private static func getKeyBitsFromKeyChain(_ tag:String) throws -> Data {
let keyAttr : [NSString:AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrApplicationTag: tag as AnyObject,
kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecReturnData : true as AnyObject
]
var result: AnyObject?
let status = SecItemCopyMatching(keyAttr as CFDictionary, &result)
guard status == errSecSuccess else {
throw AppIDError.generalError
}
return result as! Data
}
internal static func generateKeyPair(_ keySize:Int, publicTag:String, privateTag:String) throws {
//make sure keys are deleted
_ = SecurityUtils.deleteKeyFromKeyChain(publicTag)
_ = SecurityUtils.deleteKeyFromKeyChain(privateTag)
var status:OSStatus = noErr
var privateKey:SecKey?
var publicKey:SecKey?
let privateKeyAttr : [NSString:AnyObject] = [
kSecAttrIsPermanent : true as AnyObject,
kSecAttrApplicationTag : privateTag as AnyObject,
kSecAttrKeyClass : kSecAttrKeyClassPrivate
]
let publicKeyAttr : [NSString:AnyObject] = [
kSecAttrIsPermanent : true as AnyObject,
kSecAttrApplicationTag : publicTag as AnyObject,
kSecAttrKeyClass : kSecAttrKeyClassPublic,
]
let keyPairAttr : [NSString:AnyObject] = [
kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecAttrKeySizeInBits : keySize as AnyObject,
kSecPublicKeyAttrs : publicKeyAttr as AnyObject,
kSecPrivateKeyAttrs : privateKeyAttr as AnyObject
]
status = SecKeyGeneratePair(keyPairAttr as CFDictionary, &publicKey, &privateKey)
if (status != errSecSuccess) {
throw AppIDError.generalError
}
}
private static func getKeyRefFromKeyChain(_ tag:String) throws -> SecKey {
let keyAttr : [NSString:AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrApplicationTag: tag as AnyObject,
kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecReturnRef : kCFBooleanTrue
]
var result: AnyObject?
let status = SecItemCopyMatching(keyAttr as CFDictionary, &result)
guard status == errSecSuccess else {
throw AppIDError.generalError
}
return result as! SecKey
}
internal static func getItemFromKeyChain(_ label:String) -> String? {
let query: [NSString: AnyObject] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: label as AnyObject,
kSecReturnData: kCFBooleanTrue
]
var results: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &results)
if status == errSecSuccess {
let data = results as! Data
let password = String(data: data, encoding: String.Encoding.utf8)!
return password
}
return nil
}
public static func getJWKSHeader() throws ->[String:Any] {
let publicKey = try? SecurityUtils.getKeyBitsFromKeyChain(AppIDConstants.publicKeyIdentifier)
guard let unWrappedPublicKey = publicKey, let pkModulus : Data = getPublicKeyMod(unWrappedPublicKey), let pkExponent : Data = getPublicKeyExp(unWrappedPublicKey) else {
throw AppIDError.generalError
}
let mod:String = Utils.base64StringFromData(pkModulus, isSafeUrl: true)
let exp:String = Utils.base64StringFromData(pkExponent, isSafeUrl: true)
let publicKeyJSON : [String:Any] = [
"e" : exp as AnyObject,
"n" : mod as AnyObject,
"kty" : AppIDConstants.JSON_RSA_VALUE
]
return publicKeyJSON
}
private static func getPublicKeyMod(_ publicKeyBits: Data) -> Data? {
var iterator : Int = 0
iterator += 1 // TYPE - bit stream - mod + exp
_ = derEncodingGetSizeFrom(publicKeyBits, at:&iterator) // Total size
iterator += 1 // TYPE - bit stream mod
let mod_size : Int = derEncodingGetSizeFrom(publicKeyBits, at:&iterator)
if(mod_size == -1) {
return nil
}
return publicKeyBits.subdata(in: NSMakeRange(iterator, mod_size).toRange()!)
}
//Return public key exponent
private static func getPublicKeyExp(_ publicKeyBits: Data) -> Data? {
var iterator : Int = 0
iterator += 1 // TYPE - bit stream - mod + exp
_ = derEncodingGetSizeFrom(publicKeyBits, at:&iterator) // Total size
iterator += 1// TYPE - bit stream mod
let mod_size : Int = derEncodingGetSizeFrom(publicKeyBits, at:&iterator)
iterator += mod_size
iterator += 1 // TYPE - bit stream exp
let exp_size : Int = derEncodingGetSizeFrom(publicKeyBits, at:&iterator)
//Ensure we got an exponent size
if(exp_size == -1) {
return nil
}
return publicKeyBits.subdata(in: NSMakeRange(iterator, exp_size).toRange()!)
}
private static func derEncodingGetSizeFrom(_ buf : Data, at iterator: inout Int) -> Int{
// Have to cast the pointer to the right size
//let pointer = UnsafePointer<UInt8>((buf as NSData).bytes)
//let count = buf.count
// Get our buffer pointer and make an array out of it
//let buffer = UnsafeBufferPointer<UInt8>(start:pointer, count:count)
let data = buf//[UInt8](buffer)
var itr : Int = iterator
var num_bytes :UInt8 = 1
var ret : Int = 0
if (data[itr] > 0x80) {
num_bytes = data[itr] - 0x80
itr += 1
}
for i in 0 ..< Int(num_bytes) {
ret = (ret * 0x100) + Int(data[itr + i])
}
iterator = itr + Int(num_bytes)
return ret
}
internal static func signString(_ payloadString:String, keyIds ids:(publicKey: String, privateKey: String), keySize: Int) throws -> String {
do {
let privateKeySec = try getKeyRefFromKeyChain(ids.privateKey)
guard let payloadData : Data = payloadString.data(using: String.Encoding.utf8) else {
throw AppIDError.generalError
}
let signedData = try signData(payloadData, privateKey:privateKeySec)
//return signedData.base64EncodedString()
return Utils.base64StringFromData(signedData, isSafeUrl: true)
}
catch {
throw AppIDError.generalError
}
}
private static func signData(_ data:Data, privateKey:SecKey) throws -> Data {
func doSha256(_ dataIn:Data) throws -> Data {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
dataIn.withUnsafeBytes {
_ = CC_SHA256($0, CC_LONG(dataIn.count), &hash)
}
return Data(bytes: hash)
}
guard let digest:Data = try? doSha256(data), let signedData: NSMutableData = NSMutableData(length: SecKeyGetBlockSize(privateKey)) else {
throw AppIDError.generalError
}
var signedDataLength: Int = signedData.length
let digestBytes: UnsafePointer<UInt8> = ((digest as NSData).bytes).bindMemory(to: UInt8.self, capacity: digest.count)
let digestlen = digest.count
let mutableBytes: UnsafeMutablePointer<UInt8> = signedData.mutableBytes.assumingMemoryBound(to: UInt8.self)
let signStatus:OSStatus = SecKeyRawSign(privateKey, SecPadding.PKCS1SHA256, digestBytes, digestlen,
mutableBytes, &signedDataLength)
guard signStatus == errSecSuccess else {
throw AppIDError.generalError
}
return signedData as Data
}
internal static func saveItemToKeyChain(_ data:String, label: String) -> Bool{
guard let stringData = data.data(using: String.Encoding.utf8) else {
return false
}
let key: [NSString: AnyObject] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: label as AnyObject,
kSecValueData: stringData as AnyObject
]
var status = SecItemAdd(key as CFDictionary, nil)
if(status != errSecSuccess){
if(SecurityUtils.removeItemFromKeyChain(label) == true) {
status = SecItemAdd(key as CFDictionary, nil)
}
}
return status == errSecSuccess
}
internal static func removeItemFromKeyChain(_ label: String) -> Bool{
let delQuery : [NSString:AnyObject] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: label as AnyObject
]
let delStatus:OSStatus = SecItemDelete(delQuery as CFDictionary)
return delStatus == errSecSuccess
}
internal static func deleteKeyFromKeyChain(_ tag:String) -> Bool{
let delQuery : [NSString:AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrApplicationTag : tag as AnyObject
]
let delStatus:OSStatus = SecItemDelete(delQuery as CFDictionary)
return delStatus == errSecSuccess
}
}
| apache-2.0 |
1985apps/PineKit | Pod/Classes/PineMenuTransition.swift | 1 | 1791 | //
// KamaConfig.swift
// KamaUIKit
//
// Created by Prakash Raman on 13/02/16.
// Copyright © 2016 1985. All rights reserved.
//
import Foundation
import UIKit
open class PineMenuTransition : NSObject {
open var mainController: PineMenuViewController?
open var menuView: PineBaseMenuView?
public override init(){
self.mainController = nil
}
// ONCE THE CONTROLLER IS SETUP THE MENU IS SETUP AS WELL
// START MENU POSITION IS VERY IMPORTANT
func setController(_ controller: PineMenuViewController){
self.mainController = controller
self.menuView = self.mainController!.menuView!
self.setup()
}
func setup(){
self.mainController!.menuView!.frame = self.mainController!.view.frame
}
func toggle(){
setup()
if self.isOpen() {
close()
} else {
open()
}
}
func isOpen() -> Bool {
let contentFrame = self.mainController!.contentNavigationController!.view.frame
let controllerFrame = self.mainController!.view.frame
return (controllerFrame != contentFrame) ? true : false
}
func open(){
UIView.animate(withDuration: PineConfig.Menu.transitionDuration, animations: { () -> Void in
var frame = (self.mainController?.contentNavigationController!.view.frame)! as CGRect
frame.origin.x = 200
self.mainController?.contentNavigationController!.view.frame = frame
})
}
func close(){
UIView.animate(withDuration: PineConfig.Menu.transitionDuration, animations: { () -> Void in
self.mainController!.contentNavigationController!.view.frame = self.mainController!.view.frame
})
}
}
| mit |
anirudh24seven/wikipedia-ios | Wikipedia/Code/WMFReferencePanelViewController.swift | 1 | 2029 |
import Foundation
class WMFReferencePanelViewController: UIViewController {
@IBOutlet private var containerViewHeightConstraint:NSLayoutConstraint!
@IBOutlet var containerView:UIView!
var reference:WMFReference?
override func viewDidLoad() {
super.viewDidLoad()
let tapRecognizer = UITapGestureRecognizer.bk_recognizerWithHandler { (sender, state, location) in
if state == .Ended {
self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
}
view.addGestureRecognizer((tapRecognizer as? UITapGestureRecognizer)!)
embedContainerControllerView()
}
private func panelHeight() -> CGFloat {
return view.frame.size.height * (UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation) ? 0.4 : 0.6)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
containerViewHeightConstraint.constant = panelHeight()
containerController.scrollEnabled = true
containerController.scrollToTop()
}
private lazy var containerController: WMFReferencePopoverMessageViewController = {
let referenceVC = WMFReferencePopoverMessageViewController.wmf_initialViewControllerFromClassStoryboard()
referenceVC.reference = self.reference
return referenceVC
}()
private func embedContainerControllerView() {
containerController.willMoveToParentViewController(self)
containerController.view.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(containerController.view!)
containerView.bringSubviewToFront(containerController.view!)
containerController.view.mas_makeConstraints { make in
make.top.bottom().leading().and().trailing().equalTo()(self.containerView)
}
self.addChildViewController(containerController)
containerController.didMoveToParentViewController(self)
}
}
| mit |
vector-im/riot-ios | Riot/Modules/Settings/KeyBackup/SettingsKeyBackupViewModelType.swift | 1 | 1508 | /*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
protocol SettingsKeyBackupViewModelViewDelegate: class {
func settingsKeyBackupViewModel(_ viewModel: SettingsKeyBackupViewModelType, didUpdateViewState viewState: SettingsKeyBackupViewState)
func settingsKeyBackupViewModel(_ viewModel: SettingsKeyBackupViewModelType, didUpdateNetworkRequestViewState networkRequestViewSate: SettingsKeyBackupNetworkRequestViewState)
func settingsKeyBackupViewModelShowKeyBackupSetup(_ viewModel: SettingsKeyBackupViewModelType)
func settingsKeyBackup(_ viewModel: SettingsKeyBackupViewModelType, showKeyBackupRecover keyBackupVersion: MXKeyBackupVersion)
func settingsKeyBackup(_ viewModel: SettingsKeyBackupViewModelType, showKeyBackupDeleteConfirm keyBackupVersion: MXKeyBackupVersion)
}
protocol SettingsKeyBackupViewModelType {
var viewDelegate: SettingsKeyBackupViewModelViewDelegate? { get set }
func process(viewAction: SettingsKeyBackupViewAction)
}
| apache-2.0 |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/Cartography/Cartography/Compound.swift | 6 | 3774 | //
// Compound.swift
// Cartography
//
// Created by Robert Böhnke on 18/06/14.
// Copyright (c) 2014 Robert Böhnke. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public protocol Compound {
var context: Context { get }
var properties: [Property] { get }
}
/// Compound properties conforming to this protocol can use the `==` operator
/// with other compound properties of the same type.
public protocol RelativeCompoundEquality : Compound { }
/// Declares a property equal to a the result of an expression.
///
/// - parameter lhs: The affected property. The associated item will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The expression.
///
/// - returns: An `NSLayoutConstraint`.
///
@discardableResult public func == <P: RelativeCompoundEquality>(lhs: P, rhs: Expression<P>) -> [NSLayoutConstraint] {
return lhs.context.addConstraint(lhs, coefficients: rhs.coefficients, to: rhs.value)
}
/// Declares a property equal to another compound property.
///
/// - parameter lhs: The affected property. The associated item will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
@discardableResult public func == <P: RelativeCompoundEquality>(lhs: P, rhs: P) -> [NSLayoutConstraint] {
return lhs.context.addConstraint(lhs, to: rhs)
}
/// Compound properties conforming to this protocol can use the `<=` and `>=`
/// operators with other compound properties of the same type.
public protocol RelativeCompoundInequality : Compound { }
/// Declares a property less than or equal to another compound property.
///
/// - parameter lhs: The affected property. The associated item will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
/// - returns: An `NSLayoutConstraint`.
///
@discardableResult public func <= <P: RelativeCompoundInequality>(lhs: P, rhs: P) -> [NSLayoutConstraint] {
return lhs.context.addConstraint(lhs, to: rhs, relation: .lessThanOrEqual)
}
/// Declares a property greater than or equal to another compound property.
///
/// - parameter lhs: The affected property. The associated item will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
/// - returns: An `NSLayoutConstraint`.
///
@discardableResult public func >= <P: RelativeCompoundInequality>(lhs: P, rhs: P) -> [NSLayoutConstraint] {
return lhs.context.addConstraint(lhs, to: rhs, relation: .greaterThanOrEqual)
}
/// Declares a property less than or equal to the result of an expression.
///
/// - parameter lhs: The affected property. The associated item will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
/// - returns: An `NSLayoutConstraint`.
///
@discardableResult public func <= <P: RelativeCompoundInequality>(lhs: P, rhs: Expression<P>) -> [NSLayoutConstraint] {
return lhs.context.addConstraint(lhs, coefficients: rhs.coefficients, to: rhs.value, relation: .lessThanOrEqual)
}
/// Declares a property greater than or equal to the result of an expression.
///
/// - parameter lhs: The affected property. The associated item will have
/// `translatesAutoresizingMaskIntoConstraints` set to `false`.
/// - parameter rhs: The other property.
///
/// - returns: An `NSLayoutConstraint`.
///
@discardableResult public func >= <P: RelativeCompoundInequality>(lhs: P, rhs: Expression<P>) -> [NSLayoutConstraint] {
return lhs.context.addConstraint(lhs, coefficients: rhs.coefficients, to: rhs.value, relation: .greaterThanOrEqual)
}
| mit |
HarrisLee/Utils | KMNavigationBarTransition/Example/AppDelegate.swift | 1 | 2182 | //
// AppDelegate.swift
// KMNavigationBarTransition
//
// Created by Zhouqi Mo on 1/1/16.
// Copyright © 2016 Zhouqi Mo. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
scinfu/SwiftSoup | Tests/SwiftSoupTests/TagTest.swift | 1 | 2783 | //
// TagTest.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 17/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import XCTest
import SwiftSoup
class TagTest: XCTestCase {
func testLinuxTestSuiteIncludesAllTests() {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
let thisClass = type(of: self)
let linuxCount = thisClass.allTests.count
let darwinCount = Int(thisClass.defaultTestSuite.testCaseCount)
XCTAssertEqual(linuxCount, darwinCount, "\(darwinCount - linuxCount) tests are missing from allTests")
#endif
}
func testIsCaseSensitive()throws {
let p1: Tag = try Tag.valueOf("P")
let p2: Tag = try Tag.valueOf("p")
XCTAssertFalse(p1.equals(p2))
}
func testCanBeInsensitive()throws {
let p1: Tag = try Tag.valueOf("P", ParseSettings.htmlDefault)
let p2: Tag = try Tag.valueOf("p", ParseSettings.htmlDefault)
XCTAssertEqual(p1, p2)
}
func testTrims()throws {
let p1: Tag = try Tag.valueOf("p")
let p2: Tag = try Tag.valueOf(" p ")
XCTAssertEqual(p1, p2)
}
func testEquality()throws {
let p1: Tag = try Tag.valueOf("p")
let p2: Tag = try Tag.valueOf("p")
XCTAssertTrue(p1.equals(p2))
XCTAssertTrue(p1 == p2)
}
func testDivSemantics()throws {
let div = try Tag.valueOf("div")
XCTAssertTrue(div.isBlock())
XCTAssertTrue(div.formatAsBlock())
}
func testPSemantics()throws {
let p = try Tag.valueOf("p")
XCTAssertTrue(p.isBlock())
XCTAssertFalse(p.formatAsBlock())
}
func testImgSemantics()throws {
let img = try Tag.valueOf("img")
XCTAssertTrue(img.isInline())
XCTAssertTrue(img.isSelfClosing())
XCTAssertFalse(img.isBlock())
}
func testDefaultSemantics()throws {
let foo = try Tag.valueOf("FOO") // not defined
let foo2 = try Tag.valueOf("FOO")
XCTAssertEqual(foo, foo2)
XCTAssertTrue(foo.isInline())
XCTAssertTrue(foo.formatAsBlock())
}
func testValueOfChecksNotEmpty() {
XCTAssertThrowsError(try Tag.valueOf(" "))
}
static var allTests = {
return [
("testLinuxTestSuiteIncludesAllTests", testLinuxTestSuiteIncludesAllTests),
("testIsCaseSensitive", testIsCaseSensitive),
("testCanBeInsensitive", testCanBeInsensitive),
("testTrims", testTrims),
("testEquality", testEquality),
("testDivSemantics", testDivSemantics),
("testPSemantics", testPSemantics),
("testImgSemantics", testImgSemantics),
("testDefaultSemantics", testDefaultSemantics),
("testValueOfChecksNotEmpty", testValueOfChecksNotEmpty)
]
}()
}
| mit |
ZamzamInc/ZamzamKitData | ZamzamKitData Example/SecondViewController.swift | 1 | 477 | //
// SecondViewController.swift
// ZamzamKitData Example
//
// Created by Basem Emara on 3/19/16.
//
//
import UIKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
cagaray/peek-coding-challenge | PeekCodingChallengeTests/TwitterRequestTest.swift | 1 | 1426 | //
// TwitterRequestTest.swift
// PeekCodingChallenge
//
// Created by Cristián Garay on 5/18/16.
// Copyright © 2016 Cristian Garay. All rights reserved.
//
import XCTest
@testable import PeekCodingChallenge
class TwitterRequestTest: XCTestCase {
var twitterRequest: TwitterRequest? = TwitterRequest(search: "%40peek", count: 7, .Mixed, nil)
var peekMentionsArray = [Tweet]()
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
func testFetchTweets(){
twitterRequest!.fetchTweets{
(tweetArray: [Tweet]) in
for tweet in tweetArray {
self.peekMentionsArray.append(tweet)
}
XCTAssertEqual(self.peekMentionsArray.count, 7)
}
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/02402-swift-sourcemanager-getmessage.swift | 11 | 249 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct A {
i> c { func a<T where T: B<T : e
class B<T where T>(("
class
case c,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/03852-swift-sourcemanager-getmessage.swift | 11 | 329 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct d<1 {
let f = compose(x: a {
var b { func b: a : b: b> {
class B<T where T where I.b {
println() {
}
init<T {
func b: S<A.b {
class
case c,
func f<1 {
c
| mit |
zachmokahn/SUV | Sources/SUV/Util/Status.swift | 1 | 129 | public enum Status {
case OK
case Fail(Int32)
public init(_ code: Int32) {
self = code == 0 ? .OK : .Fail(code)
}
}
| mit |
huangboju/Moots | Examples/QuartzDemo/QuartzDemoUITests/QuartzDemoUITests.swift | 1 | 1255 | //
// QuartzDemoUITests.swift
// QuartzDemoUITests
//
// Created by 伯驹 黄 on 2017/4/7.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import XCTest
class QuartzDemoUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
zachmokahn/SUV | Sources/SUV/Operation/FSRequestCleanup.swift | 1 | 77 | public typealias FSRequestCleanup = (UnsafeMutablePointer<UVFSType>) -> Void
| mit |
oskarpearson/rileylink_ios | MinimedKit/PumpEvents/BatteryPumpEvent.swift | 1 | 774 | //
// BatteryPumpEvent.swift
// RileyLink
//
// Created by Pete Schwamb on 3/8/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public struct BatteryPumpEvent: TimestampedPumpEvent {
public let length: Int
public let rawData: Data
public let timestamp: DateComponents
public init?(availableData: Data, pumpModel: PumpModel) {
length = 7
guard length <= availableData.count else {
return nil
}
rawData = availableData.subdata(in: 0..<length)
timestamp = DateComponents(pumpEventData: availableData, offset: 2)
}
public var dictionaryRepresentation: [String: Any] {
return [
"_type": "Battery",
]
}
}
| mit |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/0450-llvm-foldingsetimpl-findnodeorinsertpos.swift | 13 | 372 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
import Foundation
protocol C {
class A where g(t: c> () -> {
class func a("A? {
}
var e: C) -> T where A"A.c {
extension NSSet {
func g<f : P {
}
struct B<T
| apache-2.0 |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/0385-swift-declcontext-lookupqualified.swift | 13 | 395 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class func g() {
class B<T where T.b : Int = T) {
print(T.init(n: U : Array) -> Int {
var e: T where T>)-> T -> () -> T -> T>(AnyObject) -> Void>("A: T -> (f<T>)
private let f = a
| apache-2.0 |
CoderLala/DouYZBTest | DouYZB/DouYZB/Classes/Main/View/CollectionPrettyCell.swift | 1 | 693 | //
// CollectionPrettyCell.swift
// DouYZB
//
// Created by 黄金英 on 17/2/6.
// Copyright © 2017年 黄金英. All rights reserved.
//
import UIKit
import Kingfisher
class CollectionPrettyCell: CollectionBaseCell {
//控件属性
@IBOutlet weak var cityBtn: UIButton!
//定义模型属性
override var anchor : AnchorModel?{
didSet{
guard let anchor = anchor else {
return
}
//1. 将属性传递给父类
super.anchor = anchor
//2.显示所在城市
cityBtn.setTitle(anchor.anchor_city, for: .normal)
}
}
}
| mit |
huonw/swift | test/SILGen/opaque_values_silgen_lib.swift | 3 | 4323 |
// RUN: %target-swift-emit-silgen -enable-sil-ownership -enable-sil-opaque-values -emit-sorted-sil -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck %s
precedencegroup AssignmentPrecedence { assignment: true }
enum Optional<Wrapped> {
case none
case some(Wrapped)
}
protocol EmptyP {}
struct String { var ptr: Builtin.NativeObject }
// Tests Empty protocol + Builtin.NativeObject enum (including opaque tuples as a return value)
// ---
// CHECK-LABEL: sil hidden @$Ss21s010______PAndS_casesyyF : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: [[MTYPE:%.*]] = metatype $@thin PAndSEnum.Type
// CHECK: [[EAPPLY:%.*]] = apply {{.*}}([[MTYPE]]) : $@convention(thin) (@thin PAndSEnum.Type) -> @owned @callee_guaranteed (@in_guaranteed EmptyP, @guaranteed String) -> @out PAndSEnum
// CHECK: destroy_value [[EAPPLY]]
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '$Ss21s010______PAndS_casesyyF'
func s010______PAndS_cases() {
_ = PAndSEnum.A
}
// Test emitBuiltinReinterpretCast.
// ---
// CHECK-LABEL: sil hidden @$Ss21s020__________bitCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in_guaranteed T, @thick U.Type) -> @out U {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $T,
// CHECK: [[CAST:%.*]] = unchecked_bitwise_cast [[ARG]] : $T to $U
// CHECK: [[RET:%.*]] = copy_value [[CAST]] : $U
// CHECK-NOT: destroy_value [[COPY]] : $T
// CHECK: return [[RET]] : $U
// CHECK-LABEL: } // end sil function '$Ss21s020__________bitCast_2toq_x_q_mtr0_lF'
func s020__________bitCast<T, U>(_ x: T, to type: U.Type) -> U {
return Builtin.reinterpretCast(x)
}
// Test emitBuiltinCastReference
// ---
// CHECK-LABEL: sil hidden @$Ss21s030__________refCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in_guaranteed T, @thick U.Type) -> @out U {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $T, %1 : @trivial $@thick U.Type):
// CHECK: [[COPY:%.*]] = copy_value [[ARG]] : $T
// CHECK: [[SRC:%.*]] = alloc_stack $T
// CHECK: store [[COPY]] to [init] [[SRC]] : $*T
// CHECK: [[DEST:%.*]] = alloc_stack $U
// CHECK: unchecked_ref_cast_addr T in [[SRC]] : $*T to U in [[DEST]] : $*U
// CHECK: [[LOAD:%.*]] = load [take] [[DEST]] : $*U
// CHECK: dealloc_stack [[DEST]] : $*U
// CHECK: dealloc_stack [[SRC]] : $*T
// CHECK-NOT: destroy_value [[ARG]] : $T
// CHECK: return [[LOAD]] : $U
// CHECK-LABEL: } // end sil function '$Ss21s030__________refCast_2toq_x_q_mtr0_lF'
func s030__________refCast<T, U>(_ x: T, to: U.Type) -> U {
return Builtin.castReference(x)
}
// Init of Empty protocol + Builtin.NativeObject enum (including opaque tuples as a return value)
// ---
// CHECK-LABEL: sil shared [transparent] @$Ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmF : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum {
// CHECK: bb0([[ARG0:%.*]] : @owned $EmptyP, [[ARG1:%.*]] : @owned $String, [[ARG2:%.*]] : @trivial $@thin PAndSEnum.Type):
// CHECK: [[RTUPLE:%.*]] = tuple ([[ARG0]] : $EmptyP, [[ARG1]] : $String)
// CHECK: [[RETVAL:%.*]] = enum $PAndSEnum, #PAndSEnum.A!enumelt.1, [[RTUPLE]] : $(EmptyP, String)
// CHECK: return [[RETVAL]] : $PAndSEnum
// CHECK-LABEL: } // end sil function '$Ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmF'
// CHECK-LABEL: sil shared [transparent] [thunk] @$Ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmFTc : $@convention(thin) (@thin PAndSEnum.Type) -> @owned @callee_guaranteed (@in_guaranteed EmptyP, @guaranteed String) -> @out PAndSEnum {
// CHECK: bb0([[ARG:%.*]] : @trivial $@thin PAndSEnum.Type):
// CHECK: [[RETVAL:%.*]] = partial_apply [callee_guaranteed] {{.*}}([[ARG]]) : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum
// CHECK: [[CANONICAL_THUNK_FN:%.*]] = function_ref @$Ss6EmptyP_pSSs9PAndSEnumOIegixr_sAA_pSSACIegngr_TR : $@convention(thin) (@in_guaranteed EmptyP, @guaranteed String, @guaranteed @callee_guaranteed (@in EmptyP, @owned String) -> @out PAndSEnum) -> @out PAndSEnum
// CHECK: [[CANONICAL_THUNK:%.*]] = partial_apply [callee_guaranteed] [[CANONICAL_THUNK_FN]]([[RETVAL]])
// CHECK: return [[CANONICAL_THUNK]] : $@callee_guaranteed (@in_guaranteed EmptyP, @guaranteed String) -> @out PAndSEnum
// CHECK-LABEL: } // end sil function '$Ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmFTc'
enum PAndSEnum { case A(EmptyP, String) }
| apache-2.0 |
sumitlni/LNITaskList | LNITaskListDemo/ViewController.swift | 1 | 2975 | //
// ViewController.swift
// LNITaskListDemo
//
// Created by Sumit Chawla on 6/9/16.
//
// The MIT License (MIT)
//
// Copyright © 2016 Loud Noise Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var switch1: UISwitch!
@IBOutlet weak var switch2: UISwitch!
@IBOutlet weak var switch3: UISwitch!
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.textView.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func log(text:String) {
let newText = "\(self.textView.text)\n\(text)"
self.textView.text = newText
}
func asyncTaskWithAnswer(name:String, taskList:LNITaskList, answer:Bool) {
dispatch_async(dispatch_get_main_queue()) {
self.log("Now executing \(name) with result = \(answer)")
taskList.markDone(answer)
}
}
@IBAction func startTasks(sender: AnyObject) {
textView.text = ""
// Form the task list
let taskList = LNITaskList()
taskList.onSuccess { () in
self.log("Success!")
}.onFailure {
self.log("Failed!")
}.addStep {
self.asyncTaskWithAnswer("Task 1", taskList: taskList, answer: self.switch1.on)
}.addStep {
self.asyncTaskWithAnswer("Task 2", taskList: taskList, answer: self.switch2.on)
}.addStep {
self.asyncTaskWithAnswer("Task 3", taskList: taskList, answer: self.switch3.on)
}.start()
}
}
| mit |
ello/ElloOSSUIFonts | Pod/Classes/ElloOSSUIFonts.swift | 1 | 1912 | extension UIFont {
public class func loadFonts() {}
public class func defaultFont(_ size: CGFloat = 14) -> UIFont { return UIFont.systemFont(ofSize: size) }
public class func defaultBoldFont(_ size: CGFloat = 14) -> UIFont { return UIFont.boldSystemFont(ofSize: size) }
public class func defaultItalicFont(_ size: CGFloat = 14) -> UIFont { return UIFont.italicSystemFont(ofSize: size) }
public class func regularFont(_ size: CGFloat = 14) -> UIFont { return UIFont.systemFont(ofSize: size) }
public class func regularBoldFont(_ size: CGFloat = 14) -> UIFont { return UIFont.boldSystemFont(ofSize: size) }
public class func regularBlackFont(_ size: CGFloat = 14) -> UIFont { return UIFont.boldSystemFont(ofSize: size) }
public class func regularBlackItalicFont(_ size: CGFloat = 14) -> UIFont { return UIFont.italicSystemFont(ofSize: size) }
public class func regularLightFont(_ size: CGFloat = 14) -> UIFont { return UIFont.systemFont(ofSize: size) }
public class func editorFont(_ size: CGFloat = 14) -> UIFont { return UIFont.systemFont(ofSize: size) }
public class func editorItalicFont(_ size: CGFloat = 14) -> UIFont { return UIFont.italicSystemFont(ofSize: size) }
public class func editorBoldFont(_ size: CGFloat = 14) -> UIFont { return UIFont.boldSystemFont(ofSize: size) }
public class func editorBoldItalicFont(_ size: CGFloat = 14) -> UIFont {
let descriptor = UIFont.systemFont(ofSize: size).fontDescriptor.withSymbolicTraits([.traitBold, .traitItalic])
return UIFont(descriptor: descriptor!, size: size)
}
public class func printAvailableFonts() {
for familyName in UIFont.familyNames
{
print("Family Name: \(familyName)")
for fontName in UIFont.fontNames(forFamilyName: familyName)
{
print("--Font Name: \(fontName)")
}
}
}
}
| mit |
admkopec/BetaOS | Kernel/Modules/ACPI/AML/Type2Opcodes.swift | 1 | 30713 | //
// Type2Opcodes.swift
// Kernel
//
// Created by Adam Kopeć on 1/26/18.
// Copyright © 2018 Adam Kopeć. All rights reserved.
//
// ACPI Type 2 Opcodes
protocol AMLType2Opcode: AMLTermObj, AMLTermArg {
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg
}
private let AMLIntegerFalse = AMLInteger(0)
private let AMLIntegerTrue = AMLInteger(1)
private func AMLBoolean(_ bool: Bool) -> AMLInteger {
return bool ? AMLIntegerTrue : AMLIntegerFalse
}
func operandAsInteger(operand: AMLOperand, context: inout ACPI.AMLExecutionContext) -> AMLInteger {
guard let result = operand.evaluate(context: &context) as? AMLIntegerData else {
fatalError("\(operand) does not evaluate to an integer")
}
return result.value
}
// AMLType2Opcode
typealias AMLTimeout = AMLWordData
struct AMLDefAcquire: AMLType2Opcode {
// AcquireOp MutexObject Timeout
let mutex: AMLMutexObject
let timeout: AMLTimeout
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
typealias AMLOperand = AMLTermArg // => Integer
struct AMLDefAdd: AMLType2Opcode {
// AddOp Operand Operand Target
let operand1: AMLOperand
let operand2: AMLOperand
let target: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let result = AMLIntegerData(op1 + op2)
return result
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let value = evaluate(context: &context)
target.updateValue(to: value, context: &context)
return value
}
}
struct AMLDefAnd: AMLType2Opcode {
// AndOp Operand Operand Target
let operand1: AMLOperand
let operand2: AMLOperand
let target: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let result = AMLIntegerData(op1 & op2)
target.updateValue(to: result, context: &context)
return result
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let value = evaluate(context: &context)
target.updateValue(to: value, context: &context)
return value
}
}
struct AMLBuffer: AMLBuffPkgStrObj, AMLType2Opcode, AMLComputationalData {
var isReadOnly: Bool { return true }
// BufferOp PkgLength BufferSize ByteList
let size: AMLTermArg // => Integer
let value: AMLByteList
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
guard let result = size.evaluate(context: &context) as? AMLIntegerData else {
fatalError("\(size) does not evaluate to an integer")
}
return result
}
}
typealias AMLData = AMLTermArg // => ComputationalData
struct AMLDefConcat: AMLType2Opcode {
// ConcatOp Data Data Target
let data1: AMLData
let data2: AMLData
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
typealias AMLBufData = AMLTermArg // =>
struct AMLDefConcatRes: AMLType2Opcode {
// ConcatResOp BufData BufData Target
let data1: AMLBufData
let data2: AMLBufData
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
guard let buf1 = data1.evaluate(context: &context) as? AMLBuffer,
let buf2 = data2.evaluate(context: &context) as? AMLBuffer else {
fatalError("cant evaulate to buffers")
}
// Fixme, iterate validating the individual entries and add an endtag
let result = Array(buf1.value[0..<buf1.value.count-2]) + buf2.value
let newBuffer = AMLBuffer(size: AMLIntegerData(AMLInteger(result.count)), value: result)
target.updateValue(to: newBuffer, context: &context)
return newBuffer
}
}
///ObjReference := TermArg => ObjectReference | String
//ObjectReference := Integer
struct AMLDefCondRefOf: AMLType2Opcode {
// CondRefOfOp SuperName Target
let name: AMLSuperName
var target: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
guard let n = name as? AMLNameString else {
return AMLIntegerData(0)
}
guard let (obj, _) = context.globalObjects.getGlobalObject(currentScope: context.scope, name: n) else {
return AMLIntegerData(0)
}
// FIXME, do the store into the target
//target.value = obj
kprint(String(describing: obj))
return AMLIntegerData(1)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefCopyObject: AMLType2Opcode {
// CopyObjectOp TermArg SimpleName
let object: AMLTermArg
let target: AMLSimpleName
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let value = evaluate(context: &context)
target.updateValue(to: value, context: &context)
return value
}
}
struct AMLDefDecrement: AMLType2Opcode {
// DecrementOp SuperName
let target: AMLSuperName
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
guard let result = target.evaluate(context: &context) as? AMLIntegerData else {
fatalError("\target) is not an integer")
}
return AMLIntegerData(result.value &- 1)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let value = evaluate(context: &context)
target.updateValue(to: value, context: &context)
return value
}
}
struct AMLDefDerefOf: AMLType2Opcode, AMLType6Opcode {
// DerefOfOp ObjReference
let name: AMLSuperName
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
func updateValue(to: AMLTermArg, context: inout ACPI.AMLExecutionContext) {
fatalError("Cant update \(self) to \(to)")
}
}
typealias AMLDividend = AMLTermArg // => Integer
typealias AMLDivisor = AMLTermArg // => Integer
struct AMLDefDivide: AMLType2Opcode {
// DivideOp Dividend Divisor Remainder Quotient
let dividend: AMLDividend
let divisor: AMLDivisor
let remainder: AMLTarget
let quotient: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let d1 = operandAsInteger(operand: dividend, context: &context)
let d2 = operandAsInteger(operand: divisor, context: &context)
guard d2 != 0 else {
fatalError("divisor is 0")
}
let q = AMLIntegerData((d1 / d2))
return q
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let d1 = operandAsInteger(operand: dividend, context: &context)
let d2 = operandAsInteger(operand: divisor, context: &context)
guard d2 != 0 else {
fatalError("divisor is 0")
}
let q = AMLIntegerData((d1 / d2))
let r = AMLIntegerData((d1 % d2))
quotient.updateValue(to: q, context: &context)
remainder.updateValue(to: r, context: &context)
return q
}
}
struct AMLDefFindSetLeftBit: AMLType2Opcode {
// FindSetLeftBitOp Operand Target
let operand: AMLOperand
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefFindSetRightBit: AMLType2Opcode {
// FindSetRightBitOp Operand Target
let operand: AMLOperand
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
typealias AMLBCDValue = AMLTermArg //=> Integer
struct AMLDefFromBCD: AMLType2Opcode {
// FromBCDOp BCDValue Target
let value: AMLBCDValue
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefIncrement: AMLType2Opcode {
// IncrementOp SuperName
let target: AMLSuperName
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
guard let result = target.evaluate(context: &context) as? AMLIntegerData else {
fatalError("\target) is not an integer")
}
return AMLIntegerData(result.value &+ 1)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let value = evaluate(context: &context)
target.updateValue(to: value, context: &context)
return value
}
}
struct AMLDefIndex: AMLType2Opcode, AMLType6Opcode {
// IndexOp BuffPkgStrObj IndexValue Target
let object: AMLBuffPkgStrObj // => Buffer, Package or String
let index: AMLTermArg // => Integer
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
func updateValue(to: AMLTermArg, context: inout ACPI.AMLExecutionContext) {
fatalError("Cant update \(self) to \(to)")
}
}
struct AMLDefLAnd: AMLType2Opcode {
// LandOp Operand Operand
let operand1: AMLOperand
let operand2: AMLOperand
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let value = AMLBoolean(op1 != 0 && op2 != 0)
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
return evaluate(context: &context)
}
}
struct AMLDefLEqual: AMLType2Opcode {
// LequalOp Operand Operand
let operand1: AMLOperand
let operand2: AMLOperand
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let value = AMLBoolean(op1 == op2)
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
return evaluate(context: &context)
}
}
struct AMLDefLGreater: AMLType2Opcode {
// LgreaterOp Operand Operand
let operand1: AMLOperand
let operand2: AMLOperand
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let value = AMLBoolean(op1 < op2)
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
return evaluate(context: &context)
}
}
struct AMLDefLGreaterEqual: AMLType2Opcode {
// LgreaterEqualOp Operand Operand
let operand1: AMLOperand
let operand2: AMLOperand
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let value = AMLBoolean(op1 >= op2)
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
return evaluate(context: &context)
}
}
struct AMLDefLLess: AMLType2Opcode {
// LlessOp Operand Operand
let operand1: AMLOperand
let operand2: AMLOperand
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let value = AMLBoolean(op1 < op2)
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
return evaluate(context: &context)
}
}
struct AMLDefLLessEqual: AMLType2Opcode {
// LlessEqualOp Operand Operand
let operand1: AMLOperand
let operand2: AMLOperand
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let value = AMLBoolean(op1 <= op2)
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
return evaluate(context: &context)
}
}
struct AMLDefLNot: AMLType2Opcode {
// LnotOp Operand
let operand: AMLOperand
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op = operandAsInteger(operand: operand, context: &context)
let value = AMLBoolean(op == 0)
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
return evaluate(context: &context)
}
}
struct AMLDefLNotEqual: AMLType2Opcode {
// LnotEqualOp Operand Operand
let operand1: AMLTermArg
let operand2: AMLTermArg
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefLoadTable: AMLType2Opcode {
// LoadTableOp TermArg TermArg TermArg TermArg TermArg TermArg
let arg1: AMLTermArg
let arg2: AMLTermArg
let arg3: AMLTermArg
let arg4: AMLTermArg
let arg5: AMLTermArg
let arg6: AMLTermArg
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefLOr: AMLType2Opcode {
// LorOp Operand Operand
let operand1: AMLOperand
let operand2: AMLOperand
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let value = AMLBoolean(op1 != 0 || op2 != 0)
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
return evaluate(context: &context)
}
}
struct AMLDefMatch: AMLType2Opcode {
enum AMLMatchOpcode: AMLByteData {
case mtr = 0
case meq = 1
case mle = 2
case mlt = 3
case mge = 4
case mgt = 5
}
// MatchOp SearchPkg MatchOpcode Operand MatchOpcode Operand StartIndex
let package: AMLTermArg // => Package
let matchOpcode1: AMLMatchOpcode
let operand1: AMLOperand
let matchOpcode2: AMLMatchOpcode
let operand2: AMLOperand
let startIndex: AMLTermArg // => Integer
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefMid: AMLType2Opcode {
// MidOp MidObj TermArg TermArg Target
let obj: AMLTermArg // => Buffer | String
let arg1: AMLTermArg
let arg2: AMLTermArg
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefMod: AMLType2Opcode {
// ModOp Dividend Divisor Target
let dividend: AMLDividend
let divisor: AMLDivisor
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefMultiply: AMLType2Opcode {
// MultiplyOp Operand Operand Target
let operand1: AMLOperand
let operand2: AMLOperand
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefNAnd: AMLType2Opcode {
// NandOp Operand Operand Target
let operand1: AMLOperand
let operand2: AMLOperand
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefNOr: AMLType2Opcode {
// NorOp Operand Operand Target
let operand1: AMLOperand
let operand2: AMLOperand
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefNot: AMLType2Opcode {
// NotOp Operand Target
let operand: AMLOperand
let target: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op = operandAsInteger(operand: operand, context: &context)
return AMLIntegerData(~op)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefObjectType: AMLType2Opcode {
// ObjectTypeOp <SimpleName | DebugObj | DefRefOf | DefDerefOf | DefIndex>
let object: AMLSuperName
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefOr: AMLType2Opcode {
// OrOp Operand Operand Target
let operand1: AMLOperand
let operand2: AMLOperand
let target: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
return AMLIntegerData(op1 | op2)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
return evaluate(context: &context)
}
}
typealias AMLPackageElement = AMLDataRefObject
typealias AMLPackageElementList = [AMLPackageElement]
struct AMLDefPackage: AMLBuffPkgStrObj, AMLType2Opcode, AMLDataObject, AMLTermArg {
func canBeConverted(to: AMLDataRefObject) -> Bool {
return false
}
var isReadOnly: Bool { return false }
// PackageOp PkgLength NumElements PackageElementList
//let pkgLength: AMLPkgLength
let numElements: AMLByteData
let elements: AMLPackageElementList
var value: AMLPackageElementList { return elements }
let asInteger: AMLInteger? = nil
let resultAsInteger: AMLInteger? = nil
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
typealias AMLDefVarPackage = AMLDataRefObject
struct AMLDefRefOf: AMLType2Opcode, AMLType6Opcode {
// RefOfOp SuperName
let name: AMLSuperName
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
func updateValue(to: AMLTermArg, context: inout ACPI.AMLExecutionContext) {
fatalError("cant update \(self) to \(to)")
}
}
typealias AMLShiftCount = AMLTermArg //=> Integer
struct AMLDefShiftLeft: AMLType2Opcode {
// ShiftLeftOp Operand ShiftCount Target
let operand: AMLOperand
let count: AMLShiftCount
let target: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op = operandAsInteger(operand: operand, context: &context)
let shiftCount = operandAsInteger(operand: count, context: &context)
let value = op << shiftCount
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let result = evaluate(context: &context)
target.updateValue(to: result, context: &context)
return result
}
}
struct AMLDefShiftRight: AMLType2Opcode {
// ShiftRightOp Operand ShiftCount Target
let operand: AMLOperand
let count: AMLShiftCount
let target: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op = operandAsInteger(operand: operand, context: &context)
let shiftCount = operandAsInteger(operand: count, context: &context)
let value = op >> shiftCount
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let result = evaluate(context: &context)
target.updateValue(to: result, context: &context)
return result
}
}
struct AMLDefSizeOf: AMLType2Opcode {
// SizeOfOp SuperName
let name: AMLSuperName
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg{
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefStore: AMLType2Opcode {
// StoreOp TermArg SuperName
let arg: AMLTermArg
let name: AMLSuperName
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
var source = arg
if let args2 = arg as? AMLArgObj {
guard args2.argIdx < context.args.count else {
fatalError("Tried to access arg \(args2.argIdx) but only have \(context.args.count) args")
}
source = context.args[Int(args2.argIdx)]
}
let v = source.evaluate(context: &context)
if let obj = name as? AMLDataRefObject {
//obj.updateValue(to: source, context: &context)
//return source
obj.updateValue(to: v, context: &context)
return v
}
if let localObj = name as? AMLLocalObj {
context.localObjects[localObj.argIdx] = v
return v
}
guard let sname = name as? AMLNameString else {
throw AMLError.invalidData(reason: "\(name) is not a string")
}
guard let (dest, fullPath) = context.globalObjects.getGlobalObject(currentScope: context.scope, name: sname) else {
fatalError("Can't find \(sname)")
}
// guard let target = dest.object as? AMLDataRefObject else {
// fatalError("dest not an AMLDataRefObject")
// }
// FIXME: Shouldn't be here
//guard var namedObject = dest.object else {
// fatalError("Cant find namedObj: \(sname)")
//}
// guard source.canBeConverted(to: target) else {
// fatalError("\(source) can not be converted to \(target)")
// }
let resolvedScope = AMLNameString(fullPath).removeLastSeg()
var tmpContext = ACPI.AMLExecutionContext(scope: resolvedScope,
args: context.args,
globalObjects: context.globalObjects)
if let no = dest.object as? AMLNamedObj {
no.updateValue(to: source, context: &tmpContext)
}
else if let no = dest.object as? AMLDataRefObject {
no.updateValue(to: source, context: &tmpContext)
} else if let no = dest.object as? AMLDefName {
no.value.updateValue(to: source, context: &tmpContext)
} else {
fatalError("Cant store \(source) into \(String(describing: dest.object))")
}
return v
}
}
struct AMLDefSubtract: AMLType2Opcode {
// SubtractOp Operand Operand Target
let operand1: AMLOperand
let operand2: AMLOperand
let target: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let value = op1 &- op2
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let result = evaluate(context: &context)
//target.updateValue(to: result, context: &context)
return result
}
}
struct AMLDefTimer: AMLType2Opcode {
// TimerOp
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefToBCD: AMLType2Opcode {
// ToBCDOp Operand Target
let operand: AMLOperand
let target: AMLTarget
var description: String { return "ToBCD(\(operand), \(target)" }
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefToBuffer: AMLType2Opcode {
// ToBufferOp Operand Target
let operand: AMLOperand
let target: AMLTarget
var description: String { return "ToBuffer(\(operand), \(target)" }
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefToDecimalString: AMLType2Opcode {
// ToDecimalStringOp Operand Target
let operand: AMLOperand
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefToHexString: AMLType2Opcode {
// ToHexStringOp Operand Target
let operand: AMLOperand
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefToInteger: AMLType2Opcode {
// ToIntegerOp Operand Target
let operand: AMLOperand
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefToString: AMLType2Opcode {
// ToStringOp TermArg LengthArg Target
let arg: AMLTermArg
let length: AMLTermArg // => Integer
let target: AMLTarget
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefWait: AMLType2Opcode {
// WaitOp EventObject Operand
let object: AMLEventObject
let operand: AMLOperand
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLDefXor: AMLType2Opcode {
// XorOp Operand Operand Target
let operand1: AMLOperand
let operand2: AMLOperand
var target: AMLTarget
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
let op1 = operandAsInteger(operand: operand1, context: &context)
let op2 = operandAsInteger(operand: operand2, context: &context)
let value = op1 ^ op2
return AMLIntegerData(value)
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg{
throw AMLError.unimplemented("\(type(of: self))")
}
}
struct AMLMethodInvocation: AMLType2Opcode {
// NameString TermArgList
let method: AMLNameString
let args: AMLTermArgList
init?(method: AMLNameString, args: AMLTermArgList) /*throws*/ {
guard args.count < 8 else {
// throw AMLError.invalidData(reason: "More than 7 args")
return nil
}
self.method = method
self.args = args
}
init?(method: AMLNameString, _ args: AMLTermArg...) /*throws*/ {
/*try*/ self.init(method: method, args: args)
}
private func _invokeMethod(invocation: AMLMethodInvocation,
context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg? {
let name = invocation.method.value
if name == "\\_OSI" || name == "_OSI" {
return try ACPI._OSI_Method(invocation.args)
}
guard let (obj, fullPath) = context.globalObjects.getGlobalObject(currentScope: context.scope, name: invocation.method) else {
throw AMLError.invalidMethod(reason: "Cant find method: \(name)")
}
guard let method = obj.object as? AMLMethod else {
throw AMLError.invalidMethod(reason: "\(name) [\(String(describing:obj.object))] is not an AMLMethod")
}
let termList = try method.termList()
let newArgs = invocation.args.map { $0.evaluate(context: &context) }
var newContext = ACPI.AMLExecutionContext(scope: AMLNameString(fullPath),
args: newArgs,
globalObjects: context.globalObjects)
try newContext.execute(termList: termList)
context.returnValue = newContext.returnValue
return context.returnValue
}
func execute(context: inout ACPI.AMLExecutionContext) throws -> AMLTermArg {
let returnValue = try _invokeMethod(invocation: self, context: &context)
context.returnValue = returnValue
guard let retval = returnValue else {
return AMLIntegerData(0)
}
return retval
}
func evaluate(context: inout ACPI.AMLExecutionContext) -> AMLTermArg {
do {
if let result = try _invokeMethod(invocation: self, context: &context) {
return result
}
} catch {
fatalError("cant evaluate: \(self): \(error)")
}
fatalError("Failed to evaluate \(self)")
}
}
| apache-2.0 |
darrarski/Messages-iOS | MessagesApp/Helpers/Sequence_UniqueElements.swift | 1 | 682 | extension Sequence {
func uniqueElements<T: Equatable>(identifier: (Iterator.Element) -> T) -> [Iterator.Element] {
return reduce([]) { uniqueElements, element in
if uniqueElements.contains(where: { identifier($0) == identifier(element) }) {
return uniqueElements
} else {
return uniqueElements + [element]
}
}
}
}
extension Sequence where Iterator.Element: Equatable {
var uniqueElements: [Iterator.Element] {
return self.reduce([]) { uniqueElements, element in
uniqueElements.contains(element) ? uniqueElements : uniqueElements + [element]
}
}
}
| mit |
rudsonlive/alamofire-for-networking-ios | AlamofireSample/AlamofireSample/Company.swift | 1 | 490 | //
// Company.swift
// AlamofireSample
//
// Created by Rudson Lima on 7/21/16.
// Copyright © 2016 Rudson Lima. All rights reserved.
//
import ObjectMapper
class Company: Mappable {
var id: Int? = 0
var name: String? = ""
var detail: CompanyDetail?
required init?(_ map: Map){
}
func mapping(map: Map) {
id <- map[Util.KeyCompanies.id]
name <- map[Util.KeyCompanies.name]
detail <- map[Util.KeyCompanies.detail]
}
}
| apache-2.0 |
austinzheng/swift | stdlib/public/core/StringComparable.swift | 3 | 2787 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import SwiftShims
extension StringProtocol {
@inlinable
@_specialize(where Self == String, RHS == String)
@_specialize(where Self == String, RHS == Substring)
@_specialize(where Self == Substring, RHS == String)
@_specialize(where Self == Substring, RHS == Substring)
@_effects(readonly)
public static func == <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return _stringCompare(
lhs._wholeGuts, lhs._offsetRange,
rhs._wholeGuts, rhs._offsetRange,
expecting: .equal)
}
@inlinable @inline(__always) // forward to other operator
@_effects(readonly)
public static func != <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return !(lhs == rhs)
}
@inlinable
@_specialize(where Self == String, RHS == String)
@_specialize(where Self == String, RHS == Substring)
@_specialize(where Self == Substring, RHS == String)
@_specialize(where Self == Substring, RHS == Substring)
@_effects(readonly)
public static func < <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return _stringCompare(
lhs._wholeGuts, lhs._offsetRange,
rhs._wholeGuts, rhs._offsetRange,
expecting: .less)
}
@inlinable @inline(__always) // forward to other operator
@_effects(readonly)
public static func > <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return rhs < lhs
}
@inlinable @inline(__always) // forward to other operator
@_effects(readonly)
public static func <= <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return !(rhs < lhs)
}
@inlinable @inline(__always) // forward to other operator
@_effects(readonly)
public static func >= <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return !(lhs < rhs)
}
}
extension String : Equatable {
@inlinable @inline(__always) // For the bitwise comparision
@_effects(readonly)
public static func == (lhs: String, rhs: String) -> Bool {
return _stringCompare(lhs._guts, rhs._guts, expecting: .equal)
}
}
extension String : Comparable {
@inlinable @inline(__always) // For the bitwise comparision
@_effects(readonly)
public static func < (lhs: String, rhs: String) -> Bool {
return _stringCompare(lhs._guts, rhs._guts, expecting: .less)
}
}
extension Substring : Equatable {}
| apache-2.0 |
nutts/SwiftForms | SwiftForms/SwiftyJSON.swift | 1 | 36126 | // SwiftyJSON.swift
//
// Copyright (c) 2014 Ruoyu Fu, Pinglin Tang
//
// 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
// MARK: - Error
///Error domain
public let ErrorDomain: String! = "SwiftyJSONErrorDomain"
///Error code
public let ErrorUnsupportedType: Int! = 999
public let ErrorIndexOutOfBounds: Int! = 900
public let ErrorWrongType: Int! = 901
public let ErrorNotExist: Int! = 500
// MARK: - JSON Type
/**
JSON's type definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Type :Int{
case Number
case String
case Bool
case Array
case Dictionary
case Null
case Unknown
}
// MARK: - JSON Base
public struct JSON {
/**
Creates a JSON using the data.
- parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary
- parameter opt: The JSON serialization reading options. `.AllowFragments` by default.
- parameter error: error The NSErrorPointer used to return the error. `nil` by default.
- returns: The created JSON
*/
public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) {
do {
let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt)
self.init(object)
} catch let aError as NSError {
if error != nil {
error.memory = aError
}
self.init(NSNull())
}
}
/**
Creates a JSON using the object.
- parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity.
- returns: The created JSON
*/
public init(_ object: AnyObject) {
self.object = object
}
/**
Creates a JSON from a [JSON]
- parameter jsonArray: A Swift array of JSON objects
- returns: The created JSON
*/
public init(_ jsonArray:[JSON]) {
self.init(jsonArray.map { $0.object })
}
/**
Creates a JSON from a [String: JSON]
:param: jsonDictionary A Swift dictionary of JSON objects
:returns: The created JSON
*/
public init(_ jsonDictionary:[String: JSON]) {
var dictionary = [String: AnyObject]()
for (key, json) in jsonDictionary {
dictionary[key] = json.object
}
self.init(dictionary)
}
/// Private object
private var rawArray: [AnyObject] = []
private var rawDictionary: [String : AnyObject] = [:]
private var rawString: String = ""
private var rawNumber: NSNumber = 0
private var rawNull: NSNull = NSNull()
/// Private type
private var _type: Type = .Null
/// prviate error
private var _error: NSError? = nil
/// Object in JSON
public var object: AnyObject {
get {
switch self.type {
case .Array:
return self.rawArray
case .Dictionary:
return self.rawDictionary
case .String:
return self.rawString
case .Number:
return self.rawNumber
case .Bool:
return self.rawNumber
default:
return self.rawNull
}
}
set {
_error = nil
switch newValue {
case let number as NSNumber:
if number.isBool {
_type = .Bool
} else {
_type = .Number
}
self.rawNumber = number
case let string as String:
_type = .String
self.rawString = string
case _ as NSNull:
_type = .Null
case let array as [AnyObject]:
_type = .Array
self.rawArray = array
case let dictionary as [String : AnyObject]:
_type = .Dictionary
self.rawDictionary = dictionary
default:
_type = .Unknown
_error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"])
}
}
}
/// json type
public var type: Type { get { return _type } }
/// Error in JSON
public var error: NSError? { get { return self._error } }
/// The static null json
@available(*, unavailable, renamed="null")
public static var nullJSON: JSON { get { return null } }
public static var null: JSON { get { return JSON(NSNull()) } }
}
// MARK: - CollectionType, SequenceType, Indexable
extension JSON : Swift.CollectionType, Swift.SequenceType, Swift.Indexable {
public typealias Generator = JSONGenerator
public typealias Index = JSONIndex
public var startIndex: JSON.Index {
switch self.type {
case .Array:
return JSONIndex(arrayIndex: self.rawArray.startIndex)
case .Dictionary:
return JSONIndex(dictionaryIndex: self.rawDictionary.startIndex)
default:
return JSONIndex()
}
}
public var endIndex: JSON.Index {
switch self.type {
case .Array:
return JSONIndex(arrayIndex: self.rawArray.endIndex)
case .Dictionary:
return JSONIndex(dictionaryIndex: self.rawDictionary.endIndex)
default:
return JSONIndex()
}
}
public subscript (position: JSON.Index) -> JSON.Generator.Element {
switch self.type {
case .Array:
return (String(position.arrayIndex), JSON(self.rawArray[position.arrayIndex!]))
case .Dictionary:
let (key, value) = self.rawDictionary[position.dictionaryIndex!]
return (key, JSON(value))
default:
return ("", JSON.null)
}
}
/// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `false`.
public var isEmpty: Bool {
get {
switch self.type {
case .Array:
return self.rawArray.isEmpty
case .Dictionary:
return self.rawDictionary.isEmpty
default:
return true
}
}
}
/// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`.
public var count: Int {
switch self.type {
case .Array:
return self.rawArray.count
case .Dictionary:
return self.rawDictionary.count
default:
return 0
}
}
public func underestimateCount() -> Int {
switch self.type {
case .Array:
return self.rawArray.underestimateCount()
case .Dictionary:
return self.rawDictionary.underestimateCount()
default:
return 0
}
}
/**
If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty.
- returns: Return a *generator* over the elements of JSON.
*/
public func generate() -> JSON.Generator {
return JSON.Generator(self)
}
}
public struct JSONIndex: ForwardIndexType, _Incrementable, Equatable, Comparable {
let arrayIndex: Int?
let dictionaryIndex: DictionaryIndex<String, AnyObject>?
let type: Type
init(){
self.arrayIndex = nil
self.dictionaryIndex = nil
self.type = .Unknown
}
init(arrayIndex: Int) {
self.arrayIndex = arrayIndex
self.dictionaryIndex = nil
self.type = .Array
}
init(dictionaryIndex: DictionaryIndex<String, AnyObject>) {
self.arrayIndex = nil
self.dictionaryIndex = dictionaryIndex
self.type = .Dictionary
}
public func successor() -> JSONIndex {
switch self.type {
case .Array:
return JSONIndex(arrayIndex: self.arrayIndex!.successor())
case .Dictionary:
return JSONIndex(dictionaryIndex: self.dictionaryIndex!.successor())
default:
return JSONIndex()
}
}
}
public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex == rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex == rhs.dictionaryIndex
default:
return false
}
}
public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex < rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex < rhs.dictionaryIndex
default:
return false
}
}
public func <=(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex <= rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex <= rhs.dictionaryIndex
default:
return false
}
}
public func >=(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex >= rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex >= rhs.dictionaryIndex
default:
return false
}
}
public func >(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex > rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex > rhs.dictionaryIndex
default:
return false
}
}
public struct JSONGenerator : GeneratorType {
public typealias Element = (String, JSON)
private let type: Type
private var dictionayGenerate: DictionaryGenerator<String, AnyObject>?
private var arrayGenerate: IndexingGenerator<[AnyObject]>?
private var arrayIndex: Int = 0
init(_ json: JSON) {
self.type = json.type
if type == .Array {
self.arrayGenerate = json.rawArray.generate()
}else {
self.dictionayGenerate = json.rawDictionary.generate()
}
}
public mutating func next() -> JSONGenerator.Element? {
switch self.type {
case .Array:
if let o = self.arrayGenerate!.next() {
return (String(self.arrayIndex++), JSON(o))
} else {
return nil
}
case .Dictionary:
if let (k, v): (String, AnyObject) = self.dictionayGenerate!.next() {
return (k, JSON(v))
} else {
return nil
}
default:
return nil
}
}
}
// MARK: - Subscript
/**
* To mark both String and Int can be used in subscript.
*/
public protocol JSONSubscriptType {}
extension Int: JSONSubscriptType {}
extension String: JSONSubscriptType {}
extension JSON {
/// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error.
private subscript(index index: Int) -> JSON {
get {
if self.type != .Array {
var r = JSON.null
r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"])
return r
} else if index >= 0 && index < self.rawArray.count {
return JSON(self.rawArray[index])
} else {
var r = JSON.null
r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"])
return r
}
}
set {
if self.type == .Array {
if self.rawArray.count > index && newValue.error == nil {
self.rawArray[index] = newValue.object
}
}
}
}
/// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error.
private subscript(key key: String) -> JSON {
get {
var r = JSON.null
if self.type == .Dictionary {
if let o = self.rawDictionary[key] {
r = JSON(o)
} else {
r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"])
}
} else {
r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"])
}
return r
}
set {
if self.type == .Dictionary && newValue.error == nil {
self.rawDictionary[key] = newValue.object
}
}
}
/// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`.
private subscript(sub sub: JSONSubscriptType) -> JSON {
get {
if sub is String {
return self[key:sub as! String]
} else {
return self[index:sub as! Int]
}
}
set {
if sub is String {
self[key:sub as! String] = newValue
} else {
self[index:sub as! Int] = newValue
}
}
}
/**
Find a json in the complex data structuresby using the Int/String's array.
- parameter path: The target json's path. Example:
let json = JSON[data]
let path = [9,"list","person","name"]
let name = json[path]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: [JSONSubscriptType]) -> JSON {
get {
return path.reduce(self) { $0[sub: $1] }
}
set {
switch path.count {
case 0:
return
case 1:
self[sub:path[0]].object = newValue.object
default:
var aPath = path; aPath.removeAtIndex(0)
var nextJSON = self[sub: path[0]]
nextJSON[aPath] = newValue
self[sub: path[0]] = nextJSON
}
}
}
/**
Find a json in the complex data structuresby using the Int/String's array.
- parameter path: The target json's path. Example:
let name = json[9,"list","person","name"]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: JSONSubscriptType...) -> JSON {
get {
return self[path]
}
set {
self[path] = newValue
}
}
}
// MARK: - LiteralConvertible
extension JSON: Swift.StringLiteralConvertible {
public init(stringLiteral value: StringLiteralType) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value)
}
}
extension JSON: Swift.IntegerLiteralConvertible {
public init(integerLiteral value: IntegerLiteralType) {
self.init(value)
}
}
extension JSON: Swift.BooleanLiteralConvertible {
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value)
}
}
extension JSON: Swift.FloatLiteralConvertible {
public init(floatLiteral value: FloatLiteralType) {
self.init(value)
}
}
extension JSON: Swift.DictionaryLiteralConvertible {
public init(dictionaryLiteral elements: (String, AnyObject)...) {
self.init(elements.reduce([String : AnyObject]()){(dictionary: [String : AnyObject], element:(String, AnyObject)) -> [String : AnyObject] in
var d = dictionary
d[element.0] = element.1
return d
})
}
}
extension JSON: Swift.ArrayLiteralConvertible {
public init(arrayLiteral elements: AnyObject...) {
self.init(elements)
}
}
extension JSON: Swift.NilLiteralConvertible {
public init(nilLiteral: ()) {
self.init(NSNull())
}
}
// MARK: - Raw
extension JSON: Swift.RawRepresentable {
public init?(rawValue: AnyObject) {
if JSON(rawValue).type == .Unknown {
return nil
} else {
self.init(rawValue)
}
}
public var rawValue: AnyObject {
return self.object
}
public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData {
return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt)
}
public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? {
switch self.type {
case .Array, .Dictionary:
do {
let data = try self.rawData(options: opt)
return NSString(data: data, encoding: encoding) as? String
} catch _ {
return nil
}
case .String:
return self.rawString
case .Number:
return self.rawNumber.stringValue
case .Bool:
return self.rawNumber.boolValue.description
case .Null:
return "null"
default:
return nil
}
}
}
// MARK: - Printable, DebugPrintable
extension JSON: Swift.Printable, Swift.DebugPrintable {
public var description: String {
if let string = self.rawString(options:.PrettyPrinted) {
return string
} else {
return "unknown"
}
}
public var debugDescription: String {
return description
}
}
// MARK: - Array
extension JSON {
//Optional [JSON]
public var array: [JSON]? {
get {
if self.type == .Array {
return self.rawArray.map{ JSON($0) }
} else {
return nil
}
}
}
//Non-optional [JSON]
public var arrayValue: [JSON] {
get {
return self.array ?? []
}
}
//Optional [AnyObject]
public var arrayObject: [AnyObject]? {
get {
switch self.type {
case .Array:
return self.rawArray
default:
return nil
}
}
set {
if let array = newValue {
self.object = array
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Dictionary
extension JSON {
//Optional [String : JSON]
public var dictionary: [String : JSON]? {
if self.type == .Dictionary {
return self.rawDictionary.reduce([String : JSON]()) { (dictionary: [String : JSON], element: (String, AnyObject)) -> [String : JSON] in
var d = dictionary
d[element.0] = JSON(element.1)
return d
}
} else {
return nil
}
}
//Non-optional [String : JSON]
public var dictionaryValue: [String : JSON] {
return self.dictionary ?? [:]
}
//Optional [String : AnyObject]
public var dictionaryObject: [String : AnyObject]? {
get {
switch self.type {
case .Dictionary:
return self.rawDictionary
default:
return nil
}
}
set {
if let v = newValue {
self.object = v
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Bool
extension JSON: Swift.BooleanType {
//Optional bool
public var bool: Bool? {
get {
switch self.type {
case .Bool:
return self.rawNumber.boolValue
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSNumber(bool: newValue!)
} else {
self.object = NSNull()
}
}
}
//Non-optional bool
public var boolValue: Bool {
get {
switch self.type {
case .Bool, .Number, .String:
return self.object.boolValue
default:
return false
}
}
set {
self.object = NSNumber(bool: newValue)
}
}
}
// MARK: - String
extension JSON {
//Optional string
public var string: String? {
get {
switch self.type {
case .String:
return self.object as? String
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSString(string:newValue!)
} else {
self.object = NSNull()
}
}
}
//Non-optional string
public var stringValue: String {
get {
switch self.type {
case .String:
return self.object as! String
case .Number:
return self.object.stringValue
case .Bool:
return (self.object as! Bool).description
default:
return ""
}
}
set {
self.object = NSString(string:newValue)
}
}
}
// MARK: - Number
extension JSON {
//Optional number
public var number: NSNumber? {
get {
switch self.type {
case .Number, .Bool:
return self.rawNumber
default:
return nil
}
}
set {
self.object = newValue ?? NSNull()
}
}
//Non-optional number
public var numberValue: NSNumber {
get {
switch self.type {
case .String:
let scanner = NSScanner(string: self.object as! String)
if scanner.scanDouble(nil){
if (scanner.atEnd) {
return NSNumber(double:(self.object as! NSString).doubleValue)
}
}
return NSNumber(double: 0.0)
case .Number, .Bool:
return self.object as! NSNumber
default:
return NSNumber(double: 0.0)
}
}
set {
self.object = newValue
}
}
}
//MARK: - Null
extension JSON {
public var null: NSNull? {
get {
switch self.type {
case .Null:
return self.rawNull
default:
return nil
}
}
set {
self.object = NSNull()
}
}
}
//MARK: - URL
extension JSON {
//Optional URL
public var URL: NSURL? {
get {
switch self.type {
case .String:
if let encodedString_ = self.rawString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) {
return NSURL(string: encodedString_)
} else {
return nil
}
default:
return nil
}
}
set {
self.object = newValue?.absoluteString ?? NSNull()
}
}
}
// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64
extension JSON {
public var double: Double? {
get {
return self.number?.doubleValue
}
set {
if newValue != nil {
self.object = NSNumber(double: newValue!)
} else {
self.object = NSNull()
}
}
}
public var doubleValue: Double {
get {
return self.numberValue.doubleValue
}
set {
self.object = NSNumber(double: newValue)
}
}
public var float: Float? {
get {
return self.number?.floatValue
}
set {
if newValue != nil {
self.object = NSNumber(float: newValue!)
} else {
self.object = NSNull()
}
}
}
public var floatValue: Float {
get {
return self.numberValue.floatValue
}
set {
self.object = NSNumber(float: newValue)
}
}
public var int: Int? {
get {
return self.number?.longValue
}
set {
if newValue != nil {
self.object = NSNumber(integer: newValue!)
} else {
self.object = NSNull()
}
}
}
public var intValue: Int {
get {
return self.numberValue.integerValue
}
set {
self.object = NSNumber(integer: newValue)
}
}
public var uInt: UInt? {
get {
return self.number?.unsignedLongValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uIntValue: UInt {
get {
return self.numberValue.unsignedLongValue
}
set {
self.object = NSNumber(unsignedLong: newValue)
}
}
public var int8: Int8? {
get {
return self.number?.charValue
}
set {
if newValue != nil {
self.object = NSNumber(char: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int8Value: Int8 {
get {
return self.numberValue.charValue
}
set {
self.object = NSNumber(char: newValue)
}
}
public var uInt8: UInt8? {
get {
return self.number?.unsignedCharValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedChar: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt8Value: UInt8 {
get {
return self.numberValue.unsignedCharValue
}
set {
self.object = NSNumber(unsignedChar: newValue)
}
}
public var int16: Int16? {
get {
return self.number?.shortValue
}
set {
if newValue != nil {
self.object = NSNumber(short: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int16Value: Int16 {
get {
return self.numberValue.shortValue
}
set {
self.object = NSNumber(short: newValue)
}
}
public var uInt16: UInt16? {
get {
return self.number?.unsignedShortValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedShort: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt16Value: UInt16 {
get {
return self.numberValue.unsignedShortValue
}
set {
self.object = NSNumber(unsignedShort: newValue)
}
}
public var int32: Int32? {
get {
return self.number?.intValue
}
set {
if newValue != nil {
self.object = NSNumber(int: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int32Value: Int32 {
get {
return self.numberValue.intValue
}
set {
self.object = NSNumber(int: newValue)
}
}
public var uInt32: UInt32? {
get {
return self.number?.unsignedIntValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedInt: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt32Value: UInt32 {
get {
return self.numberValue.unsignedIntValue
}
set {
self.object = NSNumber(unsignedInt: newValue)
}
}
public var int64: Int64? {
get {
return self.number?.longLongValue
}
set {
if newValue != nil {
self.object = NSNumber(longLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int64Value: Int64 {
get {
return self.numberValue.longLongValue
}
set {
self.object = NSNumber(longLong: newValue)
}
}
public var uInt64: UInt64? {
get {
return self.number?.unsignedLongLongValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedLongLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt64Value: UInt64 {
get {
return self.numberValue.unsignedLongLongValue
}
set {
self.object = NSNumber(unsignedLongLong: newValue)
}
}
}
//MARK: - Comparable
extension JSON : Swift.Comparable {}
public func ==(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber == rhs.rawNumber
case (.String, .String):
return lhs.rawString == rhs.rawString
case (.Bool, .Bool):
return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
case (.Array, .Array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.Dictionary, .Dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.Null, .Null):
return true
default:
return false
}
}
public func <=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber <= rhs.rawNumber
case (.String, .String):
return lhs.rawString <= rhs.rawString
case (.Bool, .Bool):
return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
case (.Array, .Array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.Dictionary, .Dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.Null, .Null):
return true
default:
return false
}
}
public func >=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber >= rhs.rawNumber
case (.String, .String):
return lhs.rawString >= rhs.rawString
case (.Bool, .Bool):
return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
case (.Array, .Array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.Dictionary, .Dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.Null, .Null):
return true
default:
return false
}
}
public func >(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber > rhs.rawNumber
case (.String, .String):
return lhs.rawString > rhs.rawString
default:
return false
}
}
public func <(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber < rhs.rawNumber
case (.String, .String):
return lhs.rawString < rhs.rawString
default:
return false
}
}
private let trueNumber = NSNumber(bool: true)
private let falseNumber = NSNumber(bool: false)
private let trueObjCType = String.fromCString(trueNumber.objCType)
private let falseObjCType = String.fromCString(falseNumber.objCType)
// MARK: - NSNumber: Comparable
extension NSNumber: Swift.Comparable {
var isBool:Bool {
get {
let objCType = String.fromCString(self.objCType)
if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType)
|| (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){
return true
} else {
return false
}
}
}
}
public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedSame
}
}
public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool {
return !(lhs == rhs)
}
public func <(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedAscending
}
}
public func >(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedDescending
}
}
public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != NSComparisonResult.OrderedDescending
}
}
public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != NSComparisonResult.OrderedAscending
}
} | mit |
austinzheng/swift | test/Parse/diagnose_dynamicReplacement.swift | 35 | 595 | // RUN: %target-typecheck-verify-swift -swift-version 5
dynamic func dynamic_replaceable() {
}
@_dynamicReplacement
// expected-error@-1 {{expected '(' in '_dynamicReplacement' attribute}}
func test_dynamic_replacement_for() {
}
@_dynamicReplacement(
// expected-error@-1 {{expected 'for' in '_dynamicReplacement' attribute}}
func test_dynamic_replacement_for2() {
}
@_dynamicReplacement(for: dynamically_replaceable() // expected-note {{to match this opening '('}}
func test_dynamic_replacement_for3() {
// expected-error@-1 {{expected ')' after function name for @_dynamicReplacement}}
}
| apache-2.0 |
Ben21hao/edx-app-ios-enterprise-new | Test/EndToEnd/Code/XCUIElement+Helpers.swift | 2 | 1052 | //
// XCUIElement+Helpers.swift
// edX
//
// Created by Akiva Leffert on 3/8/16.
// Copyright © 2016 edX. All rights reserved.
//
import Foundation
import XCTest
extension XCUIElement {
///Removes any current text in the field before typing in the new value
/// - Parameter text: the text to enter into the field
func clearAndEnterText(text: String) -> Void {
self.tap()
if let stringValue = self.value as? String {
let deleteString = stringValue.characters.map { _ in "\u{8}" }.joinWithSeparator("")
if deleteString.characters.count > 0 {
self.typeText(deleteString)
}
}
self.typeText(text)
}
/// Sometimes the first tap doesn't take, possibly due to a timing issue around userInteractionEnabled.
/// Tap in a loop until it works
func tapUntilElementExists(element : XCUIElement) {
while(!element.exists) {
self.tap()
if(!element.exists) {
sleep(1)
}
}
}
} | apache-2.0 |
0x0c/RDImageViewerController | RDImageViewerController/Classes/View/PagingView/PagingView.swift | 1 | 13600 | //
// RDPagingView.swift
// Pods-RDImageViewerController
//
// Created by Akira Matsuda on 2019/04/07.
//
import UIKit
public protocol PagingViewDataSource {
func pagingView(pagingView: PagingView, preloadItemAt index: Int)
func pagingView(pagingView: PagingView, cancelPreloadingItemAt index: Int)
}
public protocol PagingViewDelegate {
func pagingView(pagingView: PagingView, willChangeViewSize size: CGSize, duration: TimeInterval, visibleViews: [UIView])
func pagingView(pagingView: PagingView, willChangeIndexTo index: PagingView.VisibleIndex, currentIndex: PagingView.VisibleIndex)
func pagingView(pagingView: PagingView, didChangeIndexTo index: PagingView.VisibleIndex)
func pagingView(pagingView: PagingView, didScrollToPosition position: CGFloat)
func pagingView(pagingView: PagingView, didEndDisplaying view: UIView & PageViewRepresentation, index: Int)
func pagingViewWillBeginDragging(pagingView: PagingView)
func pagingViewDidEndDragging(pagingView: PagingView, willDecelerate decelerate: Bool)
func pagingViewWillBeginDecelerating(pagingView: PagingView)
func pagingViewDidEndDecelerating(pagingView: PagingView)
func pagingViewDidEndScrollingAnimation(pagingView: PagingView)
}
open class PagingView: UICollectionView {
public enum ForwardDirection {
case right
case left
case up
case down
}
public enum VisibleIndex {
case single(index: Int)
case double(indexes: [Int])
}
public weak var pagingDataSource: (PagingViewDataSource & UICollectionViewDataSource)?
public weak var pagingDelegate: (PagingViewDelegate & UICollectionViewDelegate & UICollectionViewDelegateFlowLayout)?
public var numberOfPages: Int {
guard let pagingDataSource = pagingDataSource else {
return 0
}
return pagingDataSource.collectionView(self, numberOfItemsInSection: 0)
}
public var preloadCount: Int = 3
private var _isRotating: Bool = false
public func beginRotate() {
_isRotating = true
}
public func endRotate() {
_isRotating = false
}
public func beginChangingBarState() {
if let layout = collectionViewLayout as? PagingViewFlowLayout {
layout.ignoreTargetContentOffset = true
}
}
public func endChangingBarState() {
if let layout = collectionViewLayout as? PagingViewFlowLayout {
layout.ignoreTargetContentOffset = false
}
}
public var isDoubleSpread: Bool = false {
didSet {
currentPageIndex = currentPageIndex.convert(double: isDoubleSpread)
if let layout = collectionViewLayout as? PagingViewFlowLayout {
layout.isDoubleSpread = isDoubleSpread
}
}
}
func setLayoutIndex(_ index: VisibleIndex) {
if let flowLayout = collectionViewLayout as? PagingViewFlowLayout {
flowLayout.currentPageIndex = index
}
}
public var scrollDirection: ForwardDirection
private var _currentPageIndex: VisibleIndex = .single(index: 0)
public var currentPageIndex: VisibleIndex {
set {
_currentPageIndex = newValue
scrollTo(index: newValue.primaryIndex())
}
get {
if isDoubleSpread {
return .double(indexes: visiblePageIndexes)
}
return _currentPageIndex
}
}
public var visiblePageIndexes: [Int] {
indexPathsForVisibleItems.map { (indexPath) -> Int in
Int(indexPath.row)
}
}
public var isLegacyLayoutSystem: Bool {
if #available(iOS 11.0, *) {
return false
}
else if scrollDirection == .left {
return true
}
else {
return false
}
}
public init(frame: CGRect, forwardDirection: ForwardDirection) {
scrollDirection = forwardDirection
if forwardDirection == .left {
super.init(frame: frame, collectionViewLayout: PagingViewRightToLeftFlowLayout())
if #available(iOS 11.0, *) {
self.contentInsetAdjustmentBehavior = .never
}
else {
transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
}
}
else if forwardDirection == .right {
super.init(frame: frame, collectionViewLayout: PagingViewHorizontalFlowLayout())
}
else if forwardDirection == .up {
super.init(frame: frame, collectionViewLayout: PagingViewBottomToTopLayout())
}
else { // .down
super.init(frame: frame, collectionViewLayout: PagingViewVerticalFlowLayout())
}
delegate = self
dataSource = self
}
@available(*, unavailable)
public required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func scrollTo(index: Int, animated: Bool = false) {
if index > numberOfPages - 1 || index < 0 {
return
}
var position: UICollectionView.ScrollPosition {
if scrollDirection.isHorizontal {
if isDoubleSpread {
if index % 2 == 0 {
return .left
}
return .right
}
return .centeredHorizontally
}
else {
return .centeredVertically
}
}
if let layout = collectionViewLayout as? PagingViewFlowLayout {
layout.currentPageIndex = currentPageIndex
}
scrollToItem(at: IndexPath(row: index, section: 0), at: position, animated: animated)
}
public func resizeVisiblePages() {
collectionViewLayout.invalidateLayout()
for cell in visibleCells {
if let view = cell as? PageViewRepresentation {
view.resize(pageIndex: cell.rd_pageIndex, scrollDirection: scrollDirection, traitCollection: traitCollection, isDoubleSpread: isDoubleSpread)
}
}
}
public func changeDirection(_ forwardDirection: ForwardDirection) {
scrollDirection = forwardDirection
if forwardDirection == .left {
collectionViewLayout = PagingViewRightToLeftFlowLayout()
if #available(iOS 11.0, *) {
self.contentInsetAdjustmentBehavior = .never
}
else {
transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
}
}
else {
transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
if forwardDirection == .right {
collectionViewLayout = PagingViewHorizontalFlowLayout()
}
else if forwardDirection == .up {
collectionViewLayout = PagingViewBottomToTopLayout()
}
else { // .down
collectionViewLayout = PagingViewVerticalFlowLayout()
}
}
reloadData()
}
override open func reloadData() {
collectionViewLayout.invalidateLayout()
super.reloadData()
}
override open func layoutSubviews() {
beginChangingBarState()
super.layoutSubviews()
endChangingBarState()
if isLegacyLayoutSystem {
for cell in visibleCells {
cell.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
}
}
}
}
extension PagingView: UIScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if _isRotating {
return
}
guard let pagingDelegate = pagingDelegate else {
return
}
let position = scrollView.contentOffset.x / scrollView.frame.width
if scrollDirection.isHorizontal {
pagingDelegate.pagingView(pagingView: self, didScrollToPosition: position)
if isDoubleSpread {
let newIndex: VisibleIndex = .double(indexes: visiblePageIndexes)
if _currentPageIndex != newIndex {
pagingDelegate.pagingView(pagingView: self, willChangeIndexTo: newIndex, currentIndex: _currentPageIndex)
}
_currentPageIndex = newIndex
}
else {
let to = Int(position + 0.5)
let newIndex: VisibleIndex = to.rd_single()
if _currentPageIndex != newIndex {
pagingDelegate.pagingView(pagingView: self, willChangeIndexTo: newIndex, currentIndex: _currentPageIndex)
}
_currentPageIndex = newIndex
}
}
else {
pagingDelegate.pagingView(pagingView: self, didScrollToPosition: scrollView.contentOffset.y)
if let index = indexPathsForVisibleItems.sorted().rd_middle {
let to = index.row
let newIndex: VisibleIndex = to.rd_convert(double: isDoubleSpread)
if _currentPageIndex != newIndex {
pagingDelegate.pagingView(pagingView: self, willChangeIndexTo: newIndex, currentIndex: _currentPageIndex)
}
_currentPageIndex = newIndex
}
}
setLayoutIndex(_currentPageIndex)
}
public func scrollViewWillBeginDragging(_: UIScrollView) {
if let pagingDelegate = pagingDelegate {
pagingDelegate.pagingViewWillBeginDragging(pagingView: self)
}
}
public func scrollViewDidEndDragging(_: UIScrollView, willDecelerate decelerate: Bool) {
if let pagingDelegate = pagingDelegate {
pagingDelegate.pagingViewDidEndDragging(pagingView: self, willDecelerate: decelerate)
if decelerate == false {
pagingDelegate.pagingView(pagingView: self, didChangeIndexTo: currentPageIndex)
}
}
}
public func scrollViewWillBeginDecelerating(_: UIScrollView) {
if let pagingDelegate = pagingDelegate {
pagingDelegate.pagingViewWillBeginDecelerating(pagingView: self)
}
}
public func scrollViewDidEndDecelerating(_: UIScrollView) {
if let pagingDelegate = pagingDelegate {
pagingDelegate.pagingViewDidEndDecelerating(pagingView: self)
pagingDelegate.pagingView(pagingView: self, didChangeIndexTo: currentPageIndex)
}
}
public func scrollViewDidEndScrollingAnimation(_: UIScrollView) {
if let pagingDelegate = pagingDelegate {
pagingDelegate.pagingViewDidEndScrollingAnimation(pagingView: self)
}
}
}
extension PagingView: UICollectionViewDelegate {}
extension PagingView: UICollectionViewDataSource {
override open func numberOfItems(inSection section: Int) -> Int {
guard let pagingDataSource = pagingDataSource else {
return 0
}
return pagingDataSource.collectionView(self, numberOfItemsInSection: section)
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let pagingDataSource = pagingDataSource else {
return 0
}
return pagingDataSource.collectionView(collectionView, numberOfItemsInSection: section)
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let pagingDataSource = pagingDataSource else {
return UICollectionViewCell(frame: CGRect.zero)
}
let cell = pagingDataSource.collectionView(collectionView, cellForItemAt: indexPath)
cell._rd_pageIndex = indexPath.row
if isLegacyLayoutSystem {
cell.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
}
// prefetch
let prefetchStartIndex = max(0, indexPath.row - preloadCount)
let prefetchEndIndex = min(numberOfPages - 1, indexPath.row + preloadCount)
for i in prefetchStartIndex ..< prefetchEndIndex {
pagingDataSource.pagingView(pagingView: self, preloadItemAt: i)
}
// cancel
let cancelStartIndex = min(max(0, indexPath.row - preloadCount - 1), numberOfPages - 1)
let cancelEndIndex = max(min(numberOfPages - 1, indexPath.row + preloadCount + 1), 0)
for i in cancelStartIndex ..< prefetchStartIndex {
pagingDataSource.pagingView(pagingView: self, cancelPreloadingItemAt: i)
}
for i in prefetchEndIndex ..< cancelEndIndex {
pagingDataSource.pagingView(pagingView: self, cancelPreloadingItemAt: i)
}
return cell
}
public func collectionView(_: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let pagingDelegate = pagingDelegate, let view = cell as? (UIView & PageViewRepresentation) else {
return
}
pagingDelegate.pagingView(pagingView: self, didEndDisplaying: view, index: indexPath.row)
}
}
extension PagingView: UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
guard let pagingDelegate = pagingDelegate else {
return .zero
}
return pagingDelegate.collectionView?(
collectionView,
layout: collectionViewLayout,
sizeForItemAt: indexPath
) ?? .zero
}
}
| mit |
yaobanglin/viossvc | viossvc/Scenes/Order/CustomView/OrderListCell.swift | 1 | 4620 | //
// Created by yaowang on 2016/11/1.
// Copyright (c) 2016 ywwlcom.yundian. All rights reserved.
//
import UIKit
class OrderListCell : OEZTableViewCell {
@IBOutlet weak var headPicImageView: UIImageView!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var nicknameLabel: UILabel!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var serviceLabel: UILabel!
@IBOutlet weak var moneyLabel: UILabel!
@IBOutlet weak var orderTypeLabel: UILabel!
let statusDict:Dictionary<OrderStatus, String> = [.WaittingAccept: "等待接受",//等待服务者接受
.Reject: "已拒绝",//服务者拒绝
.Accept: "已接受",//服务者接受
.WaittingPay: "等待支付",//等待消费者支付
.Paid: "支付完成",//已经支付
.Cancel: "已取消",//取消
.OnGoing: "进行中",//订单进行中
.Completed: "已完成",//服务者确定完成
.InvoiceMaking: "已完成",
.InvoiceMaked: "已完成"]
let statusColor:Dictionary<OrderStatus, UIColor> = [.WaittingAccept: UIColor.init(red: 245/255.0, green: 164/255.0, blue: 49/255.0, alpha: 1),
.Reject: UIColor.redColor(),
.Accept: UIColor.init(red: 245/255.0, green: 164/255.0, blue: 49/255.0, alpha: 1),
.WaittingPay: UIColor.init(red: 245/255.0, green: 164/255.0, blue: 49/255.0, alpha: 1),
.Paid: UIColor.greenColor(),
.Cancel: UIColor.grayColor(),
.OnGoing: UIColor.init(red: 245/255.0, green: 164/255.0, blue: 49/255.0, alpha: 1),//订单进行中
.Completed: UIColor.init(red: 245/255.0, green: 164/255.0, blue: 49/255.0, alpha: 1),
.InvoiceMaking: UIColor.init(red: 245/255.0, green: 164/255.0, blue: 49/255.0, alpha: 1),
.InvoiceMaked: UIColor.greenColor()]
private var dateFormatter:NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .ShortStyle
dateFormatter.timeStyle = .ShortStyle
return dateFormatter
}()
@IBAction func didSelectAction(sender: AnyObject) {
didSelectRowAction(AppConst.Action.HandleOrder.rawValue, data: nil)
}
override func update(data: AnyObject!) {
let orderListModel = data as! OrderListModel
if orderListModel.from_url!.hasPrefix("http"){
headPicImageView.kf_setImageWithURL(NSURL(string: orderListModel.from_url!), placeholderImage: UIImage(named: "head_giry"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
orderTypeLabel.text = orderListModel.order_type == 0 ? "邀约" : "预约"
nicknameLabel.text = orderListModel.from_name
serviceLabel.text = orderListModel.service_name
moneyLabel.text = "\(Float(orderListModel.order_price)/100)元"
statusLabel.text = statusDict[OrderStatus(rawValue: (orderListModel.order_status))!]
statusLabel.textColor = statusColor[OrderStatus(rawValue: (orderListModel.order_status))!]
timeLabel.text = dateFormatter.stringFromDate(NSDate(timeIntervalSince1970: Double(orderListModel.start_time)))
// + "-" + dateFormatter.stringFromDate(NSDate(timeIntervalSince1970: Double(orderListModel.end_time)))
}
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.