repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
liuCodeBoy/Ant | Ant/Ant/LunTan/Detials/Controller/RentNeedDVC.swift | 1 | 7988 | //
// RentNeedDVC.swift
// Ant
//
// Created by Weslie on 2017/8/4.
// Copyright © 2017年 LiuXinQiang. All rights reserved.
//
import UIKit
class RentNeedDVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView?
var modelInfo: LunTanDetialModel?
//定义接受id
var rentNeedID : Int?
override func viewDidLoad() {
super.viewDidLoad()
loadCellData(index: 1)
loadDetialTableView()
let view = Menu()
self.tabBarController?.tabBar.isHidden = true
view.frame = CGRect(x: 0, y: screenHeight - 124, width: screenWidth, height: 60)
self.view.addSubview(view)
}
func loadDetialTableView() {
let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 60)
self.tableView = UITableView(frame: frame, style: .grouped)
self.tableView?.delegate = self
self.tableView?.dataSource = self
self.tableView?.backgroundColor = UIColor.init(white: 0.9, alpha: 1)
self.tableView?.showsVerticalScrollIndicator = false
self.tableView?.separatorStyle = .singleLine
tableView?.register(UINib(nibName: "RentNeedDetial", bundle: nil), forCellReuseIdentifier: "rentNeedDetial")
tableView?.register(UINib(nibName: "DetialControduction", bundle: nil), forCellReuseIdentifier: "detialControduction")
tableView?.register(UINib(nibName: "ConnactOptions", bundle: nil), forCellReuseIdentifier: "connactOptions")
tableView?.register(UINib(nibName: "MessageHeader", bundle: nil), forCellReuseIdentifier: "messageHeader")
tableView?.register(UINib(nibName: "MessagesCell", bundle: nil), forCellReuseIdentifier: "messagesCell")
tableView?.separatorStyle = .singleLine
self.view.addSubview(tableView!)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 5
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0: return 1
case 2: return 5
case 3: return 1
case 4: return 1
default: return 1
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
switch section {
case 1:
let detialHeader = Bundle.main.loadNibNamed("DetialHeaderView", owner: nil, options: nil)?.first as? DetialHeaderView
detialHeader?.DetialHeaderLabel.text = "详情信息"
return detialHeader
case 2:
let connactHeader = Bundle.main.loadNibNamed("DetialHeaderView", owner: nil, options: nil)?.first as? DetialHeaderView
connactHeader?.DetialHeaderLabel.text = "联系方式"
return connactHeader
default:
return nil
}
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if section == 2 {
return Bundle.main.loadNibNamed("Share", owner: nil, options: nil)?.first as? UIView
} else {
return nil
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch section {
case 1:
return 35
case 2:
return 35
case 3:
return 10
case 4:
return 0.00001
default:
return 0.00001
}
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == 2 {
return 140
} else {
return 0.00001
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell?
switch indexPath.section {
case 0:
let rentneeddetial = tableView.dequeueReusableCell(withIdentifier: "rentNeedDetial") as! RentNeedDetial
rentneeddetial.viewModel = modelInfo
cell = rentneeddetial
if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! {
cell?.separatorInset = UIEdgeInsets.zero
}
case 1:
let detialcontroduction = tableView.dequeueReusableCell(withIdentifier: "detialControduction") as! DetialControduction
detialcontroduction.viewModel = modelInfo
cell = detialcontroduction
case 2:
let connactoptions = tableView.dequeueReusableCell(withIdentifier: "connactOptions") as! ConnactOptions
if let key = modelInfo?.connactDict[indexPath.row].first?.key {
connactoptions.con_Ways.text = key
}
if let value = modelInfo?.connactDict[indexPath.row].first?.value {
connactoptions.con_Detial.text = value
}
switch modelInfo?.connactDict[indexPath.row].first?.key {
case "联系人"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_profile")
case "电话"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_phone")
case "微信"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_wechat")
case "QQ"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_qq")
case "邮箱"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_email")
default:
break
}
cell = connactoptions
if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! {
cell?.separatorInset = UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 0)
}
case 3: cell = tableView.dequeueReusableCell(withIdentifier: "messageHeader")
case 4: cell = tableView.dequeueReusableCell(withIdentifier: "messagesCell")
default: break
}
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.section {
case 0:
return 260
case 1:
return detialHeight + 10
case 2:
return 50
case 3:
return 40
case 4:
return 120
default:
return 20
}
}
}
extension RentNeedDVC {
// MARK:- load data
fileprivate func loadCellData(index: Int) {
let group = DispatchGroup()
//将当前的下载操作添加到组中
group.enter()
NetWorkTool.shareInstance.infoDetial(VCType: .seek, id: rentNeedID!) { [weak self](result, error) in
//在这里异步加载任务
if error != nil {
print(error ?? "load house info list failed")
return
}
guard let resultDict = result!["result"] else {
return
}
let basic = LunTanDetialModel(dict: resultDict as! [String : AnyObject])
self?.modelInfo = basic
//离开当前组
group.leave()
}
group.notify(queue: DispatchQueue.main) {
//在这里告诉调用者,下完完毕,执行下一步操作
self.tableView?.reloadData()
}
}
}
| apache-2.0 | 5cbf240789cd349b7a91273085092d97 | 31.987395 | 130 | 0.573175 | 5.128021 | false | false | false | false |
debugsquad/nubecero | nubecero/Model/Store/Base/MStore.swift | 1 | 2998 | import Foundation
import StoreKit
class MStore
{
typealias PurchaseId = String
let mapItems:[PurchaseId:MStoreItem]
let references:[PurchaseId]
var error:String?
private let priceFormatter:NumberFormatter
init()
{
priceFormatter = NumberFormatter()
priceFormatter.numberStyle = NumberFormatter.Style.currencyISOCode
let itemPlus:MStoreItemPlus = MStoreItemPlus()
let itemAlbums:MStoreItemAlbums = MStoreItemAlbums()
mapItems = [
itemPlus.purchaseId:itemPlus,
itemAlbums.purchaseId:itemAlbums
]
references = [
itemPlus.purchaseId,
itemAlbums.purchaseId
]
}
//MARK: public
func loadSkProduct(skProduct:SKProduct)
{
let productId:String = skProduct.productIdentifier
guard
let mappedItem:MStoreItem = mapItems[productId]
else
{
return
}
mappedItem.skProduct = skProduct
priceFormatter.locale = skProduct.priceLocale
let priceNumber:NSDecimalNumber = skProduct.price
guard
let priceString:String = priceFormatter.string(from:priceNumber)
else
{
return
}
mappedItem.foundPurchase(price:priceString)
}
func updateTransactions(transactions:[SKPaymentTransaction])
{
for skPaymentTransaction:SKPaymentTransaction in transactions
{
let productId:String = skPaymentTransaction.payment.productIdentifier
guard
let mappedItem:MStoreItem = mapItems[productId]
else
{
continue
}
switch skPaymentTransaction.transactionState
{
case SKPaymentTransactionState.deferred:
mappedItem.statusDeferred()
break
case SKPaymentTransactionState.failed:
mappedItem.statusNew()
SKPaymentQueue.default().finishTransaction(skPaymentTransaction)
break
case SKPaymentTransactionState.purchased,
SKPaymentTransactionState.restored:
mappedItem.statusPurchased(callAction:true)
SKPaymentQueue.default().finishTransaction(skPaymentTransaction)
break
case SKPaymentTransactionState.purchasing:
mappedItem.statusPurchasing()
break
}
}
}
}
| mit | f11458bb5fb817fe42ca9c917141c093 | 26.254545 | 84 | 0.508339 | 6.907834 | false | false | false | false |
mrmichaelkang/TalkBach | Talk Bach/Talk Bach/MenuViewController.swift | 1 | 1355 | //
// ViewController.swift
// Talk Bach
//
// Created by Michael Kang on 8/5/17.
// Copyright © 2017 RITVA. All rights reserved.
//
import UIKit
class MenuViewController: UIViewController {
// MARK: Outlets
@IBOutlet weak var musicTheoryButton: UIButton!
@IBOutlet weak var earTrainingButton: UIButton!
@IBOutlet weak var menuImageView: UIImageView!
@IBOutlet weak var menuTextView: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Setup buttons
setupButton(for: musicTheoryButton)
setupButton(for: earTrainingButton)
setupLabel(for: menuTextView)
setupImage(for: menuImageView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Setup Functions
func setupButton(for button: UIButton) {
button.layer.borderWidth = 1
button.backgroundColor = UIColor.white
button.layer.cornerRadius = 7
}
func setupLabel(for label: UILabel) {
label.text = "Talk Bach"
label.font = UIFont(name: "Papyrus", size: 28)
}
func setupImage(for image: UIImageView) {
image.image = UIImage(named: "bach-caricature")
}
// MARK: Button Functions
}
| bsd-3-clause | 9c33bb71a946c5010f27cc88e18e3c91 | 23.178571 | 58 | 0.638109 | 4.528428 | false | false | false | false |
GitHubCha2016/ZLSwiftFM | ZLSwiftFM/ZLSwiftFM/Classes/Home/Controller/HomeViewController.swift | 1 | 4264 | //
// HomeViewController.swift
// ZLSwiftFM
//
// Created by ZXL on 2017/5/15.
// Copyright © 2017年 zl. All rights reserved.
//
import UIKit
class HomeViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
//初始化UI
setupUI()
}
// 标题
let titles:[String] = ["直播","热门","分类","榜单","主播"]
// 顶部标题
var titleNavi:ZLCustomNavigation?
/// 滚动的视图的滚动是否是因为用户点击了标题按钮
var isScrollViewScrollByButtonClick:Bool = false
func setupUI() {
// 添加表格
tableView.frame = CGRect(x: 0, y: 64 + kNavHeight, width: kScreenWidth, height: kScreenHeight - 64 - kNavHeight)
// view.addSubview(tableView)
automaticallyAdjustsScrollViewInsets = false
// 设置标题
navigationItem.titleView = middleTitleView
// 添加标题导航
self.titleNavi = ZLCustomNavigation(frame: CGRect.zero,
titles: titles) { [unowned self] (index) in
customLog( "点击了标题\(index)")
self.isScrollViewScrollByButtonClick = true;
self.scrollView.setContentOffset(CGPoint(x: kScreenWidth * CGFloat(index), y: 0), animated: true)
}
view.addSubview(titleNavi!)
scrollView.bringSubview(toFront: titleNavi!)
// 添加滚动视图
view.addSubview(scrollView)
}
// 搜索框
lazy var middleTitleView:UIView = {
let titleView = ZLTitleTextField()
titleView.backgroundColor = UIColor.hexInt(0xebedf1)
titleView.placeholder = "明清搜索拾遗"
titleView.frame = CGRect(x: 0, y: 0, width: 236, height: 28)
titleView.layer.cornerRadius = 14
titleView.isEnabled = false
titleView.clipsToBounds = true
return titleView
}()
// 滚动视图
lazy var scrollView:UIScrollView = {
let scrollView = UIScrollView()
scrollView.frame = CGRect(x: 0, y: 64 + kNavHeight, width: kScreenWidth, height: (kScreenHeight - 64 - kNavHeight))
scrollView.delegate = self
scrollView.isPagingEnabled = true
scrollView.contentSize = CGSize(width: kScreenWidth * CGFloat(self.titles.count), height: 0)
// 添加View
for (index, _) in self.titles.enumerated() {
let viewController = self.subViewControllers[index]
viewController.view.frame = CGRect(x: kScreenWidth * CGFloat(index), y: 0, width: kScreenWidth, height: (kScreenHeight - 64 - kNavHeight))
scrollView.addSubview(viewController.view)
}
return scrollView
}()
private lazy var subViewControllers:[UIViewController] = {
var array = [UIViewController]()
// 直播
let live = ZLLiveViewController()
self.addChildViewController(live)
array.append(live)
// 热门
let hot = ZLHotViewController()
self.addChildViewController(hot)
array.append(hot)
// 分类
let category = ZLCategoryViewController()
self.addChildViewController(category)
array.append(category)
// 榜单
let top = ZLTopsViewController()
self.addChildViewController(top)
array.append(top)
// 主播
let anchor = ZLAnchorViewController()
self.addChildViewController(anchor)
array.append(anchor)
return array
}()
}
//MARK:- UIScrollViewDelegate
extension HomeViewController {
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
/// 滚动标题
// 通过调用setContentOffset这个方法 该代理会有回调
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
/// 滚动标题
let page = Int(scrollView.contentOffset.x / kScreenWidth + 0.5)
customLog(page)
titleNavi?.setTitleIndex(index: page)
}
}
| mit | a9d2ed13a520f9c4f4674ec7c9b04739 | 30.023077 | 150 | 0.59881 | 4.853189 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new | Source/UIView+LayoutDirection.swift | 4 | 1706 | //
// UIView+LayoutDirection.swift
// edX
//
// Created by Akiva Leffert on 7/20/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
extension UIView {
var isRightToLeft : Bool {
if #available(iOS 9.0, *) {
let direction = UIView.userInterfaceLayoutDirectionForSemanticContentAttribute(self.semanticContentAttribute)
switch direction {
case .LeftToRight: return false
case .RightToLeft: return true
}
} else {
return UIApplication.sharedApplication().userInterfaceLayoutDirection == .RightToLeft
}
}
}
enum LocalizedHorizontalContentAlignment {
case Leading
case Center
case Trailing
case Fill
}
extension UIControl {
var localizedHorizontalContentAlignment : LocalizedHorizontalContentAlignment {
get {
switch self.contentHorizontalAlignment {
case .Left:
return self.isRightToLeft ? .Trailing : .Leading
case .Right:
return self.isRightToLeft ? .Leading : .Trailing
case .Center:
return .Center
case .Fill:
return .Fill
}
}
set {
switch newValue {
case .Leading:
self.contentHorizontalAlignment = self.isRightToLeft ? .Right : .Left
case .Trailing:
self.contentHorizontalAlignment = self.isRightToLeft ? .Left : .Right
case .Center:
self.contentHorizontalAlignment = .Center
case .Fill:
self.contentHorizontalAlignment = .Fill
}
}
}
} | apache-2.0 | 0546c6902b8342fd0393a0d5bb2a0260 | 27.45 | 121 | 0.578546 | 5.630363 | false | false | false | false |
wfleming/pico-block | pblock/RuleParser/ContentRuleJSONFileParser.swift | 1 | 2485 | //
// ContentRuleJSONFileParser.swift
// pblock
//
// Created by Will Fleming on 8/30/15.
// Copyright © 2015 PBlock. All rights reserved.
//
import Foundation
// a rule file parser for the WebKit content blocker extension format
class ContentRuleJSONFileParser: RuleFileParserProtocol {
private var ruleJSONObjects: Array<Dictionary<String, AnyObject>> = []
private var rules: Array<ParsedRule>? = nil
required init(fileSource: String) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(
fileSource.dataUsingEncoding(NSUTF8StringEncoding)!,
options: NSJSONReadingOptions.init(rawValue: 0))
if let castJSON = json as? Array<Dictionary<String, AnyObject>> {
self.ruleJSONObjects = castJSON
} else {
dlog("JSON parsed, but didn't match an expected format")
}
} catch {
dlog("couldn't parse JSON: \(error)")
}
}
convenience required init(fileURL: NSURL) {
let fileContents = try! String(contentsOfURL: fileURL, encoding: NSUTF8StringEncoding)
self.init(fileSource: fileContents)
}
func parsedRules() -> Array<ParsedRule> {
if let r = rules {
return r
}
let isNonNil = { (r: ParsedRule?) -> Bool in return nil != r }
let unwrapRule = { (rule: ParsedRule?) -> ParsedRule in rule! }
rules = ruleJSONObjects.map(ruleFromJSON).filter(isNonNil).map(unwrapRule)
return rules!
}
// can return nil if JSON doesn't describe a rule
private func ruleFromJSON(json: Dictionary<String, AnyObject>) -> ParsedRule? {
let sourceText = try! String(
data:NSJSONSerialization.dataWithJSONObject(json,
options: NSJSONWritingOptions.init(rawValue: 0)),
encoding: NSUTF8StringEncoding)
let action = json["action"] as? Dictionary<String, String>
let trigger = json["trigger"] as? Dictionary<String, AnyObject>
let r = ParsedRule(
sourceText: sourceText,
actionType: RuleActionType.fromJSON(action!["type"]),
actionSelector: action?["selector"],
triggerUrlFilter: trigger?["url-filter"] as? String,
triggerResourceTypes: RuleResourceTypeOptions.fromJSON(
trigger?["resource-type"] as? Array<String>
),
triggerLoadTypes: RuleLoadTypeOptions.fromJSON(
trigger?["load-type"] as? Array<String>
),
triggerIfDomain: trigger?["if-domain"] as? Array<String>,
triggerUnlessDomain: trigger?["unless-domain"] as? Array<String>
)
return r
}
}
| mit | 81eb79bb2fac18fc1a8b13a8ba369217 | 31.25974 | 90 | 0.680757 | 4.203046 | false | false | false | false |
whiteshadow-gr/HatForIOS | HAT/Objects/Profile/Education/HATProfileEducationObject.swift | 1 | 4065 | /**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
import SwiftyJSON
// MARK: Struct
public struct HATProfileEducationObject: HatApiType, Comparable {
// MARK: - Fields
/// The possible Fields of the JSON struct
struct Fields {
static let highestAcademicQualification: String = "highestAcademicQualification"
static let unixTimeStamp: String = "unixTimeStamp"
static let data: String = "data"
static let recordID: String = "recordId"
}
// MARK: - Comparable protocol
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: HATProfileEducationObject, rhs: HATProfileEducationObject) -> Bool {
return (lhs.highestAcademicQualification == rhs.highestAcademicQualification && lhs.unixTimeStamp == rhs.unixTimeStamp)
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// This function is the only requirement of the `Comparable` protocol. The
/// remainder of the relational operator functions are implemented by the
/// standard library for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func < (lhs: HATProfileEducationObject, rhs: HATProfileEducationObject) -> Bool {
return lhs.unixTimeStamp! < rhs.unixTimeStamp!
}
// MARK: - Variables
/// User's highest academic qualification
public var highestAcademicQualification: String = ""
/// Record ID
public var recordID: String = ""
/// Date of the record created in Unix time stamp
public var unixTimeStamp: Int?
// MARK: - Initialisers
/**
The default initialiser. Initialises everything to default values.
*/
public init() {
highestAcademicQualification = ""
recordID = ""
unixTimeStamp = nil
}
/**
It initialises everything from the received JSON file from the HAT
- dict: The JSON file received from the HAT
*/
public init(from dict: JSON) {
if let data = (dict[Fields.data].dictionary) {
highestAcademicQualification = (data[Fields.highestAcademicQualification]!.stringValue)
if let time = (data[Fields.unixTimeStamp]?.stringValue) {
unixTimeStamp = Int(time)
}
}
recordID = (dict[Fields.recordID].stringValue)
}
/**
It initialises everything from the received JSON file from the HAT
- dict: The JSON file received from the HAT
*/
public mutating func initialize(fromCache: Dictionary<String, Any>) {
if let tempQualification = fromCache[Fields.highestAcademicQualification] {
self.highestAcademicQualification = String(describing: tempQualification)
}
}
// MARK: - JSON Mapper
/**
Returns the object as Dictionary, JSON
- returns: Dictionary<String, String>
*/
public func toJSON() -> Dictionary<String, Any> {
return [
Fields.highestAcademicQualification: self.highestAcademicQualification,
Fields.unixTimeStamp: Int(HATFormatterHelper.formatDateToEpoch(date: Date())!)!
]
}
}
| mpl-2.0 | 1beb651361256e688e8e10757c31ebf4 | 30.269231 | 127 | 0.617958 | 4.645714 | false | false | false | false |
gservera/TaxonomyKit | Sources/TaxonomyKit/WikipediaResponse.swift | 1 | 3207 | /*
* WikipediaResponse.swift
* TaxonomyKit
*
* Created: Guillem Servera on 09/06/2017.
* Copyright: © 2017 Guillem Servera (https://github.com/gservera)
*
* 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
internal struct WikipediaResponse: Codable {
struct Query: Codable {
struct Page: Codable {
struct Thumbnail: Codable {
let source: URL
let width: Int
let height: Int
}
let thumbnail: Thumbnail?
let extract: String?
let identifier: Int?
let title: String
enum CodingKeys: String, CodingKey {
case identifier = "pageid", title, extract, thumbnail
}
var isMissing: Bool {
return identifier == -1 || identifier == nil
}
}
struct Redirect: Codable {
let from: String
let target: String
enum CodingKeys: String, CodingKey {
case from, target = "to"
}
}
let pages: [Int: WikipediaResponse.Query.Page]
let redirects: [WikipediaResponse.Query.Redirect]
init(from decoder: Decoder) throws {
let box = try decoder.container(keyedBy: CodingKeys.self)
if let redirects = try box.decodeIfPresent([WikipediaResponse.Query.Redirect].self, forKey: .redirects) {
self.redirects = redirects
} else {
self.redirects = []
}
self.pages = try box.decode(Dictionary<Int, WikipediaResponse.Query.Page>.self, forKey: .pages)
}
}
let query: Query
let warnings: [String: [String: String]]
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let warnings = try container.decodeIfPresent([String: [String: String]].self, forKey: .warnings) {
self.warnings = warnings
} else {
self.warnings = [:]
}
self.query = try container.decode(WikipediaResponse.Query.self, forKey: .query)
}
}
| mit | a77b3ad5a5b403458f60426440e35fa0 | 34.230769 | 117 | 0.627261 | 4.619597 | false | false | false | false |
apple/swift-lldb | packages/Python/lldbsuite/test/lang/swift/unknown_reference/main.swift | 1 | 1097 | // main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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 Foundation
// Auxiliary functions.
func use(_ c : ObjCClass) {}
func use(_ c : PureClass) {}
func doCall(_ fn : () -> ()) { fn() }
// Pure Swift objects.
class PureBase {
let base_string = "hello"
}
class PureClass : PureBase {
let string = "world"
}
// Objective-C objects.
class Base : NSObject {
let base_string = "hello"
}
class ObjCClass : Base {
let string = "world"
}
struct S {
let string = "offset"
unowned var pure_ref : PureClass
unowned var objc_ref : ObjCClass
func f() {
use(self.pure_ref) // break here
}
}
let pure = PureClass()
let objc = ObjCClass()
S(pure_ref: pure, objc_ref: objc).f()
| apache-2.0 | d44a8afcb6709f9a8c223a5120ebf10d | 20.509804 | 80 | 0.621696 | 3.63245 | false | false | false | false |
gregomni/swift | test/Generics/missing_sendable_conformance.swift | 8 | 1089 | // RUN: %target-typecheck-verify-swift
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s
// REQUIRES: concurrency
// rdar://91174106 - allow missing Sendable conformances when extending a
// type generically.
// FIXME: Should warn because of missing Sendable, but currently is silent
// because we aren't checking conformance availability here yet.
class C {}
struct G1<T: Sendable> {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=G1
// CHECK-NEXT: Generic signature: <T where T == C>
extension G1 where T == C {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=G1
// CHECK-NEXT: Generic signature: <T where T : C, T : Sendable>
extension G1 where T : C {}
protocol P {
associatedtype A
}
struct G2<T : P> where T.A : Sendable {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=G2
// CHECK-NEXT: Generic signature: <T where T : P, T.[P]A == C>
extension G2 where T.A == C {}
// CHECK-LABEL: ExtensionDecl line={{.*}} base=G2
// CHECK-NEXT: Generic signature: <T where T : P, T.[P]A : C, T.[P]A : Sendable>
extension G2 where T.A : C {}
| apache-2.0 | c6106af87ad86fda73ae71c659fa1f7e | 31.029412 | 91 | 0.675849 | 3.361111 | false | false | false | false |
matthewpalmer/swift-deck | Pod/Classes/Deck.swift | 1 | 2581 | //
// Deck.swift
// Pods
//
// Created by Matthew Palmer on 11/03/2015.
//
//
import UIKit
/// A generic Deck type, like a deck of cards or a slide deck.
///
/// A Deck is similar to a Stack, except that you can go forwards and backwards through it. When you get to the end of a Stack, it loops back around to the start.
public class Deck<T> {
// MARK: - Private attributes
private var cards: [T] = []
private var currentCardIndex: Int
// MARK: - Private functions
/**
Initializes a new Deck with the provided set of 'cards'.
:param: index The index of the card to retrieve
:returns: The card at the index of `cards`, provided that the index is valid (nil otherwise).
*/
private func cardAtIndex(index: Int) -> T? {
if index >= cards.count || index < 0 {
return nil
}
return cards[index]
}
// MARK: - Initialization
/**
Initializes a new Deck with the provided set of 'cards'.
:param: cards An array of cards
:returns: A 'Deck' of the provided cards
*/
public init(cards: [T]) {
self.cards = cards
self.currentCardIndex = 0
}
// MARK: - Public methods
/**
Get the card at the top of the deck, without advancing our position in the deck.
:returns: The card at the top of the deck, if it exists.
*/
public func currentCard() -> T? {
return cardAtIndex(currentCardIndex)
}
// Advance our position in the deck forwards and return the next card.
/**
Advance our position in the deck forwards and return the next card. A 'forward' progression through the deck.
:returns: The next card in the deck, if it exists.
*/
public func nextCard() -> T? {
currentCardIndex = currentCardIndex + 1
// Wrap around if we've gone past the end of the deck
if currentCardIndex >= cards.count {
currentCardIndex = 0
}
return cardAtIndex(currentCardIndex)
}
/**
Retreat our position in the deck backwards and return the previous card. A 'backward' progression through the deck.
:returns: The previous card in the deck, if it exists.
*/
public func previousCard() -> T? {
currentCardIndex = currentCardIndex - 1
// Wrap around if we've gone past the start of the deck
if currentCardIndex < 0 {
currentCardIndex = cards.count - 1
}
return cardAtIndex(currentCardIndex)
}
}
| mit | a74dc957223dd8db7eea024220c12086 | 27.362637 | 162 | 0.603255 | 4.419521 | false | false | false | false |
Majki92/SwiftEmu | SwiftBoy/GameBoyCPU.swift | 2 | 4021 | //
// GameBoyCPU.swift
// SwiftBoy
//
// Created by Michal Majczak on 12.09.2015.
// Copyright (c) 2015 Michal Majczak. All rights reserved.
//
import Foundation
class GameBoyCPU {
var registers: GameBoyRegisters
var memory: GameBoyRAM
var timer: GameBoyTimer
var opcodes: [OpCode]
var extOpcodes: [OpCode]
var interruptMasterFlag: Bool
var haltMode: Bool
init(memory mem: GameBoyRAM) {
registers = GameBoyRegisters()
memory = mem;
opcodes = generateOpCodeTable()
extOpcodes = generateExtOpCodeTable()
timer = GameBoyTimer(memory: memory)
interruptMasterFlag = false
haltMode = false
}
func tic() {
HandleInterrupts()
if !haltMode {
let opCodeVal = memory.read(address: registers.PC)
let opCode = opcodes[Int(opCodeVal)]
if opCode.instruction != nil {
//LogD("Called: \"" + opCode.name + "\" of code: 0x" + String(format:"%02X", opCodeVal) + ". PC= 0x" + String(format:"%04X",registers.PC))
opCode.instruction!(self)
} else {
LogE("ERROR: Unimplemented instruction \"" + opCode.name + "\" of code: 0x" + String(format:"%02X", opCodeVal) + " found in PC=" + String(format:"%04X", registers.PC))
exit(-1)
}
} else {
updateClock(1)
}
}
func HandleInterrupts() {
let IE = memory.read(address: GameBoyRAM.IE)
let IF = memory.read(address: GameBoyRAM.IF)
if !interruptMasterFlag {
if haltMode && (IE & IF) > 0{
haltMode = false
}
return
}
if (IE & IF & GameBoyRAM.I_P10P13) != 0 { // P10-P13 terminal negative edge
memory.write16(address: registers.SP-2, value: registers.PC)
registers.SP -= 2;
interruptMasterFlag = false
registers.PC = GameBoyRAM.JMP_I_P10P13
memory.write(address: GameBoyRAM.IF, value: IF & ~GameBoyRAM.I_P10P13)
haltMode = false
return
}
if (IE & IF & GameBoyRAM.I_SERIAL) != 0 { // Serial transfer completion
memory.write16(address: registers.SP-2, value: registers.PC)
registers.SP -= 2;
interruptMasterFlag = false
registers.PC = GameBoyRAM.JMP_I_SERIAL
memory.write(address: GameBoyRAM.IF, value: IF & ~GameBoyRAM.I_SERIAL)
haltMode = false
return
}
if (IE & IF & GameBoyRAM.I_TIMER) != 0 { // Timer overflow
memory.write16(address: registers.SP-2, value: registers.PC)
registers.SP -= 2;
interruptMasterFlag = false
registers.PC = GameBoyRAM.JMP_I_TIMER
memory.write(address: GameBoyRAM.IF, value: IF & ~GameBoyRAM.I_TIMER)
haltMode = false
return
}
if (IE & IF & GameBoyRAM.I_LCDC) != 0 { // LCDC interrupt
memory.write16(address: registers.SP-2, value: registers.PC)
registers.SP -= 2;
interruptMasterFlag = false
registers.PC = GameBoyRAM.JMP_I_LCDC
memory.write(address: GameBoyRAM.IF, value: IF & ~GameBoyRAM.I_LCDC)
haltMode = false
return
}
if (IE & IF & GameBoyRAM.I_VBLANK) != 0 { // VBlank
memory.write16(address: registers.SP-2, value: registers.PC)
registers.SP -= 2;
interruptMasterFlag = false
registers.PC = GameBoyRAM.JMP_I_VBLANK
memory.write(address: GameBoyRAM.IF, value: IF & ~GameBoyRAM.I_VBLANK)
haltMode = false
return
}
}
func updateClock(_ cycles: UInt8) {
timer.updateTimer(cycles)
}
func reset() {
registers.reset()
interruptMasterFlag = false
haltMode = false
timer.reset()
}
}
//optcodes
| gpl-2.0 | e3b5f95850d0296c4ab835e81499c30f | 32.789916 | 183 | 0.551355 | 3.873796 | false | false | false | false |
thoughtbot/Runes | Tests/RunesTests/ArraySpec.swift | 1 | 4551 | import XCTest
import SwiftCheck
import Runes
class ArraySpec: XCTestCase {
func testFunctor() {
// fmap id = id
property("identity law") <- forAll { (xs: [Int]) in
let identity: (Int) -> Int = id
let lhs = identity <^> xs
let rhs = xs
return lhs == rhs
}
// fmap (f . g) = (fmap f) . (fmap g)
property("function composition law") <- forAll { (xs: [Int], fa: ArrowOf<Int, Int>, fb: ArrowOf<Int, Int>) in
let f = fa.getArrow
let g = fb.getArrow
let lhs = f • g <^> xs
let rhs = (curry(<^>)(f) • curry(<^>)(g))(xs)
return lhs == rhs
}
}
func testApplicative() {
// pure id <*> x = x
property("identity law") <- forAll { (xs: [Int]) in
let identity: (Int) -> Int = id
let lhs = pure(identity) <*> xs
let rhs = xs
return lhs == rhs
}
// pure f <*> pure x = pure (f x)
property("homomorphism law") <- forAll { (x: Int, fa: ArrowOf<Int, Int>) in
let f = fa.getArrow
let lhs: [Int] = pure(f) <*> pure(x)
let rhs: [Int] = pure(f(x))
return rhs == lhs
}
// f <*> pure x = pure ($ x) <*> f
property("interchange law") <- forAll { (x: Int, fs: [ArrowOf<Int, Int>]) in
let f = fs.map { $0.getArrow }
let lhs = f <*> pure(x)
let rhs = pure({ $0(x) }) <*> f
return lhs == rhs
}
// u *> v = pure (const id) <*> u <*> v
property("interchange law - right sequence") <- forAll { (u: [Int], v: [Int]) in
let identity: (Int) -> Int = id
let lhs: [Int] = u *> v
let rhs: [Int] = pure(curry(const)(identity)) <*> u <*> v
return lhs == rhs
}
// u <* v = pure const <*> u <*> v
property("interchange law - left sequence") <- forAll { (u: [Int], v: [Int]) in
let lhs: [Int] = u <* v
let rhs: [Int] = pure(curry(const)) <*> u <*> v
return lhs == rhs
}
// f <*> (g <*> x) = pure (.) <*> f <*> g <*> x
property("composition law") <- forAll { (x: [Int], fs: [ArrowOf<Int, Int>], gs: [ArrowOf<Int, Int>]) in
let f = fs.map { $0.getArrow }
let g = gs.map { $0.getArrow }
let lhs = f <*> (g <*> x)
let rhs = pure(curry(•)) <*> f <*> g <*> x
return lhs == rhs
}
}
func testAlternative() {
property("alternative operator - left empty") <- forAll { (x: Int) in
let lhs: [Int] = empty() <|> pure(x)
let rhs: [Int] = pure(x)
return lhs == rhs
}
property("alternative operator - right empty") <- forAll { (x: Int) in
let lhs: [Int] = pure(x) <|> empty()
let rhs: [Int] = pure(x)
return lhs == rhs
}
property("alternative operator - neither empty") <- forAll { (x: Int, y: Int) in
let lhs: [Int] = pure(x) <|> pure(y)
let rhs: [Int] = pure(x) + pure(y)
return lhs == rhs
}
}
func testMonad() {
// return x >>= f = f x
property("left identity law") <- forAll { (x: Int, fa: ArrowOf<Int, Int>) in
let f: (Int) -> [Int] = pure • fa.getArrow
let lhs = pure(x) >>- f
let rhs = f(x)
return lhs == rhs
}
// m >>= return = m
property("right identity law") <- forAll { (x: [Int]) in
let lhs = x >>- pure
let rhs = x
return lhs == rhs
}
// (m >>= f) >>= g = m >>= (\x -> f x >>= g)
property("associativity law") <- forAll { (m: [Int], fa: ArrowOf<Int, Int>, fb: ArrowOf<Int, Int>) in
let f: (Int) -> [Int] = pure • fa.getArrow
let g: (Int) -> [Int] = pure • fb.getArrow
let lhs = (m >>- f) >>- g
let rhs = m >>- { x in f(x) >>- g }
return lhs == rhs
}
// (f >=> g) >=> h = f >=> (g >=> h)
property("left-to-right Kleisli composition of monads") <- forAll { (x: Int, fa: ArrowOf<Int, Int>, fb: ArrowOf<Int, Int>, fc: ArrowOf<Int, Int>) in
let f: (Int) -> [Int] = pure • fa.getArrow
let g: (Int) -> [Int] = pure • fb.getArrow
let h: (Int) -> [Int] = pure • fc.getArrow
let lhs = (f >-> g) >-> h
let rhs = f >-> (g >-> h)
return lhs(x) == rhs(x)
}
// (f <=< g) <=< h = f <=< (g <=< h)
property("right-to-left Kleisli composition of monads") <- forAll { (x: Int, fa: ArrowOf<Int, Int>, fb: ArrowOf<Int, Int>, fc: ArrowOf<Int, Int>) in
let f: (Int) -> [Int] = pure • fa.getArrow
let g: (Int) -> [Int] = pure • fb.getArrow
let h: (Int) -> [Int] = pure • fc.getArrow
let lhs = (f <-< g) <-< h
let rhs = f <-< (g <-< h)
return lhs(x) == rhs(x)
}
}
}
| mit | 831036d92b906afc1c2c9c01c7f8496d | 26.107784 | 152 | 0.483101 | 3.197034 | false | false | false | false |
coolshubh4/iOS-Demos | Click Counter/Click Counter/ViewController.swift | 1 | 2826 | //
// ViewController.swift
// Click Counter
//
// Created by Shubham Tripathi on 12/07/15.
// Copyright (c) 2015 Shubham Tripathi. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var count = 0
var label:UILabel!
var toggle = true
var colorOne = UIColor.yellowColor()
var colorTwo = UIColor.redColor()
var colorArray = [UIColor.yellowColor(), UIColor.redColor(), UIColor.purpleColor(), UIColor.orangeColor()]
override func viewDidLoad() {
super.viewDidLoad()
//self.view.backgroundColor = UIColor.cyanColor()
//Label
var label = UILabel()
label.frame = CGRectMake(100, 150, 60, 60)
label.text = "0"
self.view.addSubview(label)
self.label = label
//Increment Button
var incrementButton = UIButton()
incrementButton.frame = CGRectMake(100, 250, 60, 60)
incrementButton.setTitle("Inc +", forState: .Normal)
incrementButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
self.view.addSubview(incrementButton)
incrementButton.addTarget(self, action: "incrementCount", forControlEvents: UIControlEvents.TouchUpInside)
//Decrement Button
var decrementButton = UIButton()
decrementButton.frame = CGRectMake(100, 350, 60, 60)
decrementButton.setTitle("Dec -", forState: .Normal)
decrementButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
self.view.addSubview(decrementButton)
decrementButton.addTarget(self, action: "decrementCount", forControlEvents: UIControlEvents.TouchUpInside)
//BackgroungColorToggle Button
var toggleColorButton = UIButton()
toggleColorButton.frame = CGRectMake(100, 450, 150, 100)
toggleColorButton.setTitle("ToggleBGColor", forState: .Normal)
toggleColorButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
self.view.addSubview(toggleColorButton)
toggleColorButton.addTarget(self, action: "toggleBGColor", forControlEvents: UIControlEvents.TouchUpInside)
}
func incrementCount() {
self.count++
self.label.text = "\(self.count)"
}
func decrementCount() {
self.count--
self.label.text = "\(self.count)"
}
func toggleBGColor () {
// if toggle {
// self.view.backgroundColor = colorOne
// toggle = false
// } else {
// self.view.backgroundColor = colorTwo
// toggle = true
// }
let randomColor = Int(arc4random_uniform(UInt32(colorArray.count)))
print(randomColor)
self.view.backgroundColor = colorArray[randomColor]
}
}
| mit | a3ce58eae88569fdba6db2bc32c25a64 | 31.482759 | 115 | 0.62845 | 4.741611 | false | false | false | false |
phitchcock/Immunize | iOSApp/iOSApp/LocationsViewController.swift | 1 | 6344 | //
// ViewController.swift
// iOSApp
//
// Created by Peter Hitchcock on 3/2/16.
// Copyright © 2016 Peter Hitchcock. All rights reserved.
//
import UIKit
import Alamofire
import Haneke
class LocationsViewController: UIViewController {
// MARK: Properties
var locations: [Location] = [Location]()
lazy var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: "handleRefresh:", forControlEvents: UIControlEvents.ValueChanged)
return refreshControl
}()
// MARK: @IBOutlets
@IBOutlet var tableView: UITableView!
// MARK: View LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
refreshControl.tintColor = UIColor.whiteColor()
tableView.addSubview(refreshControl)
tableView.rowHeight = 125.0
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
getLocations()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// TODO: Move out of controller dup code
func getLocations() {
Alamofire.request(.GET, locationUrl)
.responseJSON { response in
if let JSON = response.result.value {
self.locations.removeAll()
let dict = JSON
let ar = dict["locations"] as! [AnyObject]
for a in ar {
// TODO: Potential crash if streetnumber != a numerical string need to check
var name: String
var streetNumber: String
var streetName: String
var city: String
var state: String
var zip: String
var date: String
var time: String
var info: String
var image: String
if let nameJson = a["name"] {
name = nameJson as! String
} else {
name = "ERROR"
}
if let streetNumberJson = a["street_number"] {
streetNumber = streetNumberJson as! String
} else {
streetNumber = "ERROR"
}
if let streetNameJson = a["street_name"] {
streetName = streetNameJson as! String
} else {
streetName = "ERROR"
}
if let cityJson = a["city"] {
city = cityJson as! String
} else {
city = "ERROR"
}
if let stateJson = a["state"] {
state = stateJson as! String
} else {
state = "ERROR"
}
if let zipJson = a["zip"] {
zip = zipJson as! String
} else {
zip = "ERROR"
}
if let dateJson = a["date"] {
date = dateJson as! String
} else {
date = "ERROR"
}
if let timeJson = a["time"] {
time = timeJson as! String
} else {
time = "ERROR"
}
if let infoJson = a["info"] {
info = infoJson as! String
} else {
info = "ERROR"
}
if let imageJson = a["image"] {
image = imageJson as! String
} else {
image = "ERROR"
}
let location = Location(name: name, streetNumber: streetNumber, streetName: streetName, city: city, state: state, zip: zip, date: date, time: time)
location.info = info
location.image = image
self.locations.append(location)
}
self.tableView.reloadData()
}
}
}
func handleRefresh(refreshControl: UIRefreshControl) {
getLocations()
refreshControl.endRefreshing()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "locationSegue" {
let dvc = segue.destinationViewController as! LocationViewController
if let row = tableView.indexPathForSelectedRow?.row {
let location = locations[row]
dvc.location = location
}
}
}
}
// MARK: UITableView Extension
extension LocationsViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return locations.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! LocationTableViewCell
let locationCell = locations[indexPath.row]
cell.nameLabel.text = locationCell.name
cell.streetlabel.text = "\(locationCell.streetNumber) \(locationCell.streetName)"
cell.cityLabel.text = "\(locationCell.city) \(locationCell.state) \(locationCell.zip)"
cell.dateLabel.text = locationCell.date
let URLString = locationCell.image
let URL = NSURL(string:URLString!)!
cell.cellImageView.hnk_setImageFromURL(URL)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
| mit | 4e15309861e4c8e189849424f85786cc | 32.384211 | 171 | 0.48857 | 5.995274 | false | false | false | false |
xwu/swift | test/expr/cast/as_coerce.swift | 5 | 6684 | // RUN: %target-typecheck-verify-swift -enable-objc-interop
// Test the use of 'as' for type coercion (which requires no checking).
@objc protocol P1 {
func foo()
}
class A : P1 {
@objc func foo() { }
}
@objc class B : A {
func bar() { }
}
func doFoo() {}
func test_coercion(_ a: A, b: B) {
// Coercion to a protocol type
let x = a as P1
x.foo()
// Coercion to a superclass type
let y = b as A
y.foo()
}
class C : B { }
class D : C { }
func prefer_coercion(_ c: inout C) {
let d = c as! D
c = d
}
// Coerce literals
var i32 = 1 as Int32
var i8 = -1 as Int8
// Coerce to a superclass with generic parameter inference
class C1<T> {
func f(_ x: T) { }
}
class C2<T> : C1<Int> { }
var c2 = C2<()>()
var c1 = c2 as C1
c1.f(5)
@objc protocol P {}
class CC : P {}
let cc: Any = CC()
if cc is P {
doFoo()
}
if let p = cc as? P {
doFoo()
_ = p
}
// Test that 'as?' coercion fails.
let strImplicitOpt: String! = nil
_ = strImplicitOpt as? String // expected-warning{{conditional downcast from 'String?' to 'String' does nothing}}{{19-30=}}
class C3 {}
class C4 : C3 {}
class C5 {}
var c: AnyObject = C3()
// XXX TODO: Constant-folding should generate an error about 'C3' not being convertible to 'C4'
//if let castX = c as! C4? {}
// XXX TODO: Only suggest replacing 'as' with 'as!' if it would fix the error.
C3() as C4 // expected-error {{'C3' is not convertible to 'C4'}}
// expected-note@-1 {{did you mean to use 'as!' to force downcast?}} {{6-8=as!}}
C3() as C5 // expected-error {{cannot convert value of type 'C3' to type 'C5' in coercion}}
// Diagnostic shouldn't include @lvalue in type of c3.
var c3 = C3()
// XXX TODO: This should not suggest `as!`
c3 as C4 // expected-error {{'C3' is not convertible to 'C4'}}
// expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{4-6=as!}}
// <rdar://problem/19495142> Various incorrect diagnostics for explicit type conversions
1 as Double as Float // expected-error{{cannot convert value of type 'Double' to type 'Float' in coercion}}
1 as Int as String // expected-error{{cannot convert value of type 'Int' to type 'String' in coercion}}
Double(1) as Double as String // expected-error{{cannot convert value of type 'Double' to type 'String' in coercion}}
["awd"] as [Int] // expected-error{{cannot convert value of type 'String' to expected element type 'Int'}}
([1, 2, 1.0], 1) as ([String], Int)
// expected-error@-1 2 {{cannot convert value of type 'Int' to expected element type 'String'}}
// expected-error@-2 {{cannot convert value of type 'Double' to expected element type 'String'}}
[[1]] as [[String]] // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}}
(1, 1.0) as (Int, Int) // expected-error{{cannot convert value of type '(Int, Double)' to type '(Int, Int)' in coercion}}
(1.0, 1, "asd") as (String, Int, Float) // expected-error{{cannot convert value of type '(Double, Int, String)' to type '(String, Int, Float)' in coercion}}
(1, 1.0, "a", [1, 23]) as (Int, Double, String, [String])
// expected-error@-1 2 {{cannot convert value of type 'Int' to expected element type 'String'}}
_ = [1] as! [String] // OK
_ = [(1, (1, 1))] as! [(Int, (String, Int))] // OK
// <rdar://problem/19495253> Incorrect diagnostic for explicitly casting to the same type
_ = "hello" as! String // expected-warning{{forced cast of 'String' to same type has no effect}} {{13-24=}}
// <rdar://problem/19499340> QoI: Nimble as -> as! changes not covered by Fix-Its
func f(_ x : String) {}
f("what" as Any as String) // expected-error {{'Any' is not convertible to 'String'}}
// expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{17-19=as!}}
f(1 as String) // expected-error{{cannot convert value of type 'Int' to type 'String' in coercion}}
// <rdar://problem/19650402> Swift compiler segfaults while running the annotation tests
let s : AnyObject = C3()
s as C3 // expected-error{{'AnyObject' is not convertible to 'C3'}}
// expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{3-5=as!}}
// SR-6022
func sr6022() -> Any { return 0 }
func sr6022_1() { return; }
protocol SR6022_P {}
_ = sr6022 as! SR6022_P // expected-warning {{cast from '() -> Any' to unrelated type 'SR6022_P' always fails}} // expected-note {{did you mean to call 'sr6022' with '()'?}}{{11-11=()}}
_ = sr6022 as? SR6022_P // expected-warning {{cast from '() -> Any' to unrelated type 'SR6022_P' always fails}} // expected-note {{did you mean to call 'sr6022' with '()'}}{{11-11=()}}
_ = sr6022_1 as! SR6022_P // expected-warning {{cast from '() -> ()' to unrelated type 'SR6022_P' always fails}}
_ = sr6022_1 as? SR6022_P // expected-warning {{cast from '() -> ()' to unrelated type 'SR6022_P' always fails}}
func testSR6022_P<T: SR6022_P>(_: T.Type) {
_ = sr6022 as! T // expected-warning {{cast from '() -> Any' to unrelated type 'T' always fails}} // expected-note {{did you mean to call 'sr6022' with '()'?}}{{13-13=()}}
_ = sr6022 as? T // expected-warning {{cast from '() -> Any' to unrelated type 'T' always fails}} // expected-note {{did you mean to call 'sr6022' with '()'?}}{{13-13=()}}
_ = sr6022_1 as! T // expected-warning {{cast from '() -> ()' to unrelated type 'T' always fails}}
_ = sr6022_1 as? T // expected-warning {{cast from '() -> ()' to unrelated type 'T' always fails}}
}
func testSR6022_P_1<U>(_: U.Type) {
_ = sr6022 as! U // Okay
_ = sr6022 as? U // Okay
_ = sr6022_1 as! U // Okay
_ = sr6022_1 as? U // Okay
}
_ = sr6022 as! AnyObject // expected-warning {{forced cast from '() -> Any' to 'AnyObject' always succeeds; did you mean to use 'as'?}}
_ = sr6022 as? AnyObject // expected-warning {{conditional cast from '() -> Any' to 'AnyObject' always succeeds}}
_ = sr6022_1 as! Any // expected-warning {{forced cast from '() -> ()' to 'Any' always succeeds; did you mean to use 'as'?}}
_ = sr6022_1 as? Any // expected-warning {{conditional cast from '() -> ()' to 'Any' always succeeds}}
// SR-13899
let any: Any = 1
if let int = any as Int { // expected-error {{'Any' is not convertible to 'Int'}}
// expected-note@-1 {{did you mean to use 'as?' to conditionally downcast?}} {{18-20=as?}}
}
let _ = any as Int // expected-error {{'Any' is not convertible to 'Int'}}
// expected-note@-1 {{did you mean to use 'as!' to force downcast?}} {{13-15=as!}}
let _: Int = any as Int // expected-error {{'Any' is not convertible to 'Int'}}
// expected-note@-1 {{did you mean to use 'as!' to force downcast?}} {{18-20=as!}}
let _: Int? = any as Int // expected-error {{'Any' is not convertible to 'Int'}}
// expected-note@-1 {{did you mean to use 'as?' to conditionally downcast?}} {{19-21=as?}}
| apache-2.0 | cfe160c3048608a7098b9cd8bd72fd2f | 41.846154 | 185 | 0.638989 | 3.140977 | false | false | false | false |
markeldigital/design-system | vendor/ruby/2.0.0/gems/pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/test.swift | 41 | 2035 | //
// test.swift
// from https://github.com/fullstackio/FlappySwift
//
// Created by Nate Murray on 6/2/14.
// Copyright (c) 2014 Fullstack.io. All rights reserved.
//
import UIKit
import SpriteKit
extension SKNode {
class func unarchiveFromFile(file : NSString) -> SKNode? {
let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks")
var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil)
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene
archiver.finishDecoding()
return scene
}
}
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.toRaw())
} else {
return Int(UIInterfaceOrientationMask.All.toRaw())
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}
| mit | 4a36347e87601bca199129197894b972 | 30.307692 | 106 | 0.637346 | 5.412234 | false | false | false | false |
Mobilette/MobiletteFoundation | Source/MBOAuthCredential.swift | 1 | 7327 | //
// MBOAuthCredential.swift
// MBOAuthCredential
//
// Created by Romain ASNAR on 19/11/15.
// Copyright © 2015 Romain ASNAR. All rights reserved.
//
import Foundation
import Security
open class MBOAuthCredential: NSObject, NSCoding
{
// MARK: - Type
fileprivate struct CodingKeys {
static let base = Bundle.main.bundleIdentifier! + "."
static let userIdentifier = base + "user_identifier"
static let accessToken = base + "access_token"
static let expirationDate = base + "expiration_date"
static let refreshToken = base + "refresh_token"
}
// MARK: - Property
open var userIdentifier: String? = nil
open var token: String? {
if self.isExpired() {
return nil
}
return self.accessToken
}
open var refreshToken: String? = nil
open var expirationDate: Date? = nil
open var archivedOAuthCredential: Data {
return NSKeyedArchiver.archivedData(withRootObject: self)
}
fileprivate var accessToken: String? = nil
// MARK: - Life cycle
public init(userIdentifier: String,
accessToken: String,
refreshToken: String,
expirationDate: Date? = nil
)
{
self.userIdentifier = userIdentifier
self.accessToken = accessToken
self.refreshToken = refreshToken
self.expirationDate = expirationDate
}
// MARK: - NSCoding protocol
@objc required public init?(coder decoder: NSCoder)
{
self.userIdentifier = decoder.decodeObject(forKey: CodingKeys.userIdentifier) as? String
self.accessToken = decoder.decodeObject(forKey: CodingKeys.accessToken) as? String
self.expirationDate = decoder.decodeObject(forKey: CodingKeys.expirationDate) as? Date
self.refreshToken = decoder.decodeObject(forKey: CodingKeys.refreshToken) as? String
}
@objc open func encode(with coder: NSCoder)
{
coder.encode(self.userIdentifier, forKey: CodingKeys.userIdentifier)
coder.encode(self.accessToken, forKey: CodingKeys.accessToken)
coder.encode(self.expirationDate, forKey: CodingKeys.expirationDate)
coder.encode(self.refreshToken, forKey: CodingKeys.refreshToken)
}
// MARK: - Archiving
open func storeToKeychain() throws
{
guard let userIdentifier = self.userIdentifier,
let _ = self.accessToken,
let _ = self.refreshToken
else {
throw MBOAuthCredentialError.badCredentials
}
let query = [
"\(kSecClass)" : "\(kSecClassGenericPassword)",
"\(kSecAttrAccount)" : userIdentifier,
"\(kSecValueData)" : self.archivedOAuthCredential
] as NSDictionary
let secItemDeleteStatus = SecItemDelete(query as CFDictionary)
if secItemDeleteStatus != noErr && secItemDeleteStatus != errSecItemNotFound {
throw MBOAuthCredentialError.unknown(Int(secItemDeleteStatus))
}
let secItemAddStatus = SecItemAdd(query as CFDictionary, nil)
if secItemAddStatus != noErr {
throw MBOAuthCredentialError.unknown(Int(secItemAddStatus))
}
let userDefaults = UserDefaults.standard
userDefaults.set(userIdentifier, forKey: "mb_user_identifier")
let synchronizeResult = userDefaults.synchronize()
if synchronizeResult == false {
throw MBUserDefaultsError.canNotSynchronizeUserDefault
}
}
open class func retreiveCredential(
userIdentifier: String? = nil
) throws -> MBOAuthCredential
{
let identifier: String
if let _userIdentifier = userIdentifier {
identifier = _userIdentifier
}
else {
guard let _userIdentifier = self.userIdentifierFromNSUserDefaults() else {
throw MBOAuthCredentialError.userIdentifierMissing
}
identifier = _userIdentifier
}
let searchQuery = [
"\(kSecClass)" : "\(kSecClassGenericPassword)",
"\(kSecAttrAccount)" : identifier,
"\(kSecReturnData)" : true
] as NSDictionary
var result: AnyObject?
let secItemCopyStatus = SecItemCopyMatching(searchQuery, &result)
if secItemCopyStatus != noErr {
throw MBOAuthCredentialError.unknown(Int(secItemCopyStatus))
}
guard let retrievedData = result as? Data else {
throw MBOAuthCredentialError.canNotCopy
}
guard let credential = NSKeyedUnarchiver.unarchiveObject(with: retrievedData) as? MBOAuthCredential else {
throw MBOAuthCredentialError.canNotUnarchiveObject
}
return credential
}
fileprivate class func userIdentifierFromNSUserDefaults() -> String?
{
let userDefaults = UserDefaults.standard
if let identifier = userDefaults.object(forKey: "mb_user_identifier") as? String {
return identifier
}
return nil
}
// MARK: - Authentication
open func isAuthenticated() -> Bool
{
let hasAccessToken = (self.accessToken != nil)
return (hasAccessToken) && (!self.isExpired())
}
open func isExpired() -> Bool
{
if let expirationDate = self.expirationDate {
let today = Date()
let isExpired = (expirationDate.compare(today) == ComparisonResult.orderedAscending)
return isExpired
}
return false
}
}
public enum MBOAuthCredentialError: MBError
{
case unknown(Int)
case badCredentials
case badResults()
case userIdentifierMissing
case canNotUnarchiveObject
case canNotCopy
public var code: Int {
switch self {
case .unknown:
return 1000
case .badCredentials:
return 1001
case .badResults:
return 1002
case .userIdentifierMissing:
return 1003
case .canNotUnarchiveObject:
return 1004
case .canNotCopy:
return 1005
}
}
public var domain: String {
return "OAuthCredentialDomain"
}
public var description: String {
switch self {
case .unknown:
return "Unknown error."
case .badCredentials:
return "Bad credentials."
case .badResults:
return "Bad results."
case .userIdentifierMissing:
return "User identifier missing"
case .canNotUnarchiveObject:
return "Can not unarchive object."
case .canNotCopy:
return "Can not copy."
}
}
public var reason: String {
switch self {
case .unknown(let status):
return "Security function throw error with status : \(status)."
case .badCredentials:
return ""
case .badResults:
return ""
case .userIdentifierMissing:
return ""
case .canNotUnarchiveObject:
return ""
case .canNotCopy:
return ""
}
}
}
| mit | e434e90157b95a106b61016141fdf043 | 29.65272 | 114 | 0.603877 | 5.304852 | false | false | false | false |
Jubilant-Appstudio/Scuba | Pods/SwifterSwift/Sources/Extensions/Foundation/DateExtensions.swift | 1 | 24159 | //
// DateExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/5/16.
// Copyright © 2016 Omar Albeik. All rights reserved.
//
import Foundation
public extension Date {
/// SwifterSwift: Day name format.
///
/// - threeLetters: 3 letter day abbreviation of day name.
/// - oneLetter: 1 letter day abbreviation of day name.
/// - full: Full day name.
public enum DayNameStyle {
case threeLetters
case oneLetter
case full
}
/// SwifterSwift: Month name format.
///
/// - threeLetters: 3 letter month abbreviation of month name.
/// - oneLetter: 1 letter month abbreviation of month name.
/// - full: Full month name.
public enum MonthNameStyle {
case threeLetters
case oneLetter
case full
}
}
// MARK: - Properties
public extension Date {
/// SwifterSwift: User’s current calendar.
public var calendar: Calendar {
return Calendar.current
}
/// SwifterSwift: Era.
///
/// Date().era -> 1
///
public var era: Int {
return Calendar.current.component(.era, from: self)
}
/// SwifterSwift: Quarter.
public var quarter: Int {
return Calendar.current.component(.quarter, from: self)
}
/// SwifterSwift: Week of year.
///
/// Date().weekOfYear -> 2 // second week in the current year.
///
public var weekOfYear: Int {
return Calendar.current.component(.weekOfYear, from: self)
}
/// SwifterSwift: Week of month.
///
/// Date().weekOfMonth -> 2 // second week in the current month.
///
public var weekOfMonth: Int {
return Calendar.current.component(.weekOfMonth, from: self)
}
/// SwifterSwift: Year.
///
/// Date().year -> 2017
///
/// var someDate = Date()
/// someDate.year = 2000 // sets someDate's year to 2000
///
public var year: Int {
get {
return Calendar.current.component(.year, from: self)
}
set {
if let date = Calendar.current.date(bySetting: .year, value: newValue, of: self) {
self = date
}
}
}
/// SwifterSwift: Month.
///
/// Date().month -> 1
///
/// var someDate = Date()
/// someDate.year = 10 // sets someDate's month to 10.
///
public var month: Int {
get {
return Calendar.current.component(.month, from: self)
}
set {
if let date = Calendar.current.date(bySetting: .month, value: newValue, of: self) {
self = date
}
}
}
/// SwifterSwift: Day.
///
/// Date().day -> 12
///
/// var someDate = Date()
/// someDate.day = 1 // sets someDate's day of month to 1.
///
public var day: Int {
get {
return Calendar.current.component(.day, from: self)
}
set {
if let date = Calendar.current.date(bySetting: .day, value: newValue, of: self) {
self = date
}
}
}
/// SwifterSwift: Weekday.
///
/// Date().weekOfMonth -> 5 // fifth day in the current week.
///
public var weekday: Int {
get {
return Calendar.current.component(.weekday, from: self)
}
set {
if let date = Calendar.current.date(bySetting: .weekday, value: newValue, of: self) {
self = date
}
}
}
/// SwifterSwift: Hour.
///
/// Date().hour -> 17 // 5 pm
///
/// var someDate = Date()
/// someDate.day = 13 // sets someDate's hour to 1 pm.
///
public var hour: Int {
get {
return Calendar.current.component(.hour, from: self)
}
set {
if let date = Calendar.current.date(bySetting: .hour, value: newValue, of: self) {
self = date
}
}
}
/// SwifterSwift: Minutes.
///
/// Date().minute -> 39
///
/// var someDate = Date()
/// someDate.minute = 10 // sets someDate's minutes to 10.
///
public var minute: Int {
get {
return Calendar.current.component(.minute, from: self)
}
set {
if let date = Calendar.current.date(bySetting: .minute, value: newValue, of: self) {
self = date
}
}
}
/// SwifterSwift: Seconds.
///
/// Date().second -> 55
///
/// var someDate = Date()
/// someDate. second = 15 // sets someDate's seconds to 15.
///
public var second: Int {
get {
return Calendar.current.component(.second, from: self)
}
set {
if let date = Calendar.current.date(bySetting: .second, value: newValue, of: self) {
self = date
}
}
}
/// SwifterSwift: Nanoseconds.
///
/// Date().nanosecond -> 981379985
///
public var nanosecond: Int {
get {
return Calendar.current.component(.nanosecond, from: self)
}
set {
if let date = Calendar.current.date(bySetting: .nanosecond, value: newValue, of: self) {
self = date
}
}
}
/// SwifterSwift: Milliseconds.
public var millisecond: Int {
get {
return Calendar.current.component(.nanosecond, from: self) / 1000000
}
set {
let ns = newValue * 1000000
if let date = Calendar.current.date(bySetting: .nanosecond, value: ns, of: self) {
self = date
}
}
}
/// SwifterSwift: Check if date is in future.
///
/// Date(timeInterval: 100, since: Date()).isInFuture -> true
///
public var isInFuture: Bool {
return self > Date()
}
/// SwifterSwift: Check if date is in past.
///
/// Date(timeInterval: -100, since: Date()).isInPast -> true
///
public var isInPast: Bool {
return self < Date()
}
/// SwifterSwift: Check if date is in today.
///
/// Date().isInToday -> true
///
public var isInToday: Bool {
return Calendar.current.isDateInToday(self)
}
/// SwifterSwift: Check if date is within yesterday.
///
/// Date().isInYesterday -> false
///
public var isInYesterday: Bool {
return Calendar.current.isDateInYesterday(self)
}
/// SwifterSwift: Check if date is within tomorrow.
///
/// Date().isInTomorrow -> false
///
public var isInTomorrow: Bool {
return Calendar.current.isDateInTomorrow(self)
}
/// SwifterSwift: Check if date is within a weekend period.
public var isInWeekend: Bool {
return Calendar.current.isDateInWeekend(self)
}
/// SwifterSwift: Check if date is within a weekday period.
public var isInWeekday: Bool {
return !Calendar.current.isDateInWeekend(self)
}
/// SwifterSwift: Check if date is within the current week.
public var isInThisWeek: Bool {
return Calendar.current.isDate(self, equalTo: Date(), toGranularity: .weekOfYear)
}
/// SwifterSwift: Check if date is within the current month.
public var isInThisMonth: Bool {
return Calendar.current.isDate(self, equalTo: Date(), toGranularity: .month)
}
/// SwifterSwift: Check if date is within the current year.
public var isInThisYear: Bool {
return Calendar.current.isDate(self, equalTo: Date(), toGranularity: .year)
}
/// SwifterSwift: ISO8601 string of format (yyyy-MM-dd'T'HH:mm:ss.SSS) from date.
///
/// Date().iso8601String -> "2017-01-12T14:51:29.574Z"
///
public var iso8601String: String {
// https://github.com/justinmakaila/NSDate-ISO-8601/blob/master/NSDateISO8601.swift
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
return dateFormatter.string(from: self).appending("Z")
}
/// SwifterSwift: Nearest five minutes to date.
///
/// var date = Date() // "5:54 PM"
/// date.minute = 32 // "5:32 PM"
/// date.nearestFiveMinutes // "5:30 PM"
///
/// date.minute = 44 // "5:44 PM"
/// date.nearestFiveMinutes // "5:45 PM"
///
public var nearestFiveMinutes: Date {
var components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: self)
let min = components.minute!
components.minute! = min % 5 < 3 ? min - min % 5 : min + 5 - (min % 5)
components.second = 0
return Calendar.current.date(from: components)!
}
/// SwifterSwift: Nearest ten minutes to date.
///
/// var date = Date() // "5:57 PM"
/// date.minute = 34 // "5:34 PM"
/// date.nearestTenMinutes // "5:30 PM"
///
/// date.minute = 48 // "5:48 PM"
/// date.nearestTenMinutes // "5:50 PM"
///
public var nearestTenMinutes: Date {
var components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: self)
let min = components.minute!
components.minute? = min % 10 < 6 ? min - min % 10 : min + 10 - (min % 10)
components.second = 0
return Calendar.current.date(from: components)!
}
/// SwifterSwift: Nearest quarter hour to date.
///
/// var date = Date() // "5:57 PM"
/// date.minute = 34 // "5:34 PM"
/// date.nearestQuarterHour // "5:30 PM"
///
/// date.minute = 40 // "5:40 PM"
/// date.nearestQuarterHour // "5:45 PM"
///
public var nearestQuarterHour: Date {
var components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: self)
let min = components.minute!
components.minute! = min % 15 < 8 ? min - min % 15 : min + 15 - (min % 15)
components.second = 0
return Calendar.current.date(from: components)!
}
/// SwifterSwift: Nearest half hour to date.
///
/// var date = Date() // "6:07 PM"
/// date.minute = 41 // "6:41 PM"
/// date.nearestHalfHour // "6:30 PM"
///
/// date.minute = 51 // "6:51 PM"
/// date.nearestHalfHour // "7:00 PM"
///
public var nearestHalfHour: Date {
var components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: self)
let min = components.minute!
components.minute! = min % 30 < 15 ? min - min % 30 : min + 30 - (min % 30)
components.second = 0
return Calendar.current.date(from: components)!
}
/// SwifterSwift: Nearest hour to date.
///
/// var date = Date() // "6:17 PM"
/// date.nearestHour // "6:00 PM"
///
/// date.minute = 36 // "6:36 PM"
/// date.nearestHour // "7:00 PM"
///
public var nearestHour: Date {
if minute >= 30 {
return beginning(of: .hour)!.adding(.hour, value: 1)
}
return beginning(of: .hour)!
}
/// SwifterSwift: Time zone used by system.
///
/// Date().timeZone -> Europe/Istanbul (current)
///
public var timeZone: TimeZone {
return Calendar.current.timeZone
}
/// SwifterSwift: UNIX timestamp from date.
///
/// Date().unixTimestamp -> 1484233862.826291
///
public var unixTimestamp: Double {
return timeIntervalSince1970
}
}
// MARK: - Methods
public extension Date {
/// SwifterSwift: Date by adding multiples of calendar component.
///
/// let date = Date() // "Jan 12, 2017, 7:07 PM"
/// let date2 = date.adding(.minute, value: -10) // "Jan 12, 2017, 6:57 PM"
/// let date3 = date.adding(.day, value: 4) // "Jan 16, 2017, 7:07 PM"
/// let date4 = date.adding(.month, value: 2) // "Mar 12, 2017, 7:07 PM"
/// let date5 = date.adding(.year, value: 13) // "Jan 12, 2030, 7:07 PM"
///
/// - Parameters:
/// - component: component type.
/// - value: multiples of components to add.
/// - Returns: original date + multiples of component added.
public func adding(_ component: Calendar.Component, value: Int) -> Date {
return Calendar.current.date(byAdding: component, value: value, to: self)!
}
/// SwifterSwift: Add calendar component to date.
///
/// var date = Date() // "Jan 12, 2017, 7:07 PM"
/// date.add(.minute, value: -10) // "Jan 12, 2017, 6:57 PM"
/// date.add(.day, value: 4) // "Jan 16, 2017, 7:07 PM"
/// date.add(.month, value: 2) // "Mar 12, 2017, 7:07 PM"
/// date.add(.year, value: 13) // "Jan 12, 2030, 7:07 PM"
///
/// - Parameters:
/// - component: component type.
/// - value: multiples of compnenet to add.
public mutating func add(_ component: Calendar.Component, value: Int) {
self = adding(component, value: value)
}
/// SwifterSwift: Date by changing value of calendar component.
///
/// let date = Date() // "Jan 12, 2017, 7:07 PM"
/// let date2 = date.changing(.minute, value: 10) // "Jan 12, 2017, 6:10 PM"
/// let date3 = date.changing(.day, value: 4) // "Jan 4, 2017, 7:07 PM"
/// let date4 = date.changing(.month, value: 2) // "Feb 12, 2017, 7:07 PM"
/// let date5 = date.changing(.year, value: 2000) // "Jan 12, 2000, 7:07 PM"
///
/// - Parameters:
/// - component: component type.
/// - value: new value of compnenet to change.
/// - Returns: original date after changing given component to given value.
public func changing(_ component: Calendar.Component, value: Int) -> Date? {
return Calendar.current.date(bySetting: component, value: value, of: self)
}
/// SwifterSwift: Data at the beginning of calendar component.
///
/// let date = Date() // "Jan 12, 2017, 7:14 PM"
/// let date2 = date.beginning(of: .hour) // "Jan 12, 2017, 7:00 PM"
/// let date3 = date.beginning(of: .month) // "Jan 1, 2017, 12:00 AM"
/// let date4 = date.beginning(of: .year) // "Jan 1, 2017, 12:00 AM"
///
/// - Parameter component: calendar component to get date at the beginning of.
/// - Returns: date at the beginning of calendar component (if applicable).
public func beginning(of component: Calendar.Component) -> Date? {
switch component {
case .second:
return Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: self))
case .minute:
return Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: self))
case .hour:
return Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month, .day, .hour], from: self))
case .day:
return Calendar.current.startOfDay(for: self)
case .weekOfYear, .weekOfMonth:
return Calendar.current.date(from:
Calendar.current.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))
case .month:
return Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month], from: self))
case .year:
return Calendar.current.date(from:
Calendar.current.dateComponents([.year], from: self))
default:
return nil
}
}
/// SwifterSwift: Date at the end of calendar component.
///
/// let date = Date() // "Jan 12, 2017, 7:27 PM"
/// let date2 = date.end(of: .day) // "Jan 12, 2017, 11:59 PM"
/// let date3 = date.end(of: .month) // "Jan 31, 2017, 11:59 PM"
/// let date4 = date.end(of: .year) // "Dec 31, 2017, 11:59 PM"
///
/// - Parameter component: calendar component to get date at the end of.
/// - Returns: date at the end of calendar component (if applicable).
public func end(of component: Calendar.Component) -> Date? {
switch component {
case .second:
var date = adding(.second, value: 1)
date = Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date))!
date.add(.second, value: -1)
return date
case .minute:
var date = adding(.minute, value: 1)
let after = Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: date))!
date = after.adding(.second, value: -1)
return date
case .hour:
var date = adding(.hour, value: 1)
let after = Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month, .day, .hour], from: date))!
date = after.adding(.second, value: -1)
return date
case .day:
var date = adding(.day, value: 1)
date = Calendar.current.startOfDay(for: date)
date.add(.second, value: -1)
return date
case .weekOfYear, .weekOfMonth:
var date = self
let beginningOfWeek = Calendar.current.date(from:
Calendar.current.dateComponents([.yearForWeekOfYear, .weekOfYear], from: date))!
date = beginningOfWeek.adding(.day, value: 7).adding(.second, value: -1)
return date
case .month:
var date = adding(.month, value: 1)
let after = Calendar.current.date(from:
Calendar.current.dateComponents([.year, .month], from: date))!
date = after.adding(.second, value: -1)
return date
case .year:
var date = adding(.year, value: 1)
let after = Calendar.current.date(from:
Calendar.current.dateComponents([.year], from: date))!
date = after.adding(.second, value: -1)
return date
default:
return nil
}
}
/// SwifterSwift: Date string from date.
///
/// Date().dateString(ofStyle: .short) -> "1/12/17"
/// Date().dateString(ofStyle: .medium) -> "Jan 12, 2017"
/// Date().dateString(ofStyle: .long) -> "January 12, 2017"
/// Date().dateString(ofStyle: .full) -> "Thursday, January 12, 2017"
///
/// - Parameter style: DateFormatter style (default is .medium).
/// - Returns: date string.
public func dateString(ofStyle style: DateFormatter.Style = .medium) -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .none
dateFormatter.dateStyle = style
return dateFormatter.string(from: self)
}
/// SwifterSwift: Date and time string from date.
///
/// Date().dateTimeString(ofStyle: .short) -> "1/12/17, 7:32 PM"
/// Date().dateTimeString(ofStyle: .medium) -> "Jan 12, 2017, 7:32:00 PM"
/// Date().dateTimeString(ofStyle: .long) -> "January 12, 2017 at 7:32:00 PM GMT+3"
/// Date().dateTimeString(ofStyle: .full) -> "Thursday, January 12, 2017 at 7:32:00 PM GMT+03:00"
///
/// - Parameter style: DateFormatter style (default is .medium).
/// - Returns: date and time string.
public func dateTimeString(ofStyle style: DateFormatter.Style = .medium) -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = style
dateFormatter.dateStyle = style
return dateFormatter.string(from: self)
}
/// SwifterSwift: Check if date is in current given calendar component.
///
/// Date().isInCurrent(.day) -> true
/// Date().isInCurrent(.year) -> true
///
/// - Parameter component: calendar component to check.
/// - Returns: true if date is in current given calendar component.
public func isInCurrent(_ component: Calendar.Component) -> Bool {
return calendar.isDate(self, equalTo: Date(), toGranularity: component)
}
/// SwifterSwift: Time string from date
///
/// Date().timeString(ofStyle: .short) -> "7:37 PM"
/// Date().timeString(ofStyle: .medium) -> "7:37:02 PM"
/// Date().timeString(ofStyle: .long) -> "7:37:02 PM GMT+3"
/// Date().timeString(ofStyle: .full) -> "7:37:02 PM GMT+03:00"
///
/// - Parameter style: DateFormatter style (default is .medium).
/// - Returns: time string.
public func timeString(ofStyle style: DateFormatter.Style = .medium) -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = style
dateFormatter.dateStyle = .none
return dateFormatter.string(from: self)
}
/// SwifterSwift: Day name from date.
///
/// Date().dayName(ofStyle: .oneLetter) -> "T"
/// Date().dayName(ofStyle: .threeLetters) -> "Thu"
/// Date().dayName(ofStyle: .full) -> "Thursday"
///
/// - Parameter Style: style of day name (default is DayNameStyle.full).
/// - Returns: day name string (example: W, Wed, Wednesday).
public func dayName(ofStyle style: DayNameStyle = .full) -> String {
// http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/
let dateFormatter = DateFormatter()
var format: String {
switch style {
case .oneLetter:
return "EEEEE"
case .threeLetters:
return "EEE"
case .full:
return "EEEE"
}
}
dateFormatter.setLocalizedDateFormatFromTemplate(format)
return dateFormatter.string(from: self)
}
/// SwifterSwift: Month name from date.
///
/// Date().monthName(ofStyle: .oneLetter) -> "J"
/// Date().monthName(ofStyle: .threeLetters) -> "Jan"
/// Date().monthName(ofStyle: .full) -> "January"
///
/// - Parameter Style: style of month name (default is MonthNameStyle.full).
/// - Returns: month name string (example: D, Dec, December).
public func monthName(ofStyle style: MonthNameStyle = .full) -> String {
// http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/
let dateFormatter = DateFormatter()
var format: String {
switch style {
case .oneLetter:
return "MMMMM"
case .threeLetters:
return "MMM"
case .full:
return "MMMM"
}
}
dateFormatter.setLocalizedDateFormatFromTemplate(format)
return dateFormatter.string(from: self)
}
/// SwifterSwift: get number of seconds between two date
///
/// - Parameter date: date to compate self to.
/// - Returns: number of seconds between self and given date.
public func secondsSince(_ date: Date) -> Double {
return self.timeIntervalSince(date)
}
/// SwifterSwift: get number of minutes between two date
///
/// - Parameter date: date to compate self to.
/// - Returns: number of minutes between self and given date.
public func minutesSince(_ date: Date) -> Double {
return self.timeIntervalSince(date)/60
}
/// SwifterSwift: get number of hours between two date
///
/// - Parameter date: date to compate self to.
/// - Returns: number of hours between self and given date.
public func hoursSince(_ date: Date) -> Double {
return self.timeIntervalSince(date)/3600
}
/// SwifterSwift: get number of days between two date
///
/// - Parameter date: date to compate self to.
/// - Returns: number of days between self and given date.
public func daysSince(_ date: Date) -> Double {
return self.timeIntervalSince(date)/(3600*24)
}
/// SwifterSwift: check if a date is between two other dates
///
/// - Parameters:
/// - startDate: start date to compare self to.
/// - endDate: endDate date to compare self to.
/// - includeBounds: true if the start and end date should be included (default is false)
/// - Returns: true if the date is between the two given dates.
public func isBetween(_ startDate: Date, _ endDate: Date, includeBounds: Bool = false) -> Bool {
if includeBounds {
return startDate.compare(self).rawValue * self.compare(endDate).rawValue >= 0
} else {
return startDate.compare(self).rawValue * self.compare(endDate).rawValue > 0
}
}
}
// MARK: - Initializers
public extension Date {
/// SwifterSwift: Create a new date form calendar components.
///
/// let date = Date(year: 2010, month: 1, day: 12) // "Jan 12, 2010, 7:45 PM"
///
/// - Parameters:
/// - calendar: Calendar (default is current).
/// - timeZone: TimeZone (default is current).
/// - era: Era (default is current era).
/// - year: Year (default is current year).
/// - month: Month (default is current month).
/// - day: Day (default is today).
/// - hour: Hour (default is current hour).
/// - minute: Minute (default is current minute).
/// - second: Second (default is current second).
/// - nanosecond: Nanosecond (default is current nanosecond).
public init?(
calendar: Calendar? = Calendar.current,
timeZone: TimeZone? = TimeZone.current,
era: Int? = Date().era,
year: Int? = Date().year,
month: Int? = Date().month,
day: Int? = Date().day,
hour: Int? = Date().hour,
minute: Int? = Date().minute,
second: Int? = Date().second,
nanosecond: Int? = Date().nanosecond) {
var components = DateComponents()
components.calendar = calendar
components.timeZone = timeZone
components.era = era
components.year = year
components.month = month
components.day = day
components.hour = hour
components.minute = minute
components.second = second
components.nanosecond = nanosecond
if let date = calendar?.date(from: components) {
self = date
} else {
return nil
}
}
/// SwifterSwift: Create date object from ISO8601 string.
///
/// let date = Date(iso8601String: "2017-01-12T16:48:00.959Z") // "Jan 12, 2017, 7:48 PM"
///
/// - Parameter iso8601String: ISO8601 string of format (yyyy-MM-dd'T'HH:mm:ss.SSSZ).
public init?(iso8601String: String) {
// https://github.com/justinmakaila/NSDate-ISO-8601/blob/master/NSDateISO8601.swift
let dateFormatter = DateFormatter()
dateFormatter.locale = .posix
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let date = dateFormatter.date(from: iso8601String) {
self = date
} else {
return nil
}
}
/// SwifterSwift: Create new date object from UNIX timestamp.
///
/// let date = Date(unixTimestamp: 1484239783.922743) // "Jan 12, 2017, 7:49 PM"
///
/// - Parameter unixTimestamp: UNIX timestamp.
public init(unixTimestamp: Double) {
self.init(timeIntervalSince1970: unixTimestamp)
}
}
| mit | 43616466973c502d2d902cfc169d7ef9 | 29.384906 | 101 | 0.648907 | 3.221659 | false | false | false | false |
PezHead/tiny-tennis-scoreboard | Tiny Tennis/MatchVictoryViewController.swift | 1 | 3083 | //
// MatchVictoryViewController.swift
// Tiny Tennis
//
// Created by David Bireta on 10/15/16.
// Copyright © 2016 David Bireta. All rights reserved.
//
class MatchVictoryViewController: UIViewController {
@IBOutlet var titleLabel: UILabel!
@IBOutlet var avatarImageView: UIImageView!
@IBOutlet var partnerAvatarImageView: UIImageView!
@IBOutlet var winnerNameLabel: UILabel!
@IBOutlet var matchSummaryLabel: UILabel!
var match: Match?
fileprivate var gradientLayer: CALayer?
override func viewDidLoad() {
super.viewDidLoad()
let radialLayer = RadialGradientLayer(withCenter: CGPoint(x: view.frame.size.width / 2, y: view.frame.size.height/2 - 30))
radialLayer.frame = view.bounds
view.layer.insertSublayer(radialLayer, at: 0)
if let match = match {
if match.blueWins == 0 || match.redWins == 0 {
titleLabel.text = "Total Domination"
} else {
titleLabel.text = "Winner"
}
let winners = match.matchWinningChampions
if winners?.count == 1 {
let winner = winners?.first
avatarImageView.image = winner?.avatarImage
partnerAvatarImageView.isHidden = true
} else if winners?.count == 2 {
avatarImageView.image = winners?[0].avatarImage
partnerAvatarImageView.image = winners?[1].avatarImage
partnerAvatarImageView.isHidden = false
}
let winnerNames = winners?.map { $0.name }.joined(separator: " / ")
winnerNameLabel.text = winnerNames
// Remove markdown formatting from summary
matchSummaryLabel.text = match.scoreSummary.replacingOccurrences(of: "*", with: "")
}
}
}
// MARK: Radial Grandient Layer subclass
class RadialGradientLayer: CALayer {
let centerPoint: CGPoint
init(withCenter center: CGPoint) {
self.centerPoint = center
super.init()
self.setNeedsDisplay()
}
required init?(coder aDecoder: NSCoder) {
centerPoint = CGPoint(x: 100, y: 100)
super.init(coder: aDecoder)
}
override func draw(in ctx: CGContext) {
let locations: [CGFloat] = [0.0, 1.0]
let colors = [UIColor.white.cgColor, Chameleon.color(withHexString: "#56D1D2").withAlphaComponent(0.8).cgColor]
let colorSpace = CGColorSpaceCreateDeviceRGB()
let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: locations)
// let radius = bounds.size.width < bounds.size.height ? bounds.size.width : bounds.size.height
let radius = CGFloat(400)
ctx.drawRadialGradient(gradient!, startCenter: centerPoint, startRadius: 0, endCenter: centerPoint, endRadius: radius, options: .drawsAfterEndLocation)
}
}
| mit | aeb1232ba523f9d3b5cd745bff860bbe | 32.5 | 159 | 0.598962 | 4.939103 | false | false | false | false |
turingcorp/gattaca | gattaca/Controller/Home/CHomeShare.swift | 1 | 3678 | import UIKit
extension CHome
{
//MARK: private
private func shareLink()
{
guard
let item:MHomeItem = model.items.first,
let identifier:String = item.gif?.identifier,
let url:URL = MGiphy.factoryShareGifUrl(
identifier:identifier)
else
{
return
}
share(url:url)
}
private func shareGif()
{
model.downloadGif
{ (url:URL?) in
DispatchQueue.main.async
{ [weak self] in
self?.asyncShareGif(url:url)
}
}
}
private func asyncShareGif(url:URL?)
{
guard
let url:URL = url
else
{
let message:String = String.localizedController(
key:"CHome_errorShareGif")
VAlert.messageFail(message:message)
return
}
share(url:url)
}
private func shareMp4()
{
guard
let item:MHomeItem = model.items.first
else
{
return
}
let url:URL = item.url
share(url:url)
}
private func share(url:URL)
{
let activity:UIActivityViewController = UIActivityViewController(
activityItems:[url],
applicationActivities:nil)
if let popover:UIPopoverPresentationController = activity.popoverPresentationController
{
popover.sourceView = view
popover.sourceRect = CGRect.zero
popover.permittedArrowDirections = UIPopoverArrowDirection.any
}
present(activity, animated:true, completion:nil)
}
//MARK: internal
func share()
{
let alert:UIAlertController = UIAlertController(
title:String.localizedController(key:"CHome_alertShareTitle"),
message:nil,
preferredStyle:UIAlertControllerStyle.actionSheet)
let actionCancel:UIAlertAction = UIAlertAction(
title:String.localizedController(key:"CHome_alertShareCancel"),
style:
UIAlertActionStyle.cancel)
let actionGif:UIAlertAction = UIAlertAction(
title:String.localizedController(key:"CHome_alertShareGif"),
style:UIAlertActionStyle.default)
{ [weak self] (action:UIAlertAction) in
self?.shareGif()
}
let actionMp4:UIAlertAction = UIAlertAction(
title:String.localizedController(key:"CHome_alertShareMp4"),
style:UIAlertActionStyle.default)
{ [weak self] (action:UIAlertAction) in
self?.shareMp4()
}
let actionLink:UIAlertAction = UIAlertAction(
title:String.localizedController(key:"CHome_alertShareLink"),
style:UIAlertActionStyle.default)
{ [weak self] (action:UIAlertAction) in
self?.shareLink()
}
alert.addAction(actionGif)
alert.addAction(actionMp4)
alert.addAction(actionLink)
alert.addAction(actionCancel)
if let popover:UIPopoverPresentationController = alert.popoverPresentationController
{
popover.sourceView = view
popover.sourceRect = CGRect.zero
popover.permittedArrowDirections = UIPopoverArrowDirection.up
}
present(alert, animated:true, completion:nil)
}
}
| mit | da2cc8d37a8d0dc9d9004e83d6d6ab9c | 25.652174 | 95 | 0.541871 | 5.606707 | false | false | false | false |
depinette/Depsic | Depsic/Sources/main.swift | 1 | 4238 | //
// main.swift
// Depsic
//
// Created by depinette on 27/12/2015.
// Copyright © 2015 depsys. All rights reserved.
// This is a sample main for a sample app.
import Foundation
#if os(Linux)
import CDispatch
import Glibc
#endif
let scgi = Depsic()
//Create one or more SCGI servers
scgi.addServer(IPV4SocketServer(port:10001))
scgi.addServer(UnixSocketServer(socketName:"/tmp/socket"))
//Hello World request handler
scgi.forRequest( {
(request:RequestInfo) -> Bool in
return request.uri == "/"
},
respond: {
(request:RequestInfo) throws -> Response<String> in
//print "Hello <ip>"
var strResponse:String = "Hello"
if let ip = request.headers["REMOTE_ADDR"] {
strResponse += " \(ip)\n"
}
return Response<String>(content:strResponse)
})
//////////////////////////////////////////////////////
//print the headers
//test with curl http://localhost:8080/headers
scgi.forRequest({
(request:RequestInfo) -> Bool in
return request.uri == "/headers"
},
respond: {
(request:RequestInfo) throws -> Response<[UInt8]> in
let content = "<html>\(request.headers)<br/></html>\n"
var buffer:[UInt8] = Array(count: 1024, repeatedValue: 0)
content.withCString {
bytes in
memcpy(&buffer, bytes,min(Int(buffer.count),Int(strlen(bytes))) )
}
return Response<[UInt8]>(headers:["Status":"200 OK", "Content-Type":"text/html"], content:buffer)
})
//////////////////////////////////////////////////////
//print the request body (using [UInt8] in closures)
//test with curl -d "Hello" http://localhost:8080/body/buffer
scgi.forRequest({
(request:RequestInfo) -> Bool in
return request.uri == "/body"
},
respond: {
(request:Request<[UInt8]>) throws -> Response<[UInt8]> in
var content:String = ""
if let body = request.body {
if let b = String.fromCString(UnsafePointer(body)) {
content = b
}
}
content = "<html>\(content)<br/></html>\n"
var buffer:[UInt8] = Array(count: 1024, repeatedValue: 0)
content.withCString {
bytes in
memcpy(&buffer, bytes,min(Int(buffer.count),Int(strlen(bytes))) )
}
return Response<[UInt8]>(content:buffer)
})
//////////////////////////////////////////////////////
//print body (use String in the closures)
//test with curl -d "Hello" http://localhost:8080/body/string
scgi.forRequest( {
(request:RequestInfo) -> Bool in
return request.uri == "/body2"
},
respond: {
(request:Request<String>) throws -> Response<String> in
var content:String = ""
if let body = request.body {
content = "<html>\(body)<br/></html>\n"
}
return Response<String>(content:content)
})
//////////////////////////////////////////////////////
//mini REST API sample////////////////////////////////
let messageApp = MessageApp()
scgi.forRequest( {
(request:RequestInfo) -> Bool in
return messageApp.requestPredicate(request)
},
respond: {
(request:Request<String>) throws -> Response<String> in
return try messageApp.requestHandler(request)
})
scgi.forRequest({ (request:RequestInfo) -> Bool in
return request.uri == "/form"
},
respond: { (request:Request<String>) -> Response<String> in
return Response<String>(
content:
"<meta charset='UTF-8'>" +
"<form action='/form_process' method='post'>" +
"<input type='text' name='param1' />" +
"<input type='email' name='param2' />" +
"<button type='submit'>send</button>" +
"</form>")
})
scgi.forFormRequest({
(request:RequestInfo) -> Bool in
return request.uri == "/form_process"
},
respond: {
(request:Request<Dictionary<String,String>>) throws -> Response<String> in
var content:String = "\(request.body)"
return Response<String>(content:content)
})
//////////////////////////////////////////////////////
//blocking call
scgi.waitForServers()
print("quit")
| mit | baec01a418fd7b9560389f462647b8ae | 27.823129 | 105 | 0.548501 | 4.121595 | false | false | false | false |
PureSwift/SwiftGL | Sources/Kronos/Capability.swift | 2 | 2298 | //
// Capability.swift
// Kronos
//
// Created by Alsey Coleman Miller on 1/21/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
#if os(iOS) || os(tvOS)
import OpenGLES
#endif
/// OpenGL server-side Capabilities. Can be enabled or disabled.
///
/// - Note: All cases, with the exception of `Dither`, are false by default.
public enum Capability: GLenum {
case Texture2D = 0x0DE1
/// If enabled, cull polygons based on their winding in window coordinates.
case CullFace = 0x0B44
/// If enabled, blend the computed fragment color values with the values in the color buffers.
case Blend = 0x0BE2
/// If enabled, dither color components or indices before they are written to the color buffer.
case Dither = 0x0BD0
/// If enabled, do stencil testing and update the stencil buffer.
case StencilTest = 0x0B90
/// If enabled, do depth comparisons and update the depth buffer.
///
/// - Note: Even if the depth buffer exists and the depth mask is non-zero,
/// the depth buffer is not updated if the depth test is disabled.
case DepthTest = 0x0B71
/// If enabled, discard fragments that are outside the scissor rectangle.
case ScissorTest = 0x0C11
/// If enabled, an offset is added to depth values of a polygon's fragments produced by rasterization.
case PloygonOffsetFill = 0x8037
/// If enabled, compute a temporary coverage value where each bit is determined by the alpha value at
/// the corresponding sample location. The temporary coverage value is then ANDed with the fragment coverage value.
case SampleAlphaToCoverage = 0x809E
/// If enabled, the fragment's coverage is ANDed with the temporary coverage value.
/// If `GL_SAMPLE_COVERAGE_INVERT` is set to `GL_TRUE`, invert the coverage value.
case SampleCoverage = 0x80A0
public var enabled: Bool {
return glIsEnabled(rawValue).boolValue
}
@inline(__always)
public func enable() {
glEnable(rawValue)
}
@inline(__always)
public func disable() {
glDisable(rawValue)
}
}
| mit | 065bc2f81405b654cdf25193a7208059 | 32.289855 | 119 | 0.634741 | 4.358634 | false | true | false | false |
pmwisdom/cordova-background-geolocation-services | src/ios/CDVBackgroundLocationServices.swift | 1 | 24723 | //
// CDVLocationServices.swift
// CordovaLib
//
// Created by Paul Michael Wisdom on 5/31/15.
//
//
import Foundation
import CoreLocation
import CoreMotion
let TAG = "[LocationServices]";
let PLUGIN_VERSION = "1.0";
func log(message: String){
if(debug == true) {
NSLog("%@ - %@", TAG, message)
}
}
var locationManager = LocationManager();
var activityManager = ActivityManager();
var taskManager = TaskManager();
//Option Vars
var distanceFilter = kCLDistanceFilterNone;
var desiredAccuracy = kCLLocationAccuracyBest;
var activityType = CLActivityType.automotiveNavigation;
var interval = 5.0;
var debug: Bool?;
var useActivityDetection = false;
var aggressiveInterval = 2.0;
var stationaryTimout = (Double)(5 * 60); // 5 minutes
var backgroundTaskCount = 0;
//State vars
var enabled = false;
var background = false;
var updatingActivities = false;
var locationUpdateCallback:String?;
var locationCommandDelegate:CDVCommandDelegate?;
var activityUpdateCallback:String?;
var activityCommandDelegate:CDVCommandDelegate?;
@objc(BackgroundLocationServices) open class BackgroundLocationServices : CDVPlugin {
//Initialize things here (basically on run)
override open func pluginInitialize() {
super.pluginInitialize();
locationManager.requestLocationPermissions();
self.promptForNotificationPermission();
NotificationCenter.default.addObserver(
self,
selector: Selector("onResume"),
name: NSNotification.Name.UIApplicationWillEnterForeground,
object: nil);
NotificationCenter.default.addObserver(
self,
selector: Selector("onSuspend"),
name: NSNotification.Name.UIApplicationDidEnterBackground,
object: nil);
NotificationCenter.default.addObserver(
self,
selector: Selector("willResign"),
name: NSNotification.Name.UIApplicationWillResignActive,
object: nil);
}
// 0 distanceFilter,
// 1 desiredAccuracy,
// 2 interval,
// 3 fastestInterval -- (not used on ios),
// 4 aggressiveInterval,
// 5 debug,
// 6 notificationTitle -- (not used on ios),
// 7 notificationText-- (not used on ios),
// 8 activityType, fences -- (not used ios)
// 9 useActivityDetection
open func configure(_ command: CDVInvokedUrlCommand) {
//log(message: "configure arguments: \(command.arguments)");
distanceFilter = command.argument(at: 0) as! CLLocationDistance;
desiredAccuracy = self.toDesiredAccuracy(distance: (command.argument(at: 1) as! Int));
interval = (Double)(command.argument(at: 2) as! Int / 1000); // Millseconds to seconds
aggressiveInterval = (Double)(command.argument(at: 4) as! Int / 1000); // Millseconds to seconds
activityType = self.toActivityType(type: command.argument(at: 8) as! String);
debug = command.argument(at: 5) as? Bool;
useActivityDetection = command.argument(at: 9) as! Bool;
log(message: "--------------------------------------------------------");
log(message: " Configuration Success");
log(message: " Distance Filter \(distanceFilter)");
log(message: " Desired Accuracy \(desiredAccuracy)");
log(message: " Activity Type \(activityType)");
log(message: " Update Interval \(interval)");
log(message: "--------------------------------------------------------");
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK)
commandDelegate!.send(pluginResult, callbackId:command.callbackId)
}
open func registerForLocationUpdates(_ command: CDVInvokedUrlCommand) {
log(message: "registerForLocationUpdates");
locationUpdateCallback = command.callbackId;
locationCommandDelegate = commandDelegate;
}
open func registerForActivityUpdates(_ command : CDVInvokedUrlCommand) {
log(message: "registerForActivityUpdates");
activityUpdateCallback = command.callbackId;
activityCommandDelegate = commandDelegate;
}
open func start(_ command: CDVInvokedUrlCommand) {
log(message: "Started");
enabled = true;
log(message: "Are we in the background? \(background)");
if(background) {
locationManager.startUpdating(force: false);
activityManager.startDetection();
}
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK)
commandDelegate!.send(pluginResult, callbackId:command.callbackId)
}
func stop(_ command: CDVInvokedUrlCommand) {
log(message: "Stopped");
enabled = false;
locationManager.stopBackgroundTracking();
activityManager.stopDetection();
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK)
commandDelegate!.send(pluginResult, callbackId:command.callbackId)
}
func getVersion(_ command: CDVInvokedUrlCommand) {
log(message: "Returning Version \(PLUGIN_VERSION)");
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: PLUGIN_VERSION);
commandDelegate!.send(pluginResult, callbackId: command.callbackId);
}
func startAggressiveTracking(command: CDVInvokedUrlCommand) {
log(message: "startAggressiveTracking");
locationManager.startAggressiveTracking();
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: PLUGIN_VERSION);
commandDelegate!.send(pluginResult, callbackId: command.callbackId);
}
func promptForNotificationPermission() {
log(message: "Prompting For Notification Permissions");
if #available(iOS 8, *) {
let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil);
UIApplication.shared.registerUserNotificationSettings(settings)
} else {
UIApplication.shared.registerForRemoteNotifications(matching: [UIRemoteNotificationType.alert, UIRemoteNotificationType.sound, UIRemoteNotificationType.badge]);
}
}
//State Methods
func onResume() {
log(message: "App Resumed");
background = false;
taskManager.endAllBackgroundTasks();
locationManager.stopUpdating();
activityManager.stopDetection();
}
func onSuspend() {
log(message: "App Suspended. Enabled? \(enabled)");
background = true;
if(enabled) {
locationManager.startUpdating(force: true);
activityManager.startDetection();
}
}
func willResign() {
log(message: "App Will Resign. Enabled? \(enabled)");
background = true;
if(enabled) {
locationManager.startUpdating(force: false);
activityManager.startDetection();
}
}
/* Pinpoint our location with the following accuracy:
*
* kCLLocationAccuracyBestForNavigation highest + sensor data
* kCLLocationAccuracyBest highest
* kCLLocationAccuracyNearestTenMeters 10 meters
* kCLLocationAccuracyHundredMeters 100 meters
* kCLLocationAccuracyKilometer 1000 meters
* kCLLocationAccuracyThreeKilometers 3000 meters
*/
func toDesiredAccuracy(distance: Int) -> CLLocationAccuracy {
if(distance == 0) {
return kCLLocationAccuracyBestForNavigation;
} else if(distance < 10) {
return kCLLocationAccuracyBest;
} else if(distance < 100) {
return kCLLocationAccuracyNearestTenMeters;
} else if (distance < 1000) {
return kCLLocationAccuracyHundredMeters
} else if (distance < 3000) {
return kCLLocationAccuracyKilometer;
} else {
return kCLLocationAccuracyThreeKilometers;
}
}
func toActivityType(type: String) -> CLActivityType {
if(type == "AutomotiveNavigation") {
return CLActivityType.automotiveNavigation;
} else if(type == "OtherNavigation") {
return CLActivityType.otherNavigation;
} else if(type == "Fitness") {
return CLActivityType.fitness;
} else {
return CLActivityType.automotiveNavigation;
}
}
}
class LocationManager : NSObject, CLLocationManagerDelegate {
var manager = CLLocationManager();
let SECS_OLD_MAX = 2.0;
var locationArray = [CLLocation]();
var updatingLocation = false;
var aggressive = false;
var lowPowerMode = false;
override init() {
super.init();
if(self.manager.delegate == nil) {
log(message: "Setting location manager");
self.manager.delegate = self;
self.enableBackgroundLocationUpdates();
self.manager.desiredAccuracy = desiredAccuracy;
self.manager.distanceFilter = distanceFilter;
self.manager.pausesLocationUpdatesAutomatically = false;
self.manager.activityType = activityType;
}
}
func enableBackgroundLocationUpdates() {
// New property required for iOS 9 to get location updates in background:
// http://stackoverflow.com/questions/30808192/allowsbackgroundlocationupdates-in-cllocationmanager-in-ios9
if #available(iOS 9, *) {
self.manager.allowsBackgroundLocationUpdates = true;
}
}
func locationToDict(loc:CLLocation) -> NSDictionary {
let locDict:Dictionary = [
"latitude" : loc.coordinate.latitude,
"longitude" : loc.coordinate.longitude,
"accuracy" : loc.horizontalAccuracy,
"timestamp" : ((loc.timestamp.timeIntervalSince1970 as Double) * 1000),
"speed" : loc.speed,
"altitude" : loc.altitude,
"heading" : loc.course
]
return locDict as NSDictionary;
}
func stopBackgroundTracking() {
taskManager.endAllBackgroundTasks();
self.stopUpdating();
}
func sync() {
self.enableBackgroundLocationUpdates();
var bestLocation:CLLocation?;
var bestAccuracy = 3000.00;
if(locationArray.count == 0) {
log(message: "locationArray has no entries");
return;
}
for loc in locationArray {
if(bestLocation == nil) {
bestAccuracy = loc.horizontalAccuracy;
bestLocation = loc;
} else if(loc.horizontalAccuracy < bestAccuracy) {
bestAccuracy = loc.horizontalAccuracy;
bestLocation = loc;
} else if (loc.horizontalAccuracy == bestAccuracy) &&
(loc.timestamp.compare(bestLocation!.timestamp) == ComparisonResult.orderedDescending) {
bestAccuracy = loc.horizontalAccuracy;
bestLocation = loc;
}
}
log(message: "bestLocation: {\(bestLocation)}");
if bestLocation != nil {
locationArray.removeAll(keepingCapacity: false);
let latitude = bestLocation!.coordinate.latitude;
let longitude = bestLocation!.coordinate.longitude;
let accuracy = bestLocation!.horizontalAccuracy;
var msg = "Got Location Update: { \(latitude) - \(longitude) } Accuracy: \(accuracy)";
if(useActivityDetection) {
msg += " Stationary : \(activityManager.isStationary)";
}
log(message: msg);
NotificationManager.manager.notify(text: msg);
locationCommandDelegate?.run(inBackground: {
var result:CDVPluginResult?;
let loc = self.locationToDict(loc: bestLocation!) as [NSObject: AnyObject];
result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs:loc);
result!.setKeepCallbackAs(true);
locationCommandDelegate?.send(result, callbackId:locationUpdateCallback);
});
}
}
func startAggressiveTracking() {
log(message: "Got Request To Start Aggressive Tracking");
self.enableBackgroundLocationUpdates();
self.aggressive = true;
interval = 1;
syncSeconds = 1;
desiredAccuracy = kCLLocationAccuracyBest;
distanceFilter = 0;
}
// Force here is to make sure we are only starting the location updates once, until we want to restart them
// Was having issues with it starting, and then starting a second time through resign on some builds.
func startUpdating(force : Bool) {
if(!self.updatingLocation || force) {
self.enableBackgroundLocationUpdates();
self.updatingLocation = true;
self.manager.delegate = self;
self.manager.desiredAccuracy = self.lowPowerMode ? kCLLocationAccuracyThreeKilometers : desiredAccuracy;
self.manager.distanceFilter = self.lowPowerMode ? 10.0 : distanceFilter;
self.manager.startUpdatingLocation();
self.manager.startMonitoringSignificantLocationChanges();
taskManager.beginNewBackgroundTask();
log(message: "Starting Location Updates!");
} else {
log(message: "A request was made to start Updating, but the plugin was already updating")
}
}
func stopUpdating() {
log(message: "[LocationManager.stopUpdating] Stopping Location Updates!");
self.updatingLocation = false;
if(locationTimer != nil) {
locationTimer.invalidate();
locationTimer = nil;
}
if(stopUpdateTimer != nil) {
stopUpdateTimer.invalidate();
stopUpdateTimer = nil;
}
self.manager.stopUpdatingLocation();
self.manager.stopMonitoringSignificantLocationChanges();
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
// If we've shut off updating on our side and a location is left in the queue to be passed back we want to toss it or the location manager will restart updating again when we dont want it to.
if(!self.updatingLocation) {
return;
}
let locationArray = locations as NSArray
let locationObj = locationArray.lastObject as! CLLocation
let eventDate = locationObj.timestamp;
let timeSinceUpdate = eventDate.timeIntervalSinceNow as Double;
//log(message: "locationArray: \(locationArray)");
//log(message: "locationObj: \(locationObj)");
//log(message: "eventDate: \(eventDate)");
//log(message: "timeSinceUpdate: \(timeSinceUpdate)");
//log(message: "locationTimer: \(locationTimer)");
//Check here to see if the location is cached
if abs(timeSinceUpdate) < SECS_OLD_MAX {
self.locationArray.append(locationObj);
}
if(locationTimer != nil) {
return;
}
taskManager.beginNewBackgroundTask();
locationTimer = Timer.scheduledTimer(timeInterval: activityManager.isStationary ? stationaryTimout : interval, target: self, selector: #selector(LocationManager.restartUpdates), userInfo: nil, repeats: false);
if(stopUpdateTimer != nil) {
stopUpdateTimer.invalidate();
stopUpdateTimer = nil;
}
stopUpdateTimer = Timer.scheduledTimer(timeInterval: syncSeconds, target: self, selector: #selector(LocationManager.syncAfterXSeconds), userInfo: nil, repeats: false);
}
func restartUpdates() {
log(message: "restartUpdates called");
if(locationTimer != nil) {
locationTimer.invalidate();
locationTimer = nil;
}
self.lowPowerMode = false;
self.manager.delegate = self;
self.manager.desiredAccuracy = desiredAccuracy;
self.manager.distanceFilter = distanceFilter;
self.startUpdating(force: true);
}
func setGPSLowPower() {
log(message: "Setting GPS To Low Power Mode ");
self.lowPowerMode = true;
self.startUpdating(force: true);
}
func syncAfterXSeconds() {
self.setGPSLowPower();
self.sync();
log(message: "Stopped Location Updates After \(syncSeconds)");
}
private func locationManagerDidPauseLocationUpdates(manager: CLLocationManager) {
log(message: "Location Manager Paused Location Updates");
}
private func locationManagerDidResumeLocationUpdates(manager: CLLocationManager) {
log(message: "Location Manager Resumed Location Updates");
}
private func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
log(message: "LOCATION ERROR: \(error.description)");
locationCommandDelegate?.run(inBackground: {
var result:CDVPluginResult?;
result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: error.description);
result!.setKeepCallbackAs(true);
locationCommandDelegate?.send(result, callbackId:locationUpdateCallback);
});
}
private func locationManager(manager: CLLocationManager, didFinishDeferredUpdatesWithError error: NSError?) {
log(message: "Location Manager FAILED deferred \(error!.description)");
}
func requestLocationPermissions() {
if (!CLLocationManager.locationServicesEnabled()) {
log(message: "Location services is not enabled");
} else {
log(message: "Location services enabled");
}
if #available(iOS 8, *) {
self.manager.requestAlwaysAuthorization();
}
}
}
class ActivityManager : NSObject {
var manager : CMMotionActivityManager?;
var available = false;
var updatingActivities = false;
var isStationary = false;
override init() {
super.init();
if(CMMotionActivityManager.isActivityAvailable()) {
log(message: "Activity Manager is Available");
self.manager = CMMotionActivityManager();
self.available = true;
} else {
log(message: "Activity Manager is not Available");
}
}
func confidenceToInt(confidence : CMMotionActivityConfidence) -> Int {
var confidenceMult = 0;
switch(confidence) {
case CMMotionActivityConfidence.high :
confidenceMult = 100;
break;
case CMMotionActivityConfidence.medium :
confidenceMult = 50;
break;
case CMMotionActivityConfidence.low :
confidenceMult = 0;
break;
default:
confidenceMult = 0;
break;
}
return confidenceMult;
}
func getActivityConfidence(detectedActivity : Bool, multiplier : Int) -> Int {
return (detectedActivity ? 1 : 0) * multiplier;
}
func activitiesToArray(data:CMMotionActivity) -> NSDictionary {
let confidenceMult = self.confidenceToInt(confidence: data.confidence);
var detectedActivities:Dictionary = [
"UNKOWN" : self.getActivityConfidence(detectedActivity: data.unknown, multiplier: confidenceMult),
"STILL" : self.getActivityConfidence(detectedActivity: data.stationary, multiplier: confidenceMult),
"WALKING" : self.getActivityConfidence(detectedActivity: data.walking, multiplier: confidenceMult),
"RUNNING" : self.getActivityConfidence(detectedActivity: data.running, multiplier: confidenceMult),
"IN_VEHICLE" : self.getActivityConfidence(detectedActivity: data.automotive, multiplier: confidenceMult)
];
// Cycling Only available on IOS 8.0
if #available(iOS 8.0, *) {
detectedActivities["ON_BICYCLE"] = self.getActivityConfidence(detectedActivity: data.cycling, multiplier: confidenceMult)
}
log(message: "Received Detected Activities : \(detectedActivities)");
return detectedActivities as NSDictionary;
}
func sendActivitiesToCallback(activities : NSDictionary) {
if(activityCommandDelegate != nil) {
activityCommandDelegate?.run(inBackground: {
var result:CDVPluginResult?;
result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs:activities as [NSObject: AnyObject]);
result!.setKeepCallbackAs(true);
activityCommandDelegate?.send(result, callbackId:activityUpdateCallback);
});
}
}
func startDetection() {
//NSLog("Activity Manager - Starting Detection %@", self.available);
if(useActivityDetection == false) {
return;
}
if(self.available) {
self.updatingActivities = true;
manager!.startActivityUpdates(to: OperationQueue()) { data in
if let data = data {
DispatchQueue.main.async(execute: {
if(data.stationary == true) {
self.isStationary = true;
} else {
if(self.isStationary == true) {
locationManager.restartUpdates();
}
self.isStationary = false
}
self.sendActivitiesToCallback(activities: self.activitiesToArray(data: data));
})
}
}
} else {
log(message: "Activity Manager - Not available on your device");
}
}
func stopDetection() {
if(self.available && self.updatingActivities) {
self.updatingActivities = false;
manager!.stopActivityUpdates();
}
}
}
var backgroundTimer: Timer!
var locationTimer: Timer!
var stopUpdateTimer: Timer!
var syncSeconds:TimeInterval = 2;
//Task Manager Singleton
class TaskManager : NSObject {
//let priority = DispatchQueue.GlobalAttributes.qosUserInitiated;
var _bgTaskList = [Int]();
var _masterTaskId = UIBackgroundTaskInvalid;
func beginNewBackgroundTask() -> UIBackgroundTaskIdentifier {
//log(message: "beginNewBackgroundTask called");
let app = UIApplication.shared;
var bgTaskId = UIBackgroundTaskInvalid;
if(app.responds(to: Selector(("beginBackgroundTask")))) {
bgTaskId = app.beginBackgroundTask(expirationHandler: {
log(message: "Background task \(bgTaskId) expired");
});
if(self._masterTaskId == UIBackgroundTaskInvalid) {
self._masterTaskId = bgTaskId;
log(message: "Started Master Task ID \(self._masterTaskId)");
} else {
log(message: "Started Background Task \(bgTaskId)");
self._bgTaskList.append(bgTaskId);
self.endBackgroundTasks();
}
}
return bgTaskId;
}
func endBackgroundTasks() {
self.drainBGTaskList(all: false);
}
func endAllBackgroundTasks() {
self.drainBGTaskList(all: true);
}
func drainBGTaskList(all:Bool){
let app = UIApplication.shared;
if(app.responds(to: Selector(("endBackgroundTask")))) {
let count = self._bgTaskList.count;
for _ in 0 ..< count {
let bgTaskId = self._bgTaskList[0] as Int;
log(message: "Ending Background Task with ID \(bgTaskId)");
app.endBackgroundTask(bgTaskId);
self._bgTaskList.remove(at: 0);
}
if(self._bgTaskList.count > 0) {
log(message: "Background Task Still Active \(self._bgTaskList[0])");
}
if(all) {
log(message: "Killing Master Task \(self._masterTaskId)");
app.endBackgroundTask(self._masterTaskId);
self._masterTaskId = UIBackgroundTaskInvalid;
} else {
log(message: "Kept Master Task ID \(self._masterTaskId)");
}
}
}
}
class NotificationManager : NSObject {
static var manager = NotificationManager();
func notify(text: String) {
if(debug == true) {
log(message: "Sending Notification");
let notification = UILocalNotification();
notification.timeZone = TimeZone.current;
notification.soundName = UILocalNotificationDefaultSoundName;
notification.alertBody = text;
UIApplication.shared.scheduleLocalNotification(notification);
}
}
}
| apache-2.0 | d77a743e2a491937bd2a3fe8efb1b605 | 33.195021 | 217 | 0.624439 | 5.145265 | false | false | false | false |
optimizely/objective-c-sdk | Pods/Mixpanel-swift/Mixpanel/Persistence.swift | 1 | 19747 | //
// Persistence.swift
// Mixpanel
//
// Created by Yarden Eitan on 6/2/16.
// Copyright © 2016 Mixpanel. All rights reserved.
//
import Foundation
struct ArchivedProperties {
let superProperties: InternalProperties
let timedEvents: InternalProperties
let distinctId: String
let anonymousId: String?
let userId: String?
let alias: String?
let hadPersistedDistinctId: Bool?
let peopleDistinctId: String?
let peopleUnidentifiedQueue: Queue
#if DECIDE
let shownNotifications: Set<Int>
let automaticEventsEnabled: Bool?
#endif // DECIDE
}
class Persistence {
private static let archiveQueue: DispatchQueue = DispatchQueue(label: "com.mixpanel.archiveQueue", qos: .utility)
enum ArchiveType: String {
case events
case people
case groups
case properties
case codelessBindings
case variants
case optOutStatus
}
static func filePathWithType(_ type: ArchiveType, token: String) -> String? {
return filePathFor(type.rawValue, token: token)
}
static private func filePathFor(_ archiveType: String, token: String) -> String? {
let filename = "mixpanel-\(token)-\(archiveType)"
let manager = FileManager.default
#if os(iOS)
let url = manager.urls(for: .libraryDirectory, in: .userDomainMask).last
#else
let url = manager.urls(for: .cachesDirectory, in: .userDomainMask).last
#endif // os(iOS)
guard let urlUnwrapped = url?.appendingPathComponent(filename).path else {
return nil
}
return urlUnwrapped
}
#if DECIDE
static func archive(eventsQueue: Queue,
peopleQueue: Queue,
groupsQueue: Queue,
properties: ArchivedProperties,
codelessBindings: Set<CodelessBinding>,
variants: Set<Variant>,
token: String) {
archiveEvents(eventsQueue, token: token)
archivePeople(peopleQueue, token: token)
archiveGroups(groupsQueue, token: token)
archiveProperties(properties, token: token)
archiveVariants(variants, token: token)
archiveCodelessBindings(codelessBindings, token: token)
}
#else
static func archive(eventsQueue: Queue,
peopleQueue: Queue,
groupsQueue: Queue,
properties: ArchivedProperties,
token: String) {
archiveEvents(eventsQueue, token: token)
archivePeople(peopleQueue, token: token)
archiveGroups(groupsQueue, token: token)
archiveProperties(properties, token: token)
}
#endif // DECIDE
static func archiveEvents(_ eventsQueue: Queue, token: String) {
archiveQueue.sync { [eventsQueue, token] in
archiveToFile(.events, object: eventsQueue, token: token)
}
}
static func archivePeople(_ peopleQueue: Queue, token: String) {
archiveQueue.sync { [peopleQueue, token] in
archiveToFile(.people, object: peopleQueue, token: token)
}
}
static func archiveGroups(_ groupsQueue: Queue, token: String) {
archiveQueue.sync { [groupsQueue, token] in
archiveToFile(.groups, object: groupsQueue, token: token)
}
}
static func archiveOptOutStatus(_ optOutStatus: Bool, token: String) {
archiveQueue.sync { [optOutStatus, token] in
archiveToFile(.optOutStatus, object: optOutStatus, token: token)
}
}
static func archiveProperties(_ properties: ArchivedProperties, token: String) {
archiveQueue.sync { [properties, token] in
var p = InternalProperties()
p["distinctId"] = properties.distinctId
p["anonymousId"] = properties.anonymousId
p["userId"] = properties.userId
p["alias"] = properties.alias
p["hadPersistedDistinctId"] = properties.hadPersistedDistinctId
p["superProperties"] = properties.superProperties
p["peopleDistinctId"] = properties.peopleDistinctId
p["peopleUnidentifiedQueue"] = properties.peopleUnidentifiedQueue
p["timedEvents"] = properties.timedEvents
#if DECIDE
p["shownNotifications"] = properties.shownNotifications
p["automaticEvents"] = properties.automaticEventsEnabled
#endif // DECIDE
archiveToFile(.properties, object: p, token: token)
}
}
#if DECIDE
static func archiveVariants(_ variants: Set<Variant>, token: String) {
archiveQueue.sync { [variants, token] in
archiveToFile(.variants, object: variants, token: token)
}
}
static func archiveCodelessBindings(_ codelessBindings: Set<CodelessBinding>, token: String) {
archiveQueue.sync { [codelessBindings, token] in
archiveToFile(.codelessBindings, object: codelessBindings, token: token)
}
}
#endif // DECIDE
static private func archiveToFile(_ type: ArchiveType, object: Any, token: String) {
var archiveObject = object
if var queue = archiveObject as? Queue {
if queue.count > QueueConstants.queueSize {
queue.removeSubrange(0..<(queue.count - QueueConstants.queueSize))
archiveObject = queue
}
}
let filePath = filePathWithType(type, token: token)
guard let path = filePath else {
Logger.error(message: "bad file path, cant fetch file")
return
}
ExceptionWrapper.try({ [cObject = archiveObject, cPath = path, cType = type] in
if !NSKeyedArchiver.archiveRootObject(cObject, toFile: cPath) {
Logger.error(message: "failed to archive \(cType.rawValue)")
return
}
}, catch: { [cType = type] (error) in
Logger.error(message: "failed to archive \(cType.rawValue) due to an uncaught exception")
return
}, finally: {})
addSkipBackupAttributeToItem(at: path)
}
static private func addSkipBackupAttributeToItem(at path: String) {
var url = URL.init(fileURLWithPath: path)
var resourceValues = URLResourceValues()
resourceValues.isExcludedFromBackup = true
do {
try url.setResourceValues(resourceValues)
} catch {
Logger.info(message: "Error excluding \(path) from backup.")
}
}
#if DECIDE
static func unarchive(token: String) -> (eventsQueue: Queue,
peopleQueue: Queue,
groupsQueue: Queue,
superProperties: InternalProperties,
timedEvents: InternalProperties,
distinctId: String,
anonymousId: String?,
userId: String?,
alias: String?,
hadPersistedDistinctId: Bool?,
peopleDistinctId: String?,
peopleUnidentifiedQueue: Queue,
shownNotifications: Set<Int>,
codelessBindings: Set<CodelessBinding>,
variants: Set<Variant>,
optOutStatus: Bool?,
automaticEventsEnabled: Bool?) {
let eventsQueue = unarchiveEvents(token: token)
let peopleQueue = unarchivePeople(token: token)
let groupsQueue = unarchiveGroups(token: token)
let codelessBindings = unarchiveCodelessBindings(token: token)
let variants = unarchiveVariants(token: token)
let optOutStatus = unarchiveOptOutStatus(token: token)
let (superProperties,
timedEvents,
distinctId,
anonymousId,
userId,
alias,
hadPersistedDistinctId,
peopleDistinctId,
peopleUnidentifiedQueue,
shownNotifications,
automaticEventsEnabled) = unarchiveProperties(token: token)
return (eventsQueue,
peopleQueue,
groupsQueue,
superProperties,
timedEvents,
distinctId,
anonymousId,
userId,
alias,
hadPersistedDistinctId,
peopleDistinctId,
peopleUnidentifiedQueue,
shownNotifications,
codelessBindings,
variants,
optOutStatus,
automaticEventsEnabled)
}
#else
static func unarchive(token: String) -> (eventsQueue: Queue,
peopleQueue: Queue,
groupsQueue: Queue,
superProperties: InternalProperties,
timedEvents: InternalProperties,
distinctId: String,
anonymousId: String?,
userId: String?,
alias: String?,
hadPersistedDistinctId: Bool?,
peopleDistinctId: String?,
peopleUnidentifiedQueue: Queue) {
let eventsQueue = unarchiveEvents(token: token)
let peopleQueue = unarchivePeople(token: token)
let groupsQueue = unarchiveGroups(token: token)
let (superProperties,
timedEvents,
distinctId,
anonymousId,
userId,
alias,
hadPersistedDistinctId,
peopleDistinctId,
peopleUnidentifiedQueue,
_) = unarchiveProperties(token: token)
return (eventsQueue,
peopleQueue,
groupsQueue,
superProperties,
timedEvents,
distinctId,
anonymousId,
userId,
alias,
hadPersistedDistinctId,
peopleDistinctId,
peopleUnidentifiedQueue)
}
#endif // DECIDE
static private func unarchiveWithFilePath(_ filePath: String) -> Any? {
var unarchivedData: Any? = nil
ExceptionWrapper.try({ [filePath] in
unarchivedData = NSKeyedUnarchiver.unarchiveObject(withFile: filePath)
if unarchivedData == nil {
Logger.info(message: "Unable to read file at path: \(filePath)")
removeArchivedFile(atPath: filePath)
}
}, catch: { [filePath] (error) in
removeArchivedFile(atPath: filePath)
Logger.info(message: "Unable to read file at path: \(filePath), error: \(String(describing: error))")
}, finally: {})
return unarchivedData
}
static private func removeArchivedFile(atPath filePath: String) {
do {
try FileManager.default.removeItem(atPath: filePath)
} catch let err {
Logger.info(message: "Unable to remove file at path: \(filePath), error: \(err)")
}
}
static private func unarchiveEvents(token: String) -> Queue {
let data = unarchiveWithType(.events, token: token)
return data as? Queue ?? []
}
static private func unarchivePeople(token: String) -> Queue {
let data = unarchiveWithType(.people, token: token)
return data as? Queue ?? []
}
static private func unarchiveGroups(token: String) -> Queue {
let data = unarchiveWithType(.groups, token: token)
return data as? Queue ?? []
}
static private func unarchiveOptOutStatus(token: String) -> Bool? {
return unarchiveWithType(.optOutStatus, token: token) as? Bool
}
#if DECIDE
static private func unarchiveProperties(token: String) -> (InternalProperties,
InternalProperties,
String,
String?,
String?,
String?,
Bool?,
String?,
Queue,
Set<Int>,
Bool?) {
let properties = unarchiveWithType(.properties, token: token) as? InternalProperties
let (superProperties,
timedEvents,
distinctId,
anonymousId,
userId,
alias,
hadPersistedDistinctId,
peopleDistinctId,
peopleUnidentifiedQueue,
automaticEventsEnabled) = unarchivePropertiesHelper(token: token)
let shownNotifications =
properties?["shownNotifications"] as? Set<Int> ?? Set<Int>()
return (superProperties,
timedEvents,
distinctId,
anonymousId,
userId,
alias,
hadPersistedDistinctId,
peopleDistinctId,
peopleUnidentifiedQueue,
shownNotifications,
automaticEventsEnabled)
}
#else
static private func unarchiveProperties(token: String) -> (InternalProperties,
InternalProperties,
String,
String?,
String?,
String?,
Bool?,
String?,
Queue,
Bool?) {
return unarchivePropertiesHelper(token: token)
}
#endif // DECIDE
static private func unarchivePropertiesHelper(token: String) -> (InternalProperties,
InternalProperties,
String,
String?,
String?,
String?,
Bool?,
String?,
Queue,
Bool?) {
let properties = unarchiveWithType(.properties, token: token) as? InternalProperties
let superProperties =
properties?["superProperties"] as? InternalProperties ?? InternalProperties()
let timedEvents =
properties?["timedEvents"] as? InternalProperties ?? InternalProperties()
var distinctId =
properties?["distinctId"] as? String ?? ""
var anonymousId =
properties?["anonymousId"] as? String ?? nil
var userId =
properties?["userId"] as? String ?? nil
var alias =
properties?["alias"] as? String ?? nil
var hadPersistedDistinctId =
properties?["hadPersistedDistinctId"] as? Bool ?? nil
var peopleDistinctId =
properties?["peopleDistinctId"] as? String ?? nil
let peopleUnidentifiedQueue =
properties?["peopleUnidentifiedQueue"] as? Queue ?? Queue()
let automaticEventsEnabled =
properties?["automaticEvents"] as? Bool ?? nil
if properties == nil {
(distinctId, peopleDistinctId, anonymousId, userId, alias, hadPersistedDistinctId) = restoreIdentity(token: token)
}
return (superProperties,
timedEvents,
distinctId,
anonymousId,
userId,
alias,
hadPersistedDistinctId,
peopleDistinctId,
peopleUnidentifiedQueue,
automaticEventsEnabled)
}
#if DECIDE
static private func unarchiveCodelessBindings(token: String) -> Set<CodelessBinding> {
let data = unarchiveWithType(.codelessBindings, token: token)
return data as? Set<CodelessBinding> ?? Set()
}
static private func unarchiveVariants(token: String) -> Set<Variant> {
let data = unarchiveWithType(.variants, token: token) as? Set<Variant>
return data ?? Set()
}
#endif // DECIDE
static private func unarchiveWithType(_ type: ArchiveType, token: String) -> Any? {
let filePath = filePathWithType(type, token: token)
guard let path = filePath else {
Logger.info(message: "bad file path, cant fetch file")
return nil
}
guard let unarchivedData = unarchiveWithFilePath(path) else {
Logger.info(message: "can't unarchive file")
return nil
}
if var queue = unarchivedData as? Queue {
if queue.count > QueueConstants.queueSize {
queue.removeSubrange(0..<(queue.count - QueueConstants.queueSize))
return queue
}
}
return unarchivedData
}
static func storeIdentity(token: String, distinctID: String, peopleDistinctID: String?, anonymousID: String?, userID: String?, alias: String?, hadPersistedDistinctId: Bool?) {
guard let defaults = UserDefaults(suiteName: "Mixpanel") else {
return
}
let prefix = "mixpanel-\(token)-"
defaults.set(distinctID, forKey: prefix + "MPDistinctID")
defaults.set(peopleDistinctID, forKey: prefix + "MPPeopleDistinctID")
defaults.set(anonymousID, forKey: prefix + "MPAnonymousId")
defaults.set(userID, forKey: prefix + "MPUserId")
defaults.set(alias, forKey: prefix + "MPAlias")
defaults.set(hadPersistedDistinctId, forKey: prefix + "MPHadPersistedDistinctId")
defaults.synchronize()
}
static func restoreIdentity(token: String) -> (String, String?, String?, String?, String?, Bool?) {
guard let defaults = UserDefaults(suiteName: "Mixpanel") else {
return ("", nil, nil, nil, nil, nil)
}
let prefix = "mixpanel-\(token)-"
return (defaults.string(forKey: prefix + "MPDistinctID") ?? "",
defaults.string(forKey: prefix + "MPPeopleDistinctID"),
defaults.string(forKey: prefix + "MPAnonymousId"),
defaults.string(forKey: prefix + "MPUserId"),
defaults.string(forKey: prefix + "MPAlias"),
defaults.bool(forKey: prefix + "MPHadPersistedDistinctId"))
}
static func deleteMPUserDefaultsData(token: String) {
guard let defaults = UserDefaults(suiteName: "Mixpanel") else {
return
}
let prefix = "mixpanel-\(token)-"
defaults.removeObject(forKey: prefix + "MPDistinctID")
defaults.removeObject(forKey: prefix + "MPPeopleDistinctID")
defaults.removeObject(forKey: prefix + "MPAnonymousId")
defaults.removeObject(forKey: prefix + "MPUserId")
defaults.removeObject(forKey: prefix + "MPAlias")
defaults.removeObject(forKey: prefix + "MPHadPersistedDistinctId")
defaults.synchronize()
}
}
| apache-2.0 | 1cb23939e8495a2ffea226b6a3bc3a9d | 38.334661 | 179 | 0.545427 | 6.038532 | false | false | false | false |
ZeeQL/ZeeQL3 | Sources/ZeeQL/Access/SQLAttributeChange.swift | 1 | 728 | //
// SQLAttributeChange.swift
// ZeeQL3
//
// Created by Helge Hess on 10/06/17.
// Copyright © 2017 ZeeZide GmbH. All rights reserved.
//
struct SQLAttributeChange : SmartDescription {
var name : ( String, String )?
var nullability : Bool?
var externalType : String?
var hasChanges : Bool {
if name != nil { return true }
if nullability != nil { return true }
if externalType != nil { return true }
return false
}
func appendToDescription(_ ms: inout String) {
if let (old,new) = name { ms += " rename[\(old)=>\(new)]" }
if let v = nullability { ms += (v ? " null" : " not-null") }
if let v = externalType { ms += " type=\(v)" }
}
}
| apache-2.0 | 6be87083ef41e8cd18f639c6f0f24600 | 25.925926 | 65 | 0.570839 | 3.616915 | false | false | false | false |
Urinx/SublimeCode | Sublime/Pods/Swifter/Sources/HttpRouter.swift | 2 | 4241 | //
// HttpRouter.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
import Foundation
public class HttpRouter {
private class Node {
var nodes = [String: Node]()
var handler: (HttpRequest -> HttpResponse)? = nil
}
private var rootNode = Node()
public func routes() -> [String] {
var routes = [String]()
for (_, child) in rootNode.nodes {
routes.appendContentsOf(routesForNode(child));
}
return routes
}
private func routesForNode(node: Node, prefix: String = "") -> [String] {
var result = [String]()
if let _ = node.handler {
result.append(prefix)
}
for (key, child) in node.nodes {
result.appendContentsOf(routesForNode(child, prefix: prefix + "/" + key));
}
return result
}
public func register(method: String?, path: String, handler: (HttpRequest -> HttpResponse)?) {
var pathSegments = stripQuery(path).split("/")
if let method = method {
pathSegments.insert(method, atIndex: 0)
} else {
pathSegments.insert("*", atIndex: 0)
}
var pathSegmentsGenerator = pathSegments.generate()
inflate(&rootNode, generator: &pathSegmentsGenerator).handler = handler
}
public func route(method: String?, path: String) -> ([String: String], HttpRequest -> HttpResponse)? {
if let method = method {
let pathSegments = (method + "/" + stripQuery(path)).split("/")
var pathSegmentsGenerator = pathSegments.generate()
var params = [String:String]()
if let handler = findHandler(&rootNode, params: ¶ms, generator: &pathSegmentsGenerator) {
return (params, handler)
}
}
let pathSegments = ("*/" + stripQuery(path)).split("/")
var pathSegmentsGenerator = pathSegments.generate()
var params = [String:String]()
if let handler = findHandler(&rootNode, params: ¶ms, generator: &pathSegmentsGenerator) {
return (params, handler)
}
return nil
}
private func inflate(inout node: Node, inout generator: IndexingGenerator<[String]>) -> Node {
if let pathSegment = generator.next() {
if let _ = node.nodes[pathSegment] {
return inflate(&node.nodes[pathSegment]!, generator: &generator)
}
var nextNode = Node()
node.nodes[pathSegment] = nextNode
return inflate(&nextNode, generator: &generator)
}
return node
}
private func findHandler(inout node: Node, inout params: [String: String], inout generator: IndexingGenerator<[String]>) -> (HttpRequest -> HttpResponse)? {
guard let pathToken = generator.next() else {
return node.handler
}
let variableNodes = node.nodes.filter { $0.0.characters.first == ":" }
if let variableNode = variableNodes.first {
if variableNode.1.nodes.count == 0 {
// if it's the last element of the pattern and it's a variable, stop the search and
// append a tail as a value for the variable.
let tail = generator.joinWithSeparator("/")
if tail.utf8.count > 0 {
params[variableNode.0] = pathToken + "/" + tail
} else {
params[variableNode.0] = pathToken
}
return variableNode.1.handler
}
params[variableNode.0] = pathToken
return findHandler(&node.nodes[variableNode.0]!, params: ¶ms, generator: &generator)
}
if let _ = node.nodes[pathToken] {
return findHandler(&node.nodes[pathToken]!, params: ¶ms, generator: &generator)
}
if let _ = node.nodes["*"] {
return findHandler(&node.nodes["*"]!, params: ¶ms, generator: &generator)
}
return nil
}
private func stripQuery(path: String) -> String {
if let path = path.split("?").first {
return path
}
return path
}
}
| gpl-3.0 | ea595b16752dbca7f43f84b12e514b16 | 36.192982 | 160 | 0.565802 | 4.674752 | false | false | false | false |
blomma/gameoflife | gameoflife/Cell.swift | 1 | 434 | enum CellState {
case alive, dead
}
class Cell {
let x: Int
let y: Int
var state: CellState
var neighbours: [Cell] = [Cell]()
init(state: CellState, x: Int, y: Int) {
self.state = state
self.x = x
self.y = y
}
}
extension Cell: Hashable {
var hashValue: Int {
return x.hashValue ^ y.hashValue
}
static func ==(lhs: Cell, rhs: Cell) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
}
| mit | 2ba5ccfa4a95b287711b092a615598f9 | 14.5 | 50 | 0.578341 | 2.893333 | false | false | false | false |
uasys/swift | test/SILGen/inherited_protocol_conformance_multi_file_2.swift | 4 | 6263 | // -- Try all the permutations of file order possible.
// Abc
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -primary-file %s %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -module-name main | %FileCheck %s --check-prefix=FILE_A
// aBc
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -module-name main | %FileCheck %s --check-prefix=FILE_B
// abC
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -module-name main | %FileCheck %s --check-prefix=FILE_C
// Bac
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift %s %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -module-name main | %FileCheck %s --check-prefix=FILE_B
// bAc
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -primary-file %s %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -module-name main | %FileCheck %s --check-prefix=FILE_A
// baC
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift %s -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -module-name main | %FileCheck %s --check-prefix=FILE_C
// OS X 10.9
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift %s %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -module-name main | %FileCheck %s --check-prefix=FILE_C
// cAb
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -primary-file %s %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -module-name main | %FileCheck %s --check-prefix=FILE_A
// caB
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift %s -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -module-name main | %FileCheck %s --check-prefix=FILE_B
// Acb
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -primary-file %s %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -module-name main | %FileCheck %s --check-prefix=FILE_A
// aCb
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -module-name main | %FileCheck %s --check-prefix=FILE_C
// abC
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -module-name main | %FileCheck %s --check-prefix=FILE_B
// Bca
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift %s -module-name main | %FileCheck %s --check-prefix=FILE_B
// bCa
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift %s -module-name main | %FileCheck %s --check-prefix=FILE_C
// bcA
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -primary-file %s -module-name main | %FileCheck %s --check-prefix=FILE_A
// Cba
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift %s -module-name main | %FileCheck %s --check-prefix=FILE_C
// cBa
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift -primary-file %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift %s -module-name main | %FileCheck %s --check-prefix=FILE_B
// cbA
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %S/Inputs/inherited_protocol_conformance_other_file_2_c.swift %S/Inputs/inherited_protocol_conformance_other_file_2_b.swift -primary-file %s -module-name main | %FileCheck %s --check-prefix=FILE_A
// FILE_A-NOT: sil [transparent] [thunk] @_T04main5ThingVs9EquatableAAsADP2eeoi{{[_0-9a-zA-Z]*}}FZTW
// FILE_A-NOT: sil [transparent] [thunk] @_T04main5ThingVs8HashableAAsADP9hashValueSivgTW
// FILE_A-NOT: sil_witness_table Thing: Hashable module main
// FILE_A-NOT: sil_witness_table Thing: Equatable module main
// FILE_B-NOT: sil [transparent] [thunk] @_T04main5ThingVs9EquatableAAsADP2eeoi{{[_0-9a-zA-Z]*}}FZTW
// FILE_B: sil private [transparent] [thunk] @_T04main5ThingVs8HashableAAsADP9hashValueSivgTW
// FILE_B-NOT: sil [transparent] [thunk] @_T04main5ThingVs9EquatableAAsADP2eeoi{{[_0-9a-zA-Z]*}}FZTW
// FILE_B-NOT: sil_witness_table hidden Thing: Equatable module main
// FILE_B: sil_witness_table hidden Thing: Hashable module main
// FILE_B-NOT: sil_witness_table hidden Thing: Equatable module main
// FILE_C-NOT: sil [transparent] [thunk] @_T04main5ThingVs8HashableAAsADP9hashValueSivgTW
// FILE_C: sil private [transparent] [thunk] @_T04main5ThingVs9EquatableAAsADP2eeoi{{[_0-9a-zA-Z]*}}FZTW
// FILE_C-NOT: sil [transparent] [thunk] @_T04main5ThingVs8HashableAAsADP9hashValueSivgTW
// FILE_C-NOT: sil_witness_table hidden Thing: Hashable module main
// FILE_C: sil_witness_table hidden Thing: Equatable module main
// FILE_C-NOT: sil_witness_table hidden Thing: Hashable module main
struct Thing { var value: Int }
| apache-2.0 | ab0df87f9ad8b4d06830aba97f19bbd7 | 93.893939 | 262 | 0.764011 | 3.044725 | false | false | false | false |
pkrawat1/TravelApp-ios | TravelApp/Model/SharedData.swift | 1 | 1101 | //
// SharedControl.swift
// TravelApp
//
// Created by rawat on 22/01/17.
// Copyright © 2017 Pankaj Rawat. All rights reserved.
//
import UIKit
class SharedData: NSObject {
// var API_URL: String = "http://localhost:3000"
// var API_URL: String = "https://travel-api-aviabird.herokuapp.com"
var API_URL: String = "https://yatrum-api.herokuapp.com"
var token: String = ""
static let sharedInstance = SharedData()
var currentUser: User!
var homeController: HomeController!
func getToken() -> String {
if token == "" {
let data = UserDefaults.standard.object(forKey: "Token") as? String
if (data != nil) {
self.token = data!
}
}
return self.token
}
func setToken() {
UserDefaults.standard.set(self.token, forKey: "Token")
}
func clearAll() {
token = ""
currentUser = nil
UserDefaults.standard.removeObject(forKey: "Token")
}
func SetCurrentUser(user: User) {
currentUser = user
}
}
| mit | e01d41f78c717d45447cb6bbe0135b5f | 22.913043 | 79 | 0.569091 | 3.971119 | false | false | false | false |
wrutkowski/Lucid-Weather-Clock | Pods/Charts/Charts/Classes/Data/Implementations/Standard/ChartDataEntry.swift | 6 | 2484 | //
// ChartDataEntry.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
open class ChartDataEntry: NSObject
{
/// the actual value (y axis)
open var value = Double(0.0)
/// the index on the x-axis
open var xIndex = Int(0)
/// optional spot for additional data this Entry represents
open var data: AnyObject?
public override required init()
{
super.init()
}
public init(value: Double, xIndex: Int)
{
super.init()
self.value = value
self.xIndex = xIndex
}
public init(value: Double, xIndex: Int, data: Any?)
{
super.init()
self.value = value
self.xIndex = xIndex
self.data = data as AnyObject
}
// MARK: NSObject
open override func isEqual(_ object: Any?) -> Bool
{
if (object == nil)
{
return false
}
let object = object as AnyObject
if (!object.isKind(of: type(of: self)))
{
return false
}
if let d = object as? ChartDataEntry, d.data !== self.data || !d.isEqual(self.data)
{
return false
}
if (object.xIndex != xIndex)
{
return false
}
if (fabs(object.value - value) > 0.00001)
{
return false
}
return true
}
// MARK: NSObject
open override var description: String
{
return "ChartDataEntry, xIndex: \(xIndex), value \(value)"
}
// MARK: NSCopying
open func copyWithZone(_ zone: NSZone?) -> Any
{
let copy = type(of: self).init()
copy.value = value
copy.xIndex = xIndex
copy.data = data
return copy
}
}
public func ==(lhs: ChartDataEntry, rhs: ChartDataEntry) -> Bool
{
if (lhs === rhs)
{
return true
}
if (!lhs.isKind(of: type(of: rhs)))
{
return false
}
if (lhs.data !== rhs.data && !lhs.data!.isEqual(rhs.data))
{
return false
}
if (lhs.xIndex != rhs.xIndex)
{
return false
}
if (fabs(lhs.value - rhs.value) > 0.00001)
{
return false
}
return true
}
| mit | 4ef011f622db737d690c841825808c17 | 17.676692 | 85 | 0.519324 | 4.126246 | false | false | false | false |
apple/swift-corelibs-foundation | Sources/FoundationNetworking/URLSession/WebSocket/WebSocketURLProtocol.swift | 1 | 7795 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import SwiftFoundation
#else
import Foundation
#endif
@_implementationOnly import CoreFoundation
@_implementationOnly import CFURLSessionInterface
import Dispatch
internal class _WebSocketURLProtocol: _HTTPURLProtocol {
public required init(task: URLSessionTask, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) {
super.init(task: task, cachedResponse: nil, client: client)
}
public required init(request: URLRequest, cachedResponse: CachedURLResponse?, client: URLProtocolClient?) {
super.init(request: request, cachedResponse: nil, client: client)
}
override class func canInit(with request: URLRequest) -> Bool {
switch request.url?.scheme {
case "ws", "wss": return true
default: return false
}
}
override func canCache(_ response: CachedURLResponse) -> Bool {
false
}
override func canRespondFromCache(using response: CachedURLResponse) -> Bool { false }
override func didReceiveResponse() {
guard let webSocketTask = task as? URLSessionWebSocketTask else { return }
guard case .transferInProgress(let ts) = self.internalState else { fatalError("Transfer not in progress.") }
guard let response = ts.response as? HTTPURLResponse else { fatalError("Header complete, but not URL response.") }
webSocketTask.protocolPicked = response.value(forHTTPHeaderField: "Sec-WebSocket-Protocol")
easyHandle.timeoutTimer = nil
webSocketTask.handshakeCompleted = true
self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
}
/// Set options on the easy handle to match the given request.
///
/// This performs a series of `curl_easy_setopt()` calls.
override func configureEasyHandle(for request: URLRequest, body: _Body) {
guard request.httpMethod == "GET" else {
NSLog("WebSocket tasks must use GET")
let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorUnsupportedURL,
userInfo: [
NSLocalizedDescriptionKey: "websocket task must use GET httpMethod",
NSURLErrorFailingURLStringErrorKey: request.url?.description ?? ""
])
internalState = .transferFailed
transferCompleted(withError: error)
return
}
super.configureEasyHandle(for: request, body: body)
easyHandle.setAllowedProtocolsToAll()
guard let webSocketTask = task as? URLSessionWebSocketTask else { return }
easyHandle.set(preferredReceiveBufferSize: webSocketTask.maximumMessageSize)
}
override func completionAction(forCompletedRequest request: URLRequest, response: URLResponse) -> _CompletionAction {
// Redirect:
guard let httpURLResponse = response as? HTTPURLResponse else {
fatalError("Response was not HTTPURLResponse")
}
if let request = redirectRequest(for: httpURLResponse, fromRequest: request) {
return .redirectWithRequest(request)
}
return .completeTask
}
func sendWebSocketData(_ data: Data, flags: _EasyHandle.WebSocketFlags) throws {
try easyHandle.sendWebSocketsData(data, flags: flags)
}
override func didReceive(data: Data) -> _EasyHandle._Action {
guard case .transferInProgress(var ts) = internalState else {
fatalError("Received web socket data, but no transfer in progress.")
}
if let response = validateHeaderComplete(transferState:ts) {
ts.response = response
}
// Note this excludes code 300 which should return the response of the redirect and not follow it.
// For other redirect codes dont notify the delegate of the data received in the redirect response.
if let httpResponse = ts.response as? HTTPURLResponse,
301...308 ~= httpResponse.statusCode {
// Save the response body in case the delegate does not perform a redirect and the 3xx response
// including its body needs to be returned to the client.
var redirectBody = lastRedirectBody ?? Data()
redirectBody.append(data)
lastRedirectBody = redirectBody
}
let flags = easyHandle.getWebSocketFlags()
notifyTask(aboutReceivedData: data, flags: flags)
internalState = .transferInProgress(ts)
return .proceed
}
fileprivate func notifyTask(aboutReceivedData data: Data, flags: _EasyHandle.WebSocketFlags) {
guard let t = self.task else {
fatalError("Cannot notify")
}
guard case .taskDelegate = t.session.behaviour(for: self.task!),
let task = self.task as? URLSessionWebSocketTask else {
fatalError("WebSocket internal invariant violated")
}
// Buffer the response message in the task
if flags.contains(.close) {
let closeCode: URLSessionWebSocketTask.CloseCode
let reasonData: Data
if data.count >= 2 {
closeCode = data.withUnsafeBytes {
let codeInt = UInt16(bigEndian: $0.load(as: UInt16.self))
return URLSessionWebSocketTask.CloseCode(rawValue: Int(codeInt)) ?? .unsupportedData
}
reasonData = Data(data[2...])
} else {
closeCode = .normalClosure
reasonData = Data()
}
task.close(code: closeCode, reason: reasonData)
} else if flags.contains(.pong) {
task.noteReceivedPong()
} else if flags.contains(.binary) {
let message = URLSessionWebSocketTask.Message.data(data)
task.appendReceivedMessage(message)
} else if flags.contains(.text) {
guard let utf8 = String(data: data, encoding: .utf8) else {
NSLog("Invalid utf8 message received from server \(data)")
let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorBadServerResponse,
userInfo: [
NSLocalizedDescriptionKey: "Invalid message received from server",
NSURLErrorFailingURLStringErrorKey: request.url?.description ?? ""
])
internalState = .transferFailed
transferCompleted(withError: error)
return
}
let message = URLSessionWebSocketTask.Message.string(utf8)
task.appendReceivedMessage(message)
} else {
NSLog("Unexpected message received from server \(data) \(flags)")
let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorBadServerResponse,
userInfo: [
NSLocalizedDescriptionKey: "Unexpected message received from server",
NSURLErrorFailingURLStringErrorKey: request.url?.description ?? ""
])
internalState = .transferFailed
transferCompleted(withError: error)
}
}
}
| apache-2.0 | 6190d4922bdd1123a6f4c0eae7707d0b | 43.289773 | 122 | 0.620269 | 5.481716 | false | false | false | false |
itssofluffy/NanoMessage | Tests/NanoMessageTests/SenderReceiverTests.swift | 1 | 4360 | /*
SenderReceiverTests.swift
Copyright (c) 2017 Stephen Whittle All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
import XCTest
import NanoMessage
class SenderReceiverTests: XCTestCase {
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 testSenderReceiver() {
var completed = false
do {
let node0 = try PushSocket()
let node1 = try PullSocket()
let node2 = try PairSocket()
let node3 = try RequestSocket()
let node4 = try ReplySocket()
let node5 = try PublisherSocket()
let node6 = try SubscriberSocket()
let node7 = try SurveyorSocket()
let node8 = try RespondentSocket()
let node9 = try BusSocket()
XCTAssertEqual(node0.receiver, false, "PushSocket() cannot be a receiver socket")
XCTAssertEqual(node0.sender, true, "PushSocket() must be a sender socket")
XCTAssertEqual(node1.receiver, true, "PullSocket() must be a receiver socket")
XCTAssertEqual(node1.sender, false, "PullSocket() cannot be a sender socket")
XCTAssertEqual(node2.receiver, true, "PairSocket() must be a receiver socket")
XCTAssertEqual(node2.sender, true, "PairSocket() must a sender socket")
XCTAssertEqual(node3.receiver, true, "RequestSocket() must be a receiver socket")
XCTAssertEqual(node3.sender, true, "RequestSocket() must a sender socket")
XCTAssertEqual(node4.receiver, true, "ReplySocket() must be a receiver socket")
XCTAssertEqual(node4.sender, true, "ReplySocket() must a sender socket")
XCTAssertEqual(node5.receiver, false, "PublisherSocket() cannot be a receiver socket")
XCTAssertEqual(node5.sender, true, "PublisherSocket() must be a sender socket")
XCTAssertEqual(node6.receiver, true, "SubscriberSocket() must be a receiver socket")
XCTAssertEqual(node6.sender, false, "SubscriberSocket() cannot be a sender socket")
XCTAssertEqual(node7.receiver, true, "SurveyorSocket() must be a receiver socket")
XCTAssertEqual(node7.sender, true, "SurveyorSocket() must a sender socket")
XCTAssertEqual(node8.receiver, true, "RespondentSocket() must be a receiver socket")
XCTAssertEqual(node8.sender, true, "RespondentSocket() must a sender socket")
XCTAssertEqual(node9.receiver, true, "BusSocket() must be a receiver socket")
XCTAssertEqual(node9.sender, true, "BusSocket() must a sender socket")
completed = true
} catch let error as NanoMessageError {
XCTAssert(false, "\(error)")
} catch {
XCTAssert(false, "an unexpected error '\(error)' has occured in the library libNanoMessage.")
}
XCTAssert(completed, "test not completed")
}
#if os(Linux)
static let allTests = [
("testSenderReceiver", testSenderReceiver)
]
#endif
}
| mit | 6e225544bb336bebabcca1b70283dc1c | 43.489796 | 111 | 0.674771 | 4.765027 | false | true | false | false |
etataurov/ImageLoaderSwift | ImageLoader/ImageLoader.swift | 1 | 10581 | //
// ImageLoader.swift
// ImageLoader
//
// Created by Hirohisa Kawasaki on 10/16/14.
// Copyright (c) 2014 Hirohisa Kawasaki. All rights reserved.
//
import Foundation
import UIKit
public protocol URLLiteralConvertible {
var URL: NSURL { get }
}
extension NSURL: URLLiteralConvertible {
public var URL: NSURL {
return self
}
}
extension String: URLLiteralConvertible {
public var URL: NSURL {
return NSURL(string: self)!
}
}
// MARK: Optimize image
extension CGBitmapInfo {
private var alphaInfo: CGImageAlphaInfo? {
let info = self & .AlphaInfoMask
return CGImageAlphaInfo(rawValue: info.rawValue)
}
}
extension UIImage {
private func inflated() -> UIImage {
let scale = UIScreen.mainScreen().scale
let width = CGImageGetWidth(CGImage)
let height = CGImageGetHeight(CGImage)
if !(width > 0 && height > 0) {
return self
}
let bitsPerComponent = CGImageGetBitsPerComponent(CGImage)
if (bitsPerComponent > 8) {
return self
}
var bitmapInfo = CGImageGetBitmapInfo(CGImage)
var alphaInfo = CGImageGetAlphaInfo(CGImage)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let colorSpaceModel = CGColorSpaceGetModel(colorSpace)
switch (colorSpaceModel.value) {
case kCGColorSpaceModelRGB.value:
// Reference: http://stackoverflow.com/questions/23723564/which-cgimagealphainfo-should-we-use
var info = CGImageAlphaInfo.PremultipliedFirst
switch alphaInfo {
case .None:
info = CGImageAlphaInfo.NoneSkipFirst
default:
break
}
bitmapInfo &= ~CGBitmapInfo.AlphaInfoMask
bitmapInfo |= CGBitmapInfo(info.rawValue)
default:
break
}
let context = CGBitmapContextCreate(
nil,
width,
height,
bitsPerComponent,
0,
colorSpace,
bitmapInfo
)
let frame = CGRect(x: 0, y: 0, width: Int(width), height: Int(height))
CGContextDrawImage(context, frame, CGImage)
let inflatedImageRef = CGBitmapContextCreateImage(context)
if let inflatedImage = UIImage(CGImage: inflatedImageRef, scale: scale, orientation: imageOrientation) {
return inflatedImage
}
return self
}
}
// MARK: Cache
/**
Cache for `ImageLoader` have to implement methods.
fetch image by cache before sending a request and set image into cache after receiving image data.
*/
public protocol ImageCache: NSObjectProtocol {
subscript (aKey: NSURL) -> UIImage? {
get
set
}
}
internal typealias CompletionHandler = (NSURL, UIImage?, NSError?) -> ()
internal class Block: NSObject {
let completionHandler: CompletionHandler
init(completionHandler: CompletionHandler) {
self.completionHandler = completionHandler
}
}
/**
Use to check state of loaders that manager has.
Ready: The manager have no loaders
Running: The manager has loaders, and they are running
Suspended: The manager has loaders, and their states are all suspended
*/
public enum State {
case Ready
case Running
case Suspended
}
/**
Responsible for creating and managing `Loader` objects and controlling of `NSURLSession` and `ImageCache`
*/
public class LoaderManager {
let session: NSURLSession
let cache: ImageCache
let delegate: SessionDataDelegate = SessionDataDelegate()
public var inflatesImage: Bool = true
// MARK: singleton instance
public class var sharedInstance: LoaderManager {
struct Singleton {
static let instance = LoaderManager()
}
return Singleton.instance
}
init(configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(),
cache: ImageCache = Diskcached()
) {
session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
self.cache = cache
}
// MARK: state
var state: State {
var status: State = .Ready
for loader: Loader in delegate.loaders.values {
switch loader.state {
case .Running:
status = .Running
case .Suspended:
if status == .Ready {
status = .Suspended
}
default:
break
}
}
return status
}
// MARK: loading
internal func load(URL: URLLiteralConvertible) -> Loader {
let URL = URL.URL
if let loader = delegate[URL] {
loader.resume()
return loader
}
let request = NSMutableURLRequest(URL: URL)
request.setValue("image/*", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request)
let loader = Loader(task: task, delegate: self)
delegate[URL] = loader
return loader
}
internal func suspend(URL: URLLiteralConvertible) -> Loader? {
let URL = URL.URL
if let loader = delegate[URL] {
loader.suspend()
return loader
}
return nil
}
internal func cancel(URL: URLLiteralConvertible, block: Block? = nil) -> Loader? {
let URL = URL.URL
if let loader = delegate[URL] {
if let block = block {
loader.remove(block)
}
if loader.blocks.count == 0 || block == nil {
loader.cancel()
delegate.remove(URL)
}
return loader
}
return nil
}
class SessionDataDelegate: NSObject, NSURLSessionDataDelegate {
private let _queue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
private var loaders: [NSURL: Loader] = [NSURL: Loader]()
subscript (URL: NSURL) -> Loader? {
get {
var loader : Loader?
dispatch_sync(_queue) {
loader = self.loaders[URL]
}
return loader
}
set {
dispatch_barrier_async(_queue) {
self.loaders[URL] = newValue!
}
}
}
private func remove(URL: NSURL) -> Loader? {
if let loader = self[URL] {
loaders.removeValueForKey(URL)
return loader
}
return nil
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
// TODO: status code 3xx
if let URL = dataTask.originalRequest.URL, let loader = self[URL] {
loader.receive(data)
}
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
completionHandler(.Allow)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
// TODO: status code 3xx
// loader completion, and store remove loader
if let URL = task.originalRequest.URL, let loader = self[URL] {
loader.complete(error)
remove(URL)
}
}
}
}
/**
Responsible for sending a request and receiving the response and calling blocks for the request.
*/
public class Loader {
let delegate: LoaderManager
let task: NSURLSessionDataTask
var receivedData: NSMutableData = NSMutableData()
let inflatesImage: Bool
internal var blocks: [Block] = []
init (task: NSURLSessionDataTask, delegate: LoaderManager) {
self.task = task
self.delegate = delegate
self.inflatesImage = delegate.inflatesImage
self.resume()
}
var state: NSURLSessionTaskState {
return task.state
}
public func completionHandler(completionHandler: (NSURL, UIImage?, NSError?) -> ()) -> Self {
let block = Block(completionHandler: completionHandler)
blocks.append(block)
return self
}
// MARK: task
public func suspend() {
task.suspend()
}
public func resume() {
task.resume()
}
public func cancel() {
task.cancel()
}
private func remove(block: Block) {
// needs to queue with sync
var newBlocks: [Block] = []
for b: Block in blocks {
if !b.isEqual(block) {
newBlocks.append(b)
}
}
blocks = newBlocks
}
private func receive(data: NSData) {
receivedData.appendData(data)
}
private func complete(error: NSError?) {
var image: UIImage?
if let URL = task.originalRequest.URL {
if error == nil {
image = UIImage(data: receivedData)
_toCache(URL, image: image)
}
for block: Block in blocks {
block.completionHandler(URL, image, error)
}
blocks = []
}
}
private func _toCache(URL: NSURL, image _image: UIImage?) {
var image = _image
if inflatesImage {
image = image?.inflated()
}
if let image = image {
delegate.cache[URL] = image
}
}
}
/**
Creates `Loader` object using the shared LoaderManager instance for the specified URL.
*/
public func load(URL: URLLiteralConvertible) -> Loader {
return LoaderManager.sharedInstance.load(URL)
}
/**
Suspends `Loader` object using the shared LoaderManager instance for the specified URL.
*/
public func suspend(URL: URLLiteralConvertible) -> Loader? {
return LoaderManager.sharedInstance.suspend(URL)
}
/**
Cancels `Loader` object using the shared LoaderManager instance for the specified URL.
*/
public func cancel(URL: URLLiteralConvertible) -> Loader? {
return LoaderManager.sharedInstance.cancel(URL)
}
/**
Fetches the image using the shared LoaderManager instance's `ImageCache` object for the specified URL.
*/
public func cache(URL: URLLiteralConvertible) -> UIImage? {
let URL = URL.URL
return LoaderManager.sharedInstance.cache[URL]
}
public var state: State {
return LoaderManager.sharedInstance.state
}
| mit | 28d906e2e9fe51a3f89da06bd9337f7e | 24.933824 | 186 | 0.596163 | 5.038571 | false | false | false | false |
blstream/StudyBox_iOS | StudyBox_iOS/DrawerViewController.swift | 1 | 11993 | //
// DrawerViewController.swift
// StudyBox_iOS
//
// Created by Damian Malarczyk on 06.03.2016.
// Copyright © 2016 BLStream. All rights reserved.
//
import UIKit
import MMDrawerController
struct DrawerNavigationChild {
let name: String
let viewControllerBlock:(() -> Void)?
let lazyLoadViewControllerBlock: (() -> UIViewController?)?
var isActive = false
private var _viewController: UIViewController? = nil
var viewController: UIViewController? {
mutating get {
if _viewController == nil {
_viewController = lazyLoadViewControllerBlock?()
}
return _viewController
}
set {
_viewController = newValue
}
}
init(name: String, viewController: UIViewController? = nil, lazyLoadViewControllerBlock: (() -> UIViewController?)? = nil,
viewControllerBlock:( () -> Void)? = nil) {
self.name = name
self.lazyLoadViewControllerBlock = lazyLoadViewControllerBlock
self.viewControllerBlock = viewControllerBlock
self.viewController = viewController
}
init(name: String, viewControllerBlock: (() -> Void)?) {
self.init(name: name, viewController: nil, lazyLoadViewControllerBlock: nil, viewControllerBlock: viewControllerBlock)
}
}
class DrawerViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var gravatarImageView: UIImageView!
static let DrawerCellId = "DrawerCellId"
var dataManager: DataManager = UIApplication.appDelegate().dataManager
private var drawerNavigationControllers = [DrawerNavigationChild]()
private static var initialControllerIndex = 0
private var currentControllerIndex = 0
var barStyle = UIStatusBarStyle.Default
private func lazyLoadViewController(withStoryboardId idStoryboard: String) -> UIViewController? {
if let board = self.storyboard {
let controller = board.instantiateViewControllerWithIdentifier(idStoryboard)
return controller
}
return nil
}
func setupDrawer() {
if drawerNavigationControllers.isEmpty {
drawerNavigationControllers.append(
DrawerNavigationChild(name: UIApplication.isUserLoggedIn ? "Moje talie" : "Wyszukaj talie", viewController: nil,
lazyLoadViewControllerBlock: {[weak self] in
return self?.lazyLoadViewController(withStoryboardId: Utils.UIIds.DecksViewControllerID)
})
)
drawerNavigationControllers.append(
DrawerNavigationChild(name: "Stwórz nową fiszkę", viewController: nil,
lazyLoadViewControllerBlock: {[weak self] in
guard UIApplication.isUserLoggedIn else {
return nil
}
let vc = self?.lazyLoadViewController(withStoryboardId: Utils.UIIds.EditFlashcardViewControllerID) as? UINavigationController
if let editVC = vc?.childViewControllers[0] as? EditFlashcardViewController {
editVC.mode = .Add
return vc
}
return nil
}) { [weak self] in
let alert = UIAlertController(title: "Uwaga", message: "Musisz być zalogowany", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Przejdź do logowania", style: .Default) { _ in
self?.selectMenuOptionAtIndex(4)
}
)
self?.presentViewController(alert, animated: true, completion: nil)
}
)
drawerNavigationControllers.append(
DrawerNavigationChild(name: "Odkryj losową talię", viewController: nil,
lazyLoadViewControllerBlock: {[weak self] in
return self?.lazyLoadViewController(withStoryboardId: Utils.UIIds.RandomDeckViewControllerID)
})
)
drawerNavigationControllers.append(
DrawerNavigationChild(name: "Statystyki", viewController: nil,
lazyLoadViewControllerBlock: { [weak self] in
return self?.lazyLoadViewController(withStoryboardId: Utils.UIIds.StatisticsViewControllerID)
})
)
if UIApplication.isUserLoggedIn {
drawerNavigationControllers.append(
DrawerNavigationChild(name: "Ustawienia", viewController: nil,
lazyLoadViewControllerBlock: {[weak self] in
return self?.lazyLoadViewController(withStoryboardId: Utils.UIIds.SettingsViewControllerID)
})
)
}
drawerNavigationControllers.append(
DrawerNavigationChild(name: UIApplication.isUserLoggedIn ? "Wyloguj" : "Zaloguj", viewController: nil) { [weak self] in
UIApplication.appDelegate().dataManager.logout()
if let storyboard = self?.storyboard {
UIApplication.sharedRootViewController = storyboard.instantiateViewControllerWithIdentifier(Utils.UIIds.LoginControllerID)
}
})
}
}
func initialCenterController() -> UIViewController? {
setupDrawer()
if !drawerNavigationControllers.isEmpty {
var index = 0
if DrawerViewController.initialControllerIndex < drawerNavigationControllers.count {
index = DrawerViewController.initialControllerIndex
}
drawerNavigationControllers[index].isActive = true
return drawerNavigationControllers[index].viewController
}
return nil
}
override func viewDidLoad() {
super.viewDidLoad()
setupDrawer()
gravatarImageView.layer.cornerRadius = gravatarImageView.bounds.width / 2
gravatarImageView.clipsToBounds = true
gravatarImageView.layer.borderColor = UIColor.sb_White().CGColor
gravatarImageView.layer.borderWidth = 3
tableView.backgroundColor = UIColor.sb_Graphite()
view.backgroundColor = UIColor.sb_Graphite()
if let email = self.dataManager.remoteDataManager.user?.email {
self.emailLabel.text = email
}
dataManager.gravatar {
if case .Success(let obj) = $0, let image = UIImage(data: obj) { //swiftlint:disable:this conditional_binding_cascade
self.gravatarImageView.image = image
} else {
self.gravatarImageView.hidden = true
self.emailLabel.hidden = true
}
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(DrawerViewController.DrawerCellId, forIndexPath: indexPath)
let drawerChild = drawerNavigationControllers[indexPath.row]
cell.textLabel?.text = drawerChild.name
if drawerChild.isActive {
cell.backgroundColor = UIColor.sb_Raspberry()
} else {
cell.backgroundColor = UIColor.sb_Graphite()
}
cell.textLabel?.textColor = UIColor.whiteColor()
cell.textLabel?.font = UIFont.sbFont(size: sbFontSizeMedium, bold: false)
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return drawerNavigationControllers.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
selectMenuOptionAtIndex(indexPath.row)
}
func selectMenuOptionAtIndex(index: Int) {
var navigationChild = drawerNavigationControllers[index]
navigationChild.isActive = true
drawerNavigationControllers[currentControllerIndex].isActive = false
if let controller = navigationChild.viewController {
// viewController getter is mutating, it's possible that it was instantiated for the first time so the value was changed
drawerNavigationControllers[index] = navigationChild
if let mmDrawer = UIApplication.sharedRootViewController as? MMDrawerController {
var sbController = controller as? StudyBoxViewController
if sbController == nil {
if let navigationController = controller as? UINavigationController {
sbController = navigationController.childViewControllers[0] as? StudyBoxViewController
}
}
//necessary condition check, to handle programmaticall change of center view controller
if mmDrawer.openSide != .None {
sbController?.isDrawerVisible = true
sbController?.setNeedsStatusBarAppearanceUpdate()
}
mmDrawer.setCenterViewController(controller, withCloseAnimation: true, completion: nil)
}
} else if let block = navigationChild.viewControllerBlock {
block()
} else {
navigationChild.isActive = false
drawerNavigationControllers[currentControllerIndex].isActive = true
return
}
currentControllerIndex = index
tableView.reloadData()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
barStyle = .Default
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return barStyle
}
func deactiveAllChildViewControllers() {
for (index, _) in drawerNavigationControllers.enumerate() {
drawerNavigationControllers[index].isActive = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
for (index, _) in drawerNavigationControllers.enumerate() {
let isActive = drawerNavigationControllers[index].isActive
var mainViewController: UIViewController?
if let navigationController = drawerNavigationControllers[index].viewController as? UINavigationController
where !navigationController.childViewControllers.isEmpty {
mainViewController = navigationController.childViewControllers[0]
} else {
mainViewController = drawerNavigationControllers[index].viewController
}
if let resourceDisposableVC = mainViewController as? DrawerResourceDisposable {
resourceDisposableVC.disposeResources(isActive)
}
if !isActive {
drawerNavigationControllers[index].viewController = nil
}
}
}
}
extension DrawerViewController {
class func sharedSbDrawerViewControllerChooseMenuOption(atIndex index: Int) {
if let sbDrawer = UIApplication.sharedRootViewController as? SBDrawerController,
drawer = sbDrawer.leftDrawerViewController as? DrawerViewController {
drawer.selectMenuOptionAtIndex(index)
}
}
}
| apache-2.0 | b9ef561898c88a3abfd19aff59fc91b1 | 41.197183 | 149 | 0.618658 | 5.918025 | false | false | false | false |
dche/GLMath | Sources/Mat.swift | 1 | 2506 | //
// GLMath - Mat.swift
//
// GLSLangSpec 8.6 Matrix Functions
//
// Copyright (c) 2017 The GLMath authors.
// Licensed under MIT License.
/// Multiply matrix `x` by matrix `y` component-wise, i.e., `result[i][j]` is
/// the scalar product of `x[i][j]` and `y[i][j]`.
///
/// - note:
/// To get linear algebraic matrix multiplication, use the multiply operator
/// `*`.
public func matrixCompMult<M: GenericMatrix>(_ x: M, _ y: M) -> M {
return x.zip(y) { $0 * $1 }
}
/// Treats the first parameter `c` as a column vector (matrix with one column)
/// and the second parameter `r` as a row vector (matrix with one row)
/// and does a linear algebraic matrix multiply `c * r`,
/// yielding a matrix whose number of rows is the number of components in `c`
/// and whose number of columns is the number of components in `r`.
public func outerProduct
<
C: FloatVector,
R: FloatVector,
M: GenericMatrix
>(_ c: C, _ r: R) -> M
where
// SWIFT BUG: Swift 4 thinks this constraint is redundant and does not
// enforce it.
C.Component == R.Component,
M.Component == C,
M.Dim == R.Dim
{
var m = [C]()
for i in 0 ..< R.dimension {
m.append(c * (r[i] as! C.Component))
}
return M(m)
}
/// Returns transpose matrix of `m`.
public func transpose(_ m: mat2) -> mat2 {
return m.transpose
}
/// Returns transpose matrix of `m`.
public func transpose(_ m: mat2x3) -> mat3x2 {
return m.transpose
}
/// Returns transpose matrix of `m`.
public func transpose(_ m: mat2x4) -> mat4x2 {
return m.transpose
}
/// Returns transpose matrix of `m`.
public func transpose(_ m: mat3x2) -> mat2x3 {
return m.transpose
}
/// Returns transpose matrix of `m`.
public func transpose(_ m: mat3) -> mat3 {
return m.transpose
}
/// Returns transpose matrix of `m`.
public func transpose(_ m: mat3x4) -> mat4x3 {
return m.transpose
}
/// Returns transpose matrix of `m`.
public func transpose(_ m: mat4x2) -> mat2x4 {
return m.transpose
}
/// Returns transpose matrix of `m`.
public func transpose(_ m: mat4x3) -> mat3x4 {
return m.transpose
}
/// Returns transpose matrix of `m`.
public func transpose(_ m: mat4) -> mat4 {
return m.transpose
}
/// Returns the determinant of `m`.
public func determinant<M: GenericSquareMatrix>(_ m: M) -> M.Component.Component {
return m.determinant
}
/// Returns a matrix that is the inverse of `m`.
public func inverse<M: GenericSquareMatrix>(_ m: M) -> M {
return m.inverse
}
| mit | d4d59247fbe794d99abc589069bfc7ef | 24.835052 | 82 | 0.64166 | 3.293035 | false | false | false | false |
nirmankarta/eddystone | tools/gatt-config/ios/Beaconfig/Beaconfig/BeaconInvestigation.swift | 2 | 15575 | // Copyright 2016 Google 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 Foundation
import CoreBluetooth
let kBroadCastCapabilitiesVersion: UInt8 = 0
let kBroadcastCapabilitiesPerSlotAdvIntervals: UInt8 = 0x1
let kBroadcastCapabilitiesPerSlotTxPower: UInt8 = 0x2
let kBroadcastCapabilitiesSupportsUID: UInt8 = 0x1
let kBroadcastCapabilitiesSupportsURL: UInt8 = 0x2
let kBroadcastCapabilitiesSupportsTLM: UInt8 = 0x4
let kBroadcastCapabilitiesSupportsEID: UInt8 = 0x8
let maxSupportedSlotsKey = "maxSupportedSlots"
let maxSupportedEIDSlotsKey = "maxSupportedEIDSlots"
let perSlotAdvIntervalsSupportedKey = "advertismentIntervalSupported"
let perSlotTxPowerSupportedKey = "txPowerSupported"
let UIDSupportedKey = "UIDSupportedKey"
let URLSupportedKey = "URLSupportedKey"
let TLMSupportedKey = "TLMSupportedKey"
let EIDSupportedKey = "EIDSupportedKey"
let BroadcastCapabilitiesSupportsEID = "BroadcastCapabilitiesSupportsEID"
let slotDataFrameTypeKey = "slotDataFrameTypeKey"
let slotDataUIDKey = "slotDataUIDKey"
let slotDataURLKey = "slotDataURLKey"
let slotDataTLMKey = "slotDataTLMKey"
let slotDataEIDKey = "slotDataEIDKey"
let slotDataAdvIntervalKey = "slotDataAdvIntervalKey"
let slotDataTxPowerKey = "slotDataTxPowerKey"
let slotDataNoFrameKey = "slotDataNoFrameKey"
let slotDataRemainConnectableKey = "slotDataRemainCOnnectableKey"
///
/// The class wants to read all the information for the beacon.
/// We have to discover the capabilities and get information such as the maximum number of
/// slots that are available, and then, for each slot, we want to read the TX Power, the
/// advertising interval and the actual slot data. We actually created a nice flow for this
/// to make things look cleaner and to be able to handle errors.
///
class BeaconInvestigation: GATTOperations {
var currentlyScannedSlot: UInt8 = 0
var beaconBroadcastCapabilities: NSDictionary = [:]
var slotData = [NSNumber : [ String : NSData]]()
var callback: ((beaconBroadcastCapabilities: NSDictionary,
slotData: Dictionary <NSNumber, Dictionary <String, NSData>>) -> Void)?
enum InvestigationState {
case BeaconUnlocked
case DiscoveredCapabilities
case ErrorDiscoveringCapabilities
case DidSetActiveSlot
case ErrorSettingActiveSlot
case ScannedSlot
case ScannedAllSlots
case ErrorScanningSlot
case DidReadTxPower
case ErrorReadingTxPower
case DidReadAdvertisingInterval
case ErrorReadingAdvertisingInterval
case DidReadRemainConnectableState
case ErrorReadingRemainCOnectableState
}
func didUpdateInvestigationState(investigationState: InvestigationState) {
switch investigationState {
case InvestigationState.BeaconUnlocked:
discoverCapabilities()
case InvestigationState.DiscoveredCapabilities:
setSlotForScan()
case InvestigationState.DidSetActiveSlot:
scanSlot()
case InvestigationState.ScannedSlot:
readTxPower()
case InvestigationState.DidReadTxPower:
readAdvertisingInterval()
case InvestigationState.DidReadAdvertisingInterval:
readRemainConnectableState()
case InvestigationState.DidReadRemainConnectableState:
setSlotForScan()
case InvestigationState.ScannedAllSlots:
if let investigationCallback = callback {
investigationCallback(beaconBroadcastCapabilities: beaconBroadcastCapabilities,
slotData: slotData)
}
case InvestigationState.ErrorScanningSlot:
currentlyScannedSlot += 1;
setSlotForScan()
default:
return
}
}
func finishedUnlockingBeacon(investigationCallback:
(beaconBroadcastCapabilities: NSDictionary,
slotData: Dictionary <NSNumber, Dictionary <String, NSData>>) -> Void) {
callback = investigationCallback
peripheral.delegate = self
didUpdateInvestigationState(InvestigationState.BeaconUnlocked)
}
func discoverCapabilities() {
if let characteristic = findCharacteristicByID(CharacteristicID.capabilities.UUID) {
peripheral.readValueForCharacteristic(characteristic)
}
}
override func peripheral(peripheral: CBPeripheral,
didUpdateValueForCharacteristic characteristic: CBCharacteristic,
error: NSError?) {
NSLog("did update value for characteristic \(characteristic.UUID)")
if let identifiedError = error {
NSLog("Error reading characteristic: \(identifiedError)")
} else {
switch characteristic.UUID {
case CharacteristicID.capabilities.UUID:
didReadBroadcastCapabilities()
case CharacteristicID.ADVSlotData.UUID:
didReadSlotData()
case CharacteristicID.radioTxPower.UUID:
didReadTxPower()
case CharacteristicID.advertisingInterval.UUID:
didReadAdvertisingInterval()
case CharacteristicID.remainConnectable.UUID:
didReadRemainConnectableState()
default:
return
}
}
}
override func peripheral(peripheral: CBPeripheral,
didWriteValueForCharacteristic characteristic: CBCharacteristic,
error: NSError?) {
NSLog("did write value for characteristic \(characteristic.UUID)")
if characteristic.UUID == CharacteristicID.activeSlot.UUID {
if error != nil {
didUpdateInvestigationState(InvestigationState.ErrorSettingActiveSlot)
} else {
didUpdateInvestigationState(InvestigationState.DidSetActiveSlot)
}
}
}
struct EddystoneGATTBroadcastCapabilities {
var version: UInt8
var maxSupportedTotalSlots: UInt8
var maxSupportedEidSlots: UInt8
var capabilitiesBitField: UInt8
var supportedFrameTypesBitFieldHigh: UInt8
var supportedFrameTypesBitFieldLow: UInt8
init() {
version = 0
maxSupportedTotalSlots = 0
maxSupportedEidSlots = 0
supportedFrameTypesBitFieldLow = 0
supportedFrameTypesBitFieldHigh = 0
capabilitiesBitField = 0
}
}
func isBitOn(field: UInt8, mask: UInt8) -> Bool {
return (field & mask) != 0
}
func didReadBroadcastCapabilities() {
if let
capabilitiesCharacteristic = findCharacteristicByID(CharacteristicID.capabilities.UUID),
capabilities = capabilitiesCharacteristic.value {
if capabilities.length < sizeof(EddystoneGATTBroadcastCapabilities) {
didUpdateInvestigationState(InvestigationState.ErrorDiscoveringCapabilities)
} else {
var broadcastCapabilities = EddystoneGATTBroadcastCapabilities()
capabilities.getBytes(&broadcastCapabilities, length: capabilities.length)
if broadcastCapabilities.version != kBroadCastCapabilitiesVersion {
didUpdateInvestigationState(InvestigationState.ErrorDiscoveringCapabilities)
} else {
let txPowers: NSMutableArray = []
var i = 6
while i < capabilities.length {
var txPower: Int8 = 0
capabilities.getBytes(&txPower, range:NSMakeRange(i, sizeof(Int8)))
txPowers.addObject(NSNumber(char: txPower))
i += 1
}
beaconBroadcastCapabilities =
[maxSupportedSlotsKey :
NSNumber(unsignedChar: broadcastCapabilities.maxSupportedTotalSlots),
maxSupportedEIDSlotsKey :
NSNumber(unsignedChar: broadcastCapabilities.maxSupportedEidSlots),
perSlotAdvIntervalsSupportedKey :
isBitOn(broadcastCapabilities.capabilitiesBitField,
mask: kBroadcastCapabilitiesPerSlotAdvIntervals),
perSlotTxPowerSupportedKey :
isBitOn(broadcastCapabilities.capabilitiesBitField,
mask: kBroadcastCapabilitiesPerSlotTxPower),
UIDSupportedKey :
isBitOn(broadcastCapabilities.supportedFrameTypesBitFieldLow,
mask: kBroadcastCapabilitiesSupportsUID),
URLSupportedKey :
isBitOn(broadcastCapabilities.supportedFrameTypesBitFieldLow,
mask: kBroadcastCapabilitiesSupportsURL),
TLMSupportedKey :
isBitOn(broadcastCapabilities.supportedFrameTypesBitFieldLow,
mask: kBroadcastCapabilitiesSupportsTLM),
EIDSupportedKey :
isBitOn(broadcastCapabilities.supportedFrameTypesBitFieldLow,
mask: kBroadcastCapabilitiesSupportsEID)]
currentlyScannedSlot = 0
didUpdateInvestigationState(InvestigationState.DiscoveredCapabilities)
}
}
}
}
func setSlotForScan() {
if let maxSupportedSlots = beaconBroadcastCapabilities[maxSupportedSlotsKey] {
let intMaxSupportedSlots: Int = maxSupportedSlots as! Int
if currentlyScannedSlot >= UInt8(intMaxSupportedSlots) {
didUpdateInvestigationState(InvestigationState.ScannedAllSlots)
} else {
if let characteristic = findCharacteristicByID(CharacteristicID.activeSlot.UUID) {
let currentSlot = NSData(bytes: ¤tlyScannedSlot, length: 1)
peripheral.writeValue(currentSlot,
forCharacteristic: characteristic,
type: CBCharacteristicWriteType.WithResponse)
}
}
}
}
func scanSlot() {
if let characteristic = findCharacteristicByID(CharacteristicID.ADVSlotData.UUID) {
peripheral.readValueForCharacteristic(characteristic)
}
}
func didReadSlotData() {
if let
characteristic = findCharacteristicByID(CharacteristicID.ADVSlotData.UUID),
value = characteristic.value {
updateSlotData(value)
}
}
func updateSlotData(value: NSData) {
var frameTypeName: String!
if value.length > 0 {
let scannedSlot: NSNumber = NSNumber(unsignedChar: currentlyScannedSlot)
var frameType: UInt8 = 0
value.getBytes(&frameType, range: NSMakeRange(0, 1))
if slotData[scannedSlot] == nil {
slotData[scannedSlot] = [String : NSData]()
}
if frameType == BeaconInfo.EddystoneUIDFrameTypeID {
frameTypeName = BeaconInfo.EddystoneFrameType.UIDFrameType.description
slotData[scannedSlot]![slotDataFrameTypeKey] =
frameTypeName.dataUsingEncoding(NSUTF8StringEncoding)
///
/// If the frame doesn't have enough characters, it means that the UID is malformed
/// and no data is saved for this slot.
///
if value.length >= 18 {
///
/// The first two bytes represent frame type and ranging data. The rest of 16 bytes
/// represent the UID - 10-byte Namespace and 6-byte Instance. If the frame has more
/// bytes, we will simply truncate it to the ones we need.
///
slotData[scannedSlot]![slotDataUIDKey] = value.subdataWithRange(NSMakeRange(2, 16))
}
} else if frameType == BeaconInfo.EddystoneURLFrameTypeID {
frameTypeName = BeaconInfo.EddystoneFrameType.URLFrameType.description
slotData[scannedSlot]![slotDataFrameTypeKey] =
frameTypeName.dataUsingEncoding(NSUTF8StringEncoding)
if let
urlData = BeaconInfo.parseURLFromFrame(value),
urlNSData = urlData.absoluteString!.dataUsingEncoding(NSUTF8StringEncoding) {
NSLog("\(slotData[scannedSlot]![slotDataFrameTypeKey])")
slotData[scannedSlot]![slotDataURLKey] = urlNSData
}
} else if frameType == BeaconInfo.EddystoneTLMFrameTypeID {
frameTypeName = BeaconInfo.EddystoneFrameType.TelemetryFrameType.description
slotData[scannedSlot]![slotDataFrameTypeKey] =
frameTypeName.dataUsingEncoding(NSUTF8StringEncoding)
slotData[scannedSlot]![slotDataTLMKey] = value
} else if frameType == BeaconInfo.EddystoneEIDFrameTypeID {
frameTypeName = BeaconInfo.EddystoneFrameType.EIDFrameType.description
slotData[scannedSlot]![slotDataFrameTypeKey] =
frameTypeName.dataUsingEncoding(NSUTF8StringEncoding)
}
didUpdateInvestigationState(InvestigationState.ScannedSlot)
} else {
let scannedSlot: NSNumber = NSNumber(unsignedChar: currentlyScannedSlot)
if slotData[scannedSlot] == nil {
slotData[scannedSlot] = [String : NSData]()
}
frameTypeName = BeaconInfo.EddystoneFrameType.NotSetFrameType.description
slotData[scannedSlot]![slotDataFrameTypeKey] =
frameTypeName.dataUsingEncoding(NSUTF8StringEncoding)
didUpdateInvestigationState(InvestigationState.ErrorScanningSlot)
}
}
func readTxPower() {
if let characteristic = findCharacteristicByID(CharacteristicID.radioTxPower.UUID) {
peripheral.readValueForCharacteristic(characteristic)
}
}
func getValueForCharacteristic(characteristicID: CBUUID) -> NSData? {
if let
characteristic = findCharacteristicByID(characteristicID),
value = characteristic.value {
return value
}
return nil
}
func didReadTxPower() {
let scannedSlot: NSNumber = NSNumber(unsignedChar: currentlyScannedSlot)
var txPower: Int8 = 0
if let value = getValueForCharacteristic(CharacteristicID.radioTxPower.UUID) {
value.getBytes(&txPower, length: sizeof(Int8))
}
if slotData[scannedSlot] != nil {
slotData[scannedSlot]![slotDataTxPowerKey] = NSData(bytes: &txPower, length: sizeof(Int8))
}
didUpdateInvestigationState(InvestigationState.DidReadTxPower)
}
func readAdvertisingInterval() {
if let characteristic = findCharacteristicByID(CharacteristicID.advertisingInterval.UUID) {
peripheral.readValueForCharacteristic(characteristic)
}
}
func didReadAdvertisingInterval() {
let scannedSlot: NSNumber = NSNumber(unsignedChar: currentlyScannedSlot)
var advertisingInterval: UInt16 = 0
if let value = getValueForCharacteristic(CharacteristicID.advertisingInterval.UUID) {
value.getBytes(&advertisingInterval, length: sizeof(UInt16))
}
if slotData[scannedSlot] != nil {
var littleEndianAdvInterval: UInt16 = CFSwapInt16BigToHost(advertisingInterval)
let bytes = NSData(bytes: &littleEndianAdvInterval,
length: sizeof(UInt16))
slotData[scannedSlot]![slotDataAdvIntervalKey] = bytes
}
didUpdateInvestigationState(InvestigationState.DidReadAdvertisingInterval)
}
func readRemainConnectableState() {
if let characteristic = findCharacteristicByID(CharacteristicID.remainConnectable.UUID) {
peripheral.readValueForCharacteristic(characteristic)
}
}
func didReadRemainConnectableState() {
let scannedSlot: NSNumber = NSNumber(unsignedChar: currentlyScannedSlot)
if let value = getValueForCharacteristic(CharacteristicID.remainConnectable.UUID) {
if slotData[scannedSlot] != nil {
slotData[scannedSlot]![slotDataRemainConnectableKey] = value
}
}
currentlyScannedSlot += 1
didUpdateInvestigationState(InvestigationState.DidReadRemainConnectableState)
}
}
| apache-2.0 | 41c50d84facb377ebed3348c2233d67a | 38.83376 | 96 | 0.72077 | 4.770291 | false | false | false | false |
natecook1000/swift | test/SILGen/keypath_application.swift | 1 | 6118 |
// RUN: %target-swift-emit-silgen -enable-sil-ownership %s | %FileCheck %s
class A {}
class B {}
protocol P {}
protocol Q {}
// CHECK-LABEL: sil hidden @{{.*}}loadable
func loadable(readonly: A, writable: inout A,
value: B,
kp: KeyPath<A, B>,
wkp: WritableKeyPath<A, B>,
rkp: ReferenceWritableKeyPath<A, B>) {
// CHECK: [[ROOT_TMP:%.*]] = alloc_stack $A
// CHECK: [[ROOT_COPY:%.*]] = copy_value %0
// CHECK: store [[ROOT_COPY]] to [init] [[ROOT_TMP]]
// CHECK: [[KP_COPY:%.*]] = copy_value %3
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
// CHECK: [[BORROWED_KP_COPY:%.*]] = begin_borrow [[KP_COPY]]
// CHECK: [[RESULT_TMP:%.*]] = alloc_stack $B
// CHECK: apply [[PROJECT]]<A, B>([[RESULT_TMP]], [[ROOT_TMP]], [[BORROWED_KP_COPY]])
// CHECK: [[RESULT:%.*]] = load [take] [[RESULT_TMP]]
// CHECK: destroy_value [[RESULT]]
_ = readonly[keyPath: kp]
_ = writable[keyPath: kp]
_ = readonly[keyPath: wkp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: wkp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: rkp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: rkp]
// CHECK: function_ref @{{.*}}_projectKeyPathWritable
writable[keyPath: wkp] = value
// CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable
readonly[keyPath: rkp] = value
// CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable
writable[keyPath: rkp] = value
}
// CHECK-LABEL: sil hidden @{{.*}}addressOnly
func addressOnly(readonly: P, writable: inout P,
value: Q,
kp: KeyPath<P, Q>,
wkp: WritableKeyPath<P, Q>,
rkp: ReferenceWritableKeyPath<P, Q>) {
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: kp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: kp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: wkp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: wkp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: rkp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: rkp]
// CHECK: function_ref @{{.*}}_projectKeyPathWritable
writable[keyPath: wkp] = value
// CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable
readonly[keyPath: rkp] = value
// CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable
writable[keyPath: rkp] = value
}
// CHECK-LABEL: sil hidden @{{.*}}reabstracted
func reabstracted(readonly: @escaping () -> (),
writable: inout () -> (),
value: @escaping (A) -> B,
kp: KeyPath<() -> (), (A) -> B>,
wkp: WritableKeyPath<() -> (), (A) -> B>,
rkp: ReferenceWritableKeyPath<() -> (), (A) -> B>) {
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: kp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: kp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: wkp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: wkp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: rkp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: rkp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathWritable
writable[keyPath: wkp] = value
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReferenceWritable
readonly[keyPath: rkp] = value
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReferenceWritable
writable[keyPath: rkp] = value
}
// CHECK-LABEL: sil hidden @{{.*}}partial
func partial<A>(valueA: A,
valueB: Int,
pkpA: PartialKeyPath<A>,
pkpB: PartialKeyPath<Int>,
akp: AnyKeyPath) {
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathAny
// CHECK: apply [[PROJECT]]<A>
_ = valueA[keyPath: akp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathPartial
// CHECK: apply [[PROJECT]]<A>
_ = valueA[keyPath: pkpA]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathAny
// CHECK: apply [[PROJECT]]<Int>
_ = valueB[keyPath: akp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathPartial
// CHECK: apply [[PROJECT]]<Int>
_ = valueB[keyPath: pkpB]
}
extension Int {
var b: Int { get { return 0 } set { } }
var u: Int { get { return 0 } set { } }
var tt: Int { get { return 0 } set { } }
}
// CHECK-LABEL: sil hidden @{{.*}}writebackNesting
func writebackNesting(x: inout Int,
y: WritableKeyPath<Int, Int>,
z: WritableKeyPath<Int, Int>,
w: Int) -> Int {
// -- get 'b'
// CHECK: function_ref @$SSi19keypath_applicationE1bSivg
// -- apply keypath y
// CHECK: [[PROJECT_FN:%.*]] = function_ref @{{.*}}_projectKeyPathWritable
// CHECK: [[PROJECT_RET:%.*]] = apply [[PROJECT_FN]]
// CHECK: ({{%.*}}, [[OWNER_Y:%.*]]) = destructure_tuple [[PROJECT_RET]]
// -- get 'u'
// CHECK: function_ref @$SSi19keypath_applicationE1uSivg
// -- apply keypath z
// CHECK: [[PROJECT_FN:%.*]] = function_ref @{{.*}}_projectKeyPathWritable
// CHECK: [[PROJECT_RET:%.*]] = apply [[PROJECT_FN]]
// CHECK: ({{%.*}}, [[OWNER_Z:%.*]]) = destructure_tuple [[PROJECT_RET]]
// -- set 'tt'
// CHECK: function_ref @$SSi19keypath_applicationE2ttSivs
// -- destroy owner for keypath projection z
// CHECK: destroy_value [[OWNER_Z]]
// -- set 'u'
// CHECK: function_ref @$SSi19keypath_applicationE1uSivs
// -- destroy owner for keypath projection y
// CHECK: destroy_value [[OWNER_Y]]
// -- set 'b'
// CHECK: function_ref @$SSi19keypath_applicationE1bSivs
x.b[keyPath: y].u[keyPath: z].tt = w
}
| apache-2.0 | 0197856a67dd02cc2e8753e67837beff | 37 | 87 | 0.587937 | 4.025 | false | false | false | false |
uhnmdi/CCGlucose | Example/CCGlucose/GlucoseMeterViewController.swift | 1 | 10567 | //
// GlucoseMeterViewController.swift
// CCBluetooth
//
// Created by Kevin Tallevi on 7/8/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
import CoreBluetooth
import CCGlucose
class GlucoseMeterViewController: UITableViewController, GlucoseProtocol {
let cellIdentifier = "GlucoseMeterCellIdentifier"
var glucoseFeatures: GlucoseFeatures!
var glucoseMeasurementCount: UInt16 = 0
var glucoseMeasurements: Array<GlucoseMeasurement> = Array<GlucoseMeasurement>()
var glucoseMeasurementsContexts: Array<GlucoseMeasurementContext> = Array<GlucoseMeasurementContext>()
var selectedGlucoseMeasurement: GlucoseMeasurement!
var selectedGlucoseMeasurementContext: GlucoseMeasurementContext!
var selectedMeter: CBPeripheral!
var meterConnected: Bool!
override func viewDidLoad() {
super.viewDidLoad()
print("GlucoseMeterViewController#viewDidLoad")
print("selectedMeter: \(selectedMeter)")
meterConnected = false
Glucose.sharedInstance().glucoseDelegate = self
}
override func didMove(toParentViewController parent: UIViewController?) {
super.didMove(toParentViewController: parent)
if(meterConnected == true) {
Glucose.sharedInstance().disconnectGlucoseMeter()
}
}
func getMeasurement(sequenceNumber: UInt16) -> GlucoseMeasurement? {
for measurement: GlucoseMeasurement in glucoseMeasurements {
if measurement.sequenceNumber == sequenceNumber {
return measurement
}
}
return nil
}
func getMeasurementContext(sequenceNumber: UInt16) -> GlucoseMeasurementContext? {
for measurementContext: GlucoseMeasurementContext in glucoseMeasurementsContexts {
if measurementContext.sequenceNumber == sequenceNumber {
return measurementContext
}
}
return nil
}
// MARK: - GlucoseProtocol
func glucoseMeterConnected(meter: CBPeripheral) {
print("GlucoseMeterViewController#glucoseMeterConnected")
meterConnected = true
}
public func glucoseMeterDisconnected(meter: CBPeripheral) {
print("GlucoseMeterViewController#glucoseMeterDisconnected")
meterConnected = false
}
func numberOfStoredRecords(number: UInt16) {
print("GlucoseMeterViewController#numberOfStoredRecords - \(number)")
glucoseMeasurementCount = number
self.refreshTable()
Glucose.sharedInstance().downloadAllRecords()
}
func glucoseMeasurement(measurement:GlucoseMeasurement) {
print("glucoseMeasurement")
if let measurementContext = getMeasurementContext(sequenceNumber: measurement.sequenceNumber) {
print("glucoseMeasurement: attaching context to measurement")
measurement.context = measurementContext
}
glucoseMeasurements.append(measurement)
self.refreshTable()
}
func glucoseMeasurementContext(measurementContext:GlucoseMeasurementContext) {
print("glucoseMeasurementContext - id: \(measurementContext.sequenceNumber)")
if let measurement = getMeasurement(sequenceNumber: measurementContext.sequenceNumber) {
print("glucoseMeasurementContext: attaching context to measurement")
measurement.context = measurementContext
}
glucoseMeasurementsContexts.append(measurementContext)
self.refreshTable()
}
func glucoseFeatures(features:GlucoseFeatures) {
print("GlucoseMeterViewController#glucoseFeatures")
glucoseFeatures = features
self.refreshTable()
}
func glucoseMeterDidTransferMeasurements(error: NSError?) {
print("GlucoseMeterViewController#glucoseMeterDidTransferMeasurements")
if (nil != error) {
print(error as Any)
} else {
print("transfer successful")
}
}
public func glucoseError(error: NSError) {
print("GlucoseMeterViewController#glucoseError")
print(error.localizedDescription)
}
// MARK: - Storyboard
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let detailsViewController = segue.destination as! GlucoseMeasurementDetailsViewController
detailsViewController.glucoseMeasurement = selectedGlucoseMeasurement
}
// MARK: - UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
if(glucoseFeatures != nil) {
return 11
} else {
return 0
}
case 1:
if(glucoseMeasurementCount > 0) {
return 1
} else {
return 0
}
case 2:
return glucoseMeasurements.count
default:
return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath as IndexPath) as UITableViewCell
switch indexPath.section {
case 0:
if(glucoseFeatures != nil) {
switch indexPath.row {
case 0:
cell.textLabel!.text = glucoseFeatures.lowBatterySupported?.description
cell.detailTextLabel!.text = "Low Battery Supported"
case 1:
cell.textLabel!.text = glucoseFeatures.sensorMalfunctionDetectionSupported?.description
cell.detailTextLabel!.text = "Sensor Malfunction Detection Supported"
case 2:
cell.textLabel!.text = glucoseFeatures.sensorSampleSizeSupported?.description
cell.detailTextLabel!.text = "Sensor Sample Size Supported"
case 3:
cell.textLabel!.text = glucoseFeatures.sensorStripInsertionErrorDetectionSupported?.description
cell.detailTextLabel!.text = "Sensor Strip Insertion Error Detection Supported"
case 4:
cell.textLabel!.text = glucoseFeatures.sensorStripTypeErrorDetectionSupported?.description
cell.detailTextLabel!.text = "Sensor Strip Type Error Detection Supported"
case 5:
cell.textLabel!.text = glucoseFeatures.sensorResultHighLowDetectionSupported?.description
cell.detailTextLabel!.text = "Sensor Result High Low Detection Supported"
case 6:
cell.textLabel!.text = glucoseFeatures.sensorTemperatureHighLowDetectionSupported?.description
cell.detailTextLabel!.text = "Sensor Temperature High Low Detection Supported"
case 7:
cell.textLabel!.text = glucoseFeatures.sensorReadInterruptDetectionSupported?.description
cell.detailTextLabel!.text = "Sensor Read Interrupt Detection Supported"
case 8:
cell.textLabel!.text = glucoseFeatures.generalDeviceFaultSupported?.description
cell.detailTextLabel!.text = "General Device Fault Supported"
case 9:
cell.textLabel!.text = glucoseFeatures.timeFaultSupported?.description
cell.detailTextLabel!.text = "Time Fault Supported"
case 10:
cell.textLabel!.text = glucoseFeatures.multipleBondSupported?.description
cell.detailTextLabel!.text = "MultipleBond Supported"
default:
cell.textLabel!.text = ""
cell.detailTextLabel!.text = ""
}
}
case 1:
if (glucoseMeasurementCount > 0) {
cell.textLabel!.text = "Number of records: " + " " + glucoseMeasurementCount.description
cell.detailTextLabel!.text = ""
}
case 2:
let measurement = Array(glucoseMeasurements)[indexPath.row]
let mmolString : String = (measurement.toMMOL()?.description)!
let contextWillFollow : Bool = (measurement.contextInformationFollows)
cell.textLabel!.text = "[\(contextWillFollow.description)] (\(measurement.sequenceNumber!)) \(measurement.glucoseConcentration!) \(measurement.unit.description) (\(mmolString) mmol/L)"
cell.detailTextLabel!.text = measurement.dateTime?.description
default:
cell.textLabel!.text = ""
cell.detailTextLabel!.text = ""
}
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 75
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return "Glucose Meter Features"
case 1:
return "Glucose Record Count"
case 2:
return "Glucose Records"
default:
return ""
}
}
//MARK: - table delegate methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if(indexPath.section == 2) {
selectedGlucoseMeasurement = Array(glucoseMeasurements)[indexPath.row]
performSegue(withIdentifier: "segueToMeasurementDetails", sender: self)
}
}
// MARK: -
func refreshTable() {
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
}
}
| mit | eca2a3c43fcc61f44c1d6f13c54ef642 | 40.11284 | 200 | 0.603066 | 6.075906 | false | false | false | false |
ianrahman/HackerRankChallenges | Swift/Data Structures/Arrays/dynamic-array.swift | 1 | 996 | import Foundation
// define initial values
var lastAns = 0
let params = readLine()!.components(separatedBy: " ").map{ Int($0)! }
let sequencesCount = params[0]
let queriesCount = params[1]
var seqList = [[Int]]()
// create necessary number of empty sequences
for _ in 0..<sequencesCount {
seqList.append([Int]())
}
// define query types
enum QueryType: Int {
case type1 = 1, type2
}
// read each query
for _ in 0..<queriesCount {
// define temp values
let query = readLine()!.components(separatedBy: " ").map{ Int($0)! }
let x = query[1]
let y = query[2]
let xor = x ^ lastAns
let index = (x ^ lastAns) % sequencesCount
// perform query
if let type = QueryType(rawValue: query[0]) {
switch type {
case .type1:
seqList[index].append(y)
case .type2:
let size = seqList[index].count
let value = seqList[index][y % size]
lastAns = value
print(lastAns)
}
}
}
| mit | e280a15e3c602cc584d569a1a8f2615e | 22.714286 | 72 | 0.591365 | 3.608696 | false | false | false | false |
96-problems/medium-sdk-swift | medium-sdk-swift-example/medium-sdk-swift-sample/ViewController.swift | 1 | 6488 | //
// ViewController.swift
// medium-sdk-swift-sample
//
// Created by drinkius on 02/05/16.
// Copyright © 2016 96problems. All rights reserved.
//
import UIKit
import MediumSDKSwift
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//
var mediumSession = MediumSDKManager.sharedInstance
// Tableview setup
var tableView: UITableView = UITableView()
var historySessions = [AnyObject]()
var buttons : [String] = [
"Authorize on Medium.com",
"Check token",
"Own profile info request",
"Own publications request",
"Publications's contributors request",
"Create a post",
"Create a post under publication",
"Sign out"
]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return buttons.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "cell")
cell.textLabel!.text = buttons[indexPath.row]
return cell;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
mediumSession.doOAuthMedium() { state, message in
if state == "success" {
self.showAlert("Success! \n\n Your Medium token is: \(message)")
} else {
self.showAlert("Error: \n\n \(message)")
}
}
case 1:
mediumSession.checkCred() { state, message in
if state == "success" {
self.showAlert("Success! \n\n Your Medium token is: \(message)")
} else {
self.showAlert("Error: \n\n \(message)")
}
}
case 2:
mediumSession.ownCredentialsRequest() { state, message in
if state == "success" {
self.showAlert("Success! \n\n Your user ID is: \(message)")
} else {
self.showAlert("Error: \n\n \(message)")
}
}
case 3:
mediumSession.userPublicationsListRequest() { state, message, _ in
if state == "success" {
self.showAlert("Success! \n\n Number of own publications: \n\n \(message)")
} else {
self.showAlert("Error: \n\n \(message)")
}
}
case 4:
// Sample postID, feel free to use any other post ID of yours to test this function
let postID = "b6bdc04b3925"
mediumSession.getListOfContributors(postID) { state, message, _ in
if state == "success" {
self.showAlert("Success! \n\n Number of contributors: \n\n \(message)")
} else {
self.showAlert("Error: \n\n \(message)")
}
}
case 5:
let title = "The first post published with SDK CC license"
let contentFormat = "html"
let content = "<h1>The first post</h1><p>Published with SDK</p>"
let canonicalUrl = "http://jamietalbot.com/posts/liverpool-fc"
let tags = ["football", "sport", "Liverpool"]
let publishStatus = MediumPublishStatus.published
let licence = MediumLicense.cc40bync
// mediumSession.createPost(title, contentFormat: contentFormat, content: content, canonicalUrl: canonicalUrl)
mediumSession.createPost(title, contentFormat: contentFormat, content: content, canonicalUrl: canonicalUrl, tags: tags, publishStatus: publishStatus, license: licence) { state, message in
if state == "success" {
self.showAlert("Success! \n\n \(message)")
} else {
self.showAlert("Error: \n\n \(message)")
}
}
case 6:
// In order to check this functionality - enter the root publication ID you got edit rights to
let rootPublication = ""
let title = "New post under publication"
let contentFormat = "html"
let content = "<h1>Test in progress</h1><p>Functions seem to be working well</p>"
let canonicalUrl = "http://phirotto.com/"
let tags = ["medium-sdk", "swift", "swiftlang"]
let publishStatus = MediumPublishStatus.published
let licence = MediumLicense.publicDomain
// mediumSession.createPostUnderPublication(rootPublication, title: title, contentFormat: contentFormat, content: content, tags: tags)
mediumSession.createPostUnderPublication(rootPublication, title: title, contentFormat: contentFormat, content: content, canonicalUrl: canonicalUrl, tags: tags, publishStatus: publishStatus, license: licence) { state, message in
if state == "success" {
self.showAlert("Success! \n\n \(message)")
} else {
self.showAlert("Error: \n\n \(message)")
}
}
case 7:
mediumSession.signOutMedium() { state, message in
if state == "success" {
self.showAlert("Success: \n\n \(message)")
} else {
self.showAlert("Error: \n\n \(message)")
}
}
default:
return
}
// print(buttons[indexPath.row])
}
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.plain)
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(self.tableView)
}
fileprivate func showAlert(_ message: String) {
let alert = UIAlertController(title: message, message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel) { [unowned self] _ in
// self.dismissViewControllerAnimated(true, completion: nil)
})
present(alert, animated: true, completion: nil)
}
}
| mit | 659fbf17e8489bd2e2630736503e9a4e | 40.851613 | 239 | 0.561122 | 4.79099 | false | false | false | false |
pengleelove/TextFieldEffects | TextFieldEffects/TextFieldEffects/MinoruTextField.swift | 11 | 4238 | //
// MinoruTextField.swift
// TextFieldEffects
//
// Created by Raúl Riera on 27/01/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import UIKit
@IBDesignable public class MinoruTextField: TextFieldEffects {
@IBInspectable public var placeholderColor: UIColor? {
didSet {
updatePlaceholder()
}
}
override public var backgroundColor: UIColor? {
set {
backgroundLayerColor = newValue!
}
get {
return backgroundLayerColor
}
}
override public var placeholder: String? {
didSet {
updatePlaceholder()
}
}
override public var bounds: CGRect {
didSet {
updateBorder()
updatePlaceholder()
}
}
private let borderThickness: CGFloat = 1
private let placeholderInsets = CGPoint(x: 6, y: 6)
private let textFieldInsets = CGPoint(x: 6, y: 6)
private let borderLayer = CALayer()
private var backgroundLayerColor: UIColor?
// MARK: - TextFieldsEffectsProtocol
override func drawViewsForRect(rect: CGRect) {
let frame = CGRect(origin: CGPointZero, size: CGSize(width: rect.size.width, height: rect.size.height))
placeholderLabel.frame = CGRectInset(frame, placeholderInsets.x, placeholderInsets.y)
placeholderLabel.font = placeholderFontFromFont(font)
updateBorder()
updatePlaceholder()
layer.addSublayer(borderLayer)
addSubview(placeholderLabel)
}
private func updateBorder() {
borderLayer.frame = rectForBorder(frame)
borderLayer.backgroundColor = backgroundColor?.CGColor
}
private func updatePlaceholder() {
placeholderLabel.text = placeholder
placeholderLabel.textColor = placeholderColor
placeholderLabel.sizeToFit()
layoutPlaceholderInTextRect()
if isFirstResponder() {
animateViewsForTextEntry()
}
}
private func placeholderFontFromFont(font: UIFont) -> UIFont! {
let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.65)
return smallerFont
}
private func rectForBorder(bounds: CGRect) -> CGRect {
var newRect = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font.lineHeight + textFieldInsets.y)
return newRect
}
private func layoutPlaceholderInTextRect() {
if !text.isEmpty {
return
}
let textRect = textRectForBounds(bounds)
var originX = textRect.origin.x
switch textAlignment {
case .Center:
originX += textRect.size.width/2 - placeholderLabel.bounds.width/2
case .Right:
originX += textRect.size.width - placeholderLabel.bounds.width
default:
break
}
placeholderLabel.frame = CGRect(x: originX, y: bounds.height - placeholderLabel.frame.height,
width: placeholderLabel.frame.size.width, height: placeholderLabel.frame.size.height)
}
override func animateViewsForTextEntry() {
borderLayer.borderColor = textColor?.CGColor
borderLayer.shadowOffset = CGSizeZero
borderLayer.borderWidth = borderThickness
borderLayer.shadowColor = textColor?.CGColor
borderLayer.shadowOpacity = 0.5
borderLayer.shadowRadius = 1
}
override func animateViewsForTextDisplay() {
borderLayer.borderColor = nil
borderLayer.shadowOffset = CGSizeZero
borderLayer.borderWidth = 0
borderLayer.shadowColor = nil
borderLayer.shadowOpacity = 0
borderLayer.shadowRadius = 0
}
// MARK: - Overrides
override public func editingRectForBounds(bounds: CGRect) -> CGRect {
let newBounds = rectForBorder(bounds)
return CGRectInset(newBounds, textFieldInsets.x, 0)
}
override public func textRectForBounds(bounds: CGRect) -> CGRect {
let newBounds = rectForBorder(bounds)
return CGRectInset(newBounds, textFieldInsets.x, 0)
}
}
| mit | ea03460177df48c8ae29dc5f7552e701 | 29.264286 | 132 | 0.627331 | 5.538562 | false | false | false | false |
github/Nimble | Nimble/Wrappers/FullMatcherWrapper.swift | 1 | 1103 | import Foundation
struct FullMatcherWrapper<M, T where M: BasicMatcher, M.ValueType == T>: Matcher {
let matcher: M
let to: String
let toNot: String
func matches(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
failureMessage.to = to
let pass = matcher.matches(actualExpression, failureMessage: failureMessage)
return pass
}
func doesNotMatch(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
failureMessage.to = toNot
let pass = matcher.matches(actualExpression, failureMessage: failureMessage)
return !pass
}
}
extension Expectation {
public func to<U where U: BasicMatcher, U.ValueType == T>(matcher: U) {
to(FullMatcherWrapper(matcher: matcher, to: "to", toNot: "to not"))
}
public func toNot<U where U: BasicMatcher, U.ValueType == T>(matcher: U) {
toNot(FullMatcherWrapper(matcher: matcher, to: "to", toNot: "to not"))
}
public func notTo<U where U: BasicMatcher, U.ValueType == T>(matcher: U) {
toNot(matcher)
}
}
| apache-2.0 | cc4e1a75f255086e34148a694bdac5a1 | 31.441176 | 96 | 0.666364 | 4.275194 | false | false | false | false |
lioonline/v2ex-lio | V2ex/Pods/Kingfisher/Kingfisher/UIButton+Kingfisher.swift | 2 | 31712 | //
// UIButton+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/13.
//
// Copyright (c) 2015 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
* Set image to use from web for a specified state.
*/
public extension UIButton {
/**
Set an image to use for a specified state with a resource.
It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource` and then set it for a button state.
The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a URL.
It will ask for Kingfisher's manager to get the image for the URL and then set it for a button state.
The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use.
If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a resource and a placeholder image.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a URL and a placeholder image.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a resource, a placeholder image and options.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a URL, a placeholder image and options.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a resource, a placeholder image, options and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set an image to use for a specified state with a URL, a placeholder image, options and completion handler.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
setImage(placeholderImage, forState: state)
kf_setWebURL(resource.downloadURL, forState: state)
let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo, progressBlock: { (receivedSize, totalSize) -> () in
if let progressBlock = progressBlock {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
progressBlock(receivedSize: receivedSize, totalSize: totalSize)
})
}
}) {[weak self] (image, error, cacheType, imageURL) -> () in
dispatch_async_safely_main_queue {
if let sSelf = self {
if (imageURL == sSelf.kf_webURLForState(state) && image != nil) {
sSelf.setImage(image, forState: state)
}
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
}
}
}
return task
}
/**
Set an image to use for a specified state with a URL, a placeholder image, options, progress handler and completion handler.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithResource(Resource(downloadURL: URL),
forState: state,
placeholderImage: placeholderImage,
optionsInfo: optionsInfo,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
}
private var lastURLKey: Void?
public extension UIButton {
/**
Get the image URL binded to this button for a specified state.
- parameter state: The state that uses the specified image.
- returns: Current URL for image.
*/
public func kf_webURLForState(state: UIControlState) -> NSURL? {
return kf_webURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL
}
private func kf_setWebURL(URL: NSURL, forState state: UIControlState) {
kf_webURLs[NSNumber(unsignedLong:state.rawValue)] = URL
}
private var kf_webURLs: NSMutableDictionary {
get {
var dictionary = objc_getAssociatedObject(self, &lastURLKey) as? NSMutableDictionary
if dictionary == nil {
dictionary = NSMutableDictionary()
kf_setWebURLs(dictionary!)
}
return dictionary!
}
}
private func kf_setWebURLs(URLs: NSMutableDictionary) {
objc_setAssociatedObject(self, &lastURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/**
* Set background image to use from web for a specified state.
*/
public extension UIButton {
/**
Set the background image to use for a specified state with a resource.
It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource` and then set it for a button state.
The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a URL.
It will ask for Kingfisher's manager to get the image for the URL and then set it for a button state.
The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use.
If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a resource and a placeholder image.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a URL and a placeholder image.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a resource, a placeholder image and options.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a URL, a placeholder image and options.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a resource, a placeholder image, options and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set the background image to use for a specified state with a URL, a placeholder image, options and completion handler.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set the background image to use for a specified state with a resource,
a placeholder image, options progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
setBackgroundImage(placeholderImage, forState: state)
kf_setBackgroundWebURL(resource.downloadURL, forState: state)
let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo, progressBlock: { (receivedSize, totalSize) -> () in
if let progressBlock = progressBlock {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
progressBlock(receivedSize: receivedSize, totalSize: totalSize)
})
}
}) { [weak self] (image, error, cacheType, imageURL) -> () in
dispatch_async_safely_main_queue {
if let sSelf = self {
if (imageURL == sSelf.kf_backgroundWebURLForState(state) && image != nil) {
sSelf.setBackgroundImage(image, forState: state)
}
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
}
}
}
return task
}
/**
Set the background image to use for a specified state with a URL,
a placeholder image, options progress handler and completion handler.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(Resource(downloadURL: URL),
forState: state,
placeholderImage: placeholderImage,
optionsInfo: optionsInfo,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
}
private var lastBackgroundURLKey: Void?
public extension UIButton {
/**
Get the background image URL binded to this button for a specified state.
- parameter state: The state that uses the specified background image.
- returns: Current URL for background image.
*/
public func kf_backgroundWebURLForState(state: UIControlState) -> NSURL? {
return kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL
}
private func kf_setBackgroundWebURL(URL: NSURL, forState state: UIControlState) {
kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] = URL
}
private var kf_backgroundWebURLs: NSMutableDictionary {
get {
var dictionary = objc_getAssociatedObject(self, &lastBackgroundURLKey) as? NSMutableDictionary
if dictionary == nil {
dictionary = NSMutableDictionary()
kf_setBackgroundWebURLs(dictionary!)
}
return dictionary!
}
}
private func kf_setBackgroundWebURLs(URLs: NSMutableDictionary) {
objc_setAssociatedObject(self, &lastBackgroundURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Deprecated
public extension UIButton {
@available(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo: instead.")
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: nil)
}
@available(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo:completionHandler: instead.")
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: completionHandler)
}
@available(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.")
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: progressBlock, completionHandler: completionHandler)
}
@available(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo: instead.")
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: nil)
}
@available(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo:completionHandler: instead.")
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: completionHandler)
}
@available(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.")
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: progressBlock, completionHandler: completionHandler)
}
}
| mit | 3084a97c37ff71830a1f617cd941299b | 52.477234 | 242 | 0.648745 | 6.004923 | false | false | false | false |
tonystone/geofeatures2 | Sources/GeoFeatures/CoordinateSystem.swift | 1 | 1078 | ///
/// CoordinateSystem.swift
///
/// Copyright (c) 2016 Tony Stone
///
/// 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.
///
/// Created by Tony Stone on 2/5/2016.
///
import Swift
///
/// Coordinate System Types
///
/// These are used by the algorithms when they are applied to the types
///
public protocol CoordinateSystem {}
public func == <T1: CoordinateSystem & Hashable, T2: CoordinateSystem & Hashable>(lhs: T1, rhs: T2) -> Bool {
if type(of: lhs) == type(of: rhs) {
return lhs.hashValue == rhs.hashValue
}
return false
}
| apache-2.0 | 974868820cd2b976c853de6f523af54d | 30.705882 | 109 | 0.686456 | 3.891697 | false | false | false | false |
andybest/SLisp | Sources/SLispCore/Namespace.swift | 1 | 5694 | /*
MIT License
Copyright (c) 2017 Andy Best
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 class Namespace: Hashable {
public let name: String
var rootBindings = [String: LispType]()
var namespaceRefs = [String: Namespace]()
var namespaceImports = Set<Namespace>()
public private(set) var hashValue: Int = 0
init(name: String) {
self.name = name
}
public static func ==(lhs: Namespace, rhs: Namespace) -> Bool {
return lhs.name == rhs.name
}
}
// Namespaces
extension Parser {
func addNamespace(_ ns: Namespace) {
namespaces[ns.name] = ns
}
func getValue(_ name: String, withEnvironment env: Environment) throws -> LispType {
var targetNamespace: String?
var binding: String
// Special symbol that returns the current namespace
if name == "*ns*" {
return .symbol(env.namespace.name)
}
// Split the input on the first forward slash to separate by
let bindingComponents = name.characters.split(maxSplits: 1, omittingEmptySubsequences: false) {
$0 == "/"
}.map(String.init)
if bindingComponents.count == 1 || bindingComponents[0] == "" {
if bindingComponents[0] == "" {
// If the input starts with a slash, it is part of the binding, not a namespace separator.
// This allows looking up "/" (divide) without a namespace qualifier, for example.
binding = "/\(bindingComponents[0])"
} else {
binding = bindingComponents[0]
}
} else {
targetNamespace = bindingComponents[0]
binding = bindingComponents[1]
}
if targetNamespace != nil {
// Search for a namespace ref, or namespace with the given name
if let ns = env.namespace.namespaceRefs[targetNamespace!] {
if let val = ns.rootBindings[binding] {
return val
}
} else if let ns = namespaces[targetNamespace!] {
if let val = ns.rootBindings[binding] {
return val
}
}
} else {
// Search environment
var currentEnv: Environment? = env
while currentEnv != nil {
if let val = currentEnv!.localBindings[name] {
return val
}
currentEnv = currentEnv?.parent
}
if let val = env.namespace.rootBindings[name] {
return val
}
for ns in env.namespace.namespaceImports {
if let val = ns.rootBindings[name] {
return val
}
}
}
throw LispError.general(msg: "Value \(name) not found.")
}
func setValue(name: String, value: LispType, withEnvironment environment: Environment) throws -> LispType {
// Search binding from the top for target value
var currentEnv: Environment? = environment
while currentEnv != nil {
if currentEnv!.localBindings[name] != nil {
currentEnv!.localBindings[name] = value
return .string(name)
}
currentEnv = currentEnv?.parent
}
throw LispError.runtime(msg: "Unable to set value \(name) as it can't be found")
}
func bindGlobal(name: LispType, value: LispType, toNamespace namespace: Namespace) throws -> LispType {
guard case let .symbol(bindingName) = name else {
throw LispError.runtime(msg: "Values can only be bound to symbols. Got \(String(describing: name))")
}
namespace.rootBindings[bindingName] = value
return .symbol("\(namespace.name)/\(bindingName)")
}
func importNamespace(_ ns: Namespace, toNamespace namespace: Namespace) {
if ns != namespace {
namespace.namespaceImports.insert(ns)
}
}
func importNamespace(_ ns: Namespace, as importName: String, toNamespace namespace: Namespace) {
namespace.namespaceRefs[importName] = ns
}
public func createOrGetNamespace(_ name: String) -> Namespace {
if let ns = namespaces[name] {
return ns
}
let ns = Namespace(name: name)
namespaces[name] = ns
coreImports.forEach {
if $0 != ns.name {
importNamespace(createOrGetNamespace($0), toNamespace: ns)
}
}
return ns
}
}
| mit | d965ae285b187f4054961158791feb3a | 32.494118 | 112 | 0.593783 | 4.895959 | false | false | false | false |
Look-ARound/LookARound2 | Pods/HDAugmentedReality/HDAugmentedReality/Classes/ARTrackingManager.swift | 1 | 24620 | //
// ARTrackingManager.swift
// HDAugmentedRealityDemo
//
// Created by Danijel Huis on 22/04/15.
// Copyright (c) 2015 Danijel Huis. All rights reserved.
//
import UIKit
import CoreMotion
import CoreLocation
import GLKit
protocol ARTrackingManagerDelegate : NSObjectProtocol
{
func arTrackingManager(_ trackingManager: ARTrackingManager, didUpdateUserLocation location: CLLocation)
func arTrackingManager(_ trackingManager: ARTrackingManager, didUpdateReloadLocation location: CLLocation)
func arTrackingManager(_ trackingManager: ARTrackingManager, didFailToFindLocationAfter elapsedSeconds: TimeInterval)
func logText(_ text: String)
}
/**
Class used internally by ARViewController for tracking and filtering location/heading/pitch etc.
ARViewController takes all these informations and stores them in ARViewController.arStatus object,
which is then passed to ARPresenter. Not intended for subclassing.
*/
public class ARTrackingManager: NSObject, CLLocationManagerDelegate
{
/**
Specifies how often are new annotations fetched and annotation views are recreated.
Default value is 50m.
*/
public var reloadDistanceFilter: CLLocationDistance! // Will be set in init
/**
Specifies how often are distances and azimuths recalculated for visible annotations. Stacking is also done on this which is heavy operation.
Default value is 15m.
*/
public var userDistanceFilter: CLLocationDistance! // Will be set in init
{
didSet
{
self.locationManager.distanceFilter = self.userDistanceFilter
}
}
/**
Filter(Smoothing) factor for heading in range 0-1. It affects horizontal movement of annotaion views. The lower the value the bigger the smoothing.
Value of 1 means no smoothing, should be greater than 0. Default value is 0.05
*/
public var headingFilterFactor: Double = 0.05
private var _headingFilterFactor: Double = 0.05
/**
Filter(Smoothing) factor for pitch in range 0-1. It affects vertical movement of annotaion views. The lower the value the bigger the smoothing.
Value of 1 means no smoothing, should be greater than 0. Default value is 0.05
*/
public var pitchFilterFactor: Double = 0.05
//===== Internal variables
/// Delegate
internal weak var delegate: ARTrackingManagerDelegate?
fileprivate(set) internal var locationManager: CLLocationManager = CLLocationManager()
/// Tracking state.
fileprivate(set) internal var tracking = false
/// Last detected user location
fileprivate(set) internal var userLocation: CLLocation?
/// Set automatically when heading changes. Also see filteredHeading.
fileprivate(set) internal var heading: Double = 0
/// Set in filterHeading. filterHeading must be called manually and often(display timer) bcs of filtering function.
fileprivate(set) internal var filteredHeading: Double = 0
/// Set in filterPitch. filterPitch must be called manually and often(display timer) bcs of filtering function.
fileprivate(set) internal var filteredPitch: Double = 0
/// If set, userLocation will return this value
internal var debugLocation: CLLocation?
/// If set, filteredHeading will return this value
internal var debugHeading: Double?
/// If set, filteredPitch will return this value
internal var debugPitch: Double?
/// Headings with greater headingAccuracy than this will be disregarded. In Degrees.
public var minimumHeadingAccuracy: Double = 120
/// Return value for locationManagerShouldDisplayHeadingCalibration.
public var allowCompassCalibration: Bool = false
/// Locations with greater horizontalAccuracy than this will be disregarded. In meters.
public var minimumLocationHorizontalAccuracy: Double = 500
/// Locations older than this will be disregarded. In seconds.
public var minimumLocationAge: Double = 30
//===== Private variables
fileprivate var motionManager: CMMotionManager = CMMotionManager()
fileprivate var previousAcceleration: CMAcceleration = CMAcceleration(x: 0, y: 0, z: 0)
fileprivate var reloadLocationPrevious: CLLocation?
fileprivate var reportLocationTimer: Timer?
fileprivate var reportLocationDate: TimeInterval?
fileprivate var locationSearchTimer: Timer? = nil
fileprivate var locationSearchStartTime: TimeInterval? = nil
fileprivate var catchupPitch = false;
fileprivate var headingStartDate: Date?
fileprivate var orientation: CLDeviceOrientation = CLDeviceOrientation.portrait
{
didSet
{
self.locationManager.headingOrientation = self.orientation
}
}
override init()
{
super.init()
self.initialize()
}
deinit
{
self.stopTracking()
NotificationCenter.default.removeObserver(self)
}
fileprivate func initialize()
{
// Defaults
self.reloadDistanceFilter = 50
self.userDistanceFilter = 15
// Setup location manager
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = CLLocationDistance(self.userDistanceFilter)
self.locationManager.headingFilter = 1
self.locationManager.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(ARTrackingManager.deviceOrientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
self.deviceOrientationDidChange()
}
@objc internal func deviceOrientationDidChange()
{
if let deviceOrientation = CLDeviceOrientation(rawValue: Int32(UIDevice.current.orientation.rawValue))
{
if deviceOrientation == .landscapeLeft || deviceOrientation == .landscapeRight || deviceOrientation == .portrait || deviceOrientation == .portraitUpsideDown
{
self.orientation = deviceOrientation
}
}
}
//==========================================================================================================================================================
// MARK: Tracking
//==========================================================================================================================================================
/**
Starts location and motion manager
- Parameter notifyFailure: If true, will call arTrackingManager:didFailToFindLocationAfter: if location is not found.
*/
public func startTracking(notifyLocationFailure: Bool = false)
{
self.resetAllTrackingData()
// Request authorization if state is not determined
if CLLocationManager.locationServicesEnabled()
{
if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.notDetermined
{
self.locationManager.requestWhenInUseAuthorization()
}
}
// Location search
if notifyLocationFailure
{
self.startLocationSearchTimer()
// Calling delegate with value 0 to be flexible, for example user might want to show indicator when search is starting.
self.delegate?.arTrackingManager(self, didFailToFindLocationAfter: 0)
}
// Debug
if let debugLocation = self.debugLocation
{
self.userLocation = debugLocation
}
// Start motion and location managers
self.motionManager.startAccelerometerUpdates()
self.locationManager.startUpdatingHeading()
self.locationManager.startUpdatingLocation()
self.tracking = true
}
/// Stops location and motion manager
public func stopTracking()
{
self.resetAllTrackingData()
// Stop motion and location managers
self.motionManager.stopAccelerometerUpdates()
self.locationManager.stopUpdatingHeading()
self.locationManager.stopUpdatingLocation()
self.tracking = false
}
/// Stops all timers and resets all data.
public func resetAllTrackingData()
{
self.stopLocationSearchTimer()
self.locationSearchStartTime = nil
self.stopReportLocationTimer()
self.reportLocationDate = nil
//self.reloadLocationPrevious = nil // Leave it, bcs of reload
self.previousAcceleration = CMAcceleration(x: 0, y: 0, z: 0)
self.userLocation = nil
self.heading = 0
self.filteredHeading = 0
self.filteredPitch = 0
// This will make filteredPitch catchup current pitch value on next heading calculation
self.catchupPitch = true
self.headingStartDate = nil
}
//==========================================================================================================================================================
// MARK: CLLocationManagerDelegate
//==========================================================================================================================================================
public func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading)
{
if newHeading.headingAccuracy < 0 || newHeading.headingAccuracy > self.minimumHeadingAccuracy
{
return
}
let previousHeading = self.heading
// filteredHeading is not updated here bcs this is not called too often. filterHeading method should be called manually
// with display timer.
if newHeading.trueHeading < 0
{
self.heading = fmod(newHeading.magneticHeading, 360.0)
}
else
{
self.heading = fmod(newHeading.trueHeading, 360.0)
}
/**
Handling unprecise readings, this whole section should prevent annotations from spinning because of
unprecise readings & filtering. e.g. if first reading is 10° and second is 80°, due to filtering, annotations
would move slowly from 10°-80°. So when we detect such situtation, we set _headingFilterFactor to 1, meaning that
filtering is temporarily disabled and annotatoions will immediately jump to new heading.
This is done only first 5 seconds after first heading.
*/
// First heading after tracking started. Catching up filteredHeading.
if self.headingStartDate == nil
{
self.headingStartDate = Date()
self.filteredHeading = self.heading
}
if let headingStartDate = self.headingStartDate // Always true
{
var recommendedHeadingFilterFactor = self.headingFilterFactor
let headingFilteringStartTime: TimeInterval = 5
// First 5 seconds after first heading?
if headingStartDate.timeIntervalSinceNow > -headingFilteringStartTime
{
// Disabling filtering if heading difference(current and previous) is > 10
if fabs(deltaAngle(self.heading, previousHeading)) > 10
{
recommendedHeadingFilterFactor = 1 // We could also just set self.filteredHeading = self.heading
}
}
_headingFilterFactor = recommendedHeadingFilterFactor
}
}
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
guard let location = locations.first else { return }
//===== Disregarding old and low quality location detections
let age = location.timestamp.timeIntervalSinceNow;
if age < -self.minimumLocationAge || location.horizontalAccuracy > self.minimumLocationHorizontalAccuracy || location.horizontalAccuracy < 0
{
print("Disregarding location: age: \(age), ha: \(location.horizontalAccuracy)")
return
}
// Location found, stop timer that is responsible for measuring how long location is not found.
self.stopLocationSearchTimer()
//===== Set current user location
self.userLocation = location
//self.userLocation = CLLocation(coordinate: location.coordinate, altitude: 95, horizontalAccuracy: 0, verticalAccuracy: 0, timestamp: Date())
if debugLocation != nil { self.userLocation = debugLocation }
if self.reloadLocationPrevious == nil { self.reloadLocationPrevious = self.userLocation }
//@DEBUG
/*if let location = self.userLocation
{
print("== \(location.horizontalAccuracy), \(age) \(location.coordinate.latitude), \(location.coordinate.longitude), \(location.altitude)" )
}*/
//===== Reporting location 5s after we get location, this will filter multiple locations calls and make only one delegate call
let reportIsScheduled = self.reportLocationTimer != nil
// First time, reporting immediately
if self.reportLocationDate == nil
{
self.reportLocationToDelegate()
}
// Report is already scheduled, doing nothing, it will report last location delivered in max 5s
else if reportIsScheduled
{
}
// Scheduling report in 5s
else
{
self.startReportLocationTimer()
}
}
public func locationManagerShouldDisplayHeadingCalibration(_ manager: CLLocationManager) -> Bool
{
return self.allowCompassCalibration
}
internal func stopReportLocationTimer()
{
self.reportLocationTimer?.invalidate()
self.reportLocationTimer = nil
}
internal func startReportLocationTimer()
{
self.stopReportLocationTimer()
self.reportLocationTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(ARTrackingManager.reportLocationToDelegate), userInfo: nil, repeats: false)
}
@objc internal func reportLocationToDelegate()
{
self.stopReportLocationTimer()
self.reportLocationDate = Date().timeIntervalSince1970
guard let userLocation = self.userLocation, let reloadLocationPrevious = self.reloadLocationPrevious else { return }
guard let reloadDistanceFilter = self.reloadDistanceFilter else { return }
if reloadLocationPrevious.distance(from: userLocation) > reloadDistanceFilter
{
self.reloadLocationPrevious = userLocation
self.delegate?.arTrackingManager(self, didUpdateReloadLocation: userLocation)
}
else
{
self.delegate?.arTrackingManager(self, didUpdateUserLocation: userLocation)
}
}
//==========================================================================================================================================================
// MARK: Calculations
//==========================================================================================================================================================
/// Returns filtered(low-pass) pitch in degrees. -90(looking down), 0(looking straight), 90(looking up)
internal func filterPitch()
{
guard self.debugPitch == nil else { return }
guard let accelerometerData = self.motionManager.accelerometerData else { return }
let acceleration: CMAcceleration = accelerometerData.acceleration
// First real reading after startTracking? Making filter catch up
if self.catchupPitch && (acceleration.x != 0 || acceleration.y != 0 || acceleration.z != 0)
{
self.previousAcceleration = acceleration
self.catchupPitch = false
}
// Low-pass filter - filtering data so it is not jumping around
let pitchFilterFactor: Double = self.pitchFilterFactor
self.previousAcceleration.x = (acceleration.x * pitchFilterFactor) + (self.previousAcceleration.x * (1.0 - pitchFilterFactor));
self.previousAcceleration.y = (acceleration.y * pitchFilterFactor) + (self.previousAcceleration.y * (1.0 - pitchFilterFactor));
self.previousAcceleration.z = (acceleration.z * pitchFilterFactor) + (self.previousAcceleration.z * (1.0 - pitchFilterFactor));
let deviceOrientation = self.orientation
var angle: Double = 0
if deviceOrientation == CLDeviceOrientation.portrait
{
angle = atan2(self.previousAcceleration.y, self.previousAcceleration.z)
}
else if deviceOrientation == CLDeviceOrientation.portraitUpsideDown
{
angle = atan2(-self.previousAcceleration.y, self.previousAcceleration.z)
}
else if deviceOrientation == CLDeviceOrientation.landscapeLeft
{
angle = atan2(self.previousAcceleration.x, self.previousAcceleration.z)
}
else if deviceOrientation == CLDeviceOrientation.landscapeRight
{
angle = atan2(-self.previousAcceleration.x, self.previousAcceleration.z)
}
angle = radiansToDegrees(angle)
angle += 90
// Not really needed but, if pointing device down it will return 0...-30...-60...270...240 but like this it returns 0...-30...-60...-90...-120
if(angle > 180) { angle -= 360 }
// Even more filtering, not sure if really needed //@TODO
self.filteredPitch = (self.filteredPitch + angle) / 2.0
}
internal func filterHeading()
{
let headingFilterFactor = _headingFilterFactor
let previousFilteredHeading = self.filteredHeading
let newHeading = self.debugHeading ?? self.heading
/*
Low pass filter on heading cannot be done by using regular formula because our input(heading)
is circular so we would have problems on heading passing North(0). Example:
newHeading = 350
previousHeading = 10
headingFilterFactor = 0.5
filteredHeading = 10 * 0.5 + 350 * 0.5 = 180 NOT OK - IT SHOULD BE 0
First solution is to instead of passing 350 to the formula, we pass -10.
Second solution is to not use 0-360 degrees but to express values with sine and cosine.
*/
/*
Second solution
let newHeadingRad = degreesToRadians(newHeading)
self.filteredHeadingSin = sin(newHeadingRad) * headingFilterFactor + self.filteredHeadingSin * (1 - headingFilterFactor)
self.filteredHeadingCos = cos(newHeadingRad) * headingFilterFactor + self.filteredHeadingCos * (1 - headingFilterFactor)
self.filteredHeading = radiansToDegrees(atan2(self.filteredHeadingSin, self.filteredHeadingCos))
self.filteredHeading = normalizeDegree(self.filteredHeading)
*/
var newHeadingTransformed = newHeading
if fabs(newHeading - previousFilteredHeading) > 180
{
if previousFilteredHeading < 180 && newHeading > 180
{
newHeadingTransformed -= 360
}
else if previousFilteredHeading > 180 && newHeading < 180
{
newHeadingTransformed += 360
}
}
self.filteredHeading = (newHeadingTransformed * headingFilterFactor) + (previousFilteredHeading * (1.0 - headingFilterFactor))
self.filteredHeading = normalizeDegree(self.filteredHeading)
}
internal func catchupHeadingPitch()
{
self.catchupPitch = true
self.filteredHeading = self.debugHeading ?? self.heading
}
//@TODO rename to heading
internal func azimuthFromUserToLocation(userLocation: CLLocation, location: CLLocation, approximate: Bool = false) -> Double
{
var azimuth: Double = 0
if approximate
{
azimuth = self.approximateBearingBetween(startLocation: userLocation, endLocation: location)
}
else
{
azimuth = self.bearingBetween(startLocation: userLocation, endLocation: location)
}
return azimuth;
}
/**
Precise bearing between two points.
*/
internal func bearingBetween(startLocation : CLLocation, endLocation : CLLocation) -> Double
{
var azimuth: Double = 0
let lat1 = degreesToRadians(startLocation.coordinate.latitude)
let lon1 = degreesToRadians(startLocation.coordinate.longitude)
let lat2 = degreesToRadians(endLocation.coordinate.latitude)
let lon2 = degreesToRadians(endLocation.coordinate.longitude)
let dLon = lon2 - lon1
let y = sin(dLon) * cos(lat2)
let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)
let radiansBearing = atan2(y, x)
azimuth = radiansToDegrees(radiansBearing)
if(azimuth < 0) { azimuth += 360 }
return azimuth
}
/**
Approximate bearing between two points, good for small distances(<10km).
This is 30% faster than bearingBetween but it is not as precise. Error is about 1 degree on 10km, 5 degrees on 300km, depends on location...
It uses formula for flat surface and multiplies it with LAT_LON_FACTOR which "simulates" earth curvature.
*/
internal func approximateBearingBetween(startLocation: CLLocation, endLocation: CLLocation) -> Double
{
var azimuth: Double = 0
let startCoordinate: CLLocationCoordinate2D = startLocation.coordinate
let endCoordinate: CLLocationCoordinate2D = endLocation.coordinate
let latitudeDistance: Double = startCoordinate.latitude - endCoordinate.latitude;
let longitudeDistance: Double = startCoordinate.longitude - endCoordinate.longitude;
azimuth = radiansToDegrees(atan2(longitudeDistance, (latitudeDistance * Double(LAT_LON_FACTOR))))
azimuth += 180.0
return azimuth
}
internal func startDebugMode(location: CLLocation? = nil, heading: Double? = nil, pitch: Double? = nil)
{
if let location = location
{
self.debugLocation = location
self.userLocation = location
}
if let heading = heading
{
self.debugHeading = heading
//self.filteredHeading = heading // Don't, it is different for heading bcs we are also simulating low pass filter
}
if let pitch = pitch
{
self.debugPitch = pitch
self.filteredPitch = pitch
}
}
internal func stopDebugMode()
{
self.debugLocation = nil
self.userLocation = nil
self.debugHeading = nil
self.debugPitch = nil
}
//==========================================================================================================================================================
// MARK: Location search
//==========================================================================================================================================================
internal func startLocationSearchTimer(resetStartTime: Bool = true)
{
self.stopLocationSearchTimer()
if resetStartTime
{
self.locationSearchStartTime = Date().timeIntervalSince1970
}
self.locationSearchTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(ARTrackingManager.locationSearchTimerTick), userInfo: nil, repeats: false)
}
internal func stopLocationSearchTimer(resetStartTime: Bool = true)
{
self.locationSearchTimer?.invalidate()
self.locationSearchTimer = nil
}
@objc internal func locationSearchTimerTick()
{
guard let locationSearchStartTime = self.locationSearchStartTime else { return }
let elapsedSeconds = Date().timeIntervalSince1970 - locationSearchStartTime
self.startLocationSearchTimer(resetStartTime: false)
self.delegate?.arTrackingManager(self, didFailToFindLocationAfter: elapsedSeconds)
}
}
| apache-2.0 | 5c5b3db6aa0fda0f8c5701ab6194bd53 | 40.441077 | 188 | 0.618866 | 5.604736 | false | false | false | false |
Vaberer/Font-Awesome-Swift | Example/AF Swift/ViewController.swift | 1 | 3549 | //
// ViewController.swift
// AF Swift
//
// Created by Patrik Vaberer on 7/13/15.
// Copyright (c) 2015 Patrik Vaberer. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating, UISearchControllerDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var bGithub: UIBarButtonItem!
@IBOutlet weak var bTwitter: UIBarButtonItem!
private var filteredData = [String]()
var resultSearchController = UISearchController()
override func viewDidLoad() {
super.viewDidLoad()
initialize()
bGithub.setFAIcon(icon: FAType.FAGithub, iconSize: 35)
bTwitter.setFAIcon(icon: FAType.FATwitter, iconSize: 35)
}
@IBAction func bGithubPressed(sender: UIBarButtonItem) {
if let requestUrl = NSURL(string: "https://github.com/Vaberer/Font-Awesome-Swift") {
UIApplication.shared.openURL(requestUrl as URL)
}
}
@IBAction func bTwitterPressed(sender: UIBarButtonItem) {
if let twitterURL = NSURL(string: "twitter://user?id=2271666416") {
if UIApplication.shared.canOpenURL(twitterURL as URL) {
UIApplication.shared.openURL(twitterURL as URL)
} else if let requestUrl = NSURL(string: "https://twitter.com/vaberer") {
UIApplication.shared.openURL(requestUrl as URL)
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let c = tableView.dequeueReusableCell(withIdentifier: "IconCell") as! IconCell
c.lFont.text = resultSearchController.isActive ? filteredData[indexPath.row] : Helper.FANames[indexPath.row]
guard let icon = resultSearchController.isActive ? FAType(rawValue: Helper.FANames.index(of: filteredData[indexPath.row])!) : FAType(rawValue: indexPath.row) else {
return UITableViewCell()
}
c.lSmall.FAIcon = icon
c.lMedium.FAIcon = icon
c.lBig.FAIcon = icon
c.iIcon.setFAIconWithName(icon: icon, textColor: UIColor.black)
return c
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resultSearchController.isActive ? filteredData.count : FAType.count
}
func updateSearchResults(for searchController: UISearchController) {
filteredData = []
filterContentForSearchText(searchText: searchController.searchBar.text!.lowercased())
self.tableView.reloadData()
}
private func initialize() {
resultSearchController = UISearchController(searchResultsController: nil)
resultSearchController.searchResultsUpdater = self
resultSearchController.delegate = self
resultSearchController.dimsBackgroundDuringPresentation = false
resultSearchController.searchBar.sizeToFit()
resultSearchController.searchBar.searchBarStyle = .minimal
resultSearchController.searchBar.barTintColor = UIColor.blue
resultSearchController.searchBar.placeholder = "Type Icon Name"
tableView.tableHeaderView = resultSearchController.searchBar
}
private func filterContentForSearchText(searchText: String) {
for f in Helper.FANames {
if f.lowercased().range(of: searchText.lowercased()) != nil {
filteredData.append(f)
}
}
}
}
| mit | 861fecaacb607da82d395961ca0a6ea3 | 38 | 172 | 0.673147 | 4.991561 | false | false | false | false |
atuooo/notGIF | notGIF/Views/GIFDetail/GIFDetailToolView.swift | 1 | 9809 | //
// GIFDetailToolView.swift
// notGIF
//
// Created by Atuooo on 19/07/2017.
// Copyright © 2017 xyz. All rights reserved.
//
import UIKit
protocol GIFDetailToolViewDelegate: class {
func changePlaySpeed(_ speed: TimeInterval)
func changePlayState(playing: Bool)
func removeTagOrGIF()
func showAllFrame()
func shareTo(_ type: GIFActionType.ShareType)
func addTag()
}
class GIFDetailToolView: UIView {
enum ToolActionType: Int {
case remove
case addTag
case share
case showAllFrame
case max
}
weak fileprivate var delegate: GIFDetailToolViewDelegate?
fileprivate let height: CGFloat = 86
fileprivate let maxSpeed: TimeInterval = 0.005
fileprivate let minSpeed: TimeInterval = 0.50
fileprivate var isInDefaultTag: Bool {
return NGUserDefaults.lastSelectTagID == Config.defaultTagID
}
fileprivate var originSpeed: TimeInterval = 1
fileprivate var currentSpeed: TimeInterval = 0.005 {
didSet {
let multiple = currentSpeed/originSpeed
let speedInfo = String(format: "%.1fx\n%.3fs", multiple, currentSpeed)
speedLabel.text = speedInfo
}
}
fileprivate lazy var playButton: PlayControlButton = {
return PlayControlButton(showPlay: false, outerDia: 22) { [weak self] isPaused in
self?.delegate?.changePlayState(playing: !isPaused)
}
}()
fileprivate lazy var speedLabel: UILabel = {
let label = UILabel()
label.textColor = UIColor.textTint
label.font = UIFont.menlo(ofSize: 14)
label.numberOfLines = 2
label.textAlignment = .center
return label
}()
fileprivate lazy var speedSlider: UISlider = {
let slider = UISlider()
slider.thumbTintColor = UIColor.textTint
slider.tintColor = UIColor.textTint
slider.maximumValue = 0.50
slider.minimumValue = 0.005
slider.minimumTrackTintColor = UIColor.textTint.withAlphaComponent(0.7)
slider.maximumTrackTintColor = UIColor.textTint.withAlphaComponent(0.7)
slider.setThumbImage(#imageLiteral(resourceName: "icon_slider_thumb"), for: .normal)
slider.setThumbImage(#imageLiteral(resourceName: "icon_slider_thumb"), for: .highlighted)
slider.setThumbImage(#imageLiteral(resourceName: "icon_slider_thumb"), for: .selected)
slider.addTarget(self, action: #selector(GIFDetailToolView.sliderValueChanged(sender:)), for: .valueChanged)
return slider
}()
fileprivate lazy var shareBar: UIView = {
let view = UIView()
view.backgroundColor = UIColor.barTint
return view
}()
init(delegate: GIFDetailToolViewDelegate? = nil) {
super.init(frame: CGRect(x: 0, y: kScreenHeight, width: kScreenWidth, height: height))
makeUI()
self.delegate = delegate
}
deinit {
printLog("deinited")
}
// MARK: - Public Action
func reset(withSpeed speed: TimeInterval) {
playButton.setPlayState(playing: true)
if speed <= 0 {
speedLabel.text = "..."
} else {
originSpeed = speed
currentSpeed = originSpeed
speedSlider.setValue(Float(speed), animated: true)
}
}
// MARK: - Control Handler
func toolButtonClicked(button: UIButton) {
guard let actionType = ToolActionType(rawValue: button.tag) else { return }
switch actionType {
case .addTag:
delegate?.addTag()
case .remove:
delegate?.removeTagOrGIF()
case .showAllFrame:
delegate?.showAllFrame()
case .share:
showShareBar()
default:
break
}
}
func shareButtonClicked(button: UIButton) {
guard let shareType = GIFActionType.ShareType(rawValue: button.tag) else { return }
hideShareBarButtonClicked()
delegate?.shareTo(shareType)
}
func hideShareBarButtonClicked() {
UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: -0.2, options: [.curveEaseInOut], animations: {
self.shareBar.transform = CGAffineTransform(translationX: 0, y: self.height)
}, completion: nil)
}
func sliderValueChanged(sender: UISlider) {
currentSpeed = TimeInterval(sender.value)
delegate?.changePlaySpeed(currentSpeed)
}
// MARK: - Helper Methods
fileprivate func makeUI() {
let sliderH: CGFloat = height * 0.4
backgroundColor = UIColor.barTint
// tool buttons
let toolButtonStackView = UIStackView()
toolButtonStackView.distribution = .fillEqually
for i in 0..<ToolActionType.max.rawValue {
guard let actionType = ToolActionType(rawValue: i) else { return }
let toolButton = UIButton()
switch actionType {
case .remove:
toolButton.setImage(isInDefaultTag ? #imageLiteral(resourceName: "icon_delete_gif") : #imageLiteral(resourceName: "icon_remove_tag"), for: .normal)
case .addTag:
toolButton.setImage(#imageLiteral(resourceName: "icon_add_tag"), for: .normal)
case .share:
toolButton.setAwesomeIcon(iconCode: .share, color: UIColor.textTint, fontSize: 22)
case .showAllFrame:
toolButton.setImage(#imageLiteral(resourceName: "icon_all_frame"), for: .normal)
default:
break
}
toolButton.tag = i
toolButton.tintColor = UIColor.textTint
toolButton.addTarget(self, action: #selector(GIFDetailToolView.toolButtonClicked(button:)), for: .touchUpInside)
toolButtonStackView.addArrangedSubview(toolButton)
}
addSubview(toolButtonStackView)
toolButtonStackView.snp.makeConstraints { make in
make.bottom.equalTo(0)
make.centerX.equalTo(self)
make.width.equalTo(kScreenWidth*0.8)
make.height.equalTo(height-sliderH)
}
playButton.center = CGPoint(x: kScreenWidth*0.1, y: sliderH*0.66)
addSubview(playButton)
addSubview(speedLabel)
speedLabel.text = "0.38s"
speedLabel.snp.makeConstraints { make in
make.right.equalTo(0)
make.centerY.equalTo(playButton)
make.width.equalTo(kScreenWidth*0.2)
}
addSubview(speedSlider)
speedSlider.snp.makeConstraints { make in
make.width.equalTo(kScreenWidth * 0.6)
make.centerX.equalTo(self)
make.centerY.equalTo(playButton)
}
}
fileprivate func setShareBar() {
var shareTypes: [GIFActionType.ShareType] = [.more, .twitter, .weibo, .wechat, .message]
if !OpenShare.canOpen(.wechat) {
shareTypes.remove(.wechat)
}
let hideButton = UIButton(type: .system)
hideButton.setImage(#imageLiteral(resourceName: "icon_slide_down"), for: .normal)
hideButton.tintColor = UIColor.textTint.withAlphaComponent(0.8)
hideButton.addTarget(self, action: #selector(GIFDetailToolView.hideShareBarButtonClicked), for: [.touchUpInside])
let stackView = UIStackView()
stackView.distribution = .fillEqually
for item in shareTypes {
let button = UIButton(iconCode: item.iconCode, color: UIColor.textTint, fontSize: 30)
button.tag = item.rawValue
button.backgroundColor = UIColor.barTint
button.addTarget(self, action: #selector(GIFDetailToolView.shareButtonClicked(button:)), for: .touchUpInside)
stackView.addArrangedSubview(button)
}
shareBar.addSubview(hideButton)
shareBar.addSubview(stackView)
addSubview(shareBar)
hideButton.snp.makeConstraints { make in
make.right.left.top.equalTo(shareBar)
make.height.equalTo(30)
}
stackView.snp.makeConstraints { make in
make.right.left.equalTo(shareBar)
make.height.equalTo(height*0.5)
make.bottom.equalTo(-height*0.2)
}
shareBar.snp.makeConstraints { make in
make.edges.equalTo(self)
}
}
fileprivate func showShareBar() {
if !shareBar.isDescendant(of: self) {
shareBar.transform = CGAffineTransform(translationX: 0, y: height)
setShareBar()
}
UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.6, options: [], animations: {
self.shareBar.transform = .identity
}, completion: nil)
}
// MARK: - Animation
public func animate() {
UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 2, options: [.curveEaseInOut], animations: {
self.frame.origin.y = kScreenHeight - self.height
}, completion: nil)
}
public func setHidden(_ shouldHide: Bool, animated: Bool) {
if animated {
UIView.animate(withDuration: 0.3, animations: {
self.frame.origin.y = shouldHide ? kScreenHeight : kScreenHeight - self.height
})
} else {
frame.origin.y = shouldHide ? kScreenHeight : kScreenHeight - height
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | ae65cfd489064a07d7aeaae4c1c2bce4 | 33.903915 | 163 | 0.612561 | 4.733591 | false | false | false | false |
xilosada/TravisViewerIOS | TVModel/Storage.swift | 1 | 3514 | //
// Storage.swift
// TravisViewerIOS
//
// Created by X.I. Losada on 13/02/16.
// Copyright © 2016 XiLosada. All rights reserved.
//
import RxSwift
///Implementation of the Storaging protocol
public class Storage: Storaging {
private let diskStorage: DiskStoraging!
private let cloudStorage: Networking!
private let disposeBag: DisposeBag = DisposeBag()
private var cachedUser: UserEntity?
private enum Errors: ErrorType {
case InvalidQueryLength
}
public init(diskStorage: DiskStoraging, cloudStorage: Networking){
self.diskStorage = diskStorage
self.cloudStorage = cloudStorage
}
public func getUser(username:String) -> Observable<UserEntity> {
if let user = cachedUser {
if user.name == username {
return Observable.just(user)
}
}
return getUserAfterFlush(username)
}
private func getUserAfterFlush(username:String) -> Observable<UserEntity>{
diskStorage.flushDb().subscribe().dispose()
return self.getUserInternal(username)
}
private func getUserInternal(username:String) -> Observable<UserEntity>{
if username.isEmpty {
return Observable.empty()
}
return diskStorage.loadUser(username).catchError{ (error) -> Observable<UserEntity> in
self.downloadAndSaveUser(username)
}
}
public func getRepos(username:String) -> Observable<[RepositoryEntity]>{
return getUserInternal(username).map{
$0.repos
}
}
public func getBuilds(repoId:Int) -> Observable<[BuildEntity]>{
return diskStorage.loadRepo(repoId).map{
$0.builds
}
}
private func downloadAndSaveUser(username: String) -> Observable<UserEntity> {
return downloadUser(username).flatMap{ (user) -> Observable<UserEntity> in
self.cachedUser = user
return self.saveUserEntity(user)
}
}
private func downloadUser(username:String) -> Observable<UserEntity> {
return Observable.zip(cloudStorage.searchUser(username), downloadRepos(username), resultSelector: {
user, repos in
var userCopy = UserEntity(name: user.name, avatarUrl: user.avatarUrl)
userCopy.repos = repos
return userCopy
})
}
private func saveUserEntity(user: UserEntity) -> Observable<UserEntity> {
return diskStorage.saveUser(user).map{ _ in user }
}
private func downloadRepos(username:String) -> Observable<[RepositoryEntity]> {
return downloadBuilds(fromObservableArrayToObservable(cloudStorage.requestRepositories(username))).toArray()
}
private func fromObservableArrayToObservable<T>(observable: Observable<[T]>) -> Observable<T> {
return observable.flatMap { array in
return array.toObservable()
}
}
private func downloadBuilds(repoObservable: Observable<RepositoryEntity>) -> Observable<RepositoryEntity> {
return repoObservable
.flatMap { repo in
return Observable.zip(
Observable.just(repo),
self.cloudStorage.requestBuilds(repo.slug),
resultSelector:{ (var repo, builds) in
repo.builds = builds
return repo
})
}
}
} | mit | 1946ff73a2d8c2094a6e2f38844d16b7 | 31.238532 | 116 | 0.615998 | 4.879167 | false | false | false | false |
DeveloperLx/LxTabBadgePoint-swift | LxTabBadgePointDemo/LxTabBadgePointDemo/ViewController.swift | 1 | 2523 | //
// ViewController.swift
// LxTabBadgePointDemo
//
// Created by DeveloperLx on 15/12/1.
// Copyright © 2015年 DeveloperLx. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red: CGFloat(arc4random()%256)/CGFloat(256.0), green: CGFloat(arc4random()%256)/CGFloat(256.0), blue: CGFloat(arc4random()%256)/CGFloat(256.0), alpha: 1)
let handleTabPointButton = UIButton(type: .Custom)
handleTabPointButton.showsTouchWhenHighlighted = true
handleTabPointButton.titleLabel?.font = UIFont.systemFontOfSize(20)
handleTabPointButton.backgroundColor = UIColor.whiteColor()
handleTabPointButton.setTitle("show badge view", forState: .Normal)
handleTabPointButton.setTitle("hide badge view", forState: .Selected)
handleTabPointButton.setTitleColor(view.backgroundColor, forState: .Normal)
handleTabPointButton.addTarget(self, action: Selector("handleTabPointButtonClicked:"), forControlEvents: .TouchUpInside)
view.addSubview(handleTabPointButton)
handleTabPointButton.translatesAutoresizingMaskIntoConstraints = false
let handleTabPointButtonCenterXConstraint = NSLayoutConstraint(item: handleTabPointButton, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0)
let handleTabPointButtonCenterYConstraint = NSLayoutConstraint(item: handleTabPointButton, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: 0)
let handleTabPointButtonWidthConstraint = NSLayoutConstraint(item: handleTabPointButton, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: 180)
let handleTabPointButtonHeightConstraint = NSLayoutConstraint(item: handleTabPointButton, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: 60)
view.addConstraints([handleTabPointButtonCenterXConstraint,
handleTabPointButtonCenterYConstraint,
handleTabPointButtonWidthConstraint,
handleTabPointButtonHeightConstraint])
}
func handleTabPointButtonClicked(btn: UIButton) {
if let nc = navigationController {
nc.showTabBadgePoint = !nc.showTabBadgePoint
btn.selected = nc.showTabBadgePoint
}
}
}
| mit | 2612e2b5bed52544dbc539df37c74e0f | 49.4 | 201 | 0.727778 | 4.701493 | false | false | false | false |
magfurulabeer/CalcuLayout | CalcuLayout/InfixOperations.swift | 1 | 11079 | //
// InfixOperations.swift
// CalcuLayout
//
// Created by Magfurul Abeer on 11/30/16.
// Copyright © 2016 Magfurul Abeer. All rights reserved.
//
import UIKit
// TODO: Add >= and <= Anchor to Modifiers
// TODO: Add ^ for Doubles and Ints
// MARK: Declarations
precedencegroup ConstraintPrecedence {
associativity: left
higherThan: AssignmentPrecedence
}
/// Practically equivalent to constraintEqualToAnchor.
infix operator <> : ConstraintPrecedence
/// Practically equivalent to constraintGreaterThanOrEqualToAnchor.
infix operator >> : ConstraintPrecedence
/// Practically equivalent to constraintLessThanOrEqualToAnchor.
infix operator << : ConstraintPrecedence
// MARK: Operators
public func += (view: UIView, anchor: Anchor) -> NSLayoutConstraint {
let constraint = NSLayoutConstraint(item: view,
attribute: anchor.attribute,
relatedBy: .equal,
toItem: anchor.view,
attribute: anchor.attribute,
multiplier: 1,
constant: 0)
constraint.isActive = true
return constraint
}
public func += (view: UIView, anchors: [Anchor]) -> [NSLayoutConstraint] {
var constraints = [NSLayoutConstraint]()
for anchor in anchors {
let constraint = (view += anchor)
constraints.append(constraint)
}
return constraints
}
// MARK: Anchor Operators
/// Practically equivalent to constraintEqualToAnchor. Discouraged to use this due to == usually being used for comparison.
public func == (firstAnchor: Anchor, secondAnchor: Anchor) -> NSLayoutConstraint {
firstAnchor.view.translatesAutoresizingMaskIntoConstraints = false
let constraint = NSLayoutConstraint(item: firstAnchor.view,
attribute: firstAnchor.attribute,
relatedBy: .equal,
toItem: secondAnchor.view,
attribute: secondAnchor.attribute,
multiplier: 1,
constant: 0)
constraint.isActive = (firstAnchor.autoActivateConstraints || secondAnchor.autoActivateConstraints) ? true: false
return constraint
}
/// Practically equivalent to constraintEqualToAnchor
public func <> (firstAnchor: Anchor, secondAnchor: Anchor) -> NSLayoutConstraint {
return firstAnchor == secondAnchor
}
/// Practically equivalent to constraintEqualToAnchor. Discouraged to use this due to == usually being used for comparison.
public func == (firstAnchor: Anchor, constant: LayoutModifier) -> NSLayoutConstraint {
firstAnchor.view.translatesAutoresizingMaskIntoConstraints = false
var constraint = NSLayoutConstraint(item: firstAnchor.view,
attribute: firstAnchor.attribute,
relatedBy: .equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: CGFloat(constant.value))
constraint = constraint.runAttachedOperations(constant.attachedOperations)
return constraint
}
/// Practically equivalent to constraintEqualToAnchor.
public func <> (firstAnchor: Anchor, constant: LayoutModifier) -> NSLayoutConstraint {
return firstAnchor == constant
}
/// Practically equivalent to constraintGreaterThanOrEqualToAnchor. Discouraged to use this due to >= usually being used for comparison.
public func >= (firstAnchor: Anchor, secondAnchor: Anchor) -> NSLayoutConstraint {
let constraint = NSLayoutConstraint(item: firstAnchor.view,
attribute: firstAnchor.attribute,
relatedBy: .greaterThanOrEqual,
toItem: secondAnchor.view,
attribute: secondAnchor.attribute,
multiplier: 1,
constant: 0)
constraint.isActive = (firstAnchor.autoActivateConstraints || secondAnchor.autoActivateConstraints) ? true: false
return constraint
}
/// Practically equivalent to constraintGreaterThanOrEqualToAnchor.
public func >> (firstAnchor: Anchor, secondAnchor: Anchor) -> NSLayoutConstraint {
return firstAnchor >= secondAnchor
}
/// Practically equivalent to constraintLessThanOrEqualToAnchor. Discouraged to use this due to <= usually being used for comparison.
public func <= (firstAnchor: Anchor, secondAnchor: Anchor) -> NSLayoutConstraint {
let constraint = NSLayoutConstraint(item: firstAnchor.view,
attribute: firstAnchor.attribute,
relatedBy: .lessThanOrEqual,
toItem: secondAnchor.view,
attribute: secondAnchor.attribute,
multiplier: 1,
constant: 0)
constraint.isActive = (firstAnchor.autoActivateConstraints || secondAnchor.autoActivateConstraints) ? true: false
return constraint
}
/// Practically equivalent to constraintLessThanOrEqualToAnchor.
public func << (firstAnchor: Anchor, secondAnchor: Anchor) -> NSLayoutConstraint {
return firstAnchor <= secondAnchor
}
// MARK: NSLayoutConstraint-LayoutModifier Operators
/// Adds LayoutModifier to NSLayoutConstraints constant value. Also adds all other attached LayoutModifiers and Activators.
public func + (constraint: NSLayoutConstraint, constant: LayoutModifier) -> NSLayoutConstraint {
var newConstraint = NSLayoutConstraint(item: constraint.firstItem,
attribute: constraint.firstAttribute,
relatedBy: constraint.relation,
toItem: constraint.secondItem,
attribute: constraint.secondAttribute,
multiplier: constraint.multiplier,
constant: constraint.constant + CGFloat(constant.value) )
newConstraint = newConstraint.runAttachedOperations(constant.attachedOperations)
return newConstraint
}
/// Subtracts LayoutModifier from NSLayoutConstraints constant value. Also adds all other attached LayoutModifiers and Activators.
public func - (constraint: NSLayoutConstraint, constant: LayoutModifier) -> NSLayoutConstraint {
var newConstraint = NSLayoutConstraint(item: constraint.firstItem,
attribute: constraint.firstAttribute,
relatedBy: constraint.relation,
toItem: constraint.secondItem,
attribute: constraint.secondAttribute,
multiplier: constraint.multiplier,
constant: constraint.constant - CGFloat(constant.value) )
newConstraint = newConstraint.runAttachedOperations(constant.attachedOperations)
return newConstraint
}
/// Multiplies NSLayoutConstraints multiplier by LayoutModifier value. Also adds all other attached LayoutModifiers and Activators.
public func * (constraint: NSLayoutConstraint, multiplier: LayoutModifier) -> NSLayoutConstraint {
var newConstraint = NSLayoutConstraint(item: constraint.firstItem,
attribute: constraint.firstAttribute,
relatedBy: constraint.relation,
toItem: constraint.secondItem,
attribute: constraint.secondAttribute,
multiplier: constraint.multiplier * CGFloat(multiplier.value),
constant: constraint.constant )
newConstraint = newConstraint.runAttachedOperations(multiplier.attachedOperations)
return newConstraint
}
/// Divides NSLayoutConstraints multiplier by LayoutModifier value. Also adds all other attached LayoutModifiers and Activators.
public func / (constraint: NSLayoutConstraint, multiplier: LayoutModifier) -> NSLayoutConstraint {
var newConstraint = NSLayoutConstraint(item: constraint.firstItem,
attribute: constraint.firstAttribute,
relatedBy: constraint.relation,
toItem: constraint.secondItem,
attribute: constraint.secondAttribute,
multiplier: constraint.multiplier / CGFloat(multiplier.value),
constant: constraint.constant )
newConstraint = newConstraint.runAttachedOperations(multiplier.attachedOperations)
return newConstraint
}
// MARK: LayoutModifier-LayoutModifier Operators
/// Stores second LayoutModifer(as an addConstant) and attached operations in First Modifier
public func + (firstModifier: LayoutModifier, secondModifier: LayoutModifier) -> LayoutModifier {
return operation(firstModifier, secondModifier: secondModifier, function: ConstraintFunction.addConstant(secondModifier.value))
}
/// Stores second LayoutModifer(as an subtractConstant) and attached operations in First Modifier
public func - (firstModifier: LayoutModifier, secondModifier: LayoutModifier) -> LayoutModifier {
return operation(firstModifier, secondModifier: secondModifier, function: ConstraintFunction.subtractConstant(secondModifier.value))
}
/// Stores second LayoutModifer(as an multiplyConstant) and attached operations in First Modifier
public func * (firstModifier: LayoutModifier, secondModifier: LayoutModifier) -> LayoutModifier {
return operation(firstModifier, secondModifier: secondModifier, function: ConstraintFunction.multiplyConstant(secondModifier.value))
}
/// Stores second LayoutModifer(as an divideConstant) and attached operations in First Modifier
public func / (firstModifier: LayoutModifier, secondModifier: LayoutModifier) -> LayoutModifier {
return operation(firstModifier, secondModifier: secondModifier, function: ConstraintFunction.divideConstant(secondModifier.value))
}
/// Adds appropriate Operation to firstModifier.
private func operation(_ firstModifier: LayoutModifier, secondModifier: LayoutModifier, function: ConstraintFunction) -> LayoutModifier {
firstModifier.attachedOperations.append(function)
firstModifier.attachedOperations += secondModifier.attachedOperations
return firstModifier
}
| mit | 37e4d0ce78d59de5b85ae10712345165 | 46.75 | 137 | 0.635855 | 6.171588 | false | false | false | false |
AlexMcArdle/LooseFoot | LooseFoot/ViewControllers/AMSearchViewController.swift | 1 | 4371 | //
// AMSearchViewController.swift
// LooseFoot
//
// Created by Alexander McArdle on 2/10/17.
// Copyright © 2017 Alexander McArdle. All rights reserved.
//
import UIKit
import AsyncDisplayKit
import Toaster
import Popover
class AMSearchViewController: ASViewController<ASTableNode> {
let tableNode = ASTableNode()
var subreddits: [AMSubreddit]?
var redditLoader: RedditLoader?
var popover: Popover?
var subredditViewController: AMSubredditViewController?
override func viewDidLoad() {
super.viewDidLoad()
print(redditLoader)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print(redditLoader)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.tableNode.view.frame = self.view.frame
print(redditLoader)
}
init(rl: RedditLoader) {
redditLoader = rl
super.init(node: tableNode)
//self.redditLoader = redditLoader
//parent as! AMSubredditViewController
tableNode.backgroundColor = UIColor.flatGrayDark
tableNode.delegate = self
tableNode.dataSource = self
tableNode.view.separatorStyle = .none
tableNode.frame = self.view.bounds
self.redditLoader?.searchDelegate = self
if(self.redditLoader?.subreddits.count == 0 ) {
Toast(text: "Fetching subs").show()
self.redditLoader?.getUserSubreddits(user: (self.redditLoader?.names[0])!)
} else {
print("found subs")
subreddits = self.redditLoader?.subreddits
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//override func
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension AMSearchViewController: RedditLoaderDelegate {
func redditLoaderDidUpdateLinks(redditLoader: RedditLoader) {
//adapter.performUpdates(animated: true)
//print("donezo")
//tableNode.reloadData()
}
func redditLoaderDidSelectLink(redditLoader: RedditLoader) {
//adapter.reloadObjects(redditLoader.posts)
}
func redditLoaderDidVote(redditLoader: RedditLoader, link: AMLink) {
//adapter.reloadObjects(redditLoader.posts)
}
func redditLoaderDidReturnToPosts(redditLoader: RedditLoader) {
//adapter.reloadObjects(redditLoader.posts)
}
func redditLoaderDidUpdateComments(redditLoader: RedditLoader, comments: [AMComment]) {
//adapter.performUpdates(animated: true)
}
func redditLoaderDidUpdateSubreddits(redditLoader: RedditLoader) {
print("donezo subreddits")
tableNode.reloadData()
}
}
extension AMSearchViewController: ASTableDataSource {
func tableNode(_ tableNode: ASTableNode, numberOfRowsInSection section: Int) -> Int {
//return layoutExamples.count
let countOfSubs = redditLoader?.subreddits.count ?? 0
print("s: \(section) count: \(countOfSubs)")
return countOfSubs
}
func tableNode(_ tableNode: ASTableNode, nodeForRowAt indexPath: IndexPath) -> ASCellNode {
let tempSub = redditLoader?.subreddits[indexPath.row]
return AMSearchCellNode(sub: tempSub!)
}
}
extension AMSearchViewController: ASTableDelegate {
func tableNode(_ tableNode: ASTableNode, didSelectRowAt indexPath: IndexPath) {
//let layoutExampleType = (tableNode.nodeForRow(at: indexPath) as! AMLinkCellNode).layoutExampleType
// let detail = AMCommentsViewController(link: redditLoader.links[indexPath.row], loader: redditLoader)
// self.navigationController?.pushViewController(detail, animated: true)
print("touched \(indexPath.row) \(redditLoader?.subreddits[indexPath.row].s.displayName)")
subredditViewController?.goToSubreddit((redditLoader?.subreddits[indexPath.row])!)
popover?.dismiss()
}
}
| gpl-3.0 | 8704a4e59b9c61b1d88aa8332e9895d1 | 31.857143 | 110 | 0.672082 | 4.802198 | false | false | false | false |
sfurlani/addsumfun | Add Sum Fun/Add Sum Fun/EquationViewController.swift | 1 | 3820 | //
// EquationViewController.swift
// Add Sum Fun
//
// Created by SFurlani on 8/26/15.
// Copyright © 2015 Dig-It! Games. All rights reserved.
//
import UIKit
protocol EquationViewControllerDelegate {
func didEnterResult(result: UInt)
}
class EquationViewController: UIViewController {
@IBOutlet var augendRow: UIStackView!
@IBOutlet var addendRow: UIStackView!
@IBOutlet var sumRow: UIStackView!
var entryViews: [NumberView] = []
var equation: EquationType!
var delegate: EquationViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
updateDisplay(equation)
}
private func updateDisplay(equation: EquationType) {
guard let augendRow = augendRow, let addendRow = addendRow, let sumRow = sumRow else {
return
}
let augViews = equation.lhs.toDigits(5).map { NumberView.newWithNumber($0) }
for case let numberView? in augViews {
augendRow.addArrangedSubview(numberView)
if numberView.number == nil {
numberView.hidden = true
}
}
let addViews = equation.rhs.toDigits(5).map { NumberView.newWithNumber($0) }
for case let numberView? in addViews {
addendRow.addArrangedSubview(numberView)
if numberView.number == nil {
numberView.hidden = true
}
}
let sum = Int(equation.result)
entryViews = sum.toDigits().map { (_: Int?) -> NumberView in
return NumberView.newWithNumber(nil)!
}
for case let numberView in entryViews {
sumRow.addArrangedSubview(numberView)
}
}
func switchNumber(number: UInt, gesture: UIPanGestureRecognizer) -> Bool {
let location = gesture.locationInView(view)
guard let numberView = view.hitTest(location, withEvent: nil) as? NumberView else {
return false
}
guard let index = entryViews.indexOf(numberView) else {
return false
}
numberView.hidden = true
let newView = NumberView.newWithNumber(number)!
newView.frame = numberView.frame
newView.alpha = 0.0
sumRow.removeArrangedSubview(numberView)
entryViews.removeAtIndex(index)
entryViews.insert(newView, atIndex: index)
sumRow.insertArrangedSubview(newView, atIndex: index)
self.sumRow.layoutIfNeeded()
UIView.animateWithDuration(0.2, animations: { newView.alpha = 1.0 }, completion: { (_) in
if let result = self.checkResult() {
self.delegate?.didEnterResult(result)
}
})
return true
}
func checkResult() -> UInt? {
let result = calculateResponse(entryViews.map { $0.number })
print(result)
let total = entryViews.reduce(0) { $0 + ($1.number != nil ? 1 : 0) }
guard Int(total) == entryViews.count else {
return nil
}
return result
}
private func calculateResponse(entered: [UInt?]) -> UInt {
var tens: UInt = 0
var sum: UInt = 0
for place in entered.reverse() {
if let place = place {
sum += place * pow(10, exponent: tens)
}
tens++
}
return sum
}
private func pow(base: UInt, exponent: UInt) -> UInt {
guard exponent > 0 else {
return 1
}
return pow(base, exponent: exponent - 1) * 10
}
}
| mit | 8c176b9d863f44f6c0f0547b6fae5573 | 26.47482 | 97 | 0.559309 | 4.674419 | false | false | false | false |
teawithfruit/Toucan | Source/Toucan.swift | 6 | 26804 | // Toucan.swift
//
// Copyright (c) 2014 Gavin Bunney, Bunney Apps (http://bunney.net.au)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import CoreGraphics
/**
Toucan - Fabulous Image Processing in Swift.
The Toucan class provides two methods of interaction - either through an instance, wrapping an single image,
or through the static functions, providing an image for each invocation.
This allows for some flexible usage. Using static methods when you need a single operation:
let resizedImage = Toucan.resize(myImage, size: CGSize(width: 100, height: 150))
Or create an instance for easy method chaining:
let resizedAndMaskedImage = Toucan(withImage: myImage).resize(CGSize(width: 100, height: 150)).maskWithEllipse().image
*/
public class Toucan : NSObject {
public var image : UIImage
public init(image withImage: UIImage) {
self.image = withImage
}
// MARK: - Resize
/**
Resize the contained image to the specified size. Depending on what fitMode is supplied, the image
may be clipped, cropped or scaled. @see documentation on FitMode.
The current image on this toucan instance is replaced with the resized image.
- parameter size: Size to resize the image to
- parameter fitMode: How to handle the image resizing process
- returns: Self, allowing method chaining
*/
public func resize(size: CGSize, fitMode: Toucan.Resize.FitMode = .Clip) -> Toucan {
self.image = Toucan.Resize.resizeImage(self.image, size: size, fitMode: fitMode)
return self
}
/**
Resize the contained image to the specified size by resizing the image to fit
within the width and height boundaries without cropping or scaling the image.
The current image on this toucan instance is replaced with the resized image.
- parameter size: Size to resize the image to
- returns: Self, allowing method chaining
*/
@objc
public func resizeByClipping(size: CGSize) -> Toucan {
self.image = Toucan.Resize.resizeImage(self.image, size: size, fitMode: .Clip)
return self
}
/**
Resize the contained image to the specified size by resizing the image to fill the
width and height boundaries and crops any excess image data.
The resulting image will match the width and height constraints without scaling the image.
The current image on this toucan instance is replaced with the resized image.
- parameter size: Size to resize the image to
- returns: Self, allowing method chaining
*/
@objc
public func resizeByCropping(size: CGSize) -> Toucan {
self.image = Toucan.Resize.resizeImage(self.image, size: size, fitMode: .Crop)
return self
}
/**
Resize the contained image to the specified size by scaling the image to fit the
constraining dimensions exactly.
The current image on this toucan instance is replaced with the resized image.
- parameter size: Size to resize the image to
- returns: Self, allowing method chaining
*/
@objc
public func resizeByScaling(size: CGSize) -> Toucan {
self.image = Toucan.Resize.resizeImage(self.image, size: size, fitMode: .Scale)
return self
}
/**
Container struct for all things Resize related
*/
public struct Resize {
/**
FitMode drives the resizing process to determine what to do with an image to
make it fit the given size bounds.
- Clip: Resizes the image to fit within the width and height boundaries without cropping or scaling the image.
- Crop: Resizes the image to fill the width and height boundaries and crops any excess image data.
- Scale: Scales the image to fit the constraining dimensions exactly.
*/
public enum FitMode {
/**
Resizes the image to fit within the width and height boundaries without cropping or scaling the image.
The resulting image is assured to match one of the constraining dimensions, while
the other dimension is altered to maintain the same aspect ratio of the input image.
*/
case Clip
/**
Resizes the image to fill the width and height boundaries and crops any excess image data.
The resulting image will match the width and height constraints without scaling the image.
*/
case Crop
/**
Scales the image to fit the constraining dimensions exactly.
*/
case Scale
}
/**
Resize an image to the specified size. Depending on what fitMode is supplied, the image
may be clipped, cropped or scaled. @see documentation on FitMode.
- parameter image: Image to Resize
- parameter size: Size to resize the image to
- parameter fitMode: How to handle the image resizing process
- returns: Resized image
*/
public static func resizeImage(image: UIImage, size: CGSize, fitMode: FitMode = .Clip) -> UIImage {
let imgRef = Util.CGImageWithCorrectOrientation(image)
let originalWidth = CGFloat(CGImageGetWidth(imgRef))
let originalHeight = CGFloat(CGImageGetHeight(imgRef))
let widthRatio = size.width / originalWidth
let heightRatio = size.height / originalHeight
let scaleRatio = widthRatio > heightRatio ? widthRatio : heightRatio
let resizedImageBounds = CGRect(x: 0, y: 0, width: round(originalWidth * scaleRatio), height: round(originalHeight * scaleRatio))
let resizedImage = Util.drawImageInBounds(image, bounds: resizedImageBounds)
switch (fitMode) {
case .Clip:
return resizedImage
case .Crop:
let croppedRect = CGRect(x: (resizedImage.size.width - size.width) / 2,
y: (resizedImage.size.height - size.height) / 2,
width: size.width, height: size.height)
return Util.croppedImageWithRect(resizedImage, rect: croppedRect)
case .Scale:
return Util.drawImageInBounds(resizedImage, bounds: CGRect(x: 0, y: 0, width: size.width, height: size.height))
}
}
}
// MARK: - Mask
/**
Mask the contained image with another image mask.
Note that the areas in the original image that correspond to the black areas of the mask
show through in the resulting image. The areas that correspond to the white areas of
the mask aren’t painted. The areas that correspond to the gray areas in the mask are painted
using an intermediate alpha value that’s equal to 1 minus the image mask sample value.
- parameter maskImage: Image Mask to apply to the Image
- returns: Self, allowing method chaining
*/
public func maskWithImage(maskImage maskImage : UIImage) -> Toucan {
self.image = Toucan.Mask.maskImageWithImage(self.image, maskImage: maskImage)
return self
}
/**
Mask the contained image with an ellipse.
Allows specifying an additional border to draw on the clipped image.
For a circle, ensure the image width and height are equal!
- parameter borderWidth: Optional width of the border to apply - default 0
- parameter borderColor: Optional color of the border - default White
- returns: Self, allowing method chaining
*/
public func maskWithEllipse(borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.whiteColor()) -> Toucan {
self.image = Toucan.Mask.maskImageWithEllipse(self.image, borderWidth: borderWidth, borderColor: borderColor)
return self
}
/**
Mask the contained image with a path (UIBezierPath) that will be scaled to fit the image.
- parameter path: UIBezierPath to mask the image
- returns: Self, allowing method chaining
*/
public func maskWithPath(path path: UIBezierPath) -> Toucan {
self.image = Toucan.Mask.maskImageWithPath(self.image, path: path)
return self
}
/**
Mask the contained image with a path (UIBezierPath) which is provided via a closure.
- parameter path: closure that returns a UIBezierPath. Using a closure allows the user to provide the path after knowing the size of the image
- returns: Self, allowing method chaining
*/
public func maskWithPathClosure(path path: (rect: CGRect) -> (UIBezierPath)) -> Toucan {
self.image = Toucan.Mask.maskImageWithPathClosure(self.image, pathInRect: path)
return self
}
/**
Mask the contained image with a rounded rectangle border.
Allows specifying an additional border to draw on the clipped image.
- parameter cornerRadius: Radius of the rounded rect corners
- parameter borderWidth: Optional width of border to apply - default 0
- parameter borderColor: Optional color of the border - default White
- returns: Self, allowing method chaining
*/
public func maskWithRoundedRect(cornerRadius cornerRadius: CGFloat, borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.whiteColor()) -> Toucan {
self.image = Toucan.Mask.maskImageWithRoundedRect(self.image, cornerRadius: cornerRadius, borderWidth: borderWidth, borderColor: borderColor)
return self
}
/**
Container struct for all things Mask related
*/
public struct Mask {
/**
Mask the given image with another image mask.
Note that the areas in the original image that correspond to the black areas of the mask
show through in the resulting image. The areas that correspond to the white areas of
the mask aren’t painted. The areas that correspond to the gray areas in the mask are painted
using an intermediate alpha value that’s equal to 1 minus the image mask sample value.
- parameter image: Image to apply the mask to
- parameter maskImage: Image Mask to apply to the Image
- returns: Masked image
*/
public static func maskImageWithImage(image: UIImage, maskImage: UIImage) -> UIImage {
let imgRef = Util.CGImageWithCorrectOrientation(image)
let maskRef = maskImage.CGImage
let mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), nil, false);
let masked = CGImageCreateWithMask(imgRef, mask);
return Util.drawImageWithClosure(size: image.size) { (size: CGSize, context: CGContext) -> () in
// need to flip the transform matrix, CoreGraphics has (0,0) in lower left when drawing image
CGContextScaleCTM(context, 1, -1)
CGContextTranslateCTM(context, 0, -size.height)
CGContextDrawImage(context, CGRect(x: 0, y: 0, width: size.width, height: size.height), masked);
}
}
/**
Mask the given image with an ellipse.
Allows specifying an additional border to draw on the clipped image.
For a circle, ensure the image width and height are equal!
- parameter image: Image to apply the mask to
- parameter borderWidth: Optional width of the border to apply - default 0
- parameter borderColor: Optional color of the border - default White
- returns: Masked image
*/
public static func maskImageWithEllipse(image: UIImage,
borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.whiteColor()) -> UIImage {
let imgRef = Util.CGImageWithCorrectOrientation(image)
let size = CGSize(width: CGFloat(CGImageGetWidth(imgRef)) / image.scale, height: CGFloat(CGImageGetHeight(imgRef)) / image.scale)
return Util.drawImageWithClosure(size: size) { (size: CGSize, context: CGContext) -> () in
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
CGContextAddEllipseInRect(context, rect)
CGContextClip(context)
image.drawInRect(rect)
if (borderWidth > 0) {
CGContextSetStrokeColorWithColor(context, borderColor.CGColor);
CGContextSetLineWidth(context, borderWidth);
CGContextAddEllipseInRect(context, CGRect(x: borderWidth / 2,
y: borderWidth / 2,
width: size.width - borderWidth,
height: size.height - borderWidth));
CGContextStrokePath(context);
}
}
}
/**
Mask the given image with a path(UIBezierPath) that will be scaled to fit the image.
- parameter image: Image to apply the mask to
- parameter path: UIBezierPath to make as the mask
- returns: Masked image
*/
public static func maskImageWithPath(image: UIImage,
path: UIBezierPath) -> UIImage {
let imgRef = Util.CGImageWithCorrectOrientation(image)
let size = CGSize(width: CGFloat(CGImageGetWidth(imgRef)) / image.scale, height: CGFloat(CGImageGetHeight(imgRef)) / image.scale)
return Util.drawImageWithClosure(size: size) { (size: CGSize, context: CGContext) -> () in
let boundSize = path.bounds.size
let pathRatio = boundSize.width / boundSize.height
let imageRatio = size.width / size.height
if pathRatio > imageRatio {
//scale based on width
let scale = size.width / boundSize.width
path.applyTransform(CGAffineTransformMakeScale(scale, scale))
path.applyTransform(CGAffineTransformMakeTranslation(0, (size.height - path.bounds.height) / 2.0))
} else {
//scale based on height
let scale = size.height / boundSize.height
path.applyTransform(CGAffineTransformMakeScale(scale, scale))
path.applyTransform(CGAffineTransformMakeTranslation((size.width - path.bounds.width) / 2.0, 0))
}
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
CGContextAddPath(context, path.CGPath)
CGContextClip(context)
image.drawInRect(rect)
}
}
/**
Mask the given image with a path(UIBezierPath) provided via a closure. This allows the user to get the size of the image before computing their path variable.
- parameter image: Image to apply the mask to
- parameter path: UIBezierPath to make as the mask
- returns: Masked image
*/
public static func maskImageWithPathClosure(image: UIImage,
pathInRect:(rect: CGRect) -> (UIBezierPath)) -> UIImage {
let imgRef = Util.CGImageWithCorrectOrientation(image)
let size = CGSize(width: CGFloat(CGImageGetWidth(imgRef)) / image.scale, height: CGFloat(CGImageGetHeight(imgRef)) / image.scale)
return maskImageWithPath(image, path: pathInRect(rect: CGRectMake(0, 0, size.width, size.height)))
}
/**
Mask the given image with a rounded rectangle border.
Allows specifying an additional border to draw on the clipped image.
- parameter image: Image to apply the mask to
- parameter cornerRadius: Radius of the rounded rect corners
- parameter borderWidth: Optional width of border to apply - default 0
- parameter borderColor: Optional color of the border - default White
- returns: Masked image
*/
public static func maskImageWithRoundedRect(image: UIImage, cornerRadius: CGFloat,
borderWidth: CGFloat = 0, borderColor: UIColor = UIColor.whiteColor()) -> UIImage {
let imgRef = Util.CGImageWithCorrectOrientation(image)
let size = CGSize(width: CGFloat(CGImageGetWidth(imgRef)) / image.scale, height: CGFloat(CGImageGetHeight(imgRef)) / image.scale)
return Util.drawImageWithClosure(size: size) { (size: CGSize, context: CGContext) -> () in
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIBezierPath(roundedRect:rect, cornerRadius: cornerRadius).addClip()
image.drawInRect(rect)
if (borderWidth > 0) {
CGContextSetStrokeColorWithColor(context, borderColor.CGColor);
CGContextSetLineWidth(context, borderWidth);
let borderRect = CGRect(x: 0, y: 0,
width: size.width, height: size.height)
let borderPath = UIBezierPath(roundedRect: borderRect, cornerRadius: cornerRadius)
borderPath.lineWidth = borderWidth * 2
borderPath.stroke()
}
}
}
}
// MARK: - Layer
/**
Overlay an image ontop of the current image.
- parameter image: Image to be on the bottom layer
- parameter overlayImage: Image to be on the top layer, i.e. drawn on top of image
- parameter overlayFrame: Frame of the overlay image
- returns: Self, allowing method chaining
*/
public func layerWithOverlayImage(overlayImage: UIImage, overlayFrame: CGRect) -> Toucan {
self.image = Toucan.Layer.overlayImage(self.image, overlayImage:overlayImage, overlayFrame:overlayFrame)
return self
}
/**
Container struct for all things Layer related.
*/
public struct Layer {
/**
Overlay the given image into a new layout ontop of the image.
- parameter image: Image to be on the bottom layer
- parameter overlayImage: Image to be on the top layer, i.e. drawn on top of image
- parameter overlayFrame: Frame of the overlay image
- returns: Masked image
*/
public static func overlayImage(image: UIImage, overlayImage: UIImage, overlayFrame: CGRect) -> UIImage {
let imgRef = Util.CGImageWithCorrectOrientation(image)
let size = CGSize(width: CGFloat(CGImageGetWidth(imgRef)) / image.scale, height: CGFloat(CGImageGetHeight(imgRef)) / image.scale)
return Util.drawImageWithClosure(size: size) { (size: CGSize, context: CGContext) -> () in
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
image.drawInRect(rect)
overlayImage.drawInRect(overlayFrame);
}
}
}
/**
Container struct for internally used utility functions.
*/
internal struct Util {
/**
Get the CGImage of the image with the orientation fixed up based on EXF data.
This helps to normalise input images to always be the correct orientation when performing
other core graphics tasks on the image.
- parameter image: Image to create CGImageRef for
- returns: CGImageRef with rotated/transformed image context
*/
static func CGImageWithCorrectOrientation(image : UIImage) -> CGImageRef {
if (image.imageOrientation == UIImageOrientation.Up) {
return image.CGImage!
}
var transform : CGAffineTransform = CGAffineTransformIdentity;
switch (image.imageOrientation) {
case UIImageOrientation.Right, UIImageOrientation.RightMirrored:
transform = CGAffineTransformTranslate(transform, 0, image.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(-1.0 * M_PI_2))
break
case UIImageOrientation.Left, UIImageOrientation.LeftMirrored:
transform = CGAffineTransformTranslate(transform, image.size.width, 0)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))
break
case UIImageOrientation.Down, UIImageOrientation.DownMirrored:
transform = CGAffineTransformTranslate(transform, image.size.width, image.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI))
break
default:
break
}
switch (image.imageOrientation) {
case UIImageOrientation.RightMirrored, UIImageOrientation.LeftMirrored:
transform = CGAffineTransformTranslate(transform, image.size.height, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break
case UIImageOrientation.DownMirrored, UIImageOrientation.UpMirrored:
transform = CGAffineTransformTranslate(transform, image.size.width, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break
default:
break
}
let context : CGContextRef = CGBitmapContextCreate(nil, CGImageGetWidth(image.CGImage), CGImageGetHeight(image.CGImage),
CGImageGetBitsPerComponent(image.CGImage),
CGImageGetBytesPerRow(image.CGImage),
CGImageGetColorSpace(image.CGImage),
CGImageGetBitmapInfo(image.CGImage).rawValue)!;
CGContextConcatCTM(context, transform);
switch (image.imageOrientation) {
case UIImageOrientation.Left, UIImageOrientation.LeftMirrored,
UIImageOrientation.Right, UIImageOrientation.RightMirrored:
CGContextDrawImage(context, CGRectMake(0, 0, image.size.height, image.size.width), image.CGImage);
break;
default:
CGContextDrawImage(context, CGRectMake(0, 0, image.size.width, image.size.height), image.CGImage);
break;
}
let cgImage = CGBitmapContextCreateImage(context);
return cgImage!;
}
/**
Draw the image within the given bounds (i.e. resizes)
- parameter image: Image to draw within the given bounds
- parameter bounds: Bounds to draw the image within
- returns: Resized image within bounds
*/
static func drawImageInBounds(image: UIImage, bounds : CGRect) -> UIImage {
return drawImageWithClosure(size: bounds.size) { (size: CGSize, context: CGContext) -> () in
image.drawInRect(bounds)
};
}
/**
Crop the image within the given rect (i.e. resizes and crops)
- parameter image: Image to clip within the given rect bounds
- parameter rect: Bounds to draw the image within
- returns: Resized and cropped image
*/
static func croppedImageWithRect(image: UIImage, rect: CGRect) -> UIImage {
return drawImageWithClosure(size: rect.size) { (size: CGSize, context: CGContext) -> () in
let drawRect = CGRectMake(-rect.origin.x, -rect.origin.y, image.size.width, image.size.height)
CGContextClipToRect(context, CGRectMake(0, 0, rect.size.width, rect.size.height))
image.drawInRect(drawRect)
};
}
/**
Closure wrapper around image context - setting up, ending and grabbing the image from the context.
- parameter size: Size of the graphics context to create
- parameter closure: Closure of magic to run in a new context
- returns: Image pulled from the end of the closure
*/
static func drawImageWithClosure(size size: CGSize!, closure: (size: CGSize, context: CGContext) -> ()) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
closure(size: size, context: UIGraphicsGetCurrentContext()!)
let image : UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
}
| mit | bcf3a5c6e29f0ed8973a75c6a9baf10e | 43.809365 | 166 | 0.609979 | 5.486486 | false | false | false | false |
mb2dev/BarnaBot | Barnabot/BBSession.swift | 1 | 9256 | //
// BBSession.swift
// MyBarnabot
//
// Created by VAUTRIN on 05/02/2017.
// Copyright © 2017 gabrielvv. All rights reserved.
//
import Foundation
/// Inspired by thread states
enum SessionState {
case pending
case new
case running
case terminated
}
class BBSession {
static let sharedInstance : BBSession = BBSession()
static let identifier : String = "BBSession"
/*static func newInstance(_ sharedUserData : Bool?) -> BBSession {
if let sud = sharedUserData {
return BBSession(sharedUserData : sud)
}
return BBSession(sharedUserData: false)
}*/
static func newInstance() -> BBSession {
return BBSession(sharedUserData: false)
}
static func newInstance(sharedUserData : Bool) -> BBSession {
return BBSession(sharedUserData : sharedUserData)
}
var state : SessionState {
get {
if(_dialogStack.count > 0){
return .running
}else{
return .pending
}
}
}
var human_feeling : Bool = true
var luis_connector : Bool = true
var userData : [String: Any] = [String: Any]()
var delegate : BBSessionDelegate?
/// Stores the result of a prompt to pass the value to the next dialog step
var result : String = String()
var sharedUserData : Bool = true
private var waiting_for_uinput : Bool = false
private var _dialogStack : Stack<BBDialog> = Stack<BBDialog>()
public var dialogStack : Stack<BBDialog> {
get {
var stack = Stack<BBDialog>()
stack.items = _dialogStack.items.map { $0.copy() }
return stack
}
}
private convenience init(){
self.init(sharedUserData : true)
}
private init(sharedUserData: Bool) {
self.sharedUserData = sharedUserData
if self.sharedUserData {
let defaults = UserDefaults.standard
if let data = defaults.dictionary(forKey: BBSession.identifier) {
userData = data as! [String: Any]
} else {
userData = [String: Any]()
}
}else{
userData = [String: Any]()
}
}
/**
Entry point to start interacting with the user.
Invokes by default the dialog registered at the path **"/"**.
*/
func beginConversation() -> BBSession {
//print("beginConversation")
return self.state == .running ? self : beginDialog(path: "/")
}
/**
Starts the dialog registered at the path and push it on the top of the dialog stack
*/
func beginDialog(path : String) -> BBSession {
// TODO check waitin_for_uinput
if let dialog : BBDialog = delegate?.botBuilder.dialogs[path] {
self.safeBegin(dialog)
}
return self
}
/**
Starts a dialog and push it on the top of the dialog stack
*/
private func beginDialog(_ dialog: BBDialog) -> BBSession {
//print("private beginDialog")
let copy = dialog.copy()
_dialogStack.push(copy)
copy.beginDialog(self)
return self
}
private func safeBegin(_ dialog : BBDialog){
if(dialog != dialogStack.last){
self.beginDialog(dialog)
}
}
/**
Persists the user data dictionary
*/
private func saveUserData() -> BBSession {
let defaults = UserDefaults.standard
defaults.setValue(userData, forKey: BBSession.identifier)
defaults.synchronize()
return self
}
func saveUserData(value : Any, forKey: String) -> BBSession {
userData.updateValue(value, forKey: forKey)
return self.sharedUserData ? saveUserData() : self
}
func getUserData(_ key: String) -> Any?{
return userData[key]
}
/*
- todo: notify every session sharing data
*/
func deleteUserData(){
self.userData.removeAll(keepingCapacity: true)
if self.sharedUserData {
let defaults = UserDefaults.standard
defaults.removeObject(forKey: BBSession.identifier)
defaults.synchronize()
}
}
/**
Ends the current dialog at the top of the stack.
Removes the dialog from the stack.
Call for the previous registered dialog.
*/
func endDialog() -> BBSession {
_dialogStack.pop()
if(self.state != .pending){
return self.resume()
}
return self
}
/**
Invokes the next step of the dialog at the top of the stack
Should be private
*/
func resume() -> BBSession {
//print("resuming")
if let dialog = _dialogStack.last {
if let next = dialog.next {
next(self)
} else {
self.endDialog()
}
}
return self
}
func next() -> BBSession { return self.resume() }
/**
- todo:
*/
func endDialogWithResult() -> Void {
}
/**
- todo:
*/
func cancelDialog() -> Void {
}
private func generateRandomNumber(min: Int, max: Int) -> Int {
let randomNum = Int(arc4random_uniform(UInt32(max) - UInt32(min)) + UInt32(min))
return randomNum
}
/**
Sends to delegate
Gives a human feeling by applying a delay before sending a message
*/
func send(_ msg : String) -> BBSession {
if(self.human_feeling){
self.delegate?.writing()
let delay : NSNumber = NSNumber.init(value: Float(generateRandomNumber(min: 1000, max: 5000)) / Float(1000))
let interval : TimeInterval = TimeInterval.init(delay)
Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(timerSend), userInfo: msg, repeats: false)
}else{
if let deleg = delegate {
deleg.send(msg)
} else {
print("BBSession has no delegate")
}
}
return self
}
@objc func timerSend(timer : Timer) -> Void {
if let deleg = delegate {
if let msg = timer.userInfo {
deleg.send(msg as! String)
}
} else {
print("BBSession has no delegate")
}
}
/**
Sends with format
*/
func send(format : String, args : AnyObject...) -> BBSession {
let msg : String = String(format: format, args)
return send(msg)
}
/**
Prompts for a simple answer
*/
func promptText(_ msg: String) -> Void {
waiting_for_uinput = true
send(msg)
}
/**
promptText with format
- SeeAlso: `promptText(_ msg: String)`
*/
func promptText(format : String, args : AnyObject...) -> Void {
let msg : String = String(format: format, args)
promptText(msg)
}
/**
Prompts for a choice
- SeeAlso: `promptText(_ msg: String)`
- todo: bullets formatting (numbers, letters, ...)
*/
func promptList(msg: String, _ list: [Any]) -> Void {
waiting_for_uinput = true
var msg_to_send = msg + "\n"
for item in list {
msg_to_send.append("\(item)")
}
send(msg_to_send)
}
/**
Interface to deal with user input
*/
func receive(_ msg : String) -> Void {
// TODO envoyer à LUIS / recast.ai
print("received msg : \(msg)")
if luis_connector {
print("on passe ici")
LuisManager.sharedIntances.RequestLuis(msg: msg){ responce in
print("callback", responce.description)
self.beginDialog(path: responce.topScoring.intent)
}
}else{
// ATTENTION à ne pas relancer un dialog déjà en cours
// (en recevant 2 fois "bonjour" à la suite par exemple)
var found : [BBIntentDialog] = matches(text: msg)
if found.count > 0 {
found = found.sorted { $0.priority > $1.priority }
if let dialog = found.first {
self.safeBegin(dialog)
}
}
}
waiting_for_uinput = false
self.result = msg
self.resume()
}
/**
Analyzes user input to detect intents
- Returns: an array of matching registered BBIntentDialog
*/
private func matches(text: String) -> [BBIntentDialog] {
var result:[BBIntentDialog] = [BBIntentDialog]()
for(regex,intentDialog) in (delegate?.botBuilder.intents)!{
let nsString = text as NSString
let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
//return results.map { nsString.substring(with: $0.range)}
if (results.map { nsString.substring(with: $0.range)}).count > 0{
result.append(intentDialog)
}
}
return result
}
}
| bsd-3-clause | e5553e3a3d6012b5d5242018b21344fd | 27.115502 | 133 | 0.544216 | 4.503408 | false | false | false | false |
colemancda/Pedido | Pedido Admin/Pedido Admin/RelationshipViewController.swift | 1 | 2254 | //
// RelationshipViewController.swift
// Pedido Admin
//
// Created by Alsey Coleman Miller on 1/3/15.
// Copyright (c) 2015 ColemanCDA. All rights reserved.
//
import Foundation
import UIKit
import CoreData
import CorePedido
import CorePedidoClient
/** View controller for editing to-many relationships between entities. Displays the contents of a many-to-one relationship. */
class RelationshipViewController: FetchedResultsViewController {
// MARK: - Properties
var relationship: (NSManagedObject, String)? {
didSet {
// create fetch request
if relationship != nil {
let (managedObject, key) = self.relationship!
let relationshipDescription = managedObject.entity.relationshipsByName[key] as? NSRelationshipDescription
assert(relationshipDescription != nil, "Relationship \(key) not found on \(managedObject.entity.name!) entity")
assert(relationshipDescription!.toMany, "Relationship \(key) on \(managedObject.entity.name!) is not to-many")
assert(!relationshipDescription!.inverseRelationship!.toMany, "Inverse relationship \(!relationshipDescription!.inverseRelationship!.toMany) is to-many")
let fetchRequest = NSFetchRequest(entityName: relationshipDescription!.destinationEntity!.name!)
fetchRequest.sortDescriptors = [NSSortDescriptor(key: Store.sharedStore.resourceIDAttributeName, ascending: true)]
fetchRequest.predicate = NSComparisonPredicate(leftExpression: NSExpression(forKeyPath: relationshipDescription!.inverseRelationship!.name), rightExpression: NSExpression(forConstantValue: managedObject), modifier: NSComparisonPredicateModifier.DirectPredicateModifier, type: NSPredicateOperatorType.EqualToPredicateOperatorType, options: NSComparisonPredicateOptions.NormalizedPredicateOption)
self.fetchRequest = fetchRequest
}
else {
self.fetchRequest = nil
}
}
}
}
| mit | 5fae7d4e41cff86e00ac0df94ec59ba1 | 42.346154 | 410 | 0.649068 | 6.226519 | false | false | false | false |
ahoppen/swift | stdlib/public/Concurrency/Task.swift | 4 | 31698 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@_implementationOnly import _SwiftConcurrencyShims
// ==== Task -------------------------------------------------------------------
/// A unit of asynchronous work.
///
/// When you create an instance of `Task`,
/// you provide a closure that contains the work for that task to perform.
/// Tasks can start running immediately after creation;
/// you don't explicitly start or schedule them.
/// After creating a task, you use the instance to interact with it ---
/// for example, to wait for it to complete or to cancel it.
/// It's not a programming error to discard a reference to a task
/// without waiting for that task to finish or canceling it.
/// A task runs regardless of whether you keep a reference to it.
/// However, if you discard the reference to a task,
/// you give up the ability
/// to wait for that task's result or cancel the task.
///
/// To support operations on the current task,
/// which can be either a detached task or child task,
/// `Task` also exposes class methods like `yield()`.
/// Because these methods are asynchronous,
/// they're always invoked as part of an existing task.
///
/// Only code that's running as part of the task can interact with that task.
/// To interact with the current task,
/// you call one of the static methods on `Task`.
///
/// A task's execution can be seen as a series of periods where the task ran.
/// Each such period ends at a suspension point or the
/// completion of the task.
/// These periods of execution are represented by instances of `PartialAsyncTask`.
/// Unless you're implementing a custom executor,
/// you don't directly interact with partial tasks.
///
/// For information about the language-level concurrency model that `Task` is part of,
/// see [Concurrency][concurrency] in [The Swift Programming Language][tspl].
///
/// [concurrency]: https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html
/// [tspl]: https://docs.swift.org/swift-book/
///
/// Task Cancellation
/// =================
///
/// Tasks include a shared mechanism for indicating cancellation,
/// but not a shared implementation for how to handle cancellation.
/// Depending on the work you're doing in the task,
/// the correct way to stop that work varies.
/// Likewise,
/// it's the responsibility of the code running as part of the task
/// to check for cancellation whenever stopping is appropriate.
/// In a long-task that includes multiple pieces,
/// you might need to check for cancellation at several points,
/// and handle cancellation differently at each point.
/// If you only need to throw an error to stop the work,
/// call the `Task.checkCancellation()` function to check for cancellation.
/// Other responses to cancellation include
/// returning the work completed so far, returning an empty result, or returning `nil`.
///
/// Cancellation is a purely Boolean state;
/// there's no way to include additional information
/// like the reason for cancellation.
/// This reflects the fact that a task can be canceled for many reasons,
/// and additional reasons can accrue during the cancellation process.
@available(SwiftStdlib 5.1, *)
@frozen
public struct Task<Success: Sendable, Failure: Error>: Sendable {
@usableFromInline
internal let _task: Builtin.NativeObject
@_alwaysEmitIntoClient
internal init(_ task: Builtin.NativeObject) {
self._task = task
}
}
@available(SwiftStdlib 5.1, *)
extension Task {
/// The result from a throwing task, after it completes.
///
/// If the task hasn't completed,
/// accessing this property waits for it to complete
/// and its priority increases to that of the current task.
/// Note that this might not be as effective as
/// creating the task with the correct priority,
/// depending on the executor's scheduling details.
///
/// If the task throws an error, this property propagates that error.
/// Tasks that respond to cancellation by throwing `CancellationError`
/// have that error propagated here upon cancellation.
///
/// - Returns: The task's result.
public var value: Success {
get async throws {
return try await _taskFutureGetThrowing(_task)
}
}
/// The result or error from a throwing task, after it completes.
///
/// If the task hasn't completed,
/// accessing this property waits for it to complete
/// and its priority increases to that of the current task.
/// Note that this might not be as effective as
/// creating the task with the correct priority,
/// depending on the executor's scheduling details.
///
/// - Returns: If the task succeeded,
/// `.success` with the task's result as the associated value;
/// otherwise, `.failure` with the error as the associated value.
public var result: Result<Success, Failure> {
get async {
do {
return .success(try await value)
} catch {
return .failure(error as! Failure) // as!-safe, guaranteed to be Failure
}
}
}
/// Indicates that the task should stop running.
///
/// Task cancellation is cooperative:
/// a task that supports cancellation
/// checks whether it has been canceled at various points during its work.
///
/// Calling this method on a task that doesn't support cancellation
/// has no effect.
/// Likewise, if the task has already run
/// past the last point where it would stop early,
/// calling this method has no effect.
///
/// - SeeAlso: `Task.checkCancellation()`
public func cancel() {
Builtin.cancelAsyncTask(_task)
}
}
@available(SwiftStdlib 5.1, *)
extension Task where Failure == Never {
/// The result from a nonthrowing task, after it completes.
///
/// If the task hasn't completed yet,
/// accessing this property waits for it to complete
/// and its priority increases to that of the current task.
/// Note that this might not be as effective as
/// creating the task with the correct priority,
/// depending on the executor's scheduling details.
///
/// Tasks that never throw an error can still check for cancellation,
/// but they need to use an approach like returning `nil`
/// instead of throwing an error.
public var value: Success {
get async {
return await _taskFutureGet(_task)
}
}
}
@available(SwiftStdlib 5.1, *)
extension Task: Hashable {
public func hash(into hasher: inout Hasher) {
UnsafeRawPointer(Builtin.bridgeToRawPointer(_task)).hash(into: &hasher)
}
}
@available(SwiftStdlib 5.1, *)
extension Task: Equatable {
public static func ==(lhs: Self, rhs: Self) -> Bool {
UnsafeRawPointer(Builtin.bridgeToRawPointer(lhs._task)) ==
UnsafeRawPointer(Builtin.bridgeToRawPointer(rhs._task))
}
}
// ==== Task Priority ----------------------------------------------------------
/// The priority of a task.
///
/// The executor determines how priority information affects the way tasks are scheduled.
/// The behavior varies depending on the executor currently being used.
/// Typically, executors attempt to run tasks with a higher priority
/// before tasks with a lower priority.
/// However, the semantics of how priority is treated are left up to each
/// platform and `Executor` implementation.
///
/// Child tasks automatically inherit their parent task's priority.
/// Detached tasks created by `detach(priority:operation:)` don't inherit task priority
/// because they aren't attached to the current task.
///
/// In some situations the priority of a task is elevated ---
/// that is, the task is treated as it if had a higher priority,
/// without actually changing the priority of the task:
///
/// - If a task runs on behalf of an actor,
/// and a new higher-priority task is enqueued to the actor,
/// then the actor's current task is temporarily elevated
/// to the priority of the enqueued task.
/// This priority elevation allows the new task
/// to be processed at the priority it was enqueued with.
/// - If a a higher-priority task calls the `get()` method,
/// then the priority of this task increases until the task completes.
///
/// In both cases, priority elevation helps you prevent a low-priority task
/// from blocking the execution of a high priority task,
/// which is also known as *priority inversion*.
@available(SwiftStdlib 5.1, *)
public struct TaskPriority: RawRepresentable, Sendable {
public typealias RawValue = UInt8
public var rawValue: UInt8
public init(rawValue: UInt8) {
self.rawValue = rawValue
}
public static let high: TaskPriority = .init(rawValue: 0x19)
@_alwaysEmitIntoClient
public static var medium: TaskPriority {
.init(rawValue: 0x15)
}
public static let low: TaskPriority = .init(rawValue: 0x11)
public static let userInitiated: TaskPriority = high
public static let utility: TaskPriority = low
public static let background: TaskPriority = .init(rawValue: 0x09)
@available(*, deprecated, renamed: "medium")
public static let `default`: TaskPriority = .init(rawValue: 0x15)
}
@available(SwiftStdlib 5.1, *)
extension TaskPriority: Equatable {
public static func == (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue == rhs.rawValue
}
public static func != (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue != rhs.rawValue
}
}
@available(SwiftStdlib 5.1, *)
extension TaskPriority: Comparable {
public static func < (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue < rhs.rawValue
}
public static func <= (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue <= rhs.rawValue
}
public static func > (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue > rhs.rawValue
}
public static func >= (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue >= rhs.rawValue
}
}
@available(SwiftStdlib 5.1, *)
extension TaskPriority: Codable { }
@available(SwiftStdlib 5.1, *)
extension Task where Success == Never, Failure == Never {
/// The current task's priority.
///
/// If you access this property outside of any task,
/// this queries the system to determine the
/// priority at which the current function is running.
/// If the system can't provide a priority,
/// this property's value is `Priority.default`.
public static var currentPriority: TaskPriority {
withUnsafeCurrentTask { task in
// If we are running on behalf of a task, use that task's priority.
if let unsafeTask = task {
return TaskPriority(rawValue: _taskCurrentPriority(unsafeTask._task))
}
// Otherwise, query the system.
return TaskPriority(rawValue: UInt8(_getCurrentThreadPriority()))
}
}
/// The current task's base priority.
///
/// If you access this property outside of any task, this returns nil
@available(SwiftStdlib 5.7, *)
public static var basePriority: TaskPriority? {
withUnsafeCurrentTask { task in
// If we are running on behalf of a task, use that task's priority.
if let unsafeTask = task {
return TaskPriority(rawValue: _taskBasePriority(unsafeTask._task))
}
return nil
}
}
}
@available(SwiftStdlib 5.1, *)
extension TaskPriority {
/// Downgrade user-interactive to user-initiated.
var _downgradeUserInteractive: TaskPriority {
return self
}
}
// ==== Job Flags --------------------------------------------------------------
/// Flags for schedulable jobs.
///
/// This is a port of the C++ FlagSet.
@available(SwiftStdlib 5.1, *)
struct JobFlags {
/// Kinds of schedulable jobs.
enum Kind: Int32 {
case task = 0
}
/// The actual bit representation of these flags.
var bits: Int32 = 0
/// The kind of job described by these flags.
var kind: Kind {
get {
Kind(rawValue: bits & 0xFF)!
}
set {
bits = (bits & ~0xFF) | newValue.rawValue
}
}
/// Whether this is an asynchronous task.
var isAsyncTask: Bool { kind == .task }
/// The priority given to the job.
var priority: TaskPriority? {
get {
let value = (Int(bits) & 0xFF00) >> 8
if value == 0 {
return nil
}
return TaskPriority(rawValue: UInt8(value))
}
set {
bits = (bits & ~0xFF00) | Int32((Int(newValue?.rawValue ?? 0) << 8))
}
}
/// Whether this is a child task.
var isChildTask: Bool {
get {
(bits & (1 << 24)) != 0
}
set {
if newValue {
bits = bits | 1 << 24
} else {
bits = (bits & ~(1 << 24))
}
}
}
/// Whether this is a future.
var isFuture: Bool {
get {
(bits & (1 << 25)) != 0
}
set {
if newValue {
bits = bits | 1 << 25
} else {
bits = (bits & ~(1 << 25))
}
}
}
/// Whether this is a group child.
var isGroupChildTask: Bool {
get {
(bits & (1 << 26)) != 0
}
set {
if newValue {
bits = bits | 1 << 26
} else {
bits = (bits & ~(1 << 26))
}
}
}
/// Whether this is a task created by the 'async' operation, which
/// conceptually continues the work of the synchronous code that invokes
/// it.
var isContinuingAsyncTask: Bool {
get {
(bits & (1 << 27)) != 0
}
set {
if newValue {
bits = bits | 1 << 27
} else {
bits = (bits & ~(1 << 27))
}
}
}
}
// ==== Task Creation Flags --------------------------------------------------
/// Form task creation flags for use with the createAsyncTask builtins.
@available(SwiftStdlib 5.1, *)
@_alwaysEmitIntoClient
func taskCreateFlags(
priority: TaskPriority?, isChildTask: Bool, copyTaskLocals: Bool,
inheritContext: Bool, enqueueJob: Bool,
addPendingGroupTaskUnconditionally: Bool
) -> Int {
var bits = 0
bits |= (bits & ~0xFF) | Int(priority?.rawValue ?? 0)
if isChildTask {
bits |= 1 << 8
}
if copyTaskLocals {
bits |= 1 << 10
}
if inheritContext {
bits |= 1 << 11
}
if enqueueJob {
bits |= 1 << 12
}
if addPendingGroupTaskUnconditionally {
bits |= 1 << 13
}
return bits
}
// ==== Task Creation ----------------------------------------------------------
@available(SwiftStdlib 5.1, *)
extension Task where Failure == Never {
/// Runs the given nonthrowing operation asynchronously
/// as part of a new top-level task on behalf of the current actor.
///
/// Use this function when creating asynchronous work
/// that operates on behalf of the synchronous function that calls it.
/// Like `Task.detached(priority:operation:)`,
/// this function creates a separate, top-level task.
/// Unlike `Task.detached(priority:operation:)`,
/// the task created by `Task.init(priority:operation:)`
/// inherits the priority and actor context of the caller,
/// so the operation is treated more like an asynchronous extension
/// to the synchronous operation.
///
/// You need to keep a reference to the task
/// if you want to cancel it by calling the `Task.cancel()` method.
/// Discarding your reference to a detached task
/// doesn't implicitly cancel that task,
/// it only makes it impossible for you to explicitly cancel the task.
///
/// - Parameters:
/// - priority: The priority of the task.
/// Pass `nil` to use the priority from `Task.currentPriority`.
/// - operation: The operation to perform.
@discardableResult
@_alwaysEmitIntoClient
public init(
priority: TaskPriority? = nil,
@_inheritActorContext @_implicitSelfCapture operation: __owned @Sendable @escaping () async -> Success
) {
#if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup
// Set up the job flags for a new task.
let flags = taskCreateFlags(
priority: priority, isChildTask: false, copyTaskLocals: true,
inheritContext: true, enqueueJob: true,
addPendingGroupTaskUnconditionally: false)
// Create the asynchronous task.
let (task, _) = Builtin.createAsyncTask(flags, operation)
self._task = task
#else
fatalError("Unsupported Swift compiler")
#endif
}
}
@available(SwiftStdlib 5.1, *)
extension Task where Failure == Error {
/// Runs the given throwing operation asynchronously
/// as part of a new top-level task on behalf of the current actor.
///
/// Use this function when creating asynchronous work
/// that operates on behalf of the synchronous function that calls it.
/// Like `Task.detached(priority:operation:)`,
/// this function creates a separate, top-level task.
/// Unlike `detach(priority:operation:)`,
/// the task created by `Task.init(priority:operation:)`
/// inherits the priority and actor context of the caller,
/// so the operation is treated more like an asynchronous extension
/// to the synchronous operation.
///
/// You need to keep a reference to the task
/// if you want to cancel it by calling the `Task.cancel()` method.
/// Discarding your reference to a detached task
/// doesn't implicitly cancel that task,
/// it only makes it impossible for you to explicitly cancel the task.
///
/// - Parameters:
/// - priority: The priority of the task.
/// Pass `nil` to use the priority from `Task.currentPriority`.
/// - operation: The operation to perform.
@discardableResult
@_alwaysEmitIntoClient
public init(
priority: TaskPriority? = nil,
@_inheritActorContext @_implicitSelfCapture operation: __owned @Sendable @escaping () async throws -> Success
) {
#if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup
// Set up the task flags for a new task.
let flags = taskCreateFlags(
priority: priority, isChildTask: false, copyTaskLocals: true,
inheritContext: true, enqueueJob: true,
addPendingGroupTaskUnconditionally: false
)
// Create the asynchronous task future.
let (task, _) = Builtin.createAsyncTask(flags, operation)
self._task = task
#else
fatalError("Unsupported Swift compiler")
#endif
}
}
// ==== Detached Tasks ---------------------------------------------------------
@available(SwiftStdlib 5.1, *)
extension Task where Failure == Never {
/// Runs the given nonthrowing operation asynchronously
/// as part of a new top-level task.
///
/// Don't use a detached task if it's possible
/// to model the operation using structured concurrency features like child tasks.
/// Child tasks inherit the parent task's priority and task-local storage,
/// and canceling a parent task automatically cancels all of its child tasks.
/// You need to handle these considerations manually with a detached task.
///
/// You need to keep a reference to the detached task
/// if you want to cancel it by calling the `Task.cancel()` method.
/// Discarding your reference to a detached task
/// doesn't implicitly cancel that task,
/// it only makes it impossible for you to explicitly cancel the task.
///
/// - Parameters:
/// - priority: The priority of the task.
/// - operation: The operation to perform.
///
/// - Returns: A reference to the task.
@discardableResult
@_alwaysEmitIntoClient
public static func detached(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async -> Success
) -> Task<Success, Failure> {
#if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup
// Set up the job flags for a new task.
let flags = taskCreateFlags(
priority: priority, isChildTask: false, copyTaskLocals: false,
inheritContext: false, enqueueJob: true,
addPendingGroupTaskUnconditionally: false)
// Create the asynchronous task future.
let (task, _) = Builtin.createAsyncTask(flags, operation)
return Task(task)
#else
fatalError("Unsupported Swift compiler")
#endif
}
}
@available(SwiftStdlib 5.1, *)
extension Task where Failure == Error {
/// Runs the given throwing operation asynchronously
/// as part of a new top-level task.
///
/// If the operation throws an error, this method propagates that error.
///
/// Don't use a detached task if it's possible
/// to model the operation using structured concurrency features like child tasks.
/// Child tasks inherit the parent task's priority and task-local storage,
/// and canceling a parent task automatically cancels all of its child tasks.
/// You need to handle these considerations manually with a detached task.
///
/// You need to keep a reference to the detached task
/// if you want to cancel it by calling the `Task.cancel()` method.
/// Discarding your reference to a detached task
/// doesn't implicitly cancel that task,
/// it only makes it impossible for you to explicitly cancel the task.
///
/// - Parameters:
/// - priority: The priority of the task.
/// - operation: The operation to perform.
///
/// - Returns: A reference to the task.
@discardableResult
@_alwaysEmitIntoClient
public static func detached(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async throws -> Success
) -> Task<Success, Failure> {
#if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup
// Set up the job flags for a new task.
let flags = taskCreateFlags(
priority: priority, isChildTask: false, copyTaskLocals: false,
inheritContext: false, enqueueJob: true,
addPendingGroupTaskUnconditionally: false
)
// Create the asynchronous task future.
let (task, _) = Builtin.createAsyncTask(flags, operation)
return Task(task)
#else
fatalError("Unsupported Swift compiler")
#endif
}
}
// ==== Voluntary Suspension -----------------------------------------------------
@available(SwiftStdlib 5.1, *)
extension Task where Success == Never, Failure == Never {
/// Suspends the current task and allows other tasks to execute.
///
/// A task can voluntarily suspend itself
/// in the middle of a long-running operation
/// that doesn't contain any suspension points,
/// to let other tasks run for a while
/// before execution returns to this task.
///
/// If this task is the highest-priority task in the system,
/// the executor immediately resumes execution of the same task.
/// As such,
/// this method isn't necessarily a way to avoid resource starvation.
public static func yield() async {
return await Builtin.withUnsafeContinuation { (continuation: Builtin.RawUnsafeContinuation) -> Void in
let job = _taskCreateNullaryContinuationJob(
priority: Int(Task.currentPriority.rawValue),
continuation: continuation)
_enqueueJobGlobal(job)
}
}
}
// ==== UnsafeCurrentTask ------------------------------------------------------
/// Calls a closure with an unsafe reference to the current task.
///
/// If you call this function from the body of an asynchronous function,
/// the unsafe task handle passed to the closure is always non-`nil`
/// because an asynchronous function always runs in the context of a task.
/// However, if you call this function from the body of a synchronous function,
/// and that function isn't executing in the context of any task,
/// the unsafe task handle is `nil`.
///
/// Don't store an unsafe task reference
/// for use outside this method's closure.
/// Storing an unsafe reference doesn't affect the task's actual life cycle,
/// and the behavior of accessing an unsafe task reference
/// outside of the `withUnsafeCurrentTask(body:)` method's closure isn't defined.
/// There's no safe way to retrieve a reference to the current task
/// and save it for long-term use.
/// To query the current task without saving a reference to it,
/// use properties like `currentPriority`.
/// If you need to store a reference to a task,
/// create an unstructured task using `Task.detached(priority:operation:)` instead.
///
/// - Parameters:
/// - body: A closure that takes an `UnsafeCurrentTask` parameter.
/// If `body` has a return value,
/// that value is also used as the return value
/// for the `withUnsafeCurrentTask(body:)` function.
///
/// - Returns: The return value, if any, of the `body` closure.
@available(SwiftStdlib 5.1, *)
public func withUnsafeCurrentTask<T>(body: (UnsafeCurrentTask?) throws -> T) rethrows -> T {
guard let _task = _getCurrentAsyncTask() else {
return try body(nil)
}
// FIXME: This retain seems pretty wrong, however if we don't we WILL crash
// with "destroying a task that never completed" in the task's destroy.
// How do we solve this properly?
Builtin.retain(_task)
return try body(UnsafeCurrentTask(_task))
}
/// An unsafe reference to the current task.
///
/// To get an instance of `UnsafeCurrentTask` for the current task,
/// call the `withUnsafeCurrentTask(body:)` method.
/// Don't store an unsafe task reference
/// for use outside that method's closure.
/// Storing an unsafe reference doesn't affect the task's actual life cycle,
/// and the behavior of accessing an unsafe task reference
/// outside of the `withUnsafeCurrentTask(body:)` method's closure isn't defined.
///
/// Only APIs on `UnsafeCurrentTask` that are also part of `Task`
/// are safe to invoke from a task other than
/// the task that this `UnsafeCurrentTask` instance refers to.
/// Calling other APIs from another task is undefined behavior,
/// breaks invariants in other parts of the program running on this task,
/// and may lead to crashes or data loss.
///
/// For information about the language-level concurrency model that `UnsafeCurrentTask` is part of,
/// see [Concurrency][concurrency] in [The Swift Programming Language][tspl].
///
/// [concurrency]: https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html
/// [tspl]: https://docs.swift.org/swift-book/
@available(SwiftStdlib 5.1, *)
public struct UnsafeCurrentTask {
internal let _task: Builtin.NativeObject
// May only be created by the standard library.
internal init(_ task: Builtin.NativeObject) {
self._task = task
}
/// A Boolean value that indicates whether the current task was canceled.
///
/// After the value of this property becomes `true`, it remains `true` indefinitely.
/// There is no way to uncancel a task.
///
/// - SeeAlso: `checkCancellation()`
public var isCancelled: Bool {
_taskIsCancelled(_task)
}
/// The current task's priority.
///
/// - SeeAlso: `TaskPriority`
/// - SeeAlso: `Task.currentPriority`
public var priority: TaskPriority {
TaskPriority(rawValue: _taskCurrentPriority(_task))
}
/// Cancel the current task.
public func cancel() {
_taskCancel(_task)
}
}
@available(SwiftStdlib 5.1, *)
@available(*, unavailable)
extension UnsafeCurrentTask: Sendable { }
@available(SwiftStdlib 5.1, *)
extension UnsafeCurrentTask: Hashable {
public func hash(into hasher: inout Hasher) {
UnsafeRawPointer(Builtin.bridgeToRawPointer(_task)).hash(into: &hasher)
}
}
@available(SwiftStdlib 5.1, *)
extension UnsafeCurrentTask: Equatable {
public static func ==(lhs: Self, rhs: Self) -> Bool {
UnsafeRawPointer(Builtin.bridgeToRawPointer(lhs._task)) ==
UnsafeRawPointer(Builtin.bridgeToRawPointer(rhs._task))
}
}
// ==== Internal ---------------------------------------------------------------
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_getCurrent")
func _getCurrentAsyncTask() -> Builtin.NativeObject?
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_getJobFlags")
func getJobFlags(_ task: Builtin.NativeObject) -> JobFlags
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_enqueueGlobal")
@usableFromInline
func _enqueueJobGlobal(_ task: Builtin.Job)
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_enqueueGlobalWithDelay")
@usableFromInline
func _enqueueJobGlobalWithDelay(_ delay: UInt64, _ task: Builtin.Job)
@available(SwiftStdlib 5.7, *)
@_silgen_name("swift_task_enqueueGlobalWithDeadline")
@usableFromInline
func _enqueueJobGlobalWithDeadline(_ seconds: Int64, _ nanoseconds: Int64,
_ toleranceSec: Int64, _ toleranceNSec: Int64,
_ clock: Int32, _ task: Builtin.Job)
@available(SwiftStdlib 5.1, *)
@usableFromInline
@_silgen_name("swift_task_asyncMainDrainQueue")
internal func _asyncMainDrainQueue() -> Never
@available(SwiftStdlib 5.1, *)
@usableFromInline
@_silgen_name("swift_task_getMainExecutor")
internal func _getMainExecutor() -> Builtin.Executor
@available(SwiftStdlib 5.1, *)
@usableFromInline
@preconcurrency
internal func _runAsyncMain(_ asyncFun: @Sendable @escaping () async throws -> ()) {
Task.detached {
do {
#if !os(Windows)
#if compiler(>=5.5) && $BuiltinHopToActor
Builtin.hopToActor(MainActor.shared)
#else
fatalError("Swift compiler is incompatible with this SDK version")
#endif
#endif
try await asyncFun()
exit(0)
} catch {
_errorInMain(error)
}
}
_asyncMainDrainQueue()
}
// FIXME: both of these ought to take their arguments _owned so that
// we can do a move out of the future in the common case where it's
// unreferenced
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_future_wait")
public func _taskFutureGet<T>(_ task: Builtin.NativeObject) async -> T
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_future_wait_throwing")
public func _taskFutureGetThrowing<T>(_ task: Builtin.NativeObject) async throws -> T
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_cancel")
func _taskCancel(_ task: Builtin.NativeObject)
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_isCancelled")
@usableFromInline
func _taskIsCancelled(_ task: Builtin.NativeObject) -> Bool
@_silgen_name("swift_task_currentPriority")
internal func _taskCurrentPriority(_ task: Builtin.NativeObject) -> UInt8
@_silgen_name("swift_task_basePriority")
internal func _taskBasePriority(_ task: Builtin.NativeObject) -> UInt8
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_createNullaryContinuationJob")
func _taskCreateNullaryContinuationJob(priority: Int, continuation: Builtin.RawUnsafeContinuation) -> Builtin.Job
@available(SwiftStdlib 5.1, *)
@usableFromInline
@_silgen_name("swift_task_isCurrentExecutor")
func _taskIsCurrentExecutor(_ executor: Builtin.Executor) -> Bool
@available(SwiftStdlib 5.1, *)
@usableFromInline
@_silgen_name("swift_task_reportUnexpectedExecutor")
func _reportUnexpectedExecutor(_ _filenameStart: Builtin.RawPointer,
_ _filenameLength: Builtin.Word,
_ _filenameIsASCII: Builtin.Int1,
_ _line: Builtin.Word,
_ _executor: Builtin.Executor)
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_getCurrentThreadPriority")
func _getCurrentThreadPriority() -> Int
#if _runtime(_ObjC)
/// Intrinsic used by SILGen to launch a task for bridging a Swift async method
/// which was called through its ObjC-exported completion-handler-based API.
@available(SwiftStdlib 5.1, *)
@_alwaysEmitIntoClient
@usableFromInline
internal func _runTaskForBridgedAsyncMethod(@_inheritActorContext _ body: __owned @Sendable @escaping () async -> Void) {
#if compiler(>=5.6)
Task(operation: body)
#else
Task<Int, Error> {
await body()
return 0
}
#endif
}
#endif
| apache-2.0 | e384d61e80c423de65e4355d2ab2a8c5 | 33.305195 | 121 | 0.675121 | 4.32442 | false | false | false | false |
cemolcay/DeserializableSwiftGenerator | DeserializableSwiftGenerator/SWClass.swift | 2 | 1077 | //
// SWClass.swift
// DeserializableSwiftGenerator
//
// Created by Cem Olcay on 25/12/14.
// Copyright (c) 2014 Cem Olcay. All rights reserved.
//
final class SWClass {
var name: String
var superName: String?
var properties: [SWProperty]?
init (name: String, superName: String?, properties: [SWProperty]?) {
self.name = name
self.superName = superName
self.properties = properties
}
func getHeader (protocolName: String?) -> String {
var header = "class " + name
if let s = superName {
header += ": " + s
if let p = protocolName {
header += ", " + p
}
} else {
if let p = protocolName {
header += ": " + p
}
}
return header + " {\n"
}
func getFields () -> String {
var fields = ""
if let p = properties {
for prop in p {
fields += "\t" + prop.getVariableLine() + "\n"
}
}
return fields
}
}
| mit | 76a54076708615a971c78bf8d60c1368 | 22.933333 | 72 | 0.481894 | 4.256917 | false | false | false | false |
BGDigital/mcwa | mcwa/mcwa/Tools/ addQuestionController.swift | 1 | 22421 | //
// addQuestionController.swift
// mcwa
//
// Created by 陈强 on 15/10/13.
// Copyright © 2015年 XingfuQiu. All rights reserved.
//
import UIKit
class addQuestionController: UIViewController,UITextFieldDelegate,UMSocialUIDelegate,DBCameraViewControllerDelegate,UITextViewDelegate {
var manager = AFHTTPRequestOperationManager()
@IBOutlet weak var segmentedbtn: UISegmentedControl!
@IBOutlet weak var oneUploadBtn: UIButton!
@IBOutlet weak var twoUploadBtn: UIButton!
@IBOutlet weak var answerSegment: UISegmentedControl!
@IBOutlet weak var titleView: UITextView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var imageBtn: UIImageView!
var textView:UITextView!
var containerView:UIView!
var cancleButton:UIButton!
var sendButton:UIButton!
var lableView:UILabel!
@IBOutlet weak var oneView: UIView!
@IBOutlet weak var twoView: UIView!
@IBOutlet weak var threeView: UIView!
@IBOutlet weak var fourView: UIView!
@IBOutlet weak var answerOne: UILabel!
@IBOutlet weak var answerTwo: UILabel!
@IBOutlet weak var answerThree: UILabel!
@IBOutlet weak var answerFour: UILabel!
var answerFlag:Int = 1
var questionType:String! = "选择题"
var reallyAnswer:String! = "正确"
var icon:UIImage!
var type:String!
var answerTitle:String! = ""
var one:String! = ""
var two:String! = ""
var three:String! = ""
var four:String! = ""
var iconValue:String! = ""
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationItem.leftBarButtonItem?.title = ""
self.titleView.tag = 10
self.titleView.delegate = self
self.view.userInteractionEnabled = true
self.scrollView.userInteractionEnabled = true
self.answerSegment.hidden = true
self.twoUploadBtn.hidden = true
self.navigationItem.title = "出题"
// imageView.layer.borderWidth = 5.0
// imageView.layer.borderColor = UIColor(patternImage: UIImage(named:"DotedImage.png")!).CGColor
// let attributes = [NSForegroundColorAttributeName:UIColor(red: 0.329, green: 0.318, blue: 0.518, alpha: 1.00) ]
// segmentedBtn.setTitleTextAttributes(attributes, forState: UIControlState.Normal)
// let highlightedAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]
// segmentedBtn.setTitleTextAttributes(highlightedAttributes, forState: UIControlState.Selected)
self.navigationItem.title = "出题"
// one = UITextField(frame: CGRectMake(0, 100, 300, 100))
// one.backgroundColor = UIColor.whiteColor()
// one.font = UIFont.systemFontOfSize(40)
// one.delegate = self
// self.view.addSubview(one)
//
// segmentedControl = HMSegmentedControl(sectionTitles: kindsArray)
// segmentedControl.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 40)
// segmentedControl.backgroundColor = UIColor.blueColor()
// segmentedControl.tintColor = UIColor.redColor()
// segmentedControl.textColor = UIColor(red: 0.694, green: 0.694, blue: 0.694, alpha: 1.00)
// segmentedControl.selectedTextColor = UIColor(red: 0.255, green: 0.788, blue: 0.298, alpha: 1.00)
// segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationNone
// segmentedControl.addTarget(self, action: "segmentSelected:", forControlEvents: UIControlEvents.ValueChanged)
// self.view.addSubview(segmentedControl)
initSegmented()
initAddImage()
initReplyBar();
// initTextField()
initView();
}
func initView(){
self.textView.delegate = self
oneView.userInteractionEnabled = true
let oneTapGR = UITapGestureRecognizer(target: self, action: "oneQuestionAction:")
oneView.addGestureRecognizer(oneTapGR)
twoView.userInteractionEnabled = true
let twoTapGR = UITapGestureRecognizer(target: self, action: "twoQuestionAction:")
twoView.addGestureRecognizer(twoTapGR)
threeView.userInteractionEnabled = true
let threeTapGR = UITapGestureRecognizer(target: self, action: "threeQuestionAction:")
threeView.addGestureRecognizer(threeTapGR)
fourView.userInteractionEnabled = true
let fourTapGR = UITapGestureRecognizer(target: self, action: "fourQuestionAction:")
fourView.addGestureRecognizer(fourTapGR)
}
func oneQuestionAction(sender:UITapGestureRecognizer) {
self.containerView.alpha = 1
answerFlag = 1
self.textView.text = ""
self.textView.becomeFirstResponder()
}
func twoQuestionAction(sender:UITapGestureRecognizer) {
self.containerView.alpha = 1
answerFlag = 2
self.textView.text = ""
self.textView.becomeFirstResponder()
}
func threeQuestionAction(sender:UITapGestureRecognizer) {
self.containerView.alpha = 1
answerFlag = 3
self.textView.text = ""
self.textView.becomeFirstResponder()
}
func fourQuestionAction(sender:UITapGestureRecognizer) {
self.containerView.alpha = 1
answerFlag = 4
self.textView.text = ""
self.textView.becomeFirstResponder()
}
func initReplyBar() {
self.containerView = UIView(frame: CGRectMake(0, self.view.bounds.height, self.view.bounds.width, 110))
self.containerView.backgroundColor = UIColor(red: 0.949, green: 0.949, blue: 0.949, alpha: 1.00)
self.cancleButton = UIButton(frame: CGRectMake(5, 5, 50, 30))
self.cancleButton.setTitle("取消", forState: UIControlState.Normal)
self.cancleButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
self.cancleButton.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Highlighted)
self.cancleButton.titleLabel?.font = UIFont.systemFontOfSize(14)
self.cancleButton.addTarget(self, action: "cancleReply", forControlEvents: UIControlEvents.TouchUpInside)
self.sendButton = UIButton(frame: CGRectMake(self.containerView.frame.size.width-5-50, 5, 50, 30))
self.sendButton.setTitle("确定", forState: UIControlState.Normal)
self.sendButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
self.sendButton.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Highlighted)
self.sendButton.titleLabel?.font = UIFont.systemFontOfSize(14)
self.sendButton.addTarget(self, action: "sendReply", forControlEvents: UIControlEvents.TouchUpInside)
self.lableView = UILabel(frame: CGRectMake((self.containerView.frame.size.width)/2-40, 5, 80, 30))
self.lableView.text = "限制10字"
self.lableView.textAlignment = NSTextAlignment.Center
self.lableView.textColor = UIColor.grayColor()
self.textView = UITextView(frame: CGRectMake(15, 50, self.containerView.frame.size.width-30, 40))
self.textView.delegate = self
textView.layer.borderColor = UIColor.grayColor().CGColor;
textView.layer.borderWidth = 1;
textView.layer.cornerRadius = 6;
textView.layer.masksToBounds = true;
textView.userInteractionEnabled = true;
textView.font = UIFont.systemFontOfSize(18)
textView.scrollEnabled = true;
textView.autoresizingMask = UIViewAutoresizing.FlexibleHeight
let tapDismiss = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
self.view.addGestureRecognizer(tapDismiss)
self.scrollView.addGestureRecognizer(tapDismiss)
self.containerView.addSubview(self.cancleButton)
self.containerView.addSubview(self.lableView)
self.containerView.addSubview(self.sendButton)
self.containerView.addSubview(self.textView)
self.view.addSubview(containerView)
self.containerView.alpha = 0
}
func textViewDidBeginEditing(textView: UITextView) {
if(textView.tag == 10){
if(textView.text == " 这里写题目"){
textView.text = ""
}
}
}
func textViewDidChange(textView: UITextView) {
textView.scrollRangeToVisible(textView.selectedRange)
}
func textViewDidEndEditing(textView: UITextView) {
if(textView.tag == 10){
if(textView.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == ""){
textView.text = " 这里写题目"
}
}
}
func keyboardDidShow(notification:NSNotification) {
self.view.bringSubviewToFront(containerView)
let userInfo: NSDictionary = notification.userInfo! as NSDictionary
let v : NSValue = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyHeight = v.CGRectValue().size.height
let duration = userInfo.objectForKey(UIKeyboardAnimationDurationUserInfoKey) as! NSNumber
let curve:NSNumber = userInfo.objectForKey(UIKeyboardAnimationCurveUserInfoKey) as! NSNumber
let temp:UIViewAnimationCurve = UIViewAnimationCurve(rawValue: curve.integerValue)!
UIView.animateWithDuration(duration.doubleValue, animations: {
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationCurve(temp)
self.containerView.frame = CGRectMake(0, self.view.frame.size.height-keyHeight-110, self.view.bounds.size.width, 110)
})
}
func keyboardDidHidden(notification:NSNotification) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.25)
self.containerView.frame = CGRectMake(0, self.view.frame.size.height, self.view.bounds.size.width, 110)
self.containerView.alpha = 0
UIView.commitAnimations()
}
func dismissKeyboard(){
self.textView.resignFirstResponder()
self.titleView.resignFirstResponder()
}
func cancleReply() {
self.textView.resignFirstResponder()
}
func sendReply() {
let answer:String! = self.textView.text
if(answer.characters.count > 10 || answer!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == ""){
MCUtils.showCustomHUD(self, aMsg: "不能为空或者超过最大字数限制", aType: .Error)
}else{
if(answerFlag == 1){
self.answerOne.text = answer
}else if(answerFlag == 2){
self.answerTwo.text = answer
}else if(answerFlag == 3){
self.answerThree.text = answer
}else if(answerFlag == 4){
self.answerFour.text = answer
}
dismissKeyboard()
}
}
// func initTextField(){
// print(self.imageBtn.frame.origin.y)
// one = UITextField(frame: CGRectMake(0, 800, 300, 300))
// one.borderStyle = UITextBorderStyle.None
// one.backgroundColor = UIColor.redColor()
// self.scrollView.addSubview(one)
// }
func initAddImage() {
imageBtn.userInteractionEnabled = true
let tapGR = UITapGestureRecognizer(target: self, action: "tapHandler:")
imageBtn.addGestureRecognizer(tapGR)
}
func tapHandler(sender:UITapGestureRecognizer) {
let cameraContainer:DBCameraContainerViewController = DBCameraContainerViewController(delegate: self)
cameraContainer.delegate = self
cameraContainer.setFullScreenMode()
let nav:UINavigationController = UINavigationController(rootViewController: cameraContainer)
nav.navigationBarHidden = true
self.presentViewController(nav, animated: true, completion: nil)
}
func camera(cameraViewController: AnyObject!, didFinishWithImage image: UIImage!, withMetadata metadata: [NSObject : AnyObject]!) {
imageBtn.image = image
icon = image
// self.icon = image
cameraViewController.restoreFullScreenMode()
self.presentedViewController?.dismissViewControllerAnimated(true, completion: nil)
}
func dismissCamera(cameraViewController: AnyObject!) {
self.presentedViewController?.dismissViewControllerAnimated(true, completion: nil)
cameraViewController.restoreFullScreenMode()
}
func initSegmented() {
let attributes = [NSForegroundColorAttributeName:UIColor(red: 0.329, green: 0.318, blue: 0.518, alpha: 1.00) ]
segmentedbtn.setTitleTextAttributes(attributes, forState: UIControlState.Normal)
let highlightedAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]
segmentedbtn.setTitleTextAttributes(highlightedAttributes, forState: UIControlState.Selected)
answerSegment.setTitleTextAttributes(attributes, forState: UIControlState.Normal)
answerSegment.setTitleTextAttributes(highlightedAttributes, forState: UIControlState.Selected)
}
@IBAction func answerSegmentAction(sender: UISegmentedControl) {
reallyAnswer = sender.titleForSegmentAtIndex(sender.selectedSegmentIndex)
}
@IBAction func segmentedAction(sender: UISegmentedControl) {
questionType = sender.titleForSegmentAtIndex(sender.selectedSegmentIndex)
if(sender.selectedSegmentIndex == 0){
self.oneView.hidden = false
self.twoView.hidden = false
self.threeView.hidden = false
self.fourView.hidden = false
self.oneUploadBtn.hidden = false
self.twoUploadBtn.hidden = true
self.answerSegment.hidden = true
}else if(sender.selectedSegmentIndex == 1){
self.oneView.hidden = true
self.twoView.hidden = true
self.threeView.hidden = true
self.fourView.hidden = true
self.oneUploadBtn.hidden = true
self.twoUploadBtn.hidden = false
self.answerSegment.hidden = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func shareFunction(sender: UIButton) {
let shareImg: UIImage! = UIImage(named: "share_default")
let shareText:String! = "jdskfjlskdjflkdsjflkdjf"
ShareUtil.shareInitWithTextAndPicture(self, text: shareText, image: shareImg!,shareUrl:"http://www.baidu.com", callDelegate: self)
}
func didFinishGetUMSocialDataInViewController(response: UMSocialResponseEntity!) {
if(response.responseCode == UMSResponseCodeSuccess) {
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
MobClick.beginLogPageView("addQuestion")
// //注册键盘通知事件
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidHidden:", name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
MobClick.endLogPageView("addQuestion")
NSNotificationCenter.defaultCenter().removeObserver(self)
}
@IBAction func addQuestionAction(sender: UIButton) {
print("addQuestionAction............")
self.oneUploadBtn?.enabled = false
self.twoUploadBtn?.enabled = false
self.type = "choice"
self.answerTitle = self.titleView.text
self.one = self.answerOne.text
self.two = self.answerTwo.text
self.three = self.answerThree.text
self.four = self.answerFour.text
if(answerTitle.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == "" || answerTitle == " 这里写题目"){
print("题目不能为空,必填项")
MCUtils.showCustomHUD(self, aMsg: "题目不能为空,必填项", aType: .Error)
self.oneUploadBtn?.enabled = true
self.twoUploadBtn?.enabled = true
return
}
if(answerTitle.characters.count > 50){
print("题目字数不能超过50字")
MCUtils.showCustomHUD(self, aMsg: "题目字数不能超过50字", aType: .Error)
self.oneUploadBtn?.enabled = true
self.twoUploadBtn?.enabled = true
return
}
if(self.questionType == "判断题"){
self.one = reallyAnswer
self.type = "judge"
}else{
if(one!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == "" || one == "正确答案"){
print("答案不能为空,必填项")
MCUtils.showCustomHUD(self, aMsg: "答案不能为空,必填项", aType: .Error)
self.oneUploadBtn?.enabled = true
self.twoUploadBtn?.enabled = true
return
}
if(two!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == "" || two == "错误答案"){
print("答案不能为空,必填项")
MCUtils.showCustomHUD(self, aMsg: "答案不能为空,必填项", aType: .Error)
self.oneUploadBtn?.enabled = true
self.twoUploadBtn?.enabled = true
return
}
if(three!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == "" || three == "错误答案"){
print("答案不能为空,必填项")
MCUtils.showCustomHUD(self, aMsg: "答案不能为空,必填项", aType: .Error)
self.oneUploadBtn?.enabled = true
self.twoUploadBtn?.enabled = true
return
}
if(four!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == "" || four == "错误答案"){
print("答案不能为空,必填项")
MCUtils.showCustomHUD(self, aMsg: "答案不能为空,必填项", aType: .Error)
self.oneUploadBtn?.enabled = true
self.twoUploadBtn?.enabled = true
return
}
}
if(self.icon != nil){
manager.POST(upload_url,
parameters:nil,
constructingBodyWithBlock: { (formData:AFMultipartFormData!) in
let key = "fileIcon"
let value = "fileNameIcon.jpg"
let imageData = UIImageJPEGRepresentation(self.icon, 0.0)
formData.appendPartWithFileData(imageData, name: key, fileName: value, mimeType: "image/jpeg")
},
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
var json = JSON(responseObject)
if "ok" == json["state"].stringValue {
self.iconValue = json["dataObject"].stringValue
self.postTalkToServer()
}else{
self.oneUploadBtn?.enabled = true
self.twoUploadBtn?.enabled = true
MCUtils.showCustomHUD(self, aMsg: "图片上传失败,请稍候再试", aType: .Error)
}
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
self.oneUploadBtn?.enabled = true
self.twoUploadBtn?.enabled = true
MCUtils.showCustomHUD(self, aMsg: "图片上传失败,请稍候再试", aType: .Error)
})
}else{
self.postTalkToServer()
}
}
func postTalkToServer() {
let params = [
"authorId":String(appUserIdSave),
"authorName":String(appUserNickName),
"questionType":self.type,
"title":self.answerTitle,
"icon":self.iconValue,
"answerOne":self.one,
"answerTwo":self.two,
"answerThree":self.three,
"answerFour":self.four
]
self.manager.POST(addTalk_url,
parameters: params,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
var json = JSON(responseObject)
if "ok" == json["state"].stringValue {
self.oneUploadBtn?.enabled = true
self.twoUploadBtn?.enabled = true
// NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "returnPage", userInfo: nil, repeats: false)
MCUtils.showCustomHUD(self, aMsg: "提交成功,返回查看", aType: .Success)
}else{
self.oneUploadBtn?.enabled = true
self.twoUploadBtn?.enabled = true
MCUtils.showCustomHUD(self, aMsg: "提交失败,请稍候再试", aType: .Error)
}
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
self.oneUploadBtn?.enabled = true
self.twoUploadBtn?.enabled = true
MCUtils.showCustomHUD(self, aMsg: "提交失败,请稍候再试", aType: .Error)
})
}
class func showAddQuestionPage(fromNavigation:UINavigationController?){
let addQuestion = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("addQuestion") as! addQuestionController
if (fromNavigation != nil) {
fromNavigation?.pushViewController(addQuestion, animated: true)
} else {
fromNavigation?.presentViewController(addQuestion, animated: true, completion: nil)
}
}
} | mit | 30f5bf751ef968718f4d522264c5d5e7 | 41.391892 | 170 | 0.631934 | 4.901339 | false | false | false | false |
Koalappp/Alamofire | Source/MultipartFormData.swift | 1 | 26343 | //
// MultipartFormData.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
#if os(iOS) || os(watchOS) || os(tvOS)
import MobileCoreServices
#elseif os(OSX)
import CoreServices
#endif
/**
Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.
For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well
and the w3 form documentation.
- https://www.ietf.org/rfc/rfc2388.txt
- https://www.ietf.org/rfc/rfc2045.txt
- https://www.w3.org/TR/html401/interact/forms.html#h-17.13
*/
public class MultipartFormData {
// MARK: - Helper Types
struct EncodingCharacters {
static let CRLF = "\r\n"
}
struct BoundaryGenerator {
enum BoundaryType {
case Initial, Encapsulated, Final
}
static func randomBoundary() -> String {
return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random())
}
static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData {
let boundaryText: String
switch boundaryType {
case .Initial:
boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)"
case .Encapsulated:
boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)"
case .Final:
boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)"
}
return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}
}
class BodyPart {
let headers: [String: String]
let bodyStream: NSInputStream
let bodyContentLength: UInt64
var hasInitialBoundary = false
var hasFinalBoundary = false
init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) {
self.headers = headers
self.bodyStream = bodyStream
self.bodyContentLength = bodyContentLength
}
}
// MARK: - Properties
/// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
public var contentType: String { return "multipart/form-data; boundary=\(boundary)" }
/// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
/// The boundary used to separate the body parts in the encoded form data.
public let boundary: String
private var bodyParts: [BodyPart]
private var bodyPartError: NSError?
private let streamBufferSize: Int
// MARK: - Lifecycle
/**
Creates a multipart form data object.
- returns: The multipart form data object.
*/
public init() {
self.boundary = BoundaryGenerator.randomBoundary()
self.bodyParts = []
/**
* The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
* information, please refer to the following article:
* - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
*/
self.streamBufferSize = 1024
}
// MARK: - Body Parts
/**
Creates a body part from the data and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}` (HTTP Header)
- Encoded data
- Multipart form boundary
- parameter data: The data to encode into the multipart form data.
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
*/
public func appendBodyPart(data data: NSData, name: String) {
let headers = contentHeaders(name: name)
let stream = NSInputStream(data: data)
let length = UInt64(data.length)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the data and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}` (HTTP Header)
- `Content-Type: #{generated mimeType}` (HTTP Header)
- Encoded data
- Multipart form boundary
- parameter data: The data to encode into the multipart form data.
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header.
*/
public func appendBodyPart(data data: NSData, name: String, mimeType: String) {
let headers = contentHeaders(name: name, mimeType: mimeType)
let stream = NSInputStream(data: data)
let length = UInt64(data.length)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the data and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
- `Content-Type: #{mimeType}` (HTTP Header)
- Encoded file data
- Multipart form boundary
- parameter data: The data to encode into the multipart form data.
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
- parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header.
*/
public func appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) {
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
let stream = NSInputStream(data: data)
let length = UInt64(data.length)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the file and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
- `Content-Type: #{generated mimeType}` (HTTP Header)
- Encoded file data
- Multipart form boundary
The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
`fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
system associated MIME type.
- parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
- parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
*/
public func appendBodyPart(fileURL fileURL: NSURL, name: String) {
if let
fileName = fileURL.lastPathComponent,
pathExtension = fileURL.pathExtension
{
let mimeType = mimeTypeForPathExtension(pathExtension)
appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType)
} else {
let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)"
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
}
}
/**
Creates a body part from the file and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
- Content-Type: #{mimeType} (HTTP Header)
- Encoded file data
- Multipart form boundary
- parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
- parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
- parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header.
*/
public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) {
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
//============================================================
// Check 1 - is file URL?
//============================================================
guard fileURL.fileURL else {
let failureReason = "The file URL does not point to a file URL: \(fileURL)"
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
return
}
//============================================================
// Check 2 - is file URL reachable?
//============================================================
var isReachable = true
if #available(OSX 10.10, *), #available(iOS 8.0, *) {
isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil)
}
guard isReachable else {
setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
return
}
//============================================================
// Check 3 - is file URL a directory?
//============================================================
var isDirectory: ObjCBool = false
guard let
path = fileURL.path
where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else
{
let failureReason = "The file URL is a directory, not a file: \(fileURL)"
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
return
}
//============================================================
// Check 4 - can the file size be extracted?
//============================================================
var bodyContentLength: UInt64?
do {
if let
path = fileURL.path,
fileSize = try NSFileManager.defaultManager().attributesOfItemAtPath(path)[NSFileSize] as? NSNumber
{
bodyContentLength = fileSize.unsignedLongLongValue
}
} catch {
// No-op
}
guard let length = bodyContentLength else {
let failureReason = "Could not fetch attributes from the file URL: \(fileURL)"
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
return
}
//============================================================
// Check 5 - can a stream be created from file URL?
//============================================================
guard let stream = NSInputStream(URL: fileURL) else {
let failureReason = "Failed to create an input stream from the file URL: \(fileURL)"
setBodyPartError(code: NSURLErrorCannotOpenFile, failureReason: failureReason)
return
}
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the stream and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
- `Content-Type: #{mimeType}` (HTTP Header)
- Encoded stream data
- Multipart form boundary
- parameter stream: The input stream to encode in the multipart form data.
- parameter length: The content length of the stream.
- parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header.
- parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header.
*/
public func appendBodyPart(
stream stream: NSInputStream,
length: UInt64,
name: String,
fileName: String,
mimeType: String)
{
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part with the headers, stream and length and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- HTTP headers
- Encoded stream data
- Multipart form boundary
- parameter stream: The input stream to encode in the multipart form data.
- parameter length: The content length of the stream.
- parameter headers: The HTTP headers for the body part.
*/
public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) {
let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
bodyParts.append(bodyPart)
}
// MARK: - Data Encoding
/**
Encodes all the appended body parts into a single `NSData` object.
It is important to note that this method will load all the appended body parts into memory all at the same
time. This method should only be used when the encoded data will have a small memory footprint. For large data
cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method.
- throws: An `NSError` if encoding encounters an error.
- returns: The encoded `NSData` if encoding is successful.
*/
public func encode() throws -> NSData {
if let bodyPartError = bodyPartError {
throw bodyPartError
}
let encoded = NSMutableData()
bodyParts.first?.hasInitialBoundary = true
bodyParts.last?.hasFinalBoundary = true
for bodyPart in bodyParts {
let encodedData = try encodeBodyPart(bodyPart)
encoded.appendData(encodedData)
}
return encoded
}
/**
Writes the appended body parts into the given file URL.
This process is facilitated by reading and writing with input and output streams, respectively. Thus,
this approach is very memory efficient and should be used for large body part data.
- parameter fileURL: The file URL to write the multipart form data into.
- throws: An `NSError` if encoding encounters an error.
*/
public func writeEncodedDataToDisk(fileURL: NSURL) throws {
if let bodyPartError = bodyPartError {
throw bodyPartError
}
if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) {
let failureReason = "A file already exists at the given file URL: \(fileURL)"
throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason)
} else if !fileURL.fileURL {
let failureReason = "The URL does not point to a valid file: \(fileURL)"
throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorBadURL, failureReason: failureReason)
}
let outputStream: NSOutputStream
if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) {
outputStream = possibleOutputStream
} else {
let failureReason = "Failed to create an output stream with the given URL: \(fileURL)"
throw Error.error(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, failureReason: failureReason)
}
outputStream.open()
self.bodyParts.first?.hasInitialBoundary = true
self.bodyParts.last?.hasFinalBoundary = true
for bodyPart in self.bodyParts {
try writeBodyPart(bodyPart, toOutputStream: outputStream)
}
outputStream.close()
}
// MARK: - Private - Body Part Encoding
private func encodeBodyPart(bodyPart: BodyPart) throws -> NSData {
let encoded = NSMutableData()
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
encoded.appendData(initialData)
let headerData = encodeHeaderDataForBodyPart(bodyPart)
encoded.appendData(headerData)
let bodyStreamData = try encodeBodyStreamDataForBodyPart(bodyPart)
encoded.appendData(bodyStreamData)
if bodyPart.hasFinalBoundary {
encoded.appendData(finalBoundaryData())
}
return encoded
}
private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData {
var headerText = ""
for (key, value) in bodyPart.headers {
headerText += "\(key): \(value)\(EncodingCharacters.CRLF)"
}
headerText += EncodingCharacters.CRLF
return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}
private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData {
let inputStream = bodyPart.bodyStream
inputStream.open()
var error: NSError?
let encoded = NSMutableData()
while inputStream.hasBytesAvailable {
var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
if inputStream.streamError != nil {
error = inputStream.streamError
break
}
if bytesRead > 0 {
encoded.appendBytes(buffer, length: bytesRead)
} else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)"
error = Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason)
break
} else {
break
}
}
inputStream.close()
if let error = error {
throw error
}
return encoded
}
// MARK: - Private - Writing Body Part to Output Stream
private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
try writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream)
try writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream)
try writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream)
try writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream)
}
private func writeInitialBoundaryDataForBodyPart(
bodyPart: BodyPart,
toOutputStream outputStream: NSOutputStream)
throws
{
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
return try writeData(initialData, toOutputStream: outputStream)
}
private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
let headerData = encodeHeaderDataForBodyPart(bodyPart)
return try writeData(headerData, toOutputStream: outputStream)
}
private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
let inputStream = bodyPart.bodyStream
inputStream.open()
while inputStream.hasBytesAvailable {
var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
if let streamError = inputStream.streamError {
throw streamError
}
if bytesRead > 0 {
if buffer.count != bytesRead {
buffer = Array(buffer[0..<bytesRead])
}
try writeBuffer(&buffer, toOutputStream: outputStream)
} else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)"
throw Error.error(domain: NSURLErrorDomain, code: .InputStreamReadFailed, failureReason: failureReason)
} else {
break
}
}
inputStream.close()
}
private func writeFinalBoundaryDataForBodyPart(
bodyPart: BodyPart,
toOutputStream outputStream: NSOutputStream)
throws
{
if bodyPart.hasFinalBoundary {
return try writeData(finalBoundaryData(), toOutputStream: outputStream)
}
}
// MARK: - Private - Writing Buffered Data to Output Stream
private func writeData(data: NSData, toOutputStream outputStream: NSOutputStream) throws {
var buffer = [UInt8](count: data.length, repeatedValue: 0)
data.getBytes(&buffer, length: data.length)
return try writeBuffer(&buffer, toOutputStream: outputStream)
}
private func writeBuffer(inout buffer: [UInt8], toOutputStream outputStream: NSOutputStream) throws {
var bytesToWrite = buffer.count
while bytesToWrite > 0 {
if outputStream.hasSpaceAvailable {
let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
if let streamError = outputStream.streamError {
throw streamError
}
if bytesWritten < 0 {
let failureReason = "Failed to write to output stream: \(outputStream)"
throw Error.error(domain: NSURLErrorDomain, code: .OutputStreamWriteFailed, failureReason: failureReason)
}
bytesToWrite -= bytesWritten
if bytesToWrite > 0 {
buffer = Array(buffer[bytesWritten..<buffer.count])
}
} else if let streamError = outputStream.streamError {
throw streamError
}
}
}
// MARK: - Private - Mime Type
private func mimeTypeForPathExtension(pathExtension: String) -> String {
if let
id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(),
contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue()
{
return contentType as String
}
return "application/octet-stream"
}
// MARK: - Private - Content Headers
private func contentHeaders(name name: String) -> [String: String] {
return ["Content-Disposition": "form-data; name=\"\(name)\""]
}
private func contentHeaders(name name: String, mimeType: String) -> [String: String] {
return [
"Content-Disposition": "form-data; name=\"\(name)\"",
"Content-Type": "\(mimeType)"
]
}
private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] {
return [
"Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"",
"Content-Type": "\(mimeType)"
]
}
// MARK: - Private - Boundary Encoding
private func initialBoundaryData() -> NSData {
return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary)
}
private func encapsulatedBoundaryData() -> NSData {
return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary)
}
private func finalBoundaryData() -> NSData {
return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary)
}
// MARK: - Private - Errors
private func setBodyPartError(code code: Int, failureReason: String) {
guard bodyPartError == nil else { return }
bodyPartError = Error.error(domain: NSURLErrorDomain, code: code, failureReason: failureReason)
}
}
| mit | 4601be536aa5a7de48d2ed75725e8ed6 | 38.974203 | 128 | 0.636792 | 5.154177 | false | false | false | false |
Mars182838/WJCycleScrollView | WJCycleScrollView/Extentions/UIColorExtensions.swift | 3 | 2823 | //
// UIColorExtensions.swift
// EZSwiftExtensions
//
// Created by Goktug Yilmaz on 15/07/15.
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit
extension UIColor {
/// EZSE: init method with RGB values from 0 to 255, instead of 0 to 1. With alpha(default:1)
public convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1) {
self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a)
}
/// EZSE: init method with hex string and alpha(default: 1)
public convenience init?(hexString: String, alpha: CGFloat = 1.0) {
var formatted = hexString.stringByReplacingOccurrencesOfString("0x", withString: "")
formatted = formatted.stringByReplacingOccurrencesOfString("#", withString: "")
if let hex = Int(formatted, radix: 16) {
let red = CGFloat(CGFloat((hex & 0xFF0000) >> 16)/255.0)
let green = CGFloat(CGFloat((hex & 0x00FF00) >> 8)/255.0)
let blue = CGFloat(CGFloat((hex & 0x0000FF) >> 0)/255.0)
self.init(red: red, green: green, blue: blue, alpha: alpha) } else {
return nil
}
}
/// EZSE: init method from Gray value and alpha(default:1)
public convenience init(gray: CGFloat, alpha: CGFloat = 1) {
self.init(red: gray/255, green: gray/255, blue: gray/255, alpha: alpha)
}
/// EZSE: Red component of UIColor (get-only)
public var redComponent: Int {
var r: CGFloat = 0
getRed(&r, green: nil, blue: nil, alpha: nil)
return Int(r * 255)
}
/// EZSE: Green component of UIColor (get-only)
public var greenComponent: Int {
var g: CGFloat = 0
getRed(nil, green: &g, blue: nil, alpha: nil)
return Int(g * 255)
}
/// EZSE: blue component of UIColor (get-only)
public var blueComponent: Int {
var b: CGFloat = 0
getRed(nil, green: nil, blue: &b, alpha: nil)
return Int(b * 255)
}
/// EZSE: Alpha of UIColor (get-only)
public var alpha: Int {
var a: CGFloat = 0
getRed(nil, green: nil, blue: nil, alpha: &a)
return Int(a)
}
/// EZSE: Returns random UIColor with random alpha(default: false)
public static func randomColor(randomAlpha: Bool = false) -> UIColor {
let randomRed = CGFloat.random()
let randomGreen = CGFloat.random()
let randomBlue = CGFloat.random()
let alpha = randomAlpha ? CGFloat.random() : 1.0
return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: alpha)
}
}
private extension CGFloat {
/// SwiftRandom extension
static func random(lower: CGFloat = 0, _ upper: CGFloat = 1) -> CGFloat {
return CGFloat(Float(arc4random()) / Float(UINT32_MAX)) * (upper - lower) + lower
}
}
| mit | b8645a336cf85586252a023da9a7dcbb | 34.734177 | 97 | 0.610344 | 3.794355 | false | false | false | false |
shadanan/mado | Antlr4Runtime/Sources/Antlr4/Lexer.swift | 1 | 13377 | /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
/// A lexer is recognizer that draws input symbols from a character stream.
/// lexer grammars result in a subclass of this object. A Lexer object
/// uses simplified match() and error recovery mechanisms in the interest
/// of speed.
import Foundation
//public class Lexer : Recognizer<Int, LexerATNSimulator>
open class Lexer: Recognizer<LexerATNSimulator>
, TokenSource {
public static let EOF: Int = -1
public static let DEFAULT_MODE: Int = 0
public static let MORE: Int = -2
public static let SKIP: Int = -3
public static let DEFAULT_TOKEN_CHANNEL: Int = CommonToken.DEFAULT_CHANNEL
public static let HIDDEN: Int = CommonToken.HIDDEN_CHANNEL
public static let MIN_CHAR_VALUE: Int = Character.MIN_VALUE;
public static let MAX_CHAR_VALUE: Int = Character.MAX_VALUE;
public var _input: CharStream?
internal var _tokenFactorySourcePair: (TokenSource?, CharStream?)
/// How to create token objects
internal var _factory: TokenFactory = CommonTokenFactory.DEFAULT
/// The goal of all lexer rules/methods is to create a token object.
/// This is an instance variable as multiple rules may collaborate to
/// create a single token. nextToken will return this object after
/// matching lexer rule(s). If you subclass to allow multiple token
/// emissions, then set this to the last token to be matched or
/// something nonnull so that the auto token emit mechanism will not
/// emit another token.
public var _token: Token?
/// What character index in the stream did the current token start at?
/// Needed, for example, to get the text for current token. Set at
/// the start of nextToken.
public var _tokenStartCharIndex: Int = -1
/// The line on which the first character of the token resides
public var _tokenStartLine: Int = 0
/// The character position of first character within the line
public var _tokenStartCharPositionInLine: Int = 0
/// Once we see EOF on char stream, next token will be EOF.
/// If you have DONE : EOF ; then you see DONE EOF.
public var _hitEOF: Bool = false
/// The channel number for the current token
public var _channel: Int = 0
/// The token type for the current token
public var _type: Int = 0
public final var _modeStack: Stack<Int> = Stack<Int>()
public var _mode: Int = Lexer.DEFAULT_MODE
/// You can set the text for the current token to override what is in
/// the input char buffer. Use setText() or can set this instance var.
public var _text: String?
public override init() {
}
public init(_ input: CharStream) {
super.init()
self._input = input
self._tokenFactorySourcePair = (self, input)
}
open func reset() throws {
// wack Lexer state variables
if let _input = _input {
try _input.seek(0) // rewind the input
}
_token = nil
_type = CommonToken.INVALID_TYPE
_channel = CommonToken.DEFAULT_CHANNEL
_tokenStartCharIndex = -1
_tokenStartCharPositionInLine = -1
_tokenStartLine = -1
_text = nil
_hitEOF = false
_mode = Lexer.DEFAULT_MODE
_modeStack.clear()
getInterpreter().reset()
}
/// Return a token from this source; i.e., match a token on the char
/// stream.
open func nextToken() throws -> Token {
guard let _input = _input else {
throw ANTLRError.illegalState(msg: "nextToken requires a non-null input stream.")
}
// Mark start location in char stream so unbuffered streams are
// guaranteed at least have text of current token
var tokenStartMarker: Int = _input.mark()
defer {
// make sure we release marker after match or
// unbuffered char stream will keep buffering
try! _input.release(tokenStartMarker)
}
do {
outer:
while true {
if _hitEOF {
emitEOF()
return _token!
}
_token = nil
_channel = CommonToken.DEFAULT_CHANNEL
_tokenStartCharIndex = _input.index()
_tokenStartCharPositionInLine = getInterpreter().getCharPositionInLine()
_tokenStartLine = getInterpreter().getLine()
_text = nil
repeat {
_type = CommonToken.INVALID_TYPE
var ttype: Int
do {
ttype = try getInterpreter().match(_input, _mode)
}
catch ANTLRException.recognition(let e) {
notifyListeners(e as! LexerNoViableAltException, recognizer: self)
try recover(e as! LexerNoViableAltException)
ttype = Lexer.SKIP
}
if try _input.LA(1) == BufferedTokenStream.EOF {
_hitEOF = true
}
if _type == CommonToken.INVALID_TYPE {
_type = ttype
}
if _type == Lexer.SKIP {
continue outer
}
} while _type == Lexer.MORE
if _token == nil {
emit()
}
return _token!
}
}
}
/// Instruct the lexer to skip creating a token for current lexer rule
/// and look for another token. nextToken() knows to keep looking when
/// a lexer rule finishes with token set to SKIP_TOKEN. Recall that
/// if token==null at end of any token rule, it creates one for you
/// and emits it.
open func skip() {
_type = Lexer.SKIP
}
open func more() {
_type = Lexer.MORE
}
open func mode(_ m: Int) {
_mode = m
}
open func pushMode(_ m: Int) {
if LexerATNSimulator.debug {
print("pushMode \(m)")
}
_modeStack.push(_mode)
mode(m)
}
@discardableResult
open func popMode() throws -> Int {
if _modeStack.isEmpty {
throw ANTLRError.unsupportedOperation(msg: " EmptyStackException")
}
if LexerATNSimulator.debug {
print("popMode back to \(String(describing: _modeStack.peek()))")
}
mode(_modeStack.pop())
return _mode
}
open override func setTokenFactory(_ factory: TokenFactory) {
self._factory = factory
}
open override func getTokenFactory() -> TokenFactory {
return _factory
}
/// Set the char stream and reset the lexer
open override func setInputStream(_ input: IntStream) throws {
self._input = nil
self._tokenFactorySourcePair = (self, _input!)
try reset()
self._input = input as? CharStream
self._tokenFactorySourcePair = (self, _input!)
}
open func getSourceName() -> String {
return _input!.getSourceName()
}
open func getInputStream() -> CharStream? {
return _input
}
/// By default does not support multiple emits per nextToken invocation
/// for efficiency reasons. Subclass and override this method, nextToken,
/// and getToken (to push tokens into a list and pull from that list
/// rather than a single variable as this implementation does).
open func emit(_ token: Token) {
//System.err.println("emit "+token);
self._token = token
}
/// The standard method called to automatically emit a token at the
/// outermost lexical rule. The token object should point into the
/// char buffer start..stop. If there is a text override in 'text',
/// use that to set the token's text. Override this method to emit
/// custom Token objects or provide a new factory.
@discardableResult
open func emit() -> Token {
let t: Token = _factory.create(_tokenFactorySourcePair, _type, _text, _channel, _tokenStartCharIndex, getCharIndex() - 1,
_tokenStartLine, _tokenStartCharPositionInLine)
emit(t)
return t
}
@discardableResult
open func emitEOF() -> Token {
let cpos: Int = getCharPositionInLine()
let line: Int = getLine()
let eof: Token = _factory.create(
_tokenFactorySourcePair,
CommonToken.EOF,
nil,
CommonToken.DEFAULT_CHANNEL,
_input!.index(),
_input!.index() - 1,
line,
cpos)
emit(eof)
return eof
}
open func getLine() -> Int {
return getInterpreter().getLine()
}
open func getCharPositionInLine() -> Int {
return getInterpreter().getCharPositionInLine()
}
open func setLine(_ line: Int) {
getInterpreter().setLine(line)
}
open func setCharPositionInLine(_ charPositionInLine: Int) {
getInterpreter().setCharPositionInLine(charPositionInLine)
}
/// What is the index of the current character of lookahead?
open func getCharIndex() -> Int {
return _input!.index()
}
/// Return the text matched so far for the current token or any
/// text override.
open func getText() -> String {
if _text != nil {
return _text!
}
return getInterpreter().getText(_input!)
}
/// Set the complete text of this token; it wipes any previous
/// changes to the text.
open func setText(_ text: String) {
self._text = text
}
/// Override if emitting multiple tokens.
open func getToken() -> Token {
return _token!
}
open func setToken(_ _token: Token) {
self._token = _token
}
open func setType(_ ttype: Int) {
_type = ttype
}
open func getType() -> Int {
return _type
}
open func setChannel(_ channel: Int) {
_channel = channel
}
open func getChannel() -> Int {
return _channel
}
open func getChannelNames() -> [String]? {
return nil
}
open func getModeNames() -> [String]? {
return nil
}
/// Used to print out token names like ID during debugging and
/// error reporting. The generated parsers implement a method
/// that overrides this to point to their String[] tokenNames.
override
open func getTokenNames() -> [String?]? {
return nil
}
/// Return a list of all Token objects in input char stream.
/// Forces load of all tokens. Does not include EOF token.
open func getAllTokens() throws -> Array<Token> {
var tokens: Array<Token> = Array<Token>()
var t: Token = try nextToken()
while t.getType() != CommonToken.EOF {
tokens.append(t)
t = try nextToken()
}
return tokens
}
open func recover(_ e: LexerNoViableAltException) throws {
if try _input!.LA(1) != BufferedTokenStream.EOF {
// skip a char and try again
try getInterpreter().consume(_input!)
}
}
open func notifyListeners<T:ATNSimulator>(_ e: LexerNoViableAltException, recognizer: Recognizer<T>) {
let text: String = _input!.getText(Interval.of(_tokenStartCharIndex, _input!.index()))
let msg: String = "token recognition error at: '\(getErrorDisplay(text))'"
let listener: ANTLRErrorListener = getErrorListenerDispatch()
listener.syntaxError(recognizer, nil, _tokenStartLine, _tokenStartCharPositionInLine, msg, e)
}
open func getErrorDisplay(_ s: String) -> String {
let buf: StringBuilder = StringBuilder()
for c: Character in s.characters {
buf.append(getErrorDisplay(c))
}
return buf.toString()
}
open func getErrorDisplay(_ c: Character) -> String {
var s: String = String(c) // String.valueOf(c as Character);
if c.integerValue == CommonToken.EOF {
s = "<EOF>"
}
switch s {
// case CommonToken.EOF :
// s = "<EOF>";
// break;
case "\n":
s = "\\n"
case "\t":
s = "\\t"
case "\r":
s = "\\r"
default:
break
}
return s
}
open func getCharErrorDisplay(_ c: Character) -> String {
let s: String = getErrorDisplay(c)
return "'\(s)'"
}
/// Lexers can normally match any char in it's vocabulary after matching
/// a token, so do the easy thing and just kill a character and hope
/// it all works out. You can instead use the rule invocation stack
/// to do sophisticated error recovery if you are in a fragment rule.
//public func recover(re : RecognitionException) {
open func recover(_ re: AnyObject) throws {
//System.out.println("consuming char "+(char)input.LA(1)+" during recovery");
//re.printStackTrace();
// TODO: Do we lose character or line position information?
try _input!.consume()
}
}
| mit | 051aa19e4627b6c689b4b7c7a872ceaf | 30.926014 | 129 | 0.586155 | 4.560859 | false | false | false | false |
jihun-kang/ios_a2big_sdk | A2bigSDK/FrameStore.swift | 1 | 7656 | import UIKit
import ImageIO
/// Responsible for storing and updating the frames of a single GIF.
class FrameStore {
/// Maximum duration to increment the frame timer with.
let maxTimeStep = 1.0
/// An array of animated frames from a single GIF image.
var animatedFrames = [AnimatedFrame]()
/// The target size for all frames.
let size: CGSize
/// The content mode to use when resizing.
let contentMode: UIViewContentMode
/// Maximum number of frames to load at once
let bufferFrameCount: Int
/// The total number of frames in the GIF.
var frameCount = 0
/// A reference to the original image source.
var imageSource: CGImageSource
/// The index of the current GIF frame.
var currentFrameIndex = 0 {
didSet {
previousFrameIndex = oldValue
}
}
/// The index of the previous GIF frame.
var previousFrameIndex = 0 {
didSet {
preloadFrameQueue.async {
self.updatePreloadedFrames()
}
}
}
/// Time elapsed since the last frame change. Used to determine when the frame should be updated.
var timeSinceLastFrameChange: TimeInterval = 0.0
/// Specifies whether GIF frames should be resized.
var shouldResizeFrames = true
/// Dispatch queue used for preloading images.
private lazy var preloadFrameQueue: DispatchQueue = {
return DispatchQueue(label: "co.kaishin.Gifu.preloadQueue")
}()
/// The current image frame to show.
var currentFrameImage: UIImage? {
return frame(at: currentFrameIndex)
}
/// The current frame duration
var currentFrameDuration: TimeInterval {
return duration(at: currentFrameIndex)
}
/// Is this image animatable?
var isAnimatable: Bool {
return imageSource.isAnimatedGIF
}
/// Creates an animator instance from raw GIF image data and an `Animatable` delegate.
///
/// - parameter data: The raw GIF image data.
/// - parameter delegate: An `Animatable` delegate.
init(data: Data, size: CGSize, contentMode: UIViewContentMode, framePreloadCount: Int) {
let options = [String(kCGImageSourceShouldCache): kCFBooleanFalse] as CFDictionary
self.imageSource = CGImageSourceCreateWithData(data as CFData, options) ?? CGImageSourceCreateIncremental(options)
self.size = size
self.contentMode = contentMode
self.bufferFrameCount = framePreloadCount
}
// MARK: - Frames
/// Loads the frames from an image source, resizes them, then caches them in `animatedFrames`.
func prepareFrames(_ completionHandler: ((Void) -> Void)? = .none) {
frameCount = Int(CGImageSourceGetCount(imageSource))
animatedFrames.reserveCapacity(frameCount)
preloadFrameQueue.async {
self.setupAnimatedFrames()
if let handler = completionHandler { handler() }
}
}
/// Returns the frame at a particular index.
///
/// - parameter index: The index of the frame.
/// - returns: An optional image at a given frame.
func frame(at index: Int) -> UIImage? {
return animatedFrames[safe: index]?.image
}
/// Returns the duration at a particular index.
///
/// - parameter index: The index of the duration.
/// - returns: The duration of the given frame.
func duration(at index: Int) -> TimeInterval {
return animatedFrames[safe: index]?.duration ?? TimeInterval.infinity
}
/// Checks whether the frame should be changed and calls a handler with the results.
///
/// - parameter duration: A `CFTimeInterval` value that will be used to determine whether frame should be changed.
/// - parameter handler: A function that takes a `Bool` and returns nothing. It will be called with the frame change result.
func shouldChangeFrame(with duration: CFTimeInterval, handler: (Bool) -> Void) {
incrementTimeSinceLastFrameChange(with: duration)
if currentFrameDuration > timeSinceLastFrameChange {
handler(false)
} else {
resetTimeSinceLastFrameChange()
incrementCurrentFrameIndex()
handler(true)
}
}
}
private extension FrameStore {
/// Whether preloading is needed or not.
var preloadingIsNeeded: Bool {
return bufferFrameCount < frameCount - 1
}
/// Optionally loads a single frame from an image source, resizes it if required, then returns an `UIImage`.
///
/// - parameter index: The index of the frame to load.
/// - returns: An optional `UIImage` instance.
func loadFrame(at index: Int) -> UIImage? {
guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else { return .none }
let image = UIImage(cgImage: imageRef)
let scaledImage: UIImage?
if shouldResizeFrames {
switch self.contentMode {
case .scaleAspectFit: scaledImage = image.constrained(by: size)
case .scaleAspectFill: scaledImage = image.filling(size: size)
default: scaledImage = image.resized(to: size)
}
} else {
scaledImage = image
}
return scaledImage
}
/// Updates the frames by preloading new ones and replacing the previous frame with a placeholder.
func updatePreloadedFrames() {
if !preloadingIsNeeded { return }
animatedFrames[previousFrameIndex] = animatedFrames[previousFrameIndex].placeholderFrame
preloadIndexes(withStartingIndex: currentFrameIndex).forEach { index in
let currentAnimatedFrame = animatedFrames[index]
if !currentAnimatedFrame.isPlaceholder { return }
animatedFrames[index] = currentAnimatedFrame.makeAnimatedFrame(with: loadFrame(at: index))
}
}
/// Increments the `timeSinceLastFrameChange` property with a given duration.
///
/// - parameter duration: An `NSTimeInterval` value to increment the `timeSinceLastFrameChange` property with.
func incrementTimeSinceLastFrameChange(with duration: TimeInterval) {
timeSinceLastFrameChange += min(maxTimeStep, duration)
}
/// Ensures that `timeSinceLastFrameChange` remains accurate after each frame change by substracting the `currentFrameDuration`.
func resetTimeSinceLastFrameChange() {
timeSinceLastFrameChange -= currentFrameDuration
}
/// Increments the `currentFrameIndex` property.
func incrementCurrentFrameIndex() {
currentFrameIndex = increment(frameIndex: currentFrameIndex)
}
/// Increments a given frame index, taking into account the `frameCount` and looping when necessary.
///
/// - parameter index: The `Int` value to increment.
/// - parameter byValue: The `Int` value to increment with.
/// - returns: A new `Int` value.
func increment(frameIndex: Int, by value: Int = 1) -> Int {
return (frameIndex + value) % frameCount
}
/// Returns the indexes of the frames to preload based on a starting frame index.
///
/// - parameter index: Starting index.
/// - returns: An array of indexes to preload.
func preloadIndexes(withStartingIndex index: Int) -> [Int] {
let nextIndex = increment(frameIndex: index)
let lastIndex = increment(frameIndex: index, by: bufferFrameCount)
if lastIndex >= nextIndex {
return [Int](nextIndex...lastIndex)
} else {
return [Int](nextIndex..<frameCount) + [Int](0...lastIndex)
}
}
/// Set up animated frames after resetting them if necessary.
func setupAnimatedFrames() {
resetAnimatedFrames()
(0..<frameCount).forEach { index in
let frameDuration = CGImageFrameDuration(with: imageSource, atIndex: index)
animatedFrames += [AnimatedFrame(image: .none, duration: frameDuration)]
if index > bufferFrameCount { return }
animatedFrames[index] = animatedFrames[index].makeAnimatedFrame(with: loadFrame(at: index))
}
}
/// Reset animated frames.
func resetAnimatedFrames() {
animatedFrames = []
}
}
| apache-2.0 | b4b37b43eee3f2b8fb393b06c89bb2a9 | 33.026667 | 130 | 0.709509 | 4.91084 | false | false | false | false |
CombineCommunity/CombineExt | Tests/PrefixWhileBehaviorTests.swift | 1 | 4624 | //
// PrefixWhileBehaviorTests.swift
// CombineExt
//
// Created by Jasdev Singh on 29/12/2020.
// Copyright © 2020 Combine Community. All rights reserved.
//
#if !os(watchOS)
import Combine
import CombineExt
import XCTest
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
final class PrefixWhileBehaviorTests: XCTestCase {
private struct SomeError: Error, Equatable {}
private var cancellable: AnyCancellable!
func testExclusiveValueEventsWithFinished() {
let intSubject = PassthroughSubject<Int, Never>()
var values = [Int]()
var completions = [Subscribers.Completion<Never>]()
cancellable = intSubject
.prefix(
while: { $0 % 2 == 0 },
behavior: .exclusive
)
.sink(
receiveCompletion: { completions.append($0) },
receiveValue: { values.append($0) }
)
[0, 2, 4, 5]
.forEach(intSubject.send)
XCTAssertEqual(values, [0, 2, 4])
XCTAssertEqual(completions, [.finished])
}
func testExclusiveValueEventsWithError() {
let intSubject = PassthroughSubject<Int, SomeError>()
var values = [Int]()
var completions = [Subscribers.Completion<SomeError>]()
cancellable = intSubject
.prefix(
while: { $0 % 2 == 0 },
behavior: .exclusive
)
.sink(
receiveCompletion: { completions.append($0) },
receiveValue: { values.append($0) }
)
[0, 2, 4]
.forEach(intSubject.send)
intSubject.send(completion: .failure(.init()))
XCTAssertEqual(values, [0, 2, 4])
XCTAssertEqual(completions, [.failure(.init())])
}
func testInclusiveValueEventsWithStopElement() {
let intSubject = PassthroughSubject<Int, Never>()
var values = [Int]()
var completions = [Subscribers.Completion<Never>]()
cancellable = intSubject
.prefix(
while: { $0 % 2 == 0 },
behavior: .inclusive
)
.sink(
receiveCompletion: { completions.append($0) },
receiveValue: { values.append($0) }
)
[0, 2, 4, 5]
.forEach(intSubject.send)
XCTAssertEqual(values, [0, 2, 4, 5])
XCTAssertEqual(completions, [.finished])
}
func testInclusiveValueEventsWithErrorAfterStopElement() {
let intSubject = PassthroughSubject<Int, SomeError>()
var values = [Int]()
var completions = [Subscribers.Completion<SomeError>]()
cancellable = intSubject
.prefix(
while: { $0 % 2 == 0 },
behavior: .inclusive
)
.sink(
receiveCompletion: { completions.append($0) },
receiveValue: { values.append($0) }
)
[0, 2, 4, 5]
.forEach(intSubject.send)
intSubject.send(completion: .failure(.init()))
XCTAssertEqual(values, [0, 2, 4, 5])
XCTAssertEqual(completions, [.finished])
}
func testInclusiveValueEventsWithErrorBeforeStop() {
let intSubject = PassthroughSubject<Int, SomeError>()
var values = [Int]()
var completions = [Subscribers.Completion<SomeError>]()
cancellable = intSubject
.prefix(
while: { $0 % 2 == 0 },
behavior: .inclusive
)
.sink(
receiveCompletion: { completions.append($0) },
receiveValue: { values.append($0) }
)
[0, 2, 4]
.forEach(intSubject.send)
intSubject.send(completion: .failure(.init()))
XCTAssertEqual(values, [0, 2, 4])
XCTAssertEqual(completions, [.failure(.init())])
}
func testInclusiveEarlyCompletion() {
let intSubject = PassthroughSubject<Int, SomeError>()
var values = [Int]()
var completions = [Subscribers.Completion<SomeError>]()
cancellable = intSubject
.prefix(
while: { $0 % 2 == 0 },
behavior: .inclusive
)
.sink(
receiveCompletion: { completions.append($0) },
receiveValue: { values.append($0) }
)
[0, 2, 4]
.forEach(intSubject.send)
intSubject.send(completion: .finished)
XCTAssertEqual(values, [0, 2, 4])
XCTAssertEqual(completions, [.finished])
}
}
#endif
| mit | 6c7f0adfcfd2f828aa93cecd8ac52acb | 26.849398 | 63 | 0.536232 | 4.765979 | false | true | false | false |
strike65/SwiftyStats | SwiftyStats/CommonSource/Shared/StatUtils/r_derived_macros.swift | 1 | 5068 | //
// Created by VT on 20.07.18.
// Copyright © 2018 strike65. All rights reserved.
//
/*
Copyright (2017-2019) strike65
GNU GPL 3+
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
/*************************************************************/
/* The R macros as free swift functions */
/*************************************************************/
extension Helpers {
/*
* Compute the log of a sum from logs of terms, i.e.,
*
* log (exp (logx) + exp (logy))
*
* without causing overflows and without throwing away large handfuls
* of accuracy.
*/
internal static func logspace_add<T: SSFloatingPoint>(_ logx: T, _ logy: T) -> T {
return max(logx, logy) + SSMath.log1p1(SSMath.exp1(-abs(logx - logy)))
}
/*
* Compute the log of a difference from logs of terms, i.e.,
*
* log (exp (logx) - exp (logy))
*
* without causing overflows and without throwing away large handfuls
* of accuracy.
*/
internal static func logspace_sub<T: SSFloatingPoint>(_ logx: T, _ logy: T, _ log_p: Bool) -> T {
return logx + r_log1_exp(x: logy - logx, log_p: log_p)
}
internal static func r_d__1<T: SSFloatingPoint>(log_p: Bool) -> T {
if log_p {
return T.zero
}
else {
return T.one
}
}
internal static func r_d__0<T: SSFloatingPoint>(log_p: Bool) -> T {
if log_p {
return -T.infinity
}
else {
return T.zero
}
}
internal static func r_log1_exp<T: SSFloatingPoint>(x: T, log_p: Bool) -> T {
if x > -T.ln2 {
return SSMath.log1(-SSMath.expm11(x))
}
else {
return SSMath.log1p1(-SSMath.exp1(x))
}
}
internal static func rd_exp<T: SSFloatingPoint>(x: T, log_p: Bool) -> T {
if log_p {
return x
}
else {
return SSMath.exp1(x)
}
}
internal static func r_dt_0<T: SSFloatingPoint>(tail: SSCDFTail, log_p: Bool) -> T {
if tail == .lower {
return r_d__0(log_p: log_p)
}
else {
return r_d__1(log_p: log_p)
}
}
internal static func r_dt_1<T: SSFloatingPoint>(tail: SSCDFTail, log_p: Bool) -> T {
if tail == .lower {
return r_d__1(log_p: log_p)
}
else {
return r_d__0(log_p: log_p)
}
}
internal static func r_d_val<T: SSFloatingPoint>(_ x: T, log_p: Bool) -> T {
if log_p {
return SSMath.log1(x)
}
else {
return x
}
}
internal static func r_d_Clog<T: SSFloatingPoint>(x: T, log_p: Bool) -> T {
if log_p {
return SSMath.log1p1(-x)
}
else {
return (T.half - x + T.half)
}
}
internal static func r_dt_val<T: SSFloatingPoint>(x: T, tail: SSCDFTail, log_p: Bool) -> T {
if tail == .lower {
return r_d_val(x, log_p: log_p)
}
else {
return r_d_Clog(x: x, log_p: log_p)
}
}
internal static func r_d_Lval<T: SSFloatingPoint>(x: T, tail: SSCDFTail) -> T {
if tail == .lower {
return x
}
else {
return T.half - x + T.half
}
}
internal static func r_dt_qIv<T: SSFloatingPoint>(x: T, tail: SSCDFTail, log_p: Bool) -> T {
if log_p {
return tail == .lower ? SSMath.exp1(x) : -SSMath.expm11(x)
}
else {
return r_d_Lval(x: x, tail: tail)
}
}
internal static func r_q_p01_boundaries<T: SSFloatingPoint>(p: T, left: T, right: T, tail: SSCDFTail! = .lower, _ log_p: Bool! = false) -> T? {
if log_p {
if p > 0 {
return T.nan
}
else if p.isZero {
return tail == .lower ? right : left
}
else if p == -T.infinity {
return tail == .lower ? left : right
}
}
else {
if p < 0 || p > 1 {
return T.nan
}
else if p.isZero {
return tail == .lower ? left : right
}
else if p == 1 {
return tail == .lower ? right : left
}
}
return nil
}
}
| gpl-3.0 | 9c22318dd3464e8f363113508fa1a3ba | 26.096257 | 148 | 0.485494 | 3.695842 | false | false | false | false |
vGubriienko/SFDispatchAfter | SFDispatchAfter/SFDispatchAfter.swift | 1 | 2587 | //
// SFDispatchAfter.swift
// SFDispatchAfter
//
// Created by Viktor Gubriienko on 3/26/15.
// Copyright (c) 2015 Viktor Gubriienko. All rights reserved.
//
import Foundation
@objcMembers public class SFDispatch: NSObject {
fileprivate var executionBlock: (() -> Void)?
fileprivate var timer: Timer?
@discardableResult public class func dispatch(after delay: TimeInterval, executionBlock: @escaping () -> Void) -> SFDispatch {
if Thread.isMainThread {
return SFDispatchQueue.addDispatch(after: delay, executionBlock: executionBlock)
} else {
var dispatch: SFDispatch!
print("Warning: dispatch will be done on the main thread")
DispatchQueue.main.sync {
dispatch = SFDispatchQueue.addDispatch(after: delay, executionBlock: executionBlock)
}
return dispatch
}
}
public func fire() {
if Thread.isMainThread {
self.timer?.fire()
} else {
DispatchQueue.main.sync {
self.timer?.fire()
}
}
}
public func cancel() {
if Thread.isMainThread {
SFDispatchQueue.cancelDispatch(self)
} else {
DispatchQueue.main.sync {
SFDispatchQueue.cancelDispatch(self)
}
}
}
fileprivate func invalidate() {
timer?.invalidate()
timer = nil
executionBlock = nil
}
}
private class SFDispatchQueue {
static var dispatches = [SFDispatch]()
class func addDispatch(after delay: TimeInterval, executionBlock: @escaping () -> Void) -> SFDispatch {
let dispatch = SFDispatch()
let timer = Timer.scheduledTimer(timeInterval: delay,
target: self,
selector: #selector(execute(timer:)),
userInfo: dispatch,
repeats: false)
dispatch.executionBlock = executionBlock
dispatch.timer = timer
dispatches.append(dispatch)
return dispatch
}
class func cancelDispatch(_ dispatch: SFDispatch) {
dispatch.invalidate()
if let index = dispatches.index(of: dispatch) {
dispatches.remove(at: index)
}
}
// MARK: - Timer execution
@objc private class func execute(timer: Timer) {
let dispatch = timer.userInfo as! SFDispatch
dispatch.executionBlock?()
cancelDispatch(dispatch)
}
}
| mit | 4e12e492ce4ff587880da3501a7e603c | 25.131313 | 130 | 0.570932 | 5.122772 | false | false | false | false |
fastred/DeallocationChecker | Sources/DeallocationChecker.swift | 1 | 5813 | import UIKit
@objc
public class DeallocationChecker: NSObject {
public enum LeakState {
case leaked
case notLeaked
}
public typealias Callback = (LeakState, UIViewController.Type) -> ()
public enum Handler {
/// Shows alert when a leak is detected.
case alert
/// Calls preconditionFailure when a leak is detected.
case precondition
/// Customization point if you need other type of logging of leak detection, for example to the console or Fabric.
case callback(Callback)
}
@objc
public static let shared = DeallocationChecker()
private(set) var handler: Handler?
/// Sets up the handler then used in all `checkDeallocation*` methods.
/// It is recommended to use DeallocationChecker only in the DEBUG configuration by wrapping this call inside
/// ```
/// #if DEBUG
/// DeallocationChecker.shared.setup(with: .alert)
/// #endif
/// ```
/// call.
///
/// This method isn't exposed to Obj-C because we use an enumeration that isn't compatible with Obj-C.
public func setup(with handler: Handler) {
self.handler = handler
}
/// This method asserts whether a view controller gets deallocated after it disappeared
/// due to one of these reasons:
/// - it was removed from its parent, or
/// - it (or one of its parents) was dismissed.
///
/// The method calls the `handler` if it's non-nil.
///
/// **You should call this method only from UIViewController.viewDidDisappear(_:).**
/// - Parameter delay: Delay after which the check if a
/// view controller got deallocated is performed
@objc(checkDeallocationOf:afterDelay:)
public func checkDeallocation(of viewController: UIViewController, afterDelay delay: TimeInterval = 1.0) {
guard let handler = DeallocationChecker.shared.handler else {
return
}
let rootParentViewController = viewController.dch_rootParentViewController
// `UITabBarController` keeps a strong reference to view controllers that disappeared from screen. So, we don't have to check if they've been deallocated.
guard !rootParentViewController.isKind(of: UITabBarController.self) else {
return
}
// We don't check `isBeingDismissed` simply on this view controller because it's common
// to wrap a view controller in another view controller (e.g. a stock UINavigationController)
// and present the wrapping view controller instead.
if viewController.isMovingFromParent || rootParentViewController.isBeingDismissed {
let viewControllerType = type(of: viewController)
let disappearanceSource: String = viewController.isMovingFromParent ? "removed from its parent" : "dismissed"
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { [weak viewController] in
let leakState: LeakState = viewController != nil ? .leaked : .notLeaked
switch handler {
case .alert:
if leakState == .leaked {
self.showAlert(for: viewControllerType)
}
case .precondition:
if leakState == .leaked {
preconditionFailure("\(viewControllerType) not deallocated after being \(disappearanceSource)")
}
case let .callback(callback):
callback(leakState, viewControllerType)
}
})
}
}
@objc(checkDeallocationWithDefaultDelayOf:)
public func checkDeallocationWithDefaultDelay(of viewController: UIViewController) {
self.checkDeallocation(of: viewController)
}
// MARK: - Private
private var window: UIWindow? = nil
private func showAlert(for viewController: UIViewController.Type) {
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = UIViewController()
window?.makeKeyAndVisible()
let message = "\(viewController) is still in memory even though its view was removed from hierarchy. Please open Memory Graph Debugger to find strong references to it."
let alertController = UIAlertController(title: "Leak Detected", message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .cancel, handler: { _ in self.window = nil })
alertController.addAction(action)
window?.rootViewController?.present(alertController, animated: true, completion: nil)
}
}
extension UIViewController {
@available(*, deprecated, message: "Please switch to using methods on DeallocationChecker. Also remember to call setup(with:) when your app starts.")
@objc(dch_checkDeallocationAfterDelay:)
public func dch_checkDeallocation(afterDelay delay: TimeInterval = 2.0) {
print("Please switch to using methods on DeallocationChecker. Also remember to call setup(with:) when your app starts.")
DeallocationChecker.shared.checkDeallocation(of: self, afterDelay: delay)
}
@available(*, deprecated, message: "Please switch to using methods on DeallocationChecker. Also remember to call setup(with:) when your app starts.")
@objc(dch_checkDeallocation)
public func objc_dch_checkDeallocation() {
print("Please switch to using methods on DeallocationChecker. Also remember to call setup(with:) when your app starts.")
DeallocationChecker.shared.checkDeallocationWithDefaultDelay(of: self)
}
fileprivate var dch_rootParentViewController: UIViewController {
var root = self
while let parent = root.parent {
root = parent
}
return root
}
}
| mit | 2852e80b23fd5e4cf3197a6c0fa24292 | 41.123188 | 176 | 0.664201 | 5.117077 | false | false | false | false |
kevin00223/iOS-demo | rac_demo/Pods/ReactiveCocoa/ReactiveCocoa/ObjC+Runtime.swift | 10 | 657 | /// Search in `class` for any method that matches the supplied selector without
/// propagating to the ancestors.
///
/// - parameters:
/// - class: The class to search the method in.
/// - selector: The selector of the method.
///
/// - returns: The matching method, or `nil` if none is found.
internal func class_getImmediateMethod(_ `class`: AnyClass, _ selector: Selector) -> Method? {
var total: UInt32 = 0
if let methods = class_copyMethodList(`class`, &total) {
defer { free(methods) }
for index in 0 ..< Int(total) {
let method = methods[index]
if method_getName(method) == selector {
return method
}
}
}
return nil
}
| mit | 3568dcbb3e646542393e2854f668f19b | 25.28 | 94 | 0.659056 | 3.532258 | false | false | false | false |
cosmo1234/MobilePassport-Express-Swift | MobilePassport-Express/Dataservice.swift | 1 | 2395 | //
// Dataservice.swift
// MobilePassport-Express
//
// Created by Sagaya Abdulhafeez on 21/08/2016.
// Copyright © 2016 sagaya Abdulhafeez. All rights reserved.
//
import Foundation
class Dataservice{
static let ds = Dataservice()
func callSH(username: String,password: String,f:()){
let url = NSURL(string: "http://exampleapp.herokuapp.com")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var params = ["first_name":username, "last_name":password] as Dictionary<String, String>
var err: NSError?
do{
var json2 = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
request.HTTPBody = json2
}catch{
print("err")
}
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithRequest(request) { (data, response, error) in
if error != nil{
print("error1")
}
do{
var json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)
let tk:String = json["token"] as! String
NSUserDefaults.standardUserDefaults().setValue(tk, forKey: "token")
}catch{
print("error2")
}
if let httprespnse = response as? NSHTTPURLResponse{
print(httprespnse.statusCode)
if httprespnse.statusCode == 200{
//SAVE THE USER INFO TO COREDATA
//let app = UIApplication.sharedApplication().delegate as! AppDelegate
//let context = app.managedObjectContext
dispatch_async(dispatch_get_main_queue()) {
f
}
//SAVE THE KEY 1 TO THE DISK IF USER IS LOGGED IN
NSUserDefaults.standardUserDefaults().setValue(1, forKey: "Logged")
}
}
}
task.resume()
}
} | mit | 6f437c236d9c9eaed2f9ba8cd46b8d8e | 34.220588 | 106 | 0.543442 | 5.148387 | false | false | false | false |
Asura19/My30DaysOfSwift | TabbarApp/TabbarApp/FirstViewController.swift | 1 | 3910 | //
// FirstViewController.swift
// TabbarApp
//
// Created by Phoenix on 2017/4/25.
// Copyright © 2017年 Phoenix. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var articleTableView: UITableView!
var data = [
Article(avatarImage: "allen", sharedName: "Allen Wang", actionType: "Read Later", articleTitle: "Giphy Cam Lets You Create And Share Homemade Gifs", articleCoverImage: "giphy", articleSouce: "TheNextWeb", articleTime: "5min • 13:20"),
Article(avatarImage: "Daniel Hooper", sharedName: "Daniel Hooper", actionType: "Shared on Twitter", articleTitle: "Principle. The Sketch of Prototyping Tools", articleCoverImage: "my workflow flow", articleSouce: "SketchTalk", articleTime: "3min • 12:57"),
Article(avatarImage: "davidbeckham", sharedName: "David Beckham", actionType: "Shared on Facebook", articleTitle: "Ohlala, An Uber For Escorts, Launches Its ‘Paid Dating’ Service In NYC", articleCoverImage: "Ohlala", articleSouce: "TechCrunch", articleTime: "1min • 12:59"),
Article(avatarImage: "bruce", sharedName: "Bruce Fan", actionType: "Shared on Weibo", articleTitle: "Lonely Planet’s new mobile app helps you explore major cities like a pro", articleCoverImage: "Lonely Planet", articleSouce: "36Kr", articleTime: "5min • 11:21"),
]
override func viewDidLoad() {
super.viewDidLoad()
articleTableView.frame = view.bounds
articleTableView.dataSource = self
articleTableView.delegate = self
articleTableView.separatorStyle = UITableViewCellSeparatorStyle.none
articleTableView.tableFooterView = UIView(frame: CGRect.zero)
}
override func viewWillAppear(_ animated: Bool) {
animateTable()
}
func animateTable() {
self.articleTableView.reloadData()
let cells = articleTableView.visibleCells
let tableHeight: CGFloat = articleTableView.bounds.size.height
for i in cells {
let cell: UITableViewCell = i as UITableViewCell
cell.transform = CGAffineTransform(translationX: 0, y: tableHeight)
}
var index = 0
for a in cells {
let cell: UITableViewCell = a as UITableViewCell
UIView.animate(withDuration: 1.0, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: {
cell.transform = CGAffineTransform(translationX: 0, y: 0);
}, completion: nil)
index += 1
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 10
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 165
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = articleTableView.dequeueReusableCell(withIdentifier: "ArticleCell", for: indexPath) as! ArticleCell
let article = data[indexPath.row]
cell.avatarImageView.image = UIImage(named: article.avatarImage)
cell.articleCoverImage.image = UIImage(named: article.articleCoverImage)
cell.sharedNameLabel.text = article.sharedName
cell.actionTypeLabel.text = article.actionType
cell.articleTitleLabel.text = article.articleTitle
cell.articleSouceLabel.text = article.articleSouce
cell.articelCreatedAtLabel.text = article.articleTime
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
}
| mit | 9aa4a069a7258f727781ad93af70d9ce | 40.860215 | 284 | 0.66504 | 4.82404 | false | false | false | false |
mattwelborn/HSTracker | HSTracker/Statistics/LadderGrid.swift | 1 | 2215 | //
// LadderGrid.swift
// HSTracker
//
// Created by Matthew Welborn on 6/25/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import SQLite
import CleanroomLogger
// Reads precomputed Monte Carlo data from grid.db
// TODO: run long simulation on cluster for better grid
struct LadderGrid {
var db: Connection?
let grid = Table("grid")
let colTargetRank = Expression<Int64>("target_rank")
let colStars = Expression<Int64>("stars")
let colBonus = Expression<Int64>("bonus")
let colWinp = Expression<Double>("winp")
let colGames = Expression<Double>("games")
init() {
do {
// TODO: put the db in the bundle
let path = NSBundle.mainBundle().resourcePath! + "/Resources/grid.db"
Log.verbose?.message("Loading grid at \(path)")
db = try Connection(path, readonly: true)
} catch {
db = nil
// swiftlint:disable line_length
Log.warning?.message("Failed to load grid db! Will result in Ladder stats tab not working.")
// swiftlint:enable line_length
}
}
func getGamesToRank(targetRank: Int, stars: Int, bonus: Int, winp: Double) -> Double? {
guard let dbgood = db
else { return nil }
let query = grid.select(colGames)
.filter(colTargetRank == Int64(targetRank))
.filter(colStars == Int64(stars))
.filter(colBonus == Int64(bonus))
// Round to nearest hundredth
let lowerWinp = Double(floor(winp*100)/100)
let upperWinp = Double(ceil(winp*100)/100)
let lower = query.filter(colWinp == lowerWinp)
let upper = query.filter(colWinp == upperWinp)
guard let lowerResult = dbgood.pluck(lower), upperResult = dbgood.pluck(upper)
else { return nil }
let l = lowerResult[colGames]
let u = upperResult[colGames]
// Linear interpolation
if lowerWinp == upperWinp {
return l
} else {
return l * ( 1 - ( winp - lowerWinp) / 0.01) + u * (winp - lowerWinp)/0.01
}
}
}
| mit | 68f98609427f3f9e995eb36a3bf92b06 | 31.086957 | 104 | 0.583559 | 4.032787 | false | false | false | false |
criticalmaps/criticalmaps-ios | CriticalMapsKit/Sources/SharedModels/Location.swift | 1 | 1649 | import Foundation
/// Rider location with a coordinate and timestamp
public struct Location: Equatable, Hashable {
public let coordinate: Coordinate
public var timestamp: Double
public var name: String?
public var color: String?
public init(
coordinate: Coordinate,
timestamp: Double,
name: String? = nil,
color: String? = nil
) {
self.coordinate = coordinate
self.timestamp = timestamp
self.name = name
self.color = color
}
}
extension Location: Codable {
private enum CodingKeys: String, CodingKey {
case longitude
case latitude
case timestamp
case name
case color
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let latitude = try container.decode(Double.self, forKey: .latitude) / 1000000
let longitude = try container.decode(Double.self, forKey: .longitude) / 1000000
coordinate = Coordinate(latitude: latitude, longitude: longitude)
try timestamp = container.decode(Double.self, forKey: .timestamp)
try name = container.decodeIfPresent(String.self, forKey: .name)
try color = container.decodeIfPresent(String.self, forKey: .color)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(coordinate.longitude * 1000000, forKey: .longitude)
try container.encode(coordinate.latitude * 1000000, forKey: .latitude)
try container.encode(timestamp, forKey: .timestamp)
try container.encodeIfPresent(color, forKey: .color)
try container.encodeIfPresent(name, forKey: .name)
}
}
| mit | f74b5b391373b0a2ab2b6ceef33cda48 | 31.98 | 83 | 0.722256 | 4.374005 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Media/StockPhotos/StockPhotosPageable.swift | 2 | 1406 |
struct StockPhotosPageable: Pageable {
let itemsPerPage: Int
let pageHandle: Int
static let defaultPageSize = 40
static let defaultPageIndex = 0
func next() -> Pageable? {
if pageHandle == 0 {
return nil
}
return StockPhotosPageable(itemsPerPage: itemsPerPage, pageHandle: pageHandle)
}
var pageSize: Int {
return itemsPerPage
}
var pageIndex: Int {
return pageHandle
}
}
extension StockPhotosPageable {
/// Builds the Pageable corresponding to the first page, with the default page size.
///
/// - Returns: A StockPhotosPageable configured with the default page size and the initial page handle
static func first() -> StockPhotosPageable {
return StockPhotosPageable(itemsPerPage: defaultPageSize, pageHandle: defaultPageIndex)
}
}
extension StockPhotosPageable: Decodable {
enum CodingKeys: String, CodingKey {
case nextPage = "next_page"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
pageHandle = try values.decode(Int.self, forKey: .nextPage)
itemsPerPage = type(of: self).defaultPageSize
}
}
extension StockPhotosPageable: CustomStringConvertible {
var description: String {
return "Stock Photos Pageable: count \(itemsPerPage) next: \(pageHandle)"
}
}
| gpl-2.0 | cae1772393d39d23a302b842aeab91ed | 26.568627 | 106 | 0.675676 | 4.5209 | false | false | false | false |
sschiau/swift-package-manager | Sources/Build/Triple.swift | 1 | 4440 | /*
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
*/
/// Triple - Helper class for working with Destination.target values
///
/// Used for parsing values such as x86_64-apple-macosx10.10 into
/// set of enums. For os/arch/abi based conditions in build plan.
///
/// @see Destination.target
/// @see https://github.com/apple/swift-llvm/blob/stable/include/llvm/ADT/Triple.h
///
public struct Triple {
public let tripleString: String
public let arch: Arch
public let vendor: Vendor
public let os: OS
public let abi: ABI
public enum Error: Swift.Error {
case badFormat
case unknownArch
case unknownOS
}
public enum Arch: String {
case x86_64
case i686
case ppc64le
case s390x
case aarch64
case armv7
case arm
}
public enum Vendor: String {
case unknown
case apple
}
public enum OS: String {
case darwin
case macOS = "macosx"
case linux
case windows
fileprivate static let allKnown:[OS] = [
.darwin,
.macOS,
.linux,
.windows
]
}
public enum ABI: String {
case unknown
case android = "androideabi"
}
public init(_ string: String) throws {
let components = string.split(separator: "-").map(String.init)
guard components.count == 3 || components.count == 4 else {
throw Error.badFormat
}
guard let arch = Arch(rawValue: components[0]) else {
throw Error.unknownArch
}
let vendor = Vendor(rawValue: components[1]) ?? .unknown
guard let os = Triple.parseOS(components[2]) else {
throw Error.unknownOS
}
let abiString = components.count > 3 ? components[3] : nil
let abi = abiString.flatMap(ABI.init)
self.tripleString = string
self.arch = arch
self.vendor = vendor
self.os = os
self.abi = abi ?? .unknown
}
fileprivate static func parseOS(_ string: String) -> OS? {
for candidate in OS.allKnown {
if string.hasPrefix(candidate.rawValue) {
return candidate
}
}
return nil
}
public func isDarwin() -> Bool {
return vendor == .apple || os == .macOS || os == .darwin
}
public func isLinux() -> Bool {
return os == .linux
}
public func isWindows() -> Bool {
return os == .windows
}
/// Returns the triple string for the given platform version.
///
/// This is currently meant for Apple platforms only.
public func tripleString(forPlatformVersion version: String) -> String {
precondition(isDarwin())
return self.tripleString + version
}
public static let macOS = try! Triple("x86_64-apple-macosx")
public static let x86_64Linux = try! Triple("x86_64-unknown-linux")
public static let i686Linux = try! Triple("i686-unknown-linux")
public static let ppc64leLinux = try! Triple("powerpc64le-unknown-linux")
public static let s390xLinux = try! Triple("s390x-unknown-linux")
public static let arm64Linux = try! Triple("aarch64-unknown-linux")
public static let armLinux = try! Triple("armv7-unknown-linux-gnueabihf")
public static let android = try! Triple("armv7-unknown-linux-androideabi")
public static let windows = try! Triple("x86_64-unknown-windows-msvc")
#if os(macOS)
public static let hostTriple: Triple = .macOS
#elseif os(Windows)
public static let hostTriple: Triple = .windows
#elseif os(Linux)
#if arch(x86_64)
public static let hostTriple: Triple = .x86_64Linux
#elseif arch(i386)
public static let hostTriple: Triple = .i686Linux
#elseif arch(powerpc64le)
public static let hostTriple: Triple = .ppc64leLinux
#elseif arch(s390x)
public static let hostTriple: Triple = .s390xLinux
#elseif arch(arm64)
public static let hostTriple: Triple = .arm64Linux
#elseif arch(arm)
public static let hostTriple: Triple = .armLinux
#endif
#endif
}
| apache-2.0 | 2ed42e80a49294bbefe35b0b0af3687d | 28.019608 | 82 | 0.625901 | 4.212524 | false | false | false | false |
iamyuiwong/swift-common | errno/PosixErrno.swift | 1 | 554 | /*
* NAME PosixErrno.swift
*
* C 15/9/30 +0800
*
* DESC
* - Xcode 7.0.1 / Swift 2.0.1 supported (Created)
*
* V1.0.0.0_
*/
import Foundation
/*
* NAME PosixErrno - class PosixErrno
*/
class PosixErrno {
static func errno2string (posixErrno _en: Int32) -> String {
var en: Int32 = 0
if (_en < 0) {
en = -_en;
} else {
en = _en;
}
let cs = strerror(en)
let ret = StringUtil.toString(fromCstring: cs,
encoding: NSUTF8StringEncoding)
if (nil != ret) {
return ret!
} else {
return "Unresolved \(en)"
}
}
}
| lgpl-3.0 | b538f55c4873287dc78afac72b77194a | 13.578947 | 61 | 0.581227 | 2.625592 | false | false | false | false |
noprom/swiftmi-app | swiftmi/swiftmi/PostDetailController.swift | 1 | 11428 | //
// PostDetailController.swift
// swiftmi
//
// Created by yangyin on 15/4/4.
// Copyright (c) 2015年 swiftmi. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import Kingfisher
class PostDetailController: UIViewController,UIScrollViewDelegate,UIWebViewDelegate,UITextViewDelegate {
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var inputWrapView: UIView!
@IBOutlet weak var inputReply: UITextView!
var article:AnyObject?
var postId:Int?
var postDetail:JSON = nil
var keyboardShow = false
override func viewDidLoad() {
super.viewDidLoad()
let center: NSNotificationCenter = NSNotificationCenter.defaultCenter()
center.addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
center.addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
//center.addObserver(self, selector:"keyboardWillChangeFrame:", name:UIKeyboardWillChangeFrameNotification,object:nil)
self.setViews()
self.inputReply.layer.borderWidth = 1
self.inputReply.layer.borderColor = UIColor(red: 0.85, green: 0.85, blue:0.85, alpha: 0.9).CGColor
// Keyboard stuff.
//
// Do any additional setup after loading the view.
}
override func viewDidAppear(animated: Bool) {
self.userActivity = NSUserActivity(activityType: "com.swiftmi.handoff.view-web")
self.userActivity?.title = "view article on mac"
self.userActivity?.webpageURL = NSURL(string: ServiceApi.getTopicShareDetail(article!.valueForKey("postId") as! Int))
self.userActivity?.becomeCurrent()
}
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
self.userActivity?.invalidate()
}
func keyboardWillShow(notification: NSNotification) {
let info:NSDictionary = notification.userInfo!
let duration = (info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let endKeyboardRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
var frame = self.view.frame
frame.origin.y = -endKeyboardRect.height
UIView.animateWithDuration(duration, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.webView.stringByEvaluatingJavaScriptFromString("$('body').css({'padding-top':'\(endKeyboardRect.height)px'});")
for constraint in self.inputWrapView.constraints {
if constraint.firstAttribute == NSLayoutAttribute.Height {
let inputWrapContraint = constraint as NSLayoutConstraint
inputWrapContraint.constant = 80
// self.inputWrapView.updateConstraintsIfNeeded()
break;
}
}
self.view.frame = frame
}, completion: nil)
}
func keyboardWillHide(notification: NSNotification) {
let info:NSDictionary = notification.userInfo!
let duration = (info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
var frame = self.view.frame
frame.origin.y = 0 // keyboardHeight
UIView.animateWithDuration(duration, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.webView.stringByEvaluatingJavaScriptFromString("$('body').css({'padding-top':'0px'});")
self.view.frame = frame
for constraint in self.inputWrapView.constraints {
if constraint.firstAttribute == NSLayoutAttribute.Height {
let inputWrapContraint = constraint as NSLayoutConstraint
inputWrapContraint.constant = 50
// self.inputWrapView.updateConstraintsIfNeeded()
break;
}
}
}, completion: nil)
}
private func GetLoadData() -> JSON {
if postDetail != nil {
return self.postDetail
}
var json:JSON = ["comments":[]]
json["topic"] = JSON(self.article!)
return json
}
func loadData(){
Alamofire.request(Router.TopicDetail(topicId: (article!.valueForKey("postId") as! Int))).responseJSON{
closureResponse in
if closureResponse.result.isFailure {
let alert = UIAlertView(title: "网络异常", message: "请检查网络设置", delegate: nil, cancelButtonTitle: "确定")
alert.show()
}
else {
let json = closureResponse.result.value
let result = JSON(json!)
if result["isSuc"].boolValue {
self.postDetail = result["result"]
}
}
let path=NSBundle.mainBundle().pathForResource("article", ofType: "html")
let url=NSURL.fileURLWithPath(path!)
let request = NSURLRequest(URL:url)
dispatch_async(dispatch_get_main_queue()) {
self.inputWrapView.hidden = false
self.webView.loadRequest(request)
}
}
}
func setViews(){
self.view.backgroundColor=UIColor.whiteColor()
self.webView.backgroundColor=UIColor.clearColor()
self.inputReply.resignFirstResponder()
self.webView.delegate=self
self.webView.scrollView.delegate=self
// self.inputView
self.startLoading()
self.inputWrapView.hidden = true
self.title="主题贴"
self.loadData()
}
@IBAction func replyClick(sender: AnyObject) {
let msg = inputReply.text;
inputReply.text = "";
if msg != nil {
let postId = article!.valueForKey("postId") as! Int
let params:[String:AnyObject] = ["postId":postId,"content":msg]
Alamofire.request(Router.TopicComment(parameters: params)).responseJSON{
closureResponse in
if closureResponse.result.isFailure {
self.notice("网络异常", type: NoticeType.error, autoClear: true)
return
}
let json = closureResponse.result.value
let result = JSON(json!)
if result["isSuc"].boolValue {
self.notice("评论成功!", type: NoticeType.success, autoClear: true)
self.webView.stringByEvaluatingJavaScriptFromString("article.addComment("+result["result"].rawString()!+");")
} else {
self.notice("评论失败!", type: NoticeType.error, autoClear: true)
}
}
}
}
func startLoading(){
self.pleaseWait()
self.webView.hidden=true
}
func stopLoading(){
self.webView.hidden=false
self.clearAllNotice()
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
{
let reqUrl=request.URL!.absoluteString
let params = reqUrl.componentsSeparatedByString("://")
dispatch_async(dispatch_get_main_queue(),{
if(params.count>=2){
if(params[0].compare("html")==NSComparisonResult.OrderedSame && params[1].compare("docready") == NSComparisonResult.OrderedSame ){
let data = self.GetLoadData()
self.webView.stringByEvaluatingJavaScriptFromString("article.render("+data.rawString()!+");")
}
else if(params[0].compare("html")==NSComparisonResult.OrderedSame && params[1].compare("contentready")==NSComparisonResult.OrderedSame){
//doc content ok
self.stopLoading()
}
else if params[0].compare("http") == NSComparisonResult.OrderedSame || params[0].compare("https") == NSComparisonResult.OrderedSame {
let webViewController:WebViewController = Utility.GetViewController("webViewController")
webViewController.webUrl = reqUrl
self.presentViewController(webViewController, animated: true, completion: nil)
}
}
})
if params[0].compare("http") == NSComparisonResult.OrderedSame || params[0].compare("https") == NSComparisonResult.OrderedSame {
return false
}
return true;
}
func webViewDidStartLoad(webView: UIWebView)
{
}
func webViewDidFinishLoad(webView: UIWebView)
{
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?)
{
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func shareClick(sender: AnyObject) {
share()
}
private func share() {
let data = GetLoadData()
let title = data["topic"]["title"].stringValue
let url = ServiceApi.getTopicShareDetail(data["topic"]["postId"].intValue)
let desc = data["topic"]["desc"].stringValue
let img = self.webView.stringByEvaluatingJavaScriptFromString("article.getShareImage()")
Utility.share(title, desc: desc, imgUrl: img, linkUrl: url)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
self.clearAllNotice()
}
}
| mit | e5e53f0edfb771fd4eea944da390ea6a | 30.495845 | 152 | 0.552155 | 5.909563 | false | false | false | false |
juanpablofernandez/CountryList | Example/Pods/CountryList/CountryList/CountryCell.swift | 2 | 1837 | //
// CountryCell.swift
// CountryListExample
//
// Created by Juan Pablo on 9/8/17.
// Copyright © 2017 Juan Pablo Fernandez. All rights reserved.
//
import UIKit
class CountryCell: UITableViewCell {
var nameLabel: UILabel?
var extensionLabel: UILabel?
var country: Country? {
didSet {
if let name = country!.name {
nameLabel?.text = "\(name)"
extensionLabel?.text = "+\(country!.phoneExtension)"
}
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func prepareForReuse() {
self.nameLabel?.text = ""
self.extensionLabel?.text = ""
}
func setup() {
nameLabel = UILabel()
nameLabel?.textColor = UIColor.black
nameLabel?.font = UIFont.systemFont(ofSize: 20)
nameLabel?.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(nameLabel!)
nameLabel?.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
nameLabel?.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 15).isActive = true
extensionLabel = UILabel()
extensionLabel?.textColor = UIColor.gray
extensionLabel?.font = UIFont.systemFont(ofSize: 18)
extensionLabel?.translatesAutoresizingMaskIntoConstraints = false
addSubview(extensionLabel!)
extensionLabel?.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
extensionLabel?.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -15).isActive = true
}
}
| mit | 1dbb638b195d4623a2db29a8555f58ae | 30.118644 | 104 | 0.634532 | 5.157303 | false | false | false | false |
glessard/swift-channels | ChannelsTests/UtilityChanTests.swift | 1 | 3362 | //
// TimeoutTests.swift
// Channels
//
// Created by Guillaume Lessard on 2015-06-13.
// Copyright © 2015 Guillaume Lessard. All rights reserved.
//
import Foundation
import XCTest
@testable import Channels
class TimeoutTests: XCTestCase
{
let delay: Int64 = 50_000
let scale = { () -> mach_timebase_info_data_t in
var info = mach_timebase_info_data_t()
mach_timebase_info(&info)
return info
}()
func testTimeout()
{
let start = mach_absolute_time()*UInt64(scale.numer)/UInt64(scale.denom)
let time1 = DispatchTime.now() + Double(delay) / Double(NSEC_PER_SEC)
let rx1 = Timeout(time1)
XCTAssert(rx1.isEmpty)
XCTAssert(rx1.isClosed == false)
<-rx1
let time2 = DispatchTime.now() + Double(0) / Double(NSEC_PER_SEC)
XCTAssert(rx1.isClosed)
XCTAssert(time1 <= time2)
let rx2 = Timeout(delay: delay)
XCTAssert(rx2.isClosed == false)
_ = rx2.receive()
XCTAssert(rx2.isClosed)
let rx3 = Receiver.Wrap(Timeout())
XCTAssert(rx3.isEmpty)
<-rx3
rx3.close()
XCTAssert(rx3.isClosed)
let dt = mach_absolute_time()*UInt64(scale.numer)/UInt64(scale.denom) - start
XCTAssert(dt > numericCast(2*delay))
}
func testSelectTimeout()
{
let count = 10
let channels = (0..<count).map { _ in Channel<Int>.Make() }
let selectables = channels.map {
(tx: Sender<Int>, rx: Receiver<Int>) -> Selectable in
return (arc4random()&1 == 0) ? tx : rx
}
var (i,j) = (0,0)
while i < 10
{
let start = mach_absolute_time()*UInt64(scale.numer)/UInt64(scale.denom)
let timer = Timeout(delay: delay)
if let selection = select_chan(selectables + [timer])
{
XCTAssert(j == i)
switch selection.id
{
case let s where s === timer: XCTFail("Timeout never sets the selection")
case _ as Sender<Int>: XCTFail("Incorrect selection")
case _ as Receiver<Int>: XCTFail("Incorrect selection")
default:
i += 1
let dt = mach_absolute_time()*UInt64(scale.numer)/UInt64(scale.denom) - start
XCTAssert(dt > numericCast(delay))
}
j += 1
}
}
}
}
class SinkTests: XCTestCase
{
func testSink()
{
let s1 = Sink<Int>()
XCTAssert(s1.isFull == false)
XCTAssert(s1.isClosed == false)
s1 <- 0
let s2 = Sender.Wrap(s1)
XCTAssert(s2.isFull == false)
XCTAssert(s2.isClosed == false)
s2 <- 0
s1.close()
}
func testSelectSink()
{
let k = Sink<Int>()
let s = [k as Selectable]
if let selection = select_chan(s), selection.id === k
{
let success = k.insert(selection, newElement: 0)
XCTAssert(success)
}
}
}
class EmptyChanTests: XCTestCase
{
func testEmptyReceiver()
{
let r = Receiver<Int>()
XCTAssert(r.isEmpty)
XCTAssert(r.isClosed)
if let _ = <-r
{
XCTFail()
}
let s = [r as Selectable]
if let selection = select_chan(s), selection.id === r
{
XCTFail()
}
r.close()
}
func testEmptySender()
{
let s1 = Sender<Int>()
XCTAssert(s1.isFull == false)
XCTAssert(s1.isClosed)
if s1.send(0)
{
XCTFail()
}
let s = [s1 as Selectable]
if let selection = select_chan(s), selection.id === s1
{
XCTFail()
}
s1.close()
}
}
| mit | afa92d52617b15ebdf8e2094d7a20e04 | 21.111842 | 87 | 0.592681 | 3.450719 | false | true | false | false |
Chaosspeeder/YourGoals | Pods/Eureka/Source/Rows/PickerInputRow.swift | 1 | 5162 | // PickerInputRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
// MARK: PickerInputCell
open class _PickerInputCell<T> : Cell<T>, CellType, UIPickerViewDataSource, UIPickerViewDelegate where T: Equatable {
lazy public var picker: UIPickerView = {
let picker = UIPickerView()
picker.translatesAutoresizingMaskIntoConstraints = false
return picker
}()
fileprivate var pickerInputRow: _PickerInputRow<T>? { return row as? _PickerInputRow<T> }
public required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func setup() {
super.setup()
accessoryType = .none
editingAccessoryType = .none
picker.delegate = self
picker.dataSource = self
}
deinit {
picker.delegate = nil
picker.dataSource = nil
}
open override func update() {
super.update()
selectionStyle = row.isDisabled ? .none : .default
if row.title?.isEmpty == false {
detailTextLabel?.text = row.displayValueFor?(row.value) ?? (row as? NoValueDisplayTextConformance)?.noValueDisplayText
} else {
textLabel?.text = row.displayValueFor?(row.value) ?? (row as? NoValueDisplayTextConformance)?.noValueDisplayText
detailTextLabel?.text = nil
}
textLabel?.textColor = row.isDisabled ? .gray : .black
if row.isHighlighted {
textLabel?.textColor = tintColor
}
picker.reloadAllComponents()
}
open override func didSelect() {
super.didSelect()
row.deselect()
}
open override var inputView: UIView? {
return picker
}
open override func cellCanBecomeFirstResponder() -> Bool {
return canBecomeFirstResponder
}
override open var canBecomeFirstResponder: Bool {
return !row.isDisabled
}
open func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
open func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerInputRow?.options.count ?? 0
}
open func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerInputRow?.displayValueFor?(pickerInputRow?.options[row])
}
open func pickerView(_ pickerView: UIPickerView, didSelectRow rowNumber: Int, inComponent component: Int) {
if let picker = pickerInputRow, picker.options.count > rowNumber {
picker.value = picker.options[rowNumber]
update()
}
}
}
open class PickerInputCell<T>: _PickerInputCell<T> where T: Equatable {
public required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func update() {
super.update()
if let selectedValue = pickerInputRow?.value, let index = pickerInputRow?.options.firstIndex(of: selectedValue) {
picker.selectRow(index, inComponent: 0, animated: true)
}
}
}
// MARK: PickerInputRow
open class _PickerInputRow<T> : Row<PickerInputCell<T>>, NoValueDisplayTextConformance where T: Equatable {
open var noValueDisplayText: String? = nil
open var options = [T]()
required public init(tag: String?) {
super.init(tag: tag)
}
}
/// A generic row where the user can pick an option from a picker view displayed in the keyboard area
public final class PickerInputRow<T>: _PickerInputRow<T>, RowType where T: Equatable, T: InputTypeInitiable {
required public init(tag: String?) {
super.init(tag: tag)
}
}
| lgpl-3.0 | a803a4e459329805b0836d71a2bbcd2b | 32.303226 | 130 | 0.682487 | 4.810811 | false | false | false | false |
aitorbf/Curso-Swift | Cat Years/Cat Years/ViewController.swift | 1 | 1224 | //
// ViewController.swift
// Cat Years
//
// Created by Aitor Baragaño Fernández on 22/9/15.
// Copyright © 2015 Aitor Baragaño Fernández. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var age: UITextField!
@IBOutlet var resultLabel: UILabel!
@IBAction func findAge(sender: AnyObject) {
let enteredAge = Int(age.text!)
if enteredAge != nil {
let catYears = enteredAge! * 7
resultLabel.textColor = UIColor.blackColor()
resultLabel.text = "Your cat is \(catYears) in cat years"
} else {
resultLabel.textColor = UIColor.redColor()
resultLabel.text = "Please enter a number in the box"
}
age.resignFirstResponder()
}
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 | f6d580ea18bd8ec6a82bca36efd316b9 | 22 | 80 | 0.566038 | 5.058091 | false | false | false | false |
a-athaullah/QToasterSwift | Example/Example/ViewController.swift | 1 | 6412 | //
// ViewController.swift
// Example
//
// Created by Ahmad Athaullah on 6/30/16.
// Copyright © 2016 Ahmad Athaullah. All rights reserved.
//
import UIKit
import QToasterSwift
class ViewController: UIViewController {
let baseColor = UIColor(red: 51/255.0, green: 204/255.0, blue: 51/255.0, alpha: 1)
let errorColor = UIColor(red: 1, green: 80/255, blue: 80/255.0, alpha: 0.9)
let lightGray = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1)
let darkGray = UIColor(red: 0.3, green: 0.3, blue: 0.3, alpha: 1)
let titleField = UITextField()
let messageField = UITextView()
let urlField = UITextField()
let errorText = "For this Demo App, at least you have message to show. otherwise we will show error toaster with non-default toaster background color."
var screenWidth:CGFloat{
get{
return UIScreen.main.bounds.size.width
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "QToasterSwift Demo"
let titleLabel = UILabel(frame: CGRect(x: 20,y: 20,width: 60,height: 30))
titleLabel.text = "Title"
titleLabel.font = UIFont.systemFont(ofSize: 13, weight: 0.5)
self.view.addSubview(titleLabel)
titleField.frame = CGRect(x: 90,y: 20,width: screenWidth - 110,height: 30)
titleField.placeholder = "Toaster title here ..."
titleField.layer.cornerRadius = 4
titleField.layer.borderColor = darkGray.cgColor
titleField.backgroundColor = lightGray
titleField.font = UIFont.systemFont(ofSize: 12, weight: 0.3)
self.view.addSubview(titleField)
let messageLabel = UILabel(frame: CGRect(x: 20,y: 60,width: 60,height: 30))
messageLabel.text = "Message"
messageLabel.font = UIFont.systemFont(ofSize: 13, weight: 0.5)
self.view.addSubview(messageLabel)
messageField.frame = CGRect(x: 90,y: 60,width: screenWidth - 110,height: 60)
messageField.isEditable = true
messageField.allowsEditingTextAttributes = false
messageField.layer.cornerRadius = 4
messageField.layer.borderColor = darkGray.cgColor
messageField.backgroundColor = lightGray
messageField.font = UIFont.systemFont(ofSize: 12, weight: 0.3)
self.view.addSubview(messageField)
let urlLabel = UILabel(frame: CGRect(x: 20,y: 130,width: 60,height: 30))
urlLabel.text = "Icon URL"
urlLabel.font = UIFont.systemFont(ofSize: 13, weight: 0.5)
self.view.addSubview(urlLabel)
urlField.frame = CGRect(x: 90,y: 130,width: screenWidth - 110,height: 30)
urlField.placeholder = "Icon URL here ..."
urlField.layer.cornerRadius = 4
urlField.layer.borderColor = darkGray.cgColor
urlField.backgroundColor = lightGray
urlField.font = UIFont.systemFont(ofSize: 12, weight: 0.3)
urlField.text = "https://qiscuss3.s3.amazonaws.com/uploads/db5cbfe427dbeca6026d57c047074866/Screenshot_2015-02-19-12-09-15-1.png"
self.view.addSubview(urlField)
let button1 = UIButton(frame: CGRect(x: 20, y: 180, width: screenWidth - 40, height: 30))
button1.setTitle("Show Toaster", for: UIControlState())
button1.backgroundColor = baseColor
button1.layer.cornerRadius = 4
button1.addTarget(self, action: #selector(ViewController.toaster1), for: UIControlEvents.touchUpInside)
button1.titleLabel?.font = UIFont.systemFont(ofSize: 12.5, weight: 0.4)
self.view.addSubview(button1)
let button2 = UIButton(frame: CGRect(x: 20, y: 220, width: screenWidth - 40, height: 30))
button2.setTitle("Show Toaster With Icon", for: UIControlState())
button2.backgroundColor = baseColor
button2.layer.cornerRadius = 4
button2.addTarget(self, action: #selector(ViewController.toaster2), for: UIControlEvents.touchUpInside)
button2.titleLabel?.font = UIFont.systemFont(ofSize: 12.5, weight: 0.4)
self.view.addSubview(button2)
let button3 = UIButton(frame: CGRect(x: 20, y: 260, width: screenWidth - 40, height: 30))
button3.setTitle("Show Toaster With Icon From URL", for: UIControlState())
button3.backgroundColor = baseColor
button3.layer.cornerRadius = 4
button3.addTarget(self, action: #selector(ViewController.toaster3), for: UIControlEvents.touchUpInside)
button3.titleLabel?.font = UIFont.systemFont(ofSize: 12.5, weight: 0.4)
self.view.addSubview(button3)
let infoLabel = UILabel(frame: CGRect(x: 20, y: 400, width: screenWidth - 40, height: 60))
infoLabel.text = "This Demo App only support secure image URL (with https protocol), if you need to load from non secure URL you need to whitelist that URL in your plist.info file"
infoLabel.numberOfLines = 0
infoLabel.textAlignment = NSTextAlignment.center
infoLabel.font = UIFont.systemFont(ofSize: 11, weight: 0.6)
infoLabel.textColor = darkGray
self.view.addSubview(infoLabel)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func toaster1(){
if messageField.text != nil && messageField.text != "" {
QToasterSwift.toast(self, text: messageField.text, title: titleField.text)
}else{
QToasterSwift.toast(self, text: errorText, title: "ERROR", backgroundColor: errorColor)
}
}
func toaster2(){
if messageField.text != nil && messageField.text != "" {
QToasterSwift.toastWithIcon(self, text: messageField.text, icon: UIImage(named: "avatar"), title: titleField.text)
}else{
QToasterSwift.toast(self, text: errorText, title: "ERROR", backgroundColor: errorColor)
}
}
func toaster3(){
if messageField.text != nil && messageField.text != "" {
QToasterSwift.toast(self, text: messageField.text, title: titleField.text, iconURL: urlField.text, iconPlaceHolder: UIImage(named: "avatar"),onTouch:{
print("working")
})
}else{
QToasterSwift.toast(self, text: errorText, title: "ERROR", backgroundColor: errorColor)
}
}
}
| mit | 62b26b2c7a2090fb6b796312487a6f9b | 44.147887 | 188 | 0.651068 | 4.240079 | false | false | false | false |
txstate-etc/mobile-tracs-ios | mobile-tracs-ios/NotificationViewController.swift | 1 | 28681 | //
// NotificationViewController.swift
// mobile-tracs-ios
//
// Created by Nick Wing on 3/18/17.
// Copyright © 2017 Texas State University. All rights reserved.
//
import UIKit
class NotificationViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
@IBOutlet var headerView: UIView!
@IBOutlet var headerLabel: UILabel!
@IBOutlet var courseDescription: UILabel!
@IBOutlet var contactLastname: UILabel!
@IBOutlet weak var contactEmail: UILabel!
let NO_FORUM_POSTS = "No new forum posts"
let NO_ANNOUNCEMENTS = "No new announcements"
let NO_TOOLS_ENABLED = "No new notifications"
var notifications: [Notification] = []
var site:Site?
var announcementCount: Int = 0
var discussionCount: Int = 0
var announcementHeader: NotificationViewHeader?
var discussionHeader: NotificationViewHeader?
enum Section: String {
case Announcements = "announcement"
case Discussions = "discussion"
}
enum Style: String {
case Dashboard = "dashboard"
case Discussions = "dicussions"
}
var announcementSection: Int?
var discussionSection: Int?
var viewStyle: Style?
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib(nibName:"NotificationViewHeader", bundle: nil), forHeaderFooterViewReuseIdentifier: "sectionlabel")
NotificationCenter.default.addObserver(self, selector: #selector(notificationReceived), name: NSNotification.Name(rawValue: ObservableEvent.PUSH_NOTIFICATION), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(loadOnAppear), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(loadOnAppear), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
if let site = site {
if site.hasannouncements {
announcementSection = 0
if site.hasdiscussions {
discussionSection = 1
}
} else {
if site.hasdiscussions {
discussionSection = 0
}
}
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let viewStyle = viewStyle {
if let site = site {
let fullName = site.contactLast.isEmpty ? "Contact info not found" : "\(site.contactFull),"
if site.contactEmail.isEmpty {
contactEmail.isHidden = true
} else {
contactEmail.text = site.contactEmail
let emailTap = UITapGestureRecognizer(target: self, action: #selector(NotificationViewController.openEmailClient))
contactEmail.addGestureRecognizer(emailTap)
contactEmail.isUserInteractionEnabled = true
}
contactLastname.text = fullName
}
switch viewStyle {
case .Discussions:
self.title = "Forums"
break
case .Dashboard:
self.title = "Notifications"
break
}
} else {
self.title = "Announcements"
removeHeaderView(headerView: headerView)
}
headerLabel.text = site?.title
loadOnAppear()
}
override func viewDidAppear(_ animated: Bool) {
TRACSClient.loginIfNecessary { (loggedin) in
if !loggedin {
let lvc = LoginViewController()
DispatchQueue.main.async {
Utils.hideActivity()
self.present(lvc, animated: true) {
self.navigationController?.popToRootViewController(animated: true)
}
}
}
IntegrationClient.registerIfNecessary();
}
}
func openEmailClient() {
let email = contactEmail.text ?? ""
if let url = URL(string: "mailto:\(email)") {
UIApplication.shared.openURL(url)
}
}
func removeHeaderView(headerView: UIView) {
var rect = headerView.frame
rect.size.height = 0
headerView.frame = rect
headerView.removeFromSuperview()
}
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
var sections: Int
if let site = site, let viewStyle = viewStyle {
sections = 0
if viewStyle == Style.Discussions {
return 1
}
if site.hasannouncements { sections += 1 }
if site.hasdiscussions { sections += 1 }
} else {
sections = 1
}
return sections
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
var sectionCount: Int
if let viewStyle = viewStyle {
switch viewStyle {
case .Discussions: //Section 0 is discussions
sectionCount = discussionCount > 0 ? discussionCount : 1
case .Dashboard:
if announcementSection == 0 {
sectionCount = announcementCount > 0 ? announcementCount : 1
} else if discussionSection == 0 {
sectionCount = discussionCount > 0 ? discussionCount : 1
} else {
sectionCount = 1
}
}
} else {
sectionCount = announcementCount > 0 ? announcementCount : 1
}
return sectionCount
case 1:
return discussionCount > 0 ? discussionCount : 1
default:
return notifications.count > 0 ? notifications.count : 1
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
var headerSize: CGFloat = 45
if site == nil {
headerSize = CGFloat.leastNonzeroMagnitude
}
if let viewStyle = viewStyle, viewStyle == Style.Discussions {
headerSize = CGFloat.leastNonzeroMagnitude
}
return headerSize
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if site != nil, let viewStyle = viewStyle {
if viewStyle == Style.Discussions { return nil }
let settings = IntegrationClient.getRegistration().settings
switch section {
case 0:
if announcementSection == 0 {
if announcementHeader == nil {
announcementHeader = initialHeaderSetup(type: Section.Announcements)
}
let setting = makeSettingForSwitch(toggleSwitch: (announcementHeader?.headerSwitch)!)
let settingIsDisabled = settings!.entryIsDisabled(SettingsEntry(dict: setting))
announcementHeader?.headerSwitch.isOn = !settingIsDisabled
return announcementHeader
} else {
if discussionHeader == nil {
discussionHeader = initialHeaderSetup(type: Section.Discussions)
}
let setting = makeSettingForSwitch(toggleSwitch: (discussionHeader?.headerSwitch)!)
let settingIsDisabled = settings!.entryIsDisabled(SettingsEntry(dict: setting))
discussionHeader?.headerSwitch.isOn = !settingIsDisabled
return discussionHeader
}
case 1:
if discussionHeader == nil {
discussionHeader = initialHeaderSetup(type: Section.Discussions)
}
let setting = makeSettingForSwitch(toggleSwitch: (discussionHeader?.headerSwitch)!)
let settingIsDisabled = settings!.entryIsDisabled(SettingsEntry(dict: setting))
discussionHeader?.headerSwitch.isOn = !settingIsDisabled
return discussionHeader
default:
break
}
}
return nil
}
func initialHeaderSetup(type: Section) -> NotificationViewHeader {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "sectionlabel") as? NotificationViewHeader
header?.headerSwitch.site = site
header?.headerSwitch.addTarget(self, action: #selector(toggleSetting(sender:)), for: UIControlEvents.touchUpInside)
switch type {
case .Announcements:
header?.headerLabel.text = "Announcements"
header?.headerSwitch.notificationType = Section.Announcements.rawValue
break
case .Discussions:
header?.headerLabel.text = "Forums"
header?.headerSwitch.notificationType = Section.Discussions.rawValue
break
}
return header!
}
func toggleSetting(sender: HeaderSwitch) {
let newSetting = makeSettingForSwitch(toggleSwitch: sender)
let settings = IntegrationClient.getRegistration().settings
if !sender.isOn {
settings?.disableEntry(SettingsEntry(dict: newSetting))
} else {
settings?.enableEntry(SettingsEntry(dict: newSetting))
}
IntegrationClient.saveSettings(settings!, completion: { (success) in
Analytics.event(category: "Filter", action: sender.isOn ? "allow" : "block", label: "\(sender.site?.id ?? "") - \(sender.notificationType ?? "")", value: nil)
NSLog("\(sender.notificationType ?? "") \(sender.isOn ? "enabled" : "disabled") for \(sender.site?.title ?? "")")
self.loadNotifications(false)
})
}
func makeSettingForSwitch(toggleSwitch: HeaderSwitch) -> [String: [String: String]] {
var newSetting = [
"keys": [
"object_type": toggleSwitch.notificationType ?? ""
]
]
if let siteID = toggleSwitch.site?.id {
newSetting["other_keys"] = ["site_id": siteID]
}
return newSetting
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: NotificationCell
switch indexPath.section {
case 0:
if let viewStyle = viewStyle { //Not in Announcements screen
cell = tableView.dequeueReusableCell(withIdentifier: "notification", for: indexPath) as! NotificationCell
if viewStyle == Style.Discussions { //In Discussion screen
if discussionCount > 0 { //Discussions are available
let notify = getNotification(notificationType: Section.Discussions.rawValue, position: indexPath.row)
cell = buildCell(cell: cell, indexPath: indexPath, notify: notify)
} else { //Nothing to display
cell = buildCell(cell: cell, indexPath: indexPath, notify: nil)
}
}
if viewStyle == Style.Dashboard { //In Dashboard screen
if announcementSection == 0 { //This section is for announcements
if announcementCount > 0 { //Announcements are available
let notify = getNotification(notificationType: Section.Announcements.rawValue, position: indexPath.row)
cell = buildCell(cell: cell, indexPath: indexPath, notify: notify)
} else { //Nothing to display
cell = buildCell(cell: cell, indexPath: indexPath, notify: nil)
}
} else if discussionSection == 0 { //This section must be for discussions
if discussionCount > 0 { //Discussions are available
let notify = getNotification(notificationType: Section.Discussions.rawValue, position: indexPath.row)
cell = buildCell(cell: cell, indexPath: indexPath, notify: notify)
} else {
cell = buildCell(cell: cell, indexPath: indexPath, notify: nil)
}
} else { //The site has no notification tools
cell = buildCell(cell: cell, indexPath: indexPath, notify: nil)
}
}
} else { //In All Announcements screen
cell = tableView.dequeueReusableCell(withIdentifier: "notification", for: indexPath) as! NotificationCell
if announcementCount > 0 { //Announcements are available
let notify = getNotification(notificationType: Section.Announcements.rawValue, position: indexPath.row)
cell = buildCell(cell: cell, indexPath: indexPath, notify: notify)
} else { //Nothing to display
cell = buildCell(cell: cell, indexPath: indexPath, notify: nil)
}
}
case 1:
cell = tableView.dequeueReusableCell(withIdentifier: "notification", for: indexPath) as! NotificationCell
if discussionCount > 0 {
let notify = getNotification(notificationType: Section.Discussions.rawValue, position: indexPath.row)
cell = buildCell(cell: cell, indexPath: indexPath, notify: notify)
} else {
cell = buildCell(cell: cell, indexPath: indexPath, notify: nil)
}
default:
cell = tableView.dequeueReusableCell(withIdentifier: "notification", for: indexPath) as! NotificationCell
break
}
return cell
}
func buildCell(cell: NotificationCell, indexPath: IndexPath, notify: Notification?) -> NotificationCell {
if let tracsobj = notify?.object {
cell.isRead = (notify?.isRead())!
let imageColor = cell.isRead ? Utils.readIcon : Utils.unreadIcon
cell.iView.image = UIImage.fontAwesomeIcon(name: tracsobj.getIcon(), textColor: imageColor, size:CGSize(width: 200, height: 200))
cell.titleLabel.text = tracsobj.tableTitle()
cell.titleLabel.font = (notify?.isRead())! ? UIFont.preferredFont(forTextStyle: .body) : Utils.boldPreferredFont(style: .body)
cell.subtitleLabel.text = getSubtitleFromNotification(notif: notify!)
cell.subtitleLabel.font = UIFont.preferredFont(forTextStyle: .caption1)
if !tracsobj.getUrl().isEmpty {
cell.accessoryType = .disclosureIndicator
}
cell.isUserInteractionEnabled = true
} else {
var titleLabel: String = ""
switch indexPath.section {
case 0:
if let viewStyle = viewStyle {
if viewStyle == Style.Discussions {
if discussionCount == 0 {
titleLabel = NO_FORUM_POSTS
}
} else {
if announcementCount == 0 && announcementSection == 0 {
titleLabel = NO_ANNOUNCEMENTS
} else if discussionCount == 0 && discussionSection == 0 {
titleLabel = NO_FORUM_POSTS
} else {
titleLabel = NO_TOOLS_ENABLED
}
}
} else {
if announcementCount == 0 {
titleLabel = NO_ANNOUNCEMENTS
}
}
case 1:
if discussionCount == 0 {
titleLabel = NO_FORUM_POSTS
}
default:
titleLabel = NO_TOOLS_ENABLED
}
cell.isRead = true
cell.iView.image = nil
cell.titleLabel.font = UIFont.preferredFont(forTextStyle: .body)
cell.titleLabel.text = titleLabel
cell.subtitleLabel.text = ""
cell.isUserInteractionEnabled = false
}
return cell
}
func getSubtitleFromNotification(notif: Notification) -> String {
if let type = notif.object_type {
switch (type) {
case "announcement":
return notif.object?.site?.title ?? ""
case "discussion":
let disc = notif.object as! Discussion
return disc.subtitle
default:
break
}
}
return ""
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UIFont.preferredFont(forTextStyle: .body).pointSize * 2.8
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
return [UITableViewRowAction(style: .default, title: "Dismiss", handler: { (action, indexPath) in
var n: Notification?
switch indexPath.section {
case 0:
if let viewStyle = self.viewStyle {
switch viewStyle {
case .Discussions:
n = self.getNotification(notificationType: Section.Discussions.rawValue, position: indexPath.row)
break
case .Dashboard:
if self.announcementSection == 0 {
n = self.getNotification(notificationType: Section.Announcements.rawValue, position: indexPath.row)
} else if self.discussionSection == 0 {
n = self.getNotification(notificationType: Section.Discussions.rawValue, position: indexPath.row)
} else {
n = self.getNotification(notificationType: Section.Announcements.rawValue, position: indexPath.row)
}
break
}
} else {
n = self.getNotification(notificationType: Section.Announcements.rawValue, position: indexPath.row)
}
break
case 1:
n = self.getNotification(notificationType: Section.Discussions.rawValue, position: indexPath.row)
break
default:
n = nil
break
}
if let n = n {
IntegrationClient.markNotificationCleared(n) { (success) in
DispatchQueue.main.async {
if success {
tableView.beginUpdates()
let index = self.convertIndex(indexPath: indexPath)
self.notifications.remove(at: index)
self.tableView.deleteRows(at: [indexPath], with: .fade)
self.tableView.reloadSections([indexPath.section], with: UITableViewRowAnimation.automatic)
tableView.endUpdates()
self.loadNotifications(true)
Analytics.event(category: "Notification", action: "cleared", label: n.object_type ?? "", value: nil)
}
}
}
}
})]
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var notify: Notification?
switch indexPath.section {
case 0:
if let style = viewStyle {
switch style {
case .Dashboard:
if announcementSection == 0 {
if announcementCount == 0 {
return
}
notify = getNotification(notificationType: Section.Announcements.rawValue, position: indexPath.row)
} else if discussionSection == 0 {
if discussionCount == 0 {
return
}
notify = getNotification(notificationType: Section.Discussions.rawValue, position: indexPath.row)
} else {
return
}
break
case .Discussions:
if discussionCount == 0 {
return
}
notify = getNotification(notificationType: Section.Discussions.rawValue, position: indexPath.row)
break
}
} else {
if announcementCount == 0 {
return
}
notify = getNotification(notificationType: Section.Announcements.rawValue, position: indexPath.row)
}
case 1:
if discussionCount == 0 {
return
}
notify = getNotification(notificationType: Section.Discussions.rawValue, position: indexPath.row)
default:
break
}
if let tracsobj = notify?.object {
if let url = URL(string: tracsobj.getUrl()) {
IntegrationClient.markNotificationRead(notify!, completion: { (success) in })
let label = notify?.object_type
Analytics.event(category: "Notification", action: "click", label: label ?? "", value: nil)
let wvStoryBoard = UIStoryboard(name: "MainStory", bundle: nil)
let wvController = wvStoryBoard.instantiateViewController(withIdentifier: "TracsWebView")
(wvController as! WebViewController).urlToLoad = url.absoluteString
navigationController?.pushViewController(wvController, animated: true)
}
}
}
// MARK: - More functions
func loadOnAppear() {
Analytics.viewWillAppear("Notifications")
loadNotifications(true)
}
func notificationReceived() {
loadNotifications(false)
}
func loadNotifications(_ showactivity:Bool) {
if showactivity { Utils.showActivity(view) }
TRACSClient.loginIfNecessary { (loggedin) in
if loggedin {
IntegrationClient.getNotifications { (notifications) in
self.discussionCount = 0
self.announcementCount = 0
if let notis = notifications {
let unseen = notis.filter({ (n) -> Bool in
var desiredSite: Bool
var willBeDisplayed: Bool = false
if let site = self.site {
desiredSite = n.site_id == site.id
if let viewStyle = self.viewStyle {
switch viewStyle {
case .Discussions:
willBeDisplayed = n.object_type == "discussion"
break
case .Dashboard:
willBeDisplayed = true
break
}
}
} else {
willBeDisplayed = n.object_type == "announcement"
desiredSite = true
}
return !n.seen && desiredSite && willBeDisplayed
})
IntegrationClient.markNotificationsSeen(unseen, completion: { (success) in
DispatchQueue.main.async {
UIApplication.shared.applicationIconBadgeNumber = 0
self.notifications = notis.filter({ (n) -> Bool in
var shouldBeDisplayed = true
if let site = self.site {
shouldBeDisplayed = n.site_id == site.id
} else {
shouldBeDisplayed = n.object_type == Section.Announcements.rawValue
}
if (shouldBeDisplayed) {
if let type = n.object_type {
switch type {
case Section.Announcements.rawValue:
self.announcementCount += 1
case Section.Discussions.rawValue:
self.discussionCount += 1
default:
break
}
}
}
return shouldBeDisplayed
})
self.tableView.reloadData()
Utils.hideActivity()
}
})
} else { //no notifications
DispatchQueue.main.async {
Utils.hideActivity()
}
}
}
}
}
}
func convertIndex(indexPath: IndexPath) -> Int {
var notificationType: String = ""
var returnIndex = -1
if let viewStyle = viewStyle {
switch viewStyle {
case .Dashboard:
switch indexPath.section {
case 0:
if announcementSection == 0 {
notificationType = Section.Announcements.rawValue
} else if discussionSection == 0 {
notificationType = Section.Discussions.rawValue
}
case 1:
notificationType = Section.Discussions.rawValue
default:
break
}
break
case .Discussions:
notificationType = Section.Discussions.rawValue
break
}
} else {
notificationType = Section.Announcements.rawValue
}
var totalFound = 0
for notif in notifications {
if notif.object_type == notificationType {
if totalFound == indexPath.row {
returnIndex = notifications.index(of: notif)!
break
}
totalFound += 1
}
}
return returnIndex
}
func getNotification(notificationType: String, position: Int) -> Notification? {
var totalFound = 0
for notif in notifications {
if notif.object_type == notificationType {
if totalFound == position {
return notif
}
totalFound += 1
}
}
return nil
}
func countTypes(notificationType: String) -> Int {
var count = 0
if self.notifications.count == 0 {
return count
}
for notif in self.notifications {
if notif.object_type == notificationType {
count += 1
}
}
return count
}
func clearAllPressed() {
IntegrationClient.markAllNotificationsCleared(notifications) { (success) in
if success {
DispatchQueue.main.async {
self.notifications = []
self.tableView.reloadData()
Analytics.event(category: "Notification", action: "cleared", label: "all", value: nil)
}
}
}
}
}
| mit | 5088fbc1d1a9ef1fef9a46856318fc97 | 41.998501 | 180 | 0.516318 | 5.934202 | false | false | false | false |
tgyhlsb/RxSwiftExt | Tests/RxSwift/applyTests.swift | 2 | 2097 | //
// applyTests.swift
// RxSwiftExt
//
// Created by Andy Chou on 2/22/17.
// Copyright © 2017 RxSwiftCommunity. All rights reserved.
//
import XCTest
import RxSwift
import RxSwiftExt
import RxTest
class applyTests: XCTestCase {
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 transform(input: Observable<Int>) -> Observable<Int> {
return input
.filter { $0 > 0 }
.map { $0 * $0 }
}
func testApply() {
let values = [0, 42, -7, 100, 1000, 1]
let scheduler = TestScheduler(initialClock: 0)
let observer = scheduler.createObserver(Int.self)
_ = Observable.from(values)
.apply(transform)
.subscribe(observer)
scheduler.start()
let correct = [
next(0, 42*42),
next(0, 100*100),
next(0, 1000*1000),
next(0, 1*1),
completed(0)
]
XCTAssertEqual(observer.events, correct)
}
func transformToString(input: Observable<Int>) -> Observable<String> {
return input
.distinctUntilChanged()
.map { String(describing: $0) }
}
func testApplyTransformingType() {
let values = [0, 0, 42, 42, -7, 100, 1000, 1, 1]
let scheduler = TestScheduler(initialClock: 0)
let observer = scheduler.createObserver(String.self)
_ = Observable.from(values)
.apply(transformToString)
.subscribe(observer)
scheduler.start()
let correct = [
next(0, "0"),
next(0, "42"),
next(0, "-7"),
next(0, "100"),
next(0, "1000"),
next(0, "1"),
completed(0)
]
XCTAssertEqual(observer.events, correct)
}
}
| mit | 01bc97dd46d9e5667594cd1f350503e9 | 23.372093 | 111 | 0.546756 | 4.208835 | false | true | false | false |
milseman/swift | test/SILGen/coverage_ternary.swift | 18 | 762 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -profile-generate -profile-coverage-mapping -emit-sorted-sil -emit-sil -module-name coverage_ternary %s | %FileCheck %s
// rdar://problem/23256795 - Avoid crash if an if_expr has no parent
// CHECK-LABEL: sil_coverage_map {{.*}}// coverage_ternary.bar.__allocating_init
class bar {
var m1 = 0 == 1
? "false" // CHECK: [[@LINE]]:16 -> [[@LINE]]:23 : 1
: "true"; // CHECK: [[@LINE]]:16 -> [[@LINE]]:22 : 0
}
// CHECK-LABEL: sil_coverage_map {{.*}}// coverage_ternary.foo
func foo(_ x : Int32) -> Int32 {
return x == 3
? 9000 // CHECK: [[@LINE]]:16 -> [[@LINE]]:20 : 1
: 1234 // CHECK: [[@LINE]]:16 -> [[@LINE]]:20 : (0 - 1)
}
foo(1)
foo(2)
foo(3)
| apache-2.0 | fcb71b321a9d0e5e67b6032a9ce574e8 | 35.285714 | 176 | 0.559055 | 3.201681 | false | false | false | false |
siyana/SwiftMaps | PhotoMaps/PhotoMaps/GoogleDataProvider.swift | 1 | 6814 | //
// GoogleDataProvider.swift
// PhotoMaps
//
// Created by Siyana Slavova on 4/3/15.
// Copyright (c) 2015 Siyana Slavova. All rights reserved.
//
import Foundation
class GoogleDataProvider {
var photoCache = [String:UIImage]()
var placesTask = NSURLSessionDataTask()
var session: NSURLSession {
return NSURLSession.sharedSession()
}
func fetchPlaceFromText(text: String, completion: (([GooglePlace]) -> Void)) -> () {
let escapedText = text.stringByReplacingOccurrencesOfString(" ", withString: "%20", options: .RegularExpressionSearch, range: Range<String.Index>(start: text.startIndex, end: text.endIndex))
var urlString = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" + escapedText + "&key=" + GlobalConstants.googleApiKey
if placesTask.taskIdentifier > 0 && placesTask.state == .Running {
placesTask.cancel()
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
if let url = NSURL(string: urlString) {
placesTask = session.dataTaskWithURL(url) { (data, response, error) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
var placesArray = [GooglePlace]()
if let json = NSJSONSerialization.JSONObjectWithData(data, options:nil, error:nil) as? NSDictionary {
if let results = json["results"] as? NSArray {
for rawPlace:AnyObject in results {
let place = GooglePlace(dictionary: rawPlace as NSDictionary, acceptedTypes: [])
placesArray.append(place)
if let reference = place.photoReference {
self.fetchPhotoFromReference(reference) { image in
place.photo = image
}
}
}
}
dispatch_async(dispatch_get_main_queue()) {
completion(placesArray)
}
}
}
placesTask.resume()
} else {
dispatch_async(dispatch_get_main_queue()) {
completion([])
}
}
}
func fetchPlacesNearCoordinate(coordinate: CLLocationCoordinate2D, radius: Double, types: [String], completion: (([GooglePlace]) -> Void)) -> () {
var urlString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=\(GlobalConstants.googleApiKey)&location=\(coordinate.latitude),\(coordinate.longitude)&radius=\(radius)&rankby=prominence&sensor=true"
let typesString = types.count > 0 ? join("|", types) : "florist"
urlString += "&types=\(typesString)"
urlString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
if placesTask.taskIdentifier > 0 && placesTask.state == .Running {
placesTask.cancel()
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
placesTask = session.dataTaskWithURL(NSURL(string: urlString)!) {data, response, error in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
var placesArray = [GooglePlace]()
if let json = NSJSONSerialization.JSONObjectWithData(data, options:nil, error:nil) as? NSDictionary {
if let results = json["results"] as? NSArray {
for rawPlace:AnyObject in results {
let place = GooglePlace(dictionary: rawPlace as NSDictionary, acceptedTypes: types)
placesArray.append(place)
if let reference = place.photoReference {
self.fetchPhotoFromReference(reference) { image in
place.photo = image
}
}
}
}
}
dispatch_async(dispatch_get_main_queue()) {
completion(placesArray)
}
}
placesTask.resume()
}
func fetchDirectionsFrom(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D, completion: ((String?) -> Void)) -> ()
{
let urlString = "https://maps.googleapis.com/maps/api/directions/json?key=\(GlobalConstants.googleApiKey)&origin=\(from.latitude),\(from.longitude)&destination=\(to.latitude),\(to.longitude)&mode=walking"
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
session.dataTaskWithURL(NSURL(string: urlString)!) {data, response, error in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
var encodedRoute: String?
if let json = NSJSONSerialization.JSONObjectWithData(data, options:nil, error:nil) as? [String:AnyObject] {
if let routes = json["routes"] as AnyObject? as? [AnyObject] {
if let route = routes.first as? [String : AnyObject] {
if let polyline = route["overview_polyline"] as AnyObject? as? [String : String] {
if let points = polyline["points"] as AnyObject? as? String {
encodedRoute = points
}
}
}
}
}
dispatch_async(dispatch_get_main_queue()) {
completion(encodedRoute)
}
}.resume()
}
func fetchPhotoFromReference(reference: String, completion: ((UIImage?) -> Void)) -> ()
{
if let photo = photoCache[reference] as UIImage! {
completion(photo)
} else {
let urlString = "https://maps.googleapis.com/maps/api/place/photo?maxwidth=200&photoreference=\(reference)&key=\(GlobalConstants.googleApiKey)"
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
session.downloadTaskWithURL(NSURL(string: urlString)!) {url, response, error in
if url != nil {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if let downloadedPhoto = UIImage(data: NSData(contentsOfURL: url)!) {
self.photoCache[reference] = downloadedPhoto
dispatch_async(dispatch_get_main_queue()) {
completion(downloadedPhoto)
}
}
}
}.resume()
}
}
}
| mit | aedeb0f861fc086185f75d754f8b855f | 46.319444 | 225 | 0.562812 | 5.438148 | false | false | false | false |
georgymh/ZHAutoScrollView | Demo/Storyboard/Scrollable Form/ViewController.swift | 1 | 2716 | //
// ViewController.swift
// Scrollable Form
//
// Created by Georgy Marrero on 6/4/15.
// Copyright (c) 2015 Georgy Marrero. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// Outlet to the Scroll View with the ZHAutoScrollView class.
@IBOutlet weak var autoScrollView: ZHAutoScrollView!
// Outlet to the first textfield.
@IBOutlet weak var usernameTextField: UITextField!
// Outlet to the second textfield.
@IBOutlet weak var passwordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
/*
The way ZHAutoScrollView works for Interface Builder storyboards is
the following:
- ZHAutoScrollView works as a UIScrollView, therefore, the UIScrollView
inside the storyboard has to have the ZHAutoScrollView.swift file as its
class.
- ZHAutoScrollView has a UIView called contentView inside of its class,
therefore, we do not need to create another UIView inside the UIScrollView
inside the storyboard because this will make the UITextFields unworkable.
- The TextFields have to be manually added as Subviews of ZHAutoScrollView
in order for the class to manage all the Automatic Scrolling functionalities.
NOTE: To solve the ambiguous content width warning, the scroll view needs all
positional constraints (with a value of 0) with respect to the super view. Also,
at least one of the Subviews of the ScrollView need to have the necessary
constraints in order for the ScrollView to know its maximum height and width.
The combination of constraints that worked for me are the Top, Leading, Trailing,
and Bottom.
*/
// Linking the textField's with the ZHAutoScrollView (Necessary).
let textFields : [UITextField] = [usernameTextField, passwordTextField]
for field in textFields {
autoScrollView.contentView.addSubview(field)
}
// Good to explicitly declare.
autoScrollView.contentViewHasSameWidthWithScrollView = true
//autoScrollView.contentViewHasSameHeightWithScrollView = true
// Not necessary if you changed this on Storyboard.
autoScrollView.userInteractionEnabled = true
autoScrollView.bounces = true
autoScrollView.scrollEnabled = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | d6a3f2bfc696f24df76e2d748b649619 | 36.205479 | 94 | 0.661267 | 5.6 | false | false | false | false |
litso/Sections | Sources/Sections/Classes/SectionBuilder.swift | 1 | 1261 | //
// SectionBuilder.swift
// Sections
//
// Created by Robert Manson on 8/20/16.
//
//
import Foundation
public struct SectionBuilder<T> {
public typealias SectionsClosure = (Sections<T>) -> Sections<T>
fileprivate var sectionClosures: [SectionsClosure] = []
public var values: Sections<T>
public var sections: Sections<T> {
let values = sectionClosures.flatMap { $0(self.values) }
return Sections<T>(sections: values)
}
public func addSections(_ f: @escaping SectionsClosure) -> SectionBuilder<T> {
var sections = self
sections.sectionClosures.append(f)
return sections
}
public init(initialValues: Sections<T>) {
self.values = initialValues
}
}
extension SectionBuilder where T: Equatable {
/**
Find index path for value.
- parameter value: Value to find.
- returns: Index path of match or nil.
*/
public func indexPathOfValue(_ value: T) -> IndexPath? {
guard let sectionIndex = sections.firstIndex(where: { $0.rows.contains(value) }) else { return nil }
guard let rowIndex = sections[sectionIndex].rows.firstIndex(of: value) else { return nil }
return IndexPath(row: rowIndex, section: sectionIndex)
}
}
| mit | b3834e208e8f490a321bfc9f1e0dcac0 | 26.413043 | 108 | 0.655829 | 4.120915 | false | false | false | false |
haijianhuo/TopStore | TopStore/TabBarContainer.swift | 1 | 1825 | //
// TabBarContainer.swift
// TopStore
//
// Created by Haijian Huo on 8/6/17.
// Copyright © 2017 Haijian Huo. All rights reserved.
//
import UIKit
enum TabBarButtonName: Int {
case product = 0
case photo
case cart
}
class TabBarContainer: UIViewController {
@IBOutlet var tabButtons: [MIBadgeButton]!
let tabBarButtonImages = ["Box", "Photo", "Cart"]
var currentTag: Int = 0
var mainTabBarController: MainTabBarController {
get {
let ctrl = childViewControllers.first(where: { $0 is MainTabBarController })
return ctrl as! MainTabBarController
}
}
override func viewDidLoad() {
super.viewDidLoad()
for button in tabButtons {
let image = UIImage(named: tabBarButtonImages[button.tag])?.withRenderingMode(.alwaysTemplate)
button.setImage(image, for: .normal)
button.tintColor = (button.tag == self.currentTag) ? nil : .lightGray
button.badgeEdgeInsets = UIEdgeInsetsMake(15, 0, 0, 15)
}
}
@IBAction func tabButtonTapped(_ sender: UIButton) {
if sender.tag == self.currentTag || sender.tag >= (self.mainTabBarController.tabBar.items?.count)! {
return
}
DispatchQueue.main.async {
for button in self.tabButtons {
button.tintColor = (button.tag == sender.tag) ? nil : .lightGray
}
}
self.mainTabBarController.selectedIndex = sender.tag
self.currentTag = sender.tag
}
func tabBarButton(name: TabBarButtonName) -> MIBadgeButton? {
if name.rawValue >= (self.mainTabBarController.tabBar.items?.count)! {
return nil
}
return tabButtons[name.rawValue]
}
}
| mit | db33ff095a5d0ba273d09d68638f49d5 | 26.223881 | 108 | 0.600329 | 4.526055 | false | false | false | false |
justindarc/firefox-ios | UITests/LoginInputTests.swift | 1 | 5248 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import EarlGrey
@testable import Client
class LoginInputTests: KIFTestCase {
fileprivate var webRoot: String!
fileprivate var profile: Profile!
override func setUp() {
super.setUp()
profile = (UIApplication.shared.delegate as! AppDelegate).profile!
webRoot = SimplePageServer.start()
BrowserUtils.configEarlGrey()
BrowserUtils.dismissFirstRunUI()
}
override func tearDown() {
_ = profile.logins.wipeLocal().value
BrowserUtils.resetToAboutHome()
BrowserUtils.clearPrivateData()
super.tearDown()
}
func enterUrl(url: String) {
EarlGrey.selectElement(with: grey_accessibilityID("url")).perform(grey_tap())
EarlGrey.selectElement(with: grey_accessibilityID("address")).perform(grey_replaceText(url))
EarlGrey.selectElement(with: grey_accessibilityID("address")).perform(grey_typeText("\n"))
}
func waitForLoginDialog(text: String, appears: Bool = true) {
var success = false
var failedReason = "Failed to display dialog"
if appears == false {
failedReason = "Dialog still displayed"
}
let saveLoginDialog = GREYCondition(name: "Check login dialog appears", block: {
var errorOrNil: NSError?
let matcher = grey_allOf([grey_accessibilityLabel(text),
grey_sufficientlyVisible()])
EarlGrey.selectElement(with: matcher)
.assert(grey_notNil(), error: &errorOrNil)
if appears == true {
success = errorOrNil == nil
} else {
success = errorOrNil != nil
}
return success
}).wait(withTimeout: 10)
GREYAssertTrue(saveLoginDialog, reason: failedReason)
}
func testLoginFormDisplaysNewSnackbar() {
let url = "\(webRoot!)/loginForm.html"
let username = "[email protected]"
enterUrl(url: url)
tester().enterText(username, intoWebViewInputWithName: "username")
tester().enterText("password", intoWebViewInputWithName: "password")
tester().tapWebViewElementWithAccessibilityLabel("submit_btn")
waitForLoginDialog(text: "Save login \(username) for \(self.webRoot!)?")
EarlGrey.selectElement(with: grey_accessibilityID("SaveLoginPrompt.dontSaveButton")).perform(grey_tap())
}
func testLoginFormDisplaysUpdateSnackbarIfPreviouslySaved() {
let url = "\(webRoot!)/loginForm.html"
let username = "[email protected]"
let password1 = "password1"
let password2 = "password2"
enterUrl(url: url)
tester().enterText(username, intoWebViewInputWithName: "username")
tester().enterText(password1, intoWebViewInputWithName: "password")
tester().tapWebViewElementWithAccessibilityLabel("submit_btn")
waitForLoginDialog(text: "Save login \(username) for \(self.webRoot!)?")
EarlGrey.selectElement(with: grey_accessibilityID("SaveLoginPrompt.saveLoginButton"))
.perform(grey_tap())
tester().enterText(username, intoWebViewInputWithName: "username")
tester().enterText(password2, intoWebViewInputWithName: "password")
tester().tapWebViewElementWithAccessibilityLabel("submit_btn")
waitForLoginDialog(text: "Update login \(username) for \(self.webRoot!)?")
EarlGrey.selectElement(with: grey_accessibilityID("UpdateLoginPrompt.updateButton"))
.perform(grey_tap())
}
func testLoginFormDoesntOfferSaveWhenEmptyPassword() {
let url = "\(webRoot!)/loginForm.html"
let username = "[email protected]"
enterUrl(url: url)
tester().enterText(username, intoWebViewInputWithName: "username")
tester().enterText("", intoWebViewInputWithName: "password")
tester().tapWebViewElementWithAccessibilityLabel("submit_btn")
waitForLoginDialog(text: "Save login \(username) for \(self.webRoot!)?", appears: false)
}
func testLoginFormDoesntOfferUpdateWhenEmptyPassword() {
let url = "\(webRoot!)/loginForm.html"
let username = "[email protected]"
let password1 = "password1"
let password2 = ""
enterUrl(url: url)
tester().enterText(username, intoWebViewInputWithName: "username")
tester().enterText(password1, intoWebViewInputWithName: "password")
tester().tapWebViewElementWithAccessibilityLabel("submit_btn")
waitForLoginDialog(text: "Save login \(username) for \(self.webRoot!)?")
EarlGrey.selectElement(with: grey_accessibilityID("SaveLoginPrompt.saveLoginButton"))
.perform(grey_tap())
tester().enterText(username, intoWebViewInputWithName: "username")
tester().enterText(password2, intoWebViewInputWithName: "password")
tester().tapWebViewElementWithAccessibilityLabel("submit_btn")
waitForLoginDialog(text: "Save login \(username) for \(self.webRoot!)?", appears: false)
}
}
| mpl-2.0 | 3bb09b5c4269df1f731a33bfd023fe9b | 40.984 | 112 | 0.661395 | 5.150147 | false | true | false | false |
wolfposd/DynamicFeedback | DynamicFeedbackSheets/DynamicFeedbackSheets/View/PhotoCell.swift | 1 | 2815 | //
// PhotoCell.swift
// DynamicFeedbackSheets
//
// Created by Jan Hennings on 09/06/14.
// Copyright (c) 2014 Jan Hennings. All rights reserved.
//
import UIKit
class PhotoCell: ModuleCell, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: Properties
@IBOutlet var descriptionLabel: UILabel!
@IBOutlet var photoView: UIImageView!
var presentingController: UIViewController?
override var module: FeedbackSheetModule? {
willSet {
if let photo = newValue as? DescriptionModule {
descriptionLabel.text = photo.text
descriptionLabel.sizeToFit()
}
}
}
// FIXME: Testing, current Bug in Xcode (Ambiguous use of module)
func setModule(module: FeedbackSheetModule) {
self.module = module
}
// MARK: View Life Cycle
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func prepareForReuse() {
super.prepareForReuse()
photoView.image = UIImage(named: "camera")
}
// MARK: IBActions
@IBAction func pickPhoto(sender: UIButton) {
if presentingController != nil {
let actionSheet = UIActionSheet(title: "Choose:", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles: "Camera", "Library")
actionSheet.showInView(self.superview)
} else {
println("Error: No presenting controller")
}
}
// MARK: UIActionSheetDelegate
func actionSheet(actionSheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == actionSheet.cancelButtonIndex { return }
let pickerController = UIImagePickerController()
pickerController.delegate = self
if buttonIndex == 0 {
if !(UIImagePickerController.isSourceTypeAvailable(.Camera)) { return }
pickerController.sourceType = .Camera
}
// FIXME: Present Controller
// self.presentingController?.presentModalViewController(pickerController, animated: true)
}
// MARK: UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: NSDictionary!) {
if let photo = module as? DescriptionModule {
let pickedPhoto = info[UIImagePickerControllerOriginalImage] as UIImage
photoView.image = pickedPhoto
//photo.responseData = pickedPhoto
//delegate?.moduleCell(self, didGetResponse: photo.responseData, forID: photo.ID)
}
presentingController?.dismissViewControllerAnimated(true, completion: nil)
}
}
| gpl-2.0 | 50f5f49d605c55bfd2d9bfc912d77ff0 | 31.732558 | 175 | 0.653641 | 5.709939 | false | false | false | false |
knutigro/AppReviews | ReviewManager/ItunesService.swift | 1 | 3490 | //
// COReviewFetcher.swift
// App Reviews
//
// Created by Knut Inge Grosland on 2015-04-09.
// Copyright (c) 2015 Cocmoc. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
class ItunesService {
var url: String {
return urlHandler.nextUrl ?? urlHandler.initialUrl
}
let apId: String
let storeId: String?
var updated: NSDate?
let urlHandler: ItunesUrlHandler
// MARK: - Init & teardown
init(apId: String, storeId: String?) {
self.apId = apId
self.storeId = storeId
urlHandler = ItunesUrlHandler(apId: apId, storeId: storeId)
}
// MARK: - Update object
func updateWithJSON(json: JSON) {
if let dateString = json.itunesReviewsUpdatedAt {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss-SS:SS'"
if let date = dateFormatter.dateFromString(dateString) {
updated = date
}
}
urlHandler.updateWithJSON(json.itunesFeedLinks)
}
// MARK: - Fetching
func fetchReviews(url: String, completion: (reviews: [JSON], error: NSError?) -> Void) {
Alamofire.request(.GET, url, parameters: nil)
.responseJSON { response in
if response.result.error != nil {
NSLog("Error: \(response.result.error)")
print(response.request)
print(response)
completion(reviews: [], error: response.result.error)
} else {
let json = JSON(response.result.value!)
let reviews = json.itunesReviews
completion(reviews: reviews, error: nil)
// TODO: THIS WILL ALLWAYS FAIL SINCE nexturl is nil from the first round
if let nextUrl = self.urlHandler.nextUrl {
if reviews.count > 0 {
self.updateWithJSON(json)
self.fetchReviews(nextUrl, completion: completion)
}
}
}
}
}
class func fetchApplications(name: String, completion: (success: Bool, applications: JSON?, error: NSError?) -> Void) {
let url = "https://itunes.apple.com/search"
let params = ["term": name, "entity": "software"]
Alamofire.request(.GET, url, parameters: params)
.responseJSON { response in
if(response.result.error != nil) {
NSLog("Error: \(response.result.error)")
print(response.request)
print(response)
completion(success: false, applications: nil, error: response.result.error)
} else {
var json = JSON(response.result.value!)
completion(success: true, applications: json["results"], error: nil)
}
}
}
}
// MARK: Extension for reviewFeed
extension JSON {
var itunesFeed: JSON { return self["feed"] }
var itunesReviews: [JSON] { return self.itunesFeed["entry"].arrayValue }
var itunesReviewsUpdatedAt: String? { return self.itunesFeed["updated"]["label"].string }
var itunesFeedLinks: [JSON] { return self.itunesFeed["link"].arrayValue }
}
| gpl-3.0 | 1fac92a39be6b4be33c7895132022d2d | 31.018349 | 123 | 0.540974 | 4.780822 | false | false | false | false |
IkeyBenz/Hijack | HighJacked.spritebuilder/Gameplay.swift | 1 | 1204 | //
// Gameplay.swift
// HighJacked
//
// Created by Ikey Benzaken on 7/9/15.
// Copyright (c) 2015 Apportable. All rights reserved.
//
import Foundation
class Gameplay: CCNode, CCPhysicsCollisionDelegate {
weak var positionOne: CCNode!
weak var gamePhysicsNode: CCPhysicsNode!
weak var enemy: Enemy!
var helicopter = CCBReader.load("Helicopter") as! Helicopter?
// var helicopter: Helicopter?
var helicopters: [Helicopter] = []
func didLoadFromCCB() {
userInteractionEnabled = true
gamePhysicsNode.addChild(helicopter)
// Set initial scale and position of helicpters.
helicopter?.position = CGPoint(x: UIScreen.mainScreen().bounds.width + helicopter!.contentSizeInPoints.width/2, y: 180)
helicopter?.moveHelicopter()
helicopters.append(helicopter!)
println("NEW GAME")
gamePhysicsNode.collisionDelegate = self
gamePhysicsNode.debugDraw = false
}
let delta: CCTime = 300000
override func update(delta: CCTime) {
helicopter?.moveHelicopter()
}
} | mit | 9d31ac9d21b0308733c4fcb702881f18 | 20.909091 | 127 | 0.610465 | 4.026756 | false | false | false | false |
TLOpenSpring/TLTranstionLib-swift | TLTranstionLib-swift/Classes/Interactors/TLPinchInteraction.swift | 1 | 4647 | //
// TLPinchInteraction.swift
// Pods
//
// Created by Andrew on 16/8/8.
//
//
import UIKit
let PinchInteractionDefaultCompletionPercentage:CGFloat = 0.5;
/// 手指捏合的交互手势
public class TLPinchInteraction: UIPercentDrivenInteractiveTransition,TLTransitionInteractionProtocol,UIGestureRecognizerDelegate {
var fromViewController:UIViewController?
var gestureRecognizer:UIPinchGestureRecognizer{
let gesture = UIPinchGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
gesture.delegate = self
return gesture
}
//MARK: - TLTransitionInteractionProtocol属性
public var isInteractive: Bool = true
public var shouldCompleteTransition: Bool = false
public var action: TLTranstionAction = TLTranstionAction.tl_Any
public var nextControllerDelegate: TLTransitionInteractionControllerDelegate?
public func attachViewController(viewController viewController: UIViewController, action: TLTranstionAction) {
self.fromViewController = viewController
self.action = action
//给当前控制器添加手势
self.attachGestureRecognizerToView((self.fromViewController?.view)!)
}
func attachGestureRecognizerToView(view:UIView) -> Void {
view.addGestureRecognizer(gestureRecognizer)
}
deinit{
self.gestureRecognizer.view?.removeGestureRecognizer(self.gestureRecognizer)
}
/**
滑动手势的百分比
- parameter pinchGestureRecognizer: 手势
- returns:
*/
func translationPercentageWithPinchGestureRecognizer(pinchGestureRecognizer:UIPinchGestureRecognizer) -> CGFloat {
return pinchGestureRecognizer.scale / 2
}
func isPinchWithGesture(pinchGestureRecognizer:UIPinchGestureRecognizer) -> Bool {
return pinchGestureRecognizer.scale < 1
}
//MARK: - 手势处理
func handlePanGesture(pinchGesture:UIPinchGestureRecognizer) -> Void {
let percentage = self.translationPercentageWithPinchGestureRecognizer(pinchGesture)
let isPinch = self.isPinchWithGesture(pinchGesture)
switch pinchGesture.state {
case .Began:
self.isInteractive = true
if let nextDelegate = self.nextControllerDelegate{
if !isPinch && nextDelegate is TLTransitionInteractionControllerDelegate{
if (action == TLTranstionAction.tl_Push){
self.fromViewController?.navigationController?.pushViewController(self.nextControllerDelegate!.nextViewControllerForInteractor(self), animated: true)
}else if(action == TLTranstionAction.tl_Present){
self.fromViewController?.presentViewController(self.nextControllerDelegate!.nextViewControllerForInteractor(self), animated: true, completion: nil)
}
}else{
if action == TLTranstionAction.tl_Pop{
//取消交互
self.cancelInteractiveTransition()
self.isInteractive = false
self.fromViewController?.navigationController?.popViewControllerAnimated(true)
}else if(action == TLTranstionAction.tl_Dismiss){
//取消交互
self.cancelInteractiveTransition()
self.isInteractive = false
self.fromViewController?.dismissViewControllerAnimated(true, completion: nil)
}
}
}
break
case .Changed:
if self.isInteractive == true{
self.shouldCompleteTransition = percentage > PinchInteractionDefaultCompletionPercentage
self.updateInteractiveTransition(percentage)
}
break
case .Cancelled:
self.isInteractive = false
self.cancelInteractiveTransition()
break
case .Ended:
if self.isInteractive{
self.isInteractive = false
if !self.shouldCompleteTransition || pinchGesture.state == .Cancelled{
self.cancelInteractiveTransition()
}else{
self.finishInteractiveTransition()
}
}
break
default:
break
}
}
}
| mit | af3ccfc408a0e989b479b792ecfd0a70 | 31.578571 | 173 | 0.607542 | 6.352368 | false | false | false | false |
billdonner/sheetcheats9 | RamPaperSwitch/RAMPaperSwitch.swift | 1 | 6947 | // RAMPaperSwitch.swift
//
// Copyright (c) 26/11/14 Ramotion Inc. (http://ramotion.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/// Swift subclass of the UISwitch which paints over the parent view with the onTintColor when the switch is turned on.
open class RAMPaperSwitch: UISwitch, CAAnimationDelegate {
struct Constants {
static let scale = "transform.scale"
static let up = "scaleUp"
static let down = "scaleDown"
}
/// The total duration of the animations, measured in seconds. Default 0.35
@IBInspectable open var duration: Double = 0.35
/// Closuer call when animation start
open var animationDidStartClosure = {(onAnimation: Bool) -> Void in }
/// Closuer call when animation finish
open var animationDidStopClosure = {(onAnimation: Bool, finished: Bool) -> Void in }
fileprivate var shape: CAShapeLayer! = CAShapeLayer()
fileprivate var radius: CGFloat = 0.0
fileprivate var oldState = false
fileprivate var defaultTintColor: UIColor?
fileprivate(set) var parentView: UIView?
// MARK: - Initialization
/**
Returns an initialized switch object.
- parameter view: animatable view
- parameter color: The color which fill view.
- returns: An initialized UISwitch object.
*/
public required init(view: UIView?, color: UIColor?) {
super.init(frame: CGRect.zero)
onTintColor = color
self.commonInit(view)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func awakeFromNib() {
self.commonInit(superview)
super.awakeFromNib()
}
// MARK: Helpers
fileprivate func commonInit(_ parentView: UIView?) {
guard let onTintColor = self.onTintColor else {
fatalError("set tint color")
}
self.parentView = parentView
self.defaultTintColor = parentView?.backgroundColor
layer.borderWidth = 0.5
layer.borderColor = UIColor.white.cgColor
layer.cornerRadius = frame.size.height / 2
shape.fillColor = onTintColor.cgColor
shape.masksToBounds = true
parentView?.layer.insertSublayer(shape, at: 0)
parentView?.layer.masksToBounds = true
showShapeIfNeed()
addTarget(self, action: #selector(RAMPaperSwitch.switchChanged), for: UIControlEvents.valueChanged)
}
override open func layoutSubviews() {
let x:CGFloat = max(frame.midX, superview!.frame.size.width - frame.midX);
let y:CGFloat = max(frame.midY, superview!.frame.size.height - frame.midY);
radius = sqrt(x*x + y*y);
shape.frame = CGRect(x: frame.midX - radius, y: frame.midY - radius, width: radius * 2, height: radius * 2)
shape.anchorPoint = CGPoint(x: 0.5, y: 0.5);
shape.path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: radius * 2, height: radius * 2)).cgPath
}
// MARK: - Public
open override func setOn(_ on: Bool, animated: Bool) {
let changed:Bool = on != self.isOn
super.setOn(on, animated: animated)
if changed {
switchChangeWithAniation(animated)
}
}
// MARK: - Private
fileprivate func showShapeIfNeed() {
shape.transform = isOn ? CATransform3DMakeScale(1.0, 1.0, 1.0) : CATransform3DMakeScale(0.0001, 0.0001, 0.0001)
}
@objc internal func switchChanged() {
switchChangeWithAniation(true)
}
// MARK: - Animations
fileprivate func animateKeyPath(_ keyPath: String, fromValue from: CGFloat?, toValue to: CGFloat, timing timingFunction: String) -> CABasicAnimation {
let animation:CABasicAnimation = CABasicAnimation(keyPath: keyPath)
animation.fromValue = from
animation.toValue = to
animation.repeatCount = 1
animation.timingFunction = CAMediaTimingFunction(name: timingFunction)
animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeForwards
animation.duration = duration
animation.delegate = self
return animation
}
fileprivate func switchChangeWithAniation(_ animation: Bool) {
guard let onTintColor = self.onTintColor else {
return
}
shape.fillColor = onTintColor.cgColor
if isOn {
let scaleAnimation:CABasicAnimation = animateKeyPath(Constants.scale,
fromValue: 0.01,
toValue: 1.0,
timing:kCAMediaTimingFunctionEaseIn);
if animation == false { scaleAnimation.duration = 0.0001 }
shape.add(scaleAnimation, forKey: Constants.up)
} else {
let scaleAnimation:CABasicAnimation = animateKeyPath(Constants.scale,
fromValue: 1.0,
toValue: 0.01,
timing:kCAMediaTimingFunctionEaseOut);
if animation == false { scaleAnimation.duration = 0.0001 }
shape.add(scaleAnimation, forKey: Constants.down)
}
}
//MARK: - CAAnimation Delegate
open func animationDidStart(_ anim: CAAnimation) {
parentView?.backgroundColor = defaultTintColor
animationDidStartClosure(isOn)
}
open func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if flag == true {
parentView?.backgroundColor = isOn == true ? onTintColor : defaultTintColor
}
animationDidStopClosure(isOn, flag)
}
}
| apache-2.0 | 966fe6b730bfb87516c44a813aaa41cb | 35.756614 | 154 | 0.62545 | 4.976361 | false | false | false | false |
nodes-ios/NStack | NStackSDK/NStackSDK/Classes/Model/AppOpenData.swift | 1 | 1486 | //
// AppOpenData.swift
// NStack
//
// Created by Kasper Welner on 09/09/15.
// Copyright © 2015 Nodes. All rights reserved.
//
import Foundation
import Serpent
struct AppOpenData {
var count = 0
var message: Message?
var update: Update?
var rateReminder: RateReminder?
var translate: NSDictionary?
var deviceMapping: [String: String] = [:] // <-ios_devices
var createdAt = Date()
var lastUpdated = Date()
}
extension AppOpenData: Serializable {
init(dictionary: NSDictionary?) {
count <== (self, dictionary, "count")
message <== (self, dictionary, "message")
update <== (self, dictionary, "update")
rateReminder <== (self, dictionary, "rate_reminder")
translate <== (self, dictionary, "translate")
deviceMapping <== (self, dictionary, "ios_devices")
createdAt <== (self, dictionary, "created_at")
lastUpdated <== (self, dictionary, "last_updated")
}
func encodableRepresentation() -> NSCoding {
let dict = NSMutableDictionary()
(dict, "count") <== count
(dict, "message") <== message
(dict, "update") <== update
(dict, "rate_reminder") <== rateReminder
(dict, "translate") <== translate
(dict, "ios_devices") <== deviceMapping
(dict, "created_at") <== createdAt
(dict, "last_updated") <== lastUpdated
return dict
}
}
| mit | 47729efd543592cb8171e2109d2da914 | 28.7 | 62 | 0.573064 | 4.171348 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/UI/PlaybackOverlayView.swift | 1 | 8033 | /*
* Copyright 2019 Google LLC. 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 third_party_objective_c_material_components_ios_components_Palettes_Palettes
/// An overlay view for ChartView that displays a flag and arrow that points to a point on a chart.
class PlaybackOverlayView: UIView {
// MARK: - DottedLineView
private class DottedLineView: ShapeView {
override init(color: UIColor, frame: CGRect, coder aDecoder: NSCoder?) {
super.init(color: color, frame: frame, coder: aDecoder)
shapeLayer.lineDashPattern = [2, 2]
shapeLayer.strokeColor = UIColor.lightGray.cgColor
shapeLayer.lineWidth = 1
}
override var intrinsicContentSize: CGSize {
return CGSize(width: 1, height: UIView.noIntrinsicMetric)
}
override func layoutSubviews() {
super.layoutSubviews()
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: 0, y: bounds.size.height))
shapeLayer.path = path.cgPath
}
}
// MARK: - ChartDotView
private class ChartDotView: ShapeView {
override init(color: UIColor, frame: CGRect, coder aDecoder: NSCoder?) {
super.init(color: color, frame: frame, coder: aDecoder)
shapeLayer.fillColor = color.cgColor
shapeLayer.strokeColor = UIColor.white.cgColor
shapeLayer.lineWidth = 2
}
override func layoutSubviews() {
super.layoutSubviews()
shapeLayer.path = UIBezierPath(ovalIn: bounds).cgPath
}
}
// MARK: - TimelineDotView
private class TimelineDotView: UIView {
let strokeWidth: CGFloat = 40
let strokeSelectedWidth: CGFloat = 20
let innerDotRadius: CGFloat = 3.5
let maxRadius: CGFloat = 25
var outerDotRadius: CGFloat {
return isSelected ? maxRadius : 10
}
let innerDotLayer = CAShapeLayer()
let outerDotLayer = CAShapeLayer()
var isSelected = false {
didSet {
setNeedsLayout()
}
}
init(frame: CGRect = .zero, coder aDecoder: NSCoder? = nil) {
if let aDecoder = aDecoder {
super.init(coder: aDecoder)!
} else {
super.init(frame: frame)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
configureView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureView()
}
override func layoutSubviews() {
super.layoutSubviews()
let innerDotFrame = CGRect(x: (bounds.size.width / 2) - innerDotRadius,
y: (bounds.size.height / 2) - innerDotRadius,
width: innerDotRadius * 2,
height: innerDotRadius * 2)
innerDotLayer.path = UIBezierPath(ovalIn: innerDotFrame).cgPath
let outerDotFrame = CGRect(x: (bounds.size.width / 2) - outerDotRadius,
y: (bounds.size.height / 2) - outerDotRadius,
width: outerDotRadius * 2,
height: outerDotRadius * 2)
outerDotLayer.path = UIBezierPath(ovalIn: outerDotFrame).cgPath
}
private func configureView() {
innerDotLayer.fillColor = MDCPalette.blue.tint600.cgColor
outerDotLayer.fillColor = UIColor(red: 0.259, green: 0.522, blue: 0.957, alpha: 0.33).cgColor
layer.addSublayer(innerDotLayer)
layer.addSublayer(outerDotLayer)
}
}
// MARK: - Properties
private let flagView = DataPointFlagView()
private let dottedLine = DottedLineView()
private let chartDot = ChartDotView()
private let timelineDot = TimelineDotView()
private let colorPalette: MDCPalette?
init(colorPalette: MDCPalette?, frame: CGRect = .zero, coder aDecoder: NSCoder? = nil) {
self.colorPalette = colorPalette
if let aDecoder = aDecoder {
super.init(coder: aDecoder)!
} else {
super.init(frame: frame)
}
configureView()
}
override convenience init(frame: CGRect) {
self.init(colorPalette: MDCPalette.blue, frame: frame)
}
required convenience init?(coder aDecoder: NSCoder) {
self.init(colorPalette: MDCPalette.blue, coder: aDecoder)
}
private func configureView() {
flagView.color = colorPalette?.tint600
chartDot.color = colorPalette?.tint600
// flagView is not added as a sub view until its frame has been calculated the first time to
// avoid a constraint error.
addSubview(dottedLine)
addSubview(chartDot)
addSubview(timelineDot)
}
/// Adjusts the flag view and dotted line to align with the given point.
///
/// - Parameters:
/// - point: A CGPoint relative to this view.
/// - timestamp: A string representing a timestamp.
/// - value: A string representing a value.
/// - isDragging: True if the current point is being dragged, otherwise false.
/// - timeAxisLineYPosition: The y-position of the time axis line, which is where the timeline
/// dot should be positioned.
func setCurrentPoint(_ point: CGPoint,
timestamp: String,
value: String,
isDragging: Bool,
timeAxisLineYPosition: CGFloat) {
// Hide flag and line if point is out of bounds.
guard point.x >= 0, point.x <= bounds.size.width else {
flagView.isHidden = true
dottedLine.isHidden = true
chartDot.isHidden = true
timelineDot.isHidden = true
return
}
flagView.isHidden = false
dottedLine.isHidden = false
chartDot.isHidden = false
timelineDot.isHidden = false
flagView.timestampLabel.text = timestamp
flagView.valueLabel.text = value
// Don't let the flag view beyond the view bounds.
let flagSize = flagView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
let flagX = min(max(0, point.x - flagSize.width / 2), bounds.size.width - flagSize.width)
flagView.frame = CGRect(x: flagX, y: 0, width: flagSize.width, height: flagSize.height)
// Add flag view the first time only after setting its frame to avoid a constraint error.
if !subviews.contains(flagView) {
addSubview(flagView)
}
// Adjust flag arrow if point is near the view edges.
let halfFlagWidth = flagSize.width / 2
let maxCenteredArrow = bounds.size.width - halfFlagWidth
let minCenteredArrow = halfFlagWidth
if point.x - maxCenteredArrow > 0 {
flagView.arrowOffset = point.x - maxCenteredArrow
} else if point.x < minCenteredArrow {
flagView.arrowOffset = point.x - minCenteredArrow
} else {
flagView.arrowOffset = 0
}
let dottedLineHeight = point.y - flagView.frame.maxY
dottedLine.frame = CGRect(x: point.x,
y: flagView.frame.maxY,
width: 1,
height: dottedLineHeight)
let chartDotRadius: CGFloat = 4
chartDot.frame = CGRect(x: point.x - chartDotRadius,
y: point.y - chartDotRadius,
width: chartDotRadius * 2,
height: chartDotRadius * 2)
timelineDot.frame = CGRect(x: point.x - timelineDot.maxRadius,
y: timeAxisLineYPosition - timelineDot.maxRadius,
width: timelineDot.maxRadius * 2,
height: timelineDot.maxRadius * 2)
timelineDot.isSelected = isDragging
}
}
| apache-2.0 | 3ce671ce160f06efb8110f74cadf4f37 | 33.182979 | 99 | 0.640732 | 4.35393 | false | false | false | false |
wikimedia/apps-ios-wikipedia | Wikipedia/Code/SearchViewController.swift | 1 | 24969 | import UIKit
class SearchViewController: ArticleCollectionViewController, UISearchBarDelegate {
// MARK - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.displayType = displayType
title = CommonStrings.searchTitle
if !areRecentSearchesEnabled, shouldSetTitleViewWhenRecentSearchesAreDisabled {
navigationItem.titleView = UIView()
}
navigationBar.isTitleShrinkingEnabled = true
navigationBar.isShadowHidingEnabled = false
navigationBar.isBarHidingEnabled = false
navigationBar.addUnderNavigationBarView(searchBarContainerView)
view.bringSubviewToFront(resultsViewController.view)
resultsViewController.view.isHidden = true
}
override func viewWillAppear(_ animated: Bool) {
updateLanguageBarVisibility()
super.viewWillAppear(animated)
reloadRecentSearches()
if animated && shouldBecomeFirstResponder {
navigationBar.isAdjustingHidingFromContentInsetChangesEnabled = false
searchBar.becomeFirstResponder()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
funnel.logSearchStart(from: source)
NSUserActivity.wmf_makeActive(NSUserActivity.wmf_searchView())
if !animated && shouldBecomeFirstResponder {
searchBar.becomeFirstResponder()
}
navigationBar.isAdjustingHidingFromContentInsetChangesEnabled = true
shouldAnimateSearchBar = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationBar.isAdjustingHidingFromContentInsetChangesEnabled = false
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
navigationBar.isAdjustingHidingFromContentInsetChangesEnabled = true
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { (context) in
self.view.setNeedsLayout()
self.resultsViewController.view.setNeedsLayout()
self.view.layoutIfNeeded()
})
}
// MARK - State
var shouldAnimateSearchBar: Bool = true
var isAnimatingSearchBarState: Bool = false
@objc var areRecentSearchesEnabled: Bool = true
@objc var shouldBecomeFirstResponder: Bool = false
var displayType: NavigationBarDisplayType = .largeTitle
var shouldSetSearchVisible: Bool = true
var shouldSetTitleViewWhenRecentSearchesAreDisabled: Bool = true
var shouldShowCancelButton: Bool = true
var delegatesSelection: Bool = false {
didSet {
resultsViewController.delegatesSelection = delegatesSelection
}
}
var showLanguageBar: Bool?
var nonSearchAlpha: CGFloat = 1 {
didSet {
collectionView.alpha = nonSearchAlpha
resultsViewController.view.alpha = nonSearchAlpha
navigationBar.backgroundAlpha = nonSearchAlpha
}
}
@objc var searchTerm: String? {
set {
searchBar.text = newValue
}
get {
return searchBar.text
}
}
private var _siteURL: URL?
var siteURL: URL? {
get {
return _siteURL ?? searchLanguageBarViewController?.currentlySelectedSearchLanguage?.siteURL() ?? MWKLanguageLinkController.sharedInstance().appLanguage?.siteURL() ?? NSURL.wmf_URLWithDefaultSiteAndCurrentLocale()
}
set {
_siteURL = newValue
}
}
@objc func search() {
search(for: searchTerm, suggested: false)
}
private func search(for searchTerm: String?, suggested: Bool) {
guard let siteURL = siteURL else {
assert(false)
return
}
guard
let searchTerm = searchTerm,
searchTerm.wmf_hasNonWhitespaceText
else {
didCancelSearch()
return
}
guard (searchTerm as NSString).character(at: 0) != NSTextAttachment.character else {
return
}
let start = Date()
MWNetworkActivityIndicatorManager.shared()?.push()
fakeProgressController.start()
let commonCompletion = {
MWNetworkActivityIndicatorManager.shared()?.pop()
}
let failure = { (error: Error, type: WMFSearchType) in
DispatchQueue.main.async {
commonCompletion()
self.fakeProgressController.stop()
guard searchTerm == self.searchBar.text else {
return
}
self.resultsViewController.emptyViewType = (error as NSError).wmf_isNetworkConnectionError() ? .noInternetConnection : .noSearchResults
self.resultsViewController.results = []
self.funnel.logShowSearchError(withTypeOf: type, elapsedTime: Date().timeIntervalSince(start), source: self.source)
}
}
let sucess = { (results: WMFSearchResults, type: WMFSearchType) in
DispatchQueue.main.async {
commonCompletion()
guard searchTerm == self.searchBar.text else {
return
}
NSUserActivity.wmf_makeActive(NSUserActivity.wmf_searchResultsActivitySearchSiteURL(siteURL, searchTerm: searchTerm))
let resultsArray = results.results ?? []
self.resultsViewController.emptyViewType = .noSearchResults
self.fakeProgressController.finish()
self.resultsViewController.resultsInfo = results
self.resultsViewController.searchSiteURL = siteURL
self.resultsViewController.results = resultsArray
guard !suggested else {
return
}
self.funnel.logSearchResults(withTypeOf: type, resultCount: UInt(resultsArray.count), elapsedTime: Date().timeIntervalSince(start), source: self.source)
}
}
fetcher.fetchArticles(forSearchTerm: searchTerm, siteURL: siteURL, resultLimit: WMFMaxSearchResultLimit, failure: { (error) in
failure(error, .prefix)
}) { (results) in
sucess(results, .prefix)
guard let resultsArray = results.results, resultsArray.count < 12 else {
return
}
self.fetcher.fetchArticles(forSearchTerm: searchTerm, siteURL: siteURL, resultLimit: WMFMaxSearchResultLimit, fullTextSearch: true, appendToPreviousResults: results, failure: { (error) in
failure(error, .full)
}) { (results) in
sucess(results, .full)
}
}
}
private func setupLanguageBarViewController() -> SearchLanguagesBarViewController {
if let vc = self.searchLanguageBarViewController {
return vc
}
let searchLanguageBarViewController = SearchLanguagesBarViewController()
searchLanguageBarViewController.apply(theme: theme)
searchLanguageBarViewController.delegate = self
self.searchLanguageBarViewController = searchLanguageBarViewController
return searchLanguageBarViewController
}
private func updateLanguageBarVisibility() {
let showLanguageBar = self.showLanguageBar ?? UserDefaults.wmf.wmf_showSearchLanguageBar()
if showLanguageBar && searchLanguageBarViewController == nil { // check this before accessing the view
let searchLanguageBarViewController = setupLanguageBarViewController()
addChild(searchLanguageBarViewController)
searchLanguageBarViewController.view.translatesAutoresizingMaskIntoConstraints = false
navigationBar.addExtendedNavigationBarView(searchLanguageBarViewController.view)
searchLanguageBarViewController.didMove(toParent: self)
searchLanguageBarViewController.view.isHidden = false
} else if !showLanguageBar && searchLanguageBarViewController != nil {
searchLanguageBarViewController?.willMove(toParent: nil)
navigationBar.removeExtendedNavigationBarView()
searchLanguageBarViewController?.removeFromParent()
searchLanguageBarViewController = nil
}
}
override var headerStyle: ColumnarCollectionViewController.HeaderStyle {
return .sections
}
// MARK - Search
lazy var fetcher: WMFSearchFetcher = {
return WMFSearchFetcher()
}()
lazy var funnel: WMFSearchFunnel = {
return WMFSearchFunnel()
}()
func didCancelSearch() {
resultsViewController.emptyViewType = .none
resultsViewController.results = []
searchBar.text = nil
fakeProgressController.stop()
}
@objc func clear() {
didCancelSearch()
}
lazy var searchBarContainerView: UIView = {
let searchContainerView = UIView()
searchBar.translatesAutoresizingMaskIntoConstraints = false
searchContainerView.addSubview(searchBar)
let leading = searchContainerView.layoutMarginsGuide.leadingAnchor.constraint(equalTo: searchBar.leadingAnchor)
let trailing = searchContainerView.layoutMarginsGuide.trailingAnchor.constraint(equalTo: searchBar.trailingAnchor)
let top = searchContainerView.topAnchor.constraint(equalTo: searchBar.topAnchor)
let bottom = searchContainerView.bottomAnchor.constraint(equalTo: searchBar.bottomAnchor)
searchContainerView.addConstraints([leading, trailing, top, bottom])
return searchContainerView
}()
lazy var searchBar: UISearchBar = {
let searchBar = UISearchBar()
searchBar.delegate = self
searchBar.returnKeyType = .search
searchBar.searchBarStyle = .minimal
searchBar.placeholder = WMFLocalizedString("search-field-placeholder-text", value: "Search Wikipedia", comment: "Search field placeholder text")
return searchBar
}()
// used to match the transition with explore
func prepareForIncomingTransition(with incomingNavigationBar: NavigationBar) {
navigationBarTopSpacingPercentHidden = incomingNavigationBar.topSpacingPercentHidden
navigationBarTopSpacing = incomingNavigationBar.barTopSpacing
navigationBar.isTopSpacingHidingEnabled = true
navigationBar.barTopSpacing = navigationBarTopSpacing
navigationBar.topSpacingPercentHidden = navigationBarTopSpacingPercentHidden
navigationBar.isTopSpacingHidingEnabled = !_isSearchVisible
navigationBarShadowAlpha = incomingNavigationBar.shadowAlpha
navigationBar.shadowAlpha = navigationBarShadowAlpha
}
func prepareForOutgoingTransition(with outgoingNavigationBar: NavigationBar) {
navigationBarTopSpacingPercentHidden = outgoingNavigationBar.topSpacingPercentHidden
navigationBarShadowAlpha = outgoingNavigationBar.shadowAlpha
navigationBarTopSpacing = outgoingNavigationBar.barTopSpacing
}
private var navigationBarShadowAlpha: CGFloat = 0
private var navigationBarTopSpacingPercentHidden: CGFloat = 0
private var navigationBarTopSpacing: CGFloat = 0
var searchLanguageBarViewController: SearchLanguagesBarViewController?
private var _isSearchVisible: Bool = false
func setSearchVisible(_ visible: Bool, animated: Bool) {
_isSearchVisible = visible
navigationBar.isAdjustingHidingFromContentInsetChangesEnabled = false
let completion = { (finished: Bool) in
self.resultsViewController.view.isHidden = !visible
self.isAnimatingSearchBarState = false
self.navigationBar.isTitleShrinkingEnabled = true
self.navigationBar.isAdjustingHidingFromContentInsetChangesEnabled = true
}
if searchLanguageBarViewController != nil {
navigationBar.shadowAlpha = 0
}
if visible {
navigationBarTopSpacingPercentHidden = navigationBar.topSpacingPercentHidden
navigationBarShadowAlpha = navigationBar.shadowAlpha
navigationBarTopSpacing = navigationBar.barTopSpacing
}
let animations = {
self.navigationBar.isBarHidingEnabled = true
self.navigationBar.isTopSpacingHidingEnabled = true
self.navigationBar.isTitleShrinkingEnabled = false
self.navigationBar.barTopSpacing = self.navigationBarTopSpacing
self.navigationBar.setNavigationBarPercentHidden(visible ? 1 : 0, underBarViewPercentHidden: 0, extendedViewPercentHidden: 0, topSpacingPercentHidden: visible ? 1 : self.navigationBarTopSpacingPercentHidden, animated: false)
self.navigationBar.isBarHidingEnabled = false
self.navigationBar.isTopSpacingHidingEnabled = !visible
self.navigationBar.shadowAlpha = visible ? 1 : self.searchLanguageBarViewController != nil ? 0 : self.navigationBarShadowAlpha
self.resultsViewController.view.alpha = visible ? 1 : 0
if self.shouldShowCancelButton {
self.searchBar.setShowsCancelButton(visible, animated: animated)
}
self.view.layoutIfNeeded()
}
guard animated else {
animations()
completion(true)
return
}
isAnimatingSearchBarState = true
self.resultsViewController.view.alpha = visible ? 0 : 1
self.resultsViewController.view.isHidden = false
self.view.layoutIfNeeded()
UIView.animate(withDuration: 0.3, animations: animations, completion: completion)
}
lazy var resultsViewController: SearchResultsViewController = {
let resultsViewController = SearchResultsViewController()
resultsViewController.dataStore = dataStore
resultsViewController.apply(theme: theme)
resultsViewController.delegate = self
addChild(resultsViewController)
view.wmf_addSubviewWithConstraintsToEdges(resultsViewController.view)
resultsViewController.didMove(toParent: self)
return resultsViewController
}()
lazy var fakeProgressController: FakeProgressController = {
return FakeProgressController(progress: navigationBar, delegate: navigationBar)
}()
// MARK - Recent Search Saving
func saveLastSearch() {
guard
let term = resultsViewController.resultsInfo?.searchTerm,
let url = resultsViewController.searchSiteURL,
let entry = MWKRecentSearchEntry(url: url, searchTerm: term)
else {
return
}
dataStore.recentSearchList.addEntry(entry)
dataStore.recentSearchList.save()
reloadRecentSearches()
}
// MARK - UISearchBarDelegate
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
guard !isAnimatingSearchBarState else {
return false
}
if shouldSetSearchVisible {
setSearchVisible(true, animated: shouldAnimateSearchBar)
}
return true
}
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
guard !isAnimatingSearchBarState else {
return false
}
guard shouldAnimateSearchBar else {
didClickSearchButton = false
return true
}
if didClickSearchButton {
didClickSearchButton = false
} else if shouldSetSearchVisible {
setSearchVisible(false, animated: shouldAnimateSearchBar)
}
return true
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
search(for: searchBar.text, suggested: false)
}
private var didClickSearchButton = false
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
saveLastSearch()
didClickSearchButton = true
searchBar.endEditing(true)
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
if let navigationController = navigationController, navigationController.viewControllers.count > 1 {
if shouldAnimateSearchBar {
searchBar.text = nil
}
navigationController.popViewController(animated: true)
} else {
searchBar.endEditing(true)
didCancelSearch()
}
deselectAll(animated: true)
}
@objc func makeSearchBarBecomeFirstResponder() {
searchBar.becomeFirstResponder()
}
// MARK - Theme
override func apply(theme: Theme) {
super.apply(theme: theme)
guard viewIfLoaded != nil else {
return
}
searchBar.apply(theme: theme)
searchBarContainerView.backgroundColor = theme.colors.paperBackground
searchLanguageBarViewController?.apply(theme: theme)
resultsViewController.apply(theme: theme)
view.backgroundColor = .clear
collectionView.backgroundColor = theme.colors.paperBackground
}
// Recent
var recentSearches: MWKRecentSearchList? {
return self.dataStore.recentSearchList
}
func reloadRecentSearches() {
guard areRecentSearchesEnabled else {
return
}
collectionView.reloadData()
}
func deselectAll(animated: Bool) {
guard let selected = collectionView.indexPathsForSelectedItems else {
return
}
for indexPath in selected {
collectionView.deselectItem(at: indexPath, animated: animated)
}
}
override func articleURL(at indexPath: IndexPath) -> URL? {
return nil
}
override func article(at indexPath: IndexPath) -> WMFArticle? {
return nil
}
override func canDelete(at indexPath: IndexPath) -> Bool {
return indexPath.row < countOfRecentSearches // ensures user can't delete the empty state row
}
override func willPerformAction(_ action: Action) -> Bool {
return self.editController.didPerformAction(action)
}
override func delete(at indexPath: IndexPath) {
guard
let entries = recentSearches?.entries,
entries.indices.contains(indexPath.item) else {
return
}
let entry = entries[indexPath.item]
recentSearches?.removeEntry(entry)
recentSearches?.save()
guard countOfRecentSearches > 0 else {
collectionView.reloadData() // reload instead of deleting the row to get to empty state
return
}
collectionView.performBatchUpdates({
self.collectionView.deleteItems(at: [indexPath])
}) { (finished) in
self.collectionView.reloadData()
}
}
var countOfRecentSearches: Int {
return recentSearches?.entries.count ?? 0
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard areRecentSearchesEnabled else {
return 0
}
return max(countOfRecentSearches, 1) // 1 for empty state
}
override func configure(cell: ArticleRightAlignedImageCollectionViewCell, forItemAt indexPath: IndexPath, layoutOnly: Bool) {
cell.articleSemanticContentAttribute = .unspecified
cell.configureForCompactList(at: indexPath.item)
cell.isImageViewHidden = true
cell.apply(theme: theme)
editController.configureSwipeableCell(cell, forItemAt: indexPath, layoutOnly: layoutOnly)
cell.topSeparator.isHidden = indexPath.item == 0
cell.bottomSeparator.isHidden = indexPath.item == self.collectionView(collectionView, numberOfItemsInSection: indexPath.section) - 1
cell.titleLabel.textColor = theme.colors.secondaryText
guard
indexPath.row < countOfRecentSearches,
let entry = recentSearches?.entries[indexPath.item]
else {
cell.titleLabel.text = WMFLocalizedString("search-recent-empty", value: "No recent searches yet", comment: "String for no recent searches available")
return
}
cell.titleLabel.text = entry.searchTerm
}
override func configure(header: CollectionViewHeader, forSectionAt sectionIndex: Int, layoutOnly: Bool) {
header.style = .recentSearches
header.apply(theme: theme)
header.title = WMFLocalizedString("search-recent-title", value: "Recently searched", comment: "Title for list of recent search terms")
header.buttonTitle = countOfRecentSearches > 0 ? WMFLocalizedString("search-clear-title", value: "Clear", comment: "Text of the button shown to clear recent search terms") : nil
header.delegate = self
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let recentSearch = recentSearches?.entry(at: UInt(indexPath.item)) else {
return
}
searchBar.text = recentSearch.searchTerm
searchBar.becomeFirstResponder()
search()
}
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
guard let recentSearches = recentSearches, recentSearches.countOfEntries() > 0 else {
return false
}
return true
}
}
extension SearchViewController: CollectionViewHeaderDelegate {
func collectionViewHeaderButtonWasPressed(_ collectionViewHeader: CollectionViewHeader) {
let dialog = UIAlertController(title: WMFLocalizedString("search-recent-clear-confirmation-heading", value: "Delete all recent searches?", comment: "Heading text of delete all confirmation dialog"), message: WMFLocalizedString("search-recent-clear-confirmation-sub-heading", value: "This action cannot be undone!", comment: "Sub-heading text of delete all confirmation dialog"), preferredStyle: .alert)
dialog.addAction(UIAlertAction(title: WMFLocalizedString("search-recent-clear-cancel", value: "Cancel", comment: "Button text for cancelling delete all action\n{{Identical|Cancel}}"), style: .cancel, handler: nil))
dialog.addAction(UIAlertAction(title: WMFLocalizedString("search-recent-clear-delete-all", value: "Delete All", comment: "Button text for confirming delete all action\n{{Identical|Delete all}}"), style: .destructive, handler: { (action) in
self.didCancelSearch()
self.dataStore.recentSearchList.removeAllEntries()
self.dataStore.recentSearchList.save()
self.reloadRecentSearches()
}))
present(dialog, animated: true)
}
}
extension SearchViewController: ArticleCollectionViewControllerDelegate {
func articleCollectionViewController(_ articleCollectionViewController: ArticleCollectionViewController, didSelectArticleWith articleURL: URL, at indexPath: IndexPath) {
funnel.logSearchResultTap(at: indexPath.item, source: source)
saveLastSearch()
guard delegatesSelection else {
return
}
delegate?.articleCollectionViewController(self, didSelectArticleWith: articleURL, at: indexPath)
}
}
extension SearchViewController: SearchLanguagesBarViewControllerDelegate {
func searchLanguagesBarViewController(_ controller: SearchLanguagesBarViewController, didChangeCurrentlySelectedSearchLanguage language: MWKLanguageLink) {
funnel.logSearchLangSwitch(source)
search()
}
}
// MARK: - Event logging
extension SearchViewController {
private var source: String {
guard let navigationController = navigationController, !navigationController.viewControllers.isEmpty else {
return "unknown"
}
let viewControllers = navigationController.viewControllers
let viewControllersCount = viewControllers.count
if viewControllersCount == 1 {
return "search_tab"
}
let penultimateViewController = viewControllers[viewControllersCount - 2]
if let searchSourceProviding = penultimateViewController as? EventLoggingSearchSourceProviding {
return searchSourceProviding.searchSource
}
return "unknown"
}
}
// Keep
// WMFLocalizedStringWithDefaultValue(@"search-did-you-mean", nil, nil, @"Did you mean %1$@?", @"Button text for searching for an alternate spelling of the search term. Parameters:\n* %1$@ - alternate spelling of the search term the user entered - ie if user types 'thunk' the API can suggest the alternate term 'think'")
| mit | 6d9261c8be5da427738531ee838e24a0 | 40.20297 | 410 | 0.675117 | 5.682522 | false | false | false | false |
coach-plus/ios | CoachPlus/ui/NavigationBar.swift | 1 | 5622 | //
// NavigationBar.swift
// CoachPlus
//
// Created by Maurice Breit on 13.04.17.
// Copyright © 2017 Mathandoro GbR. All rights reserved.
//
import Foundation
import NibDesignable
import SwiftIcons
import MMDrawerController
protocol CoachPlusNavigationBarDelegate {
func profile(sender:UIBarButtonItem)
func userSettings(sender: UIBarButtonItem)
}
extension CoachPlusNavigationBarDelegate {
func profile(sender: UIBarButtonItem) {}
func userSettings(sender: UIBarButtonItem) {}
}
class CoachPlusNavigationBar: UINavigationBar, NibDesignableProtocol {
enum BarButtonType {
case none
case back
case done
case cancel
case teams
case selectedTeam
case profile
case userSettings
}
var team:Team?
var teamSelectionV:TeamSelectionView?
var coachPlusNavigationBarDelegate:CoachPlusNavigationBarDelegate?
var leftBarButtonType:BarButtonType = .none
var rightBarButtonType:BarButtonType = .none
override init (frame : CGRect) {
super.init(frame : frame)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
func setup() {
self.setStyling()
}
private func createBarButton(type:BarButtonType) -> UIBarButtonItem? {
var btn:UIBarButtonItem?
switch type {
case .back:
btn = self.createDoneBarButton()
case .done:
btn = self.createDoneBarButton()
case .selectedTeam:
btn = self.createTeamSelectionBarButton()
case .teams:
btn = self.createTeamsBarButton()
case .profile:
btn = self.createProfileBarButton()
case .userSettings:
btn = self.createUserSettingsBarButton()
case .cancel:
btn = self.createCancelBarButton()
default:
break
}
return btn
}
func setRightBarButton(item: UINavigationItem) {
let btn = self.createBarButton(type: self.rightBarButtonType)
guard btn != nil else {
return
}
item.setRightBarButton(btn, animated: true)
}
func setLeftBarButton(item: UINavigationItem) {
let btn = self.createBarButton(type: self.leftBarButtonType)
guard btn != nil else {
return
}
item.setLeftBarButton(btn, animated: true)
}
func createDoneBarButton() -> UIBarButtonItem {
return UIBarButtonItem(title: L10n.done, style: .plain, target: self, action: #selector(done(sender:)))
}
func createCancelBarButton() -> UIBarButtonItem {
return UIBarButtonItem(title: L10n.cancel, style: .plain, target: self, action: #selector(cancel(sender:)))
}
func createProfileBarButton() -> UIBarButtonItem {
let btn = UIBarButtonItem(title: "", style: .plain, target: self, action: #selector(profile(sender:)))
btn.setCoachPlusIcon(fontType: .fontAwesomeSolid(.user), color: .white)
return btn
}
func createUserSettingsBarButton() -> UIBarButtonItem {
let btn = UIBarButtonItem(title: "", style: .plain, target: self, action: #selector(userSettings(sender:)))
btn.setCoachPlusIcon(fontType: .fontAwesomeSolid(.cogs), color: .white)
return btn
}
func createBackBarButton() -> UIBarButtonItem {
return UIBarButtonItem(title: L10n.back, style: .plain, target: self, action: #selector(back(sender:)))
}
func createTeamSelectionBarButton() -> UIBarButtonItem {
self.teamSelectionV = TeamSelectionView(frame: CGRect(x: 0, y: 0, width: 100, height: 25))
self.teamSelectionV?.setup(team: team)
let bbi = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
bbi.customView = self.teamSelectionV
return bbi
}
func createTeamsBarButton() -> UIBarButtonItem {
let btn = UIBarButtonItem(title: L10n.teams, style: .plain, target: self, action: #selector(openSlider(sender:)))
btn.setCoachPlusIcon(fontType: .fontAwesomeSolid(.tshirt), color: .white)
return btn
}
func setStyling() {
self.barTintColor = UIColor(hexString: "#3381b8")
self.tintColor = UIColor.white
self.titleTextAttributes = [
NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.font : UIFont(name: "Roboto-BoldItalic", size: 14)
]
}
@objc func openSlider(sender:UIBarButtonItem) {
FlowManager.openDrawer()
}
@objc func done(sender:UIBarButtonItem) {
let controller = UIApplication.shared.keyWindow?.rootViewController
controller?.dismiss(animated: true, completion: nil)
}
@objc func cancel(sender:UIBarButtonItem) {
let controller = UIApplication.shared.keyWindow?.rootViewController
controller?.dismiss(animated: true, completion: nil)
}
@objc func back(sender:UIBarButtonItem) {
let controller = UIApplication.shared.keyWindow?.rootViewController
controller?.navigationController?.popViewController(animated: true)
}
@objc func profile(sender:UIBarButtonItem) {
self.coachPlusNavigationBarDelegate?.profile(sender: sender)
}
@objc func userSettings(sender: UIBarButtonItem) {
self.coachPlusNavigationBarDelegate?.userSettings(sender: sender)
}
}
| mit | 05d93372ebbc0acae45012322c9c7c83 | 30.578652 | 121 | 0.638854 | 4.837349 | false | false | false | false |
digipost/ios | Digipost/POSInvoice+Methods.swift | 1 | 1885 | //
// Copyright (C) Posten Norge AS
//
// 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
extension POSInvoice {
func titleForInvoiceButtonLabel(_ isSending: Bool) -> String {
var title : String? = nil
if isSending {
title = NSLocalizedString("LETTER_VIEW_CONTROLLER_INVOICE_BUTTON_SENDING_TITLE", comment:"Sending...");
} else if (timePaid as Date? != nil) {
title = NSLocalizedString("LETTER_VIEW_CONTROLLER_INVOICE_BUTTON_PAID_TITLE", comment:"Sent to bank");
} else if (canBePaidByUser.boolValue) {
if (sendToBankUri as NSString? != nil) {
title = NSLocalizedString("LETTER_VIEW_CONTROLLER_INVOICE_BUTTON_SEND_TITLE", comment:"Send to bank");
} else {
if InvoiceBankAgreement.hasAnyActiveAgreements() {
title = NSLocalizedString("LETTER_VIEW_CONTROLLER_INVOICE_POPUP_STATUS_AGREEMENT_TYPE_2_UNPROCESSED_POPUP_TITLE", comment:"Klar til betaling");
}else{
title = NSLocalizedString("LETTER_VIEW_CONTROLLER_INVOICE_BUTTON_PAYMENT_TIPS_TITLE", comment:"Payment tips");
}
}
}else {
title = NSLocalizedString("LETTER_VIEW_CONTROLLER_INVOICE_BUTTON_PAYMENT_TIPS_TITLE", comment:"Payment tips");
}
return title!
}
}
| apache-2.0 | bfed5c0d872fbf0dfed475e0617dd8dd | 42.837209 | 163 | 0.653581 | 4.264706 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.