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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PureSwift/SwiftGL | Sources/UnitTests/Matrix4Tests.swift | 2 | 1111 | //
// Matrix4Tests.swift
// Kronos
//
// Created by Alsey Coleman Miller on 1/21/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
#if os(iOS) || os(tvOS)
import GLKit
#endif
import XCTest
import Kronos
final class Matrix4Tests: XCTestCase {
func testSize() {
XCTAssert(sizeof(Matrix4) == (sizeof(Float) * 16))
}
func testMultiply() {
let matrix1 = Matrix4((1,0,1,0), (0.5,0,0.5, 0), (0.5,0.0 ,0.5, 0), (1,0,1,0))
let matrix2 = Matrix4((0.5, 0, 0.5, 0), (1,0,1,0), (0.5,0.0 ,0.5, 0), (1,0,1,0))
let result = matrix1 * matrix2
let expectedResult = Matrix4((0.75, 0, 0.75, 0), (1.5, 0, 1.5, 0), (0.75, 0, 0.75, 0), (1.5, 0, 1.5, 0))
#if os(iOS) || os(tvOS)
do {
let glkResult = GLKMatrix4Multiply(matrix1.toUIKit(), matrix2.toUIKit())
XCTAssert(Matrix4(glkResult) == result)
}
#endif
XCTAssert(result == expectedResult)
}
} | mit | fec411b6359e91ea6fdcdf9878ba96db | 23.152174 | 112 | 0.48018 | 3.162393 | false | true | false | false |
nlgb/Weibo | Weibo/Weibo/Classes/Main/MainViewController.swift | 1 | 8106 | //
// MainViewController.swift
// Weibo
//
// Created by sw on 16/6/6.
// Copyright © 2016年 sw. All rights reserved.
//
import UIKit
class MainViewController: UITabBarController {
// MARK: 生命周期方法
override func viewDidLoad() {
super.viewDidLoad()
// 添加所有子控制器
addChildViewControllers()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// 初始化加号按钮
setupComposeBtn()
}
// MARK: 初始化加号按钮
private func setupComposeBtn() {
// 把加号按钮添加到tabBar上
tabBar.addSubview(composeButton)
// 设置宽度
// let width = tabBar.itemWidth
let width = tabBar.bounds.width / CGFloat(childViewControllers.count)
// 设置高度
let height = tabBar.frame.size.height
// 修改frame
let rect = CGRect(origin:CGPointZero, size:CGSize(width:width, height:height))
composeButton.frame = CGRectOffset(rect, 2 * width, 0)
}
// MARK: 添加所有子控制器
private func addChildViewControllers() {
/*
// addChildViewController(HomeTableViewController(), image: "tabbar_home", highLightImage: "tabbar_home_highlighted", title: "首页")
// addChildViewController(MessageTableViewController(), image: "tabbar_message_center", highLightImage: "tabbar_message_center_highlighted", title: "消息")
// addChildViewController(DiscoverTableViewController(), image: "tabbar_discover", highLightImage: "tabbar_discover_highlighted", title: "发现")
// addChildViewController(ProfileTableViewController(), image: "tabbar_profile", highLightImage: "tabbar_profile_highlighted", title: "我")
*/
let path = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil)!
let data = NSData.init(contentsOfFile: path)!
do{
let dicArr = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
for dic in dicArr as! [[String:AnyObject]]
{
addChildViewController(dic["vcName"] as? String, image: dic["imageName"] as? String, highLightImage: (dic["imageName"] as? String)! + "_highlighted", title: dic["title"] as? String)
}
} catch{
addChildViewController("HomeTableViewController", image: "tabbar_home", highLightImage: "tabbar_home_highlighted", title: "首页")
addChildViewController("MessageTableViewController", image: "tabbar_message_center", highLightImage: "tabbar_message_center_highlighted", title: "消息")
addChildViewController("NullViewController", image: "", highLightImage: "", title: "")
addChildViewController("DiscoverTableViewController", image: "tabbar_discover", highLightImage: "tabbar_discover_highlighted", title: "发现")
addChildViewController("ProfileTableViewController", image: "tabbar_profile", highLightImage: "tabbar_profile_highlighted", title: "我")
}
}
// MARK: 创建子控制器
private func addChildViewController(childControllerName: String?, image: String?, highLightImage: String?, title:String?) {
let nameSpace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"]
// 可选绑定
guard let ns = nameSpace as? String else {
WSLog("命名空间不存在")
return
}
//if let ns = nameSpace as? String {
guard let vcName = childControllerName else {
WSLog("控制器名称不能为nil")
return
}
let cls : AnyClass? = NSClassFromString(ns + "." + vcName)
// AnyClass本质是AnyObject.Type类型
// UIViewController本质是UIViewController.Type类型
// 将AnyClass转为UIViewController类型
// 类型绑定:如果是这个类型,那么就执行{}内部代码,否则不执行
// 不安全:let clsType = cls as! UIViewController.Type 直接将结果强转成UIViewController类型
guard let clsType = cls as? UIViewController.Type else {
WSLog("传入的字符串不能到最UIViewController来使用")
return
}
// if let clsType = cls as? UIViewController.Type {
let childController = clsType.init()
WSLog(childController)
// 如果是在iOS8以前,只有文字有效果,而图片没效果
tabBar.tintColor = UIColor.orangeColor()
// 控制器选项卡属性
guard let iName = image else {
return
}
childController.tabBarItem.image = UIImage(named: iName)
guard let highIName = highLightImage else {
return
}
childController.tabBarItem.selectedImage = UIImage(named: highIName)
guard let titleName = title else {
return
}
childController.title = titleName
// 包装导航控制器
let nav = UINavigationController(rootViewController: childController)
// 添加子控制器
addChildViewController(nav)
// }
// }
}
// MARK: 懒加载发布按钮
private lazy var composeButton: UIButton = {
var btn = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
btn.addTarget(self, action: Selector("composeBtnClick"), forControlEvents: UIControlEvents.TouchUpInside)
return btn
/*
var btn = UIButton.create("tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
btn.addTarget(self, action: Selector("composeBtnClick"), forControlEvents: UIControlEvents.TouchUpInside)
return btn
*/
/*
var btn = UIButton()
// 1.设置背景图片
btn.setBackgroundImage(UIImage.init(named: "tabbar_compose_button"), forState: UIControlState.Normal)
btn.setBackgroundImage(UIImage.init(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
// 2.设置前景图片
btn.setImage(UIImage.init(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
btn.setImage(UIImage.init(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
// 3.监听按钮点击
btn.addTarget(self, action: Selector("composeBtnClick"), forControlEvents: UIControlEvents.TouchUpInside)
return btn
*/
}()
//MARK: 监听按钮点击
// 注意: 由于点击事件是由NSRunLoop发起的, 并不是当前类发起的, 所以如果在点击方法前面加上private, 那么NSRunLoop无法找到该方法
// OC是基于运行时动态派发事件的, 而Swift是编译时就已经确定了方法
// 如果想给监听点击的方法加上private, 并且又想让系统动态派发时能找到这个方法, 那么可以在前面加上@objc, @objc就能让这个方法支持动态派发
@objc private func composeBtnClick() {
WSLog("点击了写作按钮")
}
// // MARK: 内部控制方法
// func addChildViewController(childController:UIViewController, image: String, highLightImage: String, title:String) {
// // 如果是在iOS8以前,只有文字有效果,而图片没效果
// tabBar.tintColor = UIColor.orangeColor()
// // 控制器选项卡属性
// childController.tabBarItem.image = UIImage(named: image)
// childController.tabBarItem.selectedImage = UIImage(named: highLightImage)
// childController.title = title
// // childController.tabBarItem.title = title;
// // childController.navigationItem.title = title;
// // 包装导航控制器
// let nav = UINavigationController(rootViewController: childController)
// // 添加子控制器
// addChildViewController(nav)
// }
}
| mit | abe437c21141920b1e240293ffd5e9f2 | 40.787356 | 197 | 0.640765 | 4.746084 | false | false | false | false |
CrazyTalkEntertainment/CTEAnimatedHamburgerView | AnimatedHamburgerTestAppTests/CALayer+AnimationsTest.swift | 1 | 2836 | //
// CALayer+AnimationsTest.swift
// AnimatedHamburgerTestApp
//
// Created by CrazyTalk Entertainment on 2014-11-14.
// Copyright (c) 2014 CrazyTalk Entertainment. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import XCTest
class CALayerAnimationsTests: XCTestCase {
let sut = CALayer()
func testAddRotationalAnimation()
{
sut.addRotationalAnimation(CGFloat(M_PI), calculationMode: nil, keyTimes: nil)
XCTAssertNotNil(sut.animationForKey("transform"), "animation was not added to layer")
}
func testAddPositionAnimation()
{
sut.addPositionAnimation(CGPoint(x: 0, y: 0), toPoint: CGPoint(x: 0, y: 100), controlPoint: CGPoint(x: 50, y: 50))
XCTAssertNotNil(sut.animationForKey("position"), "animation was not added to layer")
}
func testRotationValuesFromTransform()
{
let keyFrames = sut.rotationValuesFromTransform(CGFloat(M_PI), frames: 4)
XCTAssert(keyFrames.count == 4, "incorrect number of key frames were created")
}
//MARK: performance tests
func testPerformanceAddRotationalAnimation()
{
self.measureBlock() {
self.sut.addRotationalAnimation(CGFloat(M_PI), calculationMode: nil, keyTimes: nil)
}
}
func testPerformanceAddPositionAnimation()
{
self.measureBlock() {
self.sut.addPositionAnimation(CGPoint(x: 0, y: 0), toPoint: CGPoint(x: 0, y: 100), controlPoint: CGPoint(x: 50, y: 50))
}
}
func testPerformanceRotationValuesFromTransform()
{
self.measureBlock() {
let keyFrames = self.sut.rotationValuesFromTransform(CGFloat(M_PI), frames: 4)
}
}
}
| mit | 8e9e531ba6449ee9bc8b44e415ba32b3 | 32.761905 | 131 | 0.685472 | 4.459119 | false | true | false | false |
joshjeong/twitter | Twitter/Twitter/TweetTableViewCell.swift | 1 | 5271 | //
// TweetTableViewCell.swift
// Twitter
//
// Created by Josh Jeong on 4/17/17.
// Copyright © 2017 JoshJeong. All rights reserved.
//
import UIKit
class TweetTableViewCell: UITableViewCell {
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var tweetTextLabel: UILabel!
@IBOutlet weak var retweetCountLabel: UILabel!
@IBOutlet weak var favoritesCountLabel: UILabel!
@IBOutlet weak var retweetButton: UIButton!
@IBOutlet weak var favoriteButton: UIButton!
var isFavorited = false
var isRetweeted = false
var tweet: Tweet! {
didSet {
if let avatarImageUrl = tweet.profileImageThumbnail {
avatarImageView.setImageWith(avatarImageUrl)
}
if let name = tweet.name {
nameLabel.text = name
}
if let username = tweet.username {
usernameLabel.text = "@\(username)"
}
if let timeAgo = tweet.timeAgo {
timeLabel.text = timeAgo
}
if let tweetText = tweet.text {
tweetTextLabel.text = tweetText
}
if let retweetCount = tweet.retweetCount {
retweetCountLabel.text = "\(retweetCount)"
}
if let favoritesCount = tweet.favoritesCount {
favoritesCountLabel.text = "\(favoritesCount)"
}
if let favorited = tweet.favorited {
isFavorited = favorited
if favorited {
favoriteButton.imageView?.image = #imageLiteral(resourceName: "active-like-button")
}
}
if let retweeted = tweet.retweeted {
isRetweeted = retweeted
if retweeted {
retweetButton.imageView?.image = #imageLiteral(resourceName: "active-retweet-button")
}
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func onRetweet(_ sender: Any) {
if let id = tweet.id {
if isRetweeted {
TwitterClient.sharedInstance?.unfavorite(tweetId: id, success: {
self.isRetweeted = false
self.toggleFavoriteButton(isFavorite: false)
}, failure: { (error) in
})
} else {
TwitterClient.sharedInstance?.favorite(tweetId: id, success: {
self.isRetweeted = true
self.toggleFavoriteButton(isFavorite: true)
}, failure: { (error) in
})
}
}
}
@IBAction func onFavoriteTweet(_ sender: Any) {
if let id = tweet.id {
if isFavorited {
TwitterClient.sharedInstance?.unfavorite(tweetId: id, success: {
self.isFavorited = false
self.toggleFavoriteButton(isFavorite: false)
}, failure: { (error) in
})
} else {
TwitterClient.sharedInstance?.favorite(tweetId: id, success: {
self.isFavorited = true
self.toggleFavoriteButton(isFavorite: true)
}, failure: { (error) in
})
}
}
}
func toggleFavoriteButton(isFavorite: Bool) {
var currentFavoriteValue = Int(favoritesCountLabel.text!) ?? 0
if isFavorite {
favoriteButton.imageView?.image = #imageLiteral(resourceName: "active-like-button")
currentFavoriteValue = currentFavoriteValue + 1
} else {
favoriteButton.imageView?.image = #imageLiteral(resourceName: "like-button")
currentFavoriteValue = currentFavoriteValue - 1
}
favoritesCountLabel.text = "\(currentFavoriteValue)"
}
func toggleRetweetButton(isRetweeted: Bool) {
var currentRetweetValue = Int(retweetCountLabel.text!) ?? 0
if isRetweeted {
retweetButton.imageView?.image = #imageLiteral(resourceName: "active-like-button")
currentRetweetValue = currentRetweetValue + 1
} else {
retweetButton.imageView?.image = #imageLiteral(resourceName: "like-button")
currentRetweetValue = currentRetweetValue - 1
}
retweetCountLabel.text = "\(currentRetweetValue)"
}
@IBAction func onReplyButton(_ sender: Any) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "didTapRetweet"), object: nil, userInfo: ["tweet": tweet])
}
}
| mit | 6850c3c72edd79a660f24d19fc06e5e6 | 31.134146 | 134 | 0.53814 | 5.803965 | false | false | false | false |
lp1994428/TextKitch | TextKitchen/TextKitchen/classes/Ingredients/Main/View/IngreRecommendVIew.swift | 1 | 8230 | //
// IngreRecommendVIew.swift
// TextKitchen
//
// Created by 罗平 on 2016/10/25.
// Copyright © 2016年 罗平. All rights reserved.
//
import UIKit
//定义食材首页widget列表的类型
public enum IngreWidgetType:Int32{
case GuessYourLike = 1//猜你喜欢
case redPacket = 2
case Today = 5
case Scene = 3
case Talent = 4
case Post = 8
case SceneList = 9
}
class IngreRecommendVIew: UIView {
var jumpClosure :(String -> Void)?
var model :IngreRecommendModel?{
didSet{
tbView?.reloadData()
}
}
private var tbView:UITableView?
override init(frame: CGRect) {
super.init(frame: frame)
tbView = UITableView(frame: CGRectZero, style: .Plain)
tbView?.delegate = self
tbView?.dataSource = self
addSubview(tbView!)
//约束
tbView?.snp_makeConstraints(closure: { (make) in
make.edges.equalTo(self)
})
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension IngreRecommendVIew:UITableViewDelegate,UITableViewDataSource{
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
//banner广告显示的一个分组
var section = 1
if model?.data?.widgetList?.count > 0 {
section += (model?.data?.widgetList?.count)!
}
return section
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var row = 0
if section == 0{
row = 1
}else{
let listModel = model?.data?.widgetList![section-1]
if listModel?.widget_type?.intValue == IngreWidgetType.GuessYourLike.rawValue || listModel?.widget_type?.intValue == IngreWidgetType.redPacket.rawValue || listModel?.widget_type?.intValue == IngreWidgetType.Today.rawValue || listModel?.widget_type?.intValue == IngreWidgetType.Scene.rawValue || listModel?.widget_type?.intValue == IngreWidgetType.SceneList.rawValue||listModel?.widget_type?.intValue == IngreWidgetType.Post.rawValue{
row = 1
}else if listModel?.widget_type?.intValue == IngreWidgetType.Talent.rawValue{
row = (listModel?.widget_data?.count)! / 4
}
}
return row
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var height:CGFloat = 0
if indexPath.section == 0{
height = 140
}else{
//红包和猜你喜欢的入口
let listModel = model?.data?.widgetList![indexPath.section-1]
if listModel?.widget_type?.intValue == IngreWidgetType.GuessYourLike.rawValue {
height = 70
}else if listModel?.widget_type?.intValue == IngreWidgetType.redPacket.rawValue{
height = 75
}else if listModel?.widget_type?.intValue == IngreWidgetType.Today.rawValue{
height = 280
}else if listModel?.widget_type?.intValue == IngreWidgetType.Scene.rawValue{
height = 200
}else if listModel?.widget_type?.intValue == IngreWidgetType.SceneList.rawValue{
height = 70
}else if listModel?.widget_type?.intValue == IngreWidgetType.Talent.rawValue{
height = 80
}else if listModel?.widget_type?.intValue == IngreWidgetType.Post.rawValue{
height = 180
}
}
return height
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0{
//广告
let cell = IngreBannerTableViewCell.createBannerCell(tableView, atIndexPath: indexPath, bannerArray: model?.data!.banner)
cell.jumpClosure = self.jumpClosure
return cell
}else{
//猜你喜欢
let listModel = model?.data?.widgetList![indexPath.section-1]
if listModel?.widget_type?.intValue == IngreWidgetType.GuessYourLike.rawValue{
let cell = IngreLikeCell.createLikeCellFor(tableView, atIndexPath: indexPath, listModel: listModel)
cell.jumpClosure = jumpClosure
return cell
}else if listModel?.widget_type?.intValue == IngreWidgetType.redPacket.rawValue{
let cell = IngrePacketCell.createRedPacketCellFor(tableView, index: indexPath, listModel: listModel!)
cell.jumpClosure = jumpClosure
return cell
}else if listModel?.widget_type?.intValue == IngreWidgetType.Today.rawValue{
let cell = IngreTodayCell.createTodayCellFor(tableView, atIndexPath: indexPath, listModel: listModel)
cell.jumpClosure = jumpClosure
return cell
}else if listModel?.widget_type?.intValue == IngreWidgetType.Scene.rawValue{
let cell = IngreSceneCell.createSceneCell(tableView, index: indexPath, listModel: listModel)
cell.jumpClosure = jumpClosure
return cell
}else if listModel?.widget_type?.intValue == IngreWidgetType.SceneList.rawValue{
let cell = IngreSceneLsitCell.createSceneList(tableView, index: indexPath, listModel: listModel)
cell.jumpClosure = jumpClosure
return cell
}else if listModel?.widget_type?.intValue == IngreWidgetType.Talent.rawValue{
//获取子数组
let range = NSMakeRange(indexPath.row * 4, 4)
let array = NSArray(array:(listModel?.widget_data)!).subarrayWithRange(range) as! Array<IngreaRecommendWidgeData>
let cell = IngreTainetCell.createCell(tableView, index: indexPath, listModel: array)
cell.jumpClosure = jumpClosure
return cell
}else if listModel?.widget_type?.intValue == IngreWidgetType.Post.rawValue{
let cell = IngrePostCell.createCell(tableView, index: indexPath, model: listModel!)
cell.jump = jumpClosure
return cell
}
}
return UITableViewCell()
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section > 0{
let listModel = model?.data?.widgetList![section-1]
if listModel?.widget_type?.intValue == IngreWidgetType.GuessYourLike.rawValue {
let likeHeaderView = IngreLikeHeaderView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 44))
return likeHeaderView
}
else if listModel?.widget_type?.intValue == IngreWidgetType.Today.rawValue || listModel?.widget_type?.intValue == IngreWidgetType.Scene.rawValue || listModel?.widget_type?.intValue == IngreWidgetType.Talent.rawValue||listModel?.widget_type?.intValue == IngreWidgetType.Post.rawValue{
//今日新品
let headerView = IngreHeaderView(frame:CGRectMake(0,0,lpScreenWd,54))
headerView.jumClosure = jumpClosure
headerView.listModel = listModel
return headerView
}
}
return nil
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
var height :CGFloat = 0
if section > 0 {
let listModel = model?.data?.widgetList![section-1]
if listModel?.widget_type?.intValue == IngreWidgetType.GuessYourLike.rawValue {
height = 44
return height
} else if listModel?.widget_type?.intValue == IngreWidgetType.Today.rawValue || listModel?.widget_type?.intValue == IngreWidgetType.Scene.rawValue || listModel?.widget_type?.intValue == IngreWidgetType.Talent.rawValue || listModel?.widget_type?.intValue == IngreWidgetType.Post.rawValue{
return 54
}
}
return height
}
} | mit | a74d503e90d98a207c3ac6de9e0b6c9f | 44.351955 | 445 | 0.611063 | 5.223295 | false | false | false | false |
huangboju/Moots | Examples/UIScrollViewDemo/UIScrollViewDemo/CompanyCard/Views/MemberAlert/MemberComponentAlertView.swift | 1 | 3596 | //
// MemberComponentAlertView.swift
// UIScrollViewDemo
//
// Created by 黄伯驹 on 2017/11/13.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
class MemberComponentAlertView: UIView {
private let formView: FormView = {
let formView = FormView()
formView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0.1))
formView.separatorStyle = .none
formView.isScrollEnabled = false
formView.allowsSelection = false
formView.backgroundColor = .white
formView.layer.cornerRadius = 8
return formView
}()
private lazy var coRightsFrameView: CoRightsFrameView = {
let coRightsFrameView = CoRightsFrameView()
return coRightsFrameView
}()
private lazy var closeButton: UIButton = {
let closeButton = HZUIHelper.generateNormalButton(imageName: "ic_btn_close", target: self, action: #selector(closeAction))
closeButton.frame = CGRect(x: self.frame.width - 78, y: 85, width: 25, height: 25)
closeButton.layer.cornerRadius = closeButton.frame.height / 2
closeButton.layer.borderWidth = 1
closeButton.layer.borderColor = UIColor.white.cgColor
return closeButton
}()
static let size = UIScreen.main.bounds.size
override init(frame: CGRect) {
super.init(frame: CGRect(x: 0, y: -type(of: self).size.height, width: type(of: self).size.width, height: 0))
let topMargin: CGFloat = 136
let maxY = closeButton.frame.maxY
let height = topMargin - maxY
let vLine = CALayer(frame: CGRect(x: closeButton.center.x - 0.5, y: closeButton.frame.maxY, width: 1, height: height))
vLine.backgroundColor = UIColor.white.cgColor
layer.addSublayer(vLine)
addSubview(closeButton)
addSubview(formView)
formView.snp.makeConstraints { (make) in
make.width.equalTo(294)
make.height.equalTo(400)
make.centerX.equalToSuperview()
make.top.equalTo(topMargin)
}
}
func show() {
let buttonItem = MemberComponentBtnItem(
isShowDescLabel: true,
buttonTitle: "立即激活",
buttonTarget: target,
buttonAction: #selector(MemberAlertViewController.testAction)
)
guard superview == nil else {
return
}
formView.rows = [
[
Row<MemberAlertTitleCell>(viewData: NoneItem()),
Row<MemberComponentFrameCell>(viewData: NoneItem()),
Row<MemberComponentBtnCell>(viewData: buttonItem)
]
]
UIApplication.shared.keyWindow?.addSubview(self)
UIView.animate(withDuration: 0.4, delay: 0, options: .curveEaseOut, animations: {
self.frame.origin.y = 0
self.frame.size.height = type(of: self).size.height
}, completion: { _ in
self.backgroundColor = UIColor(white: 0, alpha: 0.6)
})
}
func dissmiss() {
UIView.animate(withDuration: 0.4, animations: {
self.backgroundColor = .clear
self.subviews.forEach { $0.removeFromSuperview() }
self.layer.sublayers?.forEach { $0.removeFromSuperlayer() }
}, completion: { _ in
self.removeFromSuperview()
})
}
@objc
private func closeAction() {
dissmiss()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 4779cc334c3f3b004027999ac98ba517 | 32.083333 | 130 | 0.604534 | 4.545802 | false | false | false | false |
catloafsoft/AudioKit | AudioKit/Common/Nodes/Playback/Phase-Locked Vocoder/AKPhaseLockedVocoder.swift | 1 | 9117 | //
// AKPhaseLockedVocoder.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// This is a phase locked vocoder. It has the ability to play back an audio
/// file loaded into an ftable like a sampler would. Unlike a typical sampler,
/// mincer allows time and pitch to be controlled separately.
///
/// - parameter audioFileURL: Location of the audio file to use.
/// - parameter position: Position in time. When non-changing it will do a spectral freeze of a the current point in time.
/// - parameter amplitude: Amplitude.
/// - parameter pitchRatio: Pitch ratio. A value of. 1 normal, 2 is double speed, 0.5 is halfspeed, etc.
///
public class AKPhaseLockedVocoder: AKNode {
// MARK: - Properties
internal var internalAU: AKPhaseLockedVocoderAudioUnit?
internal var token: AUParameterObserverToken?
private var positionParameter: AUParameter?
private var amplitudeParameter: AUParameter?
private var pitchRatioParameter: AUParameter?
/// Position in time. When non-changing it will do a spectral freeze of a the current point in time.
public var position: Double = 0 {
willSet(newValue) {
if position != newValue {
positionParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Amplitude.
public var amplitude: Double = 1 {
willSet(newValue) {
if amplitude != newValue {
amplitudeParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Pitch ratio. A value of. 1 normal, 2 is double speed, 0.5 is halfspeed, etc.
public var pitchRatio: Double = 1 {
willSet(newValue) {
if pitchRatio != newValue {
pitchRatioParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
private var audioFileURL: CFURL
// MARK: - Initialization
/// Initialize this Phase-Locked Vocoder node
///
/// - parameter audioFileURL: Location of the audio file to use.
/// - parameter position: Position in time. When non-changing it will do a spectral freeze of a the current point in time.
/// - parameter amplitude: Amplitude.
/// - parameter pitchRatio: Pitch ratio. A value of. 1 normal, 2 is double speed, 0.5 is halfspeed, etc.
///
public init(
audioFileURL: NSURL,
position: Double = 0,
amplitude: Double = 1,
pitchRatio: Double = 1) {
self.position = position
self.amplitude = amplitude
self.pitchRatio = pitchRatio
self.audioFileURL = audioFileURL
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Generator
description.componentSubType = 0x6d696e63 /*'minc'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKPhaseLockedVocoderAudioUnit.self,
asComponentDescription: description,
name: "Local AKPhaseLockedVocoder",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitGenerator = avAudioUnit else { return }
self.avAudioNode = avAudioUnitGenerator
self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKPhaseLockedVocoderAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
}
guard let tree = internalAU?.parameterTree else { return }
positionParameter = tree.valueForKey("position") as? AUParameter
amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter
pitchRatioParameter = tree.valueForKey("pitchRatio") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.positionParameter!.address {
self.position = Double(value)
} else if address == self.amplitudeParameter!.address {
self.amplitude = Double(value)
} else if address == self.pitchRatioParameter!.address {
self.pitchRatio = Double(value)
}
}
}
positionParameter?.setValue(Float(position), originator: token!)
amplitudeParameter?.setValue(Float(amplitude), originator: token!)
pitchRatioParameter?.setValue(Float(pitchRatio), originator: token!)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
public func start() {
Exit: do {
var err: OSStatus = noErr
var theFileLengthInFrames: Int64 = 0
var theFileFormat: AudioStreamBasicDescription = AudioStreamBasicDescription()
var thePropertySize: UInt32 = UInt32(strideofValue(theFileFormat))
var extRef: ExtAudioFileRef = nil
var theData: UnsafeMutablePointer<CChar> = nil
var theOutputFormat: AudioStreamBasicDescription = AudioStreamBasicDescription()
err = ExtAudioFileOpenURL(self.audioFileURL, &extRef)
if err != 0 { print("ExtAudioFileOpenURL FAILED, Error = \(err)"); break Exit }
// Get the audio data format
err = ExtAudioFileGetProperty(extRef, kExtAudioFileProperty_FileDataFormat, &thePropertySize, &theFileFormat)
if err != 0 { print("ExtAudioFileGetProperty(kExtAudioFileProperty_FileDataFormat) FAILED, Error = \(err)"); break Exit }
if theFileFormat.mChannelsPerFrame > 2 { print("Unsupported Format, channel count is greater than stereo"); break Exit }
theOutputFormat.mSampleRate = AKSettings.sampleRate
theOutputFormat.mFormatID = kAudioFormatLinearPCM
theOutputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat
theOutputFormat.mBitsPerChannel = UInt32(strideof(Float)) * 8
theOutputFormat.mChannelsPerFrame = 1; // Mono
theOutputFormat.mBytesPerFrame = theOutputFormat.mChannelsPerFrame * UInt32(strideof(Float))
theOutputFormat.mFramesPerPacket = 1
theOutputFormat.mBytesPerPacket = theOutputFormat.mFramesPerPacket * theOutputFormat.mBytesPerFrame
// Set the desired client (output) data format
err = ExtAudioFileSetProperty(extRef, kExtAudioFileProperty_ClientDataFormat, UInt32(strideofValue(theOutputFormat)), &theOutputFormat)
if err != 0 { print("ExtAudioFileSetProperty(kExtAudioFileProperty_ClientDataFormat) FAILED, Error = \(err)"); break Exit }
// Get the total frame count
thePropertySize = UInt32(strideofValue(theFileLengthInFrames))
err = ExtAudioFileGetProperty(extRef, kExtAudioFileProperty_FileLengthFrames, &thePropertySize, &theFileLengthInFrames)
if err != 0 { print("ExtAudioFileGetProperty(kExtAudioFileProperty_FileLengthFrames) FAILED, Error = \(err)"); break Exit }
// Read all the data into memory
let dataSize = UInt32(theFileLengthInFrames) * theOutputFormat.mBytesPerFrame
theData = UnsafeMutablePointer.alloc(Int(dataSize))
if theData != nil {
var theDataBuffer: AudioBufferList = AudioBufferList()
theDataBuffer.mNumberBuffers = 1
theDataBuffer.mBuffers.mDataByteSize = dataSize
theDataBuffer.mBuffers.mNumberChannels = theOutputFormat.mChannelsPerFrame
theDataBuffer.mBuffers.mData = UnsafeMutablePointer(theData)
// Read the data into an AudioBufferList
var ioNumberFrames: UInt32 = UInt32(theFileLengthInFrames)
err = ExtAudioFileRead(extRef, &ioNumberFrames, &theDataBuffer)
if err == noErr {
// success
let data=UnsafeMutablePointer<Float>(theDataBuffer.mBuffers.mData)
internalAU?.setupAudioFileTable(data, size: ioNumberFrames)
internalAU!.start()
} else {
// failure
theData.dealloc(Int(dataSize))
theData = nil // make sure to return NULL
print("Error = \(err)"); break Exit;
}
}
}
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
internalAU!.stop()
}
}
| mit | daaae423d43ff9425f8fcc30c0953064 | 43.91133 | 147 | 0.632993 | 5.795931 | false | false | false | false |
czechboy0/Buildasaur | BuildaKitTests/SyncPair_PR_Bot_Tests.swift | 2 | 7522 | //
// SyncPair_PR_Bot_Tests.swift
// Buildasaur
//
// Created by Honza Dvorsky on 17/05/2015.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import XCTest
import BuildaUtils
import BuildaGitServer
import XcodeServerSDK
import BuildaKit
//for tuples, XCTAssert... doesn't work for them
func XCTBAssertNil<T>(@autoclosure expression: () -> T?, message: String = "Must be nil",
file: StaticString = #file, line: UInt = #line) {
XCTAssert(expression() == nil, message, file:file, line:line);
}
func XCTBAssertNotNil<T>(@autoclosure expression: () -> T?, message: String = "Must not be nil",
file: StaticString = #file, line: UInt = #line) {
XCTAssert(expression() != nil, message, file:file, line:line);
}
class SyncPair_PR_Bot_Tests: XCTestCase {
func mockedPRAndBotAndCommit() -> (PullRequestType, Bot, String, BuildStatusCreator) {
let pr: PullRequestType = MockPullRequest(number: 1, title: "Awesomified The Engine")
let bot = MockBot(name: "BuildaBot [me/Repo] PR #1")
let commit = pr.headCommitSHA
let buildStatusCreator = MockBuildStatusCreator()
return (pr, bot, commit, buildStatusCreator)
}
func testNoIntegrationsYet() {
let (pr, bot, commit, statusCreator) = self.mockedPRAndBotAndCommit()
let integrations = [Integration]()
let actions = SyncPairPRResolver().resolveActionsForCommitAndIssueWithBotIntegrations(commit, issue: pr, bot: bot, hostname: "localhost", buildStatusCreator: statusCreator, integrations: integrations)
XCTAssertEqual(actions.integrationsToCancel?.count ?? 0, 0)
XCTBAssertNil(actions.statusToSet)
XCTAssertNotNil(actions.startNewIntegrationBot)
}
func testFirstIntegrationPending() throws {
let (pr, bot, commit, statusCreator) = self.mockedPRAndBotAndCommit()
let integrations = [
try MockIntegration(number: 1, step: Integration.Step.Pending)
]
let actions = SyncPairPRResolver().resolveActionsForCommitAndIssueWithBotIntegrations(commit, issue: pr, bot: bot, hostname: "localhost", buildStatusCreator: statusCreator, integrations: integrations)
XCTAssertEqual(actions.integrationsToCancel?.count ?? 0, 0)
XCTAssertNil(actions.startNewIntegrationBot)
XCTBAssertNotNil(actions.statusToSet)
XCTAssertEqual(actions.statusToSet!.status.status.state, BuildState.Pending)
}
func testMultipleIntegrationsPending() throws {
let (pr, bot, commit, statusCreator) = self.mockedPRAndBotAndCommit()
let integrations = [
try MockIntegration(number: 1, step: Integration.Step.Pending),
try MockIntegration(number: 2, step: Integration.Step.Pending),
try MockIntegration(number: 3, step: Integration.Step.Pending)
]
let actions = SyncPairPRResolver().resolveActionsForCommitAndIssueWithBotIntegrations(commit, issue: pr, bot: bot, hostname: "localhost", buildStatusCreator: statusCreator, integrations: integrations)
//should cancel all except for the last one
let toCancel = Set(actions.integrationsToCancel!)
XCTAssertEqual(toCancel.count, 2)
XCTAssertTrue(toCancel.contains(integrations[0]))
XCTAssertTrue(toCancel.contains(integrations[1]))
XCTAssertNil(actions.startNewIntegrationBot)
XCTBAssertNotNil(actions.statusToSet)
XCTAssertEqual(actions.statusToSet!.status.status.state, BuildState.Pending)
}
func testOneIntegrationRunning() throws {
let (pr, bot, commit, statusCreator) = self.mockedPRAndBotAndCommit()
let integrations = [
try MockIntegration(number: 1, step: Integration.Step.Building),
]
let actions = SyncPairPRResolver().resolveActionsForCommitAndIssueWithBotIntegrations(commit, issue: pr, bot: bot, hostname: "localhost", buildStatusCreator: statusCreator, integrations: integrations)
XCTAssertEqual(actions.integrationsToCancel!.count, 0)
XCTAssertNil(actions.startNewIntegrationBot)
XCTBAssertNotNil(actions.statusToSet)
XCTAssertEqual(actions.statusToSet!.status.status.state, BuildState.Pending)
}
func testOneIntegrationTestsFailed() throws {
let (pr, bot, commit, statusCreator) = self.mockedPRAndBotAndCommit()
let integrations = [
try MockIntegration(number: 1, step: Integration.Step.Completed, sha: "head_sha", result: Integration.Result.TestFailures)
]
let actions = SyncPairPRResolver().resolveActionsForCommitAndIssueWithBotIntegrations(commit, issue: pr, bot: bot, hostname: "localhost", buildStatusCreator: statusCreator, integrations: integrations)
XCTAssertEqual(actions.integrationsToCancel!.count, 0)
XCTAssertNil(actions.startNewIntegrationBot)
XCTBAssertNotNil(actions.statusToSet)
XCTAssertEqual(actions.statusToSet!.status.status.state, BuildState.Failure)
}
func testOneIntegrationSuccess() throws {
let (pr, bot, commit, statusCreator) = self.mockedPRAndBotAndCommit()
let integrations = [
try MockIntegration(number: 1, step: Integration.Step.Completed, sha: "head_sha", result: Integration.Result.Succeeded)
]
let actions = SyncPairPRResolver().resolveActionsForCommitAndIssueWithBotIntegrations(commit, issue: pr, bot: bot, hostname: "localhost", buildStatusCreator: statusCreator, integrations: integrations)
XCTAssertEqual(actions.integrationsToCancel!.count, 0)
XCTAssertNil(actions.startNewIntegrationBot)
XCTBAssertNotNil(actions.statusToSet)
XCTAssertEqual(actions.statusToSet!.status.status.state, BuildState.Success)
}
func testTwoIntegrationOneRunningOnePending() throws {
let (pr, bot, commit, statusCreator) = self.mockedPRAndBotAndCommit()
let integrations = [
try MockIntegration(number: 1, step: Integration.Step.Building, sha: "head_sha"),
try MockIntegration(number: 2, step: Integration.Step.Pending, sha: "head_sha")
]
let actions = SyncPairPRResolver().resolveActionsForCommitAndIssueWithBotIntegrations(commit, issue: pr, bot: bot, hostname: "localhost", buildStatusCreator: statusCreator, integrations: integrations)
XCTAssertEqual(actions.integrationsToCancel!.count, 1)
XCTAssertNil(actions.startNewIntegrationBot)
XCTBAssertNotNil(actions.statusToSet)
XCTAssertEqual(actions.statusToSet!.status.status.state, BuildState.Pending)
}
func testTwoIntegrationsDifferentCommits() throws {
let (pr, bot, commit, statusCreator) = self.mockedPRAndBotAndCommit()
let integrations = [
try MockIntegration(number: 1, step: Integration.Step.Building, sha: "old_head_sha"),
]
let actions = SyncPairPRResolver().resolveActionsForCommitAndIssueWithBotIntegrations(commit, issue: pr, bot: bot, hostname: "localhost", buildStatusCreator: statusCreator, integrations: integrations)
XCTAssertEqual(actions.integrationsToCancel!.count, 1)
XCTAssertNotNil(actions.startNewIntegrationBot)
XCTBAssertNil(actions.statusToSet) //no change
}
//TODO: add more complicated cases
}
| mit | a8c3ff663b276d5e39b090e3a32ad49f | 45.432099 | 208 | 0.69649 | 5.365193 | false | true | false | false |
adamnemecek/AudioKit | Sources/AudioKit/MIDI/MIDIFile/MIDIFile.swift | 1 | 2973 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
#if !os(tvOS)
import Foundation
/// MIDI File
public struct MIDIFile {
/// File name
public var filename: String
var chunks: [MIDIFileChunk] = []
var headerChunk: MIDIFileHeaderChunk? {
return chunks.first(where: { $0.isHeader }) as? MIDIFileHeaderChunk
}
/// Array of track chunks
public var trackChunks: [MIDIFileTrackChunk] {
return Array(chunks.drop(while: { $0.isHeader && $0.isValid })) as? [MIDIFileTrackChunk] ?? []
}
/// Optional tempo track
public var tempoTrack: MIDIFileTempoTrack? {
if format == 1, let tempoTrackChunk = trackChunks.first {
return MIDIFileTempoTrack(trackChunk: tempoTrackChunk)
}
return nil
}
/// Array of MIDI File tracks
public var tracks: [MIDIFileTrack] {
var tracks = trackChunks
if format == 1 {
tracks = Array(tracks.dropFirst()) // drop tempo track
}
return tracks.compactMap({ MIDIFileTrack(chunk: $0) })
}
/// Format integer
public var format: Int {
return headerChunk?.format ?? 0
}
/// Track count
public var trackCount: Int {
return headerChunk?.trackCount ?? 0
}
/// MIDI Time format
public var timeFormat: MIDITimeFormat? {
return headerChunk?.timeFormat
}
/// Number of ticks per beat
public var ticksPerBeat: Int? {
return headerChunk?.ticksPerBeat
}
/// Number of frames per second
public var framesPerSecond: Int? {
return headerChunk?.framesPerSecond
}
/// Number of ticks per frame
public var ticksPerFrame: Int? {
return headerChunk?.ticksPerFrame
}
/// Time division to use
public var timeDivision: UInt16 {
return headerChunk?.timeDivision ?? 0
}
/// Initialize with a URL
/// - Parameter url: URL to MIDI File
public init(url: URL) {
filename = url.lastPathComponent
if let midiData = try? Data(contentsOf: url) {
let dataSize = midiData.count
var chunks = [MIDIFileChunk]()
var processedBytes = 0
while processedBytes < dataSize {
let data = Array(midiData.suffix(from: processedBytes))
if let headerChunk = MIDIFileHeaderChunk(data: data) {
chunks.append(headerChunk)
processedBytes += headerChunk.rawData.count
} else if let trackChunk = MIDIFileTrackChunk(data: data) {
chunks.append(trackChunk)
processedBytes += trackChunk.rawData.count
}
}
self.chunks = chunks
}
}
/// Initialize with a path
/// - Parameter path: Path to MIDI FIle
public init(path: String) {
self.init(url: URL(fileURLWithPath: path))
}
}
#endif
| mit | e082ee0ec8db50f4ff941d8ec00f248f | 27.314286 | 102 | 0.598385 | 4.674528 | false | false | false | false |
AdaptiveMe/adaptive-arp-darwin | adaptive-arp-rt/Source/Sources.Impl/DeviceDelegate.swift | 1 | 16222 | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:[email protected]>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:[email protected]>
* See source code files for contributors.
Release:
* @version v2.0.2
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
import AdaptiveArpApi
#if os(iOS)
import UIKit
#endif
#if os(OSX)
import Cocoa
#endif
/**
Interface for Managing the Device operations
Auto-generated implementation of IDevice specification.
*/
public class DeviceDelegate : BaseSystemDelegate, IDevice {
/// Logger variable
let logger : ILogging = AppRegistryBridge.sharedInstance.getLoggingBridge()
let loggerTag : String = "DeviceDelegate"
/// Variable that stores the device information
var deviceInfo:DeviceInfo?
/// Array of Listeners
var buttonListeners: [IButtonListener]!
var orientationListeners: [IDeviceOrientationListener]!
/**
Default Constructor.
*/
public override init() {
super.init()
#if os(iOS)
buttonListeners = [IButtonListener]()
orientationListeners = [IDeviceOrientationListener]()
let device: UIDevice = UIDevice.currentDevice()
deviceInfo = DeviceInfo(name: device.name, model: device.model, vendor: "Apple", uuid: "\(device.identifierForVendor)")
#endif
#if os(OSX)
// TODO: Hardware Model
let host: NSHost = NSHost.currentHost()
deviceInfo = DeviceInfo(name: host.name!, model: ""/*getSysValue("hw.model")*/, vendor: "Apple", uuid: NSUUID().UUIDString)
#endif
}
/**
Returns the device information for the current device executing the runtime.
@return DeviceInfo for the current device.
@since ARP1.0
*/
public func getDeviceInfo() -> DeviceInfo? {
logger.log(ILoggingLogLevel.Debug, category: loggerTag, message: "name: \(self.deviceInfo!.getName()), model: \(self.deviceInfo!.getModel()), vendor: \(self.deviceInfo!.getVendor()), uuid: \(self.deviceInfo!.getUuid())")
return self.deviceInfo!
}
/**
Gets the current Locale for the device.
@return The current Locale information.
@since ARP1.0
*/
public func getLocaleCurrent() -> Locale? {
// Gets the current locale of the device
let currentLocale: NSLocale = NSLocale.currentLocale()
let localeComponents: [NSObject : AnyObject] = NSLocale.componentsFromLocaleIdentifier(currentLocale.localeIdentifier)
let country: String = localeComponents[NSLocaleCountryCode] as! String
let language: String = localeComponents[NSLocaleLanguageCode] as! String
logger.log(ILoggingLogLevel.Debug, category: loggerTag, message: "Country=\(country)")
logger.log(ILoggingLogLevel.Debug, category: loggerTag, message: "Language=\(language)")
return Locale(language: language, country: country)
}
/**
Register a new listener that will receive button events.
@param listener to be registered.
@since ARP1.0
*/
public func addButtonListener(listener : IButtonListener) {
// TODO: fire the event of button clicked and iterate for every listener. Find where the fire event is located
#if os(iOS)
for list:IButtonListener in buttonListeners {
if list.getId() == listener.getId() {
// If the listener has alredy registered
logger.log(ILoggingLogLevel.Warn, category: loggerTag, message: "The listener \(listener) has alredy registered")
return
}
}
// Register the listener
buttonListeners.append(listener)
logger.log(ILoggingLogLevel.Debug, category: loggerTag, message: "Listener \(listener) registered")
#endif
#if os(OSX)
// in OSX there are no hardware buttons
logger.log(ILoggingLogLevel.Warn, category: loggerTag, message: "This device doesn't have support for this kind of listeners because there aren't hardware buttons")
#endif
}
/**
De-registers an existing listener from receiving button events.
@param listener to be removed.
@since ARP1.0
*/
public func removeButtonListener(listener : IButtonListener) {
#if os(iOS)
for (index, list) in buttonListeners.enumerate() {
if list.getId() == listener.getId() {
// Remove the listener
buttonListeners.removeAtIndex(index)
logger.log(ILoggingLogLevel.Debug, category: loggerTag, message: "The listener \(listener) it has been removed")
return
}
}
logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "Listener \(listener) is not registered in the system")
#endif
#if os(OSX)
// in OSX there are no hardware buttons
logger.log(ILoggingLogLevel.Warn, category: loggerTag, message: "This device doesn't have support for this kind of listeners because there aren't hardware buttons")
#endif
}
/**
Removed all existing listeners from receiving button events.
@since ARP1.0
*/
public func removeButtonListeners() {
#if os(iOS)
let listCount:Int = buttonListeners.count
// Remove all the listeners
buttonListeners.removeAll(keepCapacity: false)
logger.log(ILoggingLogLevel.Debug, category: loggerTag, message: "Removed \(listCount) buttonListeners from the system")
#endif
#if os(OSX)
// in OSX there are no hardware buttons
logger.log(ILoggingLogLevel.Warn, category: loggerTag, message: "This device doesn't have support for this kind of listeners because there aren't hardware buttons")
#endif
}
/**
Returns the current orientation of the device. Please note that this may be different from the orientation
of the display. For display orientation, use the IDisplay APIs.
@return The current orientation of the device.
@since v2.0.5
*/
public func getOrientationCurrent() -> ICapabilitiesOrientation? {
#if os(iOS)
switch UIDevice.currentDevice().orientation {
case UIDeviceOrientation.Portrait:
return ICapabilitiesOrientation.PortraitUp
case UIDeviceOrientation.PortraitUpsideDown:
return ICapabilitiesOrientation.PortraitDown
case UIDeviceOrientation.LandscapeLeft:
return ICapabilitiesOrientation.LandscapeLeft
case UIDeviceOrientation.LandscapeRight:
return ICapabilitiesOrientation.LandscapeRight
case UIDeviceOrientation.FaceUp, UIDeviceOrientation.FaceDown, UIDeviceOrientation.Unknown:
return ICapabilitiesOrientation.Unknown
}
#endif
#if os(OSX)
return ICapabilitiesOrientation.PortraitUp
#endif
}
/**
Add a listener to start receiving device orientation change events.
@param listener Listener to add to receive orientation change events.
@since v2.0.5
*/
public func addDeviceOrientationListener(listener : IDeviceOrientationListener) {
#if os(iOS)
// Check if the device is able to generate Device Notifications
if !UIDevice.currentDevice().generatesDeviceOrientationNotifications {
logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "This device is not able to generate rotation events")
return
}
for list:IDeviceOrientationListener in orientationListeners {
if list.getId() == listener.getId() {
// If the listener has alredy registered
logger.log(ILoggingLogLevel.Warn, category: loggerTag, message: "The listener \(listener) has alredy registered")
return
}
}
// If there is no listener enabled, add an observer
if orientationListeners.count == 0 {
UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications()
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "orientationEvent",
name:UIDeviceOrientationDidChangeNotification,
object:nil)
}
// Register the listener
orientationListeners.append(listener)
logger.log(ILoggingLogLevel.Debug, category: loggerTag, message: "Listener \(listener) registered")
#endif
#if os(OSX)
// in OSX there are no orientation events
logger.log(ILoggingLogLevel.Warn, category: loggerTag, message: "This device doesn't have support for this kind of listeners because there is no way to rotate this hardware, Unless you are Hulk 💪")
#endif
}
#if os(iOS)
/**
Function that handles an event of rotation on the device. Propagates every event to the listeners
*/
// fnva (23/04/2015) Swift 1.2 Annotation @objc to solve error Object X of class Y does not implement methodSignatureForSelector
@objc func orientationEvent() {
if orientationListeners.count == 0 {
logger.log(ILoggingLogLevel.Warn, category: loggerTag, message: "There are Notifications of UIDeviceOrientationDidChangeNotification but there no listener registered on the platfform.")
} else {
// MARK: There is no way to detect the rotation effect transition.
// There is only one event fired, when the device finishes the rotation
let event:RotationEvent = RotationEvent()
event.setOrigin(ICapabilitiesOrientation.Unknown)
event.setState(RotationEventState.DidFinishRotation)
event.setTimestamp(Int64(NSDate().timeIntervalSince1970*1000))
switch UIDevice.currentDevice().orientation {
case UIDeviceOrientation.Unknown, UIDeviceOrientation.FaceUp, UIDeviceOrientation.FaceDown:
event.setDestination(ICapabilitiesOrientation.Unknown)
case UIDeviceOrientation.Portrait:
event.setDestination(ICapabilitiesOrientation.PortraitUp)
case UIDeviceOrientation.PortraitUpsideDown:
event.setDestination(ICapabilitiesOrientation.PortraitDown)
case UIDeviceOrientation.LandscapeLeft:
event.setDestination(ICapabilitiesOrientation.LandscapeLeft)
case UIDeviceOrientation.LandscapeRight:
event.setDestination(ICapabilitiesOrientation.LandscapeRight)
}
// Iterate all over the registered listeners and send an event
for list in orientationListeners {
list.onResult(event)
}
}
}
#endif
/**
Remove a listener to stop receiving device orientation change events.
@param listener Listener to remove from receiving orientation change events.
@since v2.0.5
*/
public func removeDeviceOrientationListener(listener : IDeviceOrientationListener) {
#if os(iOS)
for (index, list) in orientationListeners.enumerate() {
if list.getId() == listener.getId() {
// Remove the listener
orientationListeners.removeAtIndex(index)
// If there is no listener enabled, remove the observer and the notifications
if orientationListeners.count == 0 {
NSNotificationCenter.defaultCenter().removeObserver(self)
UIDevice.currentDevice().endGeneratingDeviceOrientationNotifications()
}
logger.log(ILoggingLogLevel.Debug, category: loggerTag, message: "The listener \(listener) it has been removed")
return
}
}
logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "Listener \(listener) is not registered in the system")
#endif
#if os(OSX)
// in OSX there are no orientation events
logger.log(ILoggingLogLevel.Warn, category: loggerTag, message: "This device doesn't have support for this kind of listeners because there is no way to rotate this hardware, Unless you are Hulk 💪")
#endif
}
/**
Remove all listeners receiving device orientation events.
@since v2.0.5
*/
public func removeDeviceOrientationListeners() {
#if os(iOS)
let listCount:Int = orientationListeners.count
// Remove all the listeners
orientationListeners.removeAll(keepCapacity: false)
// Remove the observer and the notifications
NSNotificationCenter.defaultCenter().removeObserver(self)
UIDevice.currentDevice().endGeneratingDeviceOrientationNotifications()
logger.log(ILoggingLogLevel.Debug, category: loggerTag, message: "Removed \(listCount) orientationListeners from the system")
#endif
#if os(OSX)
// in OSX there are no orientation events
logger.log(ILoggingLogLevel.Warn, category: loggerTag, message: "This device doesn't have support for this kind of listeners because there is no way to rotate this hardware, Unless you are Hulk 💪")
#endif
}
/**
Returns a variable stored in the memory stack
:param: attr Attribute to query
:returns: The value of the attribute
:author: Ferran Vila Conesa
:since: ARP1.0
*/
/*private func getSysValue(attr: String) -> String {
var size : UInt = 0
sysctlbyname(attr, nil, &size, nil, 0)
var machine = [CChar](count: Int(size), repeatedValue: 0)
sysctlbyname(attr, &machine, &size, nil, 0)
return String.fromCString(machine)!
}*/
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
| apache-2.0 | be6aace80c6e61f95ce197b8e07fb79a | 37.143529 | 228 | 0.598236 | 5.814562 | false | false | false | false |
mseemann/healthkit-sample-generator | Pod/Classes/HealthKitStoreCleaner.swift | 1 | 2874 | //
// HealthKitStoreCleaner.swift
// Pods
//
// Created by Michael Seemann on 26.10.15.
//
//
import Foundation
import HealthKit
class HealthKitStoreCleaner {
let healthStore: HKHealthStore
init(healthStore: HKHealthStore){
self.healthStore = healthStore
}
/*
healthStore.deleteObjectsOfType results to
Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.healthd.server" UserInfo={NSDebugDescription=connection to service named com.apple.healthd.server
in the simulator -> query and delete with healthStore.deleteObjects works :(
*/
/**
Cleans all HealthKIt data from the healthkit store that are created by this app.
- Parameter onProgress: callback that informs about the cleaning progress
*/
func clean( onProgress: (message: String, progressInPercent: Double?)->Void){
let source = HKSource.defaultSource()
let predicate = HKQuery.predicateForObjectsFromSource(source)
let allTypes = HealthKitConstants.authorizationWriteTypes()
for type in allTypes {
let semaphore = dispatch_semaphore_create(0)
onProgress(message: "deleting \(type)", progressInPercent: nil)
let queryCountLimit = 1000
var result : (anchor:HKQueryAnchor?, count:Int?) = (anchor:nil, count: -1)
repeat {
let query = HKAnchoredObjectQuery(
type: type,
predicate: predicate,
anchor: result.anchor,
limit: queryCountLimit) {
(query, results, deleted, newAnchor, error) -> Void in
if results?.count > 0 {
self.healthStore.deleteObjects(results!){
(success:Bool, error:NSError?) -> Void in
if success {
print("deleted \(results?.count) from \(type)")
} else {
print("error deleting from \(type): \(error)")
}
dispatch_semaphore_signal(semaphore)
}
} else {
dispatch_semaphore_signal(semaphore)
}
result.anchor = newAnchor
result.count = results?.count
}
healthStore.executeQuery(query)
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
} while result.count != 0 || result.count==queryCountLimit
}
}
} | mit | a4e0fc1c8137d5487ddb025d39acccd8 | 34.9375 | 183 | 0.513222 | 5.9875 | false | false | false | false |
DaSens/StartupDisk | Pods/ProgressKit/InDeterminate/ShootingStars.swift | 1 | 2985 | //
// ShootingStars.swift
// ProgressKit
//
// Created by Kauntey Suryawanshi on 09/07/15.
// Copyright (c) 2015 Kauntey Suryawanshi. All rights reserved.
//
import Foundation
import Cocoa
@IBDesignable
open class ShootingStars: IndeterminateAnimation {
fileprivate let animationDuration = 1.0
var starLayer1 = CAShapeLayer()
var starLayer2 = CAShapeLayer()
var animation = CABasicAnimation(keyPath: "position.x")
var tempAnimation = CABasicAnimation(keyPath: "position.x")
override func notifyViewRedesigned() {
super.notifyViewRedesigned()
starLayer1.backgroundColor = foreground.cgColor
starLayer2.backgroundColor = foreground.cgColor
}
override func configureLayers() {
super.configureLayers()
let rect = self.bounds
let dimension = rect.height
let starWidth = dimension * 1.5
self.layer?.cornerRadius = 0
/// Add Stars
do {
starLayer1.position = CGPoint(x: dimension / 2, y: dimension / 2)
starLayer1.bounds.size = CGSize(width: starWidth, height: dimension)
starLayer1.backgroundColor = foreground.cgColor
self.layer?.addSublayer(starLayer1)
starLayer2.position = CGPoint(x: rect.midX, y: dimension / 2)
starLayer2.bounds.size = CGSize(width: starWidth, height: dimension)
starLayer2.backgroundColor = foreground.cgColor
self.layer?.addSublayer(starLayer2)
}
/// Add default animation
do {
animation.fromValue = -dimension
animation.toValue = rect.width * 0.9
animation.duration = animationDuration
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
animation.isRemovedOnCompletion = false
animation.repeatCount = Float.infinity
}
/** Temp animation will be removed after first animation
After finishing it will invoke animationDidStop and starLayer2 is also given default animation.
The purpose of temp animation is to generate an temporary offset
*/
tempAnimation.fromValue = rect.midX
tempAnimation.toValue = rect.width
tempAnimation.delegate = self
tempAnimation.duration = animationDuration / 2
tempAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
}
//MARK: Indeterminable protocol
override func startAnimation() {
starLayer1.add(animation, forKey: "default")
starLayer2.add(tempAnimation, forKey: "tempAnimation")
}
override func stopAnimation() {
starLayer1.removeAllAnimations()
starLayer2.removeAllAnimations()
}
}
extension ShootingStars: CAAnimationDelegate {
open func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
starLayer2.add(animation, forKey: "default")
}
}
| apache-2.0 | b4563d40cee5923550aafd5e829cc105 | 33.709302 | 107 | 0.663987 | 5.102564 | false | false | false | false |
sahandnayebaziz/Dana-Hills | Pods/RSBarcodes_Swift/Source/RSUnifiedCodeGenerator.swift | 1 | 4389 | //
// RSUnifiedCodeGenerator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/10/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import Foundation
import UIKit
import AVFoundation
open class RSUnifiedCodeGenerator: RSCodeGenerator {
open var isBuiltInCode128GeneratorSelected = false
open var fillColor: UIColor = UIColor.white
open var strokeColor: UIColor = UIColor.black
open class var shared: RSUnifiedCodeGenerator {
return UnifiedCodeGeneratorSharedInstance
}
// MARK: RSCodeGenerator
open func isValid(_ contents: String) -> Bool {
print("Use RSUnifiedCodeValidator.shared.isValid(contents:String, machineReadableCodeObjectType: String) instead")
return false
}
open func generateCode(_ contents: String, inputCorrectionLevel: InputCorrectionLevel, machineReadableCodeObjectType: String) -> UIImage? {
var codeGenerator: RSCodeGenerator?
switch machineReadableCodeObjectType {
case AVMetadataObject.ObjectType.qr.rawValue, AVMetadataObject.ObjectType.pdf417.rawValue, AVMetadataObject.ObjectType.aztec.rawValue:
return RSAbstractCodeGenerator.generateCode(contents, inputCorrectionLevel: inputCorrectionLevel, filterName: RSAbstractCodeGenerator.filterName(machineReadableCodeObjectType))
case AVMetadataObject.ObjectType.code39.rawValue:
codeGenerator = RSCode39Generator()
case AVMetadataObject.ObjectType.code39Mod43.rawValue:
codeGenerator = RSCode39Mod43Generator()
case AVMetadataObject.ObjectType.ean8.rawValue:
codeGenerator = RSEAN8Generator()
case AVMetadataObject.ObjectType.ean13.rawValue:
codeGenerator = RSEAN13Generator()
case AVMetadataObject.ObjectType.interleaved2of5.rawValue:
codeGenerator = RSITFGenerator()
case AVMetadataObject.ObjectType.itf14.rawValue:
codeGenerator = RSITF14Generator()
case AVMetadataObject.ObjectType.upce.rawValue:
codeGenerator = RSUPCEGenerator()
case AVMetadataObject.ObjectType.code93.rawValue:
codeGenerator = RSCode93Generator()
// iOS 8 included, but my implementation's performance is better :)
case AVMetadataObject.ObjectType.code128.rawValue:
if self.isBuiltInCode128GeneratorSelected {
return RSAbstractCodeGenerator.generateCode(contents, inputCorrectionLevel: inputCorrectionLevel, filterName: RSAbstractCodeGenerator.filterName(machineReadableCodeObjectType))
} else {
codeGenerator = RSCode128Generator()
}
case AVMetadataObject.ObjectType.dataMatrix.rawValue:
codeGenerator = RSCodeDataMatrixGenerator()
case RSBarcodesTypeISBN13Code:
codeGenerator = RSISBN13Generator()
case RSBarcodesTypeISSN13Code:
codeGenerator = RSISSN13Generator()
case RSBarcodesTypeExtendedCode39Code:
codeGenerator = RSExtendedCode39Generator()
default:
print("No code generator selected.")
}
if codeGenerator != nil {
codeGenerator!.fillColor = self.fillColor
codeGenerator!.strokeColor = self.strokeColor
return codeGenerator!.generateCode(contents, inputCorrectionLevel: inputCorrectionLevel, machineReadableCodeObjectType: machineReadableCodeObjectType)
} else {
return nil
}
}
open func generateCode(_ contents: String, machineReadableCodeObjectType: String) -> UIImage? {
return self.generateCode(contents, inputCorrectionLevel: .Medium, machineReadableCodeObjectType: machineReadableCodeObjectType)
}
open func generateCode(_ machineReadableCodeObject: AVMetadataMachineReadableCodeObject, inputCorrectionLevel: InputCorrectionLevel) -> UIImage? {
return self.generateCode(machineReadableCodeObject.stringValue!, inputCorrectionLevel: inputCorrectionLevel, machineReadableCodeObjectType: machineReadableCodeObject.type.rawValue)
}
open func generateCode(_ machineReadableCodeObject: AVMetadataMachineReadableCodeObject) -> UIImage? {
return self.generateCode(machineReadableCodeObject, inputCorrectionLevel: .Medium)
}
}
let UnifiedCodeGeneratorSharedInstance = RSUnifiedCodeGenerator()
| mit | 83e7f22b4793553ac82732449245d27d | 46.706522 | 192 | 0.727501 | 6.315108 | false | false | false | false |
rhcad/SwiftGraphics | SwiftGraphics/RegularPolygon.swift | 4 | 4057 | //
// RegularPolygon.swift
// SwiftGraphics
//
// Created by Zhang Yungui on on 15/1/23.
// Copyright (c) 2015 schwa.io. All rights reserved.
//
import CoreGraphics
import SwiftUtilities
// MARK: Regular Polygon
public struct RegularPolygon {
public let nside:Int
public let center:CGPoint
public let vertex:CGPoint
public var radius:CGFloat { return center.distanceTo(vertex) }
public var startAngle:CGFloat { return (vertex - center).direction }
public init(nside:Int, center:CGPoint, vertex:CGPoint) {
self.nside = nside
self.center = center
self.vertex = vertex
}
public init(nside:Int, center:CGPoint, radius:CGFloat) {
self.init(nside:nside, center:center, vertex: center + CGPoint(x:radius))
}
public init(nside:Int, center:CGPoint, radius:CGFloat, startAngle:CGFloat) {
self.init(nside:nside, center:center, vertex: center.polarPoint(startAngle, radius:radius))
}
}
public extension RegularPolygon {
public var isDegenerate: Bool { return nside < 3 || center ==% vertex }
public var centralAngle:CGFloat { return CGFloat(2 * M_PI / Double(nside)) }
public var interiorAngle:CGFloat { return CGFloat(Double(nside - 2) * M_PI / Double(nside)) }
public var exteriorAngle:CGFloat { return centralAngle }
public var area: CGFloat { return CGFloat(radius ** 2 * sin(centralAngle) * CGFloat(nside) / 2) }
public var length:CGFloat { return sideLength * CGFloat(nside) }
public var sideLength:CGFloat { return CGFloat(2 * radius * sin(centralAngle / 2)) }
public var inradius:CGFloat { return radius * cos(centralAngle / 2) }
public var circumRadius:CGFloat { return radius }
public var circumcircle: Circle { return Circle(center:center, radius:radius) }
public var incircle: Circle { return Circle(center:center, radius:inradius) }
public var points:[CGPoint] {
let s = startAngle, c = centralAngle, r = radius
return (0..<nside).map { self.center.polarPoint(s + c * CGFloat($0), radius:r) }
}
public func getPoint(index:Int) -> CGPoint {
return center.polarPoint(startAngle + centralAngle * CGFloat(index), radius:radius)
}
}
// MARK: Applying transform
public func * (lhs:RegularPolygon, rhs:CGAffineTransform) -> RegularPolygon {
return RegularPolygon(nside:lhs.nside, center:lhs.center * rhs, vertex:lhs.vertex * rhs)
}
// MARK: Convenience initializers
public extension RegularPolygon {
//! Construct with center and two adjacent vertexes.
// The adjacent vertex is approximately on the ray from center to the first vertex.
public init(center:CGPoint, vertex:CGPoint, adjacent:CGPoint) {
let angle = (adjacent - center).angleTo(vertex - center)
let nside = (angle == 0) ? 3 : max(3, Int(round(CGFloat(M_PI) / angle)))
self.init(nside:nside, center:center, vertex:vertex)
}
}
// MARK: Move vertexes
public extension RegularPolygon {
//! Returns new polygon whose vertex moved to the specified location.
public func pointMoved(v:(Int, CGPoint)) -> RegularPolygon {
if v.0 >= 0 && v.0 < nside {
let angle = (v.1 - center).direction - centralAngle * CGFloat(v.0)
return RegularPolygon(nside:nside, center:center, radius:radius, startAngle:angle)
}
return self * CGAffineTransform(translation:v.1 - center)
}
//! Returns new polygon whose two adjacent vertexes moved to the specified locations.
public func twoPointsMoved(v1:(Int, CGPoint), _ v2:(Int, CGPoint)) -> RegularPolygon {
func isBeside(i1:Int, i2:Int) -> Bool {
return i1 >= 0 && i1 < i2 && i2 < self.nside && (i1 == i2 - 1 || (i1 == 0 && i2 == self.nside - 1))
}
if isBeside(min(v1.0, v2.0), i2: max(v1.0, v2.0)) && v1.1 !=% v2.1 {
let xf = CGAffineTransform(from1:getPoint(v1.0), from2:getPoint(v2.0), to1:v1.1, to2:v2.1)
return self * xf
}
return self
}
}
| bsd-2-clause | 9b08090472a549043b56dcb587adb84a | 36.564815 | 111 | 0.654917 | 3.845498 | false | false | false | false |
MichaelRow/MusicPlayer | Sources/Player/Vox/Vox.swift | 1 | 2421 | //
// Vox.swift
// MusicPlayer
//
// Created by Michael Row on 2017/8/31.
//
import Foundation
import ScriptingBridge
import VoxBridge
class Vox {
weak var delegate: MusicPlayerDelegate?
var voxPlayer: VoxApplication
var currentTrack: MusicTrack?
var rememberedTrackStateDate = Date()
var currentPlaybackState = MusicPlaybackState.stopped
fileprivate(set) var hashValue: Int
required init?() {
guard let player = SBApplication(bundleIdentifier: MusicPlayerName.vox.bundleID) else { return nil }
voxPlayer = player
hashValue = Int(arc4random())
currentPlaybackState = playbackState
}
deinit {
stopPlayerTracking()
}
// MARK: - Player Event Handle
func playbackStateCheckEvent() {
switch playbackState {
case .stopped:
stoppedEvent()
case .paused:
pauseEvent()
case .playing:
playingEvent()
default:
break
}
}
func pauseEvent() {
guard currentPlaybackState != .paused else { return }
currentPlaybackState = .paused
delegate?.player(self, playbackStateChanged: .paused, atPosition: playerPosition)
}
func stoppedEvent() {
PlayerTimer.shared.unregister(self)
guard currentPlaybackState != .stopped else { return }
currentPlaybackState = .stopped
delegate?.playerDidQuit(self)
}
func playingEvent() {
let voxPosition = playerPosition
if currentPlaybackState != .playing {
currentPlaybackState = .playing
delegate?.player(self, playbackStateChanged: .playing, atPosition: voxPosition)
}
repositionCheckEvent()
}
// MARK: - Notification Events
@objc func playerInfoChanged(_ notification: Notification) {
musicTrackCheckEvent()
startPeriodTimerObserving()
}
// MARK: - Timer Events
func startPeriodTimerObserving() {
// start timer
let event = PlayerTimer.Event(kind: .Infinite, precision: MusicPlayerConfig.TimerInterval) { time in
self.playbackStateCheckEvent()
}
PlayerTimer.shared.register(self, event: event)
// write down the track start time
rememberedTrackStateDate = trackStartDate
}
}
| gpl-3.0 | 2a8842175c65534e83aca8fe67ead67a | 24.484211 | 108 | 0.615448 | 5.368071 | false | false | false | false |
macmade/AtomicKit | AtomicKit/Source/DispatchedBool.swift | 1 | 4511 | /*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2017 Jean-David Gadina - www.xs-labs.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
/**
* Thread-safe value wrapper for `Bool`, using dispatch queues to achieve
* synchronization.
* This class is KVO-compliant. You may observe its `value` property to be
* notified of changes. This is applicable to Cocoa bindings.
*
* - seealso: DispatchedValueWrapper
*/
@objc public class DispatchedBool: NSObject, DispatchedValueWrapper
{
/**
* The wrapped value type, `Bool`.
*/
public typealias ValueType = Bool
/**
* Initializes a dispatched value object.
* This initializer will use the main queue for synchronization.
*
* - parameter value: The initial `Bool` value.
*/
public required convenience init( value: ValueType )
{
self.init( value: value, queue: DispatchQueue.main )
}
/**
* Initializes a dispatched value object.
*
* - parameter value: The initial `Bool` value.
* - parameter queue: The queue to use to achieve synchronization.
*/
public required init( value: ValueType = false, queue: DispatchQueue = DispatchQueue.main )
{
self._value = DispatchedValue< ValueType >( value: value, queue: queue )
}
/**
* The wrapped `Bool` value.
* This property is KVO-compliant.
*/
@objc public dynamic var value: ValueType
{
get
{
return self._value.get()
}
set( value )
{
self.willChangeValue( forKey: "value" )
self._value.set( value )
self.didChangeValue( forKey: "value" )
}
}
/**
* Atomically gets the wrapped `Bool` value.
* The getter will be executed on the queue specified in the initialzer.
*
* - returns: The actual `Bool` value.
*/
public func get() -> ValueType
{
return self.value
}
/**
* Atomically sets the wrapped `Bool` value.
* The setter will be executed on the queue specified in the initialzer.
*
* -parameter value: The `Bool` value to set.
*/
public func set( _ value: ValueType )
{
self.value = value
}
/**
* Atomically executes a closure on the wrapped `Bool` value.
* The closure will be passed the actual value of the wrapped `Bool` value,
* and is guaranteed to be executed atomically, on the queue specified in
* the initialzer.
*
* -parameter closure: The close to execute.
*/
public func execute( closure: ( ValueType ) -> Swift.Void )
{
self._value.execute( closure: closure )
}
/**
* Atomically executes a closure on the wrapped `Bool` value, returning some
* value.
* The closure will be passed the actual value of the wrapped `Bool` value,
* and is guaranteed to be executed atomically, on the queue specified in
* the initialzer.
*
* -parameter closure: The close to execute, returning some value.
*/
public func execute< R >( closure: ( ValueType ) -> R ) -> R
{
return self._value.execute( closure: closure )
}
private var _value: DispatchedValue< ValueType >
}
| mit | 53f93152b4b72ad809550eac286520c0 | 32.917293 | 95 | 0.618488 | 4.708768 | false | false | false | false |
LawrenceHan/iOS-project-playground | Swift_Algorithm/Swift_Algorithm/MathHelper.swift | 1 | 444 | //
// GreatestCommonDivisor.swift
// Swift_algorithm
//
// Created by Hanguang on 15/10/2016.
// Copyright © 2016 Hanguang. All rights reserved.
//
import Foundation
public func gcd(_ m: Int, _ n: Int) -> Int {
var a = 0
var b = max(m, n)
var r = min(m, n)
while r != 0 {
a = b
b = r
r = a % b
}
return b
}
public func lcm(_ m: Int, _ n: Int) -> Int {
return m * n / gcd(m, n)
}
| mit | 680339efccec063f4cc216097317925e | 16.038462 | 51 | 0.510158 | 2.933775 | false | false | false | false |
devgabrielcoman/woodhouse | Pod/Classes/Services/Locu/LocuSearch.swift | 1 | 2258 | //
// LocuService.swift
// Pods
//
// Created by Gabriel Coman on 23/02/2016.
//
//
import UIKit
import Alamofire
import Dollar
import KeyPathTransformer
public class LocuSearch: NSObject, ServiceProtocol {
private var qry: String = ""
private var lat: Float = 0
private var lng: Float = 0
private var rad: Float = 0
private var dataService: DataService = DataService()
public override init() {
super.init()
dataService.serviceDelegate = self
dataService.authDelgate = LocuAuth.sharedInstance
}
func apiurl() -> String {
return "https://api.locu.com/v2/venue/search/"
}
func method() -> String {
return "POST"
}
func query() -> [String : AnyObject]? {
return nil
}
func header() -> [String : AnyObject]? {
return nil
}
func body() -> [String : AnyObject]? {
return [
"fields": ["name", "location", "contact", "categories", "open_hours", "delivery", "extended", /*"menus"*/],
"venue_queries":[[
"name": qry.urlEncode(),
"location":[
"geo":[
"$in_lat_lng_radius":[lat, lng, rad]
]
]
]]
]
}
func process(JSON: AnyObject) -> AnyObject {
if let JSON = JSON as? [String:AnyObject],
let venues = JSON["venues"] {
return venues
}
return [:]
}
public func search(query qry: String?, latitude lat: Float?, longitude lng: Float?, radius rad: Float?) {
if let qry = qry, lat = lat, lng = lng, rad = rad {
self.qry = qry; self.lat = lat; self.lng = lng; self.rad = rad
}
dataService.execute() { result in
print(result)
print(">>>>><<<<<<<<<>>>>>>>>>><<<<<<<")
print(">>>>><<<<<<<<<>>>>>>>>>><<<<<<<")
if let venues = result as? [[String:AnyObject]] {
$.each(venues) { (venue: [String:AnyObject]) in
print(mapLocuToOMenu(venue))
print("#######################")
}
}
}
}
} | gpl-3.0 | fefd6f556911506300f8340884d64b80 | 25.892857 | 119 | 0.471213 | 4.498008 | false | false | false | false |
donmccaughey/Lunch | LunchKit/LunchKit/Contact.swift | 1 | 1348 | //
// Contact.swift
// LunchKit
//
// Created by Don McCaughey on 4/25/16.
// Copyright © 2016 Don McCaughey. All rights reserved.
//
import Foundation
public class Contact {
public let phone: String
public let formattedPhone: String
public var url: NSURL? {
return NSURL(string: "tel:\(phone)")
}
init(phone: String, formattedPhone: String) {
self.phone = phone
self.formattedPhone = formattedPhone
}
convenience init?(fromFoursquareJSONDictionary dictionary: [String : AnyObject]) {
guard
let phone = dictionary["phone"] as? String,
let formattedPhone = dictionary["formattedPhone"] as? String
else {
return nil
}
self.init(phone: phone, formattedPhone: formattedPhone)
}
convenience init?(fromPlistDictionary dictionary: [String : AnyObject]) {
guard
let phone = dictionary["phone"] as? String,
let formattedPhone = dictionary["formattedPhone"] as? String
else {
return nil
}
self.init(phone: phone, formattedPhone: formattedPhone)
}
func asPlistDictionary() -> [String:AnyObject] {
return [
"phone": phone,
"formattedPhone": formattedPhone,
]
}
}
| bsd-2-clause | 3abe368463e2d034b677848b0c75dc49 | 25.411765 | 86 | 0.587231 | 4.880435 | false | false | false | false |
troystribling/BlueCap | BlueCapKit/External/FutureLocation/BeaconManager.swift | 1 | 4386 | //
// BeaconManager.swift
// BlueCap
//
// Created by Troy Stribling on 8/22/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import Foundation
import CoreLocation
// MARK - FLBeaconManager -
public class BeaconManager : RegionManager {
// MARK: Properties
fileprivate var regionRangingStatus = [String : Bool]()
internal var configuredBeaconRegions = [String : BeaconRegion]()
public fileprivate(set) var isRanging = false
public func isRangingAvailable() -> Bool {
return CLLocationManager.isRangingAvailable()
}
public var beaconRegions: [BeaconRegion] {
return Array(self.configuredBeaconRegions.values)
}
public func beaconRegion(identifier: String) -> BeaconRegion? {
return self.configuredBeaconRegions[identifier]
}
//MARK: Initialize
public convenience init() {
self.init(clLocationManager: CLLocationManager())
}
public override init(clLocationManager: CLLocationManagerInjectable) {
super.init(clLocationManager: clLocationManager)
}
// MARK: Control
public func isRangingRegion(identifier:String) -> Bool {
return self.regionRangingStatus[identifier] ?? false
}
public func startRangingBeacons(in beaconRegion: BeaconRegion, authorization: CLAuthorizationStatus = .authorizedWhenInUse, capacity: Int = Int.max, context: ExecutionContext = QueueContext.main) -> FutureStream<[Beacon]> {
Logger.debug("region identifier `\(beaconRegion.identifier)`")
let authorizationFuture = self.authorize(authorization, context: context)
authorizationFuture.onFailure { _ in self.updateIsRanging(false) }
return authorizationFuture.flatMap(capacity: capacity, context: context) {status in
Logger.debug("authorization status: \(status)")
self.updateIsRanging(true)
self.configuredBeaconRegions[beaconRegion.identifier] = beaconRegion
self.clLocationManager.startRangingBeacons(in: beaconRegion.clBeaconRegion)
return beaconRegion.beaconPromise.stream
}
}
public func stopRangingBeacons(in beaconRegion: BeaconRegion) {
Logger.debug("region identifier `\(beaconRegion.identifier)`")
self.configuredBeaconRegions.removeValue(forKey: beaconRegion.identifier)
self.regionRangingStatus.removeValue(forKey: beaconRegion.identifier)
self.updateIsRanging(false)
self.clLocationManager.stopRangingBeacons(in: beaconRegion.clBeaconRegion)
}
public func stopRangingAllBeacons() {
for beaconRegion in self.beaconRegions {
self.stopRangingBeacons(in: beaconRegion)
}
}
// MARK: CLLocationManagerDelegate
@objc public func locationManager(_: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) {
self.didRange(beacons: beacons.map { $0 as CLBeaconInjectable }, inRegion: region)
}
@objc public func locationManager(_: CLLocationManager, rangingBeaconsDidFailForRegion region: CLBeaconRegion, withError error: Error) {
self.rangingBeaconsDidFail(inRegion: region, withError: error)
}
public func didRange(beacons: [CLBeaconInjectable], inRegion region: CLBeaconRegion) {
Logger.debug("ranged \(beacons.count) beacons, in region with identifier \(region.identifier)")
if let beaconRegion = self.configuredBeaconRegions[region.identifier] {
self.regionRangingStatus[beaconRegion.identifier] = true
let flBeacons = beacons.map { Beacon(clBeacon:$0) }
beaconRegion._beacons = flBeacons
beaconRegion.beaconPromise.success(flBeacons)
}
}
public func rangingBeaconsDidFail(inRegion region: CLBeaconRegion, withError error: Error) {
Logger.debug("region identifier \(region.identifier)")
self.regionRangingStatus[region.identifier] = false
self.configuredBeaconRegions[region.identifier]?.beaconPromise.failure(error)
}
// MARK: Utilies
func updateIsRanging(_ value: Bool) {
let regionCount = Array(self.regionRangingStatus.values).filter{$0}.count
if value {
self.isRanging = true
} else {
if regionCount == 0 {
self.isRanging = false
}
}
}
}
| mit | 3a7fd93bad42fd07296e1d64f98548e2 | 36.487179 | 227 | 0.693342 | 5.322816 | false | true | false | false |
Brightify/ReactantUI | Sources/Tokenizer/Properties/Types/EnumPropertyType.swift | 1 | 1238 | //
// EnumPropertyType.swift
// ReactantUIGenerator
//
// Created by Matouš Hýbl on 09/03/2018.
//
import Foundation
public protocol EnumPropertyType: RawRepresentable, SupportedPropertyType, CaseIterable {
static var enumName: String { get }
}
extension EnumPropertyType where Self.RawValue == String {
public func generate(context: SupportedPropertyTypeContext) -> String {
return "\(Self.enumName).\(rawValue)"
}
public static var xsdType: XSDType {
let values = Set(Self.allCases.map { $0.rawValue })
return .enumeration(EnumerationXSDType(name: Self.enumName, base: .string, values: values))
}
}
extension EnumPropertyType {
public static var runtimeType: String {
return enumName
}
}
extension SupportedPropertyType where Self: RawRepresentable, Self.RawValue == String {
#if SanAndreas
public func dematerialize(context: SupportedPropertyTypeContext) -> String {
return rawValue
}
#endif
public static func materialize(from value: String) throws -> Self {
guard let materialized = Self(rawValue: value) else {
throw PropertyMaterializationError.unknownValue(value)
}
return materialized
}
}
| mit | 3d1bf564462544a0422dc4f4b63d7c9d | 27.090909 | 99 | 0.696602 | 4.866142 | false | false | false | false |
silt-lang/silt | Sources/SyntaxGen/Token.swift | 1 | 633 | /// Token.swift
///
/// Copyright 2017-2018, The Silt Language Project.
///
/// This project is released under the MIT license, a copy of which is
/// available in the repository.
struct Token {
enum Kind {
case associated(String)
case keyword(String)
case punctuation(String)
}
let caseName: String
let name: String
let kind: Kind
init(name: String, _ kind: Kind) {
self.kind = kind
self.name = name
var caseName = name.replacingOccurrences(of: "Token", with: "")
.lowercaseFirstLetter
if case .keyword(_) = kind {
caseName += "Keyword"
}
self.caseName = caseName
}
}
| mit | 129d89b6225d52e75c2b942046c4baf2 | 21.607143 | 70 | 0.64455 | 3.95625 | false | false | false | false |
crazypoo/PTools | PooToolsSource/Core/PTMarcos_swift.swift | 1 | 3332 | //
// PTMarcos_swift.swift
// Diou
//
// Created by ken lam on 2021/10/19.
// Copyright © 2021 DO. All rights reserved.
//
import UIKit
import DeviceKit
public let AppWindows = UIApplication.shared.delegate?.window!
public let Gobal_device_isSimulator = Device.current.isSimulator
public let Gobal_device_info = Device.current
public let Gobal_group_of_all_iPad:[Device] = Device.allPads
public let Gobal_group_of_all_plus_device:[Device] = Device.allPlusSizedDevices
public let Gobal_group_of_all_X_device:[Device] = Device.allDevicesWithSensorHousing
public let Gobal_group_of_all_small_device:[Device] = [.iPhone5,.iPhone5c,.iPhone5s,.iPodTouch5,.iPodTouch6,.iPodTouch7,.iPhone6,.iPhone7,.iPhone8,.iPhoneSE,.iPhoneSE2,.iPhone12Mini,.iPhone13Mini,.simulator(.iPhone5),.simulator(.iPhone5c),.simulator(.iPhone5s),.simulator(.iPodTouch5),.simulator(.iPodTouch6),.simulator(.iPodTouch7),.simulator(.iPhone6),.simulator(.iPhone7),.simulator(.iPhone8),.simulator(.iPhoneSE),.simulator(.iPhoneSE2),.simulator(.iPhone12Mini),.simulator(.iPhone13Mini)]
public var isXModel: Bool {
if #available(iOS 11, *) {
guard let w = UIApplication.shared.delegate?.window, let unwrapedWindow = w else {
return false
}
if unwrapedWindow.safeAreaInsets.left > 0 || unwrapedWindow.safeAreaInsets.bottom > 0 {
return true
}
}
return false
}
/*! @brief 当前屏幕宽度
*/
public let kSCREEN_WIDTH = UIScreen.main.bounds.size.width
/*! @brief 当前屏幕高度
*/
public let kSCREEN_HEIGHT = UIScreen.main.bounds.size.height
/*! @brief 当前屏幕Bounds
*/
public let kSCREEN_BOUNDS = UIScreen.main.bounds
/*! @brief 当前屏幕Size
*/
public let kSCREEN_SIZE = kSCREEN_BOUNDS.size
/*! @brief 当前屏幕比例
*/
public let kSCREEN_SCALE = UIScreen.main.scale
public let kNavBarHeight : CGFloat = 44
/// 状态栏默认高度
public var kStatusBarHeight: CGFloat {
if #available(iOS 14.0, *)
{
return isXModel ? 48 : 20
}
return isXModel ? 44 : 20
}
public let kNavBarHeight_Total : CGFloat = kNavBarHeight + kStatusBarHeight
public let kTabbarSaveAreaHeight : CGFloat = isXModel ? 34 : 0
public let kTabbarHeight : CGFloat = 49
public let kTabbarHeight_Total : CGFloat = kTabbarSaveAreaHeight + kTabbarHeight
// MARK: - app版本&设备系统版本
public let infoDictionary = Bundle.main.infoDictionary
/* App显示名称 */
public let kAppDisplayName: String? = infoDictionary!["CFBundleDisplayName"] as? String
/* App名称 */
public let kAppName: String? = infoDictionary!["CFBundleName"] as? String
/* App版本号 */
public let kAppVersion: String? = infoDictionary!["CFBundleShortVersionString"] as? String
/* Appbuild版本号 */
public let kAppBuildVersion: String? = infoDictionary!["CFBundleVersion"] as? String
/* app bundleId */
public let kAppBundleId: String? = infoDictionary!["CFBundleIdentifier"] as? String
/* 平台名称(iphonesimulator 、 iphone)*/
public let kPlatformName: String? = infoDictionary!["DTPlatformName"] as? String
/* iOS系统版本 */
public let kiOSVersion: String = UIDevice.current.systemVersion
/* 系统名称+版本,e.g. @"iOS 12.1" */
public let kOSType: String = UIDevice.current.systemName + UIDevice.current.systemVersion
| mit | 663f73662c9aec421b2eb235262392f7 | 36.952381 | 493 | 0.723651 | 3.892552 | false | false | false | false |
castillejoale/Bluefruit_LE_Connect_v2_Minimized_UART | bluefruitconnect/Utils/LogHelper.swift | 1 | 771 | //
// LogHelper.swift
import Foundation
// dLog and aLog macros to abbreviate NSLog.
// Note: Add -D DEBUG to "Swift Compiler - Custom Flags" build section
// Use like this:
// dLog("Log this!")
#if DEBUG
func DLog(@autoclosure message: () -> String, filename: NSString = #file, function: String = #function, line: Int = #line) {
NSLog("[\(filename.lastPathComponent):\(line)] \(function) - %@", message())
}
#else
func DLog(@autoclosure message: () -> String, filename: String = #file, function: String = #function, line: Int = #line) {
}
#endif
func ALog(message: String, filename: NSString = #file, function: String = #function, line: Int = #line) {
NSLog("[\(filename.lastPathComponent):\(line)] \(function) - %@", message)
} | mit | 81dc2ba6bf3cea0b97a189a9c7a89541 | 32.565217 | 129 | 0.639429 | 3.742718 | false | false | false | false |
Marquis103/FitJourney | FitJourney/DiaryEntryDateFormatter.swift | 1 | 540 | //
// DiaryEntryDateFormatter.swift
// FitJourney
//
// Created by Marquis Dennis on 4/26/16.
// Copyright © 2016 Marquis Dennis. All rights reserved.
//
import UIKit
struct DiaryEntryDateFormatter {
static var sharedDateFormatter = DiaryEntryDateFormatter()
lazy var entryFormatter:NSDateFormatter = {
let entryFormatter = NSDateFormatter()
entryFormatter.dateFormat = "EEEE MMMM d, yyyy"
return entryFormatter
}()
/*lazy var listFormatter:NSDateFormatter = {
let listFormatter = NSDateFormatter()
}()*/
}
| gpl-3.0 | ad18e25629a84a98a3997919f8cb6b59 | 19.730769 | 59 | 0.727273 | 4.146154 | false | false | false | false |
richy486/printer-server-io | Sources/App/Models/User.swift | 1 | 5754 | import Foundation
import Vapor
import VaporPostgreSQL
import Fluent
import Auth
import Turnstile
import BCrypt
import VaporJWT
struct Authentication {
static let AccessTokenSigningKey: Bytes = Array("CHANGE_ME".utf8)
static let AccesTokenValidationLength = Date() + (60 * 5) // 5 Minutes later
}
final class User {
var exists: Bool = false
var id: Node?
var username: String!
var password: String!
var accessToken:String?
init(username: String, password: String) {
self.id = nil
self.username = username
self.password = BCrypt.hash(password: password)
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
username = try node.extract("username")
password = try node.extract("password")
accessToken = try node.extract("access_token")
}
init(credentials: UsernamePassword) {
self.username = credentials.username
self.password = BCrypt.hash(password: credentials.password)
}
init(credentials: Auth.AccessToken) {
self.accessToken = credentials.string
}
}
extension User: Model {
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"username": username,
"password": password,
"access_token": accessToken
])
}
}
extension User: Preparation {
static func prepare(_ database: Database) throws {
try database.create("users", closure: { (user) in
user.id()
user.string("username")
user.string("password")
user.string("access_token")
})
}
static func revert(_ database: Database) throws {
try database.delete("users")
}
}
extension User: Auth.User {
static func authenticate(credentials: Credentials) throws -> Auth.User {
var user: User?
switch credentials {
case let usernamePassword as UsernamePassword:
guard let fetchedUser = try User.query().filter("username", usernamePassword.username).first() else {
throw Abort.custom(status: .networkAuthenticationRequired, message: "User does not exist")
}
guard try BCrypt.verify(password: usernamePassword.password, matchesHash: fetchedUser.password) else {
throw Abort.custom(status: .networkAuthenticationRequired, message: "Invalid user name or password.")
}
user = fetchedUser
case let id as Identifier:
guard let fetchedUser = try User.find(id.id) else {
throw Abort.custom(status: .forbidden, message: "Invalid user identifier.")
}
user = fetchedUser
case let accessToken as AccessToken:
guard let fetchedUser = try User.query().filter("access_token", accessToken.string).first() else {
throw Abort.custom(status: .forbidden, message: "Invalid access token.")
}
user = fetchedUser
default:
let type = type(of: credentials)
throw Abort.custom(status: .forbidden, message: "Unsupported credential type: \(type).")
}
if var user = user {
// Check if we have an accessToken first, if not, lets create a new one
if let accessToken = user.accessToken {
// Check if our authentication token has expired, if so, lets generate a new one as this is a fresh login
let receivedJWT = try JWT(token: accessToken)
// Validate it's time stamp
if !receivedJWT.verifyClaims([ExpirationTimeClaim()]) {
try user.generateToken()
}
} else {
// We don't have a valid access token
try user.generateToken()
}
try user.save()
return user
} else {
throw IncorrectCredentialsError()
}
}
static func register(credentials: Credentials) throws -> Auth.User {
guard let usernamePassword = credentials as? UsernamePassword else {
let type = type(of: credentials)
throw Abort.custom(status: .forbidden, message: "Unsupported credential type: \(type).")
}
let user = User(username: usernamePassword.username, password: usernamePassword.password)
if try User.query().filter("username", user.username).first() == nil {
try user.generateToken()
// try user.save()
return user
} else {
throw AccountTakenError()
}
}
}
// MARK: Token Generation
extension User {
func generateToken() throws {
// Generate our Token
let jwt = try JWT(payload: Node(ExpirationTimeClaim(Authentication.AccesTokenValidationLength)), signer: HS256(key: Authentication.AccessTokenSigningKey))
self.accessToken = try jwt.createToken()
}
func validateToken() throws -> Bool {
guard let token = self.accessToken else { return false }
// Validate our current access token
let receivedJWT = try JWT(token: token)
if try receivedJWT.verifySignatureWith(HS256(key: Authentication.AccessTokenSigningKey)) {
// If we need a new token, lets generate one
if !receivedJWT.verifyClaims([ExpirationTimeClaim()]) {
try self.generateToken()
return true
}
}
return false
}
}
| mit | f1f0218d074a667a8e56f65605882c6b | 32.260116 | 162 | 0.581856 | 5.160538 | false | false | false | false |
zhiquan911/chance_btc_wallet | chance_btc_wallet/Pods/ESTabBarController-swift/Sources/ESTabBar.swift | 1 | 16494 | //
// ESTabBar.swift
//
// Created by Vincent Li on 2017/2/8.
// Copyright (c) 2013-2018 ESTabBarController (https://github.com/eggswift/ESTabBarController)
//
// 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
/// 对原生的UITabBarItemPositioning进行扩展,通过UITabBarItemPositioning设置时,系统会自动添加insets,这使得添加背景样式的需求变得不可能实现。ESTabBarItemPositioning完全支持原有的item Position 类型,除此之外还支持完全fill模式。
///
/// - automatic: UITabBarItemPositioning.automatic
/// - fill: UITabBarItemPositioning.fill
/// - centered: UITabBarItemPositioning.centered
/// - fillExcludeSeparator: 完全fill模式,布局不覆盖tabBar顶部分割线
/// - fillIncludeSeparator: 完全fill模式,布局覆盖tabBar顶部分割线
public enum ESTabBarItemPositioning : Int {
case automatic
case fill
case centered
case fillExcludeSeparator
case fillIncludeSeparator
}
/// 对UITabBarDelegate进行扩展,以支持UITabBarControllerDelegate的相关方法桥接
internal protocol ESTabBarDelegate: NSObjectProtocol {
/// 当前item是否支持选中
///
/// - Parameters:
/// - tabBar: tabBar
/// - item: 当前item
/// - Returns: Bool
func tabBar(_ tabBar: UITabBar, shouldSelect item: UITabBarItem) -> Bool
/// 当前item是否需要被劫持
///
/// - Parameters:
/// - tabBar: tabBar
/// - item: 当前item
/// - Returns: Bool
func tabBar(_ tabBar: UITabBar, shouldHijack item: UITabBarItem) -> Bool
/// 当前item的点击被劫持
///
/// - Parameters:
/// - tabBar: tabBar
/// - item: 当前item
/// - Returns: Void
func tabBar(_ tabBar: UITabBar, didHijack item: UITabBarItem)
}
/// ESTabBar是高度自定义的UITabBar子类,通过添加UIControl的方式实现自定义tabBarItem的效果。目前支持tabBar的大部分属性的设置,例如delegate,items,selectedImge,itemPositioning,itemWidth,itemSpacing等,以后会更加细致的优化tabBar原有属性的设置效果。
open class ESTabBar: UITabBar {
internal weak var customDelegate: ESTabBarDelegate?
/// tabBar中items布局偏移量
public var itemEdgeInsets = UIEdgeInsets.zero
/// 是否设置为自定义布局方式,默认为空。如果为空,则通过itemPositioning属性来设置。如果不为空则忽略itemPositioning,所以当tabBar的itemCustomPositioning属性不为空时,如果想改变布局规则,请设置此属性而非itemPositioning。
public var itemCustomPositioning: ESTabBarItemPositioning? {
didSet {
if let itemCustomPositioning = itemCustomPositioning {
switch itemCustomPositioning {
case .fill:
itemPositioning = .fill
case .automatic:
itemPositioning = .automatic
case .centered:
itemPositioning = .centered
default:
break
}
}
self.reload()
}
}
/// tabBar自定义item的容器view
internal var containers = [ESTabBarItemContainer]()
/// 缓存当前tabBarController用来判断是否存在"More"Tab
internal weak var tabBarController: UITabBarController?
/// 自定义'More'按钮样式,继承自ESTabBarItemContentView
open var moreContentView: ESTabBarItemContentView? = ESTabBarItemMoreContentView.init() {
didSet { self.reload() }
}
open override var items: [UITabBarItem]? {
didSet {
self.reload()
}
}
open var isEditing: Bool = false {
didSet {
if oldValue != isEditing {
self.updateLayout()
}
}
}
open override func setItems(_ items: [UITabBarItem]?, animated: Bool) {
super.setItems(items, animated: animated)
self.reload()
}
open override func beginCustomizingItems(_ items: [UITabBarItem]) {
ESTabBarController.printError("beginCustomizingItems(_:) is unsupported in ESTabBar.")
super.beginCustomizingItems(items)
}
open override func endCustomizing(animated: Bool) -> Bool {
ESTabBarController.printError("endCustomizing(_:) is unsupported in ESTabBar.")
return super.endCustomizing(animated: animated)
}
open override func layoutSubviews() {
super.layoutSubviews()
self.updateLayout()
}
open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
var b = super.point(inside: point, with: event)
if !b {
for container in containers {
if container.point(inside: CGPoint.init(x: point.x - container.frame.origin.x, y: point.y - container.frame.origin.y), with: event) {
b = true
}
}
}
return b
}
}
internal extension ESTabBar /* Layout */ {
internal func updateLayout() {
guard let tabBarItems = self.items else {
ESTabBarController.printError("empty items")
return
}
let tabBarButtons = subviews.filter { subview -> Bool in
if let cls = NSClassFromString("UITabBarButton") {
return subview.isKind(of: cls)
}
return false
} .sorted { (subview1, subview2) -> Bool in
return subview1.frame.origin.x < subview2.frame.origin.x
}
if isCustomizing {
for (idx, _) in tabBarItems.enumerated() {
tabBarButtons[idx].isHidden = false
moreContentView?.isHidden = true
}
for (_, container) in containers.enumerated(){
container.isHidden = true
}
} else {
for (idx, item) in tabBarItems.enumerated() {
if let _ = item as? ESTabBarItem {
tabBarButtons[idx].isHidden = true
} else {
tabBarButtons[idx].isHidden = false
}
if isMoreItem(idx), let _ = moreContentView {
tabBarButtons[idx].isHidden = true
}
}
for (_, container) in containers.enumerated(){
container.isHidden = false
}
}
var layoutBaseSystem = true
if let itemCustomPositioning = itemCustomPositioning {
switch itemCustomPositioning {
case .fill, .automatic, .centered:
break
case .fillIncludeSeparator, .fillExcludeSeparator:
layoutBaseSystem = false
}
}
if layoutBaseSystem {
// System itemPositioning
for (idx, container) in containers.enumerated(){
container.frame = tabBarButtons[idx].frame
}
} else {
// Custom itemPositioning
var x: CGFloat = itemEdgeInsets.left
var y: CGFloat = itemEdgeInsets.top
switch itemCustomPositioning! {
case .fillExcludeSeparator:
if y <= 0.0 {
y += 1.0
}
default:
break
}
let width = bounds.size.width - itemEdgeInsets.left - itemEdgeInsets.right
let height = bounds.size.height - y - itemEdgeInsets.bottom
let eachWidth = itemWidth == 0.0 ? width / CGFloat(containers.count) : itemWidth
let eachSpacing = itemSpacing == 0.0 ? 0.0 : itemSpacing
for container in containers {
container.frame = CGRect.init(x: x, y: y, width: eachWidth, height: height)
x += eachWidth
x += eachSpacing
}
}
}
}
internal extension ESTabBar /* Actions */ {
internal func isMoreItem(_ index: Int) -> Bool {
return ESTabBarController.isShowingMore(tabBarController) && (index == (items?.count ?? 0) - 1)
}
internal func removeAll() {
for container in containers {
container.removeFromSuperview()
}
containers.removeAll()
}
internal func reload() {
removeAll()
guard let tabBarItems = self.items else {
ESTabBarController.printError("empty items")
return
}
for (idx, item) in tabBarItems.enumerated() {
let container = ESTabBarItemContainer.init(self, tag: 1000 + idx)
self.addSubview(container)
self.containers.append(container)
if let item = item as? ESTabBarItem, let contentView = item.contentView {
container.addSubview(contentView)
}
if self.isMoreItem(idx), let moreContentView = moreContentView {
container.addSubview(moreContentView)
}
}
self.setNeedsLayout()
}
@objc internal func highlightAction(_ sender: AnyObject?) {
guard let container = sender as? ESTabBarItemContainer else {
return
}
let newIndex = max(0, container.tag - 1000)
guard newIndex < items?.count ?? 0, let item = self.items?[newIndex], item.isEnabled == true else {
return
}
if (customDelegate?.tabBar(self, shouldSelect: item) ?? true) == false {
return
}
if let item = item as? ESTabBarItem {
item.contentView?.highlight(animated: true, completion: nil)
} else if self.isMoreItem(newIndex) {
moreContentView?.highlight(animated: true, completion: nil)
}
}
@objc internal func dehighlightAction(_ sender: AnyObject?) {
guard let container = sender as? ESTabBarItemContainer else {
return
}
let newIndex = max(0, container.tag - 1000)
guard newIndex < items?.count ?? 0, let item = self.items?[newIndex], item.isEnabled == true else {
return
}
if (customDelegate?.tabBar(self, shouldSelect: item) ?? true) == false {
return
}
if let item = item as? ESTabBarItem {
item.contentView?.dehighlight(animated: true, completion: nil)
} else if self.isMoreItem(newIndex) {
moreContentView?.dehighlight(animated: true, completion: nil)
}
}
@objc internal func selectAction(_ sender: AnyObject?) {
guard let container = sender as? ESTabBarItemContainer else {
return
}
select(itemAtIndex: container.tag - 1000, animated: true)
}
@objc internal func select(itemAtIndex idx: Int, animated: Bool) {
let newIndex = max(0, idx)
let currentIndex = (selectedItem != nil) ? (items?.index(of: selectedItem!) ?? -1) : -1
guard newIndex < items?.count ?? 0, let item = self.items?[newIndex], item.isEnabled == true else {
return
}
if (customDelegate?.tabBar(self, shouldSelect: item) ?? true) == false {
return
}
if (customDelegate?.tabBar(self, shouldHijack: item) ?? false) == true {
customDelegate?.tabBar(self, didHijack: item)
if animated {
if let item = item as? ESTabBarItem {
item.contentView?.select(animated: animated, completion: {
item.contentView?.deselect(animated: false, completion: nil)
})
} else if self.isMoreItem(newIndex) {
moreContentView?.select(animated: animated, completion: {
self.moreContentView?.deselect(animated: animated, completion: nil)
})
}
}
return
}
if currentIndex != newIndex {
if currentIndex != -1 && currentIndex < items?.count ?? 0{
if let currentItem = items?[currentIndex] as? ESTabBarItem {
currentItem.contentView?.deselect(animated: animated, completion: nil)
} else if self.isMoreItem(currentIndex) {
moreContentView?.deselect(animated: animated, completion: nil)
}
}
if let item = item as? ESTabBarItem {
item.contentView?.select(animated: animated, completion: nil)
} else if self.isMoreItem(newIndex) {
moreContentView?.select(animated: animated, completion: nil)
}
delegate?.tabBar?(self, didSelect: item)
} else if currentIndex == newIndex {
if let item = item as? ESTabBarItem {
item.contentView?.reselect(animated: animated, completion: nil)
} else if self.isMoreItem(newIndex) {
moreContentView?.reselect(animated: animated, completion: nil)
}
if let tabBarController = tabBarController {
var navVC: UINavigationController?
if let n = tabBarController.selectedViewController as? UINavigationController {
navVC = n
} else if let n = tabBarController.selectedViewController?.navigationController {
navVC = n
}
if let navVC = navVC {
if navVC.viewControllers.contains(tabBarController) {
if navVC.viewControllers.count > 1 && navVC.viewControllers.last != tabBarController {
navVC.popToViewController(tabBarController, animated: true);
}
} else {
if navVC.viewControllers.count > 1 {
navVC.popToRootViewController(animated: animated)
}
}
}
}
}
self.updateAccessibilityLabels()
}
internal func updateAccessibilityLabels() {
guard let tabBarItems = self.items, tabBarItems.count == self.containers.count else {
return
}
for (idx, item) in tabBarItems.enumerated() {
let container = self.containers[idx]
var accessibilityTitle = ""
if let item = item as? ESTabBarItem {
accessibilityTitle = item.accessibilityLabel ?? item.title ?? ""
}
if self.isMoreItem(idx) {
accessibilityTitle = NSLocalizedString("More_TabBarItem", bundle: Bundle(for:ESTabBarController.self), comment: "")
}
let formatString = NSLocalizedString(item == selectedItem ? "TabBarItem_Selected_AccessibilityLabel" : "TabBarItem_AccessibilityLabel",
bundle: Bundle(for: ESTabBarController.self),
comment: "")
container.accessibilityIdentifier = item.accessibilityIdentifier
container.accessibilityLabel = String(format: formatString, accessibilityTitle, idx + 1, tabBarItems.count)
}
}
}
| mit | 7eff44e91437b0a93b9aa0b0c5608ce1 | 36.350588 | 180 | 0.577107 | 5.316142 | false | false | false | false |
movabletype/smartphone-app | MT_iOS/MT_iOS/Classes/Model/ItemList.swift | 1 | 3300 | //
// ItemList.swift
// MT_iOS
//
// Created by CHEEBOW on 2015/05/19.
// Copyright (c) 2015年 Six Apart, Ltd. All rights reserved.
//
import UIKit
import SwiftyJSON
class ItemList: NSObject {
var items = [BaseObject]()
var working: Bool = false
var refresh: Bool = false
var sortEnabled: Bool = true
var totalCount: Int = 0
var searchText = ""
func toModel(json: JSON)->BaseObject {
//Implemants subclass
return BaseObject(json: json)
}
func isExists(model: BaseObject)->Bool {
for item in self.items {
if (item as BaseObject).id == model.id {
return true
}
}
return false
}
func deleteObject(model: BaseObject)->Bool {
let index = existsIndex(model)
if index > NOTFOUND {
self.items.removeAtIndex(index)
return true
}
return false
}
func existsIndex(model: BaseObject)->Int {
var i = 0
for item in self.items {
if (item as BaseObject).id == model.id {
return i
}
i++
}
return NOTFOUND
}
func objectWithID(id: String)-> BaseObject? {
for item in self.items {
if (item as BaseObject).id == id {
return item
}
}
return nil
}
// func sortByCreatedAt() {
// self.items.sort {
// (a: AnyObject?, b: AnyObject?) -> Bool in
// return (a as BaseObject).createdAt.compare((b as BaseObject).createdAt) == NSComparisonResult.OrderedDescending
// }
// }
subscript(index: Int)-> BaseObject {
get {
assert(items.count > index, "index out of range")
return items[index]
}
set(item) {
assert(0 > index || items.count >= index, "index out of range")
items.insert(item, atIndex: index)
}
}
var count: Int {
return self.items.count
}
func isFinished()-> Bool {
if self.items.count == 0 && self.totalCount > 0 {
return true
}
return self.totalCount <= self.items.count
}
func parseItems(jsonItems: [JSON]!) {
for jsonItem in jsonItems {
let item: BaseObject = self.toModel(jsonItem)
if !item.id.isEmpty {
let index = self.existsIndex(item)
if index < 0 {
self.items.append(item)
} else {
self.items[index] = item
}
}
}
}
func postProcess() {
refresh = false
working = false
}
func fetch(offset: Int, success: ((items:[JSON]!, total:Int!) -> Void)!, failure: (JSON! -> Void)!) {
//Implemants subclass
}
func refresh(success: ((items:[JSON]!, total:Int!) -> Void)!, failure: (JSON! -> Void)!) {
refresh = true
self.fetch(0, success: success, failure: failure)
}
func more(success: ((items:[JSON]!, total:Int!) -> Void)!, failure: (JSON! -> Void)!) {
refresh = false
self.fetch(self.items.count, success: success, failure: failure)
}
}
| mit | 68d4c076f8a127e03b2520732bbceb55 | 24.968504 | 125 | 0.507884 | 4.362434 | false | false | false | false |
dokun1/FingerLock | FingerLock/FingerLock/PasswordFile.swift | 1 | 1653 | //
// PasswordFile.swift
// FingerLock
//
// Created by David Okun on 2/2/15.
// Copyright (c) 2015 David Okun, LLC. All rights reserved.
//
import UIKit
class PasswordFile: NSObject, Printable, NSCopying {
var title = ""
var username = ""
var password = ""
var website = ""
var notes = ""
var fileID = ""
required override init() {
super.init()
}
required init(coder aDecoder: NSCoder) {
title = aDecoder.decodeObjectForKey("Title") as! String
username = aDecoder.decodeObjectForKey("Username") as! String
password = aDecoder.decodeObjectForKey("Password") as! String
website = aDecoder.decodeObjectForKey("Website") as! String
notes = aDecoder.decodeObjectForKey("Notes") as! String
fileID = aDecoder.decodeObjectForKey("FileID") as! String
super.init()
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(title, forKey:"Title")
aCoder.encodeObject(username, forKey:"Username")
aCoder.encodeObject(password, forKey:"Password")
aCoder.encodeObject(website, forKey:"Website")
aCoder.encodeObject(notes, forKey:"Notes")
aCoder.encodeObject(fileID, forKey:"FileID")
}
func copyWithZone(zone: NSZone) -> AnyObject {
var copyInstance = self.dynamicType()
copyInstance.fileID = self.fileID
copyInstance.title = self.title
copyInstance.username = self.username
copyInstance.password = self.password
copyInstance.website = self.website
copyInstance.notes = self.notes
return copyInstance
}
} | mit | 3422289f0ffbdf1881b893a8b082b014 | 30.807692 | 69 | 0.646098 | 4.722857 | false | false | false | false |
tiagomnh/ProjectEuler | ProjectEuler/Other/SieveOfEratosthenes.swift | 1 | 732 | //
// SieveOfEratosthenes.swift
// ProjectEuler
//
// Created by Tiago Henriques on 08/05/16.
// Copyright © 2016 Tiago Henriques. All rights reserved.
//
import Foundation
final class SieveOfEratosthenes {
let list: [Bool]
init(limit: Int) {
var list = Array<Bool>(count: limit, repeatedValue: true)
list[0] = false
list[1] = false
func markMultiples(inout list: [Bool], value: Int) {
for i in (2 * value).stride(to: list.count, by: value) {
list[i] = false
}
}
for i in 0..<list.count {
if list[i] == true {
markMultiples(&list, value: i)
}
}
self.list = list
}
} | mit | 8170b2608b83b8d466fadfd3c1623ac3 | 21.181818 | 68 | 0.53078 | 3.673367 | false | false | false | false |
MichaelCampbell/DateTime | src/DateTime.swift | 1 | 13330 | /*
Copyright (c) 2015 Christopher Jones <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import UIKit
// MARK: Initialization
/**
* An immutable structure for handling date and time values.
*/
public struct DateTime: Comparable
{
/// The timezone of the date time. This defaults to the device timezone if not specified during initialization.
public let timezone: NSTimeZone
// NSDate value used internally
private let internalDate: NSDate
// NSCalendarComponents used internally.
private let calendarComponents: NSDateComponents
/**
Initializes a new instance of DateTime, with the date set to the current date and time.
:returns: A new instance of DateTime set to the current time.
*/
public init()
{
self.init(date: NSDate())
}
/**
Initializes a new instance of DateTime by initializing a time interval from the specified date.
:param: timeInterval The time interval in seconds to be added to the reference date.
:param: date The reference date.
:param: timezone The timezone for the DateTime; defaults to the device time zone if unspecified.
:returns: A new instance of DateTime set to the specified time interval since the input reference date.
*/
public init(timeInterval: NSTimeInterval, sinceDate date: NSDate, inTimezone timezone: NSTimeZone = NSTimeZone.defaultTimeZone())
{
let date = NSDate(timeInterval: timeInterval, sinceDate: date)
self.init(date: date, timezone: timezone)
}
/**
Attempts to initializes a new DateTime by parsing an input string to the specified format.
:param: string The date string to convert.
:param: format The date format to be used to convert the date.
:param: timezone The timezone for the date conversion; defaults to the device time zone if unspecified.
:returns: If the date string is valid and can be parsed, a new DateTime object; otherwise, this will be nil
*/
public init?(string: String, format: String, timezone: NSTimeZone = NSTimeZone.defaultTimeZone())
{
let dateFormatter = NSDateFormatter.sharedFormatter
dateFormatter.dateFormat = format
dateFormatter.timeZone = timezone
guard let dateValue = dateFormatter.dateFromString(string) else {
return nil
}
self.init(date: dateValue, timezone: timezone)
}
/**
Attempts to initialize a new instance of DateTime by creating a date object from input month, day, and year. The time component of the DateTime will be set to midnight.
:param: month The month for the date.
:param: day The day for the date.
:param: year The year for the date.
:param: timezone The timezone for the date; if not specified, this will default to the device timezone.
:returns: If a DateTime can be initialized with the specified input, a new DateTime object; otherwise this will be nil.
*/
public init?(month: Month, day: Int, year: Int, timezone: NSTimeZone = NSTimeZone.defaultTimeZone())
{
self.init(month: month, day: day, year: year, hour: 0, minute: 0, second: 0, timezone: timezone)
}
/**
Attempts to initialize a new instance of DateTime by creating a date and time from the specified inputs.
:param: month The month for the date.
:param: day The day for the date.
:param: year The year for the date.
:param: hour The hour for the date.
:param: minute The minute for the date.
:param: second The seconds for the date.
:param: timezone The timezone for the date; if not specified, this will default to the device timezone.
:returns: If a DateTime can be initialized with the specified input, a new DateTime object; otherwise this will be nil.
*/
public init?(month: Month, day: Int, year: Int, hour: Int, minute: Int, second: Int, timezone: NSTimeZone = NSTimeZone.defaultTimeZone())
{
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
calendar.timeZone = timezone
let components = NSDateComponents()
components.calendar = calendar
components.timeZone = timezone
components.month = month.rawValue
components.day = day
components.year = year
components.hour = hour
components.minute = minute
components.second = second
guard let dateValue = calendar.dateFromComponents(components) else {
return nil
}
self.init(date: dateValue, timezone: timezone)
}
/**
Initializes a new DateTime object with the specified NSDate and timezone.
:param: date The reference date.
:param: timezone The timezone; if not specified, this will default to the device timezone.
:returns: A new instance of DateTime.
*/
public init(date: NSDate, timezone: NSTimeZone = NSTimeZone.defaultTimeZone())
{
self.internalDate = date
self.timezone = timezone
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
calendar.timeZone = timezone
let calendarUnits = NSCalendarUnit(rawValue: UInt.max)
self.calendarComponents = calendar.components(calendarUnits, fromDate: self.internalDate)
}
}
// MARK: -
// MARK: RawRepresentable
extension DateTime: RawRepresentable
{
/// The raw type of DateTime.
public typealias RawType = NSTimeInterval
/// The raw value of the DateTime as represented in the number of seconds since 1970.
public var rawValue: RawType {
get {
return self.internalDate.timeIntervalSince1970
}
}
/**
Initializes a new instance of DateTime with its raw type.
:param: rawValue The time interval since 1970.
:returns: A new instance of DateTime; this initialization can be safely force-unwrapped.
*/
public init?(rawValue: RawType) {
let date = NSDate(timeIntervalSince1970: rawValue)
self.init(date: date)
}
}
// MARK: -
// MARK: Components
extension DateTime
{
/// The weekday component of the date.
public var weekday: Weekday {
get {
return Weekday(rawValue: self.calendarComponents.weekday)!
}
}
/// The month component of the date.
public var month: Month {
get {
return Month(rawValue: self.calendarComponents.month)!
}
}
/// The day component of the date.
public var day: Int {
get {
return self.calendarComponents.day
}
}
/// The year component of the date.
public var year: Int {
get {
return self.calendarComponents.year
}
}
/// The hour component of the date.
public var hour: Int {
get {
return self.calendarComponents.hour
}
}
/// The minute comopnent of the date.
public var minute: Int {
get {
return self.calendarComponents.minute
}
}
/// The second component of the date.
public var second: Int {
get {
return self.calendarComponents.second
}
}
}
// MARK: -
// MARK: TimeSpan
extension DateTime
{
/**
Adds the input number of seconds to the current DateTime.
:param: seconds The number of seconds to add.
:returns: A new DateTime modified by the number of seconds.
*/
public func addSeconds(seconds: Int) -> DateTime
{
let timespan = TimeSpan(days: 0, hours: 0, minutes: 0, seconds: seconds)
return self.addTimespan(timespan)
}
/**
Adds the input number of minutes to the current DateTime.
:param: minutes The number of minutes to add.
:returns: A new DateTime modified by the number of minutes.
*/
public func addMinutes(minutes: Int) -> DateTime
{
let timespan = TimeSpan(days: 0, hours: 0, minutes: minutes, seconds: 0)
return self.addTimespan(timespan)
}
/**
Adds the input number of hours to the current DateTime.
:param: hours The number of hours to add.
:returns: A new DateTime modified by the number of hours.
*/
public func addHours(hours: Int) -> DateTime
{
let timespan = TimeSpan(days: 0, hours: hours, minutes: 0, seconds: 0)
return self.addTimespan(timespan)
}
/**
Adds the input number of days to the current DateTime.
:param: days The number of days to add.
:returns: A new DateTime modified by the number of days.
*/
public func addDays(days: Int) -> DateTime
{
let timespan = TimeSpan(days: days, hours: 0, minutes: 0, seconds: 0)
return self.addTimespan(timespan)
}
/**
Adds the specified timespan to the current datetime.
:param: timespan The timespan to add.
:returns: A new DateTime modified by the timespan.
*/
public func addTimespan(timespan: TimeSpan) -> DateTime
{
let newDate = self.internalDate.dateByAddingTimeInterval(timespan.timeInterval)
return DateTime(date: newDate, timezone: self.timezone)
}
/**
Calculates the timespan since the input date.
:param: datetime The datetime to subtract from the current date.
:returns: The timespan since the current date.
*/
public func timespanSinceDate(datetime: DateTime) -> TimeSpan
{
let timeInterval = self.internalDate.timeIntervalSinceDate(datetime.internalDate)
return TimeSpan(timeInterval: timeInterval)
}
}
// MARK: -
// MARK: String Formatting
extension DateTime: CustomStringConvertible
{
/**
Converts the DateTime to a string value with the specified format.
:param: format The format for the date.
:returns: The DateTime string value.
*/
public func stringValue(format format: DateTimeStringFormat) -> String
{
return self.stringValue(format: format.rawValue)
}
/**
Converts the DateTime to a string value with the specified format.
:param: format The format for the date.
:returns: The DateTime string value.
*/
public func stringValue(format format: String) -> String
{
let dateFormatter = NSDateFormatter.sharedFormatter
dateFormatter.dateFormat = format
dateFormatter.timeZone = self.timezone
return dateFormatter.stringFromDate(self.internalDate)
}
/// The description of the DateTime; this defaults to DateTimeStringFormat.Full
public var description: String {
get {
return self.stringValue(format: .Full)
}
}
}
// MARK: -
// MARK: Comparable & Equatable
/**
Evaluates if the two DateTime values are equal.
:param: left The first DateTime.
:param: right The second DateTime.
:returns: True if the two input DateTime values are equal; otherwise false.
*/
public func ==(left: DateTime, right: DateTime) -> Bool
{
return left.rawValue == right.rawValue
}
/**
Evaluates if the first DateTime value is less than the second.
:param: left The first DateTime.
:param: right The second DateTime.
:returns: True if the first DateTime value is less than the second; otherwise false.
*/
public func <(left: DateTime, right: DateTime) -> Bool
{
return left.rawValue < right.rawValue
}
/**
Evaluates if the first DateTime value is less than or equal to the second.
:param: left The first DateTime.
:param: right The second DateTime.
:returns: True if the first DateTime value is less than or equal to the second; otherwise false.
*/
public func <=(left: DateTime, right: DateTime) -> Bool
{
return left.rawValue <= right.rawValue
}
/**
Evaluates if the first DateTime value is greater than the second.
:param: left The first DateTime.
:param: right The second DateTime.
:returns: True if the first DateTime value is greater than the second; otherwise false.
*/
public func >(left: DateTime, right: DateTime) -> Bool
{
return left.rawValue > right.rawValue
}
/**
Evaluates if the first DateTime value is greater than or equal to the second.
:param: left The first DateTime.
:param: right The second DateTime.
:returns: True if the first DateTime value is greater than or equal to the second; otherwise false.
*/
public func >=(left: DateTime, right: DateTime) -> Bool
{
return left.rawValue >= right.rawValue
} | mit | fcbfb86d40b6668ead01fb06388747db | 29.787529 | 172 | 0.682971 | 4.61885 | false | false | false | false |
xiaomudegithub/viossvc | viossvc/Scenes/Chat/CustomView/InputBarView.swift | 1 | 7918 | //
// InputBarView.swift
// viossvc
//
// Created by abx’s mac on 2016/12/1.
// Copyright © 2016年 com.yundian. All rights reserved.
//
import UIKit
protocol InputBarViewProcotol : OEZViewActionProtocol{
func inputBarDidKeyboardShow(inputBar inputBar: InputBarView,userInfo : [NSObject : AnyObject]?)
func inputBarDidKeyboardHide(inputBar inputBar: InputBarView,userInfo : [NSObject : AnyObject]?)
func inputBarDidSendMessage(inputBar inputBar: InputBarView ,message: String)
func inputBarDidChangeHeight(inputBar inputBar: InputBarView,height: CGFloat)
}
class InputBarView: OEZBaseView ,UITextViewDelegate,FaceKeyboardViewDelegate {
@IBOutlet weak var faceButton: UIButton!
@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var textView: CustomTextView!
var faceKeyboard :FaceKeyboardView = FaceKeyboardView.loadFromNib()
var faceKeyboardView : UIView = UIView()
weak var inputDelegate : InputBarViewProcotol?
var isKVO : Bool = false
// var isChangeTextViewHeight = false
let inputBarHeight : CGFloat = 50
let kFaceKeyboardHeight : CGFloat = 216
let sendLayer: CALayer = CALayer.init()
override func awakeFromNib() {
super.awakeFromNib()
sendLayerSetting()
addNotification()
textViewSetting()
facekeyboardSetting()
}
func facekeyboardSetting() {
faceKeyboard.frame = CGRectMake(0, 0, UIScreen.width(), kFaceKeyboardHeight)
faceKeyboard.faceDelegate = self
faceKeyboardView.frame = faceKeyboard.frame
faceKeyboardView.addSubview(faceKeyboard)
}
func textViewSetting() {
textView.delegate = self
textView.setPlaceHolder("输入要说的话...")
textView.settingPlaceHolderTextColor(UIColor(RGBHex: 0xbdbdbd))
let top = (self.textView.bounds.size.height - UIFont.HEIGHT(14)) / 2.0;
textView.settingScrollIndicatorInsets(UIEdgeInsetsMake(top, 5, 0, 5))
textView.addObserver(self, forKeyPath: "contentSize", options: .New, context: nil)
}
func addNotification() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(InputBarView.didKeyboardShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(InputBarView.didKeyboardHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
func registeredDelegate(sender : InputBarViewProcotol) {
inputDelegate = sender
}
func didKeyboardShow( notification: NSNotification) {
if (textView.isFirstResponder()) {
// _keyboardShow = YES;
// _isActionEmoji = NO;
//
inputDelegate?.inputBarDidKeyboardShow(inputBar: self, userInfo: notification.userInfo)
//
}
}
func didKeyboardHide(notification: NSNotification) {
if ( textView.isFirstResponder())
{
if( textView.inputView != nil )
{
textView.inputView = nil;
}
// if (![self isTouchEmoji]) {
// _keyboardShow = NO;
inputDelegate?.inputBarDidKeyboardHide(inputBar: self, userInfo: notification.userInfo)
faceButton.selected = false
// }
}
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "contentSize" && object === textView {
let contentH = getHeight()
let viewHeight = self.bounds.height
if !isKVO && viewHeight != contentH {
inputDelegate?.inputBarDidChangeHeight(inputBar: self, height: contentH)
}
textView.scrollRectToVisible(CGRectMake(0, textView.contentSize.height - UIFont.HEIGHT(14), textView.contentSize.width,UIFont.HEIGHT(14)), animated: false)
}
}
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if text == "\n"{
didSendMessage()
return false;
}
return true;
}
func textViewDidChange(textView: UITextView) {
sendLayerChangeColor(textView.text.length() > 0)
isKVO = false
}
func didSendMessage() {
let inputText = textView.text;
inputDelegate?.inputBarDidSendMessage(inputBar: self, message: inputText)
textView.text = nil;
sendLayerChangeColor(false)
isKVO = true
DidChangeHeight()
}
func DidChangeHeight() {
inputDelegate?.inputBarDidChangeHeight(inputBar: self, height:getHeight())
}
func faceKeyboardView(faceKeyboardView: FaceKeyboardView, didKeyCode keyCode: String) {
if keyCode.length() > 0{
textView.insertText(keyCode)
}else {
textView.deleteBackward()
}
sendLayerChangeColor(textView.text.length() > 0)
}
@IBAction func emojiFaceAction(sender : UIButton) {
if faceButton.selected {
textView.inputView = nil
}
let isSelected = faceButton.selected
UIView.animateWithDuration(0.2) {
self.resignTextViewFirstResponder()
}
faceButton.selected = !isSelected
setFaceBottonImage()
if faceButton.selected {
textView.inputView = faceKeyboardView
// [self emojiOpen];
}
UIView.animateWithDuration(0.2) {
self.becomeTextViewFirstResponder()
}
}
func setFaceBottonImage() {
// let image = UIImage(named: faceButton.selected ? "cm_emojiHigh" : "cm_emojiGray")
// faceButton.setImage(image, forState: .Normal)
}
@IBAction func sendButtonAction(sender : UIButton) {
MobClick.event(AppConst.Event.message_send)
didSendMessage()
}
func sendLayerSetting() {
sendLayer.frame = CGRectMake(0, 10, sendButton.bounds.width, 30)
sendLayer.masksToBounds = true
sendLayer.cornerRadius = 3
sendLayer.backgroundColor = UIColor(RGBHex: 0xE0E1E2).CGColor
sendButton.layer.addSublayer(sendLayer)
}
func sendLayerChangeColor(canSend: Bool) {
if sendButton.userInteractionEnabled != canSend {
sendLayer.backgroundColor = canSend ? UIColor(RGBHex: 0x141F33).CGColor :UIColor(RGBHex: 0xE0E1E2).CGColor
sendButton.userInteractionEnabled = canSend
}
}
func getHeight() -> CGFloat {
var height = inputBarHeight
if textView.text.length() != 0 {
height = ceil(textView.sizeThatFits(textView.frame.size).height)
height = height > 73 ? 73 : height
height += 20
}
// else
// {
// //全选剪贴的情况
// height = kInputBarHeight;
// }
height = height > inputBarHeight ? height : inputBarHeight;
return height;
}
func becomeTextViewFirstResponder() {
textView.becomeFirstResponder()
}
func resignTextViewFirstResponder() {
textView.resignFirstResponder()
}
func isTextViewFirstResponder() -> Bool{
return textView.isFirstResponder()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
textView.removeObserver(self, forKeyPath: "contentSize")
}
}
| apache-2.0 | ae49d359da18fdf9c9ec1bb7dfcbfa2c | 28.539326 | 168 | 0.609357 | 5.22664 | false | false | false | false |
MiniDOM/MiniDOM | Sources/MiniDOM/MiniDOM.swift | 1 | 20299 | //
// MiniDOM.swift
// MiniDOM
//
// Copyright 2017-2020 Anodized Software, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
/*
This file contains the protocols and classes used to define the Document
Object Model.
This is intended to provided a subset of the behavior described in the
[DOM Level 1 specification][1] and the [DOM Level 2 specification][2]. Much of
this file's documentation is adapted from those documents.
[1]: https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html
[2]: https://www.w3.org/TR/DOM-Level-2-Core/core.html
*/
import Foundation
/// An `enum` indicating the type of a `Node` object.
public enum NodeType {
/// A `Document` object
case document
/// An `Element` object
case element
/// A `Text` object
case text
/// A `ProcessingInstruction` object
case processingInstruction
/// A `Comment` object
case comment
/// A `CDATASection` object
case cdataSection
}
// MARK: - Node Protocol
/**
The `Node` protocol is the primary data type for the entire Document Object
Model. It represents a single node in the document tree. While all objects
implementing the `Node` protocol expose functionality related to children, not
all objects implementing the `Node` protocol may have children. To address this
distinction, there are two additional protocols implemented by node types:
- `ParentNode` provides a getter and setter on the `children` property
- `LeafNode` provides a getter on the `children` property that always returns
an empty array.
This is a departure from the standard DOM which would throw an error when
attempting to modify the `children` array of a leaf node.
The attributes `nodeName`, `nodeValue`, and `attributes` are included as a
mechanism to get at node information without casting down to the specific
derived type. In cases where there is no obvious mapping of these attributes
for a specific `nodeType` (e.g., `nodeValue` for an Element or `attributes` for
a Comment), this returns `nil`.
The values of `nodeName`, `nodeValue`, and `attributes` vary according to the
node type.
*/
public protocol Node: Visitable {
/**
Indicates which type of node this is.
- SeeAlso: [`Document.nodeType`](Document.html#//apple_ref/swift/Property/nodeType)
- SeeAlso: [`Element.nodeType`](Element.html#//apple_ref/swift/Property/nodeType)
- SeeAlso: [`Text.nodeType`](Text.html#//apple_ref/swift/Property/nodeType)
- SeeAlso: [`ProcessingInstruction.nodeType`](ProcessingInstruction.html#//apple_ref/swift/Property/nodeType)
- SeeAlso: [`Comment.nodeType`](Comment.html#//apple_ref/swift/Property/nodeType)
- SeeAlso: [`CDATASection.nodeType`](CDATASection.html#//apple_ref/swift/Property/nodeType)
*/
static var nodeType: NodeType { get }
/**
The name of this node, depending on its type.
- SeeAlso: [`Document.nodeName`](Document.html#//apple_ref/swift/Property/nodeName)
- SeeAlso: [`Element.nodeName`](Element.html#//apple_ref/swift/Property/nodeName)
- SeeAlso: [`Text.nodeName`](Text.html#//apple_ref/swift/Property/nodeName)
- SeeAlso: [`ProcessingInstruction.nodeName`](ProcessingInstruction.html#//apple_ref/swift/Property/nodeName)
- SeeAlso: [`Comment.nodeName`](Comment.html#//apple_ref/swift/Property/nodeName)
- SeeAlso: [`CDATASection.nodeName`](CDATASection.html#//apple_ref/swift/Property/nodeName)
*/
var nodeName: String { get }
/**
The value of this node, depending on its type.
- SeeAlso: [`Document.nodeValue`](Document.html#//apple_ref/swift/Property/nodeValue)
- SeeAlso: [`Element.nodeValue`](Element.html#//apple_ref/swift/Property/nodeValue)
- SeeAlso: [`Text.nodeValue`](Text.html#//apple_ref/swift/Property/nodeValue)
- SeeAlso: [`ProcessingInstruction.nodeValue`](ProcessingInstruction.html#//apple_ref/swift/Property/nodeValue)
- SeeAlso: [`Comment.nodeValue`](Comment.html#//apple_ref/swift/Property/nodeValue)
- SeeAlso: [`CDATASection.nodeValue`](CDATASection.html#//apple_ref/swift/Property/nodeValue)
*/
var nodeValue: String? { get }
/**
The attributes of this node, depending on its type.
- SeeAlso: [`Document.attributes`](Document.html#//apple_ref/swift/Property/attributes)
- SeeAlso: [`Element.attributes`](Element.html#//apple_ref/swift/Property/attributes)
- SeeAlso: [`Text.attributes`](Text.html#//apple_ref/swift/Property/attributes)
- SeeAlso: [`ProcessingInstruction.attributes`](ProcessingInstruction.html#//apple_ref/swift/Property/attributes)
- SeeAlso: [`Comment.attributes`](Comment.html#//apple_ref/swift/Property/attributes)
- SeeAlso: [`CDATASection.attributes`](CDATASection.html#//apple_ref/swift/Property/attributes)
*/
var attributes: [String : String]? { get }
/**
The children of this node.
- SeeAlso: [`Document.children`](Document.html#//apple_ref/swift/Property/children)
- SeeAlso: [`Element.children`](Element.html#//apple_ref/swift/Property/children)
- SeeAlso: [`Text.children`](Text.html#//apple_ref/swift/Property/children)
- SeeAlso: [`ProcessingInstruction.children`](ProcessingInstruction.html#//apple_ref/swift/Property/children)
- SeeAlso: [`Comment.children`](Comment.html#//apple_ref/swift/Property/children)
- SeeAlso: [`CDATASection.children`](CDATASection.html#//apple_ref/swift/Property/children)
*/
var children: [Node] { get }
/**
Puts all `Text` nodes in the full depth of the sub-tree underneath this
`Node`, into a "normal" form where only structure (e.g., elements,
comments, processing instructions, and CDATA sections) separates `Text`
nodes, i.e., there are neither adjacent `Text` nodes nor empty `Text`
nodes. This can be used to ensure that the DOM view of a document is the
same as if it were saved and re-loaded.
*/
mutating func normalize()
}
public extension Node {
/// Convenience accessor for the static `nodeType` property.
var nodeType: NodeType {
return Self.nodeType
}
/**
Filters the `children` array, keeping only nodes of the specified type.
Casts the nodes in the resulting array to the specified type.
- parameter type: Include children of this type in the resulting array
- returns: The nodes in the `children` array of the specified type
*/
func children<T: Node>(ofType type: T.Type) -> [T] {
return children.only(ofType: T.self)
}
/// A Boolean value indicating whether the `children` array is not empty.
var hasChildren: Bool {
return !children.isEmpty
}
/// The first node in the `children` array.
var firstChild: Node? {
return children.first
}
/// The last node in the `children` array.
var lastChild: Node? {
return children.last
}
/**
Returns an array of children with the given `nodeName`.
- parameter name: The node name to find.
- returns: The children with the given node name.
*/
func children(withName name: String) -> [Node] {
return children.nodes(withName: name)
}
/// Returns the `Element` objects from the `children` array.
var childElements: [Element] {
return self.children(ofType: Element.self)
}
/// A Boolean value indicating whether the `childElements` array is not empty
var hasChildElements: Bool {
return !childElements.isEmpty
}
/// The first element in the `childElements` array.
var firstChildElement: Element? {
return childElements.first
}
/// The last element in the `childElements` array.
var lastChildElement: Element? {
return childElements.last
}
/**
Returns an array of child `Element` objects with the given `nodeName`.
- parameter name: The node name to find.
- returns: The child elements with the given node name.
*/
func childElements(withName name: String) -> [Element] {
return children.elements(withName: name)
}
}
// MARK: - Leaf Protocol
/**
Represents a node that cannot have children.
*/
public protocol LeafNode: Node {
/**
A leaf node does not have children. The value of this property is always
an empty array.
*/
var children: [Node] { get }
}
public extension LeafNode {
/**
A leaf node does not have children. The value of this property is always
an empty array.
*/
var children: [Node] {
return []
}
mutating func normalize() { }
}
// MARK: - Parent Protocol
/**
Represents a node that can have children.
*/
public protocol ParentNode: Node {
/// The children of this node.
var children: [Node] { get set }
}
public extension ParentNode {
/**
Appends the specified node to the end of the `children` array.
- parameter child: The node to append
*/
mutating func append(child: Node) {
children.append(child)
}
mutating func normalize() {
var newChildren: [Node] = []
for var currNode in children {
if let currText = currNode as? Text, let prevText = newChildren.last as? Text {
prevText.append(currText)
}
else {
newChildren.append(currNode)
}
if currNode.hasChildren {
currNode.normalize()
}
}
children = newChildren
}
}
// MARK: - TextNode Protocol
/**
Represents a node with a text value.
*/
public protocol TextNode: LeafNode {
/// The text value associated with this node.
var text: String { get set }
}
public extension TextNode {
/// The `nodeValue` of a `TextNode` node is its `text` property.
var nodeValue: String? {
return text
}
}
// MARK: - Document
/**
The `Document` class represents the entire document. Conceptually, it is the
root of the document tree, and provides the primary access to the document's
data.
*/
public final class Document: ParentNode {
// MARK: Node
/// The `nodeType` of a `Document` is `.document`.
public static let nodeType: NodeType = .document
/// The `nodeName` of a `Document` is `#document`.
public final let nodeName: String = "#document"
/// The `nodeValue` of a `Document` is `nil`.
public final let nodeValue: String? = nil
/**
The children of the document will contain the document element and any
processing instructions or comments that are siblings of the documnent
element.
*/
public final var children: [Node] = []
/// The `attributes` dictionary of a `Document` is `nil`.
public final let attributes: [String : String]? = nil
// MARK: Document
/**
This is a convenience attribute that allows direct access to the child node
that is the root element of the document.
*/
public final var documentElement: Element? {
return children.first(ofType: Element.self)
}
/**
Creates a new `Document` node.
*/
public init() { }
}
// MARK: - Element
/**
By far the vast majority of objects (apart from text) that authors encounter
when traversing a document are Element nodes. Assume the following XML
document:
```xml
<elementExample id="demo">
<subelement1/>
<subelement2><subsubelement/></subelement2>
</elementExample>
```
When represented using the DOM, the top node is an `Element` node for
`elementExample`, which contains two child `Element` nodes, one for
`subelement1` and one for `subelement2`. `subelement1` contains no child
nodes.
Elements may have attributes associated with them; since the `Element` class
implements the `Node` protocol, the `attributes` property of the `Node`
protocol may be used to retrieve a dictionary of the attributes for an element.
*/
public final class Element: ParentNode {
// MARK: Node
/// The `nodeType` of an `Element` is `.element`.
public static let nodeType: NodeType = .element
/// The `nodeName` of an `Element` is its `tagName`.
public final var nodeName: String {
return tagName
}
/// The `nodeValue` of an `Element` is `nil`.
public final let nodeValue: String? = nil
/// The children of the element.
public final var children: [Node]
// MARK: Element
/**
The name of the element. For example, in:
```xml
<elementExample id="demo">
...
</elementExample>
```
`tagName` has the value `"elementExample"`.
*/
public final var tagName: String
/**
A dictionary that contains any attributes associated with the element.
Keys are the names of attributes, and values are attribute values.
*/
public final var attributes: [String : String]?
/**
If an element has only a single child, and that child is a text node,
return that text node's value. Otherwise, return nil. It is recommended
first to normalize the document or this element (see `Node.normalize()`).
This method will return the text as it is represented in the single child
text node. Whitespace will not be stripped or normalized (see
`String.trimmed` and `String.normalized`).
*/
public final var textValue: String? {
if children.count == 1 && firstChild?.nodeType == .text {
return firstChild?.nodeValue
}
return nil
}
// MARK: Initializer
/**
Creates a new `Element` node.
- parameter tagName: A string that is the name of an element (in its start
tag).
- parameter attributes: A dictionary that contains any attributes
associated with the element. Keys are the names of attributes, and values
are attribute values.
*/
public init(tagName: String, attributes: [String : String] = [:], children: [Node] = []) {
self.tagName = tagName
self.attributes = attributes
self.children = children
}
}
// MARK: - Text
/**
The `Text` class represents the textual content (termed character data in XML)
of an `Element`. If there is no markup inside an element's content, the text is
contained in a single object implementing the `Text` protocol that is the only
child of the element. If there is markup, it is parsed into a sequence of
elements and `Text` nodes that form the array of children of the element.
*/
public final class Text: TextNode {
// MARK: Node
/// The `nodeType` of a `Text` node is `.text`.
public static let nodeType: NodeType = .text
/// The `nodeName` of a `Text` node is `#text`.
public final let nodeName: String = "#text"
/// The `attributes` dictionary of a `Text` node is `nil`.
public final let attributes: [String : String]? = nil
// MARK: TextNode
/// The string contents of this text node.
public final var text: String
// MARK: Initializer
/**
Creates a new `Text` node.
- parameter text: The string contents of this text node.
*/
public init(text: String) {
self.text = text
}
final func append(_ other: Text) {
text = text + other.text
}
}
// MARK: - ProcessingInstruction
/**
The `ProcessingInstruction` class represents a "processing instruction", used
in XML as a way to keep processor-secific information in the text of the
document.
*/
public final class ProcessingInstruction: LeafNode {
// MARK: Node
/// The `nodeType` of a `ProcessingInstruction` is `.processingInstruction`.
public static let nodeType: NodeType = .processingInstruction
/// The `nodeName` of a `ProcessingInstruction` is its `target`.
public final var nodeName: String {
return target
}
/// The `nodeValue` of a `ProcessingInstruction` is its `data`.
public final var nodeValue: String? {
return data
}
/// The `attributes` dictionary of a `ProcessingInstruction` is `nil`.
public final let attributes: [String : String]? = nil
// MARK: ProcessingInstruction
/**
The target of this processing instruction. XML defines this as being the
first token following the `<?` that begins the processing instruction.
*/
public final var target: String
/**
The content of this processing instruction. This is from the first
non-whitespace character after the target to the character immediately
preceding the `?>`.
*/
public final var data: String?
// MARK: Initializer
/**
Creates a new `ProcessingInstruction' node.
- parameter target: The target of this processing instruction. XML defines
this as being the first token following the `<?` that begins the processing
instruction.
- parameter data: The content of this processing instruction. This is from
the first non-whitespace character after the target to the character
immediately preceding the `?>`.
*/
public init(target: String, data: String?) {
self.target = target
self.data = data
}
}
// MARK: - Comment
/**
This represents the content of a comment, i.e., all the characters between the
starting `<!--` and ending `-->`.
*/
public final class Comment: TextNode {
// MARK: Node
/// The `nodeType` of a `Comment` is `.comment`.
public static let nodeType: NodeType = .comment
/// The `nodeName` of a `Comment` is `#comment`.
public final let nodeName: String = "#comment"
/// The `attributes` dictionary of a `Comment` is `nil`.
public final let attributes: [String : String]? = nil
// MARK: TextNode
/// The string contents of this comment.
public final var text: String
// MARK: Initializer
/**
Creates a new `Comment` node.
- parameter text: The string contents of this comment.
*/
public init(text: String) {
self.text = text
}
}
// MARK: - CDATASection
/**
CDATA sections are used to escape blocks of text containing characters that
would otherwise be regarded as markup. The only delimiter that is recognized
in a CDATA section is the `"]]>"` string that ends the CDATA section. CDATA
sections can not be nested. The primary purpose is for including material such
as XML fragments, without needing to escape all the delimiters.
The `text` property holds the text that is contained by the CDATA section.
Note that this may contain characters that need to be escaped outside of CDATA
sections.
*/
public final class CDATASection: TextNode {
// MARK: Node
/// The `nodeType` of a `CDATASection` is `.cdataSection`.
public static let nodeType: NodeType = .cdataSection
/// The `nodeName` of a `CDATASection` is `#cdata-section`.
public final let nodeName: String = "#cdata-section"
/// The `attributes` dictionary of a `CDATASection` is `nil`.
public final let attributes: [String : String]? = nil
// MARK: TextNode
/// The string contents of this CDATA section.
public final var text: String
// MARK: Initializer
/**
Creates a new `CDATASection node.
- parameter text: The string contents of this CDATA secion.
*/
public init(text: String) {
self.text = text
}
}
| mit | 16d6cfd663f0b39c138027ff67cb96c8 | 30.61838 | 118 | 0.673531 | 4.3635 | false | false | false | false |
macc704/iKF | iKF/KFHttpConnection.swift | 1 | 939 | //
// KFHttpConnection.swift
// iKF
//
// Created by Yoshiaki Matsuzawa on 2014-07-23.
// Copyright (c) 2014 Yoshiaki Matsuzawa. All rights reserved.
//
import UIKit
class KFHttpConnection: NSObject {
class func connect(req: KFHttpRequest) -> KFHttpResponse{
if(req.nsRequest.URL != nil){
KFAppUtils.debug("URL='\(req.nsRequest.URL!)'");
}
req.updateParams();
var res :NSURLResponse?
var error :NSError?
KFAppUtils.debug("requestBody='\(req.getBodyAsString())'");
let bodyData = NSURLConnection.sendSynchronousRequest(req.nsRequest, returningResponse: &res, error: &error);
let kfres = KFHttpResponse();
kfres.res = res as? NSHTTPURLResponse;
kfres.error = error;
kfres.bodyData = bodyData;
KFAppUtils.debug("statusCode='\(kfres.getStatusCode())'");
return kfres;
}
}
| gpl-2.0 | dc710938bc47df67e47ef97da8f2ddb8 | 27.454545 | 117 | 0.609159 | 4.210762 | false | false | false | false |
sudiptasahoo/IVP-Luncheon | IVP Luncheon/SSExtensions.swift | 1 | 5242 | //
// SSExtensions.swift
// IVP Luncheon
//
// Created by Sudipta Sahoo on 24/05/17.
// Copyright © 2017 Sudipta Sahoo <[email protected]>. This file is part of Indus Valley Partners interview process. This file can not be copied and/or distributed without the express permission of Sudipta Sahoo. All rights reserved.
//
import UIKit
import RealmSwift
enum SSFont {
case helveticaMedium
case helveticaMediumItalic
case helveticaLight
case helveticaRegular
}
extension URLComponents{
mutating func appendQueryItem(name: String, value: String) {
var queryItems: [URLQueryItem] = self.queryItems ?? [URLQueryItem]()
queryItems.append(NSURLQueryItem(name: name, value: value) as URLQueryItem)
self.queryItems = queryItems as [URLQueryItem]
}
mutating func appendQueryItems(_ additionalQueryItems : [URLQueryItem]) {
var queryItems: [URLQueryItem] = self.queryItems ?? [URLQueryItem]()
queryItems.append(contentsOf: additionalQueryItems)
self.queryItems = queryItems as [URLQueryItem]
}
}
extension UIFont{
convenience init(font: SSFont, size: CGFloat){
switch font {
case .helveticaMedium:
self.init(name: "HelveticaNeue-Medium", size: size)!
case .helveticaLight:
self.init(name: "HelveticaNeue-Light", size: size)!
case .helveticaRegular:
self.init(name: "HelveticaNeue", size: size)!
case .helveticaMediumItalic:
self.init(name: "HelveticaNeue-MediumItalic", size: size)!
}
}
}
extension UIColor {
convenience init(hexString: String) {
var cString:String = hexString.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
let hex = cString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.characters.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (255, 0, 0, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
extension UIViewController {
func setTabBarVisible(visible: Bool, animated: Bool) {
//* This cannot be called before viewDidLayoutSubviews(), because the frame is not set before this time
// bail if the current state matches the desired state
if (isTabBarVisible == visible) { return }
// get a frame calculation ready
let frame = self.tabBarController?.tabBar.frame
let height = frame?.size.height
let offsetY = (visible ? -height! : height)
// zero duration means no animation
let duration: TimeInterval = (animated ? 0.3 : 0.0)
// animate the tabBar
if frame != nil {
UIView.animate(withDuration: duration) {
self.tabBarController?.tabBar.frame = frame!.offsetBy(dx: 0, dy: offsetY!)
return
}
}
}
var isTabBarVisible: Bool {
return (self.tabBarController?.tabBar.frame.origin.y ?? 0) < self.view.frame.maxY
}
}
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView {
func loadImageUsingCacheWithURL(url: String) {
//Placehlder Image
self.image = UIImage(named: "placeholder")
// First check if there is an image in the cache
if let cachedImage = imageCache.object(forKey: url as AnyObject) as? UIImage {
self.image = cachedImage
return
}
else {
// Otherwise download image using the url
SSCommonUtilities.addTaskToNetworkQueue()
URLSession.shared.dataTask( with: URL(string: url)!, completionHandler: { (data, response, error) in
SSCommonUtilities.removeTaskFromNetworkQueue()
if error != nil {
//Scope for retrying download
print(error!)
}
else {
DispatchQueue.main.async(execute: {
// Cache to image so it doesn't need to be reloaded every time the user scrolls and table cells are re-used.
if let downloadedImage = UIImage(data: data!) {
imageCache.setObject(downloadedImage, forKey: url as String as AnyObject)
UIView.transition(with: self,
duration: 0.3,
options: .transitionCrossDissolve,
animations: {
self.image = downloadedImage
},
completion: nil)
}
})
}
}).resume()
}
}
}
extension Results {
func toArray<T>(ofType: T.Type) -> [T] {
var array = [T]()
for i in 0 ..< count {
if let result = self[i] as? T {
array.append(result)
}
}
return array
}
}
| apache-2.0 | e3e0f60bf45499f0452da2505a95e28a | 28.44382 | 236 | 0.603892 | 4.254058 | false | false | false | false |
KingAce023/DreamChasers | Navigate/DetailViewController.swift | 1 | 4029 | //
// DetailViewController.swift
// SearchBar
//
// Created by Shinkangsan on 1/23/17.
// Copyright © 2017 Sheldon. All rights reserved.
//
import UIKit
import Firebase
class DetailViewController: UIViewController {
//from prev controller
var dataModel:Model!
//-----------VARIABLES---------------------
//IBOutlets
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var imageNameLabel: UILabel!
@IBOutlet weak var yearLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var partAdded: UILabel!
//<<<<<<< HEAD
//-------- ADD TO INVENTORY BUTTON -------
@IBAction func invList(_ sender: UIButton) {
// get current user id
let user = Auth.auth().currentUser?.uid
// add part to current user's inventory
self.dbref?.child("Users").child(user!).child("repairs").childByAutoId().setValue(imageNameLabel.text)
// show part added message
self.partAdded.isHidden = false
GlobalVariable.inventoryList.append(imageNameLabel.text!)
//---- ADD TO CGRect ARRAY AND MAKES SURE THERE IS NO DUPLICATES (TEMPORARY SOLUTION) --------------------------
if (imageNameLabel.text == "battery"){
if !(GlobalVariable.car1.contains(CGRect(x:50, y: 50, width:50, height:50))) {
GlobalVariable.car1.append(CGRect(x: 50, y: 50, width: 50, height: 50))
}
}
else if (imageNameLabel.text == "breakPads"){
if !(GlobalVariable.car1.contains(CGRect(x: 340, y: 60, width: 40, height: 40))) {
GlobalVariable.car1.append(CGRect(x: 340, y: 60, width: 40, height: 40))
}
}
else if (imageNameLabel.text == "tire"){
if !(GlobalVariable.car1.contains(CGRect(x: 170, y: 90, width: 50, height: 40))) {
GlobalVariable.car1.append(CGRect(x: 170, y: 90, width: 50, height: 40))
}
}
else if (imageNameLabel.text == "muffler"){
if !(GlobalVariable.car1.contains(CGRect(x: 270, y: 60, width: 20, height: 20))) {
GlobalVariable.car1.append(CGRect(x: 270, y: 60, width: 20, height: 20))
}
}
else if (imageNameLabel.text == "sparkPlug"){
if !(GlobalVariable.car1.contains(CGRect(x: 120, y: 85, width: 40, height: 20))) {
GlobalVariable.car1.append(CGRect(x: 120, y: 85, width: 40, height: 20))
}
}
//--------------------------------------------------------------------------------
//--------------This will reload the main page again----------------
let mainStoryBoard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let desViewController = mainStoryBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
let newFrontViewController = UINavigationController.init(rootViewController:desViewController)
revealViewController().pushFrontViewController(newFrontViewController, animated: true)
//------------------------------------------------------------------
}
// get Firebase reference
var dbref: DatabaseReference?
//------------ MAIN --------------------
override func viewDidLoad() {
super.viewDidLoad()
// get instance of firebase reference
dbref = Database.database().reference()
imageNameLabel.text = dataModel.imageName
yearLabel.text = dataModel.imageYear
priceLabel.text = dataModel.imagePrice
self.partAdded.isHidden = true
partAdded.text = "Part Added!"
imageView.image = UIImage(named: dataModel.imageName)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//--------Declaring a global variable-----------
struct GlobalVariable{
static var inventoryList = [String]()
static var car1 = [CGRect]()
}
}
| mit | 8fbbb99d2bcbec0d9e76e121f7a1fa72 | 37 | 125 | 0.578451 | 4.722157 | false | false | false | false |
xeo-it/poggy | Pods/OAuthSwift/OAuthSwift/OAuth2Swift.swift | 1 | 15326 | //
// OAuth2Swift.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/22/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import Foundation
public class OAuth2Swift: OAuthSwift {
// If your oauth provider need to use basic authentification
// set value to true (default: false)
public var accessTokenBasicAuthentification = false
// Set to true to deactivate state check. Be careful of CSRF
public var allowMissingStateCheck: Bool = false
var consumer_key: String
var consumer_secret: String
var authorize_url: String
var access_token_url: String?
var response_type: String
var content_type: String?
// MARK: init
public convenience init(consumerKey: String, consumerSecret: String, authorizeUrl: String, accessTokenUrl: String, responseType: String){
self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, authorizeUrl: authorizeUrl, responseType: responseType)
self.access_token_url = accessTokenUrl
}
public convenience init(consumerKey: String, consumerSecret: String, authorizeUrl: String, accessTokenUrl: String, responseType: String, contentType: String){
self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, authorizeUrl: authorizeUrl, responseType: responseType)
self.access_token_url = accessTokenUrl
self.content_type = contentType
}
public init(consumerKey: String, consumerSecret: String, authorizeUrl: String, responseType: String){
self.consumer_key = consumerKey
self.consumer_secret = consumerSecret
self.authorize_url = authorizeUrl
self.response_type = responseType
super.init(consumerKey: consumerKey, consumerSecret: consumerSecret)
self.client.credential.version = .OAuth2
}
public convenience init?(parameters: [String:String]){
guard let consumerKey = parameters["consumerKey"], consumerSecret = parameters["consumerSecret"],
responseType = parameters["responseType"], authorizeUrl = parameters["authorizeUrl"] else {
return nil
}
if let accessTokenUrl = parameters["accessTokenUrl"] {
self.init(consumerKey:consumerKey, consumerSecret: consumerSecret,
authorizeUrl: authorizeUrl, accessTokenUrl: accessTokenUrl, responseType: responseType)
} else {
self.init(consumerKey:consumerKey, consumerSecret: consumerSecret,
authorizeUrl: authorizeUrl, responseType: responseType)
}
}
public var parameters: [String: String] {
return [
"consumerKey": consumer_key,
"consumerSecret": consumer_secret,
"authorizeUrl": authorize_url,
"accessTokenUrl": access_token_url ?? "",
"responseType": response_type
]
}
// MARK: functions
public func authorizeWithCallbackURL(callbackURL: NSURL, scope: String, state: String, params: [String: String] = [String: String](), headers: [String:String]? = nil, success: TokenSuccessHandler, failure: ((error: NSError) -> Void)) {
self.observeCallback { [weak self] url in
guard let this = self else {return }
var responseParameters = [String: String]()
if let query = url.query {
responseParameters += query.parametersFromQueryString()
}
if let fragment = url.fragment where !fragment.isEmpty {
responseParameters += fragment.parametersFromQueryString()
}
if let accessToken = responseParameters["access_token"] {
this.client.credential.oauth_token = accessToken.safeStringByRemovingPercentEncoding
if let expiresIn:String = responseParameters["expires_in"], offset = Double(expiresIn) {
this.client.credential.oauth_token_expires_at = NSDate(timeInterval: offset, sinceDate: NSDate())
}
success(credential: this.client.credential, response: nil, parameters: responseParameters)
}
else if let code = responseParameters["code"] {
if !this.allowMissingStateCheck {
guard let responseState = responseParameters["state"] else {
let errorInfo = [NSLocalizedDescriptionKey: "Missing state"]
failure(error: NSError(domain: OAuthSwiftErrorDomain, code: OAuthSwiftErrorCode.MissingStateError.rawValue, userInfo: errorInfo))
return
}
if responseState != state {
let errorInfo = [NSLocalizedDescriptionKey: "state not equals"]
failure(error: NSError(domain: OAuthSwiftErrorDomain, code: OAuthSwiftErrorCode.StateNotEqualError.rawValue, userInfo: errorInfo))
return
}
}
this.postOAuthAccessTokenWithRequestTokenByCode(code.safeStringByRemovingPercentEncoding,
callbackURL:callbackURL, headers: headers , success: success, failure: failure)
}
else if let error = responseParameters["error"], error_description = responseParameters["error_description"] {
let errorInfo = [NSLocalizedFailureReasonErrorKey: NSLocalizedString(error, comment: error_description)]
failure(error: NSError(domain: OAuthSwiftErrorDomain, code: OAuthSwiftErrorCode.GeneralError.rawValue, userInfo: errorInfo))
}
else {
let errorInfo = [NSLocalizedDescriptionKey: "No access_token, no code and no error provided by server"]
failure(error: NSError(domain: OAuthSwiftErrorDomain, code: OAuthSwiftErrorCode.ServerError.rawValue, userInfo: errorInfo))
}
}
var queryString = "client_id=\(self.consumer_key)"
queryString += "&redirect_uri=\(callbackURL.unsafeAbsoluteString)"
queryString += "&response_type=\(self.response_type)"
if !scope.isEmpty {
queryString += "&scope=\(scope)"
}
if !state.isEmpty {
queryString += "&state=\(state)"
}
for param in params {
queryString += "&\(param.0)=\(param.1)"
}
var urlString = self.authorize_url
urlString += (self.authorize_url.has("?") ? "&" : "?")
if let encodedQuery = queryString.urlQueryEncoded, queryURL = NSURL(string: urlString + encodedQuery) {
self.authorize_url_handler.handle(queryURL)
}
else {
let errorInfo = [NSLocalizedFailureReasonErrorKey: NSLocalizedString("Failed to create URL", comment: "\(urlString) or \(queryString) not convertible to URL, please check encoding")]
failure(error: NSError(domain: OAuthSwiftErrorDomain, code: OAuthSwiftErrorCode.EncodingError.rawValue, userInfo: errorInfo))
}
}
func postOAuthAccessTokenWithRequestTokenByCode(code: String, callbackURL: NSURL, headers: [String:String]? = nil, success: TokenSuccessHandler, failure: FailureHandler?) {
var parameters = Dictionary<String, AnyObject>()
parameters["client_id"] = self.consumer_key
parameters["client_secret"] = self.consumer_secret
parameters["code"] = code
parameters["grant_type"] = "authorization_code"
parameters["redirect_uri"] = callbackURL.unsafeAbsoluteString.safeStringByRemovingPercentEncoding
requestOAuthAccessTokenWithParameters(parameters, headers: headers, success: success, failure: failure)
}
public func renewAccessTokenWithRefreshToken(refreshToken: String, headers: [String:String]? = nil, success: TokenSuccessHandler, failure: FailureHandler?) {
var parameters = Dictionary<String, AnyObject>()
parameters["client_id"] = self.consumer_key
parameters["client_secret"] = self.consumer_secret
parameters["refresh_token"] = refreshToken
parameters["grant_type"] = "refresh_token"
requestOAuthAccessTokenWithParameters(parameters, headers: headers, success: success, failure: failure)
}
private func requestOAuthAccessTokenWithParameters(parameters: [String : AnyObject], headers: [String: String]? = nil, success: TokenSuccessHandler, failure: FailureHandler?) {
let successHandler: OAuthSwiftHTTPRequest.SuccessHandler = { [unowned self]
data, response in
let responseJSON: AnyObject? = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
let responseParameters: [String: AnyObject]
if let jsonDico = responseJSON as? [String:AnyObject] {
responseParameters = jsonDico
} else {
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as String!
responseParameters = responseString.parametersFromQueryString()
}
guard let accessToken = responseParameters["access_token"] as? String else {
if let failure = failure {
let errorInfo = [NSLocalizedFailureReasonErrorKey: NSLocalizedString("Could not get Access Token", comment: "Due to an error in the OAuth2 process, we couldn't get a valid token.")]
failure(error: NSError(domain: OAuthSwiftErrorDomain, code: OAuthSwiftErrorCode.ServerError.rawValue, userInfo: errorInfo))
}
return
}
if let refreshToken = responseParameters["refresh_token"] as? String {
self.client.credential.oauth_refresh_token = refreshToken.safeStringByRemovingPercentEncoding
}
if let expiresIn = responseParameters["expires_in"] as? String, offset = Double(expiresIn) {
self.client.credential.oauth_token_expires_at = NSDate(timeInterval: offset, sinceDate: NSDate())
} else if let expiresIn = responseParameters["expires_in"] as? Double {
self.client.credential.oauth_token_expires_at = NSDate(timeInterval: expiresIn, sinceDate: NSDate())
}
self.client.credential.oauth_token = accessToken.safeStringByRemovingPercentEncoding
success(credential: self.client.credential, response: response, parameters: responseParameters)
}
if self.content_type == "multipart/form-data" {
// Request new access token by disabling check on current token expiration. This is safe because the implementation wants the user to retrieve a new token.
self.client.postMultiPartRequest(self.access_token_url!, method: .POST, parameters: parameters, headers: headers, checkTokenExpiration: false, success: successHandler, failure: failure)
} else {
// special headers
var headers: [String:String]? = nil
if accessTokenBasicAuthentification {
let authentification = "\(self.consumer_key):\(self.consumer_secret)".dataUsingEncoding(NSUTF8StringEncoding)
if let base64Encoded = authentification?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
{
headers = ["Authorization": "Basic \(base64Encoded)"]
}
}
if let access_token_url = access_token_url {
// Request new access token by disabling check on current token expiration. This is safe because the implementation wants the user to retrieve a new token.
self.client.request(access_token_url, method: .POST, parameters: parameters, headers: headers, checkTokenExpiration: false, success: successHandler, failure: failure)
}
else {
let errorInfo = [NSLocalizedFailureReasonErrorKey: NSLocalizedString("access token url not defined", comment: "access token url not defined with code type auth")]
failure?(error: NSError(domain: OAuthSwiftErrorDomain, code: OAuthSwiftErrorCode.GeneralError.rawValue, userInfo: errorInfo))
}
}
}
/**
Convenience method to start a request that must be authorized with the previously retrieved access token.
Since OAuth 2 requires support for the access token refresh mechanism, this method will take care to automatically
refresh the token if needed such that the developer only has to be concerned about the outcome of the request.
- parameter url: The url for the request.
- parameter method: The HTTP method to use.
- parameter parameters: The request's parameters.
- parameter headers: The request's headers.
- parameter onTokenRenewal: Optional callback triggered in case the access token renewal was required in order to properly authorize the request.
- parameter success: The success block. Takes the successfull response and data as parameter.
- parameter failure: The failure block. Takes the error as parameter.
*/
public func startAuthorizedRequest(url: String, method: OAuthSwiftHTTPRequest.Method, parameters: Dictionary<String, AnyObject>, headers: [String:String]? = nil, onTokenRenewal: TokenRenewedHandler? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler, failure: OAuthSwiftHTTPRequest.FailureHandler) {
// build request
self.client.request(url, method: method, parameters: parameters, headers: headers, success: success) { (error) in
switch error.code {
case OAuthSwiftErrorCode.TokenExpiredError.rawValue:
self.renewAccessTokenWithRefreshToken(self.client.credential.oauth_refresh_token, headers: headers, success: { (credential, response, refreshParameters) in
// We have successfully renewed the access token.
// If provided, fire the onRenewal closure
if let renewalCallBack = onTokenRenewal {
renewalCallBack(credential: credential)
}
// Reauthorize the request again, this time with a brand new access token ready to be used.
self.startAuthorizedRequest(url, method: method, parameters: parameters, headers: headers, onTokenRenewal: onTokenRenewal, success: success, failure: failure)
}, failure: failure)
default:
failure(error: error)
}
}
}
public func authorizeDeviceToken(deviceCode: String, success: TokenRenewedHandler, failure: OAuthSwiftHTTPRequest.FailureHandler) {
var parameters = Dictionary<String, AnyObject>()
parameters["client_id"] = self.consumer_key
parameters["client_secret"] = self.consumer_secret
parameters["code"] = deviceCode
parameters["grant_type"] = "http://oauth.net/grant_type/device/1.0"
requestOAuthAccessTokenWithParameters(parameters, success: { (credential, response, parameters) in
success(credential: credential)
}) { (error) in
failure(error: error)
}
}
}
| apache-2.0 | e6a21b31d18d67ce6e01f7df3c9b1ac0 | 55.345588 | 305 | 0.654835 | 5.51295 | false | false | false | false |
ryanbooker/Swiftz | Tests/SwiftzTests/StreamSpec.swift | 1 | 5478 | //
// StreamSpec.swift
// Swiftz
//
// Created by Robert Widmann on 4/10/16.
// Copyright © 2016 TypeLift. All rights reserved.
//
import XCTest
import Swiftz
import SwiftCheck
/*
/// Generates a Swiftz.Stream of arbitrary values.
extension Swiftz.Stream where Element : Arbitrary {
public static var arbitrary : Gen<Swiftz.Stream<Element>> {
return Element.arbitrary.flatMap { x in
return Element.arbitrary.flatMap { y in
return Element.arbitrary.flatMap { z in
return Gen.pure(Swiftz.Stream.cycle([ x, y, z ]))
}
}
}
}
public static func shrink(_ xs : Swiftz.Stream) -> [Swiftz.Stream] {
return []
}
}
extension Swiftz.Stream : WitnessedArbitrary {
public typealias Param = Element
public static func forAllWitnessed<A : Arbitrary>(_ wit : (A) -> Element, pf : ((Swiftz.Stream) -> Testable)) -> Property {
return forAllShrink(Swiftz.Stream<A>.arbitrary, shrinker: Swiftz.Stream<A>.shrink, f: { bl in
return pf(bl.fmap(wit))
})
}
}
class StreamSpec : XCTestCase {
func testProperties() {
property("pure behaves") <- forAll { (i : Int) in
let xs = Swiftz.Stream.pure(i)
return [UInt](1...10).all { n in
return xs[n] == i
}
}
property("Take behaves") <- forAll { (xs : Swiftz.Stream) in
return [UInt](1...10).all { n in
return xs.take(n).count == Int(n)
}
}
property("Interleave behaves") <- forAll { (xs : Swiftz.Stream, ys : Swiftz.Stream) in
return [UInt](1...10).all { n in
let zs = xs.interleaveWith(ys)
return zs[2 * n] == xs[n]
&& zs[2 * n + 1] == ys[n]
}
}
property("Swiftz.Stream obeys the Functor identity law") <- forAll { (x : Swiftz.Stream) in
return forAll { (n : UInt) in
return (x.fmap(identity)).take(n) == identity(x).take(n)
}
}
property("Swiftz.Stream obeys the Functor composition law") <- forAll { (_ f : ArrowOf<Int, Int>, g : ArrowOf<Int, Int>) in
return forAll { (x : Swiftz.Stream<Int>) in
return forAll { (n : UInt) in
return ((f.getArrow • g.getArrow) <^> x).take(n) == (x.fmap(g.getArrow).fmap(f.getArrow)).take(n)
}
}
}
property("Swiftz.Stream obeys the Applicative identity law") <- forAll { (x : Swiftz.Stream) in
return forAll { (n : UInt) in
return (Swiftz.Stream.pure(identity) <*> x).take(n) == x.take(n)
}
}
// Swift unroller can't handle our scale; Use only small lists.
property("Swiftz.Stream obeys the first Applicative composition law") <- forAll { (fl : Swiftz.Stream, gl : Swiftz.Stream, x : Swiftz.Stream) in
return forAll { (n : UInt) in
let f = fl.fmap({ $0.getArrow })
let g = gl.fmap({ $0.getArrow })
return (curry(•) <^> f <*> g <*> x).take(n) == (f <*> (g <*> x)).take(n)
}
}
property("Swiftz.Stream obeys the second Applicative composition law") <- forAll { (fl : Swiftz.Stream, gl : Swiftz.Stream, x : Swiftz.Stream) in
return forAll { (n : UInt) in
let f = fl.fmap({ $0.getArrow })
let g = gl.fmap({ $0.getArrow })
return (Swiftz.Stream.pure(curry(•)) <*> f <*> g <*> x).take(n) == (f <*> (g <*> x)).take(n)
}
}
/// These three take *forever* to execute. It's scary how much stack
/// space it takes to force these Swiftz.Streams.
property("Swiftz.Stream obeys the Monad left identity law") <- forAll { (a : Int, fa : ArrowOf<Int, Int>) in
let f : (Int) -> Swiftz.Stream<Int> = Swiftz.Stream<Int>.pure • fa.getArrow
return forAll { (n : UInt) in
return (Swiftz.Stream<Int>.pure(a) >>- f).take(n) == f(a).take(n)
}
}.once
property("Swiftz.Stream obeys the Monad right identity law") <- forAll { (m : Swiftz.Stream) in
return forAll { (n : UInt) in
return (m >>- Swiftz.Stream<Int>.pure).take(n) == m.take(n)
}
}.once
property("Swiftz.Stream obeys the Monad associativity law") <- forAll { (fa : ArrowOf<Int, Int>, ga : ArrowOf<Int, Int>) in
let f : (Int) -> Swiftz.Stream<Int> = Swiftz.Stream<Int>.pure • fa.getArrow
let g : (Int) -> Swiftz.Stream<Int> = Swiftz.Stream<Int>.pure • ga.getArrow
return forAll { (m : Swiftz.Stream<Int>) in
return forAll { (n : UInt) in
return ((m >>- f) >>- g).take(n) == (m >>- { x in f(x) >>- g }).take(n)
}
}
}.once
property("Swiftz.Stream obeys the Comonad identity law") <- forAll { (x : Swiftz.Stream) in
return forAll { (n : UInt) in
return x.extend({ $0.extract() }).take(n) == x.take(n)
}
}
property("Swiftz.Stream obeys the Comonad composition law") <- forAll { (ff : ArrowOf<Int, Int>) in
return forAll { (x : Identity<Int>) in
return forAll { (n : UInt) in
let f : (Identity<Int>) -> Int = ff.getArrow • { $0.runIdentity }
return x.extend(f).extract() == f(x)
}
}
}
property("Swiftz.Stream obeys the Comonad composition law") <- forAll { (ff : ArrowOf<Int, Int>, gg : ArrowOf<Int, Int>) in
return forAll { (x : Swiftz.Stream<Int>) in
let f : (Swiftz.Stream<Int>) -> Int = ff.getArrow • { $0.head }
let g : (Swiftz.Stream<Int>) -> Int = gg.getArrow • { $0.head }
return forAll { (n : UInt) in
return x.extend(f).extend(g).take(n) == x.extend({ g($0.extend(f)) }).take(n)
}
}
}
property("sequence occurs in order") <- forAll { (xs : [String]) in
let seq = sequence(xs.map({ x in Swiftz.Stream.pure(x).take(1) }))
return forAllNoShrink(Gen.pure(seq)) { ss in
return ss.first ?? [] == xs
}
}
}
}
*/
| bsd-3-clause | 4d03f12093d848744081ac181c327fc2 | 32.490798 | 147 | 0.599194 | 3.128367 | false | false | false | false |
jokechat/swift3-novel | swift_novels/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationLineSpinFadeLoader.swift | 8 | 2974 | //
// NVActivityIndicatorAnimationLineSpinFadeLoader.swift
// NVActivityIndicatorViewDemo
//
// Created by Nguyen Vinh on 7/25/15.
// Copyright (c) 2015 Nguyen Vinh. All rights reserved.
//
import UIKit
class NVActivityIndicatorAnimationLineSpinFadeLoader: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let lineSpacing: CGFloat = 2
let lineSize = CGSize(width: (size.width - 4 * lineSpacing) / 5, height: (size.height - 2 * lineSpacing) / 3)
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let duration: CFTimeInterval = 1.2
let beginTime = CACurrentMediaTime()
let beginTimes: [CFTimeInterval] = [0.12, 0.24, 0.36, 0.48, 0.6, 0.72, 0.84, 0.96]
let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
// Animation
let animation = CAKeyframeAnimation(keyPath: "opacity")
animation.keyTimes = [0, 0.5, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.3, 1]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw lines
for i in 0 ..< 8 {
let line = lineAt(angle: CGFloat(M_PI_4 * Double(i)),
size: lineSize,
origin: CGPoint(x: x, y: y),
containerSize: size,
color: color)
animation.beginTime = beginTime + beginTimes[i]
line.add(animation, forKey: "animation")
layer.addSublayer(line)
}
}
func lineAt(angle: CGFloat, size: CGSize, origin: CGPoint, containerSize: CGSize, color: UIColor) -> CALayer {
let radius = containerSize.width / 2 - max(size.width, size.height) / 2
let lineContainerSize = CGSize(width: max(size.width, size.height), height: max(size.width, size.height))
let lineContainer = CALayer()
let lineContainerFrame = CGRect(
x: origin.x + radius * (cos(angle) + 1),
y: origin.y + radius * (sin(angle) + 1),
width: lineContainerSize.width,
height: lineContainerSize.height)
let line = NVActivityIndicatorShape.line.layerWith(size: size, color: color)
let lineFrame = CGRect(
x: (lineContainerSize.width - size.width) / 2,
y: (lineContainerSize.height - size.height) / 2,
width: size.width,
height: size.height)
lineContainer.frame = lineContainerFrame
line.frame = lineFrame
lineContainer.addSublayer(line)
lineContainer.sublayerTransform = CATransform3DMakeRotation(CGFloat(M_PI_2) + angle, 0, 0, 1)
return lineContainer
}
}
| apache-2.0 | 171cff75068eefa05ba705deb593aad9 | 41.485714 | 117 | 0.603228 | 4.56135 | false | false | false | false |
mohssenfathi/MTLImage | MTLImage/Sources/Filters/WhiteBalance.swift | 1 | 1224 | //
// WhiteBalance.swift
// Pods
//
// Created by Mohssen Fathi on 4/2/16.
//
//
import UIKit
struct WhiteBalanceUniforms: Uniforms {
var temperature: Float = 0.5;
var tint: Float = 0.5;
}
public
class WhiteBalance: Filter {
var uniforms = WhiteBalanceUniforms()
@objc public var temperature: Float = 0.5 {
didSet {
clamp(&temperature, low: 0, high: 1)
needsUpdate = true
}
}
@objc public var tint: Float = 0.5 {
didSet {
clamp(&tint, low: 0, high: 1)
needsUpdate = true
}
}
public init() {
super.init(functionName: "whiteBalance")
title = "White Balance"
properties = [Property(key: "temperature", title: "Temperature"),
Property(key: "tint" , title: "Tint" )]
update()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func update() {
if self.input == nil { return }
uniforms.temperature = temperature * 2.0 - 1.0
uniforms.tint = tint * 4.0 - 2.0
updateUniforms(uniforms: uniforms)
}
}
| mit | 0d6889465887d25ecff5876e5db27676 | 22.09434 | 73 | 0.529412 | 4.08 | false | false | false | false |
SoneeJohn/WWDC | ThrowBack/TBSession.swift | 1 | 1159 | //
// TBSession.swift
// WWDC
//
// Created by Guilherme Rambo on 13/05/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Foundation
import RealmSwift
internal struct TBSession {
let identifier: String
let isFavorite: Bool
let isDownloaded: Bool
let position: Double
let relativePosition: Double
init?(_ migrationObject: MigrationObject?) {
guard let obj = migrationObject else { return nil }
guard var identifier = obj["uniqueId"] as? String else {
return nil
}
identifier = identifier.replacingOccurrences(of: "#", with: "")
guard let isFavorite = obj["favorite"] as? Bool else { return nil }
guard let isDownloaded = obj["downloaded"] as? Bool else { return nil }
guard let position = obj["currentPosition"] as? Double else { return nil }
guard let relativePosition = obj["progress"] as? Double else { return nil }
self.identifier = identifier
self.isFavorite = isFavorite
self.position = position
self.relativePosition = relativePosition
self.isDownloaded = isDownloaded
}
}
| bsd-2-clause | 0fcfcad3921787c1466f62397173c4df | 27.243902 | 83 | 0.653713 | 4.865546 | false | false | false | false |
suncry/MLHybrid | Example/Pods/Kingfisher/Sources/ImagePrefetcher.swift | 2 | 11828 | //
// ImagePrefetcher.swift
// Kingfisher
//
// Created by Claire Knight <[email protected]> on 24/02/2016
//
// Copyright (c) 2017 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
/// Progress update block of prefetcher.
///
/// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
/// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all.
/// - `completedResources`: An array of resources that are downloaded and cached successfully.
public typealias PrefetcherProgressBlock = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> ())
/// Completion block of prefetcher.
///
/// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
/// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all.
/// - `completedResources`: An array of resources that are downloaded and cached successfully.
public typealias PrefetcherCompletionHandler = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> ())
/// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs, then caching them.
/// This is useful when you know a list of image resources and want to download them before showing.
public class ImagePrefetcher {
/// The maximum concurrent downloads to use when prefetching images. Default is 5.
public var maxConcurrentDownloads = 5
private let prefetchResources: [Resource]
private let optionsInfo: KingfisherOptionsInfo
private var progressBlock: PrefetcherProgressBlock?
private var completionHandler: PrefetcherCompletionHandler?
private var tasks = [URL: RetrieveImageDownloadTask]()
private var pendingResources: ArraySlice<Resource>
private var skippedResources = [Resource]()
private var completedResources = [Resource]()
private var failedResources = [Resource]()
private var stopped = false
// The created manager used for prefetch. We will use the helper method in manager.
private let manager: KingfisherManager
private var finished: Bool {
return failedResources.count + skippedResources.count + completedResources.count == prefetchResources.count && self.tasks.isEmpty
}
/**
Init an image prefetcher with an array of URLs.
The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable.
After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process.
The images already cached will be skipped without downloading again.
- parameter urls: The URLs which should be prefetched.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled.
- parameter completionHandler: Called when the whole prefetching process finished.
- returns: An `ImagePrefetcher` object.
- Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
the downloader and cache target respectively. You can specify another downloader or cache by using a customized `KingfisherOptionsInfo`.
Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method.
*/
public convenience init(urls: [URL],
options: KingfisherOptionsInfo? = nil,
progressBlock: PrefetcherProgressBlock? = nil,
completionHandler: PrefetcherCompletionHandler? = nil)
{
let resources: [Resource] = urls.map { $0 }
self.init(resources: resources, options: options, progressBlock: progressBlock, completionHandler: completionHandler)
}
/**
Init an image prefetcher with an array of resources.
The prefetcher should be initiated with a list of prefetching targets. The resources list is immutable.
After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process.
The images already cached will be skipped without downloading again.
- parameter resources: The resources which should be prefetched. See `Resource` type for more.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled.
- parameter completionHandler: Called when the whole prefetching process finished.
- returns: An `ImagePrefetcher` object.
- Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
the downloader and cache target respectively. You can specify another downloader or cache by using a customized `KingfisherOptionsInfo`.
Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method.
*/
public init(resources: [Resource],
options: KingfisherOptionsInfo? = nil,
progressBlock: PrefetcherProgressBlock? = nil,
completionHandler: PrefetcherCompletionHandler? = nil)
{
prefetchResources = resources
pendingResources = ArraySlice(resources)
// We want all callbacks from main queue, so we ignore the call back queue in options
let optionsInfoWithoutQueue = options?.removeAllMatchesIgnoringAssociatedValue(.callbackDispatchQueue(nil))
self.optionsInfo = optionsInfoWithoutQueue ?? KingfisherEmptyOptionsInfo
let cache = self.optionsInfo.targetCache
let downloader = self.optionsInfo.downloader
manager = KingfisherManager(downloader: downloader, cache: cache)
self.progressBlock = progressBlock
self.completionHandler = completionHandler
}
/**
Start to download the resources and cache them. This can be useful for background downloading
of assets that are required for later use in an app. This code will not try and update any UI
with the results of the process.
*/
public func start()
{
// Since we want to handle the resources cancellation in main thread only.
DispatchQueue.main.safeAsync {
guard !self.stopped else {
assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.")
self.handleComplete()
return
}
guard self.maxConcurrentDownloads > 0 else {
assertionFailure("There should be concurrent downloads value should be at least 1.")
self.handleComplete()
return
}
guard self.prefetchResources.count > 0 else {
self.handleComplete()
return
}
let initialConcurentDownloads = min(self.prefetchResources.count, self.maxConcurrentDownloads)
for _ in 0 ..< initialConcurentDownloads {
if let resource = self.pendingResources.popFirst() {
self.startPrefetching(resource)
}
}
}
}
/**
Stop current downloading progress, and cancel any future prefetching activity that might be occuring.
*/
public func stop() {
DispatchQueue.main.safeAsync {
if self.finished { return }
self.stopped = true
self.tasks.values.forEach { $0.cancel() }
}
}
func downloadAndCache(_ resource: Resource) {
let downloadTaskCompletionHandler: CompletionHandler = { (image, error, _, _) -> () in
self.tasks.removeValue(forKey: resource.downloadURL)
if let _ = error {
self.failedResources.append(resource)
} else {
self.completedResources.append(resource)
}
self.reportProgress()
if self.stopped {
if self.tasks.isEmpty {
self.failedResources.append(contentsOf: self.pendingResources)
self.handleComplete()
}
} else {
DispatchQueue.main.async {
self.reportCompletionOrStartNext()
}
}
}
let downloadTask = manager.downloadAndCacheImage(
with: resource.downloadURL,
forKey: resource.cacheKey,
retrieveImageTask: RetrieveImageTask(),
progressBlock: nil,
completionHandler: downloadTaskCompletionHandler,
options: optionsInfo)
if let downloadTask = downloadTask {
tasks[resource.downloadURL] = downloadTask
}
}
func append(cached resource: Resource) {
skippedResources.append(resource)
reportProgress()
reportCompletionOrStartNext()
}
func startPrefetching(_ resource: Resource)
{
if optionsInfo.forceRefresh {
downloadAndCache(resource)
} else {
let alreadyInCache = manager.cache.imageCachedType(forKey: resource.cacheKey,
processorIdentifier: optionsInfo.processor.identifier).cached
if alreadyInCache {
append(cached: resource)
} else {
downloadAndCache(resource)
}
}
}
func reportProgress() {
progressBlock?(skippedResources, failedResources, completedResources)
}
func reportCompletionOrStartNext() {
if let resource = pendingResources.popFirst() {
startPrefetching(resource)
} else {
guard tasks.isEmpty else { return }
handleComplete()
}
}
func handleComplete() {
completionHandler?(skippedResources, failedResources, completedResources)
completionHandler = nil
progressBlock = nil
}
}
| mit | 20deb03b6be08075b03524dd40342463 | 43.466165 | 209 | 0.666469 | 5.722303 | false | false | false | false |
alskipp/Monoid | Monoid/Monoids/SumMonoid.swift | 1 | 708 | // Copyright © 2016 Al Skipp. All rights reserved.
public struct Sum<T: NumberType> {
public let value: T
public init(_ v: T) { value = v }
}
extension Sum: Monoid {
public static var mempty: Sum {
return Sum(T.zero)
}
public static func combine(_ a: Sum, _ b: Sum) -> Sum {
return Sum(a.value + b.value)
}
}
extension Sum: CustomStringConvertible {
public var description: String {
return "Sum(\(value))"
}
}
extension Sum: Equatable, Comparable, Orderable {
public static func == <N: NumberType>(x: Sum<N>, y: Sum<N>) -> Bool {
return x.value == y.value
}
public static func < <N: NumberType>(x: Sum<N>, y: Sum<N>) -> Bool {
return x.value < y.value
}
}
| mit | a24b26d833c007ec4a1ebb5fc4482036 | 21.09375 | 71 | 0.622348 | 3.258065 | false | false | false | false |
eface2face/cordova-plugin-iosrtc | src/PluginRTCRtpTransceiver.swift | 2 | 6415 | import Foundation
class PluginRTCRtpTransceiver : NSObject {
// NOTE: ID used to reference this native transceiver from JS.
var id: Int
var rtcRtpTransceiver: RTCRtpTransceiver?
var pluginRTCRtpReceiver: PluginRTCRtpReceiver?
var pluginRTCRtpSender: PluginRTCRtpSender?
init(_ rtcRtpTransceiver: RTCRtpTransceiver) {
NSLog("PluginRTCRtpTransceiver#init(rtcRtpTransceiver)")
// TODO: Using random ID could cause conflicts.
self.id = Int.random(in: 0...10000)
self.rtcRtpTransceiver = rtcRtpTransceiver
self.pluginRTCRtpSender = PluginRTCRtpSender(rtcRtpTransceiver.sender, 0)
self.pluginRTCRtpReceiver = PluginRTCRtpReceiver(rtcRtpTransceiver.receiver, 0)
super.init()
}
init(
rtcPeerConnection: RTCPeerConnection,
mediaType: RTCRtpMediaType,
options: NSDictionary?,
transceiverId: Int,
senderId: Int,
receiverId: Int
) {
NSLog("PluginRTCRtpTransceiver#init(mediaType)")
let rtcRtpTransceiverInit = PluginRTCRtpTransceiver.initFromOptionsDictionary(options)
self.id = transceiverId != 0 ? transceiverId : Int.random(in: 0...10000)
self.rtcRtpTransceiver = rtcPeerConnection.addTransceiver(of: mediaType, init: rtcRtpTransceiverInit)
if self.rtcRtpTransceiver == nil {
NSLog("PluginRTCRtpTransceiver#init(mediaType) | rtcPeerConnection.addTransceiver() failed")
} else {
if self.rtcRtpTransceiver?.sender != nil {
self.pluginRTCRtpSender = PluginRTCRtpSender(self.rtcRtpTransceiver!.sender, senderId)
}
if self.rtcRtpTransceiver?.receiver != nil {
self.pluginRTCRtpReceiver = PluginRTCRtpReceiver(self.rtcRtpTransceiver!.receiver, receiverId)
}
}
super.init()
}
init(
rtcPeerConnection: RTCPeerConnection,
mediaStreamTrack: RTCMediaStreamTrack,
options: NSDictionary?,
transceiverId: Int,
senderId: Int,
receiverId: Int
) {
NSLog("PluginRTCRtpTransceiver#init(mediaStreamTrack)")
let rtcRtpTransceiverInit = PluginRTCRtpTransceiver.initFromOptionsDictionary(options)
self.id = transceiverId != 0 ? transceiverId : Int.random(in: 0...10000)
self.rtcRtpTransceiver = rtcPeerConnection.addTransceiver(with: mediaStreamTrack, init: rtcRtpTransceiverInit)
if self.rtcRtpTransceiver == nil {
NSLog("PluginRTCRtpTransceiver#init(mediaStream) | rtcPeerConnection.addTransceiver() failed")
} else {
if self.rtcRtpTransceiver?.sender != nil {
self.pluginRTCRtpSender = PluginRTCRtpSender(self.rtcRtpTransceiver!.sender, senderId)
}
if self.rtcRtpTransceiver?.receiver != nil {
self.pluginRTCRtpReceiver = PluginRTCRtpReceiver(self.rtcRtpTransceiver!.receiver, receiverId)
}
}
super.init()
}
deinit {
NSLog("PluginRTCRtpTransceiver#deinit()")
}
func stop() {
self.rtcRtpTransceiver!.stopInternal()
}
func setDirection(direction: String) {
self.rtcRtpTransceiver?.setDirection(PluginRTCRtpTransceiver.stringToDirection(direction), error: nil)
}
static func stringToDirection(_ direction: String) -> RTCRtpTransceiverDirection {
switch direction {
case "inactive":
return RTCRtpTransceiverDirection.inactive
case "recvonly":
return RTCRtpTransceiverDirection.recvOnly
case "sendonly":
return RTCRtpTransceiverDirection.sendOnly
case "sendrecv":
return RTCRtpTransceiverDirection.sendRecv
case "stopped":
return RTCRtpTransceiverDirection.stopped
default:
NSLog("PluginRTCRtpTransceiver#stringToDirection() | Unrecognized direction value: @%", direction)
return RTCRtpTransceiverDirection.inactive
}
}
static func directionToString(_ direction: RTCRtpTransceiverDirection) -> String {
switch direction {
case RTCRtpTransceiverDirection.inactive:
return "inactive"
case RTCRtpTransceiverDirection.recvOnly:
return "recvonly"
case RTCRtpTransceiverDirection.sendOnly:
return "sendonly"
case RTCRtpTransceiverDirection.sendRecv:
return "sendrecv"
case RTCRtpTransceiverDirection.stopped:
return "stopped"
}
}
static func initFromOptionsDictionary(_ options: NSDictionary?) -> RTCRtpTransceiverInit {
let rtcRtpTransceiverInit = RTCRtpTransceiverInit();
if options?.object(forKey: "direction") != nil {
let direction = options!.object(forKey: "direction") as! String
rtcRtpTransceiverInit.direction = PluginRTCRtpTransceiver.stringToDirection(direction)
}
if options?.object(forKey: "streams") != nil {
let streamIds = options!.object(forKey: "streams") as! [String]
rtcRtpTransceiverInit.streamIds = streamIds
}
if options?.object(forKey: "sendEncodings") != nil {
let encodings = options!.object(forKey: "sendEncodings") as! [NSDictionary]
rtcRtpTransceiverInit.sendEncodings = encodings.map({ (encoding: NSDictionary) -> RTCRtpEncodingParameters in
let encodingParameters = RTCRtpEncodingParameters()
encodingParameters.isActive = encoding["active"] as? Bool ?? true
encodingParameters.maxBitrateBps = encoding["maxBitrate"] as? NSNumber
encodingParameters.maxFramerate = encoding["maxFramerate"] as? NSNumber
encodingParameters.rid = encoding["rid"] as? String
encodingParameters.scaleResolutionDownBy = encoding["scaleResolutionDownBy"] as? NSNumber
return encodingParameters
})
}
return rtcRtpTransceiverInit
}
func getJSON() -> NSDictionary {
var currentDirection = RTCRtpTransceiverDirection.inactive
self.rtcRtpTransceiver?.currentDirection(¤tDirection)
return [
"id": self.id,
"mid": self.rtcRtpTransceiver?.mid,
"stopped": self.rtcRtpTransceiver?.isStopped,
"direction": PluginRTCRtpTransceiver.directionToString(rtcRtpTransceiver!.direction),
"currentDirection": PluginRTCRtpTransceiver.directionToString(currentDirection),
"receiver": self.pluginRTCRtpReceiver?.getJSON(),
"sender": self.pluginRTCRtpSender?.getJSON()
]
}
}
| mit | b672379fc55f2bea55b32b43a4c40130 | 36.735294 | 121 | 0.690257 | 5.404381 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/API/Requests/Subscription/SubscriptionLeaveRequest.swift | 1 | 1198 | //
// SubscriptionLeaveRequest.swift
// Rocket.Chat
//
// Created by Filipe Alvarenga on 27/07/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import Foundation
import SwiftyJSON
fileprivate extension SubscriptionType {
var path: String {
switch self {
case .channel:
return "/api/v1/channels.leave"
case .group:
return "/api/v1/groups.leave"
default:
return "/api/v1/channels.leave"
}
}
}
final class SubscriptionLeaveRequest: APIRequest {
typealias APIResourceType = SubscriptionLeaveResource
let requiredVersion = Version(0, 48, 0)
let method: HTTPMethod = .post
var path: String {
return type.path
}
let rid: String
let type: SubscriptionType
init(rid: String, subscriptionType: SubscriptionType) {
self.rid = rid
self.type = subscriptionType
}
func body() -> Data? {
let body = JSON([
"roomId": rid
])
return body.rawString()?.data(using: .utf8)
}
}
final class SubscriptionLeaveResource: APIResource {
var success: Bool? {
return raw?["success"].boolValue
}
}
| mit | 70c555059eebb17ec2e730d9597be796 | 20.375 | 59 | 0.6132 | 4.244681 | false | false | false | false |
mentrena/SyncKit | Example/CoreData/SyncKitCoreDataExample/SyncKitCoreDataExampleTests/Transformable/QSNamesTransformer.swift | 1 | 2458 | //
// QSNamesTransformer.swift
// SyncKitCoreDataExampleTests
//
// Created by Manuel Entrena on 18/06/2019.
// Copyright © 2019 Manuel Entrena. All rights reserved.
//
import Foundation
class QSNamesTransformer: ValueTransformer {
static var transformedValueCalled = false
static var reverseTransformedValueCalled = false
static func resetValues() {
transformedValueCalled = false
reverseTransformedValueCalled = false
}
static func register() {
ValueTransformer.setValueTransformer(QSNamesTransformer(), forName: .namesTransformerName)
}
override class func transformedValueClass() -> AnyClass {
NSData.self
}
override class func allowsReverseTransformation() -> Bool {
true
}
override func transformedValue(_ value: Any?) -> Any? {
QSNamesTransformer.transformedValueCalled = true
return NSKeyedArchiver.archivedData(withRootObject: value)
}
override func reverseTransformedValue(_ value: Any?) -> Any? {
QSNamesTransformer.reverseTransformedValueCalled = true
return NSKeyedUnarchiver.unarchiveObject(with: value as! Data)
}
}
class QSSecureNamesTransformer: NSSecureUnarchiveFromDataTransformer {
static var transformedValueCalled = false
static var reverseTransformedValueCalled = false
static func resetValues() {
transformedValueCalled = false
reverseTransformedValueCalled = false
}
static func register() {
ValueTransformer.setValueTransformer(QSSecureNamesTransformer(), forName: .secureNamesTransformerName)
}
override class func transformedValueClass() -> AnyClass {
NSData.self
}
override class func allowsReverseTransformation() -> Bool {
true
}
override func transformedValue(_ value: Any?) -> Any? {
QSSecureNamesTransformer.transformedValueCalled = true
return NSKeyedUnarchiver.unarchiveObject(with: value as! Data)
}
override func reverseTransformedValue(_ value: Any?) -> Any? {
QSSecureNamesTransformer.reverseTransformedValueCalled = true
return NSKeyedArchiver.archivedData(withRootObject: value)
}
}
extension NSValueTransformerName {
static let namesTransformerName = NSValueTransformerName(rawValue: "QSNamesTransformer")
static let secureNamesTransformerName = NSValueTransformerName(rawValue: "QSSecureNamesTransformer")
}
| mit | 1c8b2c20b3717dc16328f4e6068f97c7 | 30.101266 | 110 | 0.720391 | 5.863962 | false | false | false | false |
SereivoanYong/Charts | Source/Charts/Jobs/ZoomViewJob.swift | 1 | 1684 | //
// ZoomViewJob.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
open class ZoomViewJob: ViewPortJob {
internal var scaleX: CGFloat
internal var scaleY: CGFloat
internal let axisDependency: YAxis.AxisDependency
public init(viewPortHandler: ViewPortHandler, scaleX: CGFloat, scaleY: CGFloat, xValue: CGFloat, yValue: CGFloat, transformer: Transformer, axis: YAxis.AxisDependency, view: ChartView) {
self.scaleX = scaleX
self.scaleY = scaleY
self.axisDependency = axis
super.init(viewPortHandler: viewPortHandler, xValue: xValue, yValue: yValue, transformer: transformer, view: view)
}
open override func doJob() {
guard let viewPortHandler = viewPortHandler, let transformer = transformer, let view = view else {
return
}
var matrix = viewPortHandler.setZoom(scaleX: scaleX, scaleY: scaleY)
let _ = viewPortHandler.refresh(newMatrix: matrix, chart: view, invalidate: false)
let yValsInView = (view as! BaseBarLineChartView).getAxis(axisDependency).axisRange / viewPortHandler.yScale
let xValsInView = (view as! BaseBarLineChartView).xAxis.axisRange / viewPortHandler.xScale
var pt = CGPoint(x: xValue - xValsInView / 2.0, y: yValue + yValsInView / 2.0)
transformer.pointValueToPixel(&pt)
matrix = viewPortHandler.translate(pt: pt)
let _ = viewPortHandler.refresh(newMatrix: matrix, chart: view, invalidate: false)
(view as! BaseBarLineChartView).calculateOffsets()
view.setNeedsDisplay()
}
}
| apache-2.0 | 4ab79b74c3197ebfb27fa73140f9b45e | 34.083333 | 188 | 0.722684 | 4.502674 | false | false | false | false |
simplicitylab/electronics-experiments | Eddy and his stones/mobile apps/SimpleIOSEddystone/Pods/Eddystone/Pod/Classes/Beacon.swift | 1 | 6257 | import CoreBluetooth
public class Beacon {
//MARK: Enumerations
public enum SignalStrength: Int {
case Excellent
case VeryGood
case Good
case Low
case VeryLow
case NoSignal
case Unknown
}
//MARK: Frames
var frames: (
url: UrlFrame?,
uid: UidFrame?,
tlm: TlmFrame?
) = (nil,nil,nil)
//MARK: Properties
var txPower: Int
var identifier: String
var rssi: Double {
get {
var totalRssi: Double = 0
for rssi in self.rssiBuffer {
totalRssi += rssi
}
let average: Double = totalRssi / Double(self.rssiBuffer.count)
return average
}
}
var signalStrength: SignalStrength = .Unknown
var rssiBuffer = [Double]()
var distance: Double {
get {
return Beacon.calculateAccuracy(txPower: self.txPower, rssi: self.rssi)
}
}
//MARK: Initializations
init(rssi: Double, txPower: Int, identifier: String) {
self.txPower = txPower
self.identifier = identifier
self.updateRssi(rssi)
}
//MARK: Delegate
var delegate: BeaconDelegate?
func notifyChange() {
self.delegate?.beaconDidChange()
}
//MARK: Functions
func updateRssi(newRssi: Double) -> Bool {
self.rssiBuffer.insert(newRssi, atIndex: 0)
if self.rssiBuffer.count >= 20 {
self.rssiBuffer.removeLast()
}
let signalStrength = Beacon.calculateSignalStrength(self.distance)
if signalStrength != self.signalStrength {
self.signalStrength = signalStrength
self.notifyChange()
}
return false
}
//MARK: Calculations
class func calculateAccuracy(txPower txPower: Int, rssi: Double) -> Double {
if rssi == 0 {
return 0
}
let ratio: Double = rssi / Double(txPower)
if ratio < 1 {
return pow(ratio, 10)
} else {
return 0.89976 * pow(ratio, 7.7095) + 0.111
}
}
class func calculateSignalStrength(distance: Double) -> SignalStrength {
switch distance {
case 0...24999:
return .Excellent
case 25000...49999:
return .VeryGood
case 50000...74999:
return .Good
case 75000...99999:
return .Low
default:
return .VeryLow
}
}
//MARK: Advertisement Data
func parseAdvertisementData(advertisementData: [NSObject : AnyObject], rssi: Double) {
self.updateRssi(rssi)
if let bytes = Beacon.bytesFromAdvertisementData(advertisementData) {
if let type = Beacon.frameTypeFromBytes(bytes) {
switch type {
case .URL:
if let frame = UrlFrame.frameWithBytes(bytes) {
if frame.url != self.frames.url?.url {
self.frames.url = frame
log("Parsed URL Frame with url: \(frame.url)")
self.notifyChange()
}
}
case .UID:
if let frame = UidFrame.frameWithBytes(bytes) {
if frame.uid != self.frames.uid?.uid {
self.frames.uid = frame
log("Parsed UID Frame with uid: \(frame.uid)")
self.notifyChange()
}
}
case .TLM:
if let frame = TlmFrame.frameWithBytes(bytes) {
self.frames.tlm = frame
log("Parsed TLM Frame with battery: \(frame.batteryVolts) temperature: \(frame.temperature) advertisement count: \(frame.advertisementCount) on time: \(frame.onTime)")
self.notifyChange()
}
}
}
}
}
//MARK: Bytes
class func beaconWithAdvertisementData(advertisementData: [NSObject : AnyObject], rssi: Double, identifier: String) -> Beacon? {
var txPower: Int?
var type: FrameType?
if let bytes = Beacon.bytesFromAdvertisementData(advertisementData) {
type = Beacon.frameTypeFromBytes(bytes)
txPower = Beacon.txPowerFromBytes(bytes)
if let txPower = txPower where type != nil {
let beacon = Beacon(rssi: rssi, txPower: txPower, identifier: identifier)
beacon.parseAdvertisementData(advertisementData, rssi: rssi)
return beacon
}
}
return nil
}
class func bytesFromAdvertisementData(advertisementData: [NSObject : AnyObject]) -> [Byte]? {
if let serviceData = advertisementData[CBAdvertisementDataServiceDataKey] as? [NSObject: AnyObject] {
if let urlData = serviceData[Scanner.eddystoneServiceUUID] as? NSData {
let count = urlData.length / sizeof(UInt8)
var bytes = [UInt8](count: count, repeatedValue: 0)
urlData.getBytes(&bytes, length:count * sizeof(UInt8))
return bytes.map { byte in
return Byte(byte)
}
}
}
return nil
}
class func frameTypeFromBytes(bytes: [Byte]) -> FrameType? {
if bytes.count >= 1 {
switch bytes[0] {
case 0:
return .UID
case 16:
return .URL
case 32:
return .TLM
default:
break
}
}
return nil
}
class func txPowerFromBytes(bytes: [Byte]) -> Int? {
if bytes.count >= 2 {
if let type = Beacon.frameTypeFromBytes(bytes) {
if type == .UID || type == .URL {
return Int(bytes[1])
}
}
}
return nil
}
}
protocol BeaconDelegate {
func beaconDidChange()
} | gpl-2.0 | 67d4d13d790709ae0ff39743b21f30cc | 29.378641 | 191 | 0.507432 | 5.082859 | false | false | false | false |
1aurabrown/eidolon | KioskTests/XAppTokenSpec.swift | 2 | 1528 | import Quick
import Nimble
class XAppTokenSpec: QuickSpec {
override func spec() {
let defaults = NSUserDefaults()
let token = XAppToken()
it("returns correct data") {
let key = "some key"
let expiry = NSDate(timeIntervalSinceNow: 1000)
setDefaultsKeys(defaults, key, expiry)
expect(token.token).to(equal(key))
expect(token.expiry).to(equal(expiry))
}
it("correctly calculates validity for expired tokens") {
let key = "some key"
let past = NSDate(timeIntervalSinceNow: -1000)
setDefaultsKeys(defaults, key, past)
expect(token.isValid).to(beFalsy())
}
it("correctly calculates validity for non-expired tokens") {
let key = "some key"
let future = NSDate(timeIntervalSinceNow: 1000)
setDefaultsKeys(defaults, key, future)
expect(token.isValid).to(beTruthy())
}
it("correctly calculates validity for empty keys") {
let key = ""
let future = NSDate(timeIntervalSinceNow: 1000)
setDefaultsKeys(defaults, key, future)
expect(token.isValid).to(beFalsy())
}
it("properly calculates validity for missing tokens") {
setDefaultsKeys(defaults, nil, nil)
expect(token.isValid).to(beFalsy())
}
}
}
| mit | 6e59717d25babf36303e5f55343c7088 | 30.833333 | 68 | 0.539921 | 5.342657 | false | false | false | false |
guoc/excerptor | Excerptor/AppDelegate.swift | 1 | 2001 | //
// AppDelegate.swift
// excerptor
//
// Created by Chen Guo on 17/05/2015.
// Copyright (c) 2015 guoc. All rights reserved.
//
import Cocoa
import PreferencePanes
class AppDelegate: NSObject, NSApplicationDelegate {
lazy var preferencesWindowController: PreferencesWindowController = PreferencesWindowController(windowNibName: NSNib.Name(rawValue: "PreferencesWindow"))
func applicationWillFinishLaunching(_ notification: Notification) {
preferencesWindowController.showPreferencesOnlyOnceIfNecessaryAfterDelay(0.3)
let servicesProvider = ServicesProvider()
NSApplication.shared.servicesProvider = servicesProvider
let appleEventManager: NSAppleEventManager = NSAppleEventManager.shared()
appleEventManager.setEventHandler(self, andSelector: #selector(handleGetURLEvent(_:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}
func applicationDidBecomeActive(_ notification: Notification) {
preferencesWindowController.showPreferencesOnlyOnceIfNecessaryAfterDelay(0.3)
}
@objc func handleGetURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent: NSAppleEventDescriptor) {
PreferencesWindowController.needShowPreferences = false
if let theURLString = event.forKeyword(AEKeyword(keyDirectObject))?.stringValue {
if let link = AnnotationLink(linkString: theURLString) ?? SelectionLink(linkString: theURLString) {
PasteboardHelper.writeExcerptorPasteboardWithLocation(link.location)
let applicationName: String
switch Preferences.sharedPreferences.appForOpenPDF {
case .preview:
applicationName = "Preview.app"
case .skim:
applicationName = "Skim.app"
}
NSWorkspace().openFile(link.getFilePath(), withApplication: applicationName, andDeactivate: true)
}
}
}
}
| mit | 9752a6dee3772b831b7717d36abe2aea | 41.574468 | 193 | 0.715642 | 5.452316 | false | false | false | false |
ikesyo/Commandant | Sources/Commandant/Errors.swift | 2 | 5164 | //
// Errors.swift
// Commandant
//
// Created by Justin Spahr-Summers on 2014-10-24.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import Foundation
import Result
/// Possible errors that can originate from Commandant.
///
/// `ClientError` should be the type of error (if any) that can occur when
/// running commands.
public enum CommandantError<ClientError>: Error {
/// An option was used incorrectly.
case usageError(description: String)
/// An error occurred while running a command.
case commandError(ClientError)
}
extension CommandantError: CustomStringConvertible {
public var description: String {
switch self {
case let .usageError(description):
return description
case let .commandError(error):
return String(describing: error)
}
}
}
/// Constructs an `InvalidArgument` error that indicates a missing value for
/// the argument by the given name.
internal func missingArgumentError<ClientError>(_ argumentName: String) -> CommandantError<ClientError> {
let description = "Missing argument for \(argumentName)"
return .usageError(description: description)
}
/// Constructs an error by combining the example of key (and value, if applicable)
/// with the usage description.
internal func informativeUsageError<ClientError>(_ keyValueExample: String, usage: String) -> CommandantError<ClientError> {
let lines = usage.components(separatedBy: .newlines)
return .usageError(description: lines.reduce(keyValueExample) { previous, value in
return previous + "\n\t" + value
})
}
/// Combines the text of the two errors, if they're both `UsageError`s.
/// Otherwise, uses whichever one is not (biased toward the left).
internal func combineUsageErrors<ClientError>(_ lhs: CommandantError<ClientError>, _ rhs: CommandantError<ClientError>) -> CommandantError<ClientError> {
switch (lhs, rhs) {
case let (.usageError(left), .usageError(right)):
let combinedDescription = "\(left)\n\n\(right)"
return .usageError(description: combinedDescription)
case (.usageError, _):
return rhs
case (_, .usageError), (_, _):
return lhs
}
}
/// Constructs an error that indicates unrecognized arguments remains.
internal func unrecognizedArgumentsError<ClientError>(_ options: [String]) -> CommandantError<ClientError> {
return .usageError(description: "Unrecognized arguments: " + options.joined(separator: ", "))
}
// MARK: Argument
/// Constructs an error that describes how to use the argument, with the given
/// example of value usage if applicable.
internal func informativeUsageError<T, ClientError>(_ valueExample: String, argument: Argument<T>) -> CommandantError<ClientError> {
if argument.defaultValue != nil {
return informativeUsageError("[\(valueExample)]", usage: argument.usage)
} else {
return informativeUsageError(valueExample, usage: argument.usage)
}
}
/// Constructs an error that describes how to use the argument.
internal func informativeUsageError<T: ArgumentProtocol, ClientError>(_ argument: Argument<T>) -> CommandantError<ClientError> {
var example = ""
var valueExample = ""
if let defaultValue = argument.defaultValue {
valueExample = "\(defaultValue)"
}
if valueExample.isEmpty {
example += "(\(T.name))"
} else {
example += valueExample
}
return informativeUsageError(example, argument: argument)
}
/// Constructs an error that describes how to use the argument list.
internal func informativeUsageError<T: ArgumentProtocol, ClientError>(_ argument: Argument<[T]>) -> CommandantError<ClientError> {
var example = ""
var valueExample = ""
if let defaultValue = argument.defaultValue {
valueExample = "\(defaultValue)"
}
if valueExample.isEmpty {
example += "(\(T.name))"
} else {
example += valueExample
}
return informativeUsageError(example, argument: argument)
}
// MARK: Option
/// Constructs an error that describes how to use the option, with the given
/// example of key (and value, if applicable) usage.
internal func informativeUsageError<T, ClientError>(_ keyValueExample: String, option: Option<T>) -> CommandantError<ClientError> {
return informativeUsageError("[\(keyValueExample)]", usage: option.usage)
}
/// Constructs an error that describes how to use the option.
internal func informativeUsageError<T: ArgumentProtocol, ClientError>(_ option: Option<T>) -> CommandantError<ClientError> {
return informativeUsageError("--\(option.key) \(option.defaultValue)", option: option)
}
/// Constructs an error that describes how to use the option.
internal func informativeUsageError<T: ArgumentProtocol, ClientError>(_ option: Option<T?>) -> CommandantError<ClientError> {
return informativeUsageError("--\(option.key) (\(T.name))", option: option)
}
/// Constructs an error that describes how to use the given boolean option.
internal func informativeUsageError<ClientError>(_ option: Option<Bool>) -> CommandantError<ClientError> {
let key = option.key
return informativeUsageError((option.defaultValue ? "--no-\(key)" : "--\(key)"), option: option)
}
// MARK: - migration support
@available(*, unavailable, message: "Use ErrorProtocol instead of ClientErrorType")
public typealias ClientErrorType = Error
| mit | f8b7c8a67414f173a44299098428ac9a | 33.891892 | 153 | 0.743997 | 4.372566 | false | false | false | false |
almachelouche/Alien-Adventure | Alien Adventure/BannedItems.swift | 1 | 1568 |
//
// BannedItems.swift
// Alien Adventure
//
// Created by Jarrod Parkes on 10/4/15.
// Copyright © 2015 Udacity. All rights reserved.
//
import Foundation
extension Hero {
func bannedItems(dataFile: String) -> [Int] {
let dataFileURL = Bundle.main.url(forResource: dataFile, withExtension: "plist")!
let LaserDictionary = NSArray(contentsOf: dataFileURL) as! [[String: Any]]
print(LaserDictionary)
var bannedItemsFromPlanet = [Int]()
var laserItems = [String]()
for item in LaserDictionary {
if let laserSearch = item["Name"] as? String {
if laserSearch.contains("Laser") {
laserItems.append(laserSearch)
print (laserItems)
let laserHistoricalDate = item["HistoricalData"] as! [String: AnyObject]
if let carbonAge = laserHistoricalDate["CarbonAge"] as? Int {
if carbonAge<30 {
bannedItemsFromPlanet.append(item["ItemID"] as! Int)
print(bannedItemsFromPlanet)
}
}
}
}
}
return bannedItemsFromPlanet
}
}
// If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 6"
| mit | f42c531cb55d79dc1144f651a3c55732 | 35.44186 | 235 | 0.551372 | 4.927673 | false | false | false | false |
evan3rd/URLConnection | URLConnection.swift | 2 | 6262 | //
// URLConnection.swift
// Copyright (c) 2015年 evan3rd. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
private let _SomeManagerSharedInstance = URLConnection()
class URLConnection: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDownloadDelegate {
static let sharedInstance = URLConnection()
var _downloadCompletionBlock: ((data: NSData, url: NSURL) -> Void)?
var _downloadProgressBlock: ((progress: Float) -> Void)?
var _uploadCompletionBlock: (() -> Void)?
var _uploadProgressBlock: ((progress: Float) -> Void)?
func asyncConnectionWithURLString(urlString: String?, completionBlock completion:((NSData, NSURLResponse) -> Void), errorBlock: ((error: NSError) -> Void)) {
let request = NSURLRequest(URL: NSURL(string: urlString!)!)
asyncConnectionWithRequest(request, completion: completion, errorBlock: errorBlock)
}
func asyncConnectionWithRequest(request:NSURLRequest!, completion:(data: NSData, response: NSURLResponse) -> Void, errorBlock: ((error: NSError) -> Void)) {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error == nil {
completion(data: data!, response: response!)
} else {
errorBlock(error: error!)
}
}
task!.resume()
}
func asyncConnectionDownload(request: NSURLRequest!, completion: (data: NSData, url: NSURL) -> Void, errorBlock: (error: NSError) -> Void, downloadProgressBlock: ((progress: Float) -> Void)?) {
_downloadCompletionBlock = completion
_downloadProgressBlock = downloadProgressBlock
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.downloadTaskWithRequest(request)
task!.resume()
}
func asyncConnectionUpload(request: NSURLRequest!, data: NSData!, completion: () -> Void, errorBlock: (error: NSError) -> Void, uploadProgressBlock: ((progress: Float) -> Void)?) {
_uploadCompletionBlock = completion
_uploadProgressBlock = uploadProgressBlock
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.uploadTaskWithRequest(request, fromData: data)
task!.resume()
}
// MARK: - NSURLSessionDelegate
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!))
}
// MARK: - NSURLSessionTaskDelegate
func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest?) -> Void) {
let newRequest : NSURLRequest? = request
print(newRequest?.description)
completionHandler(newRequest)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
let progress = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
if let block = _uploadProgressBlock {
block(progress: progress)
}
}
// MARK: - NSURLSessionDownloadTaskDelegate
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
if let block = _downloadProgressBlock {
block(progress: progress)
}
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
print("location \(location.path)")
let fileManager = NSFileManager.defaultManager()
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let documentsDirectory = NSURL(string: documentsPath)
let originalUrl = downloadTask.originalRequest?.URL
let destinationUrl = documentsDirectory!.URLByAppendingPathComponent(originalUrl!.lastPathComponent!)
print("destinationUrl \(destinationUrl.path)")
do {
try fileManager.removeItemAtPath(destinationUrl.path!)
} catch let error {
print("remove file error: \(error)")
}
do {
try fileManager.copyItemAtPath(location.path!, toPath: destinationUrl.path!)
} catch let error {
print("copy file error \(error)")
}
if let fileData = fileManager.contentsAtPath(destinationUrl.path!) {
if let block = _downloadCompletionBlock {
block(data: fileData, url: destinationUrl)
}
}
}
} | mit | da34ff40df59d8ba5082fe19a9b6a421 | 44.70073 | 200 | 0.741534 | 5.2827 | false | true | false | false |
andrewcar/hoods | Project/hoods/hoods/MapVC+Profiles.swift | 1 | 11364 | //
// MapVC+Profiles.swift
// hoods
//
// Created by Andrew Carvajal on 6/19/18.
// Copyright © 2018 YugeTech. All rights reserved.
//
import UIKit
import Firebase
extension MapVC {
// MARK: User Profile
func addProfileView() {
profileView = ProfileView(frame: Frames.si.profileFrames.profileViewHidden)
profileView.button.addTarget(self, action: #selector(profileViewButtonTapped), for: .touchDown)
profileView.swipe.addTarget(self, action: #selector(didSwipeDownOnProfileView))
profileViewShadow = UIView(frame: Frames.si.profileFrames.profileViewShadowHidden)
profileViewShadow.backgroundColor = UIColor(white: 0.1, alpha: 0.5)
profileViewShadow.layer.cornerRadius = Frames.si.profileFrames.profileViewShadowHidden.width / 2
profileViewShadow.layer.masksToBounds = true
mapboxView.addSubview(profileViewShadow)
mapboxView.addSubview(profileView)
}
// MARK: Button Tap
@objc func profileViewButtonTapped(sender: UIButton) {
animateProfileViewTap {
self.openProfileView {
self.disableMap()
Spotify.shared.getSpotifyCurrentUser(completionHandler: { (user) in
self.updateProfileView(user: user)
})
}
}
}
func updateProfileView(user: User) {
if let pic = user.profilePicture {
let picSize = CGSize(width: pic.size.width, height: pic.size.height)
let largerDiameter = picSize.width > picSize.height ? picSize.width : picSize.height
let croppedImage = Source.si.crop(image: pic, width: Double(largerDiameter), height: Double(largerDiameter))
hoodView.composeView.profilePictureImageView.image = croppedImage
profileView.profileImageView.image = croppedImage
let colors = croppedImage.getColors()
profileView.nameLabel.textColor = colors.primary
}
profileView.nameLabel.text = user.displayName
}
fileprivate func animateProfileViewTap(completionHandler: @escaping () -> Void) {
UIView.animate(withDuration: 0.1, animations: {
self.profileView.frame = Frames.si.profileFrames.profileViewTapped
self.profileViewShadow.frame = Frames.si.profileFrames.profileViewShadowTapped
}, completion: { (Bool) in
UIView.animate(withDuration: 0.2, animations: {
self.profileView.frame = Frames.si.profileFrames.profileViewClosed
self.profileViewShadow.frame = Frames.si.profileFrames.profileViewShadowClosed
}, completion: { (finished) in
completionHandler()
})
})
}
// MARK: Open Profile
fileprivate func openProfileView(completionHandler: @escaping () -> Void) {
view.bringSubview(toFront: profileViewShadow)
view.bringSubview(toFront: profileView)
profileView.activateOpenConstraints(view.frame.width)
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1.5, initialSpringVelocity: 1.5, options: .curveEaseInOut, animations: {
self.profileView.frame = Frames.si.profileFrames.profileViewOpen
self.profileViewShadow.frame = Frames.si.profileFrames.profileViewShadowOpen
}) { (finished) in
States.si.profileState = .open
completionHandler()
}
}
// MARK: Close/Hide Profile
@objc fileprivate func didSwipeDownOnProfileView() {
closeProfileView {
self.enableMap()
}
}
fileprivate func closeProfileView(completionHandler: @escaping () -> Void) {
States.si.profileState = .closing
profileView.activateClosedConstraints(Frames.si.closedProfileSize.width)
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1.5, initialSpringVelocity: 1.5, options: .curveEaseInOut, animations: {
self.profileView.frame = Frames.si.profileFrames.profileViewClosed
self.profileViewShadow.frame = Frames.si.profileFrames.profileViewShadowClosed
}) { (finished) in
States.si.profileState = .closed
Source.si.numberOfSecondsUntilMapButtonHide = 9
self.runTimer()
completionHandler()
}
}
func hideProfileView(completionHandler: @escaping () -> Void) {
if States.si.profileState != .open && States.si.profileState != .closing {
UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 1.5, initialSpringVelocity: 1.5, options: .curveEaseInOut, animations: {
self.profileViewShadow.frame = Frames.si.profileFrames.profileViewShadowHidden
self.profileView.frame = Frames.si.profileFrames.profileViewHidden
}, completion: { (finished) in
States.si.profileState = .closed
completionHandler()
})
}
}
// MARK: jockey Profile
func addJockeyProfileView() {
jockeyProfileView = ProfileView(frame: Frames.si.profileFrames.jockeyProfileViewHidden)
jockeyProfileView.button.addTarget(self, action: #selector(jockeyProfileViewButtonTapped), for: .touchDown)
jockeyProfileView.swipe.addTarget(self, action: #selector(didSwipeDownOnJockeyProfileView))
jockeyProfileViewShadow = UIView(frame: Frames.si.profileFrames.jockeyProfileViewShadowHidden)
jockeyProfileViewShadow.backgroundColor = UIColor(white: 0.1, alpha: 0.5)
jockeyProfileViewShadow.layer.cornerRadius = Frames.si.buttonSize.width / 2
jockeyProfileViewShadow.layer.masksToBounds = true
mapboxView.addSubview(jockeyProfileViewShadow)
mapboxView.addSubview(jockeyProfileView)
}
func showJockeyProfileView(delay: TimeInterval) {
if States.si.jockeyProfileState != .open {
// animate showing of profile
UIView.animate(withDuration: 0.6, delay: delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 4, options: .curveEaseIn, animations: {
self.jockeyProfileViewShadow.frame = Frames.si.profileFrames.jockeyProfileViewShadowClosed
self.jockeyProfileView.frame = Frames.si.profileFrames.jockeyProfileViewClosed
}, completion: { finished in
})
}
}
@objc func jockeyProfileViewButtonTapped(sender: UIButton) {
animateJockeyProfileViewTap {
self.openJockeyProfileView {
self.disableMap()
// get jockey canonical username from current song
guard let currentSong = Music.shared.currentSong else { return }
guard let jockeyCanonicalUsername = currentSong.chosenBy else { return }
Spotify.shared.getSpotifyJockey(jockeyCanonicalUsername: jockeyCanonicalUsername, completionHandler: { (user) in
guard let canonicalUsername = user.canonicalUsername else { return }
self.updateJockeyProfileView(canonicalUsername: canonicalUsername)
})
}
}
}
func updateJockeyProfileView(canonicalUsername: String) {
// create user
Spotify.shared.getSpotifyJockey(jockeyCanonicalUsername: canonicalUsername, completionHandler: { (user) in
// got jockey
if let pic = user.profilePicture {
let picSize = CGSize(width: pic.size.width, height: pic.size.height)
let largerDiameter = picSize.width > picSize.height ? picSize.width : picSize.height
let croppedImage = Source.si.crop(image: pic, width: Double(largerDiameter), height: Double(largerDiameter))
self.jockeyProfileView.profileImageView.image = croppedImage
}
self.jockeyProfileView.nameLabel.text = user.displayName
})
}
fileprivate func animateJockeyProfileViewTap(completionHandler: @escaping () -> Void) {
UIView.animate(withDuration: 0.1, animations: {
self.jockeyProfileView.frame = Frames.si.profileFrames.jockeyProfileViewTapped
self.jockeyProfileViewShadow.frame = Frames.si.profileFrames.jockeyProfileViewShadowTapped
}, completion: { (Bool) in
UIView.animate(withDuration: 0.2, animations: {
self.jockeyProfileView.frame = Frames.si.profileFrames.jockeyProfileViewClosed
self.jockeyProfileViewShadow.frame = Frames.si.profileFrames.jockeyProfileViewShadowClosed
}, completion: { (finished) in
completionHandler()
})
})
}
// MARK: Open Jockey Profile
fileprivate func openJockeyProfileView(completionHandler: @escaping () -> Void) {
view.bringSubview(toFront: jockeyProfileViewShadow)
view.bringSubview(toFront: jockeyProfileView)
jockeyProfileView.activateOpenConstraints(view.frame.width)
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1.5, initialSpringVelocity: 1.5, options: .curveEaseInOut, animations: {
self.jockeyProfileView.frame = Frames.si.profileFrames.jockeyProfileViewOpen
self.jockeyProfileViewShadow.frame = Frames.si.profileFrames.jockeyProfileViewShadowOpen
}) { (finished) in
States.si.jockeyProfileState = .open
completionHandler()
}
}
// MARK: Close/Hide Jockey Profile
@objc fileprivate func didSwipeDownOnJockeyProfileView() {
closeJockeyProfileView {
self.enableMap()
}
}
fileprivate func closeJockeyProfileView(completionHandler: @escaping () -> Void) {
jockeyProfileView.activateClosedConstraints(Frames.si.buttonSize.width)
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1.5, initialSpringVelocity: 1.5, options: .curveEaseInOut, animations: {
self.jockeyProfileView.frame = Frames.si.profileFrames.jockeyProfileViewClosed
self.jockeyProfileViewShadow.frame = Frames.si.profileFrames.jockeyProfileViewShadowClosed
}) { (finished) in
States.si.jockeyProfileState = .closed
Source.si.numberOfSecondsUntilMapButtonHide = 9
self.runTimer()
completionHandler()
}
}
func hideJockeyProfileView(completionHandler: @escaping () -> Void) {
if States.si.jockeyProfileState != .open {
UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 1.5, initialSpringVelocity: 1.5, options: .curveEaseInOut, animations: {
self.jockeyProfileViewShadow.frame = Frames.si.profileFrames.jockeyProfileViewShadowHidden
self.jockeyProfileView.frame = Frames.si.profileFrames.jockeyProfileViewHidden
}, completion: { (finished) in
States.si.jockeyProfileState = .closed
completionHandler()
})
}
}
}
| mit | a1fa53592f49e0a93a7ca07a61208619 | 43.042636 | 152 | 0.64666 | 5.408377 | false | false | false | false |
simpleandpretty/decider-ios | MessagesExtension/PlayFightViewController.swift | 1 | 8010 | import UIKit
import Messages
protocol PlayFightViewControllerDelegate: class {
func playFightViewControllerDidSelectMakeOfficial(_ controller: PlayFightViewController)
}
class PlayFightViewController: UIViewController {
enum PlayState {
case playStart
case playAttack
case playDefense
case playEnd
}
static let storyboardIdentifier = "PlayFightViewController"
@IBOutlet var captionLabel: UILabel!
@IBOutlet var titleLabel: UILabel!
@IBOutlet var emojiLabel: UILabel!
@IBOutlet var makeOfficialButton: UIButton!
@IBOutlet var fightVideoView: VideoPlayerView!
weak var delegate: PlayFightViewControllerDelegate?
var fight: Fight!
var message: MSMessage!
var conversation: MSConversation!
var state: PlayState = .playStart
func setup(conversation: MSConversation) {
self.conversation = conversation
guard
let message = conversation.selectedMessage,
let fightURL = message.url
else {
return;
}
fight = Fight.decode(fromURL: fightURL)
self.message = message
}
override func viewDidLoad() {
super.viewDidLoad()
fightVideoView.delegate = self
makeOfficialButton.contentEdgeInsets = UIEdgeInsets(top:12, left:12, bottom:12, right:12)
makeOfficialButton.layer.cornerRadius = 5
advanceState()
}
@IBAction func makeItOfficialAction(_ sender:UIButton) {
sendMessage()
}
func sendMessage() {
guard
let session = message.session,
let conversation = self.conversation,
let remoteIdentifier = conversation.remoteParticipantIdentifiers.first,
fight.state == .finished
else {
return
}
let newMessage = MSMessage(session: session)
let template = MSMessageTemplateLayout()
var winnerId = message.senderParticipantIdentifier
var looserId = conversation.localParticipantIdentifier
switch fight.result {
case .attackerWon:
if message.senderParticipantIdentifier == conversation.localParticipantIdentifier {
winnerId = remoteIdentifier
looserId = conversation.localParticipantIdentifier
} else {
looserId = remoteIdentifier
winnerId = conversation.localParticipantIdentifier
}
case .defenderWon:
if message.senderParticipantIdentifier == conversation.localParticipantIdentifier {
looserId = remoteIdentifier
winnerId = conversation.localParticipantIdentifier
} else {
winnerId = remoteIdentifier
looserId = conversation.localParticipantIdentifier
}
case .draw:
captionLabel.text = NSLocalizedString("It was a draw...", comment: "")
default:
captionLabel.text = NSLocalizedString("Still fighting it out!", comment: "")
}
template.imageTitle = NSLocalizedString("Tap to watch replay", comment: "Prompt to start fight.").uppercased()
var caption = "🏆 $\(winnerId) is the Decider! 💩 $\(looserId) is the looser!"
if fight.result == .draw {
caption = NSLocalizedString("It was a draw...", comment: "")
}
template.caption = caption
template.mediaFileURL = MediaResources.mediaURLForConclusion()
newMessage.layout = template
var endFight = fight!
endFight.ended = true
newMessage.url = endFight.encode()
newMessage.summaryText = template.caption
conversation.insert(newMessage)
delegate?.playFightViewControllerDidSelectMakeOfficial(self)
}
fileprivate func advanceState() {
if fight.state == .defending {
titleLabel.text = NSLocalizedString("Waiting for retaliation", comment: "Title for fight replay when waiting for answer.").uppercased()
} else {
titleLabel.text = NSLocalizedString("Fight replay", comment: "Title for fight replay fight is done.").uppercased()
}
switch state {
case .playStart:
if let attackOption = fight?.attackerOption {
fightVideoView.videoURL = MediaResources.mediaURL(forGameOption: attackOption)
if fight.state == .defending {
if message.senderParticipantIdentifier == conversation.localParticipantIdentifier {
captionLabel.text = "You attacked with \(attackOption.localizedText())!"
} else {
captionLabel.text = "They attacked you with a \(attackOption.localizedText())!"
}
} else if fight.state == .finished {
if message.senderParticipantIdentifier == conversation.localParticipantIdentifier {
captionLabel.text = "\(attackOption.localizedText()) attack!"
} else {
captionLabel.text = "\(attackOption.localizedText()) attack!"
}
}
emojiLabel.text = MediaResources.emoji(forFightMove: attackOption)
state = .playAttack
} else {
state = .playEnd
}
case .playAttack:
if let defendOption = fight.defenderOption {
fightVideoView.videoURL = MediaResources.mediaURL(forGameOption: defendOption)
if message.senderParticipantIdentifier == conversation.localParticipantIdentifier {
captionLabel.text = "\(defendOption.localizedText()) Retaliation!"
} else {
captionLabel.text = "\(defendOption.localizedText()) Retaliation!"
}
emojiLabel.text = MediaResources.emoji(forFightMove: defendOption)
state = .playDefense
} else {
state = .playEnd
}
case .playDefense:
state = .playEnd
var emoji = ""
switch fight.result {
case .attackerWon:
if message.senderParticipantIdentifier == conversation.localParticipantIdentifier {
captionLabel.text = NSLocalizedString("You lost! :(", comment: "")
emoji = "💩"
} else {
captionLabel.text = NSLocalizedString("You won! :)", comment: "")
emoji = "🏆"
}
case .defenderWon:
if message.senderParticipantIdentifier == conversation.localParticipantIdentifier {
captionLabel.text = NSLocalizedString("You won! :)", comment: "")
emoji = "🏆"
} else {
captionLabel.text = NSLocalizedString("You lost! :(", comment: "")
emoji = "💩"
}
case .draw:
captionLabel.text = NSLocalizedString("It was a draw...", comment: "")
emoji = "💪"
default:
captionLabel.text = NSLocalizedString("Still fighting it out!", comment: "")
}
fightVideoView.videoURL = MediaResources.mediaURLForConclusion()
emojiLabel.text = emoji
case .playEnd:
if fight.state == .finished && !fight.ended {
makeOfficialButton.isHidden = false
captionLabel.isHidden = true
}
}
}
}
extension PlayFightViewController: VideoPlayerViewDelegate {
func videoPlayerViewStarted(_ playerView: VideoPlayerView) {
}
func videoPlayerViewFinish(_ playerView: VideoPlayerView) {
DispatchQueue.main.async {
self.advanceState()
}
}
func videoPlayerView(_ playerView: VideoPlayerView, didFailedWithError error: NSError) {
}
}
| gpl-3.0 | def93fd4fd6b3aa320046600b0ad75b4 | 37.042857 | 147 | 0.591689 | 5.895941 | false | false | false | false |
GiorgioG/iOS-Playground | iOS Playground/iOS9/TouchID/TouchIDViewController.swift | 1 | 2457 | //
// TouchIDViewController.swift
// iOS Playground
//
// Created by Giorgio Galante on 9/24/15.
// Copyright © 2015 Galante Software. All rights reserved.
//
import Foundation
import UIKit
import LocalAuthentication
import GSFramework
class TouchIDViewController: XibViewController {
@IBOutlet var touchIDButton: UIButton?
@IBOutlet var touchIDResultLabel: UILabel?
override func getXibName() -> String { return "TouchIDView" }
override func loadView() {
super.loadView()
self.title = "Touch ID"
if let touchIDButton = self.touchIDButton {
touchIDButton.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
} else {
OS.crashApplication("Something very bad happened.")
}
}
func buttonAction(sender: UIButton!)
{
let context: LAContext = LAContext()
var error: NSError?
let reasonString = "Go ahead touch it."
if context.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: &error) {
[context .evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: reasonString, reply: { (success: Bool, evalPolicyError: NSError?) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if success {
self.touchIDResultLabel!.text = "Authentication Successful!"
self.touchIDResultLabel!.textColor = UIColor.blackColor()
}
else {
self.touchIDResultLabel!.textColor = UIColor.redColor()
if let policyError = evalPolicyError {
Logger.log(policyError.localizedDescription)
switch policyError.code {
case LAError.SystemCancel.rawValue:
self.touchIDResultLabel!.text = "Authentication was cancelled by the system"
case LAError.UserCancel.rawValue:
self.touchIDResultLabel!.text = "Authentication was cancelled by the user"
default:
self.touchIDResultLabel!.text = "Authentication failed"
}
}
}
})
})]
}
}
}
| mit | 7a193ea12997fbd27b8b3bea3ad1d753 | 34.594203 | 180 | 0.572476 | 5.961165 | false | false | false | false |
naokits/my-programming-marathon | SocialLoginDemo/SocialLoginDemo/AppDelegate.swift | 1 | 3339 | //
// AppDelegate.swift
// SocialLoginDemo
//
// Created by Naoki Tsutsui on 3/5/16.
// Copyright © 2016 Naoki Tsutsui. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
| mit | d6ebfaef7ca610b7617a3b8cb799cdbb | 53.721311 | 285 | 0.765428 | 6.19295 | false | false | false | false |
gorozco58/Apps-List | Apps List/Application/Controllers/Apps Controllers/Cells/AppCollectionViewCell.swift | 1 | 1385 | //
// AppCollectionViewCell.swift
// Apps List
//
// Created by iOS on 3/25/16.
// Copyright © 2016 Giovanny Orozco. All rights reserved.
//
import UIKit
import AlamofireImage
class AppCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var appImageView: UIImageView!
@IBOutlet weak var progressIndicatorView: CircularLoaderView!
static let identifier = "AppCollectionViewCell"
static let nibName = "AppCollectionViewCell"
//MARK: Utils
func loadImage(imageUrl: NSURL, animated: Bool) {
appImageView.af_setImageWithURL(imageUrl, placeholderImage: UIImage(named: "placeholder-app.png"), filter: nil, progress: { [weak self] (bytesRead, totalBytesRead, totalExpectedBytesToRead) in
if animated {
self?.progressIndicatorView.progress = CGFloat(totalBytesRead) / CGFloat(totalExpectedBytesToRead)
}
}, progressQueue: dispatch_get_main_queue(), imageTransition: .None, runImageTransitionIfCached: true) { [weak self] (response) in
dispatch_async(dispatch_get_main_queue(), {
if let image = response.result.value {
self?.appImageView.image = image
}
if animated {
self?.progressIndicatorView.reveal()
}
})
}
}
}
| mit | 07e646f6a82598cb98ce0af0dcbce0b2 | 33.6 | 200 | 0.628613 | 5.125926 | false | false | false | false |
shohei/firefox-ios | Client/Frontend/Reader/ReaderMode.swift | 12 | 9365 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import WebKit
let ReaderModeProfileKeyStyle = "readermode.style"
enum ReaderModeMessageType: String {
case StateChange = "ReaderModeStateChange"
case PageEvent = "ReaderPageEvent"
}
enum ReaderPageEvent: String {
case PageShow = "PageShow"
}
enum ReaderModeState: String {
case Available = "Available"
case Unavailable = "Unavailable"
case Active = "Active"
}
enum ReaderModeTheme: String {
case Light = "light"
case Dark = "dark"
case Sepia = "sepia"
}
enum ReaderModeFontType: String {
case Serif = "serif"
case SansSerif = "sans-serif"
}
enum ReaderModeFontSize: Int {
case Size1 = 1
case Size2 = 2
case Size3 = 3
case Size4 = 4
case Size5 = 5
case Size6 = 6
case Size7 = 7
case Size8 = 8
case Size9 = 9
case Size10 = 10
case Size11 = 11
case Size12 = 12
case Size13 = 13
func isSmallest() -> Bool {
return self == Size1
}
func smaller() -> ReaderModeFontSize {
if isSmallest() {
return self
} else {
return ReaderModeFontSize(rawValue: self.rawValue - 1)!
}
}
func isLargest() -> Bool {
return self == Size13
}
static var defaultSize: ReaderModeFontSize {
return .Size5
}
func bigger() -> ReaderModeFontSize {
if isLargest() {
return self
} else {
return ReaderModeFontSize(rawValue: self.rawValue + 1)!
}
}
}
struct ReaderModeStyle {
var theme: ReaderModeTheme
var fontType: ReaderModeFontType
var fontSize: ReaderModeFontSize
/// Encode the style to a JSON dictionary that can be passed to ReaderMode.js
func encode() -> String {
return JSON(["theme": theme.rawValue, "fontType": fontType.rawValue, "fontSize": fontSize.rawValue]).toString(pretty: false)
}
/// Encode the style to a dictionary that can be stored in the profile
func encode() -> [String:AnyObject] {
return ["theme": theme.rawValue, "fontType": fontType.rawValue, "fontSize": fontSize.rawValue]
}
init(theme: ReaderModeTheme, fontType: ReaderModeFontType, fontSize: ReaderModeFontSize) {
self.theme = theme
self.fontType = fontType
self.fontSize = fontSize
}
/// Initialize the style from a dictionary, taken from the profile. Returns nil if the object cannot be decoded.
init?(dict: [String:AnyObject]) {
let themeRawValue = dict["theme"] as? String
let fontTypeRawValue = dict["fontType"] as? String
let fontSizeRawValue = dict["fontSize"] as? Int
if themeRawValue == nil || fontTypeRawValue == nil || fontSizeRawValue == nil {
return nil
}
let theme = ReaderModeTheme(rawValue: themeRawValue!)
let fontType = ReaderModeFontType(rawValue: fontTypeRawValue!)
let fontSize = ReaderModeFontSize(rawValue: fontSizeRawValue!)
if theme == nil || fontType == nil || fontSize == nil {
return nil
}
self.theme = theme!
self.fontType = fontType!
self.fontSize = fontSize!
}
}
let DefaultReaderModeStyle = ReaderModeStyle(theme: .Light, fontType: .SansSerif, fontSize: ReaderModeFontSize.defaultSize)
/// This struct captures the response from the Readability.js code.
struct ReadabilityResult {
var domain = ""
var url = ""
var content = ""
var title = ""
var credits = ""
init?(object: AnyObject?) {
if let dict = object as? NSDictionary {
if let uri = dict["uri"] as? NSDictionary {
if let url = uri["spec"] as? String {
self.url = url
}
if let host = uri["host"] as? String {
self.domain = host
}
}
if let content = dict["content"] as? String {
self.content = content
}
if let title = dict["title"] as? String {
self.title = title
}
if let credits = dict["byline"] as? String {
self.credits = credits
}
} else {
return nil
}
}
/// Initialize from a JSON encoded string
init?(string: String) {
let object = JSON(string: string)
let domain = object["domain"].asString
let url = object["url"].asString
let content = object["content"].asString
let title = object["title"].asString
let credits = object["credits"].asString
if domain == nil || url == nil || content == nil || title == nil || credits == nil {
return nil
}
self.domain = domain!
self.url = url!
self.content = content!
self.title = title!
self.credits = credits!
}
/// Encode to a dictionary, which can then for example be json encoded
func encode() -> [String:AnyObject] {
return ["domain": domain, "url": url, "content": content, "title": title, "credits": credits]
}
/// Encode to a JSON encoded string
func encode() -> String {
return JSON(encode() as [String:AnyObject]).toString(pretty: false)
}
}
/// Delegate that contains callbacks that we have added on top of the built-in WKWebViewDelegate
protocol ReaderModeDelegate {
func readerMode(readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forBrowser browser: Browser)
func readerMode(readerMode: ReaderMode, didDisplayReaderizedContentForBrowser browser: Browser)
}
let ReaderModeNamespace = "_firefox_ReaderMode"
class ReaderMode: BrowserHelper {
var delegate: ReaderModeDelegate?
private weak var browser: Browser?
var state: ReaderModeState = ReaderModeState.Unavailable
private var originalURL: NSURL?
class func name() -> String {
return "ReaderMode"
}
required init(browser: Browser) {
self.browser = browser
// This is a WKUserScript at the moment because webView.evaluateJavaScript() fails with an unspecified error. Possibly script size related.
if let path = NSBundle.mainBundle().pathForResource("Readability", ofType: "js") {
if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as? String {
var userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
browser.webView!.configuration.userContentController.addUserScript(userScript)
}
}
// This is executed after a page has been loaded. It executes Readability and then fires a script message to let us know if the page is compatible with reader mode.
if let path = NSBundle.mainBundle().pathForResource("ReaderMode", ofType: "js") {
if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as? String {
var userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
browser.webView!.configuration.userContentController.addUserScript(userScript)
}
}
}
func scriptMessageHandlerName() -> String? {
return "readerModeMessageHandler"
}
private func handleReaderPageEvent(readerPageEvent: ReaderPageEvent) {
switch readerPageEvent {
case .PageShow:
delegate?.readerMode(self, didDisplayReaderizedContentForBrowser: browser!)
}
}
private func handleReaderModeStateChange(state: ReaderModeState) {
self.state = state
delegate?.readerMode(self, didChangeReaderModeState: state, forBrowser: browser!)
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
println("DEBUG: readerModeMessageHandler message: \(message.body)")
if let msg = message.body as? Dictionary<String,String> {
if let messageType = ReaderModeMessageType(rawValue: msg["Type"] ?? "") {
switch messageType {
case .PageEvent:
if let readerPageEvent = ReaderPageEvent(rawValue: msg["Value"] ?? "Invalid") {
handleReaderPageEvent(readerPageEvent)
}
break
case .StateChange:
if let readerModeState = ReaderModeState(rawValue: msg["Value"] ?? "Invalid") {
handleReaderModeStateChange(readerModeState)
}
break
}
}
}
}
var style: ReaderModeStyle = DefaultReaderModeStyle {
didSet {
if state == ReaderModeState.Active {
browser!.webView?.evaluateJavaScript("\(ReaderModeNamespace).setStyle(\(style.encode()))", completionHandler: {
(object, error) -> Void in
return
})
}
}
}
} | mpl-2.0 | e18debd5ab605f686edb6c6746c79ea9 | 33.182482 | 172 | 0.615697 | 5.15978 | false | false | false | false |
davedelong/DDMathParser | MathParser/Sources/MathParser/ExpressionRewriter.swift | 1 | 2300 | //
// ExpressionRewriter.swift
// DDMathParser
//
// Created by Dave DeLong on 8/25/15.
//
//
import Foundation
public struct ExpressionRewriter {
private let maxIterationCount: UInt
private var rules: Array<RewriteRule>
public static let `default` = ExpressionRewriter(rules: RewriteRule.defaultRules)
public init(rules: Array<RewriteRule>, maxIterationCount: UInt = 256) {
self.maxIterationCount = maxIterationCount
self.rules = rules
}
public mutating func addRule(_ rule: RewriteRule) {
rules.append(rule)
}
public func rewriteExpression(_ expression: Expression, substitutions: Substitutions = [:], evaluator: Evaluator = Evaluator.default) -> Expression {
var tmp = expression
var iterationCount: UInt = 0
repeat {
var changed = false
for rule in rules {
let rewritten = rewrite(tmp, usingRule: rule, substitutions: substitutions, evaluator: evaluator)
if rewritten != tmp {
changed = true
tmp = rewritten
}
}
if changed == false { break }
iterationCount += 1
} while iterationCount < maxIterationCount
if iterationCount >= maxIterationCount {
NSLog("replacement limit reached")
}
return tmp
}
private func rewrite(_ expression: Expression, usingRule rule: RewriteRule, substitutions: Substitutions, evaluator: Evaluator) -> Expression {
let simplified = expression.simplify(substitutions, evaluator: evaluator)
let rewritten = rule.rewrite(simplified, substitutions: substitutions, evaluator: evaluator)
if rewritten != expression { return rewritten }
guard case let .function(f, args) = rewritten.kind else { return rewritten }
let newArgs = args.map { rewrite($0, usingRule: rule, substitutions: substitutions, evaluator: evaluator) }
// if nothing changed, reture
guard args != newArgs else { return rewritten }
return Expression(kind: .function(f, newArgs), range: rewritten.range)
}
}
| mit | 30e9a50231aeb8de332c24d2c926dfd0 | 31.857143 | 153 | 0.603043 | 5.515588 | false | false | false | false |
gdimaggio/SwiftlyRater | SwiftlyRater/SRConstants.swift | 1 | 743 | //
// SRConstants.swift
// SwiftlyRaterSample
//
// Created by Gianluca Di Maggio on 1/7/17.
// Copyright © 2017 dima. All rights reserved.
//
import Foundation
struct SRConstants {
static let usesUntilPrompt = 10
static let daysUntilPrompt = 5
static let eventsUntilPrompt = 10
static let daysBeforeReminding = 2
static let rateButtonTitle = "Rate Now"
static let remindButtonTitle = "Maybe Later"
static let neverRemindButtonTitle = "No Thanks"
static let reviewTitle = "Rate %@"
static let reviewMessage = "Enjoying the app? Please take a moment to leave a five-star review on the AppStore! Your support is very much appreciated!"
}
| mit | 1e74591667dbc665325d6a47c738ed89 | 32.727273 | 165 | 0.660377 | 4.289017 | false | false | false | false |
wireapp/wire-ios-data-model | Tests/Source/Utils/RolesMigrationTests.swift | 1 | 5374 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import XCTest
@testable import WireDataModel
class RolesMigrationTests: DiskDatabaseTest {
func testMarkingTeamsAndConversationForDownalod() {
// Given
let selfUser = ZMUser.selfUser(in: moc)
let team = createTeam()
team.remoteIdentifier = UUID.create()
_ = createMembership(user: selfUser, team: team)
team.needsToDownloadRoles = false
let groupConvo = createConversation()
groupConvo.addParticipantAndUpdateConversationState(user: selfUser, role: nil)
groupConvo.userDefinedName = "Group"
groupConvo.needsToDownloadRoles = false
groupConvo.needsToBeUpdatedFromBackend = false
let groupConvoInTeam = createConversation()
groupConvoInTeam.addParticipantAndUpdateConversationState(user: selfUser, role: nil)
groupConvoInTeam.userDefinedName = "Group"
groupConvoInTeam.needsToDownloadRoles = false
groupConvoInTeam.needsToBeUpdatedFromBackend = false
groupConvoInTeam.team = team
let groupConvoInAnotherTeam = createConversation()
groupConvoInAnotherTeam.addParticipantAndUpdateConversationState(user: selfUser, role: nil)
groupConvoInAnotherTeam.userDefinedName = "Group"
groupConvoInAnotherTeam.needsToDownloadRoles = false
groupConvoInAnotherTeam.needsToBeUpdatedFromBackend = false
groupConvoInAnotherTeam.teamRemoteIdentifier = UUID.create()
let groupConvoThatUserLeft = createConversation()
groupConvoThatUserLeft.needsToDownloadRoles = false
groupConvoThatUserLeft.userDefinedName = "GroupThatUserLeft"
groupConvoThatUserLeft.needsToDownloadRoles = false
groupConvoThatUserLeft.needsToBeUpdatedFromBackend = false
let oneToOneConvo = createConversation()
oneToOneConvo.addParticipantAndUpdateConversationState(user: selfUser, role: nil)
oneToOneConvo.conversationType = .oneOnOne
oneToOneConvo.userDefinedName = "OneToOne"
oneToOneConvo.needsToDownloadRoles = false
oneToOneConvo.needsToBeUpdatedFromBackend = false
let selfConvo = ZMConversation.selfConversation(in: self.moc)
selfConvo.conversationType = .self
selfConvo.addParticipantAndUpdateConversationState(user: selfUser, role: nil)
selfConvo.userDefinedName = "Self"
selfConvo.needsToDownloadRoles = false
selfConvo.needsToBeUpdatedFromBackend = false
let connectionConvo = createConversation()
connectionConvo.conversationType = .connection
connectionConvo.addParticipantAndUpdateConversationState(user: selfUser, role: nil)
connectionConvo.userDefinedName = "Connection"
connectionConvo.needsToDownloadRoles = false
connectionConvo.needsToBeUpdatedFromBackend = false
self.moc.saveOrRollback()
// When
WireDataModel.ZMConversation.forceToFetchConversationRoles(in: moc)
// Then
XCTAssertFalse(groupConvoThatUserLeft.needsToDownloadRoles)
XCTAssertFalse(groupConvoThatUserLeft.needsToBeUpdatedFromBackend)
XCTAssertFalse(oneToOneConvo.needsToDownloadRoles)
XCTAssertFalse(oneToOneConvo.needsToBeUpdatedFromBackend)
XCTAssertFalse(selfConvo.needsToDownloadRoles)
XCTAssertFalse(selfConvo.needsToBeUpdatedFromBackend)
XCTAssertFalse(connectionConvo.needsToDownloadRoles)
XCTAssertFalse(connectionConvo.needsToBeUpdatedFromBackend)
XCTAssertFalse(groupConvoInTeam.needsToDownloadRoles)
XCTAssertTrue(groupConvoInTeam.needsToBeUpdatedFromBackend)
XCTAssertTrue(groupConvo.needsToDownloadRoles)
XCTAssertTrue(groupConvo.needsToBeUpdatedFromBackend)
XCTAssertTrue(groupConvoInAnotherTeam.needsToDownloadRoles)
XCTAssertTrue(groupConvoInAnotherTeam.needsToBeUpdatedFromBackend)
XCTAssertTrue(team.needsToDownloadRoles)
}
func testMigratingUsers() {
// Given
let oldKey = "lastServerSyncedActiveParticipants"
let user1 = ZMUser.insertNewObject(in: moc)
user1.name = "u1"
let user2 = ZMUser.insertNewObject(in: moc)
user2.name = "u2"
let groupConvo = createConversation()
let orderedSet = NSOrderedSet(array: [user1, user2])
groupConvo.setValue(orderedSet, forKey: oldKey)
self.moc.saveOrRollback()
// When
WireDataModel.ZMConversation.migrateUsersToParticipants(in: moc)
// Then
XCTAssertEqual(groupConvo.localParticipants, Set([user1, user2]))
XCTAssertEqual((groupConvo.value(forKey: oldKey) as! NSOrderedSet).count, 0)
}
}
| gpl-3.0 | 1e822365e436bcfa7308849a0361361b | 41.650794 | 99 | 0.738742 | 6.058625 | false | false | false | false |
hulu001/ImagePickerSheetController | ImagePickerSheetController/ImagePickerSheetController/Sheet/SheetPreviewCollectionViewCell.swift | 2 | 1369 | //
// SheetPreviewCollectionViewCell.swift
// ImagePickerSheetController
//
// Created by Laurin Brandner on 06/09/14.
// Copyright (c) 2014 Laurin Brandner. All rights reserved.
//
import UIKit
class SheetPreviewCollectionViewCell: SheetCollectionViewCell {
var collectionView: PreviewCollectionView? {
willSet {
if let collectionView = collectionView {
collectionView.removeFromSuperview()
}
if let collectionView = newValue {
addSubview(collectionView)
}
}
}
// MARK: - Other Methods
override func prepareForReuse() {
collectionView = nil
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
// Setting the frame of the collectionView this large avoids a small animation glitch when resizing the previews. You'll get a beer from @larcus94 if you'll get it to work without this workaround :)
if let collectionView = collectionView {
collectionView.frame = CGRect(x: -bounds.width, y: bounds.minY, width: 3 * bounds.width, height: bounds.height)
collectionView.contentInset = UIEdgeInsetsMake(0.0, bounds.width + backgroundInsets.left, 0.0, bounds.width + backgroundInsets.right)
}
}
}
| mit | 36027862e846688f7c6f6ca716f8c565 | 30.113636 | 206 | 0.631848 | 5.245211 | false | false | false | false |
exyte/Macaw | Source/views/Touchable.swift | 1 | 681 | class MTouchEvent: Hashable {
let id: Int
let x: Double
let y: Double
init(x: Double, y: Double, id: Int) {
self.x = x
self.y = y
self.id = id
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
public static func == (lhs: MTouchEvent, rhs: MTouchEvent) -> Bool {
return lhs.id == rhs.id
}
}
protocol Touchable {
func mTouchesBegan(_ touches: Set<MTouch>, with event: MEvent?)
func mTouchesMoved(_ touches: Set<MTouch>, with event: MEvent?)
func mTouchesEnded(_ touches: Set<MTouch>, with event: MEvent?)
func mTouchesCancelled(_ touches: Set<MTouch>, with event: MEvent?)
}
| mit | 430592a19735468f43ff79965191139d | 25.192308 | 72 | 0.610866 | 3.510309 | false | false | false | false |
Liqiankun/DLSwift | Swift/Swift控制转移.playground/Contents.swift | 1 | 530 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
var getAnswer = false
for m in 1...300{
for n in 1...300{
if m * m * m * m - n * n == 15 * m * n{
print(m,n)
getAnswer = true
break
}
}
if getAnswer{
break
}
}
findAnswer : for m in 1...300{
for n in 1...300{
if m * m * m * m - n * n == 15 * m * n{
print(m,n)
break findAnswer//结束这个循环
}
}
}
| mit | 6301991ea6e48d8eef3fd5ea22d9b44b | 15.709677 | 52 | 0.444015 | 3.2375 | false | false | false | false |
apple/swift-async-algorithms | Sources/AsyncAlgorithms/CombineLatest/CombineLatestStorage.swift | 1 | 12697 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 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
//
//===----------------------------------------------------------------------===//
final class CombineLatestStorage<
Base1: AsyncSequence,
Base2: AsyncSequence,
Base3: AsyncSequence
>: Sendable where
Base1: Sendable,
Base1.Element: Sendable,
Base2: Sendable,
Base2.Element: Sendable,
Base3: Sendable,
Base3.Element: Sendable {
typealias StateMachine = CombineLatestStateMachine<Base1, Base2, Base3>
private let stateMachine: ManagedCriticalState<StateMachine>
init(_ base1: Base1, _ base2: Base2, _ base3: Base3?) {
self.stateMachine = .init(.init(base1: base1, base2: base2, base3: base3))
}
func iteratorDeinitialized() {
let action = self.stateMachine.withCriticalRegion { $0.iteratorDeinitialized() }
switch action {
case .cancelTaskAndUpstreamContinuations(
let task,
let upstreamContinuation
):
upstreamContinuation.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
case .none:
break
}
}
func next() async rethrows -> (Base1.Element, Base2.Element, Base3.Element?)? {
try await withTaskCancellationHandler {
let result = await withUnsafeContinuation { continuation in
self.stateMachine.withCriticalRegion { stateMachine in
let action = stateMachine.next(for: continuation)
switch action {
case .startTask(let base1, let base2, let base3):
// first iteration, we start one child task per base to iterate over them
self.startTask(
stateMachine: &stateMachine,
base1: base1,
base2: base2,
base3: base3,
downStreamContinuation: continuation
)
case .resumeContinuation(let downstreamContinuation, let result):
downstreamContinuation.resume(returning: result)
case .resumeUpstreamContinuations(let upstreamContinuations):
// bases can be iterated over for 1 iteration so their next value can be retrieved
upstreamContinuations.forEach { $0.resume() }
case .resumeDownstreamContinuationWithNil(let continuation):
// the async sequence is already finished, immediately resuming
continuation.resume(returning: .success(nil))
}
}
}
print("Returning: \(result)")
return try result._rethrowGet()
} onCancel: {
self.stateMachine.withCriticalRegion { stateMachine in
let action = stateMachine.cancelled()
switch action {
case .resumeDownstreamContinuationWithNilAndCancelTaskAndUpstreamContinuations(
let downstreamContinuation,
let task,
let upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
downstreamContinuation.resume(returning: .success(nil))
case .cancelTaskAndUpstreamContinuations(let task, let upstreamContinuations):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
case .none:
break
}
}
}
}
private func startTask(
stateMachine: inout StateMachine,
base1: Base1,
base2: Base2,
base3: Base3?,
downStreamContinuation: StateMachine.DownstreamContinuation
) {
// This creates a new `Task` that is iterating the upstream
// sequences. We must store it to cancel it at the right times.
let task = Task {
await withThrowingTaskGroup(of: Void.self) { group in
// For each upstream sequence we are adding a child task that
// is consuming the upstream sequence
group.addTask {
var base1Iterator = base1.makeAsyncIterator()
loop: while true {
// We are creating a continuation before requesting the next
// element from upstream. This continuation is only resumed
// if the downstream consumer called `next` to signal his demand.
try await withUnsafeThrowingContinuation { continuation in
self.stateMachine.withCriticalRegion { stateMachine in
let action = stateMachine.childTaskSuspended(baseIndex: 0, continuation: continuation)
switch action {
case .resumeContinuation(let upstreamContinuation):
upstreamContinuation.resume()
case .resumeContinuationWithError(let upstreamContinuation, let error):
upstreamContinuation.resume(throwing: error)
case .none:
break
}
}
}
if let element1 = try await base1Iterator.next() {
self.stateMachine.withCriticalRegion { stateMachine in
let action = stateMachine.elementProduced((element1, nil, nil))
switch action {
case .resumeContinuation(let downstreamContinuation, let result):
downstreamContinuation.resume(returning: result)
case .none:
break
}
}
} else {
let action = self.stateMachine.withCriticalRegion { stateMachine in
stateMachine.upstreamFinished(baseIndex: 0)
}
switch action {
case .resumeContinuationWithNilAndCancelTaskAndUpstreamContinuations(
let downstreamContinuation,
let task,
let upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
downstreamContinuation.resume(returning: .success(nil))
break loop
case .cancelTaskAndUpstreamContinuations(let task, let upstreamContinuations):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
break loop
case .none:
break loop
}
}
}
}
group.addTask {
var base1Iterator = base2.makeAsyncIterator()
loop: while true {
// We are creating a continuation before requesting the next
// element from upstream. This continuation is only resumed
// if the downstream consumer called `next` to signal his demand.
try await withUnsafeThrowingContinuation { continuation in
self.stateMachine.withCriticalRegion { stateMachine in
let action = stateMachine.childTaskSuspended(baseIndex: 1, continuation: continuation)
switch action {
case .resumeContinuation(let upstreamContinuation):
upstreamContinuation.resume()
case .resumeContinuationWithError(let upstreamContinuation, let error):
upstreamContinuation.resume(throwing: error)
case .none:
break
}
}
}
if let element2 = try await base1Iterator.next() {
self.stateMachine.withCriticalRegion { stateMachine in
let action = stateMachine.elementProduced((nil, element2, nil))
switch action {
case .resumeContinuation(let downstreamContinuation, let result):
downstreamContinuation.resume(returning: result)
case .none:
break
}
}
} else {
let action = self.stateMachine.withCriticalRegion { stateMachine in
stateMachine.upstreamFinished(baseIndex: 1)
}
switch action {
case .resumeContinuationWithNilAndCancelTaskAndUpstreamContinuations(
let downstreamContinuation,
let task,
let upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
downstreamContinuation.resume(returning: .success(nil))
break loop
case .cancelTaskAndUpstreamContinuations(let task, let upstreamContinuations):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
break loop
case .none:
break loop
}
}
}
}
if let base3 = base3 {
group.addTask {
var base1Iterator = base3.makeAsyncIterator()
loop: while true {
// We are creating a continuation before requesting the next
// element from upstream. This continuation is only resumed
// if the downstream consumer called `next` to signal his demand.
try await withUnsafeThrowingContinuation { continuation in
self.stateMachine.withCriticalRegion { stateMachine in
let action = stateMachine.childTaskSuspended(baseIndex: 2, continuation: continuation)
switch action {
case .resumeContinuation(let upstreamContinuation):
upstreamContinuation.resume()
case .resumeContinuationWithError(let upstreamContinuation, let error):
upstreamContinuation.resume(throwing: error)
case .none:
break
}
}
}
if let element3 = try await base1Iterator.next() {
self.stateMachine.withCriticalRegion { stateMachine in
let action = stateMachine.elementProduced((nil, nil, element3))
switch action {
case .resumeContinuation(let downstreamContinuation, let result):
downstreamContinuation.resume(returning: result)
case .none:
break
}
}
} else {
let action = self.stateMachine.withCriticalRegion { stateMachine in
stateMachine.upstreamFinished(baseIndex: 2)
}
switch action {
case .resumeContinuationWithNilAndCancelTaskAndUpstreamContinuations(
let downstreamContinuation,
let task,
let upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
downstreamContinuation.resume(returning: .success(nil))
break loop
case .cancelTaskAndUpstreamContinuations(let task, let upstreamContinuations):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
break loop
case .none:
break loop
}
}
}
}
}
do {
try await group.waitForAll()
} catch {
// One of the upstream sequences threw an error
self.stateMachine.withCriticalRegion { stateMachine in
let action = stateMachine.upstreamThrew(error)
switch action {
case .cancelTaskAndUpstreamContinuations(let task, let upstreamContinuations):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
case .resumeContinuationWithErrorAndCancelTaskAndUpstreamContinuations(
let downstreamContinuation,
let error,
let task,
let upstreamContinuations
):
upstreamContinuations.forEach { $0.resume(throwing: CancellationError()) }
task.cancel()
downstreamContinuation.resume(returning: .failure(error))
case .none:
break
}
}
group.cancelAll()
}
}
}
stateMachine.taskIsStarted(task: task, downstreamContinuation: downStreamContinuation)
}
}
| apache-2.0 | a38624dcb176487ac94296fa0a0e74f4 | 34.46648 | 104 | 0.580216 | 6.301241 | false | false | false | false |
amdaza/HackerBooks | HackerBooks/HackerBooks/AGTBook.swift | 1 | 1812 | //
// AGTBook.swift
// HackerBooks
//
// Created by Alicia Daza on 03/07/16.
// Copyright © 2016 Alicia Daza. All rights reserved.
//
import UIKit
class AGTBook : Comparable {
let title: String
var authors: [String]
var tags: [String]
let image_url: URL
let pdf_url: URL
var favourite: Bool
let image: AsyncImage
var index: Int
// MARK: - Computed properties
var authorsDescription: String {
get {
return "Authors: " + authors.joined(separator: ", ")
}
}
var tagsText: String {
get {
let capTags = tags.map({"\n -> " + $0.capitalized})
return capTags.joined(separator: "\n")
}
}
// MARK: - Initialization
init(title: String, authors: [String],
tags: [String], image_url: URL,
pdf_url: URL, favourite: Bool,
image: AsyncImage) {
self.title = title
self.authors = authors
self.tags = tags
self.image_url = image_url
self.pdf_url = pdf_url
self.favourite = favourite
self.image = image
self.index = 0
}
//MARK: - Proxies
var proxyForComparison : String{
get {
return "\(title)\(image_url)\(pdf_url)"
}
}
func syncDownload(_ imageUrl: URL) -> UIImage? {
if let data = try? Data(contentsOf: imageUrl) {
return UIImage(data: data)
}
return nil
}
}
// Mark: - Equatable
func ==(lhs: AGTBook, rhs: AGTBook) -> Bool {
guard (lhs !== rhs) else {
return true
}
return lhs.proxyForComparison == rhs.proxyForComparison
}
// Mark: - Comparable
func <(lhs: AGTBook, rhs: AGTBook) -> Bool {
return lhs.title.lowercased() < rhs.title.lowercased()
}
| gpl-3.0 | 1a7458d1e16f4ef3ad3f152a9f725a46 | 21.085366 | 64 | 0.54942 | 3.911447 | false | false | false | false |
tony-dinh/today | today/today/SettingsController.swift | 1 | 1577 | //
// SettingsController.swift
// today
//
// Created by Tony Dinh on 2016-11-10.
// Copyright © 2016 Tony Dinh. All rights reserved.
//
import Foundation
import UIKit
class SettingsController:
BaseTableViewController,
UITableViewDelegate,
UITableViewDataSource
{
let settings: [String] = ["Calendars"]
override func viewDidLoad() {
super.viewDidLoad()
title = "Settings"
tableView.delegate = self
tableView.dataSource = self
tableView.register(
DefaultCell.self,
forCellReuseIdentifier: DefaultCell.constants.reuseIdentifier
)
}
// MARK: UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return settings.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return DefaultCell(accessoryType: .disclosureIndicator, text: settings[indexPath.row])
}
// MARK: UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch settings[indexPath.row] {
case "Calendars":
let calendarSettingsController = CalendarSettingsController()
navigationController?.pushViewController(calendarSettingsController, animated: true)
break;
default:
break;
}
}
}
| mit | 8ddf6c5c11b284b3871880a1e18483da | 26.649123 | 100 | 0.665609 | 5.472222 | false | false | false | false |
arvedviehweger/swift | test/decl/protocol/special/coding/class_codable_simple_extension.swift | 1 | 1258 | // RUN: %target-typecheck-verify-swift -verify-ignore-unknown
// Simple classes where Codable conformance is added in extensions should still
// derive conformance.
class SimpleClass {
var x: Int = 1
var y: Double = .pi
static var z: String = "foo"
// These lines have to be within the SimpleClass type because CodingKeys
// should be private.
func foo() {
// They should receive a synthesized CodingKeys enum.
let _ = SimpleClass.CodingKeys.self
// The enum should have a case for each of the vars.
let _ = SimpleClass.CodingKeys.x
let _ = SimpleClass.CodingKeys.y
// Static vars should not be part of the CodingKeys enum.
let _ = SimpleClass.CodingKeys.z // expected-error {{type 'SimpleClass.CodingKeys' has no member 'z'}}
}
}
extension SimpleClass : Codable {}
// These are wrapped in a dummy function to avoid binding a global variable.
func foo() {
// They should receive synthesized init(from:) and an encode(to:).
let _ = SimpleClass.init(from:)
let _ = SimpleClass.encode(to:)
// The synthesized CodingKeys type should not be accessible from outside the
// class.
let _ = SimpleClass.CodingKeys.self // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
}
| apache-2.0 | c2b252fb1851083553f9d6b3ea0acad3 | 33.944444 | 122 | 0.709062 | 4.264407 | false | false | false | false |
BridgeTheGap/KRAnimationKit | KRAnimationKit/UIViewExtension/UIView+BGColorAnim.swift | 1 | 2175 | //
// UIView+BGColorAnim.swift
// KRAnimationKit
//
// Created by Joshua Park on 15/10/2019.
//
import UIKit
import KRTimingFunction
// MARK: - Background color
public extension UIView {
// MARK: - Animate
@discardableResult
func animate(
backgroundColor color: CGColor,
duration: Double,
function: FunctionType = .linear,
reverses: Bool = false,
repeatCount: Float = 0.0,
completion: (() -> Void)? = nil)
-> String
{
return animate(
backgroundColor: color.uiColor,
duration: duration,
function: function,
reverses: reverses,
repeatCount: repeatCount,
completion: completion)
}
@discardableResult
func animate(
backgroundColor color: UIColor,
duration: Double,
function: FunctionType = .linear,
reverses: Bool = false,
repeatCount: Float = 0.0,
completion: (() -> Void)? = nil)
-> String
{
let animDesc = AnimationDescriptor(
view: self,
delay: 0.0,
property: .backgroundColor,
endValue: color,
duration: duration,
function: function)
return KRAnimation.animate(
animDesc,
reverses: reverses,
repeatCount: repeatCount,
completion: completion)
}
// MARK: - Chain
func chain(
backgroundColor color: CGColor,
duration: Double,
function: FunctionType = .linear)
-> [AnimationDescriptor]
{
return chain(backgroundColor: color.uiColor, duration: duration, function: function)
}
func chain(
backgroundColor color: UIColor,
duration: Double,
function: FunctionType = .linear)
-> [AnimationDescriptor]
{
return [
AnimationDescriptor(
view: self,
delay: 0.0,
property: .backgroundColor,
endValue: color,
duration: duration,
function: function),
]
}
}
| mit | 2e502aef16dcfd0533aa4a5027b9d353 | 23.438202 | 92 | 0.535632 | 5.215827 | false | false | false | false |
hlts2/SwiftyLogger | Sources/SwiftyLogger.swift | 1 | 2599 | import Foundation
open class SwiftyLogger {
private init() {}
public static let instance: SwiftyLogger = {
return SwiftyLogger()
}()
open var settings = LoggerSettings()
private func logIn(lebel: LogLebel, message : [String]?, fileName: String = #file, line: Int = #line ,funcName: String = #function) {
if settings.logHidden {
return
}
var output = ""
if settings.showEmoji {
output += lebel.emojiDescription()
}
if settings.showDate {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = settings.dateFormat
output += dateFormatter.string(from: Date()) + " "
}
output += "[" + lebel.description() + "] "
if settings.showFileName {
output += "[" + fileName.pregReplace(pattern: ".*/", with: "") + ":" + String(line) + "] "
}
if settings.showFunctionName {
output += funcName
}
if let messages = message {
output += " ▶ " + messages.joined(separator: ", ")
}
if settings.isFileWrite {
if FileDestination.generateFile(path: settings.filePath) {
FileDestination.addMessage(path: settings.filePath, message: output)
}
} else {
print(output)
}
}
open func verbose(message: String..., file: String = #file, line: Int = #line, function: String = #function) {
self.logIn(lebel: .verbose, message: message, fileName: file, line: line, funcName: function)
}
open func debug(message: String..., file: String = #file, line: Int = #line ,function: String = #function) {
self.logIn(lebel: .debug, message: message, fileName: file, line: line, funcName: function)
}
open func info(message: String..., file: String = #file, line: Int = #line ,function: String = #function) {
self.logIn(lebel: .info, message: message, fileName: file, line: line, funcName: function)
}
open func warn(message: String..., file: String = #file, line: Int = #line ,function: String = #function) {
self.logIn(lebel: .warn, message: message, fileName: file, line: line, funcName: function)
}
open func error(message: String..., file: String = #file, line: Int = #line ,function: String = #function) {
self.logIn(lebel: .error, message: message, fileName: file, line: line, funcName: function)
}
}
| mit | d8b58f95ceb2b594c7a3eace914675f5 | 34.094595 | 137 | 0.560647 | 4.48532 | false | false | false | false |
adamnemecek/AudioKit | Sources/AudioKit/Nodes/Node+connectionTreeDescription.swift | 1 | 1011 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import Foundation
let connectionTreeLinePrefix = "AudioKit | "
extension Node {
/// Nice printout of all the node connections
public var connectionTreeDescription: String {
return String(createConnectionTreeDescription().dropLast())
}
private func createConnectionTreeDescription(paddedWith indentation: String = "") -> String {
var nodeDescription = String(describing: self).components(separatedBy: ".").last ?? "Unknown"
if let namedSelf = self as? NamedNode {
nodeDescription += "(\"\(namedSelf.name)\")"
}
var connectionTreeDescription = "\(connectionTreeLinePrefix)\(indentation)↳\(nodeDescription)\n"
for connectionNode in self.connections {
connectionTreeDescription += connectionNode.createConnectionTreeDescription(paddedWith: " "+indentation)
}
return connectionTreeDescription
}
}
| mit | d3fbbb4cb1d99d1257ab5c07e0afa6e5 | 35.035714 | 116 | 0.700694 | 5.227979 | false | false | false | false |
sekouperry/bemyeyes-ios | BeMyEyes/Source/Controllers/DemoCallVideoViewController.swift | 2 | 1572 | //
// DemoCallVideoViewController.swift
// BeMyEyes
//
// Created by Simon Støvring on 22/01/15.
// Copyright (c) 2015 Be My Eyes. All rights reserved.
//
import UIKit
class DemoCallVideoViewController: VideoViewController {
@IBOutlet weak var cancelButton: Button!
internal var completion: ((UIViewController) -> ())?;
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
MKLocalization.registerForLocalization(self)
let isIpad = UIDevice.currentDevice().userInterfaceIdiom == .Pad
moviePlayerController.scalingMode = isIpad ? .AspectFit : .AspectFill
if let videoPath = NSBundle.mainBundle().pathForResource("demo", ofType: "mp4") {
let videoUrl = NSURL(fileURLWithPath: videoPath)
moviePlayerController.contentURL = videoUrl
moviePlayerController.play()
}
if let movieView = moviePlayerController.view {
view.insertSubview(movieView, belowSubview: cancelButton)
}
}
override func accessibilityPerformEscape() -> Bool {
navigationController?.popViewControllerAnimated(false)
return true
}
// MARK: - Private methods
@IBAction func cancelButtonPressed(sender: AnyObject) {
dismiss()
}
override func finishedPlaying() {
super.finishedPlaying()
dismiss()
}
private func dismiss() {
if let completion = completion {
completion(self)
}
}
}
extension DemoCallVideoViewController: MKLocalizable {
func shouldLocalize() {
cancelButton.title = MKLocalizedFromTable("BME_CALL_DISCONNECT", "BMECallLocalizationTable");
}
}
| mit | e08a0f21cf4ba945af24e416c83716cf | 23.546875 | 101 | 0.715468 | 4.376045 | false | false | false | false |
JaSpa/swift | test/IRGen/sil_witness_tables.swift | 3 | 3872 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-module -o %t %S/sil_witness_tables_external_conformance.swift
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -assume-parsing-unqualified-ownership-sil -I %t -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
import sil_witness_tables_external_conformance
// FIXME: This should be a SIL test, but we can't parse sil_witness_tables
// yet.
protocol A {}
protocol P {
associatedtype Assoc: A
static func staticMethod()
func instanceMethod()
}
protocol Q : P {
func qMethod()
}
protocol QQ {
func qMethod()
}
struct AssocConformer: A {}
struct Conformer: Q, QQ {
typealias Assoc = AssocConformer
static func staticMethod() {}
func instanceMethod() {}
func qMethod() {}
}
// CHECK: [[EXTERNAL_CONFORMER_EXTERNAL_P_WITNESS_TABLE:@_T039sil_witness_tables_external_conformance17ExternalConformerVAA0F1PAAWP]] = external global i8*, align 8
// CHECK: [[CONFORMER_Q_WITNESS_TABLE:@_T018sil_witness_tables9ConformerVAA1QAAWP]] = hidden constant [2 x i8*] [
// CHECK: i8* bitcast ([4 x i8*]* [[CONFORMER_P_WITNESS_TABLE:@_T018sil_witness_tables9ConformerVAA1PAAWP]] to i8*),
// CHECK: i8* bitcast (void (%V18sil_witness_tables9Conformer*, %swift.type*, i8**)* @_T018sil_witness_tables9ConformerVAA1QAaaDP7qMethod{{[_0-9a-zA-Z]*}}FTW to i8*)
// CHECK: ]
// CHECK: [[CONFORMER_P_WITNESS_TABLE]] = hidden constant [4 x i8*] [
// CHECK: i8* bitcast (%swift.type* ()* @_T018sil_witness_tables14AssocConformerVMa to i8*),
// CHECK: i8* bitcast (i8** ()* @_T018sil_witness_tables14AssocConformerVAA1AAAWa to i8*)
// CHECK: i8* bitcast (void (%swift.type*, %swift.type*, i8**)* @_T018sil_witness_tables9ConformerVAA1PAaaDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW to i8*),
// CHECK: i8* bitcast (void (%V18sil_witness_tables9Conformer*, %swift.type*, i8**)* @_T018sil_witness_tables9ConformerVAA1PAaaDP14instanceMethod{{[_0-9a-zA-Z]*}}FTW to i8*)
// CHECK: ]
// CHECK: [[CONFORMER2_P_WITNESS_TABLE:@_T018sil_witness_tables10Conformer2VAA1PAAWP]] = hidden constant [4 x i8*]
struct Conformer2: Q {
typealias Assoc = AssocConformer
static func staticMethod() {}
func instanceMethod() {}
func qMethod() {}
}
// CHECK-LABEL: define hidden void @_T018sil_witness_tables7erasureAA2QQ_pAA9ConformerV1c_tF(%P18sil_witness_tables2QQ_* noalias nocapture sret)
// CHECK: [[WITNESS_TABLE_ADDR:%.*]] = getelementptr inbounds %P18sil_witness_tables2QQ_, %P18sil_witness_tables2QQ_* %0, i32 0, i32 2
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* [[CONFORMER_QQ_WITNESS_TABLE:@_T0.*WP]], i32 0, i32 0), i8*** [[WITNESS_TABLE_ADDR]], align 8
func erasure(c c: Conformer) -> QQ {
return c
}
// CHECK-LABEL: define hidden void @_T018sil_witness_tables15externalErasure0a1_b1_c1_D12_conformance9ExternalP_pAC0G9ConformerV1c_tF(%P39sil_witness_tables_external_conformance9ExternalP_* noalias nocapture sret)
// CHECK: [[WITNESS_TABLE_ADDR:%.*]] = getelementptr inbounds %P39sil_witness_tables_external_conformance9ExternalP_, %P39sil_witness_tables_external_conformance9ExternalP_* %0, i32 0, i32 2
// CHECK-NEXT: store i8** [[EXTERNAL_CONFORMER_EXTERNAL_P_WITNESS_TABLE]], i8*** %2, align 8
func externalErasure(c c: ExternalConformer) -> ExternalP {
return c
}
// FIXME: why do these have different linkages?
// CHECK-LABEL: define hidden %swift.type* @_T018sil_witness_tables14AssocConformerVMa()
// CHECK: ret %swift.type* bitcast (i64* getelementptr inbounds {{.*}} @_T018sil_witness_tables14AssocConformerVMf, i32 0, i32 1) to %swift.type*)
// CHECK-LABEL: define hidden i8** @_T018sil_witness_tables9ConformerVAA1PAAWa()
// CHECK: ret i8** getelementptr inbounds ([4 x i8*], [4 x i8*]* @_T018sil_witness_tables9ConformerVAA1PAAWP, i32 0, i32 0)
| apache-2.0 | b381c7b03137e2ebd50614e6f8823af4 | 47.4 | 213 | 0.715134 | 3.22398 | false | false | false | false |
alokard/savings-assistant | savings-assistant/SettingsViewController.swift | 3 | 1619 | //
// SettingsViewController.swift
// savings-assistant
//
// Created by Chris Amanse on 8/4/15.
// Copyright (c) 2015 Joe Christopher Paul Amanse. All rights reserved.
//
import UIKit
class SettingsViewController: UITableViewController {
var indexPathForAcknowledgements: NSIndexPath {
return NSIndexPath(forRow: 0, inSection: 0)
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch indexPath {
case indexPathForAcknowledgements:
if let plistPath = NSBundle.mainBundle().pathForResource("Pods-savings-assistant-acknowledgements", ofType: "plist") {
let viewController = AcknowledgementsViewController(acknowledgementsPlistPath: plistPath)
let navController = UINavigationController(rootViewController: viewController)
splitViewController?.showDetailViewController(navController, sender: self)
}
default:
break
}
}
}
| gpl-2.0 | 3494d27ce184d141c3c3fdf9f131b6d0 | 33.446809 | 130 | 0.69055 | 5.887273 | false | false | false | false |
27629678/RxDemo | RxDemo/SearchViewController.swift | 1 | 1756 | //
// SearchViewController.swift
// RxDemo
//
// Created by hzyuxiaohua on 2016/10/25.
// Copyright © 2016年 hzyuxiaohua. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class SearchViewController: UIViewController {
let disposeBag = DisposeBag()
var myDisposable: Disposable? = nil
@IBOutlet weak var input: UITextField!
@IBOutlet weak var `switch`: UISwitch!
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
title = "Search"
// bind switch action
`switch`.rx.value
.subscribe(onNext: { [weak self] in self?.switchBtnAction(isOn: $0)} )
.addDisposableTo(disposeBag)
}
func switchBtnAction(isOn: Bool) {
input.text = ""
textView.text = ""
myDisposable?.dispose()
if isOn {
textView.text.append("Throttle")
myDisposable = input.rx.text
.throttle(1, scheduler: MainScheduler.instance)
.subscribe(onNext: { [weak self] in self?.handle($0) })
}
else {
textView.text.append("Debounce")
myDisposable = input.rx.text
.debounce(1, scheduler: MainScheduler.instance)
.subscribe(onNext: { [weak self] in self?.handle($0) })
}
myDisposable?.addDisposableTo(disposeBag)
}
func handle(_ keyword: String?) {
guard let text = keyword, text.characters.count > 0 else {
return
}
textView.text.append("\n" + String(Int(Date().timeIntervalSince1970)) + "\t:" + text)
}
}
| mit | f79fe6bd2e866fcda9fa7770c6e6a2e8 | 26.390625 | 93 | 0.575585 | 4.649867 | false | false | false | false |
eRGoon/RGPageViewController | RGPageViewController/RGPageViewController/Source/Extensions/RGPageViewController+UICollectionViewDataSource.swift | 1 | 1177 | //
// RGPageViewController+UICollectionViewDataSource.swift
// RGPageViewController
//
// Created by Ronny Gerasch on 23.01.17.
// Copyright © 2017 Ronny Gerasch. All rights reserved.
//
import Foundation
// MARK: - UICollectionViewDataSource
extension RGPageViewController: UICollectionViewDataSource {
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return pageCount
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "rgTabCell", for: indexPath)
cell.tag = indexPath.row
if let tabView = tabViewAtIndex(indexPath.row) {
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
if indexPath.row == currentTabIndex {
tabView.selected = true
} else {
tabView.selected = false
}
cell.contentView.addSubview(tabView)
}
return cell
}
}
| mit | d7bfc1acc3db59e87e96fd0fa6bf8bea | 27 | 126 | 0.702381 | 5.135371 | false | false | false | false |
moosichu/hac-website | Sources/HaCWebsiteLib/Views/LandingPage/LandingPage.swift | 1 | 8852 | import HaCTML
// swiftlint:disable line_length
struct LandingPage: Nodeable {
let updates: [PostCard]
let feature: LandingFeature?
let youtubeUrl = "https://www.youtube.com/hackersatcambridge"
let facebookUrl = "https://www.facebook.com/hackersatcambridge"
let githubUrl = "https://github.com/hackersatcambridge/"
let mediumUrl = "https://medium.com/hackers-at-cambridge"
let calendarUrl = "https://calendar.google.com/calendar/embed?src=10isedeg17ugvrvg73jq9p5gts%40group.calendar.google.com&ctz=Europe/London"
let demonstratorsGroupUrl = "https://www.facebook.com/groups/1567785333234852/"
var featureNode: Nodeable? {
return feature.map{ feature in
El.Section[Attr.className => "LandingFeature LandingTop__feature"].containing(
El.H1[Attr.className => "LandingFeature__subtitle Text--sectionHeading"].containing("Featured"),
El.Div[Attr.className => "LandingFeature__hero"].containing(feature)
)
}
}
var node: Node {
return Page(
title: "Hackers at Cambridge",
content: Fragment(
El.Div[Attr.className => "LandingTop"].containing(
El.Header[Attr.className => "LandingIntroduction LandingTop__introduction"].containing(
El.Div[Attr.className => "LandingIntroduction__titleContainer"].containing(
El.Img[
Attr.className => "SiteLogo",
Attr.src => Assets.publicPath("/images/hac-logo-dark.svg"),
Attr.alt => "Hackers at Cambridge"
],
El.Div[Attr.className => "TagLine"].containing("Cambridge's student tech society")
),
El.P[Attr.className => "LandingIntroduction__missionStatement"].containing("We are a community focused on learning about and building things with technology."),
El.A[Attr.href => "http://eepurl.com/ckeD2b"].containing(
El.Div[Attr.className => "BigButton"].containing(
"Join our mailing list"
)
),
El.Div[Attr.className => "LandingIntroduction__social"].containing(
El.Div[Attr.className => "LandingIntroduction__socialText"].containing("And find us on"),
El.Div[Attr.className => "LandingIntroduction__socialIconRow"].containing(
El.A[Attr.href => githubUrl, Attr.className => "LandingIntroduction__socialLinkIcon"].containing(
El.Img[
Attr.className => "LandingIntroduction__socialLinkIconImg",
Attr.src => Assets.publicPath("/images/github_icon.svg"),
Attr.alt => "GitHub"
]
),
El.A[Attr.href => facebookUrl, Attr.className => "LandingIntroduction__socialLinkIcon"].containing(
El.Img[
Attr.className => "LandingIntroduction__socialLinkIconImg",
Attr.src => Assets.publicPath("/images/facebook_icon.svg"),
Attr.alt => "Facebook"
]
),
El.A[Attr.href => youtubeUrl, Attr.className => "LandingIntroduction__socialLinkIcon"].containing(
El.Img[
Attr.className => "LandingIntroduction__socialLinkIconImg",
Attr.src => Assets.publicPath("/images/youtube_icon.svg"),
Attr.alt => "YouTube"
]
),
El.A[Attr.href => mediumUrl, Attr.className => "LandingIntroduction__socialLinkIcon"].containing(
El.Img[
Attr.className => "LandingIntroduction__socialLinkIconImg",
Attr.src => Assets.publicPath("/images/medium_icon.svg"),
Attr.alt => "Medium"
]
)
)
)
),
featureNode
),
// El.Section[Attr.className => "LandingUpdateFeed"].containing(
// El.H1[Attr.className => "LandingUpdateFeed__title Text--sectionHeading"].containing("Updates"),
// El.Div[Attr.className => "LandingUpdateFeed__postContainer"].containing(
// updates.map {
// El.Div[Attr.className => "LandingUpdateFeed__item"].containing($0)
// }
// )
// ),
El.Article[Attr.className => "LandingAbout", Attr.id => "about"].containing(
El.Div[Attr.className => "LandingAbout__section"].containing(
El.Div[Attr.className => "LandingAbout__imageContainer"].containing(
El.Img[
Attr.className => "LandingAbout__image",
Attr.src => Assets.publicPath("/images/whoishac.jpg")
]
),
El.Div[Attr.className => "LandingAbout__text"].containing(
El.H1[Attr.className => "LandingAbout__subtitle Text--sectionHeading"].containing("About"),
El.H2[Attr.className => "Text--headline"].containing("Who are Hackers at Cambridge?"),
Markdown("""
Don't let the name scare you, we aren't the kind of hackers that try our best to get around complex security systems. We are simply an enthusiastic group of people who love technology.
At HaC it’s our mission to empower everyone to build whatever technology project they want. Whether you are a complete beginner or a seasoned pro, we're here to help you develop and share your tech skills.
""")
)
),
El.Article[Attr.className => "LandingAbout__section"].containing(
El.Div[Attr.className => "LandingAbout__imageContainer"].containing(
El.Img[
Attr.className => "LandingAbout__image",
Attr.src => Assets.publicPath("/images/hacworkshop.jpg")
]
),
El.Div[Attr.className => "LandingAbout__text"].containing(
El.H1[Attr.className => "Text--headline"].containing("Workshops"),
Markdown("""
Run by members of the community and open to everyone, our workshops aim to inspire and to teach practical technology skills.
If you've missed one of our workshops and would like to catch up, check out our [YouTube page](\(youtubeUrl)) for recordings.
If you would like to help out at one of our workshops, join the [demonstrators group](\(demonstratorsGroupUrl)), we'd love to have you!
"""),
El.A[
Attr.href => "/workshops",
Attr.className => "BigButton"
].containing(
"Check out our workshops"
)
)
),
El.Article[Attr.className => "LandingAbout__section"].containing(
El.Div[Attr.className => "LandingAbout__imageContainer"].containing(
El.Img[
Attr.className => "LandingAbout__image",
Attr.src => Assets.publicPath("/images/hachackathon.jpg")
]
),
El.Div[Attr.className => "LandingAbout__text"].containing(
El.H1[Attr.className => "Text--headline"].containing("Hackathons and Game Jams"),
Markdown("""
At the end of the Michaelmas we run the annual Hackers at Cambridge Game Gig - a fun and friendly competition where 100 Cambridge students from a wide variety of courses get together to make games in 12 hours
At the end of the Lent term we additionally run an annual themed hackathon. Last year we partnered with charities in order to tackle problems around the world.
These competitions naturally come with lots of awesome free food.
""")
)
),
El.Article[Attr.className => "LandingAbout__section"].containing(
El.Div[Attr.className => "LandingAbout__imageContainer"].containing(
El.Img[
Attr.className => "LandingAbout__image",
Attr.src => Assets.publicPath("/images/hashcode.jpg")
]
),
El.Div[Attr.className => "LandingAbout__text"].containing(
El.H1[Attr.className => "Text--headline"].containing("HaC Nights"),
Markdown("""
HaC Nights are weekly events we run for people of all experience levels! If you have something you’re working on - be it a project, some supervision work or coursework – then a HaC night is a great social environment for getting things done.
We’ll bring the food, you bring the work and if you get stuck, there’s bound to be someone in the room who can help you out!
Find us on [our Facebook page](\(facebookUrl)) to stay up to date
""")
)
)
)
)
).node
}
}
| mit | 392b867ebeacbfa8309fd5303c03a2e4 | 50.707602 | 257 | 0.583465 | 4.723291 | false | false | false | false |
crossroadlabs/Boilerplate | Sources/Boilerplate/Curry.swift | 1 | 1787 | //===--- Curry.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//===----------------------------------------------------------------------===//
public func curry<A, B, Z>(_ f: @escaping (A, B)->Z) -> (A) -> (B) -> Z {
return { a in
{ b in
f(a, b)
}
}
}
public func curry<A, B, C, Z>(_ f: @escaping (A, B, C)->Z) -> (A) -> (B) -> (C) -> Z {
return { a in
{ b in
{ c in
f(a, b, c)
}
}
}
}
public func curry<A, B, C, D, Z>(_ f: @escaping (A, B, C, D)->Z) -> (A) -> (B) -> (C) -> (D) -> Z {
return { a in
{ b in
{ c in
{ d in
f(a, b, c, d)
}
}
}
}
}
public func uncurry<A, B, Z>(_ f: @escaping (A) -> (B) -> Z) -> (A, B) -> Z {
return { a, b in
f(a)(b)
}
}
public func uncurry<A, B, C, Z>(_ f: @escaping (A) -> (B) -> (C) -> Z) -> (A, B, C) -> Z {
return { a, b, c in
f(a)(b)(c)
}
}
public func uncurry<A, B, C, D, Z>(_ f: @escaping (A) -> (B) -> (C) -> (D) -> Z) -> (A, B, C, D) -> Z {
return { a, b, c, d in
f(a)(b)(c)(d)
}
}
| apache-2.0 | 0f8460f6fc2027529cae7e304a7b55e9 | 27.365079 | 103 | 0.438724 | 3.185383 | false | false | false | false |
Yalantis/Segmentio | Segmentio/Source/Cells/SegmentioCellWithImageAfterLabel.swift | 1 | 2118 | //
// SegmentioCellWithImageAfterLabel.swift
// Segmentio
//
// Created by Dmitriy Demchenko
// Copyright © 2016 Yalantis Mobile. All rights reserved.
//
import UIKit
final class SegmentioCellWithImageAfterLabel: SegmentioCell {
override func setupConstraintsForSubviews() {
super.setupConstraintsForSubviews()
guard let imageContainerView = imageContainerView else {
return
}
guard let containerView = containerView else {
return
}
let metrics = ["labelHeight": SegmentioCell.segmentTitleLabelHeight]
let views = [
"imageContainerView": imageContainerView,
"containerView": containerView
]
// main constraints
let segmentImageViewVerticalConstraint = NSLayoutConstraint.constraints(
withVisualFormat: "V:[imageContainerView(labelHeight)]",
options: [.alignAllCenterY],
metrics: metrics,
views: views)
NSLayoutConstraint.activate(segmentImageViewVerticalConstraint)
let contentViewHorizontalConstraints = NSLayoutConstraint.constraints(
withVisualFormat: "|-[containerView]-[imageContainerView(labelHeight)]-|",
options: [.alignAllCenterY],
metrics: metrics,
views: views)
NSLayoutConstraint.activate(contentViewHorizontalConstraints)
// custom constraints
topConstraint = NSLayoutConstraint(
item: containerView,
attribute: .top,
relatedBy: .equal,
toItem: contentView,
attribute: .top,
multiplier: 1,
constant: padding
)
topConstraint?.isActive = true
bottomConstraint = NSLayoutConstraint(
item: contentView,
attribute: .bottom,
relatedBy: .equal,
toItem: containerView,
attribute: .bottom,
multiplier: 1,
constant: padding
)
bottomConstraint?.isActive = true
}
}
| mit | f53846da3e80bb03c83bb82ef0a61a66 | 30.132353 | 86 | 0.601323 | 6.319403 | false | false | false | false |
quire-io/SwiftyChrono | Sources/Parsers/Parser.swift | 1 | 3172 | //
// Parser.swift
// SwiftyChrono
//
// Created by Jerry Chen on 1/18/17.
// Copyright © 2017 Potix. All rights reserved.
//
import Foundation
public class Parser {
let strictMode: Bool
var pattern: String { return "" }
var language: Language { return .english }
public init(strictMode: Bool) {
self.strictMode = strictMode
}
public func extract(text: String, ref: Date, match: NSTextCheckingResult, opt: [OptionType: Int]) -> ParsedResult? {
return nil
}
public func execute(text: String, ref: Date, opt: [OptionType: Int]) -> [ParsedResult] {
var results = [ParsedResult]()
let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive)
var startIndex = 0
var remainingText = text
var match = regex?.firstMatch(in: text, range: NSRange(location: startIndex, length: remainingText.count))
while let existingMatch = match {
let result = extract(text: text, ref: ref, match: existingMatch, opt: opt)
if let result = result {
if !result.isMoveIndexMode { // extraction is success, normal mode
// If success, start from the end of the result
startIndex = result.index + result.text.count
remainingText = String(text[text.index(text.startIndex, offsetBy: startIndex)...])
if !strictMode || result.hasPossibleDates() {
results.append(result)
}
} else { // extraction is failure, skip this extraction and move on to specific index
startIndex = result.index
remainingText = text.substring(from: startIndex)
}
} else { // extraction is failure
// If fail, move on by 1
let location = existingMatch.range.location + 1
remainingText = String(text[text.index(text.startIndex, offsetBy: location)...])
startIndex = location
}
let remainingTextLength = remainingText.count
match = remainingTextLength > 0 ?
regex?.firstMatch(in: text, range: NSRange(location: startIndex, length: remainingTextLength)) : nil
}
return results
}
final func matchTextAndIndex(from text: String, andMatchResult matchResult: NSTextCheckingResult) -> (matchText: String, index: Int) {
let index1Length = matchResult.range(at: 1).length
let matchText = matchResult.string(from: text, atRangeIndex: 0).substring(from: index1Length)
let index = matchResult.range(at: 0).location + index1Length
return (matchText, index)
}
final func matchTextAndIndexForCHHant(from text: String, andMatchResult matchResult: NSTextCheckingResult) -> (matchText: String, index: Int) {
let matchText = matchResult.string(from: text, atRangeIndex: 0)
let index = matchResult.range(at: 0).location
return (matchText, index)
}
}
| mit | a76e40d0f21cc50db94fa894f1cab9ee | 39.653846 | 147 | 0.594765 | 4.962441 | false | false | false | false |
parrotbait/CorkWeather | CorkWeather/Source/AppDelegate.swift | 1 | 1500 | //
// AppDelegate.swift
// Cork Weather
//
// Created by Eddie Long on 03/08/2017.
// Copyright © 2017 eddielong. All rights reserved.
//
import UIKit
import Firebase
import SWLogger
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var coordinator: MainCoordinator?
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
#if DEBUG
//Log.setTagFilters(tags: ["MainVC"])
Log.setLevel(.debug)
if let docDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
print ("Documents directory: \(docDirectory)")
}
#endif
/*let logger = DefaultFileHandler()
Log.addHandler(logger)
*/
let navController = UINavigationController()
// send that into our coordinator so that it can display view controllers
coordinator = MainCoordinator(navController: navController)
// tell the coordinator to take over control
coordinator?.start()
// create a basic UIWindow and activate it
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = navController
window?.makeKeyAndVisible()
// Override point for customization after application launch.
return true
}
}
| mit | 8992bdd3d044c8cec83573b40b88fcd9 | 28.98 | 145 | 0.658439 | 5.29682 | false | false | false | false |
stripe/stripe-ios | StripePaymentSheet/StripePaymentSheet/PaymentSheet/Views/UIKit+PaymentSheet.swift | 1 | 4519 | //
// UIKit+PaymentSheet.swift
// StripePaymentSheet
//
// Created by Yuki Tokuhiro on 11/10/20.
// Copyright © 2020 Stripe, Inc. All rights reserved.
//
import Foundation
import PassKit
import UIKit
@_spi(STP) import StripeCore
@_spi(STP) import StripeUICore
enum PaymentSheetUI {
/// The padding between views in the sheet e.g., between the bottom of the form and the Pay button
static let defaultPadding: CGFloat = 20
static let defaultMargins: NSDirectionalEdgeInsets = .insets(
leading: defaultPadding, trailing: defaultPadding)
static let defaultSheetMargins: NSDirectionalEdgeInsets = .insets(
leading: defaultPadding, bottom: 36, trailing: defaultPadding)
static let minimumTapSize: CGSize = CGSize(width: 44, height: 44)
static let defaultAnimationDuration: TimeInterval = 0.2
static let quickAnimationDuration: TimeInterval = 0.1
/// The minimnum amount of time to spend processing before transitioning to success/failure
static let minimumFlightTime: TimeInterval = 1
static let delayBetweenSuccessAndDismissal: TimeInterval = 1.5
static let minimumHitArea = CGSize(width: 44, height: 44)
static func makeHeaderLabel(appearance: PaymentSheet.Appearance) -> UILabel {
let header = UILabel()
header.textColor = appearance.colors.text
header.numberOfLines = 2
header.font = appearance.scaledFont(for: appearance.font.base.bold, style: .title3, maximumPointSize: 35)
header.accessibilityTraits = [.header]
header.adjustsFontSizeToFitWidth = true
header.adjustsFontForContentSizeCategory = true
return header
}
}
extension PKPaymentButtonStyle {
static var compatibleAutomatic: PKPaymentButtonStyle {
if #available(iOS 14.0, *) {
return .automatic
} else {
return .black
}
}
}
extension UIViewController {
func switchContentIfNecessary(
to toVC: UIViewController, containerView: DynamicHeightContainerView
) {
assert(children.count <= 1)
// Swap out child view controllers if necessary
if let fromVC = children.first {
guard fromVC != toVC else {
return
}
// Add the new one
self.addChild(toVC)
toVC.view.alpha = 0
containerView.addPinnedSubview(toVC.view)
containerView.layoutIfNeeded() // Lay the view out now or it animates layout from a zero size
// Remove the child view controller, but don't remove its view yet - keep it on screen so we can fade it out
fromVC.willMove(toParent: nil)
fromVC.removeFromParent()
animateHeightChange(
{
containerView.updateHeight()
toVC.didMove(toParent: self)
fromVC.view.alpha = 0
toVC.view.alpha = 1
},
completion: { _ in
// Remove the old one
self.remove(childViewController: fromVC)
UIAccessibility.post(notification: .screenChanged, argument: toVC.view)
}
)
} else {
addChild(toVC)
containerView.addPinnedSubview(toVC.view)
containerView.updateHeight()
toVC.didMove(toParent: self)
containerView.setNeedsLayout()
containerView.layoutIfNeeded()
UIAccessibility.post(notification: .screenChanged, argument: toVC.view)
}
}
func remove(childViewController: UIViewController) {
childViewController.view.removeFromSuperview()
childViewController.didMove(toParent: nil)
}
}
extension UIFont {
var regular: UIFont { return withWeight(.regular) }
var medium: UIFont { return withWeight(.medium) }
var bold: UIFont { return withWeight(.bold) }
private func withWeight(_ weight: UIFont.Weight) -> UIFont {
var attributes = fontDescriptor.fontAttributes
var traits = (attributes[.traits] as? [UIFontDescriptor.TraitKey: Any]) ?? [:]
traits[.weight] = weight
attributes[.name] = nil // nil out name so we fallback on the font family to compute the correct weight
attributes[.traits] = traits
attributes[.family] = familyName
let descriptor = UIFontDescriptor(fontAttributes: attributes)
return UIFont(descriptor: descriptor, size: pointSize)
}
}
| mit | d1afef072641b930ad747b97c184d986 | 36.032787 | 120 | 0.643205 | 5.181193 | false | false | false | false |
tensorflow/codelabs | ODML/ImageClassificationMobile/ios/ImageClassifierStep2/ImageClassifierStep2/ViewController.swift | 2 | 3005 | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ViewController.swift
// ImageClassifierStep2
//
// Created by Laurence Moroney on 3/31/21.
//
import UIKit
import MLKitVision
import MLKit
import MLKitImageLabelingCommon
import MLKitImageLabelingCustom
class ViewController: UIViewController {
@IBAction func doClassification(_ sender: Any) {
getLabels(with: imageView.image!)
}
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var lblOutput: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
imageView.image = UIImage(named:"flower2.jpg")
}
// This is called when the user presses the button
func getLabels(with image: UIImage){
// Get the image from the UI Image element and set its orientation
let visionImage = VisionImage(image: image)
visionImage.orientation = image.imageOrientation
// Add this code to use a custom model
let localModelFilePath = Bundle.main.path(forResource: "model", ofType: "tflite")
let localModel = LocalModel(path: localModelFilePath!)
// Create Image Labeler options, and set the threshold to 0.4
// so we will ignore all classes with a probability of 0.4 or less
let options = CustomImageLabelerOptions(localModel: localModel)
options.confidenceThreshold = 0.4
// Initialize the labeler with these options
let labeler = ImageLabeler.imageLabeler(options: options)
// And then process the image, with the callback going to self.processresult
labeler.process(visionImage) { labels, error in
self.processResult(from: labels, error: error)
}
}
// This gets called by the labeler's callback
func processResult(from labels: [ImageLabel]?, error: Error?){
// String to hold the labels
var labeltexts = ""
// Check that we have valid labels first
guard let labels = labels else{
return
}
// ...and if we do we can iterate through the set to get the description and confidence
for label in labels{
let labelText = label.text + " : " + label.confidence.description + "\n"
labeltexts += labelText
}
// And when we're done we can update the UI with the list of labels
lblOutput.text = labeltexts
}
}
| apache-2.0 | 39140f2a4260285efcd6ddc8afea76d3 | 35.646341 | 95 | 0.672213 | 4.525602 | false | false | false | false |
VernonVan/SmartClass | SmartClass/Paper/Paper Result/View/ResultContainerViewController.swift | 1 | 1713 | //
// ResultContainerViewController.swift
// SmartClass
//
// Created by Vernon on 16/8/26.
// Copyright © 2016年 Vernon. All rights reserved.
//
import UIKit
class ResultContainerViewController: UIViewController
{
var paper: Paper?
@IBOutlet weak var resultContainerView: UIView!
@IBOutlet weak var chartContainerView: UIView!
override func viewDidLoad()
{
super.viewDidLoad()
}
@IBAction func showComponent(_ segmentControl: UISegmentedControl)
{
if segmentControl.selectedSegmentIndex == 0 {
UIView.animate(withDuration: 0.5, animations: {
self.resultContainerView.alpha = 1
self.chartContainerView.alpha = 0
})
} else {
UIView.animate(withDuration: 0.5, animations: {
self.resultContainerView.alpha = 0
self.chartContainerView.alpha = 1
})
}
}
// MARK: - Segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
if segue.identifier == "previewPaper" {
if let desVC = segue.destination as? PreviewRootViewController {
desVC.paper = paper
}
} else if segue.identifier == "showOrder" {
if let desVC = segue.destination as? ExamResultViewController {
desVC.paper = paper
}
} else if segue.identifier == "showChart" {
if let desVC = segue.destination as? ResultChartViewController {
desVC.paper = paper
}
}
}
}
| mit | ecd6630258c25c32a9dd5e51e8dac533 | 27.983051 | 110 | 0.592982 | 4.942197 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Pods/Nuke-FLAnimatedImage-Plugin/Source/AnimatedImage.swift | 1 | 1076 | // The MIT License (MIT)
//
// Copyright (c) 2016-2018 Alexander Grebenyuk (github.com/kean).
import UIKit
import FLAnimatedImage
import Nuke
extension FLAnimatedImageView {
@objc open override func display(image: Image?) {
guard image != nil else {
self.animatedImage = nil
self.image = nil
return
}
if let data = image?.animatedImageData {
// Display poster image immediately
self.image = image
// Prepare FLAnimatedImage object asynchronously (it takes a
// noticeable amount of time), and start playback.
DispatchQueue.global().async {
let animatedImage = FLAnimatedImage(animatedGIFData: data)
DispatchQueue.main.async {
// If view is still displaying the same image
if self.image === image {
self.animatedImage = animatedImage
}
}
}
} else {
self.image = image
}
}
}
| mit | 0f733e7fc9a11baef12e63263fbb6e1d | 29.742857 | 74 | 0.542751 | 5.57513 | false | false | false | false |
caoimghgin/HexKit | Example/Tests/TestHexCenterPointsEvenFlat6x6.swift | 1 | 11714 | //
// TestHexCenterPointsEvenFlat6x6.swift
// HexKit
//
// Copyright © 2015 Kevin Muldoon.
// https://github.com/caoimghgin/HexKit
//
import UIKit
import XCTest
import HexKit
class TestHexCenterPointsEvenFlat6x6: XCTestCase {
let width = 6
let height = 6
let gridShape = Grid.Shape.Even
let tileShape = Tile.Shape.FlatTopped
let tileRadius = 22.0
let accuracy : Double = 0.000000000001
override func setUp() {
super.setUp()
HexKit.sharedInstance.start(
Grid.Size(width : width, height : height),
gridShape: gridShape,
tileShape: tileShape,
tileRadius: tileRadius
)
}
override func tearDown() {
super.tearDown()
}
func test_Q0() {
let q : Int = 1
var tile : Tile!
tile = HexKit.sharedInstance.tile(q:q, r:0)
XCTAssertEqualWithAccuracy (tile.center.x, 22.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 38.1051177665153, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:1)
XCTAssertEqualWithAccuracy (tile.center.x, 22.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 76.2102355330306, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:2)
XCTAssertEqualWithAccuracy (tile.center.x, 22.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 114.315353299546, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:3)
XCTAssertEqualWithAccuracy (tile.center.x, 22.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 152.420471066061, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:4)
XCTAssertEqualWithAccuracy (tile.center.x, 22.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 190.525588832576, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:5)
XCTAssertEqualWithAccuracy (tile.center.x, 22.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 228.630706599092, accuracy: accuracy, "Expected result not equal");
}
func test_Q1() {
let q : Int = 2
var tile : Tile!
tile = HexKit.sharedInstance.tile(q:q, r:-1)
XCTAssertEqualWithAccuracy (tile.center.x, 55.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 19.0525588832576, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:0)
XCTAssertEqualWithAccuracy (tile.center.x, 55.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 57.157676649773, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:1)
XCTAssertEqualWithAccuracy (tile.center.x, 55.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 95.2627944162882, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:2)
XCTAssertEqualWithAccuracy (tile.center.x, 55.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 133.367912182804, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:3)
XCTAssertEqualWithAccuracy (tile.center.x, 55.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 171.473029949319, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:4)
XCTAssertEqualWithAccuracy (tile.center.x, 55.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 209.578147715834, accuracy: accuracy, "Expected result not equal");
}
func test_Q2() {
let q : Int = 3
var tile : Tile!
tile = HexKit.sharedInstance.tile(q:q, r:-1)
XCTAssertEqualWithAccuracy (tile.center.x, 88.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 38.1051177665153, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:0)
XCTAssertEqualWithAccuracy (tile.center.x, 88.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 76.2102355330306, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:1)
XCTAssertEqualWithAccuracy (tile.center.x, 88.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 114.315353299546, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:2)
XCTAssertEqualWithAccuracy (tile.center.x, 88.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 152.420471066061, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:3)
XCTAssertEqualWithAccuracy (tile.center.x, 88.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 190.525588832576, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:4)
XCTAssertEqualWithAccuracy (tile.center.x, 88.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 228.630706599092, accuracy: accuracy, "Expected result not equal");
}
func test_Q3() {
let q : Int = 4
var tile : Tile!
tile = HexKit.sharedInstance.tile(q:q, r:-2)
XCTAssertEqualWithAccuracy (tile.center.x, 121.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 19.0525588832576, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:-1)
XCTAssertEqualWithAccuracy (tile.center.x, 121.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 57.157676649773, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:0)
XCTAssertEqualWithAccuracy (tile.center.x, 121.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 95.2627944162882, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:1)
XCTAssertEqualWithAccuracy (tile.center.x, 121.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 133.367912182804, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:2)
XCTAssertEqualWithAccuracy (tile.center.x, 121.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 171.473029949319, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:3)
XCTAssertEqualWithAccuracy (tile.center.x, 121.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 209.578147715834, accuracy: accuracy, "Expected result not equal");
}
func test_Q4() {
let q : Int = 5
var tile : Tile!
tile = HexKit.sharedInstance.tile(q:q, r:-2)
XCTAssertEqualWithAccuracy (tile.center.x, 154.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 38.1051177665153, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:-1)
XCTAssertEqualWithAccuracy (tile.center.x, 154.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 76.2102355330306, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:0)
XCTAssertEqualWithAccuracy (tile.center.x, 154.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 114.315353299546, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:1)
XCTAssertEqualWithAccuracy (tile.center.x, 154.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 152.420471066061, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:2)
XCTAssertEqualWithAccuracy (tile.center.x, 154.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 190.525588832576, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:3)
XCTAssertEqualWithAccuracy (tile.center.x, 154.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 228.630706599092, accuracy: accuracy, "Expected result not equal");
}
func test_Q5() {
let q : Int = 6
var tile : Tile!
tile = HexKit.sharedInstance.tile(q:q, r:-3)
XCTAssertEqualWithAccuracy (tile.center.x, 187.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 19.0525588832576, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:-2)
XCTAssertEqualWithAccuracy (tile.center.x, 187.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 57.157676649773, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:-1)
XCTAssertEqualWithAccuracy (tile.center.x, 187.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 95.2627944162882, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:0)
XCTAssertEqualWithAccuracy (tile.center.x, 187.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 133.367912182804, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:1)
XCTAssertEqualWithAccuracy (tile.center.x, 187.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 171.473029949319, accuracy: accuracy, "Expected result not equal");
tile = HexKit.sharedInstance.tile(q:q, r:2)
XCTAssertEqualWithAccuracy (tile.center.x, 187.0, accuracy: accuracy, "Expected result not equal");
XCTAssertEqualWithAccuracy (tile.center.y, 209.578147715834, accuracy: accuracy, "Expected result not equal");
}
}
| mit | 9aec8bf51c595f9bed35a3de21820563 | 51.524664 | 118 | 0.670793 | 4.325332 | false | false | false | false |
Neo11/ChitChat | ChitChat/WKScriptMessageHandlerToNotification.swift | 1 | 1294 | //
// Created by Tom Schmidt on 10.03.16.
// Copyright (c) 2016 Tom Schmidt. All rights reserved.
//
import Foundation
import WebKit
class WKScriptMessageHandlerToNotification: NSObject, WKScriptMessageHandler {
let window: NSWindow
var counter = 0
init(window: NSWindow) {
self.window = window
}
@available(OSX 10.10, *)
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if self.window.mainWindow {
return
}
let messageBody = message.body as! [String]
let notification = NSUserNotification()
notification.hasReplyButton = true
notification.responsePlaceholder = "Reply..."
notification.title = messageBody[0]
notification.subtitle = messageBody[1]
let identifier = "\(messageBody[2]):\(counter)"
notification.identifier = identifier;
counter += 1
let base64URL = NSURL(string: messageBody[3])
let imageData = NSData(contentsOfURL: base64URL!)
let avatar = NSImage(data: imageData!)
notification.setValue(avatar, forKey: "_identityImage")
NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification(notification)
}
}
| mit | a6ee43645c8ff57036ad4b6c5397a352 | 32.179487 | 130 | 0.684699 | 5.238866 | false | false | false | false |
A-Kod/vkrypt | Pods/SwiftyVK/Library/Sources/API Supporting/Response.swift | 4 | 685 | import Foundation
enum Response {
case success(Data)
case error(VKError)
init(_ data: Data) {
do {
let json = try JSON(data: data)
if let apiError = ApiError(json) {
self = .error(.api(apiError))
return
}
let successData = json.forcedData("response")
if successData.isEmpty {
self = .success(data)
}
else {
self = .success(successData)
}
}
catch let error {
self = .error(.jsonNotParsed(error))
return
}
}
}
| apache-2.0 | f38ce03ef9664a1fc74fd052f58a785d | 21.833333 | 57 | 0.421898 | 5 | false | false | false | false |
fguchelaar/AdventOfCode2016 | AdventOfCode2016/aoc-day24/main.swift | 1 | 6784 | //
// main.swift
// aoc-day24
//
// Created by Frank Guchelaar on 24/12/2016.
// Copyright © 2016 Awesomation. All rights reserved.
//
import Foundation
var input = try String(contentsOfFile: "day24/input.txt")
.trimmingCharacters(in: .whitespacesAndNewlines)
enum LocationType {
case wall
case open
case waypoint
}
struct Location : Equatable, Hashable {
let x: Int
let y: Int
let type: LocationType
let id: Int?
public static func ==(lhs: Location, rhs: Location) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
var hashValue: Int {
return (x * 1000 + y).hashValue
}
}
extension Location {
func up(in grid:[[Location]]) -> Location {
return grid[self.y-1][self.x]
}
func down(in grid:[[Location]]) -> Location {
return grid[self.y+1][self.x]
}
func left(in grid:[[Location]]) -> Location {
return grid[self.y][self.x-1]
}
func right(in grid:[[Location]]) -> Location {
return grid[self.y][self.x+1]
}
}
func parseInput() -> [[Location]] {
var grid = [[Location]]()
for (rowIndex, row) in input.components(separatedBy: .newlines).enumerated() {
var gridRow = [Location]()
for (colIndex, col) in row.characters.enumerated() {
switch col {
case "#":
gridRow.append(Location(x: colIndex, y: rowIndex, type: .wall, id: nil))
case ".":
gridRow.append(Location(x: colIndex, y: rowIndex, type: .open, id: nil))
default:
gridRow.append(Location(x: colIndex, y: rowIndex, type: .waypoint, id: Int(String(col))))
}
}
grid.append(gridRow)
}
return grid
}
func displayGrid(grid: [[Location]], distance: [Location: Int]) {
var output = ""
for row in 0..<grid.count {
for col in 0..<grid[row].count {
let location = grid[row][col]
switch location.type {
case .wall:
output.append("⏹")
case .open:
if let _ = distance[location] {
output.append("🚶🏽")
}
else {
output.append("◽️")
}
case .waypoint:
output.append("🅰️")
// output.append(String(location.id!))
}
}
output.append("\n")
}
print (output.trimmingCharacters(in: .newlines))
}
// I'm using Dijkstra's algorithm to calculate the shortest path, escaping when we're at the target location, or scipping new locations if we've reached a max distance. Since the grid is potentially infinite, I'm building op the Unvisited set as we traverse the maze
func Dijkstra(grid: [[Location]], source: Location, targets: [Location]) -> [Location : Int] {
func neighborsOf(location: Location) -> [Location] {
return [ location.up(in: grid), location.down(in: grid), location.left(in: grid), location.right(in: grid)]
.filter { !($0.type == .wall) }
}
var distance = [Location: Int]()
var previous = [Location: Location]()
var unvisited = Set<Location>()
var visited = Set<Location>()
var targetWaypoints = targets
distance[source] = 0
unvisited.insert(source)
while !unvisited.isEmpty {
let current = distance
.filter { unvisited.contains($0.key) }
.sorted { $0.value < $1.value }
.first!.key
if let wp = targetWaypoints.index(of: current) {
print ("Distance from \(source.id!) to \(current.id!): \(distance[current]!)")
targetWaypoints.remove(at: wp)
if targetWaypoints.isEmpty {
break
}
}
visited.insert(unvisited.remove(current)!)
for neighbor in neighborsOf(location: current) {
if !visited.contains(neighbor) {
unvisited.insert(neighbor) // unvisited is a set, so no harm is done here by adding a location twice
}
let currentDistance = distance[current]!
if let neighborDistance = distance[neighbor] {
if currentDistance + 1 < neighborDistance {
distance[neighbor] = currentDistance + 1
previous[neighbor] = current
}
}
else {
distance[neighbor] = currentDistance + 1
previous[neighbor] = current
}
}
}
return distance
}
func permutations(array: [Location]) -> [[Location]] {
var arr = array
return permutations(arr.count, &arr)
}
private func permutations(_ n:Int, _ a:inout Array<Location>) -> [[Location]] {
var p = [[Location]]()
if n == 1 {
p.append(a)
}
else {
for i in 0..<n-1 {
p.append(contentsOf: permutations(n-1,&a))
Swift.swap(&a[n-1], &a[(n%2 == 1) ? 0 : i])
}
p.append(contentsOf: permutations(n-1,&a))
}
return p
}
let grid = parseInput()
let waypoints = grid.flatMap { $0 }.filter { $0.type == .waypoint }.sorted { $0.id! < $1.id! }
measure {
var distances = [Location: [Location: Int]]()
for wp in waypoints {
distances[wp] = [Location: Int]()
}
for (sourceIndex, source) in Array(waypoints[0..<waypoints.count-1]).enumerated() {
let targets = Array(waypoints[sourceIndex+1..<waypoints.count])
let distance = Dijkstra(grid: grid, source: source, targets: targets)
for target in targets {
// add both ways, for convienence
distances[source]![target] = distance[target]!
distances[target]![source] = distance[target]!
}
}
var minPath = Int.max
for permutation in permutations(array: Array(waypoints.suffix(from: 1))) {
var previous = waypoints[0]
var sum = (permutation + [waypoints[0]]).reduce(0, { (result, wp) -> Int in
let r = result + distances[previous]![wp]!
previous = wp
return r
})
if sum < minPath {
minPath = sum
print("Found new shortest path with length \(sum)")
print(([waypoints[0]] + permutation + [waypoints[0]]).map { "\($0.id!)" }.joined(separator: " -> "))
}
}
// displayGrid(grid: grid, distance: distance)
}
/* Pseudo
for all sorted waypoint {
use Dijkstra to calculate distance from current to following wp. (nb: a->b == b->a)
}
for each wp [0] + permutations of [1,2,3,4,5,6,7] {
sum distances
}
sum with smallest distance = winner
*/
| mit | 12d8ec884e499803fffda1578a56ef2e | 28.675439 | 266 | 0.547 | 4.105583 | false | false | false | false |
GXFrighting/GXComboBox | GXComboBox/Classes/GXComboBoxView.swift | 1 | 13824 | //
// GXComboBoxView.swift
// GXComboBox
//
// Created by Jiang on 2017/9/19.
// Copyright © 2017年 Jiang. All rights reserved.
//
import UIKit
public class GXComboBoxViewType {
open var normalTitleColor: UIColor = UIColor.init(red: 30/255.0, green: 30/255.0, blue: 30/255.0, alpha: 1)
open var selectedTitleColor: UIColor = UIColor.init(red: 62/255.0, green: 92/255.0, blue: 238/255.0, alpha: 1)
}
public class GXIndexPath {
/// 列 (顶部按钮tag 0,1,2...)
open var column: Int
/// 第几个tableview
open var section: Int
/// 第几行
open var row: Int
public init(row: Int, section: Int, column: Int) {
self.section = section
self.row = row
self.column = column
}
}
// MARK: GXComboBoxViewDataSoure
public protocol GXComboBoxViewDataSoure {
/// 在这里注册每个TableView Cell
///
/// - Parameters:
/// - comboBoxView: comboBoxView
/// - column: 列数
/// - section: 第几个TableView
/// - tableView: TableView
/// - Returns: void
func comboBoxView(_ comboBoxView: GXComboBoxView, numberOfSectionInColumn column: Int, section: Int, regiseCell tableView: UITableView)
/// 获取列数
///
/// - Parameters:
/// - comboBoxView: comboBoxView
/// - Returns: 列数(顶部按钮多少个)
func numberOfColumn(in comboBoxView: GXComboBoxView) -> Int
/// 获取列对应的tableView个数
///
/// - Parameters:
/// - comboBoxView: comboBoxView
/// - column: 列数
/// - Returns: tableView个数
func comboBoxView(_ comboBoxView: GXComboBoxView, numberOfSectionInColumn column: Int) -> Int
/// 获取每个tableview row个数
///
/// - Parameters:
/// - comboBoxView: comboBoxView
/// - column: 列数
/// - section: 第几个TableView
/// - Returns: row
func comboBoxView(_ comboBoxView: GXComboBoxView, numberOfRowsInColum column: Int, section: Int) -> Int
/// 获取cell
///
/// - Parameters:
/// - comboBoxView: comboBoxView
/// - indexPath: indexPath
/// - Returns: cell
func comboBoxView(_ comboBoxView: GXComboBoxView, cellForRowAt indexPath: GXIndexPath) -> UITableViewCell
/// 按钮的标题
///
/// - Parameters:
/// - comboBoxView: comboBoxView
/// - column: 列数
/// - Returns: 按钮标题
func titleOfColumn(_ comboBoxView: GXComboBoxView, numberOfColumn column: Int) -> String
}
// MARK: GXComboBoxViewDelegate
public protocol GXComboBoxViewDelegate {
/// cell height
///
/// - Parameters:
/// - comboBoxView: comboBoxView
/// - indexPath: indexPath
/// - Returns: cell height
func comboBoxView(_ comboBoxView: GXComboBoxView, heightForRowAt indexPath: GXIndexPath) -> CGFloat
/// cell click
///
/// - Parameters:
/// - comboBoxView: comboBoxView
/// - indexPath: indexPath
func comboBoxView(_ comboBoxView: GXComboBoxView, didSelectedRowAt indexPath: GXIndexPath)
}
public class GXComboBoxView: UIView {
open var dataSoure: GXComboBoxViewDataSoure? {
didSet {
setUpUI()
}
}
open var delegate: GXComboBoxViewDelegate? {
didSet {
setUpUI()
}
}
fileprivate func maxY() -> CGFloat {
return UIScreen.main.bounds.size.height - frame.maxY
}
open var stytle: GXComboBoxViewType = GXComboBoxViewType()
fileprivate var currentBtn: GXComboBoxBtn?
fileprivate var btns: [GXComboBoxBtn] = [GXComboBoxBtn]()
fileprivate var tableViews: [UITableView] = [UITableView]()
fileprivate var popView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
return view
}()
fileprivate lazy var btnsStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.distribution = .fillEqually
stackView.alignment = .fill
stackView.spacing = 0
return stackView
}()
fileprivate lazy var tableViewStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.distribution = .fillEqually
stackView.alignment = .top
stackView.spacing = 0
return stackView
}()
public override init(frame: CGRect) {
super.init(frame: frame)
initUI()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initUI()
}
public func reloadData() {
setUpTableViews()
setUpTitles()
}
@objc public func closeSelecting() {
hidenPopView(isAnimal: true)
hidenTableViews(isAnimal: true)
_ = btns.map({ $0.isSelected = false })
}
}
// MARK: UI
extension GXComboBoxView {
fileprivate func initUI() {
addSubview(btnsStackView)
translatesAutoresizingMaskIntoConstraints = false
}
fileprivate func setUpTitles() {
for btn in btns {
let title = self.dataSoure?.titleOfColumn(self, numberOfColumn: btn.tag)
btn.setTitle(title, for: .normal)
}
}
fileprivate func setUpUI() {
for btn in btns {
btnsStackView.removeArrangedSubview(btn)
}
btns.removeAll()
let count = self.dataSoure?.numberOfColumn(in: self) ?? 0
for i in 0..<count {
let btn = GXComboBoxBtn()
let title = self.dataSoure?.titleOfColumn(self, numberOfColumn: i)
btn.setTitle(title, for: .normal)
btn.setTitleColor(stytle.normalTitleColor, for: .normal)
btn.setTitleColor(stytle.selectedTitleColor, for: .selected)
let defaultImage = UIImage(named: "GXComboBox.bundle/btn_default_img") ?? UIImage(named: "Frameworks/GXComboBox.framework/GXComboBox.bundle/btn_default_img")
let selectedImage = UIImage(named: "GXComboBox.bundle/btn_selected_img") ?? UIImage(named: "Frameworks/GXComboBox.framework/GXComboBox.bundle/btn_selected_img")
btn.setImage(defaultImage, for: .normal)
btn.setImage(selectedImage, for: .selected)
btn.tag = i
btn.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
btnsStackView.addArrangedSubview(btn)
btns.append(btn)
}
}
@objc fileprivate func btnClick(_ thisBtn: GXComboBoxBtn) {
if thisBtn.isSelected {
thisBtn.isSelected = false
} else {
for btn in btns {
btn.isSelected = btn.tag == thisBtn.tag
}
}
currentBtn = thisBtn
setUpPopView()
setUpTableViews()
}
fileprivate func setUpTableViews() {
if let btn = btns.filter({ $0.isSelected }).first {
// 有选中
showTableViews(isAnimal: true)
let col = dataSoure?.comboBoxView(self, numberOfSectionInColumn: btn.tag) ?? 0
if col < tableViews.count {
for _ in 0..<(tableViews.count - col) {
tableViews.last!.removeFromSuperview()
// tableViewStackView.removeArrangedSubview(tableViews.last!)
tableViews.removeLast()
}
} else if col > tableViews.count {
for i in tableViews.count..<col {
let tableView = UITableView()
tableView.tag = i
dataSoure?.comboBoxView(self, numberOfSectionInColumn: btn.tag, section: i, regiseCell: tableView)
tableView.dataSource = self
tableView.delegate = self
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.frame.origin.x = (frame.size.width / CGFloat(col)) * CGFloat(i)
tableView.frame.size.width = frame.size.width / CGFloat(col)
let heightConstraint = NSLayoutConstraint(item: tableView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 0)
tableView.addConstraint(heightConstraint)
tableViewStackView.addArrangedSubview(tableView)
tableViews.append(tableView)
}
}
for (index, tableView) in tableViews.enumerated() {
tableView.reloadData()
let row = self.delegate?.comboBoxView(self, heightForRowAt: GXIndexPath(row: 0, section: index, column: btn.tag)) ?? 0
let cellHeight = CGFloat(self.dataSoure?.comboBoxView(self, numberOfRowsInColum: btn.tag, section: index) ?? 0)
let height = row * cellHeight
let maxHeight = maxY()
tableView.constraints.first?.constant = height > maxHeight ? maxHeight : height
}
UIView.animate(withDuration: 0.25, animations: {
self.tableViewStackView.layoutIfNeeded()
})
} else {
// 没有选中
hidenTableViews(isAnimal: true)
}
}
fileprivate func showTableViews(isAnimal: Bool) {
guard tableViewStackView.superview != nil else {
tableViewStackView.frame = CGRect.init(x: 0, y: self.frame.maxY, width: self.frame.size.width, height: 0)
superview?.addSubview(tableViewStackView)
UIView.animate(withDuration: isAnimal ? 0.25 : 0, animations: {
self.tableViewStackView.frame = CGRect.init(x: 0, y: self.frame.maxY, width: self.frame.size.width, height: self.maxY())
}, completion: nil)
return
}
}
fileprivate func hidenTableViews(isAnimal: Bool) {
_ = self.tableViews.map({ $0.constraints.first?.constant = 0 })
UIView.animate(withDuration: isAnimal ? 0.25 : 0, animations: {
self.tableViewStackView.layoutIfNeeded()
self.tableViewStackView.frame = CGRect.init(x: 0, y: self.frame.maxY, width: self.frame.size.width, height: 0)
}) { (_) in
self.tableViewStackView.removeFromSuperview()
self.removeAllTableViews()
}
}
fileprivate func removeAllTableViews() {
for tableView in tableViews {
tableView.removeFromSuperview()
}
tableViews.removeAll()
}
fileprivate func setUpPopView() {
if btns.filter({ $0.isSelected }).first != nil {
// 有选中
if popView.superview == nil {
showPopView(isAnimal: true)
}
} else {
// 没有选中
hidenPopView(isAnimal: true)
}
}
fileprivate func showPopView(isAnimal: Bool) {
popView.backgroundColor = UIColor.clear
superview?.addSubview(popView)
UIView.animate(withDuration: isAnimal ? 0.25 : 0, animations: {
self.popView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
}) { (_) in
}
}
fileprivate func hidenPopView(isAnimal: Bool) {
UIView.animate(withDuration: isAnimal ? 0.25 : 0, animations: {
self.popView.backgroundColor = UIColor.clear
}) { (_) in
self.popView.removeFromSuperview()
}
}
override public func layoutSubviews() {
super.layoutSubviews()
btnsStackView.frame = bounds
popView.frame = CGRect.init(x: 0, y: frame.maxY, width: frame.size.width, height: maxY())
}
}
extension GXComboBoxView: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSoure?.comboBoxView(self, numberOfRowsInColum: currentBtn?.tag ?? 0, section: tableView.tag) ?? 0
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let indexPath = GXIndexPath(row: indexPath.row, section: tableView.tag, column: currentBtn?.tag ?? 0)
let cell = self.dataSoure?.comboBoxView(self, cellForRowAt: indexPath)
return cell ?? UITableViewCell()
}
}
extension GXComboBoxView: UITableViewDelegate {
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let col = dataSoure?.comboBoxView(self, numberOfSectionInColumn: tableView.tag) ?? 0
return self.delegate?.comboBoxView(self, heightForRowAt: GXIndexPath(row: indexPath.row, section: tableView.tag, column: col)) ?? 0
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let btn = btns.filter({ $0.isSelected }).first {
self.delegate?.comboBoxView(self, didSelectedRowAt: GXIndexPath(row: indexPath.row, section: tableView.tag, column: btn.tag))
}
}
}
| mit | 0ae2ddca55befff2fc041f2c6fb459ae | 30.640371 | 186 | 0.572633 | 5.144097 | false | false | false | false |
SuPair/firefox-ios | SharedTests/FeatureSwitchTests.swift | 13 | 6121 | /* 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/. */
@testable import Shared
import XCTest
class FeatureSwitchTests: XCTestCase {
let buildChannel = AppConstants.BuildChannel
func testPersistent() {
let featureSwitch = FeatureSwitch(named: "test-persistent-over-restarts", allowPercentage: 50, buildChannel: buildChannel)
let prefs = MockProfilePrefs()
var membership = featureSwitch.isMember(prefs)
var changed = 0
for _ in 0..<100 {
if featureSwitch.isMember(prefs) != membership {
membership = !membership
changed += 1
}
}
XCTAssertEqual(changed, 0, "Users should get and keep the feature over restarts")
}
func testConsistentWhenChangingPercentage() {
let featureID = "test-persistent-over-releases"
let prefs = MockProfilePrefs()
let guardFeatureSwitch = FeatureSwitch(named: featureID, allowPercentage: 50, buildChannel: buildChannel)
while guardFeatureSwitch.alwaysMembership(prefs) {
guardFeatureSwitch.resetMembership(prefs)
}
var membership = false
var changed = 0
for percent in 0..<100 {
let featureSwitch = FeatureSwitch(named: featureID, allowPercentage: percent, buildChannel: buildChannel)
if featureSwitch.isMember(prefs) != membership {
membership = !membership
changed += 1
}
}
XCTAssertEqual(changed, 1, "Users should get and keep the feature if the feature is becoming successful")
}
func testReallyConsistentWhenChangingPercentage() {
for _ in 0..<1000 {
testConsistentWhenChangingPercentage()
}
}
func testUserEnabled() {
let prefs = MockProfilePrefs()
let featureSwitch = FeatureSwitch(named: "test-user-enabled", allowPercentage: 0, buildChannel: buildChannel)
XCTAssertFalse(featureSwitch.isMember(prefs), "The feature should be disabled")
featureSwitch.setMembership(true, for: prefs) // enable the feature
XCTAssertTrue(featureSwitch.isMember(prefs), "The feature should be enabled")
featureSwitch.setMembership(false, for: prefs) // disable the feature
XCTAssertFalse(featureSwitch.isMember(prefs), "The feature should be disabled again")
}
func testForceDisabled() {
let prefs = MockProfilePrefs()
let featureSwitch = FeatureSwitch(named: "test-user-disabled", allowPercentage: 100, buildChannel: buildChannel)
XCTAssertTrue(featureSwitch.isMember(prefs), "The feature should be enabled")
featureSwitch.setMembership(false, for: prefs) // disable the feature
XCTAssertFalse(featureSwitch.isMember(prefs), "The feature should be disabled again")
}
}
extension FeatureSwitchTests {
func test0Percent() {
let featureSwitch = FeatureSwitch(named: "test-never", allowPercentage: 0, buildChannel: buildChannel)
testExactly(featureSwitch, expected: 0)
testApprox(featureSwitch, expected: 0)
}
func test100Percent() {
let featureSwitch = FeatureSwitch(named: "test-always", allowPercentage: 100, buildChannel: buildChannel)
testExactly(featureSwitch, expected: 100)
testApprox(featureSwitch, expected: 100)
}
func test50Percent() {
let featureSwitch = FeatureSwitch(named: "test-half-the-population", allowPercentage: 50, buildChannel: buildChannel)
testApprox(featureSwitch, expected: 50)
}
func test30Percent() {
let featureSwitch = FeatureSwitch(named: "test-30%-population", allowPercentage: 30, buildChannel: buildChannel)
testApprox(featureSwitch, expected: 30)
}
func testPerformance() {
let featureSwitch = FeatureSwitch(named: "test-30%-population", allowPercentage: 30, buildChannel: buildChannel)
let prefs = MockProfilePrefs()
measure {
for _ in 0..<1000 {
_ = featureSwitch.isMember(prefs)
}
}
}
func testAppConstantsWin() {
// simulate in release channel, but switched off in AppConstants.
let featureFlaggedOff = FeatureSwitch(named: "test-release-flagged-off", false, allowPercentage: 100, buildChannel: buildChannel)
testExactly(featureFlaggedOff, expected: 0)
// simulate in non-release channel, but switched on in AppConstants.
let buildChannelAndFlaggedOn = FeatureSwitch(named: "test-flagged-on", true, allowPercentage: 0)
testExactly(buildChannelAndFlaggedOn, expected: 100)
// simulate in non-release channel, but switched off in AppConstants.
let buildChannelAndFlaggedOff = FeatureSwitch(named: "test-flagged-off", false, allowPercentage: 100)
testExactly(buildChannelAndFlaggedOff, expected: 0)
}
}
private extension FeatureSwitchTests {
func sampleN(_ featureSwitch: FeatureSwitch, testCount: Int = 1000) -> Int {
var count = 0
for _ in 0..<testCount {
let prefs = MockProfilePrefs()
if featureSwitch.isMember(prefs) {
count += 1
}
}
return count
}
func testExactly(_ featureSwitch: FeatureSwitch, expected: Int) {
let testCount = 1000
let count = sampleN(featureSwitch, testCount: testCount)
let normalizedExpectedCount = (testCount * expected) / 100
XCTAssertEqual(count, normalizedExpectedCount)
}
func testApprox(_ featureSwitch: FeatureSwitch, expected: Int, epsilon: Int = 2) {
let testCount = 10000
let count = sampleN(featureSwitch, testCount: testCount)
let acceptableRange = Range(uncheckedBounds: (
lower: testCount * (expected - epsilon) / 100,
upper: testCount * (expected + epsilon) / 100))
XCTAssertTrue(acceptableRange.contains(count), "\(count) in \(acceptableRange)?")
}
}
| mpl-2.0 | ee164fb5b81261a65035356d19805aec | 40.639456 | 137 | 0.667375 | 5.071251 | false | true | false | false |
airbnb/lottie-ios | Sources/Public/DynamicProperties/ValueProviders/GradientValueProvider.swift | 3 | 2877 | //
// GradientValueProvider.swift
// lottie-swift
//
// Created by Enrique Bermúdez on 10/27/19.
//
import CoreGraphics
import Foundation
/// A `ValueProvider` that returns a Gradient Color Value.
public final class GradientValueProvider: ValueProvider {
// MARK: Lifecycle
/// Initializes with a block provider.
public init(
block: @escaping ColorsValueBlock,
locations: ColorLocationsBlock? = nil)
{
self.block = block
locationsBlock = locations
colors = []
self.locations = []
}
/// Initializes with an array of colors.
public init(
_ colors: [LottieColor],
locations: [Double] = [])
{
self.colors = colors
self.locations = locations
updateValueArray()
hasUpdate = true
}
// MARK: Public
/// Returns a [LottieColor] for a CGFloat(Frame Time).
public typealias ColorsValueBlock = (CGFloat) -> [LottieColor]
/// Returns a [Double](Color locations) for a CGFloat(Frame Time).
public typealias ColorLocationsBlock = (CGFloat) -> [Double]
/// The colors values of the provider.
public var colors: [LottieColor] {
didSet {
updateValueArray()
hasUpdate = true
}
}
/// The color location values of the provider.
public var locations: [Double] {
didSet {
updateValueArray()
hasUpdate = true
}
}
// MARK: ValueProvider Protocol
public var valueType: Any.Type {
[Double].self
}
public var storage: ValueProviderStorage<[Double]> {
.closure { [self] frame in
hasUpdate = false
if let block = block {
let newColors = block(frame)
let newLocations = locationsBlock?(frame) ?? []
value = value(from: newColors, locations: newLocations)
}
return value
}
}
public func hasUpdate(frame _: CGFloat) -> Bool {
if block != nil || locationsBlock != nil {
return true
}
return hasUpdate
}
// MARK: Private
private var hasUpdate = true
private var block: ColorsValueBlock?
private var locationsBlock: ColorLocationsBlock?
private var value: [Double] = []
private func value(from colors: [LottieColor], locations: [Double]) -> [Double] {
var colorValues = [Double]()
var alphaValues = [Double]()
var shouldAddAlphaValues = false
for i in 0..<colors.count {
if colors[i].a < 1 { shouldAddAlphaValues = true }
let location = locations.count > i
? locations[i]
: (Double(i) / Double(colors.count - 1))
colorValues.append(location)
colorValues.append(colors[i].r)
colorValues.append(colors[i].g)
colorValues.append(colors[i].b)
alphaValues.append(location)
alphaValues.append(colors[i].a)
}
return colorValues + (shouldAddAlphaValues ? alphaValues : [])
}
private func updateValueArray() {
value = value(from: colors, locations: locations)
}
}
| apache-2.0 | fb468a2faffd2626c2421ab9f5ea9c79 | 22.382114 | 83 | 0.646384 | 4.235641 | false | false | false | false |
belatrix/BelatrixEventsIOS | Hackatrix/Controller/NewsVC.swift | 1 | 3340 | //
// NewsVC.swift
// Hackatrix
//
// Created by Erik Fernando Flores Quispe on 9/05/17.
// Copyright © 2017 Belatrix. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import DZNEmptyDataSet
class NewsVC: UIViewController {
//MARK: - Properties
@IBOutlet weak var tableViewNews: UITableView!
@IBOutlet weak var activity: UIActivityIndicatorView!
var news:[News] = [] {
didSet {
self.tableViewNews.reloadData()
}
}
//MARK: - LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
self.customStyleTableView()
self.getNews {
self.tableViewNews.isHidden = false
self.activity.stopAnimating()
}
self.addPullRefresh()
}
//MARK: - Functions
func customStyleTableView() {
self.tableViewNews.rowHeight = UITableViewAutomaticDimension
self.tableViewNews.estimatedRowHeight = 50
self.tableViewNews.emptyDataSetSource = self;
self.tableViewNews.emptyDataSetDelegate = self;
self.tableViewNews.tableFooterView = UIView()
}
func getNews(complete: (()->Void)? = nil) {
Alamofire.request(api.url.notifications.all).responseJSON { response in
if let responseServer = response.result.value {
let json = JSON(responseServer)
for (_,subJson):(String, JSON) in json {
self.news.append(News(data: subJson))
}
if complete != nil {
complete!()
}
}
}
}
func addPullRefresh() {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self,action: #selector(self.refreshTable(sender:)),for: .valueChanged)
if #available(iOS 10.0, *) {
self.tableViewNews.refreshControl = refreshControl
} else {
self.tableViewNews.addSubview(refreshControl)
}
}
func refreshTable(sender: UIRefreshControl) {
self.news = []
self.tableViewNews.reloadData()
self.getNews {
sender.endRefreshing()
}
}
}
//MARK: - UITableViewDataSource
extension NewsVC: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return news.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: K.cell.news) as! NewsCell
cell.dateLbl.text = Utils.date.getFormatter(dateString: self.news[indexPath.row].datetime!)
cell.descriptionLbl.text = self.news[indexPath.row].text
return cell
}
}
//MARK: - UITableViewDelegate
extension NewsVC: UITableViewDelegate {
}
//MARK: - DZNEmptyDataSet
extension NewsVC: DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
return UIImage(named: "BelatrixLogo")
}
func emptyDataSetShouldAllowTouch(_ scrollView: UIScrollView!) -> Bool {
return true
}
func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool {
return true
}
}
| apache-2.0 | 3beee16f3bfa8e0ed77397174a589fbd | 26.368852 | 103 | 0.621743 | 5.051437 | false | false | false | false |
Ajunboys/actor-platform | actor-apps/app-ios/Actor/Utils/MeasureUtils.swift | 40 | 525 | //
// MeasureUtils.swift
// ActorApp
//
// Created by Stepan Korshakov on 27.07.15.
// Copyright (c) 2015 Actor LLC. All rights reserved.
//
import Foundation
private var startTime: NSDate!
func startMeasure() {
startTime = NSDate()
}
func trackMeasure(name: String) {
if startTime == nil {
return
}
let timeInterval = Int(NSDate().timeIntervalSinceDate(startTime) * 1000)
startTime = NSDate()
log("Measured \(name) in \(timeInterval) ms")
}
func stopMeasure() {
startTime = nil
} | mit | fa69ac7da58ee66af5ec8de56402c184 | 17.785714 | 76 | 0.657143 | 3.671329 | false | false | false | false |
MadAppGang/SmartLog | iOS/Pods/Dip/Sources/AutoInjection_swift2.swift | 3 | 4413 | //
// Dip
//
// Copyright (c) 2015 Olivier Halligon <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if !swift(>=3.0)
extension Injected {
/**
Creates a new wrapper for auto-injected property.
- parameters:
- required: Defines if the property is required or not.
If container fails to inject required property it will als fail to resolve
the instance that defines that property. Default is `true`.
- tag: An optional tag to use to lookup definitions when injecting this property. Default is `nil`.
- didInject: block that will be called when concrete instance is injected in this property.
Similar to `didSet` property observer. Default value does nothing.
*/
public convenience init(required: Bool = true, didInject: (T) -> () = { _ in }) {
self.init(value: nil, required: required, tag: nil, overrideTag: false, didInject: didInject)
}
public convenience init(required: Bool = true, tag: DependencyTagConvertible?, didInject: (T) -> () = { _ in }) {
self.init(value: nil, required: required, tag: tag, overrideTag: true, didInject: didInject)
}
public func resolve(container: DependencyContainer) throws {
let resolved: T? = try super.resolve(with: container)
value = resolved
}
/// Returns a new wrapper with provided value.
public func setValue(value: T?) -> Injected {
guard (required && value != nil) || !required else {
fatalError("Can not set required property to nil.")
}
return Injected(value: value, required: required, tag: tag, overrideTag: overrideTag, didInject: didInject)
}
}
extension InjectedWeak {
/**
Creates a new wrapper for weak auto-injected property.
- parameters:
- required: Defines if the property is required or not.
If container fails to inject required property it will als fail to resolve
the instance that defines that property. Default is `true`.
- tag: An optional tag to use to lookup definitions when injecting this property. Default is `nil`.
- didInject: block that will be called when concrete instance is injected in this property.
Similar to `didSet` property observer. Default value does nothing.
*/
public convenience init(required: Bool = true, didInject: (T) -> () = { _ in }) {
self.init(value: nil, required: required, tag: nil, overrideTag: false, didInject: didInject)
}
public convenience init(required: Bool = true, tag: DependencyTagConvertible?, didInject: (T) -> () = { _ in }) {
self.init(value: nil, required: required, tag: tag, overrideTag: true, didInject: didInject)
}
public func resolve(container: DependencyContainer) throws {
let resolved: T? = try super.resolve(with: container)
valueBox = resolved.map(WeakBox.init)
}
/// Returns a new wrapper with provided value.
public func setValue(value: T?) -> InjectedWeak {
guard (required && value != nil) || !required else {
fatalError("Can not set required property to nil.")
}
return InjectedWeak(value: value, required: required, tag: tag, overrideTag: overrideTag, didInject: didInject)
}
}
#endif
| mit | b3d310f2f125a6c0da075143801c5325 | 44.030612 | 117 | 0.672785 | 4.664905 | false | false | false | false |
bastienFalcou/FindMyContacts | Missed Contacts Widget/TodayViewModel.swift | 1 | 1134 | //
// TodayViewModel.swift
// FindMyContacts
//
// Created by Bastien Falcou on 7/15/17.
// Copyright © 2017 Bastien Falcou. All rights reserved.
//
import Foundation
import ReactiveSwift
import DataSource
final class TodayViewModel: NSObject {
var syncedPhoneContacts = MutableProperty<Set<PhoneContact>>([])
var dataSource = MutableProperty<DataSource>(EmptyDataSource())
func updateDataSource() {
let existingContacts = self.syncedPhoneContacts.value.filter { !$0.hasBeenSeen }
var sections: [DataSourceSection<ContactTableViewCellModel>] = existingContacts
.splitBetween {
return floor($0.0.dateAdded.timeIntervalSince1970 / (60 * 60 * 24)) != floor($0.1.dateAdded.timeIntervalSince1970 / (60 * 60 * 24))
}.map { contacts in
return DataSourceSection(items: contacts.map { ContactTableViewCellModel(contact: $0) })
}
let newContacts = self.syncedPhoneContacts.value.filter { $0.hasBeenSeen }
if !newContacts.isEmpty {
sections.append(DataSourceSection(items: newContacts.map { ContactTableViewCellModel(contact: $0) }))
}
self.dataSource.value = StaticDataSource(sections: sections)
}
}
| mit | 60d7bddf42e3ca93ab7ee67dd18a0e4b | 34.40625 | 135 | 0.750221 | 3.814815 | false | false | false | false |
dreamsxin/swift | test/DebugInfo/enum.swift | 3 | 3289 | // RUN: %target-swift-frontend -primary-file %s -emit-ir -g -o - | FileCheck %s
// CHECK: ![[EMPTY:.*]] = !{}
protocol P {}
enum Either {
case First(Int64), Second(P), Neither
// CHECK: !DICompositeType(tag: DW_TAG_union_type, name: "Either",
// CHECK-SAME: line: [[@LINE-3]],
// CHECK-SAME: size: {{328|168}},
}
// CHECK: ![[INT:.*]] = !DICompositeType({{.*}}identifier: "_TtSi"
let E : Either = .Neither;
// CHECK: !DICompositeType(tag: DW_TAG_union_type, name: "Color",
// CHECK-SAME: line: [[@LINE+3]]
// CHECK-SAME: size: 8, align: 8,
// CHECK-SAME: identifier: "_TtO4enum5Color"
enum Color : UInt64 {
// This is effectively a 2-bit bitfield:
// CHECK: !DIDerivedType(tag: DW_TAG_member, name: "Red"
// CHECK-SAME: baseType: ![[UINT64:[0-9]+]]
// CHECK-SAME: size: 8, align: 8{{[,)]}}
// CHECK: ![[UINT64]] = !DICompositeType({{.*}}identifier: "_TtVs6UInt64"
case Red, Green, Blue
}
// CHECK: !DICompositeType(tag: DW_TAG_union_type, name: "MaybeIntPair",
// CHECK-SAME: line: [[@LINE+3]],
// CHECK-SAME: size: 136, align: 64{{[,)]}}
// CHECK-SAME: identifier: "_TtO4enum12MaybeIntPair"
enum MaybeIntPair {
// CHECK: !DIDerivedType(tag: DW_TAG_member, name: "none"
// CHECK-SAME: baseType: ![[INT]], align: 8{{[,)]}}
case none
// CHECK: !DIDerivedType(tag: DW_TAG_member, name: "just"
// CHECK-SAME: baseType: ![[INTTUP:[0-9]+]]
// CHECK-SAME: size: 128, align: 64{{[,)]}}
// CHECK: ![[INTTUP]] = !DICompositeType({{.*}}identifier: "_TtTVs5Int64S__"
case just(Int64, Int64)
}
enum Maybe<T> {
case none
case just(T)
}
let r = Color.Red
let c = MaybeIntPair.just(74, 75)
// CHECK: !DICompositeType(tag: DW_TAG_union_type, name: "Maybe",
// CHECK-SAME: line: [[@LINE-8]],
// CHECK-SAME: size: 8, align: 8{{[,)]}}
// CHECK-SAME: identifier: "_TtGO4enum5MaybeOS_5Color_"
let movie : Maybe<Color> = .none
public enum Nothing { }
public func foo(_ empty : Nothing) { }
// CHECK: !DICompositeType({{.*}}name: "Nothing", {{.*}}elements: ![[EMPTY]]
// CHECK: !DICompositeType({{.*}}name: "Rose", {{.*}}elements: ![[ELTS:[0-9]+]],
// CHECK-SAME: {{.*}}identifier: "_TtGO4enum4Rosex_")
enum Rose<A> {
case MkRose(() -> A, () -> [Rose<A>])
// CHECK: !DICompositeType({{.*}}name: "Rose", {{.*}}elements: ![[ELTS]],
// CHECK-SAME: {{.*}}identifier: "_TtGO4enum4RoseQq_S0__")
case IORose(() -> Rose<A>)
}
func foo<T>(_ x : Rose<T>) -> Rose<T> { return x }
// CHECK: !DICompositeType({{.*}}name: "Tuple", {{.*}}elements: ![[ELTS:[0-9]+]],
// CHECK-SAME: {{.*}}identifier: "_TtGO4enum5Tuplex_")
public enum Tuple<P> {
// CHECK: !DICompositeType({{.*}}name: "Tuple", {{.*}}elements: ![[ELTS]],
// CHECK-SAME: {{.*}}identifier: "_TtGO4enum5TupleQq_S0__")
case C(P, () -> Tuple)
}
func bar<T>(_ x : Tuple<T>) -> Tuple<T> { return x }
// CHECK: ![[LIST:.*]] = !DICompositeType({{.*}}identifier: "_TtGO4enum4ListQq_S0__"
public enum List<T> {
indirect case Tail(List, T)
case End
// CHECK: !DILocalVariable(name: "self", arg: 1, {{.*}} line: [[@LINE+1]], type: ![[LIST]], flags: DIFlagArtificial)
func fooMyList() {}
}
| apache-2.0 | 7dd60c5ab3e7905b943ff389426c3517 | 35.955056 | 116 | 0.559745 | 3.2182 | false | false | false | false |
klundberg/swift-corelibs-foundation | Foundation/Measurement.swift | 1 | 12507 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import CoreFoundation
/// A `Measurement` is a model type that holds a `Double` value associated with a `Unit`.
///
/// Measurements support a large set of operators, including `+`, `-`, `*`, `/`, and a full set of comparison operators.
public struct Measurement<UnitType : Unit> : ReferenceConvertible, Comparable, Equatable, CustomStringConvertible {
public typealias ReferenceType = NSMeasurement
/// The unit component of the `Measurement`.
public let unit: UnitType
/// The value component of the `Measurement`.
public var value: Double
/// Create a `Measurement` given a specified value and unit.
public init(value: Double, unit: UnitType) {
self.value = value
self.unit = unit
}
public var hashValue: Int {
return Int(bitPattern: _CFHashDouble(value))
}
public var description: String {
return "\(value) \(unit.symbol)"
}
public var debugDescription: String {
return "\(value) \(unit.symbol)"
}
}
/// When a `Measurement` contains a `Dimension` unit, it gains the ability to convert between the kinds of units in that dimension.
extension Measurement where UnitType : Dimension {
/// Returns a new measurement created by converting to the specified unit.
///
/// - parameter otherUnit: A unit of the same `Dimension`.
/// - returns: A converted measurement.
public func converted(to otherUnit: UnitType) -> Measurement<UnitType> {
if unit.isEqual(otherUnit) {
return Measurement(value: value, unit: otherUnit)
} else {
let valueInTermsOfBase = unit.converter.baseUnitValue(fromValue: value)
if otherUnit.isEqual(unit.dynamicType.baseUnit()) {
return Measurement(value: valueInTermsOfBase, unit: otherUnit)
} else {
let otherValueFromTermsOfBase = otherUnit.converter.value(fromBaseUnitValue: valueInTermsOfBase)
return Measurement(value: otherValueFromTermsOfBase, unit: otherUnit)
}
}
}
/// Converts the measurement to the specified unit.
///
/// - parameter otherUnit: A unit of the same `Dimension`.
public mutating func convert(to otherUnit: UnitType) {
self = converted(to: otherUnit)
}
}
/// Add two measurements of the same Unit.
/// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`.
/// - returns: A measurement of value `lhs.value + rhs.value` and unit `lhs.unit`.
public func +<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit.isEqual(rhs.unit) {
return Measurement(value: lhs.value + rhs.value, unit: lhs.unit)
} else {
fatalError("Attempt to add measurements with non-equal units")
}
}
/// Add two measurements of the same Dimension.
///
/// If the `unit` of the `lhs` and `rhs` are `isEqual`, then this returns the result of adding the `value` of each `Measurement`. If they are not equal, then this will convert both to the base unit of the `Dimension` and return the result as a `Measurement` of that base unit.
/// - returns: The result of adding the two measurements.
public func +<UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit.isEqual(rhs.unit) {
return Measurement(value: lhs.value + rhs.value, unit: lhs.unit)
} else {
let lhsValueInTermsOfBase = lhs.unit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhs.unit.converter.baseUnitValue(fromValue: rhs.value)
return Measurement(value: lhsValueInTermsOfBase + rhsValueInTermsOfBase, unit: lhs.unit.dynamicType.baseUnit())
}
}
/// Subtract two measurements of the same Unit.
/// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`.
/// - returns: A measurement of value `lhs.value - rhs.value` and unit `lhs.unit`.
public func -<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit.isEqual(rhs.unit) {
return Measurement(value: lhs.value - rhs.value, unit: lhs.unit)
} else {
fatalError("Attempt to subtract measurements with non-equal units")
}
}
/// Subtract two measurements of the same Dimension.
///
/// If the `unit` of the `lhs` and `rhs` are `==`, then this returns the result of subtracting the `value` of each `Measurement`. If they are not equal, then this will convert both to the base unit of the `Dimension` and return the result as a `Measurement` of that base unit.
/// - returns: The result of adding the two measurements.
public func -<UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
if lhs.unit == rhs.unit {
return Measurement(value: lhs.value - rhs.value, unit: lhs.unit)
} else {
let lhsValueInTermsOfBase = lhs.unit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhs.unit.converter.baseUnitValue(fromValue: rhs.value)
return Measurement(value: lhsValueInTermsOfBase - rhsValueInTermsOfBase, unit: lhs.unit.dynamicType.baseUnit())
}
}
/// Multiply a measurement by a scalar value.
/// - returns: A measurement of value `lhs.value * rhs` with the same unit as `lhs`.
public func *<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> {
return Measurement(value: lhs.value * rhs, unit: lhs.unit)
}
/// Multiply a scalar value by a measurement.
/// - returns: A measurement of value `lhs * rhs.value` with the same unit as `rhs`.
public func *<UnitType : Unit>(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
return Measurement(value: lhs * rhs.value, unit: rhs.unit)
}
/// Divide a measurement by a scalar value.
/// - returns: A measurement of value `lhs.value / rhs` with the same unit as `lhs`.
public func /<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> {
return Measurement(value: lhs.value / rhs, unit: lhs.unit)
}
/// Divide a scalar value by a measurement.
/// - returns: A measurement of value `lhs / rhs.value` with the same unit as `rhs`.
public func /<UnitType : Unit>(lhs: Double, rhs: Measurement<UnitType>) -> Measurement<UnitType> {
return Measurement(value: lhs / rhs.value, unit: rhs.unit)
}
/// Compare two measurements of the same `Unit`.
/// - returns: `true` if `lhs.value == rhs.value && lhs.unit == rhs.unit`.
public func ==<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
return lhs.value == rhs.value && lhs.unit == rhs.unit
}
/// Compare two measurements of the same `Dimension`.
///
/// If `lhs.unit == rhs.unit`, returns `lhs.value == rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values.
/// - returns: `true` if the measurements are equal.
public func ==<UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value == rhs.value
} else {
let rhsInLhs = rhs.converted(to: lhs.unit)
return lhs.value == rhsInLhs.value
}
}
/// Compare two measurements of the same `Unit`.
/// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`.
/// - returns: `lhs.value < rhs.value`
public func <<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
return lhs.value < rhs.value
}
/// Compare two measurements of the same `Dimension`.
///
/// If `lhs.unit == rhs.unit`, returns `lhs.value < rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values.
/// - returns: `true` if `lhs` is less than `rhs`.
public func <<UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value < rhs.value
} else {
let rhsInLhs = rhs.converted(to: lhs.unit)
return lhs.value < rhsInLhs.value
}
}
/// Compare two measurements of the same `Unit`.
/// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`.
/// - returns: `lhs.value > rhs.value`
public func ><UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
return lhs.value > rhs.value
}
/// Compare two measurements of the same `Dimension`.
///
/// If `lhs.unit == rhs.unit`, returns `lhs.value > rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values.
/// - returns: `true` if `lhs` is greater than `rhs`.
public func ><UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value > rhs.value
} else {
let rhsInLhs = rhs.converted(to: lhs.unit)
return lhs.value > rhsInLhs.value
}
}
/// Compare two measurements of the same `Unit`.
/// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`.
/// - returns: `lhs.value <= rhs.value`
public func <=<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
return lhs.value <= rhs.value
}
/// Compare two measurements of the same `Dimension`.
///
/// If `lhs.unit == rhs.unit`, returns `lhs.value < rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values.
/// - returns: `true` if `lhs` is less than or equal to `rhs`.
public func <=<UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value <= rhs.value
} else {
let rhsInLhs = rhs.converted(to: lhs.unit)
return lhs.value <= rhsInLhs.value
}
}
/// Compare two measurements of the same `Unit`.
/// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`.
/// - returns: `lhs.value >= rhs.value`
public func >=<UnitType : Unit>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
return lhs.value >= rhs.value
}
/// Compare two measurements of the same `Dimension`.
///
/// If `lhs.unit == rhs.unit`, returns `lhs.value >= rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values.
/// - returns: `true` if `lhs` is greater or equal to `rhs`.
public func >=<UnitType : Dimension>(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value >= rhs.value
} else {
let rhsInLhs = rhs.converted(to: lhs.unit)
return lhs.value >= rhsInLhs.value
}
}
// Implementation note: similar to NSArray, NSDictionary, etc., NSMeasurement's import as an ObjC generic type is suppressed by the importer. Eventually we will need a more general purpose mechanism to correctly import generic types.
extension Measurement {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSMeasurement {
return NSMeasurement(doubleValue: value, unit: unit)
}
public static func _forceBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) {
result = Measurement(value: source.doubleValue, unit: source.unit as! UnitType)
}
public static func _conditionallyBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) -> Bool {
if let u = source.unit as? UnitType {
result = Measurement(value: source.doubleValue, unit: u)
return true
} else {
return false
}
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSMeasurement?) -> Measurement {
let u = source!.unit as! UnitType
return Measurement(value: source!.doubleValue, unit: u)
}
}
| apache-2.0 | 6d21742cabcea203c5585a8d8965cb01 | 44.151625 | 276 | 0.665707 | 4.208277 | false | false | false | false |
XuJanet/DouYuZB | DYZB/DYZB/Classes/Tools/Extension/UIBarButtonItem-Extension.swift | 1 | 1260 | //
// UIBarButtonItem-Extension.swift
// DYZB
//
// Created by xuwenrou on 2017/6/18.
// Copyright © 2017年 xuwenrou. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
class func createItem(imageName:String,highImageName:String,size:CGSize) -> UIBarButtonItem{
let btn = UIButton()
btn.setImage(UIImage(named:imageName), for: .normal)
btn.setImage(UIImage(named:highImageName), for: .highlighted)
btn.frame = CGRect(origin: CGPoint.zero, size: size)
return UIBarButtonItem(customView: btn)
}
//便利构造器
convenience init(imageName:String,highImageName:String = "",size:CGSize = CGSize.zero) {
let btn = UIButton()
btn.setImage(UIImage(named:imageName), for: .normal)
if highImageName != "" {
btn.setImage(UIImage(named:highImageName), for: .highlighted)
}
if size == CGSize.zero {
btn.sizeToFit()
}else{
btn.frame = CGRect(origin: CGPoint.zero, size: size)
}
self.init(customView: btn)
}
}
| mit | 5ef9a896a6a8bf9081a2dd63caeb592e | 22.980769 | 96 | 0.541299 | 4.723485 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.