repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
samodom/UIKitSwagger
|
refs/heads/master
|
UIKitSwagger/AutoLayout/NSLayoutConstraintSearch.swift
|
mit
|
1
|
//
// NSLayoutConstraintSearch.swift
// UIKitSwagger
//
// Created by Sam Odom on 9/25/14.
// Copyright (c) 2014 Sam Odom. All rights reserved.
//
import UIKit
internal extension NSLayoutConstraint {
internal func hasItem(item: AnyObject) -> Bool {
return firstItem.isEqual(item) || (secondItem != nil && secondItem!.isEqual(item))
}
internal func hasItems(itemOne: AnyObject, _ itemTwo: AnyObject) -> Bool {
assert(itemOne !== itemTwo, "The items must be different")
return secondItem != nil && itemsMatch(itemOne, itemTwo)
}
private func itemsMatch(itemOne: AnyObject, _ itemTwo: AnyObject) -> Bool {
return firstItem.isEqual(itemOne) && secondItem!.isEqual(itemTwo) ||
firstItem.isEqual(itemTwo) && secondItem!.isEqual(itemOne)
}
internal func hasAttribute(attribute: NSLayoutAttribute) -> Bool {
return firstAttribute == attribute || secondAttribute == attribute
}
internal func hasAttributedItem(attributedItem: AutoLayoutAttributedItem) -> Bool {
switch attributedItem.attribute {
case firstAttribute:
return firstItem.isEqual(attributedItem.item)
case secondAttribute:
return secondItem != nil && secondItem!.isEqual(attributedItem.item)
default:
return false
}
}
internal func hasAttributedItems(itemOne: AutoLayoutAttributedItem, _ itemTwo: AutoLayoutAttributedItem) -> Bool {
return hasAttributedItem(itemOne) && hasAttributedItem(itemTwo)
}
}
|
d17471b66bd9ab24e03d4575ae10a1b4
| 31.354167 | 118 | 0.675467 | false | false | false | false |
rohan1989/FacebookOauth2Swift
|
refs/heads/master
|
FacebookOauth2Swift/GraphRootViewController.swift
|
mit
|
1
|
//
// GraphRootViewController.swift
// FacebookOauth2Swift
//
// Created by Rohan Sonawane on 06/12/16.
// Copyright © 2016 Rohan Sonawane. All rights reserved.
//
import UIKit
struct GraphRootViewControllerConstants {
static let graphSegueIdentifier = "showGraphView"
}
class GraphRootViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var enterCityTextField: UITextField!
var weatherArray:Array<WeatherForecast>?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.enterCityTextField.resignFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/**
Generalise method to show alerts
@param title -- Alert Title.
@param message -- Alert message.
@return None.
*/
private func showAlert(title:String, message:String){
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
private func showWeatherGraph(){
self.performSegue(withIdentifier: GraphRootViewControllerConstants.graphSegueIdentifier, sender: nil)
}
@IBAction func showWeatherButtonAction(_ sender: Any) {
if enterCityTextField.text?.characters.count == 0 {return}
let openWeatherManager:OpenWeatherManager = OpenWeatherManager()
openWeatherManager.getWeatherForCity(city: enterCityTextField.text!, completionWithWeatherArray: {weatherArray, error in
DispatchQueue.main.async() { () -> Void in
if((error?.code) != 111){
self.weatherArray = weatherArray as? Array<WeatherForecast>
self.showWeatherGraph()
}
else{
self.showAlert(title: "Error Occurred", message: (error?.localizedDescription)!)
}
}
})
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if GraphRootViewControllerConstants.graphSegueIdentifier == segue.identifier {
let destinationViewController = segue.destination as! GraphViewController
destinationViewController.weatherArray = self.weatherArray
destinationViewController.city = enterCityTextField.text
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool { //delegate method
textField.resignFirstResponder()
return true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
b555a1645dc7cca8b02e9b82bfbf3bbe
| 33.298969 | 128 | 0.661557 | false | false | false | false |
zarkopopovski/IOS-Tutorials
|
refs/heads/master
|
BookmarkIN/BookmarkIN/BookmarksListViewController.swift
|
mit
|
1
|
//
// BookmarksListViewController.swift
// BookmarkIN
//
// Created by Zarko Popovski on 5/2/17.
// Copyright © 2017 ZPOTutorials. All rights reserved.
//
import UIKit
import SVProgressHUD
import SwiftyJSON
class BookmarksListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var bookmarksTableView: UITableView!
@IBOutlet weak var btnAdd: UIButton!
let API_CONNECTOR = ApiConnector.sharedInstance
var userBookmarks:[[String:String]] = [[String:String]]()
var userGroups:[[String:String]] = [[String:String]]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.reloadBookmarksData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.userBookmarks.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44.0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let CELL_ID = "Cell"
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: CELL_ID, for: indexPath)
let bookmarkData = self.userBookmarks[indexPath.row]
cell.textLabel?.text = bookmarkData["title"]
cell.detailTextLabel?.text = bookmarkData["url"]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
@IBAction func btnAddAction(_ sender: UIButton) {
let bookmarkURLEntryAlert = UIAlertController(title: "Bookmark Entry", message: "URL Field", preferredStyle: .alert)
bookmarkURLEntryAlert.addTextField { (urlField) in
urlField.placeholder = ""
}
let okAction = UIAlertAction(title: "Ok", style: .default) { (newAction) in
let urlField = bookmarkURLEntryAlert.textFields![0] as UITextField
let bookmarkURL = urlField.text!
SVProgressHUD.show(withStatus: "Loading")
self.API_CONNECTOR.createNewBookmark(bookmarkURL: bookmarkURL, completition: {(hasError, result) in
SVProgressHUD.dismiss()
if !hasError {
self.reloadBookmarksData()
} else {
let errorAlert = UIAlertController(title: "Error", message: "Error saving.", preferredStyle: .alert)
let alertClose = UIAlertAction(title: "Close", style: .cancel, handler: { (alert) in
self.dismiss(animated: true, completion: nil)
})
errorAlert.addAction(alertClose)
self.present(errorAlert, animated: true, completion: nil)
}
})
}
let closeAction = UIAlertAction(title: "Close", style: .destructive) { (newAction) in
bookmarkURLEntryAlert.dismiss(animated: true, completion: nil)
}
bookmarkURLEntryAlert.addAction(okAction)
bookmarkURLEntryAlert.addAction(closeAction)
present(bookmarkURLEntryAlert, animated: true, completion: nil)
}
func reloadBookmarksData() {
SVProgressHUD.show(withStatus: "Loading")
API_CONNECTOR.findAllBookmarks(completition: {(hasError, result) in
SVProgressHUD.dismiss()
if !hasError {
self.userBookmarks = result
self.bookmarksTableView.reloadData()
} else {
let errorAlert = UIAlertController(title: "Error", message: "No data.", preferredStyle: .alert)
let alertClose = UIAlertAction(title: "Close", style: .cancel, handler: { (alert) in
self.dismiss(animated: true, completion: nil)
})
errorAlert.addAction(alertClose)
self.present(errorAlert, animated: true, completion: nil)
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
d526786ba69df130b8c76a4c12dc91fa
| 35.238806 | 124 | 0.612232 | false | false | false | false |
WebAPIKit/WebAPIKit
|
refs/heads/master
|
Sources/WebAPIKit/Request/Request.swift
|
mit
|
1
|
/**
* WebAPIKit
*
* Copyright (c) 2017 Evan Liu. Licensed under the MIT license, as follows:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import Foundation
public typealias ResultHandler = (WebAPIResult) -> Void
open class WebAPIRequest {
open let provider: WebAPIProvider
open let path: String
open let method: HTTPMethod
open var requireAuthentication: Bool?
open var authentication: WebAPIAuthentication?
/// `HttpClient` to send out the http request.
open var httpClient: HTTPClient?
/// Plugins only apply to this request.
open var plugins: PluginHub?
/// Query items in url.
open var queryItems = [URLQueryItem]()
/// Http header fileds.
open var headers = HTTPHeaders()
/// Parameters for POST, PUT, PATCH requests.
/// To be encoded to `httpBody` by `parameterEncoding`.
/// Will be ignored if `httpBody` is set.
open var parameters = Parameters()
/// Encoding to encode `parameters` to `httpBody`.
open var parameterEncoding: ParameterEncoding?
/// Http body for POST, PUT, PATCH requests.
/// Will ignore `parameters` if value provided.
open var httpBody: Data?
public init(provider: WebAPIProvider, path: String, method: HTTPMethod = .get) {
self.provider = provider
self.path = path
self.method = method
}
@discardableResult
open func send(by httpClient: HTTPClient? = nil, handler: @escaping ResultHandler) -> Cancelable {
let httpClient = httpClient ?? self.httpClient ?? provider.httpClient ?? SessionManager.default
return WebAPISender(provider: provider, request: self, httpClient: httpClient, handler: handler)
}
/// Turn to an `URLRequest`, to be sent by `HttpClient` or `URLSession` or any other networking library.
open func toURLRequest() throws -> URLRequest {
let url = try makeURL()
let request = try makeURLRequest(with: url)
return try processURLRequest(request)
}
/// Step 1/3 of `toURLRequest()`: make `URL` from `baseURL`, `path`, and `queryItems`.
open func makeURL() throws -> URL {
let url = provider.baseURL.appendingPathComponent(path)
if queryItems.isEmpty {
return url
}
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
throw AFError.invalidURL(url: url)
}
components.queryItems = queryItems
return try components.asURL()
}
/// Step 2/3 of `toURLRequest()`: make `URLRequest` from `URL`, `method`, `headers`, and `parameters`/`httpBody`.
open func makeURLRequest(with url: URL) throws -> URLRequest {
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
if !headers.isEmpty {
request.allHTTPHeaderFields = headers
}
if let httpBody = httpBody {
request.httpBody = httpBody
} else if !parameters.isEmpty {
let encoding = parameterEncoding ?? provider.parameterEncoding
return try encoding.encode(request, with: parameters)
}
return request
}
/// Step 3/3 of `toURLRequest()`: process `URLRequest` by `Authentication` and `RequestProcessor` plugins.
open func processURLRequest(_ request: URLRequest) throws -> URLRequest {
var request = request
if requireAuthentication ?? provider.requireAuthentication {
guard let authentication = authentication ?? provider.authentication else {
throw WebAPIError.authentication(.missing)
}
request = try authentication.authenticate(request)
}
try provider.plugins.requestProcessors.forEach {
request = try $0.processRequest(request)
}
try plugins?.requestProcessors.forEach {
request = try $0.processRequest(request)
}
return request
}
}
|
1e07adf63276d18bdb07e1b9ae8877af
| 35.764706 | 117 | 0.6732 | false | false | false | false |
MrLSPBoy/LSPDouYu
|
refs/heads/master
|
LSPDouYuTV/LSPDouYuTV/Classes/Main/View/LSPageContentView.swift
|
mit
|
1
|
//
// LSPageContentView.swift
// LSPDouYuTV
//
// Created by lishaopeng on 17/2/28.
// Copyright © 2017年 lishaopeng. All rights reserved.
//
import UIKit
protocol LSPageContentViewDelegate : class {
func pageContentView(contentView: LSPageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int)
}
fileprivate let cellId = "cellId"
class LSPageContentView: UIView {
//MARK: - 定义属性
fileprivate var childVCs: [UIViewController]
fileprivate weak var parentViewController: UIViewController?
fileprivate var startOffsetX: CGFloat = 0
fileprivate var isForbidScrollDelegate : Bool = false
weak var delegate : LSPageContentViewDelegate?
//MARK: - 懒加载属性
fileprivate lazy var collectionView : UICollectionView = {[weak self] in
//1.创建layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
//创建UICollectionView
let collectionView = UICollectionView(frame:CGRect(x: 0, y: 0, width: 0, height: 0) , collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
return collectionView
}()
//MARK: - 自定义构造函数
init(frame: CGRect,childVCs : [UIViewController], parentViewController : UIViewController?) {
self.childVCs = childVCs
self.parentViewController = parentViewController
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: - 设置UI界面
extension LSPageContentView{
fileprivate func setupUI(){
//1.将所有的子控制器添加到父控制器中
for childVC in childVCs {
parentViewController?.addChildViewController(childVC)
}
//2.添加UICollectionView,用于在cell中存放控制器的View
addSubview(collectionView)
collectionView.frame = bounds
}
}
//MARK: - UICollectionViewDataSource
extension LSPageContentView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVCs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1.创建cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
//2.给cell设置内容
let childVc = childVCs[indexPath.item]
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
}
//MARK: - UICollectionViewDelegate
extension LSPageContentView : UICollectionViewDelegate{
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelegate = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//0.判断是否是点击事件
if isForbidScrollDelegate { return }
//1.定义获取需要的数据
var progress: CGFloat = 0
var sourceIndex: Int = 0
var targetIndex: Int = 0
//2.判断是左滑还是右滑
let currentOffsetX = scrollView.contentOffset.x
let scrollViewWidth = scrollView.bounds.width
if currentOffsetX > startOffsetX {//左滑
//1.计算progress
progress = currentOffsetX / scrollViewWidth - floor(currentOffsetX / scrollViewWidth)
//2.计算sourceIndex
sourceIndex = Int(currentOffsetX / scrollViewWidth)
//3.计算targetIndex
targetIndex = sourceIndex + 1
if targetIndex >= childVCs.count {
targetIndex = childVCs.count - 1
}
//4.如果完全划过去
if currentOffsetX - startOffsetX == scrollViewWidth{
progress = 1
targetIndex = sourceIndex
}
}else{//右滑
//1.计算progress
progress = 1 - (currentOffsetX / scrollViewWidth - floor(currentOffsetX / scrollViewWidth))
//2.计算targetIndex
targetIndex = Int(currentOffsetX / scrollViewWidth)
//3.计算soureIndex
sourceIndex = targetIndex + 1
if sourceIndex >= childVCs.count {
sourceIndex = childVCs.count - 1
}
}
// print("progress\(progress) sourceIndex\(sourceIndex) targetIndex\(targetIndex)")
//3.将progress/sourceIndex/targetIndex传递给titleView
delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
//MARK:--对外暴露的方法
extension LSPageContentView{
func setCurrentIndex(currentIndex: Int) {
//1.记录需要禁止我们的执行代理方法
isForbidScrollDelegate = true
//2.滚动正确的位置
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
}
}
|
1f36997e73a16406d1f13a4723eabe7a
| 30.92 | 124 | 0.639456 | false | false | false | false |
radioboo/SemanticVersion
|
refs/heads/master
|
SemanticVersion/Regexp.swift
|
mit
|
1
|
//
// Regexp.swift
// SemanticVersion
//
// Created by atsushi.sakai on 2016/03/07.
// Copyright © 2016年 Atsushi Sakai. All rights reserved.
//
// Inspired by https://gist.github.com/takafumir/317b9325bebf677326b4
// Thanks, takafumir!!
import Foundation
class Regexp {
let internalRegexp: NSRegularExpression
let pattern: String
init(_ pattern: String) {
self.pattern = pattern
do {
self.internalRegexp = try NSRegularExpression(pattern: pattern, options: [])
} catch let error as NSError {
print(error.localizedDescription)
self.internalRegexp = NSRegularExpression()
}
}
func isMatch(_ input: String) -> Bool {
let inputAsNSString = input as NSString
let matches = self.internalRegexp.matches(
in: input,
options: [],
range:NSMakeRange(0, inputAsNSString.length)
)
return matches.count > 0
}
func matches(_ input: String) -> [String]? {
if self.isMatch(input) {
let inputAsNSString = input as NSString
let matches = self.internalRegexp.matches(
in: input,
options: [],
range:NSMakeRange(0, inputAsNSString.length)
)
var results: [String] = []
for i in 0 ..< matches.count {
results.append( inputAsNSString.substring(with: matches[i].range) )
}
return results
}
return nil
}
}
|
ae0c8c3ac32b0d93d5d0098232563772
| 28.056604 | 88 | 0.571429 | false | false | false | false |
gouyz/GYZBaking
|
refs/heads/master
|
baking/Classes/Main/GYZMainTabBarVC.swift
|
mit
|
1
|
//
// GYZMainTabBarVC.swift
// baking
//
// Created by gouyz on 2017/3/23.
// Copyright © 2017年 gouyz. All rights reserved.
//
import UIKit
class GYZMainTabBarVC: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
setUp()
}
func setUp(){
tabBar.tintColor = kYellowFontColor
addViewController(GYZHomeVC(), title: "首页", normalImgName: "icon_tab_home")
addViewController(GYZCategoryVC(), title: "分类", normalImgName: "icon_tab_category")
addViewController(GYZOrderVC(), title: "订单", normalImgName: "icon_tab_order")
addViewController(GYZMineVC(), title: "我的", normalImgName: "icon_tab_mine")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 添加子控件
fileprivate func addViewController(_ childController: UIViewController, title: String,normalImgName: String) {
let nav = GYZBaseNavigationVC(rootViewController:childController)
addChildViewController(nav)
childController.tabBarItem.title = title
childController.tabBarItem.image = UIImage(named: normalImgName)
childController.tabBarItem.selectedImage = UIImage(named: normalImgName + "_selected")
}
}
|
6e6f4750bdcd7957e2b8656e8b4ee7a6
| 30.738095 | 114 | 0.675169 | false | false | false | false |
Rag0n/QuNotes
|
refs/heads/master
|
Core/Utility/Extensions/Array+Extensions.swift
|
gpl-3.0
|
1
|
//
// Array+Extensions.swift
// QuNotes
//
// Created by Alexander Guschin on 12.07.17.
// Copyright © 2017 Alexander Guschin. All rights reserved.
//
extension Array where Element: Equatable {
func appending(_ newElement: Element) -> [Element] {
var updatedArray = self
updatedArray.append(newElement)
return updatedArray
}
func removing(_ element: Element) -> [Element] {
guard let index = index(of: element) else { return self }
var updatedArray = self
updatedArray.remove(at: index)
return updatedArray
}
func removing(at index: Int) -> [Element] {
var updatedArray = self
updatedArray.remove(at: index)
return updatedArray
}
func replacing(at index: Int, with element: Element) -> [Element] {
var updatedArray = self
updatedArray[index] = element
return updatedArray
}
}
|
e2cad8264983a457b89653fee6fb753b
| 26.058824 | 71 | 0.629348 | false | false | false | false |
imitationgame/pokemonpassport
|
refs/heads/master
|
pokepass/View/Projects/VProjectsDetailHeader.swift
|
mit
|
1
|
import UIKit
class VProjectsDetailHeader:UICollectionReusableView
{
weak var label:UILabel!
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
isUserInteractionEnabled = false
let label:UILabel = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.isUserInteractionEnabled = false
label.backgroundColor = UIColor.clear
label.font = UIFont.bold(size:15)
label.textColor = UIColor.black
label.textAlignment = NSTextAlignment.center
label.numberOfLines = 0
self.label = label
addSubview(label)
let views:[String:UIView] = [
"label":label]
let metrics:[String:CGFloat] = [:]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-10-[label]-10-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:[label(20)]-10-|",
options:[],
metrics:metrics,
views:views))
}
required init?(coder:NSCoder)
{
fatalError()
}
}
|
95d9dbfb831c9668d228830f8a53e6f7
| 26.680851 | 63 | 0.583397 | false | false | false | false |
programersun/HiChongSwift
|
refs/heads/master
|
HiChongSwift/PetSubTypeViewController.swift
|
apache-2.0
|
1
|
//
// PetSubTypeViewController.swift
// HiChongSwift
//
// Created by eagle on 14/12/24.
// Copyright (c) 2014年 多思科技. All rights reserved.
//
import UIKit
class PetSubTypeViewController: UITableViewController {
weak var delegate: PetCateFilterDelegate?
weak var root: UIViewController?
var parentID: String?
private var subTypeInfo: LCYPetSubTypeBase?
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()
if let uid = parentID{
let parameter = ["f_id": uid]
LCYNetworking.sharedInstance.POST(LCYApi.PetSubType, parameters: parameter, success: { [weak self] (object) -> Void in
var info = LCYPetSubTypeBase.modelObjectWithDictionary(object as [NSObject : AnyObject])
if info.childStyle.count == 3 {
info.childStyle = (info.childStyle as! [LCYPetSubTypeChildStyle]).sorted({
func toSortInt(name: String) -> Int {
if name == "大型犬" {
return 3
} else if name == "中型犬" {
return 2
} else {
return 1
}
}
let first = toSortInt($0.name)
let second = toSortInt($1.name)
return first > second
})
}
self?.subTypeInfo = info
self?.tableView.reloadData()
return
}, failure: { [weak self](error) -> Void in
self?.alert("您的网络状态不给力哟")
return
})
} else {
alert("内部错误,请退回重试")
}
tableView.backgroundColor = UIColor.LCYThemeColor()
navigationItem.title = "分类"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
if subTypeInfo != nil {
return 1
} else {
return 0
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
if let count = subTypeInfo?.childStyle.count {
return count
} else {
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(PetCateFilterCell.identifier(), forIndexPath: indexPath) as! PetCateFilterCell
if let childInfo = subTypeInfo?.childStyle[indexPath.row] as? LCYPetSubTypeChildStyle {
cell.icyImageView?.setImageWithURL(NSURL(string: childInfo.headImg.toAbsolutePath()), placeholderImage: UIImage(named: "placeholderLogo"))
cell.icyTextLabel?.text = childInfo.name
}
return cell
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if let identifier = segue.identifier {
switch identifier {
case "showLV3":
let destination = segue.destinationViewController as! PetFinalFilterViewController
if let indexPath = tableView.indexPathForSelectedRow()?.row {
let info = subTypeInfo?.childStyle[indexPath] as? LCYPetSubTypeChildStyle
destination.parentID = info?.catId
destination.delegate = delegate
destination.root = root
}
default:
break
}
}
}
}
|
66f3b569281a22f812c9cdf343d04444
| 35.28 | 150 | 0.574201 | false | false | false | false |
johnjohn7188/NetActivity
|
refs/heads/master
|
NetActivity/FTDI.swift
|
mit
|
1
|
//
// FTDI.swift
// NetActivity
//
// Created by John Aguilar on 2/3/18.
// Copyright © 2018 John. All rights reserved.
//
import Foundation
struct FTDI {
struct Pins: OptionSet, CustomStringConvertible {
let rawValue: UInt8
static let tx = Pins(rawValue: 1 << 0)
static let rx = Pins(rawValue: 1 << 1)
static let rts = Pins(rawValue: 1 << 2)
static let cts = Pins(rawValue: 1 << 3)
static let dtr = Pins(rawValue: 1 << 4)
static let dsr = Pins(rawValue: 1 << 5)
static let dcd = Pins(rawValue: 1 << 6)
static let ri = Pins(rawValue: 1 << 7)
var description: String {
var outputString = ""
if self.contains(.tx) { outputString += "TX " }
if self.contains(.rx) { outputString += "RX " }
if self.contains(.rts) { outputString += "RTS " }
if self.contains(.cts) { outputString += "CTS " }
if self.contains(.dtr) { outputString += "DTR " }
if self.contains(.dsr) { outputString += "DSR " }
if self.contains(.dcd) { outputString += "DCD " }
if self.contains(.ri) { outputString += "RI " }
return outputString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
/// Intialize FTDI to BitBang output mode and set all outputs to low
static func initDevice() -> Bool {
var ftHandle: FT_HANDLE?
// Open Device
if FT_Open(0, &ftHandle) != FT_OK { return false }
// Handle must be valid
guard let handle = ftHandle else { return false }
// Set Output Mode to Bit Bang
let mask: UCHAR = 0xFF
let mode: UCHAR = 0x01
if FT_SetBitMode(handle, mask, mode) != FT_OK { return false }
// Set all outputs to low
var outputByte: UCHAR = 0
let outputByteCount: DWORD = 1
var bytesWritten: DWORD = 0
if FT_Write(handle, &outputByte, outputByteCount, &bytesWritten) != FT_OK { return false }
// Close Device
if FT_Close(handle) != FT_OK { return false }
return true
}
static func setOutput(for pins: Pins, value: Bool) -> Bool {
var ftHandle: FT_HANDLE?
// Open Device
if FT_Open(0, &ftHandle) != FT_OK { return false }
// Handle must be valid
guard let handle = ftHandle else { return false }
var currentPins: UCHAR = 0
var bytesReturned: DWORD = 0
if FT_Read(handle, ¤tPins, 1, &bytesReturned) != FT_OK || bytesReturned != 1 { return false }
if value == true {
// set output
currentPins |= pins.rawValue
} else {
currentPins &= ~pins.rawValue
}
// Write new value
var bytesWritten: DWORD = 0
if FT_Write(handle, ¤tPins, 1, &bytesWritten) != FT_OK { return false }
// Close Device
if FT_Close(handle) != FT_OK { return false }
return true
}
}
|
054d49a43a7b2ed784783928d990448c
| 30.643564 | 107 | 0.529412 | false | false | false | false |
mozilla-mobile/focus-ios
|
refs/heads/main
|
Blockzilla/Onboarding/OnboardingConstants.swift
|
mpl-2.0
|
1
|
/* 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
struct OnboardingConstants {
static let onboardingDidAppear = "OnboardingDidAppear"
static let alwaysShowOnboarding = "AlwaysShowOnboarding"
static let ignoreOnboardingExperiment = "IgnoreOnboardingExperiment"
static let showOldOnboarding = "ShowOldOnboarding"
static let shownTips = "ShownTips"
}
|
051c5cc983aac84c2aebc0c6b079c272
| 40.769231 | 72 | 0.760589 | false | false | false | false |
oscarqpe/machine-learning-algorithms
|
refs/heads/master
|
LNN/HashTable.swift
|
gpl-3.0
|
1
|
//
// HastTable.swift
// LSH Test
//
// Created by Andre Valdivia on 18/05/16.
// Copyright © 2016 Andre Valdivia. All rights reserved.
//
import Foundation
class HashTable {
private var hashUnits = Array<HashUnit>()
var keys = Array<Double>()
var key:Double = 0
init(){
for _ in 0..<Param.K{
hashUnits.append(HashUnit())
keys.append(0)
}
}
//Retorna el key de multiplicar
func train(x:Array<Double>) -> Double{
//Get key de todos los hashUnits
for i in 0..<hashUnits.count{
keys[i] = hashUnits[i].getKey(x)
}
//Setear el key = keys * Primos
self.key = 1
for i in 0..<Param.P2.count{
let pos = Param.hpos[i]
self.key += keys[pos] * Double(Param.P2[i])
}
return key
}
//Setear el delta de todos los HashUnits
func setDeltas(delta:Double){
for i in 0..<Param.P2.count{
let pos = Param.hpos[i]
hashUnits[pos].setDelta(delta * Double(Param.P2[i])) // El delta del HT * Primo usado para hallar key
}
}
func actualizarPesos(x:Array<Double>){
for HU in hashUnits{
HU.actualizarPesos(x)
}
}
}
|
9a80d35021c3c395c4a0328f2392e138
| 23.692308 | 113 | 0.536243 | false | false | false | false |
tkabit/Aless
|
refs/heads/master
|
Aless/Aless/Uncompressor.swift
|
mit
|
1
|
//
// Uncompressor.swift
// aless
//
// Created by Sergey Tkachenko on 10/6/15.
// Copyright © 2015 Sergey Tkachenko. All rights reserved.
//
import Foundation
open class Uncompressor {
fileprivate let data : Data
fileprivate let centralDirectory : CentralDirectory
fileprivate var headers : [FileHeader] = [FileHeader]()
fileprivate var offsetFh : Int
/// File names inside the zip
open var files : [String] = [String]()
init?(fromData data : Data) {
self.data = data
self.centralDirectory = CentralDirectory.init(fromData: self.data)!
self.offsetFh = Int(centralDirectory.cdPosition)
for _ in 0...centralDirectory.countOfItems {
if let fh : FileHeader = FileHeader.init(data: data, fhOffset: offsetFh) {
headers.append(fh)
offsetFh = fh.extraDataRange.upperBound + Int(fh.fileComLen) - 1
self.files.append(fh.filename)
}
}
}
/// Test if `file` exists
func containsFile(_ file: String) -> Bool {
return false
}
/// Get data for `file`
func dataForFile(_ file: String) -> Data? {
return nil
}
}
public extension Uncompressor {
/// Create an Uncompressor with an URL, shortcut for `createWithData`
static func createWithURL(_ zipFileURL: URL) -> Uncompressor? {
if let data = try? Data(contentsOf: zipFileURL) {
return createWithData(data)
}
return nil
}
/// Create an Uncompressor with given `NSData`
static func createWithData(_ data: Data) -> Uncompressor? {
return Uncompressor(fromData: data)
}
}
|
2fdc2e0149074eff176c590048a071dd
| 26.919355 | 86 | 0.599653 | false | false | false | false |
lipka/JSON
|
refs/heads/master
|
Tests/JSONTests/Post.swift
|
mit
|
2
|
import Foundation
import JSON
struct Post: Equatable {
enum State: String {
case draft
case published
}
let title: String
let author: User
let state: State
static func == (lhs: Post, rhs: Post) -> Bool {
return lhs.title == rhs.title && lhs.author == rhs.author && lhs.state == rhs.state
}
}
extension Post: JSONDeserializable {
init(json: JSON) throws {
title = try json.decode(key: "title")
author = try json.decode(key: "author")
state = try json.decode(key: "state")
}
}
|
c5141f5003e91b37dad5e1e4e9413476
| 19 | 85 | 0.67 | false | false | false | false |
lockersoft/Winter2016-iOS
|
refs/heads/master
|
BMICalcLecture/Charts/Classes/Data/Implementations/Standard/LineRadarChartDataSet.swift
|
unlicense
|
1
|
//
// LineRadarChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class LineRadarChartDataSet: LineScatterCandleRadarChartDataSet, ILineRadarChartDataSet
{
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
/// The color that is used for filling the line surface area.
private var _fillColor = UIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)
/// The color that is used for filling the line surface area.
public var fillColor: UIColor
{
get { return _fillColor }
set
{
_fillColor = newValue
fill = nil
}
}
/// The object that is used for filling the area below the line.
/// - default: nil
public var fill: ChartFill?
/// The alpha value that is used for filling the line surface,
/// - default: 0.33
public var fillAlpha = CGFloat(0.33)
private var _lineWidth = CGFloat(1.0)
/// line width of the chart (min = 0.2, max = 10)
///
/// **default**: 1
public var lineWidth: CGFloat
{
get
{
return _lineWidth
}
set
{
if (newValue < 0.2)
{
_lineWidth = 0.2
}
else if (newValue > 10.0)
{
_lineWidth = 10.0
}
else
{
_lineWidth = newValue
}
}
}
public var drawFilledEnabled = false
public var isDrawFilledEnabled: Bool
{
return drawFilledEnabled
}
// MARK: NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = super.copyWithZone(zone) as! LineRadarChartDataSet
copy.fillColor = fillColor
copy._lineWidth = _lineWidth
copy.drawFilledEnabled = drawFilledEnabled
return copy
}
}
|
0ef31c79f2e3cd283392767b69f8d867
| 23.228261 | 105 | 0.565276 | false | false | false | false |
StachkaConf/ios-app
|
refs/heads/develop
|
RectangleDissolve/Classes/TempoCounter.swift
|
mit
|
2
|
//
// TempoCounter.swift
// GithubItunesViewer
//
// Created by MIKHAIL RAKHMANOV on 12.02.17.
// Copyright © 2017 m.rakhmanov. All rights reserved.
//
import Foundation
import Foundation
import QuartzCore
enum BeatStep: Int {
case fourth = 4
case eighth = 8
case sixteenth = 16
case thirtyTwo = 32
}
typealias Handler = () -> ()
class TempoCounter {
fileprivate var displayLink: CADisplayLink?
fileprivate let frameRate = 60
fileprivate var internalCounter = 0
var tempo = 60.0
var beatStep = BeatStep.fourth
var handler: Handler?
fileprivate var nextTickLength: Int {
return Int(Double(frameRate) / (tempo / 60.0 * Double(beatStep.rawValue) / 4.0))
}
init() {
displayLink = CADisplayLink(target: self, selector: #selector(fire))
if #available(iOS 10.0, *) {
displayLink?.preferredFramesPerSecond = frameRate
}
displayLink?.add(to: RunLoop.main, forMode: .commonModes)
displayLink?.isPaused = true
}
deinit {
displayLink?.remove(from: RunLoop.main, forMode: .commonModes)
}
func start() {
displayLink?.isPaused = false
}
func stop() {
displayLink?.isPaused = true
}
@objc func fire() {
internalCounter += 1
if internalCounter >= nextTickLength {
internalCounter = 0
handler?()
}
}
}
|
4f3e60adfb23233f3d18d359ead97e78
| 20.861538 | 88 | 0.617875 | false | false | false | false |
GMSLabs/Hyber-SDK-iOS
|
refs/heads/swift-3.0
|
Hyber/Classes/HyberLogger/HyberLogger.swift
|
apache-2.0
|
1
|
//
// HyberLogger.swift
// Hyber-SDK
//
// Created by Taras on 10/27/16.
// Incuube
//
public let HyberLogger = Hyber.hyberLog
public extension Hyber {
static let hyberLog : Logger = {
let log = Logger()
return log
}()
}
private let benchmarker = Benchmarker()
public enum Level {
case trace, debug, info, warning, error
var description: String {
switch self {
case .trace: return "✅ HyberTrace"
case .debug: return "🐞HyberDEBUG"
case .info: return "❗️HyberInfo"
case .warning: return "⚠️ HyberWarinig"
case .error: return "❌ HyberERROR"
}
}
}
extension Level: Comparable {}
public func ==(x: Level, y: Level) -> Bool {
return x.hashValue == y.hashValue
}
public func <(x: Level, y: Level) -> Bool {
return x.hashValue < y.hashValue
}
open class Logger {
public var enabled: Bool = true
public var formatter: Formatter {
didSet { formatter.logger = self }
}
public var theme: Theme?
public var minLevel: Level
public var format: String {
return formatter.description
}
public var colors: String {
return theme?.description ?? ""
}
private let queue = DispatchQueue(label: "Hyber.log")
public init(formatter: Formatter = .default, theme: Theme? = nil, minLevel: Level = .trace) {
self.formatter = formatter
self.theme = theme
self.minLevel = minLevel
formatter.logger = self
}
open func trace(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) {
log(.trace, items, separator, terminator, file, line, column, function)
}
open func debug(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) {
log(.debug, items, separator, terminator, file, line, column, function)
}
open func info(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) {
log(.info, items, separator, terminator, file, line, column, function)
}
open func warning(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) {
log(.warning, items, separator, terminator, file, line, column, function)
}
open func error(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) {
log(.error, items, separator, terminator, file, line, column, function)
}
private func log(_ level: Level, _ items: [Any], _ separator: String, _ terminator: String, _ file: String, _ line: Int, _ column: Int, _ function: String) {
guard enabled && level >= minLevel else { return }
let date = Date()
let result = formatter.format(
level: level,
items: items,
separator: separator,
terminator: terminator,
file: file,
line: line,
column: column,
function: function,
date: date
)
queue.async {
Swift.print(result, separator: "", terminator: "")
}
}
public func measure(_ description: String? = nil, iterations n: Int = 10, file: String = #file, line: Int = #line, column: Int = #column, function: String = #function, block: () -> Void) {
guard enabled && .debug >= minLevel else { return }
let measure = benchmarker.measure(description, iterations: n, block: block)
let date = Date()
let result = formatter.format(
description: measure.description,
average: measure.average,
relativeStandardDeviation: measure.relativeStandardDeviation,
file: file,
line: line,
column: column,
function: function,
date: date
)
queue.async {
Swift.print(result)
}
}
}
|
6ceb08168ff8cc472d8e8057d9c4832e
| 29.689655 | 192 | 0.568539 | false | false | false | false |
Hikaruapp/Swift-PlayXcode
|
refs/heads/master
|
Swift-TegakiNumberGame/Swift-TegakiNumberGame/MPSCNN/SlimMPSCNN.swift
|
mit
|
1
|
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file describes slimmer routines to create some common MPSCNNFunctions, it is useful especially to fetch network parameters from .dat files
*/
import Foundation
import MetalPerformanceShaders
/**
This depends on MetalPerformanceShaders.framework
The SlimMPSCNNConvolution is a wrapper class around MPSCNNConvolution used to encapsulate:
- making an MPSCNNConvolutionDescriptor,
- adding network parameters (weights and bias binaries by memory mapping the binaries)
- getting our convolution layer
*/
class SlimMPSCNNConvolution: MPSCNNConvolution{
/**
A property to keep info from init time whether we will pad input image or not for use during encode call
*/
private var padding = true
/**
Initializes a fully connected kernel.
- Parameters:
- kernelWidth: Kernel Width
- kernelHeight: Kernel Height
- inputFeatureChannels: Number feature channels in input of this layer
- outputFeatureChannels: Number feature channels from output of this layer
- neuronFilter: A neuronFilter to add at the end as activation, default is nil
- device: The MTLDevice on which this SlimMPSCNNConvolution filter will be used
- kernelParamsBinaryName: name of the layer to fetch kernelParameters by adding a prefix "weights_" or "bias_"
- padding: Bool value whether to use padding or not
- strideXY: Stride of the filter
- destinationFeatureChannelOffset: FeatureChannel no. in the destination MPSImage to start writing from, helps with concat operations
- groupNum: if grouping is used, default value is 1 meaning no groups
- Returns:
A valid SlimMPSCNNConvolution object or nil, if failure.
*/
init(kernelWidth: UInt, kernelHeight: UInt, inputFeatureChannels: UInt, outputFeatureChannels: UInt, neuronFilter: MPSCNNNeuron? = nil, device: MTLDevice, kernelParamsBinaryName: String, padding willPad: Bool = true, strideXY: (UInt, UInt) = (1, 1), destinationFeatureChannelOffset: UInt = 0, groupNum: UInt = 1){
// calculate the size of weights and bias required to be memory mapped into memory
let sizeBias = outputFeatureChannels * UInt(MemoryLayout<Float>.size)
let sizeWeights = inputFeatureChannels * kernelHeight * kernelWidth * outputFeatureChannels * UInt(MemoryLayout<Float>.size)
// get the url to this layer's weights and bias
let wtPath = Bundle.main.path(forResource: "weights_" + kernelParamsBinaryName, ofType: "dat")
let bsPath = Bundle.main.path(forResource: "bias_" + kernelParamsBinaryName, ofType: "dat")
// open file descriptors in read-only mode to parameter files
let fd_w = open( wtPath!, O_RDONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
let fd_b = open( bsPath!, O_RDONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
assert(fd_w != -1, "Error: failed to open output file at \""+wtPath!+"\" errno = \(errno)\n")
assert(fd_b != -1, "Error: failed to open output file at \""+bsPath!+"\" errno = \(errno)\n")
// memory map the parameters
let hdrW = mmap(nil, Int(sizeWeights), PROT_READ, MAP_FILE | MAP_SHARED, fd_w, 0)
let hdrB = mmap(nil, Int(sizeBias), PROT_READ, MAP_FILE | MAP_SHARED, fd_b, 0)
// cast Void pointers to Float
let w = UnsafePointer(hdrW!.bindMemory(to: Float.self, capacity: Int(sizeWeights)))
let b = UnsafePointer(hdrB!.bindMemory(to: Float.self, capacity: Int(sizeBias)))
assert(w != UnsafePointer<Float>(bitPattern: -1), "mmap failed with errno = \(errno)")
assert(b != UnsafePointer<Float>(bitPattern: -1), "mmap failed with errno = \(errno)")
// create appropriate convolution descriptor with appropriate stride
let convDesc = MPSCNNConvolutionDescriptor(kernelWidth: Int(kernelWidth),
kernelHeight: Int(kernelHeight),
inputFeatureChannels: Int(inputFeatureChannels),
outputFeatureChannels: Int(outputFeatureChannels),
neuronFilter: neuronFilter)
convDesc.strideInPixelsX = Int(strideXY.0)
convDesc.strideInPixelsY = Int(strideXY.1)
assert(groupNum > 0, "Group size can't be less than 1")
convDesc.groups = Int(groupNum)
// initialize the convolution layer by calling the parent's (MPSCNNConvlution's) initializer
super.init(device: device,
convolutionDescriptor: convDesc,
kernelWeights: w,
biasTerms: b,
flags: MPSCNNConvolutionFlags.none)
self.destinationFeatureChannelOffset = Int(destinationFeatureChannelOffset)
// set padding for calculation of offset during encode call
padding = willPad
// unmap files at initialization of MPSCNNConvolution, the weights are copied and packed internally we no longer require these
assert(munmap(hdrW, Int(sizeWeights)) == 0, "munmap failed with errno = \(errno)")
assert(munmap(hdrB, Int(sizeBias)) == 0, "munmap failed with errno = \(errno)")
// close file descriptors
close(fd_w)
close(fd_b)
}
/**
Encode a MPSCNNKernel into a command Buffer. The operation shall proceed out-of-place.
We calculate the appropriate offset as per how TensorFlow calculates its padding using input image size and stride here.
This [Link](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/nn.py) has an explanation in header comments how tensorFlow pads its convolution input images.
- Parameters:
- commandBuffer: A valid MTLCommandBuffer to receive the encoded filter
- sourceImage: A valid MPSImage object containing the source image.
- destinationImage: A valid MPSImage to be overwritten by result image. destinationImage may not alias sourceImage
*/
override func encode(commandBuffer: MTLCommandBuffer, sourceImage: MPSImage, destinationImage: MPSImage) {
// select offset according to padding being used or not
if padding {
let pad_along_height = ((destinationImage.height - 1) * strideInPixelsY + kernelHeight - sourceImage.height)
let pad_along_width = ((destinationImage.width - 1) * strideInPixelsX + kernelWidth - sourceImage.width)
let pad_top = Int(pad_along_height / 2)
let pad_left = Int(pad_along_width / 2)
self.offset = MPSOffset(x: ((Int(kernelWidth)/2) - pad_left), y: (Int(kernelHeight/2) - pad_top), z: 0)
}
else{
self.offset = MPSOffset(x: Int(kernelWidth)/2, y: Int(kernelHeight)/2, z: 0)
}
super.encode(commandBuffer: commandBuffer, sourceImage: sourceImage, destinationImage: destinationImage)
}
}
/**
This depends on MetalPerformanceShaders.framework
The SlimMPSCNNFullyConnected is a wrapper class around MPSCNNFullyConnected used to encapsulate:
- making an MPSCNNConvolutionDescriptor,
- adding network parameters (weights and bias binaries by memory mapping the binaries)
- getting our fullyConnected layer
*/
class SlimMPSCNNFullyConnected: MPSCNNFullyConnected{
/**
Initializes a fully connected kernel.
- Parameters:
- kernelWidth: Kernel Width
- kernelHeight: Kernel Height
- inputFeatureChannels: Number feature channels in input of this layer
- outputFeatureChannels: Number feature channels from output of this layer
- neuronFilter: A neuronFilter to add at the end as activation, default is nil
- device: The MTLDevice on which this SlimMPSCNNConvolution filter will be used
- kernelParamsBinaryName: name of the layer to fetch kernelParameters by adding a prefix "weights_" or "bias_"
- destinationFeatureChannelOffset: FeatureChannel no. in the destination MPSImage to start writing from, helps with concat operations
- Returns:
A valid SlimMPSCNNFullyConnected object or nil, if failure.
*/
init(kernelWidth: UInt, kernelHeight: UInt, inputFeatureChannels: UInt, outputFeatureChannels: UInt, neuronFilter: MPSCNNNeuron? = nil, device: MTLDevice, kernelParamsBinaryName: String, destinationFeatureChannelOffset: UInt = 0){
// calculate the size of weights and bias required to be memory mapped into memory
let sizeBias = outputFeatureChannels * UInt(MemoryLayout<Float>.size)
let sizeWeights = inputFeatureChannels * kernelHeight * kernelWidth * outputFeatureChannels * UInt(MemoryLayout<Float>.size)
// get the url to this layer's weights and bias
let wtPath = Bundle.main.path(forResource: "weights_" + kernelParamsBinaryName, ofType: "dat")
let bsPath = Bundle.main.path(forResource: "bias_" + kernelParamsBinaryName, ofType: "dat")
// open file descriptors in read-only mode to parameter files
let fd_w = open(wtPath!, O_RDONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
let fd_b = open(bsPath!, O_RDONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
assert(fd_w != -1, "Error: failed to open output file at \""+wtPath!+"\" errno = \(errno)\n")
assert(fd_b != -1, "Error: failed to open output file at \""+bsPath!+"\" errno = \(errno)\n")
// memory map the parameters
let hdrW = mmap(nil, Int(sizeWeights), PROT_READ, MAP_FILE | MAP_SHARED, fd_w, 0)
let hdrB = mmap(nil, Int(sizeBias), PROT_READ, MAP_FILE | MAP_SHARED, fd_b, 0)
// cast Void pointers to Float
let w = UnsafePointer(hdrW!.bindMemory(to: Float.self, capacity: Int(sizeWeights)))
let b = UnsafePointer(hdrB!.bindMemory(to: Float.self, capacity: Int(sizeBias)))
assert(w != UnsafePointer<Float>(bitPattern: -1), "mmap failed with errno = \(errno)")
assert(b != UnsafePointer<Float>(bitPattern: -1), "mmap failed with errno = \(errno)")
// create appropriate convolution descriptor (in fully connected, stride is always 1)
let convDesc = MPSCNNConvolutionDescriptor(kernelWidth: Int(kernelWidth),
kernelHeight: Int(kernelHeight),
inputFeatureChannels: Int(inputFeatureChannels),
outputFeatureChannels: Int(outputFeatureChannels),
neuronFilter: neuronFilter)
// initialize the convolution layer by calling the parent's (MPSCNNFullyConnected's) initializer
super.init(device: device,
convolutionDescriptor: convDesc,
kernelWeights: w,
biasTerms: b,
flags: MPSCNNConvolutionFlags.none)
self.destinationFeatureChannelOffset = Int(destinationFeatureChannelOffset)
// unmap files at initialization of MPSCNNFullyConnected, the weights are copied and packed internally we no longer require these
assert(munmap(hdrW, Int(sizeWeights)) == 0, "munmap failed with errno = \(errno)")
assert(munmap(hdrB, Int(sizeBias)) == 0, "munmap failed with errno = \(errno)")
// close file descriptors
close(fd_w)
close(fd_b)
}
}
|
022decfb66a7cbcd2f1f9f82c8e35f7e
| 54.930233 | 317 | 0.64341 | false | false | false | false |
chitaranjan/Album
|
refs/heads/master
|
MYAlbum/Pods/SABlurImageView/SABlurImageView/SABlurImageView.swift
|
mit
|
2
|
//
// UIImageView+BlurEffect.swift
// SABlurImageView
//
// Created by 鈴木大貴 on 2015/03/27.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
import Foundation
import QuartzCore
open class SABlurImageView: UIImageView {
//MARK: - Static Properties
fileprivate struct Const {
static let fadeAnimationKey = "FadeAnimationKey"
static let maxImageCount: Int = 10
static let contentsAnimationKey = "contents"
}
//MARK: - Instance Properties
fileprivate var cgImages: [CGImage] = [CGImage]()
fileprivate var nextBlurLayer: CALayer?
fileprivate var previousImageIndex: Int = -1
fileprivate var previousPercentage: CGFloat = 0.0
open fileprivate(set) var isBlurAnimating: Bool = false
deinit {
clearMemory()
}
//MARK: - Life Cycle
open override func layoutSubviews() {
super.layoutSubviews()
nextBlurLayer?.frame = bounds
}
open func configrationForBlurAnimation(_ boxSize: CGFloat = 100) {
guard let image = image else { return }
let baseBoxSize = max(min(boxSize, 200), 0)
let baseNumber = sqrt(CGFloat(baseBoxSize)) / CGFloat(Const.maxImageCount)
let baseCGImages = [image].flatMap { $0.cgImage }
cgImages = bluredCGImages(baseCGImages, sourceImage: image, at: 0, to: Const.maxImageCount, baseNumber: baseNumber)
}
fileprivate func bluredCGImages(_ images: [CGImage], sourceImage: UIImage?, at index: Int, to limit: Int, baseNumber: CGFloat) -> [CGImage] {
guard index < limit else { return images }
let newImage = sourceImage?.blurEffect(pow(CGFloat(index) * baseNumber, 2))
let newImages = images + [newImage].flatMap { $0?.cgImage }
return bluredCGImages(newImages, sourceImage: newImage, at: index + 1, to: limit, baseNumber: baseNumber)
}
open func clearMemory() {
cgImages.removeAll(keepingCapacity: false)
nextBlurLayer?.removeFromSuperlayer()
nextBlurLayer = nil
previousImageIndex = -1
previousPercentage = 0.0
layer.removeAllAnimations()
}
//MARK: - Add single blur
open func addBlurEffect(_ boxSize: CGFloat, times: UInt = 1) {
guard let image = image else { return }
self.image = addBlurEffectTo(image, boxSize: boxSize, remainTimes: times)
}
fileprivate func addBlurEffectTo(_ image: UIImage, boxSize: CGFloat, remainTimes: UInt) -> UIImage {
guard let blurImage = image.blurEffect(boxSize) else { return image }
return remainTimes > 0 ? addBlurEffectTo(blurImage, boxSize: boxSize, remainTimes: remainTimes - 1) : image
}
//MARK: - Percentage blur
open func blur(_ percentage: CGFloat) {
let percentage = min(max(percentage, 0.0), 0.99)
if previousPercentage - percentage > 0 {
let index = Int(floor(percentage * 10)) + 1
if index > 0 {
setLayers(index, percentage: percentage, currentIndex: index - 1, nextIndex: index)
}
} else {
let index = Int(floor(percentage * 10))
if index < cgImages.count - 1 {
setLayers(index, percentage: percentage, currentIndex: index, nextIndex: index + 1)
}
}
previousPercentage = percentage
}
fileprivate func setLayers(_ index: Int, percentage: CGFloat, currentIndex: Int, nextIndex: Int) {
if index != previousImageIndex {
CATransaction.animationWithDuration(0) { layer.contents = self.cgImages[currentIndex] }
if nextBlurLayer == nil {
let nextBlurLayer = CALayer()
nextBlurLayer.frame = bounds
layer.addSublayer(nextBlurLayer)
self.nextBlurLayer = nextBlurLayer
}
CATransaction.animationWithDuration(0) {
self.nextBlurLayer?.contents = self.cgImages[nextIndex]
self.nextBlurLayer?.opacity = 1.0
}
}
previousImageIndex = index
let minPercentage = percentage * 100.0
let alpha = min(max((minPercentage - CGFloat(Int(minPercentage / 10.0) * 10)) / 10.0, 0.0), 1.0)
CATransaction.animationWithDuration(0) { self.nextBlurLayer?.opacity = Float(alpha) }
}
//MARK: - Animation blur
open func startBlurAnimation(_ duration: TimeInterval) {
if isBlurAnimating { return }
isBlurAnimating = true
let count = cgImages.count
let group = CAAnimationGroup()
group.animations = cgImages.enumerated().flatMap {
guard $0.offset < count - 1 else { return nil }
let anim = CABasicAnimation(keyPath: Const.contentsAnimationKey)
anim.fromValue = $0.element
anim.toValue = cgImages[$0.offset + 1]
anim.fillMode = kCAFillModeForwards
anim.isRemovedOnCompletion = false
anim.duration = duration / TimeInterval(count)
anim.beginTime = anim.duration * TimeInterval($0.offset)
return anim
}
group.duration = duration
group.delegate = self
group.isRemovedOnCompletion = false
group.fillMode = kCAFillModeForwards
layer.add(group, forKey: Const.fadeAnimationKey)
cgImages = cgImages.reversed()
}
}
extension SABlurImageView: CAAnimationDelegate {
open func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
guard let _ = anim as? CAAnimationGroup else { return }
layer.removeAnimation(forKey: Const.fadeAnimationKey)
isBlurAnimating = false
guard let cgImage = cgImages.first else { return }
image = UIImage(cgImage: cgImage)
}
}
|
fd9457e713201d8ebec3616c140e832d
| 38.367347 | 145 | 0.63107 | false | false | false | false |
CharlesVu/Smart-iPad
|
refs/heads/master
|
Persistance/Persistance/RealmModels/RealmJourney.swift
|
mit
|
1
|
//
// Journey.swift
// Persistance
//
// Created by Charles Vu on 05/06/2019.
// Copyright © 2019 Charles Vu. All rights reserved.
//
import Foundation
import RealmSwift
@objcMembers public final class RealmJourney: Object {
public dynamic var id: String! = UUID().uuidString
public dynamic var originCRS: String! = ""
public dynamic var destinationCRS: String! = ""
convenience public init(originCRS: String, destinationCRS: String) {
self.init()
self.originCRS = originCRS
self.destinationCRS = destinationCRS
self.id = originCRS + destinationCRS
}
override public static func primaryKey() -> String? {
return "id"
}
convenience init(journey: Journey) {
self.init()
self.originCRS = journey.originCRS
self.destinationCRS = journey.destinationCRS
}
}
|
e34c1f77784d4020426b3698005f9382
| 25.090909 | 72 | 0.664344 | false | false | false | false |
Rep2/IRSocket
|
refs/heads/master
|
IRSocket/IRSockaddr.swift
|
mit
|
1
|
//
// IRSockaddr.swift
// RASUSLabos
//
// Created by Rep on 12/14/15.
// Copyright © 2015 Rep. All rights reserved.
//
import Foundation
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
class IRSockaddr{
var cSockaddr:sockaddr_in
init(ip: UInt32 = 0, port: UInt16 = 0, domain:Int32 = AF_INET){
cSockaddr = sockaddr_in(
sin_len: __uint8_t(sizeof(sockaddr_in)),
sin_family: sa_family_t(domain),
sin_port: htons(port),
sin_addr: in_addr(s_addr: ip),
sin_zero: ( 0, 0, 0, 0, 0, 0, 0, 0 )
)
}
init(socket: sockaddr_in){
cSockaddr = socket
}
func toString() -> String{
return "127.0.0.1 \(ntohs(cSockaddr.sin_port))"
}
}
|
e1b20c7955d538caaa69195f102fd151
| 20.243243 | 67 | 0.53758 | false | false | false | false |
shaoyihe/100-Days-of-IOS
|
refs/heads/master
|
24 - CUSTOM COLLECTION VIEW/24 - CUSTOM COLLECTION VIEW/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// 24 - CUSTOM COLLECTION VIEW
//
// Created by heshaoyi on 4/4/16.
// Copyright © 2016 heshaoyi. All rights reserved.
//
import UIKit
import Photos
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var phResult: PHFetchResult?
@IBOutlet var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let opt = PHFetchOptions()
// let desc = NSSortDescriptor(key: "startDate", ascending: true)
// opt.sortDescriptors = [desc]
self.phResult = PHAsset.fetchAssetsWithOptions(opt)
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return (self.phResult?.count)!
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("image", forIndexPath: indexPath) as! ImageCollectionViewCell
let asset = phResult?.objectAtIndex(indexPath.row) as! PHAsset
PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: cell.frame.size, contentMode: .AspectFill, options: nil, resultHandler: {
(im:UIImage?, info:[NSObject : AnyObject]?) in
if let im = im {
cell.imageView.image = im
}
})
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
let width = view.frame.size.width / 3
return CGSize(width: width, height: 100)
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator){
collectionView.collectionViewLayout.invalidateLayout()
}
}
|
a6d380d195567dcb7b22d90e21edbb3d
| 36.214286 | 168 | 0.696737 | false | false | false | false |
simonnarang/Fandom
|
refs/heads/master
|
Desktop/Fandom-IOS-master/Fandomm/RedisClient.swift
|
unlicense
|
2
|
//
// RedisClient.swift
// Redis-Framework
//
// Copyright (c) 2015, Eric Orion Anderson
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
public let RedisErrorDomain = "com.rareairconsulting.redis"
public enum RedisLogSeverity:String
{
case Info = "Info"
case Debug = "Debug"
case Error = "Error"
case Critical = "Critical"
}
public typealias RedisLoggingBlock = ((redisClient:AnyObject, message:String, severity:RedisLogSeverity) -> Void)?
public typealias RedisCommandStringBlock = ((string:String!, error:NSError!)->Void)
public typealias RedisCommandIntegerBlock = ((int:Int!, error:NSError!)->Void)
public typealias RedisCommandArrayBlock = ((array:[AnyObject]!, error:NSError!)->Void)
public typealias RedisCommandDataBlock = ((data:NSData!, error:NSError!)->Void)
/// RedisClient
///
/// A simple redis client that can be extended for supported Redis commands.
/// This client expects a response for each request and acts as a serial queue.
/// See: RedisPubSubClient for publish/subscribe functionality.
public class RedisClient
{
private let _loggingBlock:RedisLoggingBlock
private let _delegateQueue:NSOperationQueue!
private let _serverHost:String!
private let _serverPort:Int!
lazy private var _commander:RESPCommander = RESPCommander(redisClient: self)
internal var closeExpected:Bool = false {
didSet {
self._commander._closeExpected = self.closeExpected
}
}
public var host:String {
return self._serverHost
}
public var port:Int {
return self._serverPort
}
internal func performBlockOnDelegateQueue(block:dispatch_block_t) -> Void {
self._delegateQueue.addOperationWithBlock(block)
}
public init(host:String, port:Int, loggingBlock:RedisLoggingBlock? = nil, delegateQueue:NSOperationQueue? = nil)
{
self._serverHost = host
self._serverPort = port
if loggingBlock == nil
{
self._loggingBlock = {(redisClient:AnyObject, message:String, severity:RedisLogSeverity) in
switch(severity)
{
case .Critical, .Error:
print(message)
default: break
}
}
}
else {
self._loggingBlock = loggingBlock!
}
if delegateQueue == nil {
self._delegateQueue = NSOperationQueue.mainQueue()
}
else {
self._delegateQueue = delegateQueue
}
}
public func sendCommandWithArrayResponse(command: String, data:NSData? = nil, completionHandler: RedisCommandArrayBlock)
{
self._commander.sendCommand(RESPUtilities.commandToRequestString(command, data:(data != nil)), completionHandler: { (data, error) -> Void in
self.performBlockOnDelegateQueue({ () -> Void in
if error != nil {
completionHandler(array: nil, error: error)
}
else {
let parsingResults:(array:[AnyObject]!, error:NSError!) = RESPUtilities.respArrayFromData(data)
completionHandler(array: parsingResults.array, error: parsingResults.error)
}
})
})
}
public func sendCommandWithIntegerResponse(command: String, data:NSData? = nil, completionHandler: RedisCommandIntegerBlock)
{
self._commander.sendCommand(RESPUtilities.commandToRequestString(command, data:(data != nil)), completionHandler: { (data, error) -> Void in
self.performBlockOnDelegateQueue({ () -> Void in
if error != nil {
completionHandler(int: nil, error: error)
}
else {
let parsingResults:(int:Int!, error:NSError!) = RESPUtilities.respIntegerFromData(data)
completionHandler(int: parsingResults.int, error: parsingResults.error)
}
})
})
}
public func sendCommandWithStringResponse(command: String, data:NSData? = nil, completionHandler: RedisCommandStringBlock)
{
self._commander.sendCommand(RESPUtilities.commandToRequestString(command, data:(data != nil)), data:data, completionHandler: { (data, error) -> Void in
self.performBlockOnDelegateQueue({ () -> Void in
if error != nil {
completionHandler(string: nil, error: error)
}
else {
let parsingResults = RESPUtilities.respStringFromData(data)
completionHandler(string: parsingResults.string, error: parsingResults.error)
}
})
})
}
public func sendCommandWithDataResponse(command: String, data:NSData? = nil, completionHandler: RedisCommandDataBlock)
{
self._commander.sendCommand(RESPUtilities.commandToRequestString(command, data:(data != nil)), completionHandler: { (data, error) -> Void in
self.performBlockOnDelegateQueue({ () -> Void in
completionHandler(data: data, error: error)
})
})
}
private func log(message:String, severity:RedisLogSeverity)
{
if NSThread.isMainThread() {
self._loggingBlock!(redisClient: self, message: message, severity: severity)
}
else {
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
self._loggingBlock!(redisClient: self, message: message, severity: severity)
})
}
}
}
private class RESPCommander:NSObject, NSStreamDelegate
{
private let _redisClient:RedisClient!
private var _inputStream:NSInputStream!
private var _outputStream:NSOutputStream!
private let _operationQueue:NSOperationQueue!
private let _commandLock:dispatch_semaphore_t!
private let _queueLock:dispatch_semaphore_t!
private var _incomingData:NSMutableData!
private let operationLock:String = "RedisOperationLock"
private var _queuedCommand:String! = nil
private var _queuedData:NSData! = nil
private var _error:NSError?
private var _closeExpected:Bool = false
private func _closeStreams()
{
if self._inputStream != nil
{
self._inputStream.close()
self._inputStream.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
self._inputStream = nil
}
if self._outputStream != nil
{
self._outputStream.close()
self._outputStream.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
self._outputStream = nil
}
}
private func _openStreams()
{
self._closeStreams()
var readStream:NSInputStream? = nil
var writeStream:NSOutputStream? = nil
NSStream.getStreamsToHostWithName(self._redisClient._serverHost, port: self._redisClient._serverPort, inputStream: &readStream, outputStream: &writeStream)
self._inputStream = readStream
self._outputStream = writeStream
self._inputStream.delegate = self
self._outputStream.delegate = self
self._inputStream.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
self._outputStream.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
self._inputStream.open()
self._outputStream.open()
}
init(redisClient: RedisClient)
{
self._commandLock = dispatch_semaphore_create(0);
self._queueLock = dispatch_semaphore_create(1)
self._operationQueue = NSOperationQueue()
self._redisClient = redisClient
super.init()
self._openStreams()
}
@objc func stream(theStream: NSStream, handleEvent streamEvent: NSStreamEvent)
{
switch(streamEvent)
{
case NSStreamEvent.HasBytesAvailable:
if self._inputStream === theStream //reading
{
self._redisClient.log("\tHasBytesAvailable", severity: .Debug)
self._redisClient.log("\t--READING COMMAND RESPONSE---", severity: .Debug)
let bufferSize:Int = 1024
var buffer = [UInt8](count: bufferSize, repeatedValue: 0)
let bytesRead:Int = self._inputStream.read(&buffer, maxLength: bufferSize)
self._redisClient.log("\tbytes read:\(bytesRead)", severity: .Debug)
let data = NSData(bytes: buffer, length: bytesRead)
if bytesRead == bufferSize && self._inputStream.hasBytesAvailable //reached the end of the buffer, more to come
{
if self._incomingData != nil { //there was existing data
self._incomingData.appendData(data)
}
else {
self._incomingData = NSMutableData(data: data)
}
}
else if bytesRead > 0 //finished
{
if self._incomingData != nil //there was existing data
{
self._incomingData.appendData(data)
}
else { //got it all in one shot
self._incomingData = NSMutableData(data: data)
}
self._redisClient.log("\tfinished reading", severity: .Debug)
dispatch_semaphore_signal(self._commandLock) //signal we are done
}
else
{
if !self._closeExpected
{
self._error = NSError(domain: "com.rareairconsulting.resp", code: 0, userInfo: [NSLocalizedDescriptionKey:"Error occured while reading."])
dispatch_semaphore_signal(self._commandLock) //signal we are done
}
}
}
case NSStreamEvent.HasSpaceAvailable:
self._redisClient.log("\tHasSpaceAvailable", severity: .Debug)
if theStream === self._outputStream && self._queuedCommand != nil { //writing
self._sendQueuedCommand()
}
case NSStreamEvent.OpenCompleted:
self._redisClient.log("\tOpenCompleted", severity: .Debug)
case NSStreamEvent.ErrorOccurred:
self._redisClient.log("\tErrorOccurred", severity: .Debug)
self._error = theStream.streamError
dispatch_semaphore_signal(self._commandLock) //signal we are done
case NSStreamEvent.EndEncountered: //cleanup
self._redisClient.log("\tEndEncountered", severity: .Debug)
self._closeStreams()
default:
break
}
}
private func _sendQueuedCommand()
{
let queuedCommand = self._queuedCommand
self._queuedCommand = nil
if queuedCommand != nil && !queuedCommand.isEmpty
{
self._redisClient.log("\t--SENDING COMMAND (\(queuedCommand))---", severity: .Debug)
let commandStringData:NSMutableData = NSMutableData(data: queuedCommand.dataUsingEncoding(NSUTF8StringEncoding)!)
if self._queuedData != nil
{
commandStringData.appendData("$\(self._queuedData.length)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
commandStringData.appendData(self._queuedData)
commandStringData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
self._queuedData = nil
}
self._incomingData = nil
let bytesWritten = self._outputStream.write(UnsafePointer<UInt8>(commandStringData.bytes), maxLength: commandStringData.length)
self._redisClient.log("\tbytes sent: \(bytesWritten)", severity: .Debug)
}
}
private func sendCommand(command:NSString, data:NSData? = nil, completionHandler:RedisCommandDataBlock)
{
//could probably use gcd barriers for this but this seems good for now
self._operationQueue.addOperationWithBlock { [unowned self] () -> Void in
self._redisClient.log("***Adding to the command queue***", severity: .Debug)
dispatch_semaphore_wait(self._queueLock, DISPATCH_TIME_FOREVER)
self._redisClient.log("***New command starting off queue***", severity: .Debug)
self._queuedCommand = command as String
self._queuedData = data
if self._inputStream != nil
{
switch(self._inputStream.streamStatus)
{
case NSStreamStatus.Closed, NSStreamStatus.Error: //try opening it if closed
self._openStreams()
default: break
}
}
else {
self._openStreams()
}
switch(self._outputStream.streamStatus)
{
case NSStreamStatus.Closed, NSStreamStatus.Error: //try opening it if closed
self._openStreams()
case NSStreamStatus.Open:
self._sendQueuedCommand()
default: break
}
dispatch_semaphore_wait(self._commandLock, DISPATCH_TIME_FOREVER)
self._redisClient.log("***Releasing command queue lock***", severity: .Debug)
completionHandler(data: self._incomingData, error: self._error)
dispatch_semaphore_signal(self._queueLock)
}
}
}
|
e90c115f434ea2e988a8cfa001aada9d
| 42.381356 | 166 | 0.598359 | false | false | false | false |
X8/CocoaMarkdown
|
refs/heads/master
|
Example/Pods/Nimble/Sources/Nimble/Matchers/SatisfyAllOf.swift
|
mit
|
7
|
import Foundation
/// A Nimble matcher that succeeds when the actual value matches with all of the matchers
/// provided in the variable list of matchers.
public func satisfyAllOf<T, U>(_ matchers: U...) -> Predicate<T>
where U: Matcher, U.ValueType == T {
return satisfyAllOf(matchers)
}
/// Deprecated. Please use `satisfyAnyOf<T>(_) -> Predicate<T>` instead.
internal func satisfyAllOf<T, U>(_ matchers: [U]) -> Predicate<T>
where U: Matcher, U.ValueType == T {
return NonNilMatcherFunc<T> { actualExpression, failureMessage in
let postfixMessages = NSMutableArray()
var matches = true
for matcher in matchers {
if try matcher.doesNotMatch(actualExpression, failureMessage: failureMessage) {
matches = false
}
postfixMessages.add(NSString(string: "{\(failureMessage.postfixMessage)}"))
}
failureMessage.postfixMessage = "match all of: " + postfixMessages.componentsJoined(by: ", and ")
if let actualValue = try actualExpression.evaluate() {
failureMessage.actualValue = "\(actualValue)"
}
return matches
}.predicate
}
internal func satisfyAllOf<T>(_ predicates: [Predicate<T>]) -> Predicate<T> {
return Predicate { actualExpression in
var postfixMessages = [String]()
var matches = true
for predicate in predicates {
let result = try predicate.satisfies(actualExpression)
if result.toBoolean(expectation: .toNotMatch) {
matches = false
}
postfixMessages.append("{\(result.message.expectedMessage)}")
}
var msg: ExpectationMessage
if let actualValue = try actualExpression.evaluate() {
msg = .expectedCustomValueTo(
"match all of: " + postfixMessages.joined(separator: ", and "),
"\(actualValue)"
)
} else {
msg = .expectedActualValueTo(
"match all of: " + postfixMessages.joined(separator: ", and ")
)
}
return PredicateResult(
bool: matches,
message: msg
)
}.requireNonNil
}
public func && <T>(left: Predicate<T>, right: Predicate<T>) -> Predicate<T> {
return satisfyAllOf(left, right)
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
extension NMBObjCMatcher {
@objc public class func satisfyAllOfMatcher(_ matchers: [NMBMatcher]) -> NMBPredicate {
return NMBPredicate { actualExpression in
if matchers.isEmpty {
return NMBPredicateResult(
status: NMBPredicateStatus.fail,
message: NMBExpectationMessage(
fail: "satisfyAllOf must be called with at least one matcher"
)
)
}
var elementEvaluators = [Predicate<NSObject>]()
for matcher in matchers {
let elementEvaluator = Predicate<NSObject> { expression in
if let predicate = matcher as? NMBPredicate {
// swiftlint:disable:next line_length
return predicate.satisfies({ try! expression.evaluate() }, location: actualExpression.location).toSwift()
} else {
let failureMessage = FailureMessage()
// swiftlint:disable:next line_length
let success = matcher.matches({ try! expression.evaluate() }, failureMessage: failureMessage, location: actualExpression.location)
return PredicateResult(bool: success, message: failureMessage.toExpectationMessage())
}
}
elementEvaluators.append(elementEvaluator)
}
return try! satisfyAllOf(elementEvaluators).satisfies(actualExpression).toObjectiveC()
}
}
}
#endif
|
8e60fd77909f53c6f3b0886cf50bcf48
| 38.782178 | 154 | 0.580139 | false | false | false | false |
CraigZheng/KomicaViewer
|
refs/heads/master
|
KomicaViewer/KomicaViewer/ViewController/ForumTextInputViewController.swift
|
mit
|
1
|
//
// ForumTextInputViewController.swift
// KomicaViewer
//
// Created by Craig Zheng on 21/08/2016.
// Copyright © 2016 Craig. All rights reserved.
//
import UIKit
protocol ForumTextInputViewControllerProtocol {
func forumDetailEntered(_ inputViewController: ForumTextInputViewController, enteredDetails: String, forField: ForumField)
}
class ForumTextInputViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var textViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var toolbarBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var insertBarButtonItem: UIBarButtonItem!
@IBOutlet weak var saveBarButtonItem: UIBarButtonItem!
var allowEditing = true
var delegate: ForumTextInputViewControllerProtocol?
var prefilledString: String?
var pageSpecifier: String?
var field: ForumField! {
didSet {
self.title = field.rawValue
switch field! {
case ForumField.listURL:
pageSpecifier = "<PAGE>"
case ForumField.responseURL:
pageSpecifier = "<ID>"
default:
break;
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
if let prefilledString = prefilledString {
textView.text = prefilledString
}
// Keyboard events observer.
NotificationCenter.default.addObserver(self, selector: #selector(ForumTextInputViewController.handlekeyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ForumTextInputViewController.handleKeyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
// Configure the text view.
insertBarButtonItem.isEnabled = pageSpecifier?.isEmpty == false
if !allowEditing {
textView.isEditable = false
insertBarButtonItem.isEnabled = false
saveBarButtonItem.isEnabled = false
} else {
textView.becomeFirstResponder()
}
}
}
extension ForumTextInputViewController: UITextViewDelegate {
func textViewDidEndEditing(_ textView: UITextView) {
}
func textViewDidChange(_ textView: UITextView) {
// When page specifier is not empty.
if let pageSpecifier = pageSpecifier, !pageSpecifier.isEmpty
{
// Insert button enables itself when the textView.text does not contain the page specifier.
insertBarButtonItem.isEnabled = (textView.text as NSString).range(of: pageSpecifier).location == NSNotFound
}
}
}
// MARK: UI actions.
extension ForumTextInputViewController {
@IBAction func saveAction(_ sender: AnyObject) {
textView.resignFirstResponder()
if let enteredText = textView.text, !enteredText.isEmpty {
// If page specifier is not empty and the enteredText does not contain it, show a warning.
if let pageSpecifier = pageSpecifier, !pageSpecifier.isEmpty && !enteredText.contains(pageSpecifier) {
ProgressHUD.showMessage("Cannot save, \(pageSpecifier) is required.")
} else {
delegate?.forumDetailEntered(self, enteredDetails: enteredText, forField: field)
_ = navigationController?.popViewController(animated: true)
}
}
}
@IBAction func insertAction(_ sender: AnyObject) {
let alertController = UIAlertController(title: "Insert \(pageSpecifier ?? "")", message: "Insert the tag specifier to the current position", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: {_ in
if let pageSpecifier = self.pageSpecifier, !pageSpecifier.isEmpty {
let generalPasteboard = UIPasteboard.general
let items = generalPasteboard.items
generalPasteboard.string = pageSpecifier
self.textView.paste(self)
generalPasteboard.items = items
}
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alertController.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem
if let topViewController = UIApplication.topViewController {
topViewController.present(alertController, animated: true, completion: nil)
}
}
}
// MARK: keyboard events.
extension ForumTextInputViewController {
func handlekeyboardWillShow(_ notification: Notification) {
if let keyboardValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue
{
let keyboardRect = view.convert(keyboardValue.cgRectValue, from: nil)
textViewBottomConstraint.constant = keyboardRect.size.height
toolbarBottomConstraint.constant = keyboardRect.size.height
}
}
func handleKeyboardWillHide(_ notification: Notification) {
textViewBottomConstraint.constant = 0
toolbarBottomConstraint.constant = 0
}
}
|
d2dfc2605e44fc3f0ea0ee26f563f6cd
| 38.938462 | 189 | 0.672188 | false | false | false | false |
hzalaz/analytics-ios
|
refs/heads/master
|
Example/Tests/FileStorageTest.swift
|
mit
|
1
|
//
// FileStorageTest.swift
// Analytics
//
// Copyright © 2016 Segment. All rights reserved.
//
import Quick
import Nimble
import Analytics
class FileStorageTest : QuickSpec {
override func spec() {
var storage : SEGFileStorage!
beforeEach {
let url = SEGFileStorage.applicationSupportDirectoryURL()
expect(url).toNot(beNil())
expect(url?.lastPathComponent) == "Application Support"
storage = SEGFileStorage(folder: url!, crypto: nil)
}
it("creates folder if none exists") {
let tempDir = NSURL(fileURLWithPath: NSTemporaryDirectory())
let url = tempDir.URLByAppendingPathComponent(NSUUID().UUIDString)
expect(url.checkResourceIsReachableAndReturnError(nil)) == false
_ = SEGFileStorage(folder: url, crypto: nil)
var isDir: ObjCBool = false
let exists = NSFileManager.defaultManager().fileExistsAtPath(url.path!, isDirectory: &isDir)
expect(exists) == true
expect(Bool(isDir)) == true
}
it("persists and loads data") {
let dataIn = "segment".dataUsingEncoding(NSUTF8StringEncoding)!
storage.setData(dataIn, forKey: "mydata")
let dataOut = storage.dataForKey("mydata")
expect(dataOut) == dataIn
let strOut = String(data: dataOut!, encoding: NSUTF8StringEncoding)
expect(strOut) == "segment"
}
it("persists and loads string") {
let str = "san francisco"
storage.setString(str, forKey: "city")
expect(storage.stringForKey("city")) == str
storage.removeKey("city")
expect(storage.stringForKey("city")).to(beNil())
}
it("persists and loads array") {
let array = [
"san francisco",
"new york",
"tallinn",
]
storage.setArray(array, forKey: "cities")
expect(storage.arrayForKey("cities") as? Array<String>) == array
storage.removeKey("cities")
expect(storage.arrayForKey("cities")).to(beNil())
}
it("persists and loads dictionary") {
let dict = [
"san francisco": "tech",
"new york": "finance",
"paris": "fashion",
]
storage.setDictionary(dict, forKey: "cityMap")
expect(storage.dictionaryForKey("cityMap") as? Dictionary<String, String>) == dict
storage.removeKey("cityMap")
expect(storage.dictionaryForKey("cityMap")).to(beNil())
}
it("saves file to disk and removes from disk") {
let key = "input.txt"
let url = storage.urlForKey(key)
expect(url.checkResourceIsReachableAndReturnError(nil)) == false
storage.setString("sloth", forKey: key)
expect(url.checkResourceIsReachableAndReturnError(nil)) == true
storage.removeKey(key)
expect(url.checkResourceIsReachableAndReturnError(nil)) == false
}
it("should be binary compatible with old SDKs") {
let key = "traits.plist"
let dictIn = [
"san francisco": "tech",
"new york": "finance",
"paris": "fashion",
]
(dictIn as NSDictionary).writeToURL(storage.urlForKey(key), atomically: true)
let dictOut = storage.dictionaryForKey(key)
expect(dictOut as? [String: String]) == dictIn
}
it("should work with crypto") {
let url = SEGFileStorage.applicationSupportDirectoryURL()
let crypto = SEGAES256Crypto(password: "thetrees")
let s = SEGFileStorage(folder: url!, crypto: crypto)
let dict = [
"san francisco": "tech",
"new york": "finance",
"paris": "fashion",
]
s.setDictionary(dict, forKey: "cityMap")
expect(s.dictionaryForKey("cityMap") as? Dictionary<String, String>) == dict
s.removeKey("cityMap")
expect(s.dictionaryForKey("cityMap")).to(beNil())
}
afterEach {
storage.resetAll()
}
}
}
|
5698080d03fbc544dd9dbb8159836b1e
| 30.430894 | 98 | 0.622866 | false | false | false | false |
chuhlomin/football
|
refs/heads/master
|
football/Game.swift
|
mit
|
1
|
//
// Game.swift
// football
//
// Created by Konstantin Chukhlomin on 14/02/15.
// Copyright (c) 2015 Konstantin Chukhlomin. All rights reserved.
//
import Foundation
class Game
{
let PLAYER_ALICE = 1
let PLAYER_BOB = 2
var isRun: Bool
var board: Board
var lastDot: (Int, Int)
var currentPlayer: Int
var possibleMoves: [(Int, Int)] = []
init(board: Board) {
self.board = board
currentPlayer = PLAYER_ALICE
lastDot = board.getMiddleDotIndex()
board.board[lastDot.0][lastDot.1] = currentPlayer
self.isRun = false
possibleMoves = getPossibleMoves()
}
func start() {
isRun = true
}
func stop() {
isRun = false
}
func makeMove(location: (Int, Int)) -> Bool {
if !isRun {
return false
}
let filtered = possibleMoves.filter { self.board.compareTuples($0, tupleTwo: location)}
if (filtered.count > 0) {
board.addLine(lastDot, locationTo: location, player: currentPlayer)
board.board[location.0][location.1] = currentPlayer
lastDot = location
possibleMoves = getPossibleMoves()
return true
}
return false
}
func isMovePossible(pointFrom: (Int, Int), pointTo: (Int, Int)) -> Bool {
if (destinationIsReachable(pointTo) == false) {
return false
}
if (moveHasCorrectLenght(pointFrom, pointTo: pointTo) == false) {
return false
}
if (isLineExist(pointFrom, pointTo: pointTo) == true) {
return false
}
return true
}
func moveHasCorrectLenght(pointFrom: (Int, Int), pointTo: (Int, Int)) -> Bool {
if abs(pointFrom.0 - pointTo.0) > 1 {
return false
}
if abs(pointFrom.1 - pointTo.1) > 1 {
return false
}
if (pointFrom.0 - pointTo.0 == 0 &&
pointFrom.1 - pointTo.1 == 0) {
return false
}
return true
}
func isLineExist(pointFrom: (Int, Int), pointTo: (Int, Int)) -> Bool {
if let line = board.searchLine(pointFrom, pointTo: pointTo) {
return true
}
return false
}
func getPossibleMoves() -> [(Int, Int)] {
var result: [(Int, Int)] = []
for dX in -1...1 {
for dY in -1...1 {
if dX == 0 && dY == 0 {
continue
}
let nextDot = (lastDot.0 + dX, lastDot.1 + dY)
if (isMovePossible(lastDot, pointTo: nextDot) == true) {
result.append(nextDot)
if (dX > 0 && dY > 0) {
print("↗︎")
}
if (dX > 0 && dY < 0) {
print("↘︎")
}
if (dX > 0 && dY == 0) {
print("→")
}
if (dX == 0 && dY > 0) {
print("↑")
}
if (dX == 0 && dY < 0) {
print("↓")
}
if (dX < 0 && dY > 0) {
print("↖︎")
}
if (dX < 0 && dY < 0) {
print("↙︎")
}
if (dX < 0 && dY == 0) {
print("←")
}
}
}
}
println("")
return result
}
func destinationIsReachable(destination: (Int, Int)) -> Bool {
if (board.getDot(destination) == board.UNREACHABLE) {
return false
}
return true
}
func isMoveOver(dot: Int) -> Bool {
if (dot == board.EMPTY ||
dot == board.GOAL_ALICE ||
dot == board.GOAL_BOB) {
return true
}
return false
}
func getWinner(dot: Int) -> Int? {
if dot == board.GOAL_ALICE {
return PLAYER_BOB
}
if dot == board.GOAL_BOB {
return PLAYER_ALICE
}
return nil
}
func switchPlayer() -> Int {
if currentPlayer == PLAYER_ALICE {
currentPlayer = PLAYER_BOB
} else {
currentPlayer = PLAYER_ALICE
}
return currentPlayer
}
func restart() -> Void {
currentPlayer = PLAYER_ALICE
lastDot = board.getMiddleDotIndex()
board.board[lastDot.0][lastDot.1] = currentPlayer
possibleMoves = getPossibleMoves()
self.isRun = true
}
}
|
20d7535ecae2574229800c8ef6a8e0b3
| 24.952381 | 95 | 0.429241 | false | false | false | false |
prolificinteractive/Yoshi
|
refs/heads/master
|
Yoshi/Yoshi/Menus/YoshiDateSelectorMenu/YoshiDateSelectorMenuCellDataSource.swift
|
mit
|
1
|
//
// YoshiDateSelectorMenuCellDataSource.swift
// Yoshi
//
// Created by Kanglei Fang on 24/02/2017.
// Copyright © 2017 Prolific Interactive. All rights reserved.
//
/// Cell data source defining the layout for YoshiDateSelectorMenu's cell
struct YoshiDateSelectorMenuCellDataSource: YoshiReusableCellDataSource {
private let title: String
private let date: Date
private var dateFormatter: DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .short
return dateFormatter
}
/// Intialize the YoshiDateSelectorMenuCellDataSource instance
///
/// - Parameters:
/// - title: Main title for the cell
/// - date: Selected Date
init(title: String, date: Date) {
self.title = title
self.date = date
}
func cellFor(tableView: UITableView) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: YoshiDateSelectorMenuCellDataSource.reuseIdentifier) ??
UITableViewCell(style: .subtitle, reuseIdentifier: YoshiDateSelectorMenuCellDataSource.reuseIdentifier)
cell.textLabel?.text = title
cell.detailTextLabel?.text = dateFormatter.string(from: date)
cell.accessoryType = .disclosureIndicator
return cell
}
}
|
f6d5630905984a3570dc166ab40ab6cc
| 28.955556 | 120 | 0.697329 | false | false | false | false |
wayfair/brickkit-ios
|
refs/heads/master
|
Tests/Behaviors/OffsetLayoutBehaviorTests.swift
|
apache-2.0
|
1
|
//
// OffsetLayoutBehaviorTests.swift
// BrickKit
//
// Created by Justin Shiiba on 6/8/16.
// Copyright © 2016 Wayfair LLC. All rights reserved.
//
import XCTest
@testable import BrickKit
class OffsetLayoutBehaviorTests: BrickFlowLayoutBaseTests {
var behavior:OffsetLayoutBehavior!
override func setUp() {
super.setUp()
layout.zIndexBehavior = .bottomUp
}
func testEmptyCollectionView() {
behavior = OffsetLayoutBehavior(dataSource: FixedOffsetLayoutBehaviorDataSource(originOffset: CGSize(width: 20, height: -40), sizeOffset: nil))
self.layout.behaviors.insert(behavior)
setDataSources(SectionsCollectionViewDataSource(sections: []), brickLayoutDataSource: FixedBrickLayoutDataSource(widthRatio: 1, height: 300))
XCTAssertFalse(behavior.hasInvalidatableAttributes())
let attributes = layout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0))
XCTAssertNil(attributes?.frame)
}
func testOriginOffset() {
let fixedOffsetLayout = FixedOffsetLayoutBehaviorDataSource(originOffset: CGSize(width: 20, height: -40), sizeOffset: nil)
behavior = OffsetLayoutBehavior(dataSource: fixedOffsetLayout)
self.layout.behaviors.insert(behavior)
setDataSources(SectionsCollectionViewDataSource(sections: [1]), brickLayoutDataSource: FixedBrickLayoutDataSource(widthRatio: 1, height: 300))
let attributes = layout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0))
XCTAssertEqual(attributes?.frame, CGRect(x: 20, y: -40, width: 320, height: 300))
}
func testSizeOffset() {
let fixedOffsetLayout = FixedOffsetLayoutBehaviorDataSource(originOffset: nil, sizeOffset: CGSize(width: -40, height: 20))
behavior = OffsetLayoutBehavior(dataSource: fixedOffsetLayout)
self.layout.behaviors.insert(behavior)
setDataSources(SectionsCollectionViewDataSource(sections: [1]), brickLayoutDataSource: FixedBrickLayoutDataSource(widthRatio: 1, height: 300))
let attributes = layout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0))
XCTAssertEqual(attributes?.frame, CGRect(x: 0, y: 0, width: 280, height: 320))
}
func testOriginAndSizeOffset() {
let fixedOffsetLayoutBehavior = FixedOffsetLayoutBehaviorDataSource(originOffset: CGSize(width: 20, height: -40), sizeOffset: CGSize(width: -40, height: 20))
behavior = OffsetLayoutBehavior(dataSource: fixedOffsetLayoutBehavior)
self.layout.behaviors.insert(behavior)
setDataSources(SectionsCollectionViewDataSource(sections: [1]), brickLayoutDataSource: FixedBrickLayoutDataSource(widthRatio: 1, height: 300))
let attributes = layout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0))
XCTAssertEqual(attributes?.frame, CGRect(x: 20, y: -40, width: 280, height: 320))
}
func testOffsetAfterScroll() {
let fixedOffsetLayout = FixedOffsetLayoutBehaviorDataSource(originOffset: CGSize(width: 20, height: -40), sizeOffset: CGSize(width: -40, height: 20))
behavior = OffsetLayoutBehavior(dataSource: fixedOffsetLayout)
self.layout.behaviors.insert(behavior)
setDataSources(SectionsCollectionViewDataSource(sections: [1]), brickLayoutDataSource: FixedBrickLayoutDataSource(widthRatio: 1, height: 300))
let attributes = layout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0))
XCTAssertEqual(attributes?.frame, CGRect(x: 20, y: -40, width: 280, height: 320))
layout.collectionView?.contentOffset.y = 60
XCTAssertTrue(behavior.hasInvalidatableAttributes())
layout.invalidateLayout(with: BrickLayoutInvalidationContext(type: .scrolling))
XCTAssertEqual(attributes?.frame, CGRect(x: 20, y: -40, width: 280, height: 320))
}
}
|
0e4f251bd2d6b3dd87eaf5b428eb7241
| 50.106667 | 165 | 0.733107 | false | true | false | false |
RocketChat/Rocket.Chat.iOS
|
refs/heads/develop
|
Rocket.Chat/Managers/Model/CustomEmojiManager.swift
|
mit
|
1
|
//
// CustomEmojiManager.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 11/6/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
import RealmSwift
struct CustomEmojiManager {
static func sync(realm: Realm? = Realm.current) {
CustomEmoji.cachedEmojis = nil
API.current(realm: realm)?.fetch(CustomEmojiRequest()) { response in
switch response {
case .resource(let resource):
guard resource.success else {
return Log.debug(resource.errorMessage)
}
realm?.execute({ realm in
realm.delete(realm.objects(CustomEmoji.self))
let emoji = List<CustomEmoji>()
resource.customEmoji.forEach({ customEmoji in
let realmCustomEmoji = realm.create(CustomEmoji.self, value: customEmoji, update: true)
emoji.append(realmCustomEmoji)
})
realm.add(emoji, update: true)
})
case .error(let error):
switch error {
case .version:
// For Rocket.Chat < 0.75.0
oldSync(realm: realm)
default:
break
}
}
}
}
private static func oldSync(realm: Realm? = Realm.current) {
CustomEmoji.cachedEmojis = nil
API.current(realm: realm)?.fetch(CustomEmojiRequestOld()) { response in
if case let .resource(resource) = response {
guard resource.success else {
return Log.debug(resource.errorMessage)
}
realm?.execute({ realm in
realm.delete(realm.objects(CustomEmoji.self))
let emoji = List<CustomEmoji>()
resource.customEmoji.forEach({ customEmoji in
let realmCustomEmoji = realm.create(CustomEmoji.self, value: customEmoji, update: true)
emoji.append(realmCustomEmoji)
})
realm.add(emoji, update: true)
})
}
}
}
}
|
f042908af9f3cd7dda496881e9dbcc7f
| 31.142857 | 111 | 0.512444 | false | false | false | false |
swift102016team5/mefocus
|
refs/heads/master
|
MeFocus/MeFocus/SessionPickMonitorViewController.swift
|
mit
|
1
|
//
// SessionPickMonitorViewController.swift
// MeFocus
//
// Created by Hao on 11/28/16.
// Copyright © 2016 Group5. All rights reserved.
//
import UIKit
class SessionPickMonitorViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet var tableView: UITableView!
var users:[User] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
Api.shared?.fetch(
name: "",
completion: { (users:[User]) in
self.users = users
self.tableView.reloadData()
})
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if let identifier = segue.identifier {
if identifier == "Choose" {
let user = users[(tableView.indexPathForSelectedRow?.row)!]
let navigation = segue.destination as! UINavigationController
let start = navigation.topViewController as! SessionStartViewController
start.coach = user
}
}
}
}
extension SessionPickMonitorViewController:UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MonitorTableViewCell") as! MonitorTableViewCell
let user = users[indexPath.row]
cell.user = user
return cell
}
}
|
2c66c98286c273ca1891b49a68f42e07
| 27.987342 | 113 | 0.610044 | false | false | false | false |
vchuo/Photoasis
|
refs/heads/master
|
Photoasis/Classes/Views/ViewControllers/POHomeViewController.swift
|
mit
|
1
|
//
// POHomeViewController.swift
// ホームビューコントローラ。
//
// Created by Vernon Chuo Chian Khye on 2017/02/25.
// Copyright © 2017 Vernon Chuo Chian Khye. All rights reserved.
//
import UIKit
import RxSwift
import ChuoUtil
import Kingfisher
class POHomeViewController: UIViewController {
// MARK: - Public Properties
// MARK: - Private Properties
private let homeViewModel = POHomeViewModel()
private let disposeBag = DisposeBag()
private var photosTableView = POHomePhotosTableView()
private let homeNavigationButton = POHomeNavigationButtonView()
private let savedPhotosNavigationButtonView = POSavedPhotosNavigationButtonView()
private let loadingIndicator = UIActivityIndicatorView()
// MARK: - Lifecycle Events
override func viewDidLoad() {
super.viewDidLoad()
// フォトテーブルビュー
photosTableView.setup()
view.addSubview(photosTableView)
// ナビボタン
homeNavigationButton.buttonAction = {
if self.homeViewModel.numberOfDisplayedPhotos() != 0 {
self.photosTableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: .Top, animated: true)
}
}
savedPhotosNavigationButtonView.backgroundColor = POColors.NavigationButtonUnselectedStateBackgroundColor
savedPhotosNavigationButtonView.buttonAction = {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let vc = storyboard.instantiateViewControllerWithIdentifier("POSavedPhotosViewController") as? POSavedPhotosViewController {
self.presentViewController(vc, animated: false, completion: nil)
}
}
view.addSubview(homeNavigationButton)
view.addSubview(savedPhotosNavigationButtonView)
// ローディングインジケータ
loadingIndicator.activityIndicatorViewStyle = .WhiteLarge
loadingIndicator.sizeToFit()
loadingIndicator.color = POColors.HomeViewLoadingIndicatorColor
loadingIndicator.center = CUHelper.centerPointOf(view)
loadingIndicator.hidden = true
view.addSubview(loadingIndicator)
subscribeToObservables()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
loadingIndicator.startAnimating()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
photosTableView.delegate = self
photosTableView.dataSource = self
homeViewModel.prepareDataForViewDisplay()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
ImageCache.defaultCache.clearMemoryCache()
}
// MARK: - Private Functions
/**
オブザーバブルにサブスクライブする。
*/
private func subscribeToObservables() {
// コンテンツをリロードするかを監視
homeViewModel.shouldReloadContent.asObservable().subscribeNext({ [unowned self](shouldReload) in
self.loadingIndicator.stopAnimating()
if let indexPaths = self.photosTableView.indexPathsForVisibleRows {
self.photosTableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: .Fade)
}
}).addDisposableTo(disposeBag)
// 新しいフォトが保存されたかを監視
homeViewModel.newPhotoSaved.asObservable()
.subscribeNext({ [unowned self](photoItem) in
self.executeAnimationForNewPhotoSaved(photoItem)
}).addDisposableTo(disposeBag)
// フォトが未保存されたかを監視
homeViewModel.photoUnsaved.asObservable()
.subscribeNext({ [unowned self](photoItem) in
self.executeAnimationForPhotoUnsaved(photoItem)
}).addDisposableTo(disposeBag)
}
/**
新しいフォトが保存されたアニメーションを実行。
- parameter photoItem: 新しい保存されたフォト
*/
private func executeAnimationForNewPhotoSaved(photoItem: POPhotoDisplayItem) {
self.photosTableView.visibleCells.flatMap{ $0 as? POHomeTableViewCell }.forEach { cell in
if cell.recycledCellData.imageURL == photoItem.photoURL {
// フォト保存する時にアニメーションするイメージビュー
let animatedImageView = UIImageView()
if let image = cell.photo.image {
animatedImageView.image = image
} else {
animatedImageView.backgroundColor = POColors.NoImageBackgroundColor
}
animatedImageView.bounds.size.width = POConstants.HomeTableViewCellPhotoWidth
animatedImageView.layer.anchorPoint = CGPointZero
animatedImageView.layer.cornerRadius = POConstants.HomeTableViewCellPhotoCornerRadius
animatedImageView.clipsToBounds = true
animatedImageView.bounds.size = cell.photo.bounds.size
animatedImageView.frame.origin = cell.convertPoint(cell.photo.frame.origin, toView: self.view)
animatedImageView.userInteractionEnabled = false
self.view.addSubview(animatedImageView)
CUHelper.animateKeyframes(
POConstants.HomeViewPhotoSavedAnimationDuration,
options: .CalculationModeCubic,
animations: {
UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 1) {
animatedImageView.center = self.savedPhotosNavigationButtonView.center
}
UIView.addKeyframeWithRelativeStartTime(0.2, relativeDuration: 0.7) {
animatedImageView.transform = CGAffineTransformMakeScale(0.1, 0.1)
}
UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.4) {
animatedImageView.alpha = 0.4
}
UIView.addKeyframeWithRelativeStartTime(0.9, relativeDuration: 0.1) {
animatedImageView.transform = CGAffineTransformMakeScale(0.01, 0.01)
animatedImageView.alpha = 0
}
}
) { _ in
self.savedPhotosNavigationButtonView.executePhotoSavedAnimation()
animatedImageView.removeFromSuperview()
}
}
}
self.homeViewModel.updateNewPhotoSaved(nil)
}
/**
フォトが未保存されたアニメーションを実行。
- parameter photoItem: 未保存されたフォト
*/
private func executeAnimationForPhotoUnsaved(photoItem: POPhotoDisplayItem) {
self.photosTableView.visibleCells.flatMap{ $0 as? POHomeTableViewCell }.forEach { cell in
if cell.recycledCellData.imageURL == photoItem.photoURL {
// フォトが未保存する時にアニメーションするイメージビュー
let animatedImageView = UIImageView()
if let image = cell.photo.image {
animatedImageView.image = image
} else {
animatedImageView.backgroundColor = POColors.NoImageBackgroundColor
}
animatedImageView.bounds.size.width = POConstants.HomeTableViewCellPhotoWidth
animatedImageView.layer.anchorPoint = CGPointZero
animatedImageView.layer.cornerRadius = POConstants.HomeTableViewCellPhotoCornerRadius
animatedImageView.clipsToBounds = true
animatedImageView.bounds.size = cell.photo.bounds.size
animatedImageView.center = self.savedPhotosNavigationButtonView.center
animatedImageView.transform = CGAffineTransformMakeScale(0.01, 0.01)
animatedImageView.userInteractionEnabled = false
let photoViewOrigin = cell.convertPoint(cell.photo.frame.origin, toView: self.view)
self.view.addSubview(animatedImageView)
CUHelper.animateKeyframes(
POConstants.HomeViewPhotoUnsavedAnimationDuration,
animations: {
UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 1.0) {
animatedImageView.frame.origin = photoViewOrigin
animatedImageView.transform = CGAffineTransformMakeScale(1, 1)
}
UIView.addKeyframeWithRelativeStartTime(0.85, relativeDuration: 0.15) {
animatedImageView.alpha = 0
}
}
) { _ in animatedImageView.removeFromSuperview() }
}
}
self.homeViewModel.updatePhotoUnsaved(nil)
}
}
extension POHomeViewController: UITableViewDelegate {}
extension POHomeViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return homeViewModel.numberOfDisplayedPhotos()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableView.dequeueReusableCellWithIdentifier(POStrings.HomeTableViewCellIdentifier) as! POHomeTableViewCell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
guard let cell = cell as? POHomeTableViewCell else {
return
}
cell.photo.image = nil
cell.itemIndex = indexPath.row
cell.updateSerialOperationQueueWith {
guard let photo = self.homeViewModel.getDisplayedPhotoAt(indexPath.row) else {
return
}
let photoURL = photo.photoURL,
photoAspectRatio = photo.photoAspectRatio,
isSaved = photo.isSaved
cell.recycledCellData.imageURL = photoURL
cell.photo.photoAuthorName = photo.authorName
CUHelper.executeOnBackgroundThread {
let photoHeight = POConstants.HomeTableViewCellPhotoWidth / CGFloat(photoAspectRatio),
cellHeight = photoHeight + POConstants.HomeTableViewCellVerticalContentInset * 2
CUImageManager.loadRecycledCellImageFrom(
photoURL,
imageView: cell.photo,
recycledCellData: cell.recycledCellData,
noImageBackgroundColor: POColors.NoImageBackgroundColor,
fadeIn: true
)
CUHelper.executeOnMainThread {
cell.photo.updateSize(height: photoHeight)
cell.bounds.size.height = cellHeight
cell.toggleSaveButton.defaultBackgroundColor = isSaved ?
POColors.HomeTableViewCellToggleSaveButtonSavedStateDefaultBackgroundColor :
POColors.HomeTableViewCellToggleSaveButtonNotSavedStateDefaultBackgroundColor
cell.toggleSaveButton.title = isSaved ?
POStrings.HomeTableViewCellToggleSaveButtonSavedText :
POStrings.HomeTableViewCellToggleSaveButtonSaveText
}
}
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return getHeightForRow(indexPath.row)
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return getHeightForRow(indexPath.row)
}
/**
行の高さを返す。
- parameter row: 行インデックス
- returns: 行の高さ
*/
private func getHeightForRow(row: Int) -> CGFloat {
if let photo = homeViewModel.getDisplayedPhotoAt(row) {
return POConstants.HomeTableViewCellPhotoWidth / CGFloat(photo.photoAspectRatio)
+ POConstants.HomeTableViewCellVerticalContentInset * 2
}
return 0
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
headerView.bounds.size = POConstants.HomeTableViewHeaderViewSize
headerView.frame.origin = CGPointZero
headerView.userInteractionEnabled = false
return headerView
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return POConstants.HomeTableViewHeaderViewSize.height
}
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView()
footerView.bounds.size = POConstants.HomeTableViewFooterViewSize
footerView.frame.origin = CGPointZero
footerView.userInteractionEnabled = false
return footerView
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return POConstants.HomeTableViewFooterViewSize.height
}
}
|
869e6994cbc61561e00b92a98f740ea8
| 41.859477 | 139 | 0.632101 | false | false | false | false |
fnky/drawling-components
|
refs/heads/master
|
DrawlingComponents/ViewController.swift
|
gpl-2.0
|
1
|
//
// ViewController.swift
// DrawlingComponents
//
// Created by Christian Petersen
// Copyright (c) 2015 Reversebox. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var scroller = RBScrollView(frame: CGRectMake(0, 100, 640, 80))
var smallScroller: RBScrollView = RBScrollView(frame: CGRectMake(0, 200, 640, 80))
override func viewDidLoad() {
scroller.backgroundColor = UIColor.clearColor()
smallScroller.backgroundColor = UIColor.clearColor()
//scroller.contentSize = CGSizeMake(1136, 64)
for (var i = 0; i < 10; i++) {
// (current * (size + margin) + offset)
var avatar: RBAvatarView = RBAvatarView(frame: CGRectMake(CGFloat(i * 48), 16, 48, 48),
image: UIImage(named: "avatarStd")!)
//(size + (size / 2)) + offset
var avatarSmall: RBAvatarView = RBAvatarView(frame: CGRectMake(CGFloat(i * 32), 16, 32, 32),
image: UIImage(named: "avatarStd")!)
let rotation: CGFloat = ( i % 2 == 0) ? 0.00 : -0.00
avatar.rotation = rotation
avatarSmall.rotation = rotation
scroller.addSubview(avatar)
smallScroller.addSubview(avatarSmall)
}
self.view.addSubview(scroller)
self.view.addSubview(smallScroller)
super.viewDidLoad()
}
override func viewDidLayoutSubviews() {
}
}
|
2c8d56dafe24dda5040b2bc4e825aa32
| 25.538462 | 98 | 0.636957 | false | false | false | false |
qinting513/WeiBo-Swift
|
refs/heads/master
|
WeiBo_V3/WeiBo/Classes/View[视图跟控制器]/Main/OAuth/WBOAuthViewController.swift
|
apache-2.0
|
1
|
//
// WBOAuthViewController.swift
// WeiBo
//
// Created by Qinting on 16/9/8.
// Copyright © 2016年 Qinting. All rights reserved.
//
import UIKit
import SVProgressHUD
//通过webView登录
class WBOAuthViewController: UIViewController {
private lazy var webView = UIWebView()
override func loadView() {
view = webView
webView.delegate = self
webView.scrollView.isScrollEnabled = false
view.backgroundColor = UIColor.white()
title = "登录新浪微博"
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", normalColor:UIColor.black(), highlightedColor: UIColor.orange(), target: self, action: #selector(close))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .plain, target: self, action: #selector(autoFill))
}
override func viewDidLoad() {
super.viewDidLoad()
let urlStr = "https://api.weibo.com/oauth2/authorize?redirect_uri=\(WBRedirectURI)&client_id=\(WBAppKey)"
guard let url = URL.init(string: urlStr) else {
return
}
webView.loadRequest(URLRequest.init(url: url))
}
@objc private func close(){
SVProgressHUD.dismiss()
dismiss(animated: true, completion: nil)
}
/// 自动填充 - webView的注入 直接通过 js 修改‘本地浏览器中的缓存’的页面内容
/// 点击登录 执行 submit() 将本地数据提交给服务器 注意啊 有分号区别
//js 语句一定要写对
@objc private func autoFill() {
let js = "document.getElementById('userId').value = '[email protected]' ; " + "document.getElementById('passwd').value = 'Chunwoaini7758'; "
webView.stringByEvaluatingJavaScript(from: js)
}
}
extension WBOAuthViewController : UIWebViewDelegate {
/// 是否加载request
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//确认思路
//1.如果请求地址包含 http://baidu.com 不加载页面 / 否则加载页面
print("加载请求---\(request.url?.absoluteString)")
if request.url?.absoluteString?.hasPrefix(WBRedirectURI) == false {
return true
}
//2. 如果回调地址的 '查询' 字符串中查找 'code=' query 就是URL中 ‘?’后面的所有部分
if request.url?.query?.hasPrefix("code=" ) == false{
print("取消授权")
close()
return false
}
//3.如果有 则授权成功,如果没有授权失败
//来到此处 url中肯定包含 ‘ code =’
let str = (request.url?.absoluteString)! as NSString
var code : String?
if str.length > 0 {
let ra = str.range(of: "code=")
code = str.substring(from: (ra.location + ra.length) ?? 0 )
}
// let code = request.url?.absoluteString?.substring(from:"code=".endIndex) ?? ""
//4.用授权码获取accessToken
print("授权码:\(code)")
guard code != "" else {
print("授权码为空:\(code)")
close()
return false
}
//能够到这一步 说明code是非空的字符串
WBNetworkManager.shared.loadAccessToken(code: code!) { (isSuccess) in
if !isSuccess {
SVProgressHUD.showInfo(withStatus: "网络请求失败")
}else{
//登录成功,通过通知跳转界面,关闭窗口
NotificationCenter.default().post(name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification), object: nil)
self.close()
return
}
}
return false
}
func webViewDidStartLoad(_ webView: UIWebView) {
SVProgressHUD.show()
}
func webViewDidFinishLoad(_ webView: UIWebView) {
SVProgressHUD.dismiss()
}
func webView(_ webView: UIWebView, didFailLoadWithError error: NSError?) {
SVProgressHUD.dismiss()
}
}
|
517ce85887d877c1772f9574ce4a07c2
| 31.903509 | 176 | 0.589709 | false | false | false | false |
intel-isl/MiDaS
|
refs/heads/master
|
mobile/ios/Midas/ViewControllers/ViewController.swift
|
mit
|
1
|
// Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import AVFoundation
import UIKit
import os
public struct PixelData {
var a: UInt8
var r: UInt8
var g: UInt8
var b: UInt8
}
extension UIImage {
convenience init?(pixels: [PixelData], width: Int, height: Int) {
guard width > 0 && height > 0, pixels.count == width * height else { return nil }
var data = pixels
guard let providerRef = CGDataProvider(data: Data(bytes: &data, count: data.count * MemoryLayout<PixelData>.size) as CFData)
else { return nil }
guard let cgim = CGImage(
width: width,
height: height,
bitsPerComponent: 8,
bitsPerPixel: 32,
bytesPerRow: width * MemoryLayout<PixelData>.size,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue),
provider: providerRef,
decode: nil,
shouldInterpolate: false,
intent: .defaultIntent)
else { return nil }
self.init(cgImage: cgim)
}
}
class ViewController: UIViewController {
// MARK: Storyboards Connections
@IBOutlet weak var previewView: PreviewView!
//@IBOutlet weak var overlayView: OverlayView!
@IBOutlet weak var overlayView: UIImageView!
private var imageView : UIImageView = UIImageView(frame:CGRect(x:0, y:0, width:400, height:400))
private var imageViewInitialized: Bool = false
@IBOutlet weak var resumeButton: UIButton!
@IBOutlet weak var cameraUnavailableLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var threadCountLabel: UILabel!
@IBOutlet weak var threadCountStepper: UIStepper!
@IBOutlet weak var delegatesControl: UISegmentedControl!
// MARK: ModelDataHandler traits
var threadCount: Int = Constants.defaultThreadCount
var delegate: Delegates = Constants.defaultDelegate
// MARK: Result Variables
// Inferenced data to render.
private var inferencedData: InferencedData?
// Minimum score to render the result.
private let minimumScore: Float = 0.5
private var avg_latency: Double = 0.0
// Relative location of `overlayView` to `previewView`.
private var overlayViewFrame: CGRect?
private var previewViewFrame: CGRect?
// MARK: Controllers that manage functionality
// Handles all the camera related functionality
private lazy var cameraCapture = CameraFeedManager(previewView: previewView)
// Handles all data preprocessing and makes calls to run inference.
private var modelDataHandler: ModelDataHandler?
// MARK: View Handling Methods
override func viewDidLoad() {
super.viewDidLoad()
do {
modelDataHandler = try ModelDataHandler()
} catch let error {
fatalError(error.localizedDescription)
}
cameraCapture.delegate = self
tableView.delegate = self
tableView.dataSource = self
// MARK: UI Initialization
// Setup thread count stepper with white color.
// https://forums.developer.apple.com/thread/121495
threadCountStepper.setDecrementImage(
threadCountStepper.decrementImage(for: .normal), for: .normal)
threadCountStepper.setIncrementImage(
threadCountStepper.incrementImage(for: .normal), for: .normal)
// Setup initial stepper value and its label.
threadCountStepper.value = Double(Constants.defaultThreadCount)
threadCountLabel.text = Constants.defaultThreadCount.description
// Setup segmented controller's color.
delegatesControl.setTitleTextAttributes(
[NSAttributedString.Key.foregroundColor: UIColor.lightGray],
for: .normal)
delegatesControl.setTitleTextAttributes(
[NSAttributedString.Key.foregroundColor: UIColor.black],
for: .selected)
// Remove existing segments to initialize it with `Delegates` entries.
delegatesControl.removeAllSegments()
Delegates.allCases.forEach { delegate in
delegatesControl.insertSegment(
withTitle: delegate.description,
at: delegate.rawValue,
animated: false)
}
delegatesControl.selectedSegmentIndex = 0
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
cameraCapture.checkCameraConfigurationAndStartSession()
}
override func viewWillDisappear(_ animated: Bool) {
cameraCapture.stopSession()
}
override func viewDidLayoutSubviews() {
overlayViewFrame = overlayView.frame
previewViewFrame = previewView.frame
}
// MARK: Button Actions
@IBAction func didChangeThreadCount(_ sender: UIStepper) {
let changedCount = Int(sender.value)
if threadCountLabel.text == changedCount.description {
return
}
do {
modelDataHandler = try ModelDataHandler(threadCount: changedCount, delegate: delegate)
} catch let error {
fatalError(error.localizedDescription)
}
threadCount = changedCount
threadCountLabel.text = changedCount.description
os_log("Thread count is changed to: %d", threadCount)
}
@IBAction func didChangeDelegate(_ sender: UISegmentedControl) {
guard let changedDelegate = Delegates(rawValue: delegatesControl.selectedSegmentIndex) else {
fatalError("Unexpected value from delegates segemented controller.")
}
do {
modelDataHandler = try ModelDataHandler(threadCount: threadCount, delegate: changedDelegate)
} catch let error {
fatalError(error.localizedDescription)
}
delegate = changedDelegate
os_log("Delegate is changed to: %s", delegate.description)
}
@IBAction func didTapResumeButton(_ sender: Any) {
cameraCapture.resumeInterruptedSession { complete in
if complete {
self.resumeButton.isHidden = true
self.cameraUnavailableLabel.isHidden = true
} else {
self.presentUnableToResumeSessionAlert()
}
}
}
func presentUnableToResumeSessionAlert() {
let alert = UIAlertController(
title: "Unable to Resume Session",
message: "There was an error while attempting to resume session.",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
}
}
// MARK: - CameraFeedManagerDelegate Methods
extension ViewController: CameraFeedManagerDelegate {
func cameraFeedManager(_ manager: CameraFeedManager, didOutput pixelBuffer: CVPixelBuffer) {
runModel(on: pixelBuffer)
}
// MARK: Session Handling Alerts
func cameraFeedManagerDidEncounterSessionRunTimeError(_ manager: CameraFeedManager) {
// Handles session run time error by updating the UI and providing a button if session can be
// manually resumed.
self.resumeButton.isHidden = false
}
func cameraFeedManager(
_ manager: CameraFeedManager, sessionWasInterrupted canResumeManually: Bool
) {
// Updates the UI when session is interupted.
if canResumeManually {
self.resumeButton.isHidden = false
} else {
self.cameraUnavailableLabel.isHidden = false
}
}
func cameraFeedManagerDidEndSessionInterruption(_ manager: CameraFeedManager) {
// Updates UI once session interruption has ended.
self.cameraUnavailableLabel.isHidden = true
self.resumeButton.isHidden = true
}
func presentVideoConfigurationErrorAlert(_ manager: CameraFeedManager) {
let alertController = UIAlertController(
title: "Confirguration Failed", message: "Configuration of camera has failed.",
preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
func presentCameraPermissionsDeniedAlert(_ manager: CameraFeedManager) {
let alertController = UIAlertController(
title: "Camera Permissions Denied",
message:
"Camera permissions have been denied for this app. You can change this by going to Settings",
preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { action in
if let url = URL.init(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
alertController.addAction(cancelAction)
alertController.addAction(settingsAction)
present(alertController, animated: true, completion: nil)
}
@objc func runModel(on pixelBuffer: CVPixelBuffer) {
guard let overlayViewFrame = overlayViewFrame, let previewViewFrame = previewViewFrame
else {
return
}
// To put `overlayView` area as model input, transform `overlayViewFrame` following transform
// from `previewView` to `pixelBuffer`. `previewView` area is transformed to fit in
// `pixelBuffer`, because `pixelBuffer` as a camera output is resized to fill `previewView`.
// https://developer.apple.com/documentation/avfoundation/avlayervideogravity/1385607-resizeaspectfill
let modelInputRange = overlayViewFrame.applying(
previewViewFrame.size.transformKeepAspect(toFitIn: pixelBuffer.size))
// Run Midas model.
guard
let (result, width, height, times) = self.modelDataHandler?.runMidas(
on: pixelBuffer,
from: modelInputRange,
to: overlayViewFrame.size)
else {
os_log("Cannot get inference result.", type: .error)
return
}
if avg_latency == 0 {
avg_latency = times.inference
} else {
avg_latency = times.inference*0.1 + avg_latency*0.9
}
// Udpate `inferencedData` to render data in `tableView`.
inferencedData = InferencedData(score: Float(avg_latency), times: times)
//let height = 256
//let width = 256
let outputs = result
let outputs_size = width * height;
var multiplier : Float = 1.0;
let max_val : Float = outputs.max() ?? 0
let min_val : Float = outputs.min() ?? 0
if((max_val - min_val) > 0) {
multiplier = 255 / (max_val - min_val);
}
// Draw result.
DispatchQueue.main.async {
self.tableView.reloadData()
var pixels: [PixelData] = .init(repeating: .init(a: 255, r: 0, g: 0, b: 0), count: width * height)
for i in pixels.indices {
//if(i < 1000)
//{
let val = UInt8((outputs[i] - min_val) * multiplier)
pixels[i].r = val
pixels[i].g = val
pixels[i].b = val
//}
}
/*
pixels[i].a = 255
pixels[i].r = .random(in: 0...255)
pixels[i].g = .random(in: 0...255)
pixels[i].b = .random(in: 0...255)
}
*/
DispatchQueue.main.async {
let image = UIImage(pixels: pixels, width: width, height: height)
self.imageView.image = image
if (self.imageViewInitialized == false) {
self.imageViewInitialized = true
self.overlayView.addSubview(self.imageView)
self.overlayView.setNeedsDisplay()
}
}
/*
let image = UIImage(pixels: pixels, width: width, height: height)
var imageView : UIImageView
imageView = UIImageView(frame:CGRect(x:0, y:0, width:400, height:400));
imageView.image = image
self.overlayView.addSubview(imageView)
self.overlayView.setNeedsDisplay()
*/
}
}
/*
func drawResult(of result: Result) {
self.overlayView.dots = result.dots
self.overlayView.lines = result.lines
self.overlayView.setNeedsDisplay()
}
func clearResult() {
self.overlayView.clear()
self.overlayView.setNeedsDisplay()
}
*/
}
// MARK: - TableViewDelegate, TableViewDataSource Methods
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return InferenceSections.allCases.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let section = InferenceSections(rawValue: section) else {
return 0
}
return section.subcaseCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "InfoCell") as! InfoCell
guard let section = InferenceSections(rawValue: indexPath.section) else {
return cell
}
guard let data = inferencedData else { return cell }
var fieldName: String
var info: String
switch section {
case .Score:
fieldName = section.description
info = String(format: "%.3f", data.score)
case .Time:
guard let row = ProcessingTimes(rawValue: indexPath.row) else {
return cell
}
var time: Double
switch row {
case .InferenceTime:
time = data.times.inference
}
fieldName = row.description
info = String(format: "%.2fms", time)
}
cell.fieldNameLabel.text = fieldName
cell.infoLabel.text = info
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let section = InferenceSections(rawValue: indexPath.section) else {
return 0
}
var height = Traits.normalCellHeight
if indexPath.row == section.subcaseCount - 1 {
height = Traits.separatorCellHeight + Traits.bottomSpacing
}
return height
}
}
// MARK: - Private enums
/// UI coinstraint values
fileprivate enum Traits {
static let normalCellHeight: CGFloat = 35.0
static let separatorCellHeight: CGFloat = 25.0
static let bottomSpacing: CGFloat = 30.0
}
fileprivate struct InferencedData {
var score: Float
var times: Times
}
/// Type of sections in Info Cell
fileprivate enum InferenceSections: Int, CaseIterable {
case Score
case Time
var description: String {
switch self {
case .Score:
return "Average"
case .Time:
return "Processing Time"
}
}
var subcaseCount: Int {
switch self {
case .Score:
return 1
case .Time:
return ProcessingTimes.allCases.count
}
}
}
/// Type of processing times in Time section in Info Cell
fileprivate enum ProcessingTimes: Int, CaseIterable {
case InferenceTime
var description: String {
switch self {
case .InferenceTime:
return "Inference Time"
}
}
}
|
3d04e0139f653f647ba5bed065819ad0
| 30.102249 | 132 | 0.679598 | false | false | false | false |
richardpiazza/XCServerCoreData
|
refs/heads/master
|
Tests/CoreDataVersion.swift
|
mit
|
1
|
import Foundation
import CoreData
import XCServerCoreData
class CoreDataVersion {
public static var v_1_2_0 = CoreDataVersion(with: "XCServerCoreData_1.2.0")
public static var v_1_2_0_empty = CoreDataVersion(with: "XCServerCoreData_1.2.0_empty")
public static var v_2_0_0_empty = CoreDataVersion(with: "XCServerCoreData_2.0.0_empty")
public static var v_2_0_1 = CoreDataVersion(with: "XCServerCoreData_2.0.1")
public var resource: String
public init(with resource: String) {
self.resource = resource
}
static var documentsDirectory: URL {
do {
return try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
} catch {
fatalError("Failed to find documents directory")
}
}
static var tempDirectory: URL {
return documentsDirectory.appendingPathComponent("temp")
}
static var baseResource: String = "XCServerCoreData"
static var documentsSQLite: URL {
return documentsDirectory.appendingPathComponent(baseResource).appendingPathExtension(CoreDataExtension.sqlite.rawValue)
}
static var documentsSHM: URL {
return documentsDirectory.appendingPathComponent(baseResource).appendingPathExtension(CoreDataExtension.shm.rawValue)
}
static var documentsWAL: URL {
return documentsDirectory.appendingPathComponent(baseResource).appendingPathExtension(CoreDataExtension.wal.rawValue)
}
static var tempSQLite: URL {
return tempDirectory.appendingPathComponent(baseResource).appendingPathExtension(CoreDataExtension.sqlite.rawValue)
}
static var tempSHM: URL {
return tempDirectory.appendingPathComponent(baseResource).appendingPathExtension(CoreDataExtension.shm.rawValue)
}
static var tempWAL: URL {
return tempDirectory.appendingPathComponent(baseResource).appendingPathExtension(CoreDataExtension.wal.rawValue)
}
static func overwriteSQL(withVersion version: CoreDataVersion) -> Bool {
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: tempDirectory.path) {
do {
print("Creating TEMP directory")
try fileManager.createDirectory(at: tempDirectory, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
return false
}
}
print("Clearing TEMP directory")
do {
if fileManager.fileExists(atPath: tempSQLite.path) {
try fileManager.removeItem(at: tempSQLite)
}
if fileManager.fileExists(atPath: tempSHM.path) {
try fileManager.removeItem(at: tempSHM)
}
if fileManager.fileExists(atPath: tempWAL.path) {
try fileManager.removeItem(at: tempWAL)
}
} catch {
print(error)
return false
}
let replacementOptions = FileManager.ItemReplacementOptions()
print("Copying/Overwriting SQLite File")
do {
try fileManager.copyItem(at: version.bundleSQLite!, to: tempSQLite)
try fileManager.replaceItem(at: documentsSQLite, withItemAt: tempSQLite, backupItemName: nil, options: replacementOptions, resultingItemURL: nil)
} catch {
print(error)
return false
}
if let url = version.bundleSHM {
print("Copying/Overwriting SHM File")
do {
try fileManager.copyItem(at: url, to: tempSHM)
try fileManager.replaceItem(at: documentsSHM, withItemAt: tempSHM, backupItemName: nil, options: replacementOptions, resultingItemURL: nil)
} catch {
print(error)
}
}
if let url = version.bundleWAL {
print("Copying/Overwriting WAL File")
do {
try fileManager.copyItem(at: url, to: tempWAL)
try fileManager.replaceItem(at: documentsWAL, withItemAt: tempWAL, backupItemName: nil, options: replacementOptions, resultingItemURL: nil)
} catch {
print(error)
}
}
return true
}
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
static var persistentContainer: NSPersistentContainer {
let fileManager = FileManager.default
var modelURL: URL
let bundle = Bundle(for: XCServerCoreData.self)
if let url = bundle.url(forResource: "XCServerCoreData", withExtension: "momd") {
modelURL = url
} else {
modelURL = URL(fileURLWithPath: fileManager.currentDirectoryPath).appendingPathComponent("Tests").appendingPathComponent("XCServerCoreData.momd")
}
guard fileManager.fileExists(atPath: modelURL.path) else {
fatalError("Failed to locate XCServerCoreData.momd\n\(modelURL.path)")
}
guard let model = NSManagedObjectModel(contentsOf: modelURL) else {
fatalError("Failed to load XCServerCoreData Model")
}
var storeURL: URL
do {
var searchPathDirectory: FileManager.SearchPathDirectory
#if os(tvOS)
searchPathDirectory = .cachesDirectory
#else
searchPathDirectory = .documentDirectory
#endif
storeURL = try FileManager.default.url(for: searchPathDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("XCServerCoreData.sqlite")
} catch {
print(error)
fatalError(error.localizedDescription)
}
let instance = NSPersistentContainer(name: "XCServerCoreData", managedObjectModel: model)
let description = NSPersistentStoreDescription(url: storeURL)
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
instance.persistentStoreDescriptions = [description]
instance.viewContext.automaticallyMergesChangesFromParent = true
return instance
}
}
enum CoreDataExtension: String {
case sqlite = "sqlite"
case shm = "sqlite-shm"
case wal = "sqlite-wal"
}
extension CoreDataVersion {
func url(for res: String, extension ext: CoreDataExtension) -> URL? {
let bundle = Bundle(for: CoreDataVersion.self)
if let url = bundle.url(forResource: res, withExtension: ext.rawValue) {
return url
}
let path = FileManager.default.currentDirectoryPath
let url = URL(fileURLWithPath: path).appendingPathComponent("Tests").appendingPathComponent(res).appendingPathExtension(ext.rawValue)
if !FileManager.default.fileExists(atPath: url.path) {
print("Unable to locate resource \(res).\(ext.rawValue)")
return nil
}
return url
}
var bundleSQLite: URL? {
return self.url(for: resource, extension: .sqlite)
}
var bundleSHM: URL? {
return self.url(for: resource, extension: .shm)
}
var bundleWAL: URL? {
return self.url(for: resource, extension: .wal)
}
}
|
e66a1f81389442bf976f7e37da6c9b13
| 36.659898 | 182 | 0.633509 | false | false | false | false |
BennyKJohnson/OpenCloudKit
|
refs/heads/master
|
Sources/Bridging.swift
|
mit
|
1
|
//
// Bridging.swift
// OpenCloudKit
//
// Created by Benjamin Johnson on 20/07/2016.
//
//
import Foundation
public protocol _OCKBridgable {
associatedtype ObjectType
func bridge() -> ObjectType
}
public protocol CKNumberValueType: CKRecordValue {}
extension CKNumberValueType where Self: _OCKBridgable, Self.ObjectType == NSNumber {
public var recordFieldDictionary: [String: Any] {
return ["value": self.bridge()]
}
}
extension String: _OCKBridgable {
public typealias ObjectType = NSString
public func bridge() -> NSString {
return NSString(string: self)
}
}
extension Int: _OCKBridgable {
public typealias ObjectType = NSNumber
public func bridge() -> NSNumber {
return NSNumber(value: self)
}
}
extension UInt: _OCKBridgable {
public typealias ObjectType = NSNumber
public func bridge() -> NSNumber {
return NSNumber(value: self)
}
}
extension Float: _OCKBridgable {
public typealias ObjectType = NSNumber
public func bridge() -> NSNumber {
return NSNumber(value: self)
}
}
extension Double: _OCKBridgable {
public typealias ObjectType = NSNumber
public func bridge() -> NSNumber {
return NSNumber(value: self)
}
}
extension Dictionary {
func bridge() -> NSDictionary {
var newDictionary: [NSString: Any] = [:]
for (key,value) in self {
if let stringKey = key as? String {
newDictionary[stringKey.bridge()] = value
} else if let nsstringKey = key as? NSString {
newDictionary[nsstringKey] = value
}
}
return newDictionary._bridgeToObjectiveC()
}
}
#if !os(Linux)
typealias NSErrorUserInfoType = [AnyHashable: Any]
public extension NSString {
func bridge() -> String {
return self as String
}
}
extension NSArray {
func bridge() -> Array<Any> {
return self as! Array<Any>
}
}
extension NSDictionary {
public func bridge() -> [NSObject: Any] {
return self as [NSObject: AnyObject]
}
}
extension Array {
func bridge() -> NSArray {
return self as NSArray
}
}
extension Date {
func bridge() -> NSDate {
return self as NSDate
}
}
extension NSDate {
func bridge() -> Date {
return self as Date
}
}
extension NSData {
func bridge() -> Data {
return self as Data
}
}
#elseif os(Linux)
typealias NSErrorUserInfoType = [String: Any]
public extension NSString {
func bridge() -> String {
return self._bridgeToSwift()
}
}
extension NSArray {
public func bridge() -> Array<Any> {
return self._bridgeToSwift()
}
}
extension NSDictionary {
public func bridge() -> [AnyHashable: Any] {
return self._bridgeToSwift()
}
}
extension Array {
public func bridge() -> NSArray {
return self._bridgeToObjectiveC()
}
}
extension NSData {
public func bridge() -> Data {
return self._bridgeToSwift()
}
}
extension Date {
public func bridge() -> NSDate {
return self._bridgeToObjectiveC()
}
}
extension NSDate {
public func bridge() -> Date {
return self._bridgeToSwift()
}
}
#endif
extension NSError {
public convenience init(error: Error) {
var userInfo: [String : Any] = [:]
var code: Int = 0
// Retrieve custom userInfo information.
if let customUserInfoError = error as? CustomNSError {
userInfo = customUserInfoError.errorUserInfo
code = customUserInfoError.errorCode
}
if let localizedError = error as? LocalizedError {
if let description = localizedError.errorDescription {
userInfo[NSLocalizedDescriptionKey] = description
}
if let reason = localizedError.failureReason {
userInfo[NSLocalizedFailureReasonErrorKey] = reason
}
if let suggestion = localizedError.recoverySuggestion {
userInfo[NSLocalizedRecoverySuggestionErrorKey] = suggestion
}
if let helpAnchor = localizedError.helpAnchor {
userInfo[NSHelpAnchorErrorKey] = helpAnchor
}
}
if let recoverableError = error as? RecoverableError {
userInfo[NSLocalizedRecoveryOptionsErrorKey] = recoverableError.recoveryOptions
// userInfo[NSRecoveryAttempterErrorKey] = recoverableError
}
self.init(domain: "OpenCloudKit", code: code, userInfo: userInfo)
}
}
|
7e263570640b80341a4a18259dfd3be0
| 21.799107 | 91 | 0.558449 | false | false | false | false |
yanif/circator
|
refs/heads/master
|
MetabolicCompassKit/PopulationHealthManager.swift
|
apache-2.0
|
1
|
//
// PopulationHealthManager.swift
// MetabolicCompass
//
// Created by Yanif Ahmad on 1/31/16.
// Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved.
//
import Foundation
import HealthKit
import Async
import MCCircadianQueries
/**
This is the manager of information for the comparison population.
By providing this comparison we provide our study participants with a greater ability to view themselves in context.
Initially this is defined by the NHANES data.
With sufficient enrolled subjects, this will be determined by aggregates over the ongoing study population.
- remark: pulls from PostgreSQL store (AWS RDS) -- see MCRouter --
*/
public class PopulationHealthManager {
public static let sharedManager = PopulationHealthManager()
public var aggregateRefreshDate : NSDate = NSDate()
public var mostRecentAggregates = [HKSampleType: [MCSample]]() {
didSet {
aggregateRefreshDate = NSDate()
}
}
// MARK: - Population query execution.
// Clear all aggregates.
public func resetAggregates() { mostRecentAggregates = [:] }
// Retrieve aggregates for all previewed rows.
// TODO: enable input of start time, end time and columns retrieved in the query view controllers.
public func fetchAggregates() {
var columnIndex = 0
var columns : [String:AnyObject] = [:]
var tstart : NSDate = NSDate(timeIntervalSince1970: 0)
var tend : NSDate = NSDate()
var userfilter : [String:AnyObject] = [:]
// Add population filter parameters.
let popQueryIndex = QueryManager.sharedManager.getSelectedQuery()
let popQueries = QueryManager.sharedManager.getQueries()
if popQueryIndex >= 0 && popQueryIndex < popQueries.count {
let popQuery = popQueries[popQueryIndex]
switch popQuery.1 {
case Query.ConjunctiveQuery(let qstartOpt, let qendOpt, let qcolsOpt, let aggpreds):
if let qstart = qstartOpt { tstart = qstart }
if let qend = qendOpt { tend = qend }
if let qcols = qcolsOpt {
for (hksType, mealActivityInfoOpt) in qcols {
if hksType.identifier == HKObjectType.workoutType().identifier && mealActivityInfoOpt != nil {
if let mealActivityInfo = mealActivityInfoOpt {
switch mealActivityInfo {
case .MCQueryMeal(let meal_type):
columns[String(columnIndex)] = ["meal_duration": meal_type]
columnIndex += 1
case .MCQueryActivity(let hkWorkoutType, let mcActivityValueType):
if let mcActivityType = HMConstants.sharedInstance.hkActivityToMCDB[hkWorkoutType] {
if mcActivityValueType == .Duration {
columns[String(columnIndex)] = ["activity_duration": mcActivityType]
columnIndex += 1
} else {
let quantity = mcActivityValueType == .Distance ? "distance" : "kcal_burned"
columns[String(columnIndex)] = ["activity_value": [mcActivityType: quantity]]
columnIndex += 1
}
}
}
}
} else {
if let column = HMConstants.sharedInstance.hkToMCDB[hksType.identifier] {
columns[String(columnIndex)] = column
columnIndex += 1
} else if hksType.identifier == HKCorrelationTypeIdentifierBloodPressure {
// Issue queries for both systolic and diastolic.
columns[String(columnIndex)] = HMConstants.sharedInstance.hkToMCDB[HKQuantityTypeIdentifierBloodPressureDiastolic]!
columnIndex += 1
columns[String(columnIndex)] = HMConstants.sharedInstance.hkToMCDB[HKQuantityTypeIdentifierBloodPressureSystolic]!
columnIndex += 1
} else {
log.info("Cannot perform population query for \(hksType.identifier)")
}
}
}
}
let units : UnitsSystem = UserManager.sharedManager.useMetricUnits() ? .Metric : .Imperial
let convert : (String, Int) -> Int = { (type, value) in
return Int((type == HKQuantityTypeIdentifierHeight) ?
UnitsUtils.heightValueInDefaultSystem(fromValue: Float(value), inUnitsSystem: units)
: UnitsUtils.weightValueInDefaultSystem(fromValue: Float(value), inUnitsSystem: units))
}
let predArray = aggpreds.map {
let predicateType = $0.1.0.identifier
if HMConstants.sharedInstance.healthKitTypesWithCustomMetrics.contains(predicateType) {
if let lower = $0.2, upper = $0.3, lowerInt = Int(lower), upperInt = Int(upper) {
return ($0.0, $0.1, String(convert(predicateType, lowerInt)), String(convert(predicateType, upperInt)))
}
return $0
} else {
return $0
}
}.map(serializeMCQueryPredicateREST)
for pred in predArray {
for (k,v) in pred {
userfilter.updateValue(v, forKey: k)
}
}
}
}
if columns.isEmpty {
for hksType in PreviewManager.supportedTypes {
if let column = HMConstants.sharedInstance.hkToMCDB[hksType.identifier] {
columns[String(columnIndex)] = column
columnIndex += 1
}
else if let (activity_category, quantity) = HMConstants.sharedInstance.hkQuantityToMCDBActivity[hksType.identifier] {
columns[String(columnIndex)] = ["activity_value": [activity_category:quantity]]
columnIndex += 1
}
else if hksType.identifier == HKCorrelationTypeIdentifierBloodPressure {
// Issue queries for both systolic and diastolic.
columns[String(columnIndex)] = HMConstants.sharedInstance.hkToMCDB[HKQuantityTypeIdentifierBloodPressureDiastolic]!
columnIndex += 1
columns[String(columnIndex)] = HMConstants.sharedInstance.hkToMCDB[HKQuantityTypeIdentifierBloodPressureSystolic]!
columnIndex += 1
}
else {
log.warning("No population query column available for \(hksType.identifier)")
}
}
}
let params : [String:AnyObject] = [
"tstart" : Int(floor(tstart.timeIntervalSince1970)),
"tend" : Int(ceil(tend.timeIntervalSince1970)),
"columns" : columns,
"userfilter" : userfilter
]
// log.info("Running popquery \(params)")
Service.json(MCRouter.AggregateMeasures(params), statusCode: 200..<300, tag: "AGGPOST") {
_, response, result in
guard !result.isSuccess else {
self.refreshAggregatesFromMsg(result.value)
return
}
}
}
// TODO: the current implementation of population aggregates is not sufficiently precise to distinguish between meals/activities.
// These values are all treated as workout types, and thus produce a single population aggregate given mostRecentAggregtes is indexed
// by a HKSampleType.
//
// We need to reimplement mostRecentAggregates as a mapping between a triple of (HKSampleType, MCDBType, Quantity) => value
// where MCDBType is a union type, MCDBType = HKWorkoutActivityType | String (e.g., for meals)
// and Quantity is a String (e.g., distance, kcal_burned, step_count, flights)
//
func refreshAggregatesFromMsg(payload: AnyObject?) {
var populationAggregates : [HKSampleType: [MCSample]] = [:]
if let response = payload as? [String:AnyObject],
aggregates = response["items"] as? [[String:AnyObject]]
{
var failed = false
for sample in aggregates {
for (column, val) in sample {
if !failed {
log.verbose("Refreshing population aggregate for \(column)")
// Handle meal_duration/activity_duration/activity_value columns.
// TODO: this only supports activity values that are HealthKit quantities for now (step count, flights climbed, distance/walking/running)
// We should support all MCDB meals/activity categories.
if HMConstants.sharedInstance.mcdbCategorized.contains(column) {
let categoryQuantities: [String: (String, String)] = column == "activity_value" ? HMConstants.sharedInstance.mcdbActivityToHKQuantity : [:]
if let categorizedVals = val as? [String:AnyObject] {
for (category, catval) in categorizedVals {
if let (mcdbQuantity, hkQuantity) = categoryQuantities[category],
sampleType = HKObjectType.quantityTypeForIdentifier(hkQuantity),
categoryValues = catval as? [String: AnyObject]
{
if let sampleValue = categoryValues[mcdbQuantity] as? Double {
populationAggregates[sampleType] = [doubleAsAggregate(sampleType, sampleValue: sampleValue)]
} else {
populationAggregates[sampleType] = []
}
}
else {
failed = true
log.error("Invalid MCDB categorized quantity in popquery response: \(category) \(catval)")
}
}
}
else {
failed = true
log.error("Invalid MCDB categorized values in popquery response: \(val)")
}
}
else if let typeIdentifier = HMConstants.sharedInstance.mcdbToHK[column]
{
var sampleType: HKSampleType! = nil
switch typeIdentifier {
case HKCategoryTypeIdentifierSleepAnalysis:
sampleType = HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierSleepAnalysis)!
case HKCategoryTypeIdentifierAppleStandHour:
sampleType = HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierAppleStandHour)!
default:
sampleType = HKObjectType.quantityTypeForIdentifier(typeIdentifier)!
}
if let sampleValue = val as? Double {
let agg = doubleAsAggregate(sampleType, sampleValue: sampleValue)
populationAggregates[sampleType] = [agg]
// Population correlation type entry for systolic/diastolic blood pressure sample.
if typeIdentifier == HKQuantityTypeIdentifierBloodPressureSystolic
|| typeIdentifier == HKQuantityTypeIdentifierBloodPressureDiastolic
{
let bpType = HKObjectType.correlationTypeForIdentifier(HKCorrelationTypeIdentifierBloodPressure)!
let sType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodPressureSystolic)!
let dType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodPressureDiastolic)!
let bpIndex = typeIdentifier == HKQuantityTypeIdentifierBloodPressureSystolic ? 0 : 1
if populationAggregates[bpType] == nil {
populationAggregates[bpType] = [
MCAggregateSample(value: Double.quietNaN, sampleType: sType, op: sType.aggregationOptions),
MCAggregateSample(value: Double.quietNaN, sampleType: dType, op: dType.aggregationOptions),
]
}
populationAggregates[bpType]![bpIndex] = agg
}
} else {
populationAggregates[sampleType] = []
}
}
else {
failed = true
// let err = NSError(domain: "App error", code: 0, userInfo: [NSLocalizedDescriptionKey:kvdict.description])
// let dict = ["title":"population data error", "error":err]
// NSNotificationCenter.defaultCenter().postNotificationName("ncAppLogNotification", object: nil, userInfo: dict)
}
}
}
}
if ( !failed ) {
Async.main {
// let dict = ["title":"population data", "obj":populationAggregates.description ?? ""]
// NSNotificationCenter.defaultCenter().postNotificationName("ncAppLogNotification", object: nil, userInfo: dict)
self.mostRecentAggregates = populationAggregates
NSNotificationCenter.defaultCenter().postNotificationName(HMDidUpdateRecentSamplesNotification, object: self)
}
}
else {
log.error("Failed to retrieve population aggregates from response: \(response)")
}
}
else {
log.error("Failed to deserialize population query response")
}
}
func doubleAsAggregate(sampleType: HKSampleType, sampleValue: Double) -> MCAggregateSample {
let convertedSampleValue = HKQuantity(unit: sampleType.serviceUnit!, doubleValue: sampleValue).doubleValueForUnit(sampleType.defaultUnit!)
log.info("Popquery \(sampleType.displayText ?? sampleType.identifier) \(sampleValue) \(convertedSampleValue)")
return MCAggregateSample(value: convertedSampleValue, sampleType: sampleType, op: sampleType.aggregationOptions)
}
// MARK : - Study stats queries
public func fetchStudyStats(completion: (Bool, AnyObject?) -> Void) {
Service.json(MCRouter.StudyStats, statusCode: 200..<300, tag: "GETSTUDYSTATS") {
_, response, result in
completion(result.isSuccess, result.value)
}
}
}
|
5c81929fb729c6050ed97f77a610ef3f
| 52.73064 | 167 | 0.532306 | false | false | false | false |
mgadda/swift-parse
|
refs/heads/master
|
Sources/SwiftParse/Operators.swift
|
mit
|
1
|
//
// Operators.swift
// SwiftParse
//
// Created by Matt Gadda on 11/30/19.
//
// MARK: ~ (compose)
infix operator ~: MultiplicationPrecedence
public func ~<T, U, V, LeftParsedValue, RightParsedValue>(
_ left: @autoclosure @escaping () -> Parser<T, LeftParsedValue, U>,
_ right: @autoclosure @escaping () -> Parser<U, RightParsedValue, V>
) -> Parser<T, (LeftParsedValue, RightParsedValue), V> {
return compose(left(), right())
}
public func ~<ParserTU: ParserConvertible, ParserUV: ParserConvertible>(
_ left: ParserTU,
_ right: ParserUV
) -> Parser<
ParserTU.InputType.Element,
(ParserTU.ParsedValueType, ParserUV.ParsedValueType),
ParserUV.OutputType.Element> where
ParserTU.OutputType == ParserUV.InputType
{
return compose(left, right)
}
func ~<T, U, LeftParsedValue, ParserUV: ParserConvertible>(
_ left: @autoclosure @escaping () -> Parser<T, LeftParsedValue, U>,
_ right: ParserUV
) -> Parser<T, (LeftParsedValue, ParserUV.ParsedValueType), ParserUV.OutputType.Element> where
U == ParserUV.InputType.Element
{
return compose(left(), right)
}
func ~<ParserTU: ParserConvertible, U, V, RightParsedValue>(
_ left: ParserTU,
_ right: @autoclosure @escaping () -> Parser<U, RightParsedValue, V>
) -> Parser<ParserTU.InputType.Element, (ParserTU.ParsedValueType, RightParsedValue), V> where
ParserTU.OutputType.Element == U
{
return compose(left, right())
}
// MARK: ~> (compose, ignore right)
infix operator ~>: MultiplicationPrecedence
public func ~><T, U, V, LeftParsedValue, RightParsedValue>(
_ left: @autoclosure @escaping () -> Parser<T, LeftParsedValue, U>,
_ right: @autoclosure @escaping () -> Parser<U, RightParsedValue, V>
) -> Parser<T, LeftParsedValue, V> {
return map(compose(left(), right())) { (left, _) in left }
}
public func ~><ParserTU: ParserConvertible, ParserUV: ParserConvertible>(
_ left: ParserTU,
_ right: ParserUV
) -> Parser<ParserTU.InputType.Element, ParserTU.ParsedValueType, ParserUV.OutputType.Element>
where ParserTU.OutputType == ParserUV.InputType {
left.mkParser() ~> right.mkParser()
}
public func ~><ParserLike: ParserConvertible, V, RightParsedValue>(
_ left: ParserLike,
_ right: @autoclosure @escaping () -> Parser<ParserLike.OutputType.Element, RightParsedValue, V>
) -> Parser<ParserLike.InputType.Element, ParserLike.ParsedValueType, V> {
left.mkParser() ~> right()
}
public func ~><T, LeftParsedValue, ParserLike: ParserConvertible>(
_ left: @autoclosure @escaping () -> Parser<T, LeftParsedValue, ParserLike.InputType.Element>,
_ right: ParserLike
) -> Parser<T, LeftParsedValue, ParserLike.OutputType.Element> {
left() ~> right.mkParser()
}
// MARK: <~ (compose, ignore left)
infix operator <~: MultiplicationPrecedence
public func <~ <T, U, V, LeftParsedValue, RightParsedValue>(
_ left: @autoclosure @escaping () -> Parser<T, LeftParsedValue, U>,
_ right: @autoclosure @escaping () -> Parser<U, RightParsedValue, V>
) -> Parser<T, RightParsedValue, V> {
return map(compose(left(), right())) { (_, right) in right }
}
public func <~<ParserTU: ParserConvertible, ParserUV: ParserConvertible>(
_ left: ParserTU,
_ right: ParserUV
) -> Parser<ParserTU.InputType.Element, ParserUV.ParsedValueType, ParserUV.OutputType.Element>
where ParserTU.OutputType == ParserUV.InputType {
left.mkParser() <~ right.mkParser()
}
public func <~<ParserLike: ParserConvertible, V, RightParsedValue>(
_ left: ParserLike,
_ right: @autoclosure @escaping () -> Parser<ParserLike.OutputType.Element, RightParsedValue, V>
) -> Parser<ParserLike.InputType.Element, RightParsedValue, V> {
left.mkParser() <~ right()
}
public func <~<T, LeftParsedValue, ParserLike: ParserConvertible>(
_ left: @autoclosure @escaping () -> Parser<T, LeftParsedValue, ParserLike.InputType.Element>,
_ right: ParserLike
) -> Parser<T, ParserLike.ParsedValueType, ParserLike.OutputType.Element> {
left() <~ right.mkParser()
}
// MARK: | (or)
public func |<T, U, ParsedValue>(
_ left: @autoclosure @escaping () -> Parser<T, ParsedValue, U>,
_ right: @autoclosure @escaping () -> Parser<T, ParsedValue, U>
) -> Parser<T, ParsedValue, U> {
return or(left(), right())
}
public func |<ParserLike: ParserConvertible>(
_ left: ParserLike,
_ right: ParserLike
) -> ParserFrom<ParserLike> {
or(left, right)
}
public func |<ParserLike: ParserConvertible>(
_ left: @autoclosure @escaping () -> ParserFrom<ParserLike>,
_ right: ParserLike
) -> ParserFrom<ParserLike> {
or(left(), right)
}
public func |<ParserLike: ParserConvertible>(
_ left: ParserLike,
_ right: @autoclosure @escaping () -> ParserFrom<ParserLike>
) -> ParserFrom<ParserLike> {
or(left, right())
}
// MARK: ^^ (map)
precedencegroup MapGroup {
higherThan: AssignmentPrecedence
lowerThan: AdditionPrecedence
}
infix operator ^^: MapGroup
public func ^^<T, U, InputElement, OutputElement>(
_ parser: @autoclosure @escaping () -> Parser<InputElement, T, OutputElement>,
fn: @escaping (T) -> U
) -> Parser<InputElement, U, OutputElement> {
return map(parser(), fn: fn)
}
public func ^^<U, ParserLike: ParserConvertible>(
_ parser: ParserLike,
fn: @escaping (ParserLike.ParsedValueType) -> U
) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element> {
map(parser, fn: fn)
}
public func ^^<T1, T2, T3, U, InputElement, OutputElement>(
_ parser: @autoclosure @escaping () -> Parser<InputElement, ((T1, T2), T3), OutputElement>,
fn: @escaping (T1, T2, T3) -> U
) -> Parser<InputElement, U, OutputElement> {
return map(parser(), fn: fn)
}
public func ^^<T1, T2, T3, U, ParserLike: ParserConvertible>(
_ parser: ParserLike,
fn: @escaping (ParserLike.ParsedValueType) -> U
) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element>
where ParserLike.ParsedValueType == ((T1, T2), T3) {
map(parser, fn: fn)
}
public func ^^<T1, T2, T3, T4, U, InputElement, OutputElement>(
_ parser: @autoclosure @escaping () -> Parser<InputElement, (((T1, T2), T3), T4), OutputElement>,
fn: @escaping (T1, T2, T3, T4) -> U
) -> Parser<InputElement, U, OutputElement> {
return map(parser(), fn: fn)
}
public func ^^<T1, T2, T3, T4, U, ParserLike: ParserConvertible>(
_ parser: ParserLike,
fn: @escaping (ParserLike.ParsedValueType) -> U
) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element>
where ParserLike.ParsedValueType == (((T1, T2), T3), T4) {
map(parser, fn: fn)
}
public func ^^<T1, T2, T3, T4, T5, U, InputElement, OutputElement>(
_ parser: @autoclosure @escaping () -> Parser<InputElement, ((((T1, T2), T3), T4), T5), OutputElement>,
fn: @escaping (T1, T2, T3, T4, T5) -> U
) -> Parser<InputElement, U, OutputElement> {
return map(parser(), fn: fn)
}
public func ^^<T1, T2, T3, T4, T5, U, ParserLike: ParserConvertible>(
_ parser: ParserLike,
fn: @escaping (ParserLike.ParsedValueType) -> U
) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element>
where ParserLike.ParsedValueType == ((((T1, T2), T3), T4), T5) {
map(parser, fn: fn)
}
public func ^^<T1, T2, T3, T4, T5, T6, U, InputElement, OutputElement>(
_ parser: @autoclosure @escaping () -> Parser<InputElement, (((((T1, T2), T3), T4), T5), T6), OutputElement>,
fn: @escaping (T1, T2, T3, T4, T5, T6) -> U
) -> Parser<InputElement, U, OutputElement> {
return map(parser(), fn: fn)
}
public func ^^<T1, T2, T3, T4, T5, T6, U, ParserLike: ParserConvertible>(
_ parser: ParserLike,
fn: @escaping (ParserLike.ParsedValueType) -> U
) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element>
where ParserLike.ParsedValueType == (((((T1, T2), T3), T4), T5), T6) {
map(parser, fn: fn)
}
public func ^^<T1, T2, T3, T4, T5, T6, T7, U, InputElement, OutputElement>(
_ parser: @autoclosure @escaping () -> Parser<InputElement, ((((((T1, T2), T3), T4), T5), T6), T7), OutputElement>,
fn: @escaping (T1, T2, T3, T4, T5, T6, T7) -> U
) -> Parser<InputElement, U, OutputElement> {
return map(parser(), fn: fn)
}
public func ^^<T1, T2, T3, T4, T5, T6, T7, U, ParserLike: ParserConvertible>(
_ parser: ParserLike,
fn: @escaping (ParserLike.ParsedValueType) -> U
) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element>
where ParserLike.ParsedValueType == ((((((T1, T2), T3), T4), T5), T6), T7) {
map(parser, fn: fn)
}
public func ^^<T1, T2, T3, T4, T5, T6, T7, T8, U, InputElement, OutputElement>(
_ parser: @autoclosure @escaping () -> Parser<InputElement, (((((((T1, T2), T3), T4), T5), T6), T7), T8), OutputElement>,
fn: @escaping (T1, T2, T3, T4, T5, T6, T7, T8) -> U
) -> Parser<InputElement, U, OutputElement> {
return map(parser(), fn: fn)
}
public func ^^<T1, T2, T3, T4, T5, T6, T7, T8, U, ParserLike: ParserConvertible>(
_ parser: ParserLike,
fn: @escaping (ParserLike.ParsedValueType) -> U
) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element>
where ParserLike.ParsedValueType == (((((((T1, T2), T3), T4), T5), T6), T7), T8) {
map(parser, fn: fn)
}
// MARK: * (rep)
postfix operator *
public postfix func *<T, InputElement>(_ parser: @autoclosure @escaping () -> Parser<InputElement, T, InputElement>) -> Parser<InputElement, [T], InputElement> {
rep(parser())
}
public postfix func *<ParserLike: ParserConvertible>(
_ parser: ParserLike
) -> StandardParser<ParserLike.InputType, [ParserLike.ParsedValueType]>
where ParserLike.InputType == ParserLike.OutputType
{
rep(parser.mkParser())
}
// MARK: + (rep1)
postfix operator +
public postfix func +<T, InputElement>(_ parser: @autoclosure @escaping () -> Parser<InputElement, T, InputElement>) -> Parser<InputElement, [T], InputElement> {
return rep1(parser())
}
public postfix func +<ParserLike: ParserConvertible>(
_ parser: ParserLike
) -> StandardParser<ParserLike.InputType, [ParserLike.ParsedValueType]>
where ParserLike.InputType == ParserLike.OutputType {
rep1(parser)
}
// MARK: *? (opt)
postfix operator *?
public postfix func *?<InputElement, T>(_ parser: @autoclosure @escaping () -> Parser<InputElement, T, InputElement>) -> Parser<InputElement, T?, InputElement> {
return opt(parser())
}
public postfix func *?<ParserLike: ParserConvertible>(
_ parser: ParserLike
) -> StandardParser<ParserLike.InputType, ParserLike.ParsedValueType?>
where ParserLike.InputType == ParserLike.OutputType {
return opt(parser)
}
// MARK: & (and)
infix operator &: MultiplicationPrecedence
public func &<T, U, V, LeftValue, RightValue>(
_ left: @autoclosure @escaping () -> Parser<T, LeftValue, U>,
_ right: @autoclosure @escaping () -> Parser<T, RightValue, V>) -> Parser<T, LeftValue, U> {
and(left(), right())
}
public func &<V, RightValue, ParserTU: ParserConvertible>(
_ left: ParserTU,
_ right: @autoclosure @escaping () -> Parser<ParserTU.InputType.Element, RightValue, V>
) -> ParserFrom<ParserTU> {
and(left, right())
}
public func &<U, LeftValue, ParserTV: ParserConvertible>(
_ left: @autoclosure @escaping () -> Parser<ParserTV.InputType.Element, LeftValue, U>,
_ right: ParserTV
) -> Parser<ParserTV.InputType.Element, LeftValue, U> {
and(left(), right)
}
public func &<ParserTU: ParserConvertible, ParserTV: ParserConvertible>(
_ left: ParserTU,
_ right: ParserTV) -> ParserFrom<ParserTU>
where ParserTU.InputType == ParserTV.InputType
{
and(left, right)
}
|
60f337197e527d4badf1b938798ffefd
| 33.692073 | 161 | 0.686088 | false | false | false | false |
hfutrell/BezierKit
|
refs/heads/master
|
BezierKit/BezierKitTests/Path+ProjectionTests.swift
|
mit
|
1
|
//
// Path+ProjectionTests.swift
// BezierKit
//
// Created by Holmes Futrell on 11/23/20.
// Copyright © 2020 Holmes Futrell. All rights reserved.
//
@testable import BezierKit
import XCTest
#if canImport(CoreGraphics)
import CoreGraphics
class PathProjectionTests: XCTestCase {
func testProjection() {
XCTAssertNil(Path().project(CGPoint.zero), "projection requires non-empty path.")
let triangle1 = { () -> Path in
let cgPath = CGMutablePath()
cgPath.addLines(between: [CGPoint(x: 0, y: 2),
CGPoint(x: 2, y: 4),
CGPoint(x: 0, y: 4)])
cgPath.closeSubpath()
return Path(cgPath: cgPath)
}()
let triangle2 = { () -> Path in
let cgPath = CGMutablePath()
cgPath.addLines(between: [CGPoint(x: 2, y: 1),
CGPoint(x: 3, y: 1),
CGPoint(x: 3, y: 2)])
cgPath.closeSubpath()
return Path(cgPath: cgPath)
}()
let square = Path(rect: CGRect(x: 3, y: 3, width: 1, height: 1))
let path = Path(components: triangle1.components + triangle2.components + square.components)
let projection = path.project(CGPoint(x: 2, y: 2))
XCTAssertEqual(projection?.location, IndexedPathLocation(componentIndex: 1, elementIndex: 2, t: 0.5))
XCTAssertEqual(projection?.point, CGPoint(x: 2.5, y: 1.5))
}
func testPointIsWithinDistanceOfBoundary() {
let circleCGPath = CGMutablePath()
circleCGPath.addEllipse(in: CGRect(origin: CGPoint(x: -1.0, y: -1.0), size: CGSize(width: 2.0, height: 2.0)))
let circlePath = Path(cgPath: circleCGPath) // a circle centered at origin with radius 1
let d = CGFloat(0.1)
let p1 = CGPoint(x: -3.0, y: 0.0)
let p2 = CGPoint(x: -0.9, y: 0.9)
let p3 = CGPoint(x: 0.75, y: 0.75)
let p4 = CGPoint(x: 0.5, y: 0.5)
XCTAssertFalse(circlePath.pointIsWithinDistanceOfBoundary(p1, distance: d)) // no, path bounding box isn't even within that distance
XCTAssertFalse(circlePath.pointIsWithinDistanceOfBoundary(p2, distance: d)) // no, within bounding box, but no individual curves are within that distance
XCTAssertTrue(circlePath.pointIsWithinDistanceOfBoundary(p3, distance: d)) // yes, one of the curves that makes up the circle is within that distance
XCTAssertTrue(circlePath.pointIsWithinDistanceOfBoundary(p3, distance: CGFloat(10.0))) // yes, so obviously within that distance implementation should early return yes
XCTAssertFalse(circlePath.pointIsWithinDistanceOfBoundary(p4, distance: d)) // no, we are inside the path but too far from the boundary
}
}
#endif
|
e6ecdef563155830b4acdc3b6cf265e4
| 44.467742 | 176 | 0.620788 | false | true | false | false |
QuarkWorks/RealmModelGenerator
|
refs/heads/master
|
RealmModelGenerator/RealmSchemaDocument.swift
|
mit
|
1
|
//
// RealmSchemaDocument.swift
// RealmModelGenerator
//
// Created by Zhaolong Zhong on 3/14/16.
// Copyright © 2016 QuarkWorks. All rights reserved.
//
import Cocoa
class RealmSchemaDocument: NSDocument {
static let TAG = String(describing: RealmSchemaDocument.self)
let MAIN: NSStoryboard.Name = NSStoryboard.Name(rawValue: "Main")
let DOCUMENT_WINDOW_CONTROLLER: NSStoryboard.SceneIdentifier = NSStoryboard.SceneIdentifier(rawValue: "Document Window Controller")
private var mainVC: MainVC!
private var schema = Schema()
private var windowController:NSWindowController?
override init() {
super.init()
// Add your subclass-specific initialization here.
}
override func windowControllerDidLoadNib(_ aController: NSWindowController) {
super.windowControllerDidLoadNib(aController)
// Add any code here that needs to be executed once the windowController has loaded the document's window.
}
override class var autosavesInPlace: Bool {
return true
}
override func makeWindowControllers() {
// Returns the Storyboard that contains your Document window.
let storyboard = NSStoryboard(name: MAIN, bundle: nil)
let windowController = storyboard.instantiateController(withIdentifier: DOCUMENT_WINDOW_CONTROLLER) as! NSWindowController
if let v = windowController.contentViewController as? MainVC {
mainVC = v
mainVC.schema = schema
}
self.addWindowController(windowController)
}
override func data(ofType: String) throws -> Data {
// Insert code here to write your document to data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning nil.
// You can also choose to override fileWrapperOfType:error:, writeToURL:ofType:error:, or writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead.
var arrayOfDictionaries = [[String:Any]]()
let schemaDict = mainVC.schema!.toDictionary()
arrayOfDictionaries.append(schemaDict)
let data: Data? = try JSONSerialization.data(withJSONObject: arrayOfDictionaries, options: [])
if let value = data {
return value
}
throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}
override func read(from data: Data, ofType typeName: String) throws {
// Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false.
// You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead.
// If you override either of these, you should also override -isEntireFileLoaded to return false if the contents are lazily loaded.
do {
try parseSchemaJson(data: data)
return
} catch GeneratorError.InvalidFileContent(let errorMsg) {
// MARK: - correct print function?
Swift.print("Invalid JSON format: \(errorMsg)")
}
Tools.popupAlert(messageText: "Error", buttonTitle: "OK", informativeText: "Invalid content")
}
func parseSchemaJson(data: Data) throws {
if let arrayOfDictionaries = try! JSONSerialization.jsonObject(with: data, options: []) as? [[String:Any]]{
guard let dictionary = arrayOfDictionaries.first else {
throw GeneratorError.InvalidFileContent(errorMsg: RealmSchemaDocument.TAG + ": No schema in this file")
}
try schema.map(dictionary: dictionary )
return
}
}
}
|
d4b6b68054570f30345e0dfcd7885d5f
| 39.020619 | 186 | 0.659196 | false | false | false | false |
pattogato/WGUtils
|
refs/heads/master
|
WGUtils/WGDateUtils.swift
|
mit
|
1
|
//
// DateUtils.swift
// WGUtils
//
// Created by Bence Pattogato on 18/02/16.
// Copyright © 2016 Wintergarden. All rights reserved.
//
import UIKit
class DateUtils: NSObject {
// Takes a String and a Format and converts it to an NSDate?
static func stringToDate(string: String, _ format: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = format
let date = dateFormatter.dateFromString(string)
return date
}
//Converts an NSDate into a string with the given format
static func dateToString(format: String, date: NSDate) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = format
let string = dateFormatter.stringFromDate(date)
return string
}
}
// MARK: - Date Extension
extension NSDate {
/// Init NSDate with day, month and year
class func initDate(day: Int, month: Int, year: Int) -> NSDate? {
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone.systemTimeZone()
let components = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: NSDate())
components.year = year
components.month = month
components.day = day
return calendar.dateFromComponents(components)
}
/// Returns if the NSDate instance is on a same day parameter date
func isOnSameDay(date: NSDate) -> Bool {
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone.systemTimeZone()
let componentsForFirstDate = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: self)
let componentsForSecondDate = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: date)
return componentsForFirstDate.year == componentsForSecondDate.year &&
componentsForFirstDate.month == componentsForSecondDate.month &&
componentsForFirstDate.day == componentsForSecondDate.day
}
/// Returns if the NSDate instance is on a same month parameter date
func inInSameMonth(date: NSDate) -> Bool {
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone.systemTimeZone()
let componentsForFirstDate = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: self)
let componentsForSecondDate = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: date)
return componentsForFirstDate.year == componentsForSecondDate.year &&
componentsForFirstDate.month == componentsForSecondDate.month
}
/// Returns the beginning of the given date (hour, min, sec)
func beginningOfDay() -> NSDate {
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone.systemTimeZone()
let components = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second ], fromDate: self)
components.hour = 0
components.minute = 0
components.second = 0
return calendar.dateFromComponents(components) ?? self
}
/// Returns the end of the given date (hour, min, sec)
func endOfDay(isStartOfNextDay isStartOfNextDay: Bool = false) -> NSDate {
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone.systemTimeZone()
let components = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second ], fromDate: self)
if isStartOfNextDay {
components.hour = 24
components.minute = 0
components.second = 0
} else {
components.hour = 23
components.minute = 59
components.second = 59
}
return calendar.dateFromComponents(components) ?? self
}
/// Returns the month name as string
func monthName() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMMM"
return dateFormatter.stringFromDate(self)
}
/// Returns the years name as string
func yearString() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY"
return dateFormatter.stringFromDate(self)
}
/// Returns the days of the month's days
func getMonthsDays() -> [NSDate] {
let nextCalendar = NSCalendar.currentCalendar()
let nextComponents = nextCalendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.WeekOfMonth, NSCalendarUnit.Weekday], fromDate: self)
nextComponents.day = 0
guard let monthBeginningDate = nextCalendar.dateFromComponents(nextComponents) else {
return [NSDate]()
}
nextComponents.month = nextComponents.month + 1
nextComponents.day = 0
guard let monthEndDate = nextCalendar.dateFromComponents(nextComponents) else {
return [NSDate]()
}
let monthDays = NSDate.daysBetweenDates(monthBeginningDate, endDate: monthEndDate)
return monthDays
}
/// Returns an NSDate array between startDate and endDate
class func daysBetweenDates(startDate: NSDate!, endDate: NSDate!) -> [NSDate] {
var date = startDate
// date for the loop
let gregorian:NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let dateComponents = NSDateComponents()
dateComponents.year = 1
// Create an array to hold *all* the returned
// results for the year
var datesArray = [NSDate]()
// Loop through each date until the ending date is
// reached
while date.compare(endDate) != NSComparisonResult.OrderedDescending {
// increment the date by 1 day
let dateComponents = NSDateComponents()
dateComponents.day = 1
date = gregorian.dateByAddingComponents(dateComponents, toDate: date, options: NSCalendarOptions.MatchFirst)
datesArray.append(date)
}
datesArray.removeAtIndex(datesArray.count - 1)
return datesArray
}
/// Returns the next month's date
func nextMonthDate() -> NSDate {
let nextCalendar = NSCalendar.currentCalendar()
let nextComponents = nextCalendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: self)
nextComponents.month = nextComponents.month + 1
guard let nextMonth = nextCalendar.dateFromComponents(nextComponents) else {
return NSDate()
}
return nextMonth
}
/// Returns the previous month's date
func previousMonthDate() -> NSDate {
let prevCalendar = NSCalendar.currentCalendar()
let prevComponents = prevCalendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: self)
prevComponents.month = prevComponents.month - 1
guard let prevMonth = prevCalendar.dateFromComponents(prevComponents) else {
return NSDate()
}
return prevMonth
}
/// Returns the month's first day
func getMonthFirstDay() -> NSDate? {
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone.systemTimeZone()
let components = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: self)
components.day = 1
return calendar.dateFromComponents(components)
}
/// Returns a touple(year, month, day) as the date's components
func components() -> (year: Int, month: Int, day: Int) {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: self)
return (components.year, components.month, components.day)
}
/// Returns the number of days in the month
func numberOfDaysInMonth() -> Int {
let calendar = NSCalendar.currentCalendar()
let daysRange = calendar.rangeOfUnit(.Day, inUnit: .Month, forDate: self)
return daysRange.length
}
}
extension NSDate: Comparable {}
public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 == rhs.timeIntervalSince1970
}
public func <(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 < rhs.timeIntervalSince1970
}
|
3e49606c8838d24930f6c74ca311e92b
| 37.168776 | 193 | 0.654395 | false | false | false | false |
butterproject/butter-ios
|
refs/heads/master
|
Butter/API/ButterAPIManager.swift
|
gpl-3.0
|
1
|
//
// ButterAPIManager.swift
// Butter
//
// Created by DjinnGA on 24/07/2015.
// Copyright (c) 2015 Butter Project. All rights reserved.
//
import Foundation
class ButterAPIManager: NSObject {
static let sharedInstance = ButterAPIManager()
let moviesAPIEndpoint: String = "http://vodo.net/popcorn" // ToDo: Add Vodo
let moviesAPIEndpointCloudFlareHost : String = ""
let TVShowsAPIEndpoint: String = ""
let animeAPIEndpoint: String = ""
var isSearching = false
var cachedMovies = OrderedDictionary<String,ButterItem>()
var cachedTVShows = OrderedDictionary<String,ButterItem>()
var cachedAnime = OrderedDictionary<String,ButterItem>()
var moviesPage = 0
var showsPage = 0
var searchPage = 0
static let languages = [
"ar": "Arabic",
"eu": "Basque",
"bs": "Bosnian",
"br": "Breton",
"bg": "Bulgarian",
"zh": "Chinese",
"hr": "Croatian",
"cs": "Czech",
"da": "Danish",
"nl": "Dutch",
"en": "English",
"et": "Estonian",
"fi": "Finnish",
"fr": "French",
"de": "German",
"el": "Greek",
"he": "Hebrew",
"hu": "Hungarian",
"it": "Italian",
"lt": "Lithuanian",
"mk": "Macedonian",
"fa": "Persian",
"pl": "Polish",
"pt": "Portuguese",
"ro": "Romanian",
"ru": "Russian",
"sr": "Serbian",
"sl": "Slovene",
"es": "Spanish",
"sv": "Swedish",
"th": "Thai",
"tr": "Turkish",
"uk": "Ukrainian"
]
var searchResults = OrderedDictionary<String,ButterItem>()
var amountToLoad: Int = 50
var mgenres: [String] = ["All"]
var genres: [String] {
set(newValue) {
self.mgenres = newValue
if (newValue[0] != "All") {
isSearching = true
searchPage = 0
} else {
isSearching = false
}
}
get {
return self.mgenres
}
}
var quality: String = "All"
private var msearchString: String = ""
var searchString: String {
set(newValue) {
self.msearchString = newValue.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
searchResults = OrderedDictionary<String,ButterItem>()
if (newValue != "") {
isSearching = true
searchPage = 0
} else {
isSearching = false
}
}
get {
return self.msearchString
}
}
func loadMovies(onCompletion: (newItems : Bool) -> Void) {
var page : Int!
if isSearching {
page = ++searchPage
} else {
page = ++moviesPage
}
MovieAPI.sharedInstance.load(page) { (newItems) in
onCompletion(newItems: newItems)
}
}
func loadTVShows(onCompletion: (newItems : Bool) -> Void) {
var page : Int!
if isSearching {
page = ++searchPage
} else {
page = ++showsPage
}
TVAPI.sharedInstance.load(page) { (newItems) in
onCompletion(newItems: newItems)
}
}
func loadAnime(onCompletion: () -> Void) {
var page : Int!
if isSearching {
page = ++searchPage
} else {
page = ++showsPage
}
AnimeAPI.sharedInstance.load(page, onCompletion: {
onCompletion()
})
}
func makeMagnetLink(torrHash:String, title: String)-> String {
let torrentHash = torrHash
let movieTitle = title
let demoniiTracker = "udp://open.demonii.com:1337"
let istoleTracker = "udp://tracker.istole.it:80"
let yifyTracker = "http://tracker.yify-torrents.com/announce"
let publicbtTracker = "udp://tracker.publicbt.com:80"
let openBTTracker = "udp://tracker.openbittorrent.com:80"
let copperTracker = "udp://tracker.coppersurfer.tk:6969"
let desync1Tracker = "udp://exodus.desync.com:6969"
let desync2Tracker = "http://exodus.desync.com:6969/announce"
let magnetURL = "magnet:?xt=urn:btih:\(torrentHash)&dn=\(movieTitle)&tr=\(demoniiTracker)&tr=\(istoleTracker)&tr=\(yifyTracker)&tr=\(publicbtTracker)&tr=\(openBTTracker)&tr=\(copperTracker)&tr=\(desync1Tracker)&tr=\(desync2Tracker)"
return magnetURL
}
}
|
f2f3157291f86c630b78a4b19477d16e
| 25.980892 | 240 | 0.578512 | false | false | false | false |
gtsif21/PushNotificationHandler
|
refs/heads/master
|
PushNotificationHandler/PushNotificationHandler.swift
|
mit
|
1
|
//
// PushNotificationHandler.swift
//
// Created by George Tsifrikas on 16/06/16.
// Copyright © 2016 George Tsifrikas. All rights reserved.
//
import Foundation
struct WeakContainer<T: AnyObject> {
weak var _value : T?
init (value: T) {
_value = value
}
func get() -> T? {
return _value
}
}
public class PushNotificationHandler {
public static let sharedInstance = PushNotificationHandler()
private var subscribers: [WeakContainer<UIViewController>] = []
private var apnsToken: String?
public typealias NewTokenHandlerArguments = (tokenData: Data?, token: String?, error: Error?)
private var newTokenHandler: (NewTokenHandlerArguments) -> Void = {_,_,_ in}
private func alreadySubscribedIndex(potentialSubscriber: PushNotificationSubscriber) -> Int? {
return subscribers.index(where: { (weakSubscriber) -> Bool in
guard let validPotentialSubscriber = potentialSubscriber as? UIViewController,
let validWeakSubscriber = weakSubscriber.get() else {
return false
}
return validPotentialSubscriber === validWeakSubscriber
})
}
public func registerNewAPNSTokenHandler(handler: @escaping (NewTokenHandlerArguments) -> Void) {
newTokenHandler = handler
}
public func subscribeForPushNotifications<T: PushNotificationSubscriber>(subscriber: T) {
if let validSubscriber = subscriber as? UIViewController {
if alreadySubscribedIndex(potentialSubscriber: subscriber) == nil {
subscribers += [WeakContainer(value: validSubscriber)]
}
}
}
public func unsubscribeForPushNotifications<T: PushNotificationSubscriber>(subscriber: T) {
if let index = alreadySubscribedIndex(potentialSubscriber: subscriber) {
subscribers.remove(at: index)
}
}
public func registerForPushNotifications(application: UIApplication) {
let notificationSettings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)
application.registerUserNotificationSettings(notificationSettings)
}
public func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != .none {
application.registerForRemoteNotifications()
}
}
public func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenString = deviceToken.map { String(format: "%02.2hhx", arguments: [$0]) }.joined()
apnsToken = tokenString
newTokenHandler((tokenData: deviceToken, token: tokenString, error: nil))
}
public func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
newTokenHandler((tokenData: nil, token: nil, error: error))
print("Failed to register:", error)
}
public func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
let aps = userInfo["aps"]
handleAPNS(aps: aps as! [AnyHashable : Any])
}
private func handleAPNS(aps: [AnyHashable : Any]) {
for containerOfSubscriber in subscribers {
(containerOfSubscriber.get() as? PushNotificationSubscriber)?.newPushNotificationReceived(aps: aps)
}
}
public func handleApplicationStartWith(application: UIApplication, launchOptions: [UIApplicationLaunchOptionsKey : Any]?) {
if let notification = launchOptions?[.remoteNotification] as? [String: AnyObject] {
if let aps = notification["aps"] as? [String: AnyObject] {
handleAPNS(aps: aps)
}
}
}
}
public protocol PushNotificationSubscriber {
func newPushNotificationReceived(aps: [AnyHashable : Any])
}
|
729c23dad3fb740c1a20c8664be43a55
| 37.037736 | 127 | 0.670635 | false | false | false | false |
rcobelli/GameOfficials
|
refs/heads/master
|
Game Officials/GameViewController.swift
|
mit
|
1
|
//
// GameViewController.swift
// Game Officials
//
// Created by Ryan Cobelli on 1/2/17.
// Copyright © 2017 Rybel LLC. All rights reserved.
//
import UIKit
import Eureka
import Alamofire
import MessageUI
class GameViewController: FormViewController, MFMailComposeViewControllerDelegate {
var json : JSON = ""
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
let params : Parameters = ["username" : UserDefaults.standard.string(forKey: "username")!, "password": UserDefaults.standard.string(forKey: "password")!]
Alamofire.request("https://rybel-llc.com/game-officials/otherOfficialsInfo.php?id=" + json["GameID"].string!, method: .post, parameters: params)
.responseString { response in
if response.result.isSuccess {
if let dataFromString = response.result.value?.data(using: String.Encoding.utf8, allowLossyConversion: false) {
let info = JSON(data: dataFromString)
if info["REF"].array != nil {
if (info["REF"].array?.count)! > 1 {
self.createOfficial(position: "Ref", email: info["REF"][1].string, phone: info["REF"][0].string)
}
else {
if info["REF"][0].string?.range(of: "[") != nil {
self.createOfficial(position: "Ref", email: nil, phone: info["REF"][0].string)
}
else {
self.createOfficial(position: "Ref", email: info["REF"][0].string, phone: nil)
}
}
}
if info["AR1"].array != nil {
if (info["AR1"].array?.count)! > 1 {
self.createOfficial(position: "AR1", email: info["AR1"][1].string, phone: info["AR1"][0].string)
}
else {
if info["AR1"][0].string?.range(of: "[") != nil {
self.createOfficial(position: "AR1", email: nil, phone: info["AR1"][0].string)
}
else {
self.createOfficial(position: "AR1", email: info["AR1"][0].string, phone: nil)
}
}
}
if info["AR2"].array != nil {
if (info["AR2"].array?.count)! > 1 {
self.createOfficial(position: "AR2", email: info["AR2"][1].string, phone: info["AR2"][0].string)
}
else {
if info["AR2"][0].string?.range(of: "[") != nil {
self.createOfficial(position: "AR2", email: nil, phone: info["AR2"][0].string)
}
else {
self.createOfficial(position: "AR2", email: info["AR2"][0].string, phone: nil)
}
}
}
if info["FOURTH"].array != nil {
if (info["FOURTH"].array?.count)! > 1 {
self.createOfficial(position: "4th", email: info["FOURTH"][1].string, phone: info["FOURTH"][0].string)
}
else {
if info["FOURTH"][0].string?.range(of: "[") != nil {
self.createOfficial(position: "4th", email: nil, phone: info["FOURTH"][0].string)
}
else {
self.createOfficial(position: "4th", email: info["FOURTH"][0].string, phone: nil)
}
}
}
}
else {
print("Can not encode")
}
}
else {
print("Could Not Load Data")
}
}
self.title = "Game #: " + String(describing: json["GameNumber"]).replacingOccurrences(of: " ", with: "")
let teams = String(describing: json["Teams"]).components(separatedBy: " vs. ")
let info = Section("Game Info")
<<< LabelRow(){ row in
row.title = (String(describing: json["DateAndTime"]).components(separatedBy: " "))[0].replacingOccurrences(of: " ", with: "")
}
<<< LabelRow(){ row in
row.title = (String(describing: json["Venue"]).components(separatedBy: " "))[0]
}
<<< LabelRow(){ row in
row.title = String(describing: json["League"]).replacingOccurrences(of: " ", with: "")
}
<<< LabelRow(){ row in
row.title = String(describing: json["Division"]).replacingOccurrences(of: " ", with: "")
}
<<< LabelRow(){ row in
row.title = "Home Team: " + teams[0]
}
<<< LabelRow(){ row in
row.title = "Away Team: " + teams[1]
}
form += [info]
}
func createOfficial(position: String, email: String?, phone: String?) {
var section = Section(position)
<<< LabelRow(){ row in
row.title = json["Officials"][position].string?.replacingOccurrences(of: " ", with: "")
}
if email != nil {
let button = ButtonRow(){ row in
row.title = email!
}.onCellSelection { cell, row in
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients([email!])
self.present(mail, animated: true, completion: nil)
}
else {
DispatchQueue.global().async {
UIPasteboard.general.string = email!
}
let alert = UIAlertController(title: "Unable To Send Email", message: "The mail app is not setup, so we copied the email address to your clipboard instead", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
section += [button]
}
if phone != nil {
let button = ButtonRow(){ row in
row.title = phone!
}.onCellSelection { cell, row in
let correctedNumber = phone!.digits
print(correctedNumber)
if let url = URL(string:"tel://\(correctedNumber)"), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
}
else {
DispatchQueue.global().async {
UIPasteboard.general.string = email!
}
let alert = UIAlertController(title: "Unable To Make Call", message: "We were unable to complete the call, so we copied the phone number to your clipboard instead", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
section += [button]
}
form += [section]
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true)
}
}
|
ddd2d2201a2fa61e8574b1768466cc21
| 34.171271 | 216 | 0.614515 | false | false | false | false |
cfilipov/MuscleBook
|
refs/heads/master
|
MuscleBook/DB+Calculations.swift
|
gpl-3.0
|
1
|
/*
Muscle Book
Copyright (C) 2016 Cristian Filipov
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 SQLite
extension DB {
func get(type: PersonalRecord.Type, input: Workset.Input) -> [PersonalRecord] {
guard let exerciseID = input.exerciseID else { return [] }
var records: [PersonalRecord] = []
let calculations = input.calculations
if let weight = input.weight,
w = maxReps(exerciseID: exerciseID, weight: weight, todate: input.startTime) {
records.append(
.MaxReps(
worksetID: w.worksetID,
maxReps: w.input.reps!,
curReps: input.reps))
}
if let w = maxRM(exerciseID: exerciseID, todate: input.startTime) {
records.append(
.MaxWeight(
worksetID: w.worksetID,
maxWeight: w.input.weight!,
curWeight: input.weight))
}
if let w = max1RM(exerciseID: exerciseID, todate: input.startTime) {
records.append(
.Max1RM(
worksetID: w.worksetID,
maxWeight: w.input.weight!,
curWeight: input.weight))
}
if let w = maxE1RM(exerciseID: exerciseID, todate: input.startTime) {
records.append(
.MaxE1RM(
worksetID: w.worksetID,
maxWeight: w.calculations.e1RM!,
curWeight: calculations.findmap {
if case let .E1RM(val) = $0 { return val }
return nil
}))
}
if let w = maxVolume(exerciseID: exerciseID, todate: input.startTime) {
records.append(
.MaxVolume(
worksetID: w.worksetID,
maxVolume: w.calculations.volume!,
curVolume: calculations.findmap {
if case let .Volume(val) = $0 { return val }
return nil
}))
}
if let reps = input.reps,
w = maxXRM(exerciseID: exerciseID, reps: reps, todate: input.startTime) {
records.append(
.MaxXRM(
worksetID: w.worksetID,
maxWeight: w.input.weight!,
curWeight: input.weight))
}
return records
}
func get(type: Records.Type, input: Workset.Input) -> Records? {
guard let exerciseID = input.exerciseID else { return nil }
var perf = Records()
perf.maxReps = input.weight.flatMap { self.maxReps(exerciseID: exerciseID, weight: $0, todate: input.startTime) }
perf.maxWeight = maxRM(exerciseID: exerciseID, todate: input.startTime)
perf.max1RM = max1RM(exerciseID: exerciseID, todate: input.startTime)
perf.maxE1RM = maxE1RM(exerciseID: exerciseID, todate: input.startTime)
perf.maxVolume = maxVolume(exerciseID: exerciseID, todate: input.startTime)
perf.maxXRM = input.reps.flatMap { maxXRM(exerciseID: exerciseID, reps: $0, todate: input.startTime) }
return perf
}
func maxRM(exerciseID exerciseID: Int64, todate date: NSDate = NSDate()) -> Workset? {
return db.pluck(
Workset.Schema.table
.filter(
Workset.Schema.startTime.localDay < date.localDay &&
Workset.Schema.exerciseID == exerciseID &&
Workset.Schema.exerciseID != nil &&
Workset.Schema.weight != nil)
.order(Workset.Schema.weight.desc)
.limit(1))
}
func maxReps(exerciseID exerciseID: Int64, weight: Double, todate date: NSDate = NSDate()) -> Workset? {
return db.pluck(
Workset.Schema.table
.filter(
Workset.Schema.startTime.localDay < date.localDay &&
Workset.Schema.exerciseID == exerciseID &&
Workset.Schema.exerciseID != nil &&
Workset.Schema.weight >= weight &&
Workset.Schema.reps != nil)
.order(Workset.Schema.reps.desc)
.limit(1)
)
}
func max1RM(exerciseID exerciseID: Int64, todate date: NSDate = NSDate()) -> Workset? {
typealias W = Workset.Schema
return db.pluck(W.table
.filter(
W.startTime.localDay < date.localDay &&
W.exerciseID == exerciseID &&
W.exerciseID != nil &&
W.reps == 1 &&
W.weight != nil)
.order(Workset.Schema.weight.desc)
.limit(1))
}
func maxE1RM(exerciseID exerciseID: Int64, todate date: NSDate = NSDate()) -> Workset? {
typealias W = Workset.Schema
return db.pluck(W.table
.filter(
W.startTime.localDay < date.localDay &&
W.exerciseID == exerciseID &&
W.exerciseID != nil &&
W.e1RM != nil)
.order(W.e1RM.desc)
.limit(1))
}
func maxXRM(exerciseID exerciseID: Int64, reps: Int, todate date: NSDate = NSDate()) -> Workset? {
typealias W = Workset.Schema
return db.pluck(W.table
.filter(
W.startTime.localDay < date.localDay &&
W.exerciseID == exerciseID &&
W.exerciseID != nil &&
W.reps == reps &&
W.weight != nil)
.order(Workset.Schema.weight.desc)
.limit(1)
)
}
func maxVolume(exerciseID exerciseID: Int64, todate date: NSDate = NSDate()) -> Workset? {
return db.pluck(
Workset.Schema.table
.filter(
Workset.Schema.startTime.localDay < date.localDay &&
Workset.Schema.exerciseID == exerciseID &&
Workset.Schema.exerciseID != nil &&
Workset.Schema.weight != nil &&
Workset.Schema.volume != nil)
.order(Workset.Schema.volume.desc)
.limit(1))
}
func maxSquat(sinceDate date: NSDate) -> Double? {
typealias W = Workset.Schema
return db.scalar(W.table
.select(W.weight.max)
.filter(
W.startTime.localDay >= date &&
W.exerciseID == 973))
}
func maxDeadlift(sinceDate date: NSDate) -> Double? {
typealias W = Workset.Schema
return db.scalar(W.table
.select(W.weight.max)
.filter(
W.startTime.localDay >= date &&
W.exerciseID == 723))
}
func maxBench(sinceDate date: NSDate) -> Double? {
typealias W = Workset.Schema
return db.scalar(W.table
.select(W.weight.max)
.filter(
W.startTime.localDay >= date &&
W.exerciseID == 482))
}
func recalculateAll(after startTime: NSDate = NSDate(timeIntervalSince1970: 0)) throws {
typealias W = Workset.Schema
for workset: Workset in try db.prepare(W.table.filter(W.startTime >= startTime)) {
guard let records = get(Records.self, input: workset.input) else { continue }
let relRecords = RelativeRecords(input: workset.input, records: records)
let newWorkset = workset.copy(input: workset.input, calculations: relRecords.calculations)
try update(newWorkset)
try recalculate(workoutID: workset.workoutID)
}
}
func totalActiveDuration(sinceDate date: NSDate) -> Double? {
typealias W = Workset.Schema
return db.scalar(W.table
.select(W.duration.sum)
.filter(W.startTime.localDay >= date))
}
func totalSets(sinceDate date: NSDate) -> Int {
typealias W = Workset.Schema
return db.scalar(W.table
.select(W.worksetID.count)
.filter(W.startTime.localDay >= date))
}
func totalReps(sinceDate date: NSDate) -> Int? {
typealias W = Workset.Schema
return db.scalar(W.table
.select(W.reps.sum)
.filter(W.startTime.localDay >= date))
}
func totalVolume(sinceDate date: NSDate) -> Double? {
typealias W = Workset.Schema
let query: ScalarQuery = W.table.select(W.volume.sum)
return db.scalar(query.filter(W.startTime.localDay >= date))
}
func totalPRs(sinceDate date: NSDate) -> Int {
typealias W = Workset.Schema
return db.scalar(W.table
.select(W.worksetID.count)
.filter(W.startTime.localDay >= date &&
(W.intensity > 1.0 || W.intensity > 1.0)))
}
func volumeByDay() throws -> [(NSDate, Double)] {
let cal = NSCalendar.currentCalendar()
return try all(Workout).map { workout in
let date = cal.startOfDayForDate(workout.startTime)
return (date, workout.volume ?? 0)
}
}
}
|
fce59cbfe451a094071db0b672047686
| 37.753968 | 121 | 0.54915 | false | false | false | false |
brentvatne/react-native-video
|
refs/heads/master
|
ios/Video/Features/RCTVideoSave.swift
|
mit
|
1
|
import AVFoundation
enum RCTVideoSave {
static func save(
options:NSDictionary!,
resolve: @escaping RCTPromiseResolveBlock,
reject:@escaping RCTPromiseRejectBlock,
playerItem: AVPlayerItem?
) {
let asset:AVAsset! = playerItem?.asset
guard asset != nil else {
reject("ERROR_ASSET_NIL", "Asset is nil", nil)
return
}
guard let exportSession = AVAssetExportSession(asset: asset, presetName:AVAssetExportPresetHighestQuality) else {
reject("ERROR_COULD_NOT_CREATE_EXPORT_SESSION", "Could not create export session", nil)
return
}
var path:String! = nil
path = RCTVideoSave.generatePathInDirectory(
directory: URL(fileURLWithPath: RCTVideoSave.cacheDirectoryPath() ?? "").appendingPathComponent("Videos").path,
withExtension: ".mp4")
let url:NSURL! = NSURL.fileURL(withPath: path) as NSURL
exportSession.outputFileType = AVFileType.mp4
exportSession.outputURL = url as URL?
exportSession.videoComposition = playerItem?.videoComposition
exportSession.shouldOptimizeForNetworkUse = true
exportSession.exportAsynchronously(completionHandler: {
switch (exportSession.status) {
case .failed:
reject("ERROR_COULD_NOT_EXPORT_VIDEO", "Could not export video", exportSession.error)
break
case .cancelled:
reject("ERROR_EXPORT_SESSION_CANCELLED", "Export session was cancelled", exportSession.error)
break
default:
resolve(["uri": url.absoluteString])
break
}
})
}
static func generatePathInDirectory(directory: String?, withExtension `extension`: String?) -> String? {
let fileName = UUID().uuidString + (`extension` ?? "")
RCTVideoSave.ensureDirExists(withPath: directory)
return URL(fileURLWithPath: directory ?? "").appendingPathComponent(fileName).path
}
static func cacheDirectoryPath() -> String? {
let array = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).map(\.path)
return array[0]
}
static func ensureDirExists(withPath path: String?) -> Bool {
var isDir: ObjCBool = false
var error: Error?
let exists = FileManager.default.fileExists(atPath: path ?? "", isDirectory: &isDir)
if !(exists && isDir.boolValue) {
do {
try FileManager.default.createDirectory(atPath: path ?? "", withIntermediateDirectories: true, attributes: nil)
} catch {
}
if error != nil {
return false
}
}
return true
}
}
|
b4318b1bbd048f286a645e77ab005358
| 37.226667 | 127 | 0.598884 | false | false | false | false |
raptorxcz/Rubicon
|
refs/heads/main
|
Rubicon/FileReaderImpl.swift
|
mit
|
1
|
//
// FileReaderImpl.swift
// Rubicon
//
// Created by Kryštof Matěj on 08/05/2017.
// Copyright © 2017 Kryštof Matěj. All rights reserved.
//
import Foundation
public class FileReaderImpl: FileReader {
public func readFiles(at path: String) -> [String] {
let fileNames = findFileNames(at: path)
let contentOfFiles = fileNames.compactMap({ try? String(contentsOfFile: $0, encoding: .utf8) })
return contentOfFiles
}
private func findFileNames(at path: String) -> [String] {
let fileManager = FileManager.default
var fileNames = [String]()
let items = try! FileManager.default.contentsOfDirectory(atPath: path)
for fileName in items {
let itemPath = path + "/" + fileName
var isDir: ObjCBool = false
if fileManager.fileExists(atPath: itemPath, isDirectory: &isDir) {
if isDir.boolValue {
fileNames += findFileNames(at: itemPath)
} else {
if fileName.hasSuffix(".swift") {
fileNames.append(itemPath)
}
}
}
}
return fileNames
}
}
|
84485b5c56e76520012d7ff40e5b364c
| 27.093023 | 103 | 0.570364 | false | false | false | false |
xmartlabs/Bender
|
refs/heads/master
|
Sources/Core/ParameterDataSource.swift
|
mit
|
1
|
//
// ParameterDataSource.swift
// MetalBender
//
// Created by Mathias Claassen on 4/2/18.
//
import MetalPerformanceShaders
@available(iOS 11.0, *)
public class ConvolutionDataSource: NSObject, MPSCNNConvolutionDataSource {
public func copy(with zone: NSZone? = nil) -> Any {
if let parameterLoader = parameterLoader {
return ConvolutionDataSource(cnnDescriptor: cnnDescriptor, parameterLoader: parameterLoader, layerId: layerId, weightCount: weightCount, biasCount: biasCount, useHalf: useHalf)
} else {
return ConvolutionDataSource(cnnDescriptor: cnnDescriptor, weights: weightsPointer, bias: biasPointer, useHalf: useHalf)
}
}
var useHalf: Bool
var cnnDescriptor: MPSCNNConvolutionDescriptor
var weightsPointer: UnsafeMutableRawPointer?
var biasPointer: UnsafeMutablePointer<Float>?
var parameterLoader: ParameterLoader?
var layerId: String = ""
var weightCount: Int = -1, biasCount: Int = -1
public init(cnnDescriptor: MPSCNNConvolutionDescriptor, weights: UnsafeMutableRawPointer?,
bias: UnsafeMutablePointer<Float>?, useHalf: Bool = false) {
self.useHalf = useHalf
self.cnnDescriptor = cnnDescriptor
self.weightsPointer = weights
self.biasPointer = bias
}
public init(cnnDescriptor: MPSCNNConvolutionDescriptor, parameterLoader: ParameterLoader, layerId: String,
weightCount: Int, biasCount: Int, useHalf: Bool = false) {
self.useHalf = useHalf
self.cnnDescriptor = cnnDescriptor
self.layerId = layerId
self.weightCount = weightCount
self.biasCount = biasCount
self.parameterLoader = parameterLoader
}
public func dataType() -> MPSDataType {
return useHalf ? .float16 : .float32
}
public func weights() -> UnsafeMutableRawPointer {
return weightsPointer!
}
public func descriptor() -> MPSCNNConvolutionDescriptor {
return cnnDescriptor
}
public func biasTerms() -> UnsafeMutablePointer<Float>? {
guard let bias = biasPointer else {
return nil
}
return bias
}
public func load() -> Bool {
if let parameterLoader = parameterLoader {
biasPointer = UnsafeMutablePointer(mutating: parameterLoader.loadWeights(for: layerId,
modifier: Convolution.biasModifier,
size: biasCount))
weightsPointer = UnsafeMutableRawPointer(mutating: parameterLoader.loadWeights(for: layerId,
modifier: Convolution.weightModifier,
size: weightCount))
}
return true
}
public func purge() {
if parameterLoader != nil {
biasPointer = nil
weightsPointer = nil
}
}
public func label() -> String? {
return nil
}
}
|
8f14ea1f24c2d2886fb7878ccf669f15
| 34.355556 | 188 | 0.59648 | false | false | false | false |
qingcai518/MyReader_ios
|
refs/heads/develop
|
MyReader/CloudController.swift
|
mit
|
1
|
//
// CloudController.swift
// MyReader
//
// Created by RN-079 on 2017/02/20.
// Copyright © 2017年 RN-079. All rights reserved.
//
import UIKit
import MJRefresh
import Kingfisher
class CloudController: ViewController {
@IBOutlet weak var tableView : UITableView!
let model = CloudModel()
var header : MJRefreshGifHeader!
var footer : MJRefreshAutoNormalFooter!
var currentInfo : CloudBookInfo!
override func viewDidLoad() {
super.viewDidLoad()
createIndicator()
setRefreshHeaderAndFooter()
setTableView()
getData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
private func setRefreshHeaderAndFooter() {
header = MJRefreshGifHeader(refreshingTarget: self, refreshingAction: #selector(getData))
footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(getMoreData))
header.setImages(AppUtility.getIdleImages(), for: .idle)
header.setImages(AppUtility.getPullingImages(), for: .pulling)
header.setImages(AppUtility.getRefreshingImages(), duration: 1, for: .refreshing)
footer.isHidden = true
tableView.mj_header = header
tableView.mj_footer = footer
}
private func setTableView() {
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
}
func getData() {
startIndicator()
model.getCloudBooks { [weak self] msg in
self?.header.endRefreshing()
self?.stopIndicator()
if let errorMsg = msg {
print("error = \(errorMsg)")
} else {
self?.footer.isHidden = false
}
self?.tableView.reloadData()
}
}
func getMoreData() {
model.getMoreCloudBooks { [weak self] (msg, isLast) in
self?.footer.endRefreshing()
self?.footer.isHidden = isLast
if let errorMsg = msg {
print("error = \(errorMsg)")
}
self?.tableView.reloadData()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "ToCloudDetail") {
guard let next = segue.destination as? CloudDetailController else {
return
}
next.bookInfo = currentInfo
next.hidesBottomBarWhenPushed = true
}
}
}
extension CloudController : UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 144
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
currentInfo = model.cloudBooks[indexPath.row]
self.performSegue(withIdentifier: "ToCloudDetail", sender: nil)
}
}
extension CloudController : UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return model.cloudBooks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let info = model.cloudBooks[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "CloudCell", for: indexPath) as! CloudCell
cell.bookNameLbl.text = info.bookName
cell.bookImgView.kf.setImage(with: URL(string: info.bookImgUrl))
cell.authorNameLbl.text = info.authorName
cell.detailLbl.text = info.detail
cell.cosmosView.rating = info.rating
cell.cosmosView.text = String(info.rating)
return cell
}
}
|
380ca86776be28f86ef304fda63901d2
| 29.607692 | 108 | 0.615481 | false | false | false | false |
AnthonyMDev/AmazonS3RequestManager
|
refs/heads/develop
|
Source/AmazonS3RequestManager/Region.swift
|
mit
|
2
|
//
// Region.swift
//
// Created by Anthony Miller on 1/17/17.
// Copyright (c) 2017 App-Order, LLC. All rights reserved.
//
import Foundation
/**
MARK: Amazon S3 Regions
The possible Amazon Web Service regions for the client.
- USStandard: N. Virginia or Pacific Northwest
- USWest1: Oregon
- USWest2: N. California
- EUWest1: Ireland
- EUCentral1: Frankfurt
- APSoutheast1: Singapore
- APSoutheast2: Sydney
- APNortheast1: Toyko
- APNortheast2: Seoul
- SAEast1: Sao Paulo
*/
public enum Region: Equatable {
case USStandard,
USWest1,
USWest2,
EUWest1,
EUCentral1,
APSoutheast1,
APSoutheast2,
APNortheast1,
APNortheast2,
SAEast1,
custom(hostName: String, endpoint: String)
var hostName: String {
switch self {
case .USStandard: return "us-east-1"
case .USWest1: return "us-west-1"
case .USWest2: return "us-west-2"
case .EUWest1: return "eu-west-1"
case .EUCentral1: return "eu-central-1"
case .APSoutheast1: return "ap-southeast-1"
case .APSoutheast2: return "ap-southeast-2"
case .APNortheast1: return "ap-northeast-1"
case .APNortheast2: return "ap-northeast-2"
case .SAEast1: return "sa-east-1"
case .custom(let hostName, _): return hostName
}
}
var endpoint: String {
switch self {
case .USStandard: return "s3.amazonaws.com"
case .USWest1: return "s3-us-west-1.amazonaws.com"
case .USWest2: return "s3-us-west-2.amazonaws.com"
case .EUWest1: return "s3-eu-west-1.amazonaws.com"
case .EUCentral1: return "s3-eu-central-1.amazonaws.com"
case .APSoutheast1: return "s3-ap-southeast-1.amazonaws.com"
case .APSoutheast2: return "s3-ap-southeast-2.amazonaws.com"
case .APNortheast1: return "s3-ap-northeast-1.amazonaws.com"
case .APNortheast2: return "s3-ap-northeast-2.amazonaws.com"
case .SAEast1: return "s3-sa-east-1.amazonaws.com"
case .custom(_, let endpoint): return endpoint
}
}
}
public func ==(lhs: Region, rhs: Region) -> Bool {
switch (lhs, rhs) {
case (.USStandard, .USStandard),
(.USWest1, .USWest1),
(.USWest2, .USWest2),
(.EUWest1, .EUWest1),
(.EUCentral1, .EUCentral1),
(.APSoutheast1, .APSoutheast1),
(.APSoutheast2, .APSoutheast2),
(.APNortheast1, .APNortheast1),
(.APNortheast2, .APNortheast2),
(.SAEast1, .SAEast1):
return true
case (.custom(let host1, let endpoint1), .custom(let host2, let endpoint2)):
return host1 == host2 && endpoint1 == endpoint2
default:
return false
}
}
|
825623c3cec4407032a71e8f44f25d17
| 29.247312 | 80 | 0.605759 | false | false | false | false |
netprotections/atonecon-ios
|
refs/heads/master
|
AtoneConTests/StringTests.swift
|
mit
|
1
|
//
// StringTest.swift
// AtoneCon
//
// Created by Pham Ngoc Hanh on 8/18/17.
// Copyright © 2017 AsianTech Inc. All rights reserved.
//
import XCTest
@testable import AtoneCon
final class StringTests: XCTestCase {
func testLocalizedShouldReturnStringResultWhenItWasDefinedInLocalizableString() {
// When "okay" was defined is "OK" in localizable.strings
let okay = "okay"
let network = "network"
let cancel = "cancel"
let close = "close"
let quitPayment = "quitPayment"
let networkError = "networkError"
// Then
XCTAssertEqual(okay.localized(), "OK")
XCTAssertEqual(network.localized(), "ネットワーク")
XCTAssertEqual(cancel.localized(), "キャンセル")
XCTAssertEqual(close.localized(), "閉じる")
XCTAssertEqual(quitPayment.localized(), "決済が終了します。よろしいでしょうか?")
XCTAssertEqual(networkError.localized(), "ネットワークが圏外です")
}
}
|
08a4ae813481930e5248993bd8f5b5b0
| 29.16129 | 85 | 0.657754 | false | true | false | false |
tapglue/ios_sdk
|
refs/heads/master
|
Sources/RxTapglue.swift
|
apache-2.0
|
2
|
//
// Tapglue.swift
// Tapglue
//
// Created by John Nilsen on 6/27/16.
// Copyright © 2016 Tapglue. All rights reserved.
//
import Foundation
import RxSwift
/// Provides a RxSwift interface to the tapglue sdk
open class RxTapglue {
var userStore = UserStore()
var network: Network
open fileprivate(set) var currentUser: User? {
get {
return userStore.user
}
set {
userStore.user = newValue
}
}
/// Constructs instance of RxTapglue
/// - parameter configuration: Configuration to be used
public init(configuration: Configuration) {
Router.configuration = configuration
Log.isDebug = configuration.log
network = Network()
if let sessionToken = currentUser?.sessionToken {
Router.sessionToken = sessionToken
}
}
/// creates a user on tapglue
/// - parameter user: user to be created
/// - parameter inviteConnections: optional - if user has been invited through friend/follow
/// - Note: username or email is required, password is required
/// - Note: does not login user
/// - Note: inviteConnection may be used when providing social_ids to the user object
/// to create a pending connection to people who invited that specific social id
open func createUser(_ user: User, inviteConnections: String? = nil) -> Observable<User> {
return network.createUser(user, inviteConnections: inviteConnections)
}
/// logs in user on tapglue
/// - parameter username: username of the user to be logged in
/// - parameter password: password of the user to be logged in
open func loginUser(_ username: String, password: String) -> Observable<User> {
return network.loginUser(username, password: password).map(toCurrentUserMap)
}
/// logs in user on tapglue
/// - parameter email: email of the user to be logged in
/// - parameter password: password of the user to be logged in
open func loginUserWithEmail(_ email: String, password: String) -> Observable<User> {
return network.loginUserWithEmail(email, password: password).map(toCurrentUserMap)
}
/// update information on the current user by providing a user entity
/// - parameter user: entity with the information to be updated
open func updateCurrentUser(_ user: User) -> Observable<User> {
return network.updateCurrentUser(user).map(toCurrentUserMap)
}
/// refreshes locally stored copy of the current user
open func refreshCurrentUser() -> Observable<User> {
return network.refreshCurrentUser().map(toCurrentUserMap)
}
/// creates an invite with a socialid key and value
/// - parameter key: social id name or custom key
/// - parameter key: social id value or custom value
open func createInvite(_ key: String, _ value: String) -> Observable<Void> {
return network.createInvite(key, value)
}
/// logs out the current user
open func logout() -> Observable<Void> {
return network.logout().do(onCompleted: {
self.currentUser = nil
})
}
/// deletes current user from tapglue
open func deleteCurrentUser() -> Observable<Void> {
return network.deleteCurrentUser().do(onCompleted: {
self.currentUser = nil
})
}
/// search for users on tapglue
/// - parameter searchTerm: term to search for
@available(*, deprecated: 2.1)
open func searchUsersForSearchTerm(_ term: String) -> Observable<[User]> {
return network.searchUsers(forSearchTerm: term)
}
/// Search tapglue for users with emails
/// - parameter emails: search tapglue for users with emails within this list
@available(*, deprecated: 2.1)
open func searchEmails(_ emails: [String]) -> Observable<[User]> {
return network.searchEmails(emails)
}
/// Search tapglue for users with social ids
/// - parameter ids: list of ids to search for
/// - parameter platform: platform name for which the search is performed
@available(*, deprecated: 2.1)
open func searchSocialIds(_ ids: [String], onPlatform platform: String) ->
Observable<[User]> {
return network.searchSocialIds(ids, onPlatform: platform)
}
/// create connection on tapglue
/// - parameter connection: connection to be created
open func createConnection(_ connection: Connection) -> Observable<Connection> {
return network.createConnection(connection)
}
/// delete connection on tapglue
/// - parameter userId: user id of the user the connection is
/// - parameter type: the type of connection to be deleted
open func deleteConnection(toUserId userId: String, type: ConnectionType)
-> Observable<Void> {
return network.deleteConnection(toUserId: userId, type: type)
}
/// create connections to users by using their ids from another platform
/// - parameter socialConnections: contains the platform name and list of ids
@available(*, deprecated: 2.1)
open func createSocialConnections(_ socialConnections: SocialConnections) ->
Observable<[User]> {
return network.createSocialConnections(socialConnections)
}
/// retrieves the followers of the current user
@available(*, deprecated: 2.1)
open func retrieveFollowers() -> Observable<[User]> {
return network.retrieveFollowers()
}
/// retrieves the users followed by the current user
@available(*, deprecated: 2.1)
open func retrieveFollowings() -> Observable<[User]> {
return network.retrieveFollowings()
}
/// retrieves followers for a given user
/// - parameter id: followers of the user of the given id
@available(*, deprecated: 2.1)
open func retrieveFollowersForUserId(_ id: String) -> Observable<[User]> {
return network.retrieveFollowersForUserId(id)
}
/// retrieves users followed by a given user
/// - parameter id: followings of the user of the given id
@available(*, deprecated: 2.1)
open func retrieveFollowingsForUserId(_ id: String) -> Observable<[User]> {
return network.retrieveFollowingsForUserId(id)
}
/// retrieve friends for current user
@available(*, deprecated: 2.1)
open func retrieveFriends() -> Observable<[User]> {
return network.retrieveFriends()
}
/// Retrieve friends for a given user
/// - parameter id: friends of the user with the given id
@available(*, deprecated: 2.1)
open func retrieveFriendsForUserId(_ id: String) -> Observable<[User]> {
return network.retrieveFriendsForUserId(id)
}
/// retrieve pending connections
@available(*, deprecated: 2.1)
open func retrievePendingConnections() -> Observable<Connections> {
return network.retrievePendingConnections()
}
/// retrieve rejected connections
@available(*, deprecated: 2.1)
open func retrieveRejectedConnections() -> Observable<Connections> {
return network.retrieveRejectedConnections()
}
/// retrieve a user
/// - parameter id: id of the user to be retrieved
open func retrieveUser(_ id: String) -> Observable<User> {
return network.retrieveUser(id)
}
/// creates post
/// - parameter post: post to be created
open func createPost(_ post: Post) -> Observable<Post> {
return network.createPost(post)
}
/// retrieve a post
/// - parameter id: id of the post to be retrieved
open func retrievePost(_ id: String) -> Observable<Post> {
return network.retrievePost(id)
}
/// update post
/// - parameter post: the post to replace the old one
/// - note: post id must be set on the post object
open func updatePost(_ id: String, post: Post) -> Observable<Post> {
return network.updatePost(id, post: post)
}
/// delete post
/// - parameter id: id of the post to be deleted
open func deletePost(_ id: String) -> Observable<Void> {
return network.deletePost(id)
}
/// retrieve posts created by a user
/// - parameter userId: id of the user from whom the posts will be retrieved
@available(*, deprecated: 2.1)
open func retrievePostsByUser(_ userId: String) -> Observable<[Post]> {
return network.retrievePostsByUser(userId)
}
/// retrieves all public and global posts
@available(*, deprecated: 2.1)
open func retrieveAllPosts() -> Observable<[Post]> {
return network.retrieveAllPosts()
}
/// Retrieves posts that have all the tags in the tags list. The query behaves like a logical
/// `and` operation
/// - parameter tags: tags to filter
@available(*, deprecated: 2.1)
open func filterPostsByTags(_ tags: [String]) -> Observable<[Post]> {
return network.filterPostsByTags(tags)
}
/// Creates a comment on a post
open func createComment(_ comment: Comment) -> Observable<Comment> {
return network.createComment(comment)
}
/// retrieve comments on a post
@available(*, deprecated: 2.1)
open func retrieveComments(_ postId: String) -> Observable<[Comment]> {
return network.retrieveComments(postId)
}
/// updates comment
/// - parameter postId: post to which the comment belongs
/// - parameter commentId: id of the comment to be updated
/// - parameter comment: the new comment to replace the old
open func updateComment(_ postId: String, commentId: String, comment: Comment) ->
Observable<Comment> {
return network.updateComment(postId, commentId: commentId, comment: comment)
}
/// deletes comment
/// - parameter postId: post to which the comment belongs
/// - parameter commentId: id of the comment to be deleted
open func deleteComment(forPostId postId: String, commentId: String) -> Observable<Void> {
return network.deleteComment(postId, commentId: commentId)
}
/// creates like
/// - parameter postId: post to be liked
@available(*, deprecated: 2.2)
open func createLike(forPostId postId: String) -> Observable<Like> {
return network.createLike(forPostId: postId)
}
/// creates reaction on a post
/// - parameter reaction: the reaction to be created. Check corresponding class for more
/// information
/// - forPostId: post on which the reaction is created
open func createReaction(_ reaction: Reaction, forPostId postId: String) -> Observable<Void> {
return network.createReaction(reaction, forPostId: postId);
}
/// deletes reaction
/// - parameter reaction: the reaction to be deleted. Check corresponding class for more
/// information
/// - forPostId: post on which the reaction is deleted
open func deleteReaction(_ reaction: Reaction, forPostId postId: String) -> Observable<Void> {
return network.deleteReaction(reaction, forPostId: postId)
}
/// retrieves likes on a post
/// - parameter postId: id of the post
@available(*, deprecated: 2.1)
open func retrieveLikes(_ postId: String) -> Observable<[Like]> {
return network.retrieveLikes(postId)
}
/// delete like on a post
/// - parameter postId: post that was liked
open func deleteLike(forPostId postId: String) -> Observable<Void> {
return network.deleteLike(forPostId: postId)
}
@available(*, deprecated: 2.1)
open func retrieveLikesByUser(_ userId: String) -> Observable<[Like]> {
return network.retrieveLikesByUser(userId)
}
/// Retrieves activities created by a user
/// - parameter userId: user from whom you want the activities
@available(*, deprecated: 2.1)
open func retrieveActivitiesByUser(_ userId: String) -> Observable<[Activity]> {
return network.retrieveActivitiesByUser(userId)
}
/// retrieves post feed
@available(*, deprecated: 2.1)
open func retrievePostFeed() -> Observable<[Post]> {
return network.retrievePostFeed()
}
/// retrieves activity feed
/// - note: event feed on the api documentation
@available(*, deprecated: 2.1)
open func retrieveActivityFeed() -> Observable<[Activity]> {
return network.retrieveActivityFeed()
}
/// retrieves news feed
@available(*, deprecated: 2.1)
open func retrieveNewsFeed() -> Observable<NewsFeed> {
return network.retrieveNewsFeed()
}
/// retrieves a feed of activities tageting the current user
@available(*, deprecated: 2.1)
open func retrieveMeFeed() -> Observable<[Activity]> {
return network.retrieveMeFeed()
}
/// search for users on tapglue
/// - parameter searchTerm: term to search for
open func searchUsersForSearchTerm(_ term: String) -> Observable<RxPage<User>> {
return network.searchUsers(forSearchTerm: term)
}
/// Search tapglue for users with emails
/// - parameter emails: search tapglue for users with emails within this list
open func searchEmails(_ emails: [String]) -> Observable<RxPage<User>> {
return network.searchEmails(emails)
}
/// Search tapglue for users with social ids
/// - parameter ids: list of ids to search for
/// - parameter platform: platform name for which the search is performed
open func searchSocialIds(_ ids: [String], onPlatform platform: String) ->
Observable<RxPage<User>> {
return network.searchSocialIds(ids, onPlatform: platform)
}
/// create connections to users by using their ids from another platform
/// - parameter socialConnections: contains the platform name and list of ids
open func createSocialConnections(_ socialConnections: SocialConnections) ->
Observable<RxPage<User>> {
return network.createSocialConnections(socialConnections)
}
/// retrieves the followers of the current user
open func retrieveFollowers() -> Observable<RxPage<User>> {
return network.retrieveFollowers()
}
/// retrieves the users followed by the current user
open func retrieveFollowings() -> Observable<RxPage<User>> {
return network.retrieveFollowings()
}
/// retrieves followers for a given user
/// - parameter id: followers of the user of the given id
open func retrieveFollowersForUserId(_ id: String) -> Observable<RxPage<User>> {
return network.retrieveFollowersForUserId(id)
}
/// retrieves users followed by a given user
/// - parameter id: followings of the user of the given id
open func retrieveFollowingsForUserId(_ id: String) -> Observable<RxPage<User>> {
return network.retrieveFollowingsForUserId(id)
}
/// retrieve friends for current user
open func retrieveFriends() -> Observable<RxPage<User>> {
return network.retrieveFriends()
}
/// Retrieve friends for a given user
/// - parameter id: friends of the user with the given id
open func retrieveFriendsForUserId(_ id: String) -> Observable<RxPage<User>> {
return network.retrieveFriendsForUserId(id)
}
/// retrieve pending connections
open func retrievePendingConnections() -> Observable<RxCompositePage<Connections>> {
return network.retrievePendingConnections()
}
/// retrieve rejected connections
open func retrieveRejectedConnections() -> Observable<RxCompositePage<Connections>> {
return network.retrieveRejectedConnections()
}
/// retrieve posts created by a user
/// - parameter userId: id of the user from whom the posts will be retrieved
open func retrievePostsByUser(_ userId: String) -> Observable<RxPage<Post>> {
return network.retrievePostsByUser(userId)
}
/// retrieves all public and global posts
open func retrieveAllPosts() -> Observable<RxPage<Post>> {
return network.retrieveAllPosts()
}
/// Retrieves posts that have all the tags in the tags list. The query behaves like a logical
/// `and` operation
/// - parameter tags: tags to filter
open func filterPostsByTags(_ tags: [String]) -> Observable<RxPage<Post>> {
return network.filterPostsByTags(tags)
}
/// retrieve comments on a post
open func retrieveComments(_ postId: String) -> Observable<RxPage<Comment>> {
return network.retrieveComments(postId)
}
/// retrieves likes on a post
/// - parameter postId: id of the post
open func retrieveLikes(_ postId: String) -> Observable<RxPage<Like>> {
return network.retrieveLikes(postId)
}
open func retrieveLikesByUser(_ userId: String) -> Observable<RxPage<Like>> {
return network.retrieveLikesByUser(userId)
}
/// retrieves post feed
open func retrievePostFeed() -> Observable<RxPage<Post>> {
return network.retrievePostFeed()
}
/// retrieves activity feed
/// - note: event feed on the api documentation
open func retrieveActivityFeed() -> Observable<RxPage<Activity>> {
return network.retrieveActivityFeed()
}
/// retrieves a feed of activities tageting the current user
open func retrieveMeFeed() -> Observable<RxPage<Activity>> {
return network.retrieveMeFeed()
}
/// retrieves news feed
open func retrieveNewsFeed() -> Observable<RxCompositePage<NewsFeed>> {
return network.retrieveNewsFeed()
}
/// update count to backend
open func updateCount(newCount: Int, withNameSpace nameSpace: String) -> Observable<Void> {
return network.updateCount(newCount, nameSpace)
}
/// get count to backend
open func getCount(withNameSpace nameSpace: String) -> Observable<Count> {
return network.getCount(nameSpace)
}
fileprivate func toCurrentUserMap(_ user: User) -> User {
currentUser = user
return user
}
}
|
8b05be90378e3d56adf537d720524d9d
| 41.315166 | 98 | 0.671221 | false | false | false | false |
zhugejunwei/LeetCode
|
refs/heads/master
|
64. Minimum Path Sum.swift
|
mit
|
1
|
import Darwin
func minPathSum(grid: [[Int]]) -> Int {
var record = grid
let m = grid.count, n = grid[0].count
var i = 1
while i < m {
record[i][0] += record[i-1][0]
i += 1
}
var j = 1
while j < n {
record[0][j] += record[0][j-1]
j += 1
}
var row = 1
while row < m {
var col = 1
while col < n {
record[row][col] += min(record[row-1][col], record[row][col-1])
col += 1
}
row += 1
}
return record[m-1][n-1]
}
var a = [[1,5],[3,2]]
minPathSum(a)
|
8bea29e7a6c6de836e105f2225cdb061
| 18.366667 | 75 | 0.432759 | false | false | false | false |
iOSWizards/AwesomeMedia
|
refs/heads/master
|
AwesomeMedia/Classes/Controllers/AwesomeMediaVideoViewController.swift
|
mit
|
1
|
//
// AwesomeMediaVideoViewController.swift
// AwesomeMedia
//
// Created by Evandro Harrison Hoffmann on 4/4/18.
//
import UIKit
public class AwesomeMediaVideoViewController: UIViewController {
public static var presentingVideoInFullscreen = false
@IBOutlet public weak var playerView: AwesomeMediaView!
// Public variables
public var mediaParams = AwesomeMediaParams()
var controls: AwesomeMediaVideoControls = .all
var titleViewVisible: Bool = true
public override func viewDidLoad() {
super.viewDidLoad()
playerView.configure(withMediaParams: mediaParams,
controls: controls,
states: .standard,
trackingSource: .videoFullscreen,
titleViewVisible: titleViewVisible)
playerView.controlView?.fullscreenCallback = { [weak self] in
self?.close()
// track event
track(event: .toggleFullscreen, source: .videoFullscreen)
}
playerView.controlView?.jumpToCallback = { [weak self] in
guard let self = self else { return }
self.showMarkers(self.mediaParams.markers) { (mediaMarker) in
if let mediaMarker = mediaMarker {
sharedAVPlayer.seek(toTime: mediaMarker.time)
sharedAVPlayer.play()
}
}
}
playerView.titleView?.closeCallback = { [weak self] in
sharedAVPlayer.stop()
self?.close()
// track event
track(event: .closeFullscreen, source: .videoFullscreen)
track(event: .stoppedPlaying, source: .videoFullscreen)
}
playerView.finishedPlayingCallback = { [weak self] in
self?.close()
}
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// adds player layer in case it's not visible
playerView.addPlayerLayer()
}
public override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
AwesomeMediaVideoViewController.presentingVideoInFullscreen = false
// remove observers when leaving
playerView.removeObservers()
}
public override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
// track event
track(event: .changedOrientation, source: .audioFullscreen, value: UIApplication.shared.statusBarOrientation)
}
// MARK: Events
@IBAction func toggleControlsButtonPressed(_ sender: Any) {
playerView.controlView?.toggleViewIfPossible()
}
// MARK: - Marker Selected
public func markerSelected(marker: AwesomeMediaMarker) {
}
//to hide the bottom bar on iPhone X+ after a few seconds
override public var prefersHomeIndicatorAutoHidden: Bool {
return true
}
}
extension AwesomeMediaVideoViewController {
fileprivate func close() {
dismiss(animated: true) {
if AwesomeMedia.shouldStopVideoWhenCloseFullScreen {
sharedAVPlayer.stop()
AwesomeMedia.shouldStopVideoWhenCloseFullScreen = false
}
AwesomeMediaVideoViewController.presentingVideoInFullscreen = false
}
}
}
// MARK: - ViewController Initialization
extension AwesomeMediaVideoViewController {
public static var newInstance: AwesomeMediaVideoViewController {
let storyboard = UIStoryboard(name: "AwesomeMedia", bundle: AwesomeMedia.bundle)
return storyboard.instantiateViewController(withIdentifier: "AwesomeMediaVideoViewController") as! AwesomeMediaVideoViewController
}
}
extension UIViewController {
public func presentVideoFullscreen(withMediaParams mediaParams: AwesomeMediaParams,
withControls controls: AwesomeMediaVideoControls = .all,
titleViewVisible: Bool = true) {
guard !AwesomeMediaVideoViewController.presentingVideoInFullscreen else {
return
}
AwesomeMediaPlayerType.type = .video
AwesomeMediaVideoViewController.presentingVideoInFullscreen = true
let viewController = AwesomeMediaVideoViewController.newInstance
viewController.mediaParams = mediaParams
viewController.controls = controls
viewController.titleViewVisible = titleViewVisible
interactor = AwesomeMediaInteractor()
viewController.modalPresentationStyle = .fullScreen
viewController.transitioningDelegate = self
viewController.interactor = interactor
self.present(viewController, animated: true, completion: nil)
}
}
|
5e73db34cf6bb429d9f6c295d5498012
| 34.330935 | 138 | 0.643861 | false | false | false | false |
crazypoo/ArcheryScoreBoard
|
refs/heads/master
|
OCAndSwift/SwiftClass/DetailledTarget.swift
|
mit
|
1
|
//
// DetailledTarget.swift
// ReperageFleche
//
// Created by Rémy Vermeersch on 23/04/2016.
// Copyright © 2016 Rémy Vermeersch . All rights reserved.
//
import UIKit
class DetailledTarget: BaseViewController {
var arrow : Arrow!
var reperageViews = [CrossMarkerView]()
var targetImageView: UIImageView!
var endCountLabel: UILabel!
var scoreLabel: UILabel!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
updateUI()
}
func updateUI() {
self.title = "箭落点: \((arrow?.arrowId)!+1)"
targetImageView = UIImageView.init(frame: CGRect.init(x: 20, y: 84, width: self.view.frame.size.width-40, height: self.view.frame.size.width-40))
targetImageView.image = UIImage.init(named: "TargetImage")
self.view.addSubview(targetImageView)
var scoreTotal : Int = 0
for i in (arrow?.shots)! {
let x:NSString = String(i.value) as NSString
if x.isEqual(to: "11") {
scoreTotal += 10
}
else
{
scoreTotal += i.value
}
}
endCountLabel = UILabel.init()
endCountLabel.textAlignment = .center
endCountLabel.text = "射击点数量: " + String(arrow.shots.count)
self.view.addSubview(endCountLabel)
endCountLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(self.view)
make.height.equalTo(30)
make.bottom.equalTo(self.view.snp.bottom).offset(-150)
}
scoreLabel = UILabel.init()
scoreLabel.textAlignment = .center
scoreLabel.text = "得分 : \(scoreTotal)"
self.view.addSubview(scoreLabel)
scoreLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(self.view)
make.height.equalTo(30)
make.top.equalTo(endCountLabel.snp.bottom)
}
updateMarkers((arrow?.shots)!)
}
func updateMarkers(_ shots : [Shot]){
for i in reperageViews {
i.removeFromSuperview()
}
reperageViews.removeAll()
for currentShot in shots {
reperageViews.append(CrossMarkerView(shot: currentShot, frame: targetImageView.bounds))
targetImageView.addSubview(reperageViews.last!)
}
}
}
|
050a2d15bba923952056743699ddfb90
| 26.655914 | 153 | 0.577372 | false | false | false | false |
williamshowalter/DOTlog_iOS
|
refs/heads/master
|
DOTlog/Error Handling/ErrorFactory.swift
|
mit
|
1
|
//
// ErrorFactory.swift
// DOTlog
//
// Created by William Showalter on 15/05/02.
// Copyright (c) 2015 UAF CS Capstone 2015. All rights reserved.
//
import Foundation
import UIKit
import CoreData
class ErrorFactory {
// Class that creates alerts given internally designated error codes and a view controller to present the errors to.
class func ErrorAlert (error: NSError, caller: UIViewController) -> UIAlertController {
let code = error.code
var errorTitle = "Unable to Sync"
var errorDetailTitle = "Error Code: \(code)"
var errorMessage : String? = "Contact Regional Aviation Office If Problem Persists."
var errorDetailMessage = error.localizedDescription
if let detailMessage : [NSObject : AnyObject] = error.userInfo {
if let errorDetailMessageText = detailMessage["NSLocalizedDescriptionKey"] as? String {
errorDetailMessage = "\(errorDetailMessageText)"
}
}
if code == 401 {
errorTitle = error.domain
errorMessage = nil
}
if code == 430 {
errorTitle = "Delete all events and sync before recreating"
errorMessage = "User does not have access to airports they are submitting for."
}
if code == 431 {
errorTitle = "Delete all events and sync before recreating"
errorMessage = "Airport not found in database."
}
if code == 432 {
errorTitle = "Delete all events and sync before recreating"
errorMessage = "Category not found in database."
}
if code == 445 {
errorTitle = "Contact Supervisor - Account does not have access to DOTlog"
errorMessage = nil
}
if code == -1003 {
errorTitle = "Bad Address" // Needs to match page wording
errorMessage = "Confirm Address in Account Settings"
}
let errorAlert = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: UIAlertControllerStyle.Alert)
let errorAlertDetail = UIAlertController(title: errorDetailTitle, message: errorDetailMessage as String, preferredStyle: UIAlertControllerStyle.Alert)
errorAlert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Cancel, handler:{ (ACTION :UIAlertAction!)in }))
errorAlert.addAction(UIAlertAction(title: "Details", style: UIAlertActionStyle.Default, handler:{ (ACTION :UIAlertAction!)in caller.presentViewController(errorAlertDetail, animated: true, completion: nil)}))
errorAlertDetail.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Cancel, handler:{ (ACTION :UIAlertAction!)in }))
return errorAlert
}
}
|
ae57533347910a38a4567858b7f218f6
| 34.371429 | 209 | 0.742222 | false | false | false | false |
aksalj/Helium
|
refs/heads/master
|
Helium/HeliumShareExtension/ShareViewController.swift
|
mit
|
1
|
//
// ShareViewController.swift
// Share
//
// Created by Kyle Carson on 10/30/15.
// Copyright © 2015 Jaden Geller. All rights reserved.
//
import Cocoa
class ShareViewController: NSViewController {
override var nibName: String? {
return "ShareViewController"
}
override func viewDidLoad() {
if let item = self.extensionContext!.inputItems.first as? NSExtensionItem,
let attachment = item.attachments?.first as? NSItemProvider
where attachment.hasItemConformingToTypeIdentifier("public.url")
{
attachment.loadItemForTypeIdentifier("public.url", options: nil)
{
(url, error) in
if let url = url as? NSURL,
let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false)
{
components.scheme = "helium"
let heliumURL = components.URL!
NSWorkspace.sharedWorkspace().openURL( heliumURL )
}
}
self.extensionContext!.completeRequestReturningItems(nil, completionHandler: nil)
return
}
let error = NSError(domain: NSCocoaErrorDomain, code: NSURLErrorBadURL, userInfo: nil)
self.extensionContext!.cancelRequestWithError(error)
}
@IBAction func send(sender: AnyObject?) {
let outputItem = NSExtensionItem()
// Complete implementation by setting the appropriate value on the output item
let outputItems = [outputItem]
self.extensionContext!.completeRequestReturningItems(outputItems, completionHandler: nil)
}
@IBAction func cancel(sender: AnyObject?) {
let cancelError = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil)
self.extensionContext!.cancelRequestWithError(cancelError)
}
}
|
4850292a12b128d47305aa82c2533454
| 26.459016 | 98 | 0.721791 | false | false | false | false |
XCEssentials/UniFlow
|
refs/heads/master
|
.setup/Setup/main.swift
|
mit
|
2
|
import PathKit
import XCERepoConfigurator
// MARK: - PRE-script invocation output
print("\n")
print("--- BEGIN of '\(Executable.name)' script ---")
// MARK: -
// MARK: Parameters
Spec.BuildSettings.swiftVersion.value = "5.3"
let localRepo = try Spec.LocalRepo.current()
let remoteRepo = try Spec.RemoteRepo(
accountName: localRepo.context,
name: localRepo.name
)
let travisCI = (
address: "https://travis-ci.com/\(remoteRepo.accountName)/\(remoteRepo.name)",
branch: "master"
)
let company = (
prefix: "XCE",
name: remoteRepo.accountName
)
let project = (
name: remoteRepo.name,
summary: "Uni-directional data flow & finite state machine merged together",
copyrightYear: 2016
)
let productName = company.prefix + project.name
let authors = [
("Maxim Khatskevich", "[email protected]")
]
typealias PerSubSpec<T> = (
core: T,
tests: T
)
let subSpecs: PerSubSpec = (
"Core",
"AllTests"
)
let targetNames: PerSubSpec = (
productName,
productName + subSpecs.tests
)
let sourcesLocations: PerSubSpec = (
Spec.Locations.sources + subSpecs.core,
Spec.Locations.tests + subSpecs.tests
)
// MARK: Parameters - Summary
localRepo.report()
remoteRepo.report()
// MARK: -
// MARK: Write - ReadMe
try ReadMe()
.addGitHubLicenseBadge(
account: company.name,
repo: project.name
)
.addGitHubTagBadge(
account: company.name,
repo: project.name
)
.addSwiftPMCompatibleBadge()
.addWrittenInSwiftBadge(
version: Spec.BuildSettings.swiftVersion.value
)
.addStaticShieldsBadge(
"platforms",
status: "macOS | iOS | tvOS | watchOS | Linux",
color: "blue",
title: "Supported platforms",
link: "Package.swift"
)
.add("""
[.svg?branch=\(travisCI.branch))](\(travisCI.address))
"""
)
.add("""
# \(project.name)
\(project.summary)
"""
)
.prepare(
removeRepeatingEmptyLines: false
)
.writeToFileSystem(
ifFileExists: .skip
)
// MARK: Write - License
try License
.MIT(
copyrightYear: UInt(project.copyrightYear),
copyrightEntity: authors.map{ $0.0 }.joined(separator: ", ")
)
.prepare()
.writeToFileSystem()
// MARK: Write - GitHub - PagesConfig
try GitHub
.PagesConfig()
.prepare()
.writeToFileSystem()
// MARK: Write - Git - .gitignore
try Git
.RepoIgnore()
.addMacOSSection()
.addCocoaSection()
.addSwiftPackageManagerSection(ignoreSources: true)
.add(
"""
# we don't need to store project file,
# as we generate it on-demand
*.\(Xcode.Project.extension)
"""
)
.prepare()
.writeToFileSystem()
// MARK: Write - Package.swift
let dependencies = (
requirement: (
name: """
XCERequirement
""",
swiftPM: """
.package(name: "XCERequirement", url: "https://github.com/XCEssentials/Requirement", from: "2.0.0")
"""
),
pipeline: (
name: """
XCEPipeline
""",
swiftPM: """
.package(name: "XCEPipeline", url: "https://github.com/XCEssentials/Pipeline", from: "3.0.0")
"""
),
swiftHamcrest: (
name: """
SwiftHamcrest
""",
swiftPM: """
.package(name: "SwiftHamcrest", url: "https://github.com/nschum/SwiftHamcrest", from: "2.1.1")
"""
)
)
try CustomTextFile("""
// swift-tools-version:\(Spec.BuildSettings.swiftVersion.value)
import PackageDescription
let package = Package(
name: "\(productName)",
products: [
.library(
name: "\(productName)",
targets: [
"\(targetNames.core)"
]
)
],
dependencies: [
\(dependencies.requirement.swiftPM),
\(dependencies.pipeline.swiftPM),
\(dependencies.swiftHamcrest.swiftPM)
],
targets: [
.target(
name: "\(targetNames.core)",
dependencies: [
"\(dependencies.requirement.name)",
"\(dependencies.pipeline.name)"
],
path: "\(sourcesLocations.core)"
),
.testTarget(
name: "\(targetNames.tests)",
dependencies: [
"\(targetNames.core)",
"\(dependencies.requirement.name)",
"\(dependencies.pipeline.name)",
"\(dependencies.swiftHamcrest.name)"
],
path: "\(sourcesLocations.tests)"
),
]
)
"""
)
.prepare(
at: ["Package.swift"]
)
.writeToFileSystem()
// MARK: - POST-script invocation output
print("--- END of '\(Executable.name)' script ---")
|
7bcfa86e46efec2455a3a051f1bc3e0e
| 21.269912 | 111 | 0.546791 | false | false | false | false |
groomsy/odot-ios
|
refs/heads/master
|
OdOt/AuthenticationViewController.swift
|
mit
|
1
|
//
// AuthenticationViewController.swift
// OdOt
//
// Created by Todd Grooms on 9/25/14.
// Copyright (c) 2014 Todd Grooms. All rights reserved.
//
import Alamofire
import UIKit
class AuthenticationViewController: UITableViewController, UITextFieldDelegate {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
var endpoint: String!
var authenticateUserDelegate: AuthenticateUserProtocol?
func contentSizeCategoryChanged(notification: NSNotification) {
self.tableView.reloadData()
}
func dismiss() {
if let delegate = self.authenticateUserDelegate {
delegate.authenticatedUser(User(id: "some_id"))
}
}
func submitRequest() {
self.tableView.deselectRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1), animated: true)
self.usernameTextField.resignFirstResponder()
self.passwordTextField.resignFirstResponder()
self.tableView.userInteractionEnabled = false
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let delay = 2 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) { () -> Void in
let parameters = [
"username": self.usernameTextField.text,
"password": self.passwordTextField.text
]
Alamofire.request(.POST, self.endpoint, parameters: parameters)
.responseJSON({ (NSURLRequest request, NSHTTPURLResponse response, JSON json, NSError error) -> Void in
self.tableView.userInteractionEnabled = true
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
self.dismiss()
})
}
}
func userInformationPresent() -> Bool {
return countElements(self.usernameTextField.text) > 0 && countElements(self.passwordTextField.text) > 0
}
// MARK: View Lifecycle Methods
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 44
self.tableView.rowHeight = UITableViewAutomaticDimension
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "contentSizeCategoryChanged:", name: UIContentSizeCategoryDidChangeNotification, object: nil)
self.tableView.reloadData()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIContentSizeCategoryDidChangeNotification, object: nil)
}
// MARK: UITableViewDelegate Methods
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if ( indexPath.section == 1 && self.userInformationPresent() ) || indexPath.section == 2 {
return indexPath
}
return nil
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 0 {
if indexPath.item == 0 {
self.usernameTextField.becomeFirstResponder()
} else {
self.passwordTextField.becomeFirstResponder()
}
} else if indexPath.section == 1 {
self.submitRequest()
}
}
// MARK: UITextFieldDelegate Methods
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == self.usernameTextField {
self.passwordTextField.becomeFirstResponder()
} else {
self.passwordTextField.resignFirstResponder()
self.submitRequest()
}
return true
}
}
|
ade9828e050992e026d8620852148362
| 33.681034 | 166 | 0.642555 | false | false | false | false |
calkinssean/TIY-Assignments
|
refs/heads/master
|
Day 21/SpotifyAPI/Pods/StarWars/StarWars/StarWarsGLAnimator/ViewTexture.swift
|
cc0-1.0
|
4
|
//
// Created by Artem Sidorenko on 10/9/15.
// Copyright © 2015 Yalantis. All rights reserved.
//
// Licensed under the MIT license: http://opensource.org/licenses/MIT
// Latest version can be found at https://github.com/Yalantis/StarWars.iOS
//
import UIKit
class ViewTexture {
var name: GLuint = 0
var width: GLsizei = 0
var height: GLsizei = 0
func setupOpenGL() {
glGenTextures(1, &name)
glBindTexture(GLenum(GL_TEXTURE_2D), name)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GLint(GL_LINEAR))
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GLint(GL_LINEAR))
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GLint(GL_CLAMP_TO_EDGE))
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GLint(GL_CLAMP_TO_EDGE))
glBindTexture(GLenum(GL_TEXTURE_2D), 0);
}
deinit {
if name != 0 {
glDeleteTextures(1, &name)
}
}
func renderView(view: UIView) {
let scale = UIScreen.mainScreen().scale
width = GLsizei(view.layer.bounds.size.width * scale)
height = GLsizei(view.layer.bounds.size.height * scale)
var texturePixelBuffer = [GLubyte](count: Int(height * width * 4), repeatedValue: 0)
let colorSpace = CGColorSpaceCreateDeviceRGB()
withUnsafeMutablePointer(&texturePixelBuffer[0]) { texturePixelBuffer in
let context = CGBitmapContextCreate(texturePixelBuffer,
Int(width), Int(height), 8, Int(width * 4), colorSpace,
CGImageAlphaInfo.PremultipliedLast.rawValue | CGBitmapInfo.ByteOrder32Big.rawValue)!
CGContextScaleCTM(context, scale, scale)
UIGraphicsPushContext(context)
view.drawViewHierarchyInRect(view.layer.bounds, afterScreenUpdates: false)
UIGraphicsPopContext()
glBindTexture(GLenum(GL_TEXTURE_2D), name);
glTexImage2D(GLenum(GL_TEXTURE_2D), 0, GLint(GL_RGBA), width, height, 0, GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), texturePixelBuffer)
glBindTexture(GLenum(GL_TEXTURE_2D), 0);
}
}
}
|
8470d64384a4f8560ca7f1345a93bf94
| 38.189655 | 147 | 0.635284 | false | false | false | false |
hfutrell/BezierKit
|
refs/heads/master
|
BezierKit/Library/BezierCurve.swift
|
mit
|
1
|
//
// BezierCurve.swift
// BezierKit
//
// Created by Holmes Futrell on 2/19/17.
// Copyright © 2017 Holmes Futrell. All rights reserved.
//
#if canImport(CoreGraphics)
import CoreGraphics
#endif
import Foundation
public struct Subcurve<CurveType> where CurveType: BezierCurve {
public let t1: CGFloat
public let t2: CGFloat
public let curve: CurveType
internal var canSplit: Bool {
let mid = 0.5 * (self.t1 + self.t2)
return mid > self.t1 && mid < self.t2
}
internal init(curve: CurveType) {
self.t1 = 0.0
self.t2 = 1.0
self.curve = curve
}
internal init(t1: CGFloat, t2: CGFloat, curve: CurveType) {
self.t1 = t1
self.t2 = t2
self.curve = curve
}
internal func split(from t1: CGFloat, to t2: CGFloat) -> Subcurve<CurveType> {
let curve: CurveType = self.curve.split(from: t1, to: t2)
return Subcurve<CurveType>(t1: Utils.map(t1, 0, 1, self.t1, self.t2),
t2: Utils.map(t2, 0, 1, self.t1, self.t2),
curve: curve)
}
internal func split(at t: CGFloat) -> (left: Subcurve<CurveType>, right: Subcurve<CurveType>) {
let (left, right) = curve.split(at: t)
let t1 = self.t1
let t2 = self.t2
let tSplit = Utils.map(t, 0, 1, t1, t2)
let subcurveLeft = Subcurve<CurveType>(t1: t1, t2: tSplit, curve: left)
let subcurveRight = Subcurve<CurveType>(t1: tSplit, t2: t2, curve: right)
return (left: subcurveLeft, right: subcurveRight)
}
}
extension Subcurve: Equatable where CurveType: Equatable {
// extension exists for automatic Equatable synthesis
}
// MARK: -
extension BezierCurve {
/*
Calculates the length of this Bezier curve. Length is calculated using numerical approximation, specifically the Legendre-Gauss quadrature algorithm.
*/
public func length() -> CGFloat {
return Utils.length({(_ t: CGFloat) in self.derivative(at: t)})
}
// MARK: -
public func hull(_ t: CGFloat) -> [CGPoint] {
return Utils.hull(self.points, t)
}
public func lookupTable(steps: Int = 100) -> [CGPoint] {
assert(steps >= 0)
return (0 ... steps).map {
let t = CGFloat($0) / CGFloat(steps)
return self.point(at: t)
}
}
// MARK: -
/*
Reduces a curve to a collection of "simple" subcurves, where a simpleness is defined as having all control points on the same side of the baseline (cubics having the additional constraint that the control-to-end-point lines may not cross), and an angle between the end point normals no greater than 60 degrees.
The main reason this function exists is to make it possible to scale curves. As mentioned in the offset function, curves cannot be offset without cheating, and the cheating is implemented in this function. The array of simple curves that this function yields can safely be scaled.
*/
public func reduce() -> [Subcurve<Self>] {
let step: CGFloat = BezierKit.reduceStepSize
var extrema: [CGFloat] = []
self.extrema().all.forEach {
if $0 < step {
return // filter out extreme points very close to 0.0
} else if (1.0 - $0) < step {
return // filter out extreme points very close to 1.0
} else if let last = extrema.last, $0 - last < step {
return
}
return extrema.append($0)
}
// aritifically add 0.0 and 1.0 to our extreme points
extrema.insert(0.0, at: 0)
extrema.append(1.0)
// first pass: split on extrema
let pass1: [Subcurve<Self>] = (0..<extrema.count-1).map {
let t1 = extrema[$0]
let t2 = extrema[$0+1]
let curve = self.split(from: t1, to: t2)
return Subcurve(t1: t1, t2: t2, curve: curve)
}
func bisectionMethod(min: CGFloat, max: CGFloat, tolerance: CGFloat, callback: (_ value: CGFloat) -> Bool) -> CGFloat {
var lb = min // lower bound (callback(x <= lb) should return true
var ub = max // upper bound (callback(x >= ub) should return false
while (ub - lb) > tolerance {
let val = 0.5 * (lb + ub)
if callback(val) {
lb = val
} else {
ub = val
}
}
return lb
}
// second pass: further reduce these segments to simple segments
var pass2: [Subcurve<Self>] = []
pass2.reserveCapacity(pass1.count)
pass1.forEach({(p1: Subcurve<Self>) in
let adjustedStep = step / (p1.t2 - p1.t1)
var t1: CGFloat = 0.0
while t1 < 1.0 {
let fullSegment = p1.split(from: t1, to: 1.0)
if (1.0 - t1) <= adjustedStep || fullSegment.curve.simple {
// if the step is small or the full segment is simple, use it
pass2.append(fullSegment)
t1 = 1.0
} else {
// otherwise use bisection method to find a suitable step size
let t2 = bisectionMethod(min: t1 + adjustedStep, max: 1.0, tolerance: adjustedStep) {
return p1.split(from: t1, to: $0).curve.simple
}
let partialSegment = p1.split(from: t1, to: t2)
pass2.append(partialSegment)
t1 = t2
}
}
})
return pass2
}
// MARK: -
/// Scales a curve with respect to the intersection between the end point normals. Note that this will only work if that intersection point exists, which is only guaranteed for simple segments.
/// - Parameter distance: desired distance the resulting curve should fall from the original (in the direction of its normals).
public func scale(distance: CGFloat) -> Self? {
let order = self.order
assert(order < 4, "only works with cubic or lower order")
guard order > 0 else { return self } // points cannot be scaled
let points = self.points
let n1 = self.normal(at: 0)
let n2 = self.normal(at: 1)
guard n1.x.isFinite, n1.y.isFinite, n2.x.isFinite, n2.y.isFinite else { return nil }
let origin = Utils.linesIntersection(self.startingPoint, self.startingPoint + n1, self.endingPoint, self.endingPoint - n2)
func scaledPoint(index: Int) -> CGPoint {
let referencePointIsStart = (index < 2 && order > 1) || (index == 0 && order == 1)
let referenceT: CGFloat = referencePointIsStart ? 0.0 : 1.0
let referenceIndex = referencePointIsStart ? 0 : self.order
let referencePoint = self.offset(t: referenceT, distance: distance)
switch index {
case 0, self.order:
return referencePoint
default:
let tangent = self.normal(at: referenceT).perpendicular
if let origin = origin, let intersection = Utils.linesIntersection(referencePoint, referencePoint + tangent, origin, points[index]) {
return intersection
} else {
// no origin to scale control points through, just use start and end points as a reference
return referencePoint + (points[index] - points[referenceIndex])
}
}
}
let scaledPoints = (0..<self.points.count).map(scaledPoint)
return type(of: self).init(points: scaledPoints)
}
// MARK: -
public func offset(distance d: CGFloat) -> [BezierCurve] {
// for non-linear curves we need to create a set of curves
var result: [BezierCurve] = self.reduce().compactMap { $0.curve.scale(distance: d) }
ensureContinuous(&result)
return result
}
public func offset(t: CGFloat, distance: CGFloat) -> CGPoint {
return self.point(at: t) + distance * self.normal(at: t)
}
// MARK: - outlines
public func outline(distance d1: CGFloat) -> PathComponent {
return internalOutline(d1: d1, d2: d1)
}
public func outline(distanceAlongNormal d1: CGFloat, distanceOppositeNormal d2: CGFloat) -> PathComponent {
return internalOutline(d1: d1, d2: d2)
}
private func ensureContinuous(_ curves: inout [BezierCurve]) {
for i in 0..<curves.count {
if i > 0 {
curves[i].startingPoint = curves[i-1].endingPoint
}
if i < curves.count-1 {
curves[i].endingPoint = 0.5 * ( curves[i].endingPoint + curves[i+1].startingPoint )
}
}
}
private func internalOutline(d1: CGFloat, d2: CGFloat) -> PathComponent {
let reduced = self.reduce()
let length = reduced.count
var forwardCurves: [BezierCurve] = reduced.compactMap { $0.curve.scale(distance: d1) }
var backCurves: [BezierCurve] = reduced.compactMap { $0.curve.scale(distance: -d2) }
ensureContinuous(&forwardCurves)
ensureContinuous(&backCurves)
// reverse the "return" outline
backCurves = backCurves.reversed().map { $0.reversed() }
// form the endcaps as lines
let forwardStart = forwardCurves[0].points[0]
let forwardEnd = forwardCurves[length-1].points[forwardCurves[length-1].points.count-1]
let backStart = backCurves[length-1].points[backCurves[length-1].points.count-1]
let backEnd = backCurves[0].points[0]
let lineStart = LineSegment(p0: backStart, p1: forwardStart)
let lineEnd = LineSegment(p0: forwardEnd, p1: backEnd)
let segments = [lineStart] + forwardCurves + [lineEnd] + backCurves
return PathComponent(curves: segments)
}
// MARK: shapes
public func outlineShapes(distance d1: CGFloat, accuracy: CGFloat = BezierKit.defaultIntersectionAccuracy) -> [Shape] {
return self.outlineShapes(distanceAlongNormal: d1, distanceOppositeNormal: d1, accuracy: accuracy)
}
public func outlineShapes(distanceAlongNormal d1: CGFloat, distanceOppositeNormal d2: CGFloat, accuracy: CGFloat = BezierKit.defaultIntersectionAccuracy) -> [Shape] {
let outline = self.outline(distanceAlongNormal: d1, distanceOppositeNormal: d2)
var shapes: [Shape] = []
let len = outline.numberOfElements
for i in 1..<len/2 {
let shape = Shape(outline.element(at: i), outline.element(at: len-i), i > 1, i < len/2-1)
shapes.append(shape)
}
return shapes
}
}
public let defaultIntersectionAccuracy = CGFloat(0.5)
internal let reduceStepSize: CGFloat = 0.01
public func == (left: BezierCurve, right: BezierCurve) -> Bool {
return left.points == right.points
}
public protocol BoundingBoxProtocol {
var boundingBox: BoundingBox { get }
}
public protocol Transformable {
func copy(using: CGAffineTransform) -> Self
}
public protocol Reversible {
func reversed() -> Self
}
public protocol BezierCurve: BoundingBoxProtocol, Transformable, Reversible {
var simple: Bool { get }
var points: [CGPoint] { get }
var startingPoint: CGPoint { get set }
var endingPoint: CGPoint { get set }
var order: Int { get }
init(points: [CGPoint])
func point(at t: CGFloat) -> CGPoint
func derivative(at t: CGFloat) -> CGPoint
func normal(at t: CGFloat) -> CGPoint
func split(from t1: CGFloat, to t2: CGFloat) -> Self
func split(at t: CGFloat) -> (left: Self, right: Self)
func length() -> CGFloat
func extrema() -> (x: [CGFloat], y: [CGFloat], all: [CGFloat])
func lookupTable(steps: Int) -> [CGPoint]
func project(_ point: CGPoint) -> (point: CGPoint, t: CGFloat)
// intersection routines
var selfIntersects: Bool { get }
var selfIntersections: [Intersection] { get }
func intersects(_ line: LineSegment) -> Bool
func intersects(_ curve: BezierCurve, accuracy: CGFloat) -> Bool
func intersections(with line: LineSegment) -> [Intersection]
func intersections(with curve: BezierCurve, accuracy: CGFloat) -> [Intersection]
}
internal protocol NonlinearBezierCurve: BezierCurve, ComponentPolynomials, Implicitizeable {
// intentionally empty, just declare conformance if you're not a line
}
public protocol Flatness: BezierCurve {
// the flatness of a curve is defined as the square of the maximum distance it is from a line connecting its endpoints https://jeremykun.com/2013/05/11/bezier-curves-and-picasso/
var flatnessSquared: CGFloat { get }
var flatness: CGFloat { get }
}
public extension Flatness {
var flatness: CGFloat {
return sqrt(flatnessSquared)
}
}
|
3908faf756c26a401953df0fc2e3d1af
| 38.722222 | 315 | 0.610878 | false | false | false | false |
Gunmer/EmojiLog
|
refs/heads/master
|
EmojiLog/Classes/TraceBuilder.swift
|
mit
|
1
|
public protocol TraceBuilder {
func add(emoji: String) -> Self
func add(level: LogLevel) -> Self
func add(date: Date) -> Self
func add(className: String) -> Self
func add(functionName: String) -> Self
func add(message: String) -> Self
func add(dateFormat: String) -> Self
func add(line: Int) -> Self
func build() -> String
}
class TraceBuilderDefault: TraceBuilder {
fileprivate var className = ""
fileprivate var date = Date()
fileprivate var emoji = ""
fileprivate var functionName = ""
fileprivate var level = LogLevel.debug
fileprivate var message = ""
fileprivate var dateFormat = "dd/MM/yyyy HH:mm:ss:SSS"
fileprivate var line = 0
func add(className: String) -> Self {
self.className = className
return self
}
func add(date: Date) -> Self {
self.date = date
return self
}
func add(emoji: String) -> Self {
self.emoji = emoji
return self
}
func add(functionName: String) -> Self {
if functionName.hasSuffix("()") {
self.functionName = functionName.replacingOccurrences(of: "()", with: "")
} else {
self.functionName = functionName
}
return self
}
func add(level: LogLevel) -> Self {
self.level = level
return self
}
func add(message: String) -> Self {
self.message = message
return self
}
func add(dateFormat: String) -> Self {
self.dateFormat = dateFormat
return self
}
func add(line: Int) -> Self {
self.line = line
return self
}
func build() -> String {
let formater = DateFormatter()
formater.dateFormat = dateFormat
let stringDate = formater.string(from: date)
return "\(emoji) |\(level.initial)| \(stringDate) -> \(className).\(functionName)[\(line)]: \(message)"
}
}
|
0fb5e1c7fdc530ec7441d30c7856dcf2
| 25.105263 | 111 | 0.569556 | false | false | false | false |
svanimpe/around-the-table
|
refs/heads/master
|
Sources/AroundTheTable/Services/NotificationService.swift
|
bsd-2-clause
|
1
|
/**
A service that sends notifications to users.
*/
public class NotificationService {
/// The persistence layer.
private let persistence: Persistence
/**
Initializes a notification service.
*/
init(persistence: Persistence) {
self.persistence = persistence
}
/**
Sends a notification to inform a player that his registration for an activity was automatically approved.
*/
func notify(_ player: User, ofAutomaticApprovalFor activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
let message = Strings.registrationWasAutoApproved(for: activity)
let link = "activity/\(id)"
let notification = Notification(recipient: player, message: message, link: link)
try persistence.add(notification)
}
/**
Sends a notification to inform a player that a host approved his registration for an activity.
*/
func notify(_ player: User, thatHostApprovedRegistrationFor activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
let message = Strings.hostApprovedRegistration(for: activity)
let link = "activity/\(id)"
let notification = Notification(recipient: player, message: message, link: link)
try persistence.add(notification)
}
/**
Sends a notification to inform a player that a host cancelled an activity.
*/
func notify(_ player: User, thatHostCancelled activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
let message = Strings.hostCancelled(activity)
let link = "activity/\(id)"
let notification = Notification(recipient: player, message: message, link: link)
try persistence.add(notification)
}
/**
Sends a notification to inform a player that a host cancelled his registration for an activity.
*/
func notify(_ player: User, thatHostCancelledRegistrationFor activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
let message = Strings.hostCancelledRegistration(for: activity)
let link = "activity/\(id)"
let notification = Notification(recipient: player, message: message, link: link)
try persistence.add(notification)
}
/**
Sends a notification to inform a player that a host changed the location of an activity.
*/
func notify(_ player: User, thatHostChangedAddressFor activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
let message = Strings.hostChangedAddress(of: activity)
let link = "activity/\(id)"
let notification = Notification(recipient: player, message: message, link: link)
try persistence.add(notification)
}
/**
Sends a notification to inform a player that a host changed the date or time of an activity.
*/
func notify(_ player: User, thatHostChangedDateFor activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
let message = Strings.hostChangedDate(of: activity)
let link = "activity/\(id)"
let notification = Notification(recipient: player, message: message, link: link)
try persistence.add(notification)
}
/**
Sends a notification to inform a host that a player cancelled his registration for an activity.
*/
func notify(_ host: User, that player: User, cancelledRegistrationFor activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
let message = Strings.player(player, cancelledRegistrationFor: activity)
let link = "activity/\(id)"
let notification = Notification(recipient: host, message: message, link: link)
try persistence.add(notification)
}
/**
Sends a notification to inform a host that a player's registration for an activity was automatically approved.
*/
func notify(_ host: User, that player: User, joined activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
let message = Strings.player(player, joined: activity)
let link = "activity/\(id)"
let notification = Notification(recipient: host, message: message, link: link)
try persistence.add(notification)
}
/**
Sends a notification to inform a host that a player submitted a registration for an activity.
*/
func notify(_ host: User, that player: User, sentRegistrationFor activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
let message = Strings.player(player, sentRegistrationFor: activity)
let link = "activity/\(id)"
let notification = Notification(recipient: host, message: message, link: link)
try persistence.add(notification)
}
}
|
ed16bb20f2e36cd68f25258bb873710f
| 39.265152 | 115 | 0.655315 | false | false | false | false |
varshylmobile/VMXMLParser
|
refs/heads/master
|
VMXMLParser.swift
|
mit
|
1
|
//
// VMXMLParser.swift
// XMLParserTest
//
// Created by Jimmy Jose on 22/08/14.
//
// 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
// Todo: Add documentation
class VMXMLParser: NSObject,NSXMLParserDelegate{
private let kParserError = "Parser Error"
private var activeElement = ""
private var previousElement = "-1"
private var previousElementValue = ""
private var arrayFinalXML = NSMutableArray()
private var dictFinalXML = NSMutableDictionary()
private var completionHandler:((tags:NSArray?, error:String?)->Void)?
var lameMode = true
var reoccuringTag:NSString = ""
/**
Initializes a new parser with url of NSURL type.
- parameter url: The url of xml file to be parsed
- parameter completionHandler: The completion handler
- returns: Void.
*/
override init() {
super.init()
}
func parseXMLFromURL(url:NSURL,takeChildOfTag:NSString,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil){
self.reoccuringTag = takeChildOfTag
VMXMLParser().initWithURL(url, completionHandler: completionHandler)
}
func parseXMLFromURLString(urlString:NSString,takeChildOfTag:NSString,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil){
self.reoccuringTag = takeChildOfTag
initWithURLString(urlString, completionHandler: completionHandler)
}
func parseXMLFromData(data:NSData,takeChildOfTag:NSString,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil){
self.reoccuringTag = takeChildOfTag
initWithContentsOfData(data, completionHandler:completionHandler)
}
class func initParserWithURL(url:NSURL,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil){
VMXMLParser().initWithURL(url, completionHandler: completionHandler)
}
class func initParserWithURLString(urlString:NSString,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil){
VMXMLParser().initWithURLString(urlString, completionHandler: completionHandler)
}
class func initParserWithData(data:NSData,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil){
VMXMLParser().initWithContentsOfData(data, completionHandler:completionHandler)
}
private func initWithURL(url:NSURL,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil) -> AnyObject {
parseXMLForUrl(url :url, completionHandler: completionHandler)
return self
}
private func initWithURLString(urlString :NSString,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil) -> AnyObject {
let url = NSURL(string: urlString as String)!
parseXMLForUrl(url :url, completionHandler: completionHandler)
return self
}
private func initWithContentsOfData(data:NSData,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil) -> AnyObject {
initParserWith(data: data)
return self
}
private func parseXMLForUrl(url url:NSURL,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil){
self.completionHandler = completionHandler
beginParsingXMLForUrl(url)
}
private func beginParsingXMLForUrl(url:NSURL){
let request:NSURLRequest = NSURLRequest(URL:url)
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request,queue:queue,completionHandler:{response,data,error in
if(error != nil){
if(self.completionHandler != nil){
self.completionHandler?(tags:nil,error:error!.localizedDescription)
}
}else{
self.initParserWith(data: data!)
}})
}
private func initParserWith(data data:NSData){
let parser = NSXMLParser(data: data)
parser.delegate = self
let success:Bool = parser.parse()
if success {
if(self.arrayFinalXML.count > 0){
if(self.completionHandler != nil){
self.completionHandler?(tags:self.arrayFinalXML,error:nil)
}
}
} else {
if(self.completionHandler != nil){
self.completionHandler?(tags:nil,error:kParserError)
}
}
}
internal func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
activeElement = elementName;
if(reoccuringTag.isEqualToString(elementName)){
dictFinalXML = NSMutableDictionary()
}
}
internal func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if(reoccuringTag.length == 0){
if((dictFinalXML.objectForKey(activeElement)) != nil){
arrayFinalXML.addObject(dictFinalXML)
dictFinalXML = NSMutableDictionary()
}else{
dictFinalXML.setValue(previousElementValue, forKey: activeElement)
}
}else{
//println(elementName)
if(reoccuringTag.isEqualToString(elementName)){
arrayFinalXML.addObject(dictFinalXML)
dictFinalXML = NSMutableDictionary()
}else{
dictFinalXML.setValue(previousElementValue, forKey: activeElement)
}
}
previousElement = "-1"
previousElementValue = ""
}
internal func parser(parser: NSXMLParser, foundCharacters string: String) {
if var str = string as NSString? {
str = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if((previousElement as NSString).isEqualToString("-1")){
previousElement = activeElement
previousElementValue = str as String
}else{
if((previousElement as NSString).isEqualToString(activeElement)){
previousElementValue = previousElementValue + (str as String)
}else{
previousElement = activeElement
previousElementValue = str as String
}
}
}
}
internal func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) {
if(self.completionHandler != nil){
self.completionHandler?(tags:nil,error:parseError.localizedDescription)
}
}
}
|
707a3fb5da03825ee969a24127f278b7
| 32.428 | 182 | 0.604356 | false | false | false | false |
izhuster/TechnicalTest
|
refs/heads/master
|
TechnicalTest/TechnicalTest/ViewControllers/Home/PokemonDataSource.swift
|
mit
|
2
|
//
// PokemonDataSource.swift
// TechnicalTest
//
// Created by Alejandro Cárdenas on 11/28/16.
// Copyright © 2016 alekscbarragan. All rights reserved.
//
import UIKit
protocol PokemonDataSourceDelegate {
func shouldUpdateTableView(sender: PokemonDataSource)
func shouldShowLoadingView(show: Bool)
func pokemonDataSource(dataSource: PokemonDataSource, didSelectPhotos object: AnyObject?)
func pokemonDataSource(dataSource: PokemonDataSource, didSelectPokemon pokemon: Pokemon)
}
// MARK: - Data source class
class PokemonDataSource: NSObject {
var delegate: PokemonDataSourceDelegate?
var pokemonFetcher: PokemonFetcher!
var pokemons = [Pokemon]()
override init() {
super.init()
}
func requestPokemons() {
delegate?.shouldShowLoadingView(true)
let pokemons = DataAccessor.sharedInstance.currentPokemons()
if pokemons.count > 0 {
self.pokemons = pokemons
delegate?.shouldUpdateTableView(self)
delegate?.shouldShowLoadingView(false)
} else {
pokemonFetcher.requestPokemons { (finished) in
if (finished) {
NSOperationQueue.mainQueue().addOperationWithBlock({
DataAccessor.sharedInstance.saveContext()
})
self.pokemons = DataAccessor.sharedInstance.currentPokemons()
self.delegate?.shouldUpdateTableView(self)
self.delegate?.shouldShowLoadingView(false)
}
}
}
}
}
// MARK: - Pokemon cell delegate
extension PokemonDataSource: PokemonTableViewCellDelegate {
func cell(cell: PokemonTableViewCell, didSelectPhotos sender: AnyObject) {
delegate?.pokemonDataSource(self, didSelectPhotos: cell)
}
}
// MARK: - table view data source
extension PokemonDataSource: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pokemons.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = String(PokemonTableViewCell)
let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! PokemonTableViewCell
let pokemon = pokemons[indexPath.row]
cell.nameLabel.text = pokemon.name
cell.delegate = self
return cell
}
}
// MARK: - Table view delegate
extension PokemonDataSource: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let pokemon = pokemons[indexPath.row]
delegate?.pokemonDataSource(self, didSelectPokemon: pokemon)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
|
b01994e0d888f5c8877944ba16b25e06
| 27.073684 | 120 | 0.732283 | false | false | false | false |
evan-liu/GitHubExplorer
|
refs/heads/master
|
GitHubExplorer/UI.swift
|
mit
|
1
|
import UIKit
import FormationLayout
typealias LayoutBlock = (ConstraintMaker) -> Void
/// Helper class to build UI
class UI {
/// Only for getting `view` and `topLayoutGuide/bottomLayoutGuide`
unowned let controller: UIViewController
init(controller: UIViewController) {
self.controller = controller
view.backgroundColor = .sceneBackground
build()
}
lazy var view: UIView = self.controller.view
lazy var layout: FormationLayout = FormationLayout(rootView: self.view)
var topLayoutGuide: UILayoutSupport {
return controller.topLayoutGuide
}
var bottomLayoutGuide: UILayoutSupport {
return controller.bottomLayoutGuide
}
func build() {
}
}
/// App level ui helper
protocol AppUI {
/// App root controller
var controller: UIViewController { get }
}
extension UI: AppUI { }
|
86251ba990addb1dd64d8740a650f1c9
| 22.026316 | 75 | 0.692571 | false | false | false | false |
a497500306/yijia_kuanjia
|
refs/heads/master
|
医家/医家/主项目/MLTabBarController/MLTabBarController.swift
|
apache-2.0
|
1
|
//
// MLTabBarController.swift
// 医家
//
// Created by 洛耳 on 15/12/21.
// Copyright © 2015年 workorz. All rights reserved.
//
import UIKit
class MLTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
let item = self.tabBar.items![0]
let image = UIImage(named: "首页_nor")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
let seleImage = UIImage(named: "首页_pre")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
item.selectedImage = seleImage
item.image = image
item.title = "首页"
let attributes = NSMutableDictionary()
attributes.setValue(UIColor(red: 3/255.0, green: 166/255.0, blue: 116/255.0, alpha: 1), forKey: NSForegroundColorAttributeName)
item.setTitleTextAttributes(attributes as NSDictionary as? [String : AnyObject], forState: UIControlState.Selected)
let item1 = self.tabBar.items![1]
let image1 = UIImage(named: "论坛_nor")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
let seleImage1 = UIImage(named: "论坛_pre")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
item1.selectedImage = seleImage1
item1.image = image1
item1.title = "论坛"
item1.setTitleTextAttributes(attributes as NSDictionary as? [String : AnyObject], forState: UIControlState.Selected)
let item2 = self.tabBar.items![2]
let image2 = UIImage(named: "测试_nor")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
let seleImage2 = UIImage(named: "测试_pre")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
item2.selectedImage = seleImage2
item2.title = "测试"
item2.image = image2
item2.setTitleTextAttributes(attributes as NSDictionary as? [String : AnyObject], forState: UIControlState.Selected)
let item3 = self.tabBar.items![3]
let image3 = UIImage(named: "消息_nor")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
let seleImage3 = UIImage(named: "消息_pre")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
item3.selectedImage = seleImage3
item3.image = image3
item3.title = "消息"
item3.setTitleTextAttributes(attributes as NSDictionary as? [String : AnyObject], forState: UIControlState.Selected)
}
}
|
ff636c9adaf432e700ee00813520725f
| 45.711538 | 135 | 0.690819 | false | false | false | false |
ljshj/actor-platform
|
refs/heads/master
|
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Managed Runtime/AAManagedTable.swift
|
agpl-3.0
|
2
|
//
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
public class AAManagedTable {
//------------------------------------------------------------------------//
// Controller of table
public let controller: UIViewController
// Table view
public let style: AAContentTableStyle
public let tableView: UITableView
public var tableViewDelegate: UITableViewDelegate { get { return baseDelegate } }
public var tableViewDataSource: UITableViewDataSource { get { return baseDelegate } }
// Scrolling closure
public var tableScrollClosure: ((tableView: UITableView) -> ())?
// Is fade in/out animated
public var fadeShowing = false
// Sections of table
public var sections: [AAManagedSection] = [AAManagedSection]()
// Fixed Height
public var fixedHeight: CGFloat?
// Can Edit All rows
public var canEditAll: Bool?
// Can Delete All rows
public var canDeleteAll: Bool?
// Is Table in editing mode
public var isEditing: Bool {
get {
return tableView.editing
}
}
// Is updating sections
private var isUpdating = false
// Reference to table view delegate/data source
private var baseDelegate: AMBaseTableDelegate!
// Search
private var isSearchInited: Bool = false
private var isSearchAutoHide: Bool = false
private var searchDisplayController: UISearchDisplayController!
private var searchManagedController: AnyObject!
//------------------------------------------------------------------------//
public init(style: AAContentTableStyle, tableView: UITableView, controller: UIViewController) {
self.style = style
self.controller = controller
self.tableView = tableView
if style == .SettingsGrouped {
self.baseDelegate = AMGrouppedTableDelegate(data: self)
} else {
self.baseDelegate = AMPlainTableDelegate(data: self)
}
self.tableView.dataSource = self.baseDelegate
self.tableView.delegate = self.baseDelegate
}
//------------------------------------------------------------------------//
// Entry point to adding
public func beginUpdates() {
if isUpdating {
fatalError("Already updating table")
}
isUpdating = true
}
public func addSection(autoSeparator: Bool = false) -> AAManagedSection {
if !isUpdating {
fatalError("Table is not in updating mode")
}
let res = AAManagedSection(table: self, index: sections.count)
res.autoSeparators = autoSeparator
sections.append(res)
return res
}
public func search<C where C: AABindedSearchCell, C: UITableViewCell>(cell: C.Type, @noescape closure: (s: AAManagedSearchConfig<C>) -> ()) {
if !isUpdating {
fatalError("Table is not in updating mode")
}
if isSearchInited {
fatalError("Search already inited")
}
isSearchInited = true
// Configuring search source
let config = AAManagedSearchConfig<C>()
closure(s: config)
// Creating search source
let searchSource = AAManagedSearchController<C>(config: config, controller: controller, tableView: tableView)
self.searchDisplayController = searchSource.searchDisplay
self.searchManagedController = searchSource
self.isSearchAutoHide = config.isSearchAutoHide
}
public func endUpdates() {
if !isUpdating {
fatalError("Table is not in editable mode")
}
isUpdating = false
}
// Reloading table
public func reload() {
self.tableView.reloadData()
}
public func reload(section: Int) {
self.tableView.reloadSections(NSIndexSet(index: section), withRowAnimation: .Automatic)
}
// Binding methods
public func bind(binder: AABinder) {
for s in sections {
s.bind(self, binder: binder)
}
}
public func unbind(binder: AABinder) {
for s in sections {
s.unbind(self, binder: binder)
}
}
// Show/hide table
public func showTable() {
if isUpdating || !fadeShowing {
self.tableView.alpha = 1
} else {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.tableView.alpha = 1
})
}
}
public func hideTable() {
if isUpdating || !fadeShowing {
self.tableView.alpha = 0
} else {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.tableView.alpha = 0
})
}
}
// Controller callbacks
public func controllerViewWillDisappear(animated: Bool) {
// Auto close search on leaving controller
if isSearchAutoHide {
//dispatchOnUi { () -> Void in
searchDisplayController?.setActive(false, animated: false)
//}
}
}
public func controllerViewDidDisappear(animated: Bool) {
// Auto close search on leaving controller
// searchDisplayController?.setActive(false, animated: animated)
}
public func controllerViewWillAppear(animated: Bool) {
// Search bar dissapear fixing
// Hack No 1
if searchDisplayController != nil {
let searchBar = searchDisplayController!.searchBar
let superView = searchBar.superview
if !(superView is UITableView) {
searchBar.removeFromSuperview()
superView?.addSubview(searchBar)
}
}
// Hack No 2
tableView.tableHeaderView?.setNeedsLayout()
tableView.tableFooterView?.setNeedsLayout()
// Status bar styles
if (searchDisplayController != nil && searchDisplayController!.active) {
// If search is active: apply search status bar style
UIApplication.sharedApplication().setStatusBarStyle(ActorSDK.sharedActor().style.searchStatusBarStyle, animated: true)
} else {
// If search is not active: apply main status bar style
UIApplication.sharedApplication().setStatusBarStyle(ActorSDK.sharedActor().style.vcStatusBarStyle, animated: true)
}
}
}
// Closure based extension
public extension AAManagedTable {
public func section(closure: (s: AAManagedSection) -> ()){
closure(s: addSection(true))
}
}
// Table view delegates and data sources
private class AMPlainTableDelegate: AMBaseTableDelegate {
@objc func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat(data.sections[section].headerHeight)
}
@objc func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat(data.sections[section].footerHeight)
}
@objc func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if (data.sections[section].headerText == nil) {
return UIView()
} else {
return nil
}
}
@objc func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if (data.sections[section].footerText == nil) {
return UIView()
} else {
return nil
}
}
}
private class AMGrouppedTableDelegate: AMBaseTableDelegate {
@objc func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel!.textColor = ActorSDK.sharedActor().style.cellHeaderColor
}
@objc func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel!.textColor = ActorSDK.sharedActor().style.cellFooterColor
}
}
private class AMBaseTableDelegate: NSObject, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
unowned private let data: AAManagedTable
init(data: AAManagedTable) {
self.data = data
}
@objc func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return data.sections.count
}
@objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.sections[section].numberOfItems(data)
}
@objc func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return data.sections[indexPath.section].cellForItem(data, indexPath: indexPath)
}
@objc func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let text = data.sections[section].headerText
if text != nil {
return AALocalized(text!)
} else {
return text
}
}
@objc func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
let text = data.sections[section].footerText
if text != nil {
return AALocalized(text!)
} else {
return text
}
}
@objc func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if data.fixedHeight != nil {
return data.fixedHeight!
}
return data.sections[indexPath.section].cellHeightForItem(data, indexPath: indexPath)
}
@objc func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
if data.canEditAll != nil {
return data.canEditAll!
}
return (data.sections[indexPath.section].numberOfItems(data) > 0 ? data.sections[indexPath.section].canDelete(data, indexPath: indexPath) : false)
}
@objc func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
@objc func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
if data.canDeleteAll != nil {
if data.canDeleteAll! {
return .Delete
} else {
return .None
}
}
return data.sections[indexPath.section].canDelete(data, indexPath: indexPath) ? .Delete : .None
}
@objc func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
return data.sections[indexPath.section].delete(data, indexPath: indexPath)
}
@objc func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let section = data.sections[indexPath.section]
if section.canSelect(data, indexPath: indexPath) {
if section.select(data, indexPath: indexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
} else {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
@objc func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
if action == "copy:" {
let section = data.sections[indexPath.section]
return section.canCopy(data, indexPath: indexPath)
}
return false
}
@objc func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool {
let section = data.sections[indexPath.section]
return section.canCopy(data, indexPath: indexPath)
}
@objc func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
if action == "copy:" {
let section = data.sections[indexPath.section]
if section.canCopy(data, indexPath: indexPath) {
section.copy(data, indexPath: indexPath)
}
}
}
@objc func scrollViewDidScroll(scrollView: UIScrollView) {
if (data.tableView == scrollView) {
data.tableScrollClosure?(tableView: data.tableView)
}
}
}
public class AAManagedSearchConfig<BindCell where BindCell: AABindedSearchCell, BindCell: UITableViewCell> {
public var searchList: ARBindedDisplayList!
public var selectAction: ((BindCell.BindData) -> ())?
public var isSearchAutoHide: Bool = true
public var didBind: ((c: BindCell, d: BindCell.BindData) -> ())?
}
private class AAManagedSearchController<BindCell where BindCell: AABindedSearchCell, BindCell: UITableViewCell>: NSObject, UISearchBarDelegate, UISearchDisplayDelegate, UITableViewDataSource, UITableViewDelegate, ARDisplayList_Listener {
let config: AAManagedSearchConfig<BindCell>
let displayList: ARBindedDisplayList
let searchDisplay: UISearchDisplayController
init(config: AAManagedSearchConfig<BindCell>, controller: UIViewController, tableView: UITableView) {
self.config = config
self.displayList = config.searchList
let style = ActorSDK.sharedActor().style
let searchBar = UISearchBar()
// Styling Search bar
searchBar.searchBarStyle = UISearchBarStyle.Default
searchBar.translucent = false
searchBar.placeholder = "" // SearchBar placeholder animation fix
// SearchBar background color
searchBar.barTintColor = style.searchBackgroundColor.forTransparentBar()
searchBar.setBackgroundImage(Imaging.imageWithColor(style.searchBackgroundColor, size: CGSize(width: 1, height: 1)), forBarPosition: .Any, barMetrics: .Default)
searchBar.backgroundColor = style.searchBackgroundColor
// SearchBar cancel color
searchBar.tintColor = style.searchCancelColor
// Apply keyboard color
searchBar.keyboardAppearance = style.isDarkApp ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light
// SearchBar field color
let fieldBg = Imaging.imageWithColor(style.searchFieldBgColor, size: CGSize(width: 14,height: 28))
.roundCorners(14, h: 28, roundSize: 4)
searchBar.setSearchFieldBackgroundImage(fieldBg.stretchableImageWithLeftCapWidth(7, topCapHeight: 0), forState: UIControlState.Normal)
// SearchBar field text color
for subView in searchBar.subviews {
for secondLevelSubview in subView.subviews {
if let tf = secondLevelSubview as? UITextField {
tf.textColor = style.searchFieldTextColor
break
}
}
}
self.searchDisplay = UISearchDisplayController(searchBar: searchBar, contentsController: controller)
super.init()
// Creating Search Display Controller
self.searchDisplay.searchBar.delegate = self
self.searchDisplay.searchResultsDataSource = self
self.searchDisplay.searchResultsDelegate = self
self.searchDisplay.delegate = self
// Styling search list
self.searchDisplay.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyle.None
self.searchDisplay.searchResultsTableView.backgroundColor = ActorSDK.sharedActor().style.vcBgColor
// Adding search to table header
let header = AATableViewHeader(frame: CGRectMake(0, 0, 320, 44))
header.addSubview(self.searchDisplay.searchBar)
tableView.tableHeaderView = header
// Start receiving events
self.displayList.addListener(self)
}
// Model
func objectAtIndexPath(indexPath: NSIndexPath) -> BindCell.BindData {
return displayList.itemWithIndex(jint(indexPath.row)) as! BindCell.BindData
}
@objc func onCollectionChanged() {
searchDisplay.searchResultsTableView.reloadData()
}
// Table view data
@objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Int(displayList.size());
}
@objc func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let item = objectAtIndexPath(indexPath)
return BindCell.self.bindedCellHeight(item)
}
@objc func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let item = objectAtIndexPath(indexPath)
let cell = tableView.dequeueCell(BindCell.self, indexPath: indexPath) as! BindCell
cell.bind(item, search: nil)
return cell
}
@objc func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let item = objectAtIndexPath(indexPath)
config.selectAction!(item)
// MainAppTheme.navigation.applyStatusBar()
}
// Search updating
@objc func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
let normalized = searchText.trim().lowercaseString
if (normalized.length > 0) {
displayList.initSearchWithQuery(normalized, withRefresh: false)
} else {
displayList.initEmpty()
}
}
// Search styling
@objc func searchDisplayControllerWillBeginSearch(controller: UISearchDisplayController) {
UIApplication.sharedApplication().setStatusBarStyle(ActorSDK.sharedActor().style.searchStatusBarStyle, animated: true)
}
@objc func searchDisplayControllerWillEndSearch(controller: UISearchDisplayController) {
UIApplication.sharedApplication().setStatusBarStyle(ActorSDK.sharedActor().style.vcStatusBarStyle, animated: true)
}
@objc func searchDisplayController(controller: UISearchDisplayController, didShowSearchResultsTableView tableView: UITableView) {
for v in tableView.subviews {
if (v is UIImageView) {
(v as! UIImageView).alpha = 0;
}
}
}
}
|
6cd9496530ead6f7d8da522009676683
| 33.314545 | 237 | 0.633074 | false | false | false | false |
vitormesquita/Malert
|
refs/heads/master
|
Malert/Classes/MalertView/MalertView.swift
|
mit
|
1
|
//
// MalertView.swift
// Pods
//
// Created by Vitor Mesquita on 31/10/16.
//
//
import UIKit
public class MalertView: UIView {
private lazy var titleLabel = UILabel.ilimitNumberOfLines()
private lazy var buttonsStackView = UIStackView.defaultStack(axis: .vertical)
private var stackConstraints: [NSLayoutConstraint] = []
private var titleLabelConstraints: [NSLayoutConstraint] = []
private var customViewConstraints: [NSLayoutConstraint] = []
private var _buttonsHeight: CGFloat = 44
private var _buttonsSeparetorColor: UIColor = UIColor(white: 0.8, alpha: 1)
private var _buttonsFont: UIFont = UIFont.systemFont(ofSize: 16)
private var inset: CGFloat = 0 {
didSet { refreshViews() }
}
private var stackSideInset: CGFloat = 0 {
didSet { updateButtonsStackViewConstraints() }
}
private var stackBottomInset: CGFloat = 0 {
didSet { updateButtonsStackViewConstraints() }
}
private var customView: UIView? {
didSet {
if let oldValue = oldValue {
oldValue.removeFromSuperview()
}
}
}
// MARK: - Init
init() {
super.init(frame: .zero)
clipsToBounds = true
margin = 0
cornerRadius = 6
backgroundColor = .white
textColor = .black
textAlign = .left
titleFont = UIFont.systemFont(ofSize: 14)
buttonsSpace = 0
buttonsSideMargin = 0
buttonsAxis = .vertical
}
@available(*, unavailable)
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK - Utils
private var hasButtons: Bool {
guard buttonsStackView.isDescendant(of: self) else { return false }
return !buttonsStackView.arrangedSubviews.isEmpty
}
private func refreshViews() {
updateTitleLabelConstraints()
updateCustomViewConstraints()
updateButtonsStackViewConstraints()
}
}
// MARK: - Extensions to setUp Views in alert
extension MalertView {
func seTitle(_ title: String?) {
if let title = title {
titleLabel.text = title
if !titleLabel.isDescendant(of: self) {
self.addSubview(titleLabel)
refreshViews()
}
}
}
func setCustomView(_ customView: UIView?) {
guard let customView = customView else { return }
self.customView = customView
self.addSubview(customView)
refreshViews()
}
func addButton(_ button: MalertAction, actionCallback: MalertActionCallbackProtocol?) {
let buttonView = MalertButtonView(type: .system)
buttonView.height = _buttonsHeight
buttonView.titleFont = _buttonsFont
buttonView.separetorColor = _buttonsSeparetorColor
buttonView.callback = actionCallback
buttonView.setUpBy(action: button)
buttonView.setUp(index: buttonsStackView.arrangedSubviews.count, hasMargin: buttonsSpace > 0, isHorizontalAxis: buttonsAxis == .horizontal)
buttonsStackView.addArrangedSubview(buttonView)
if !buttonsStackView.isDescendant(of: self) {
self.addSubview(buttonsStackView)
refreshViews()
}
}
}
/**
* Extensios that implements Malert constraints to:
* - Title Label
* - Custom View
* - Buttons Stack View
*/
extension MalertView {
private func updateTitleLabelConstraints() {
NSLayoutConstraint.deactivate(titleLabelConstraints)
guard titleLabel.isDescendant(of: self) else { return }
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabelConstraints = [
titleLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: inset),
titleLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -inset),
titleLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: inset)
]
NSLayoutConstraint.activate(titleLabelConstraints)
}
private func updateCustomViewConstraints() {
guard let customView = customView else { return }
NSLayoutConstraint.deactivate(customViewConstraints)
customView.translatesAutoresizingMaskIntoConstraints = false
customViewConstraints = [
customView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -inset),
customView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: inset)
]
if titleLabel.isDescendant(of: self) {
customViewConstraints.append(customView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: inset))
} else {
customViewConstraints.append(customView.topAnchor.constraint(equalTo: self.topAnchor, constant: inset))
}
if !hasButtons {
customViewConstraints.append(customView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -inset))
}
NSLayoutConstraint.activate(customViewConstraints)
}
private func updateButtonsStackViewConstraints() {
guard hasButtons else { return }
NSLayoutConstraint.deactivate(stackConstraints)
buttonsStackView.translatesAutoresizingMaskIntoConstraints = false
stackConstraints = [
buttonsStackView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -stackSideInset),
buttonsStackView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: stackSideInset),
buttonsStackView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -stackBottomInset)
]
if let customView = customView {
stackConstraints.append(buttonsStackView.topAnchor.constraint(equalTo: customView.bottomAnchor, constant: inset))
} else if titleLabel.isDescendant(of: self) {
stackConstraints.append(buttonsStackView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: inset))
} else {
stackConstraints.append(buttonsStackView.topAnchor.constraint(equalTo: self.topAnchor, constant: inset))
}
NSLayoutConstraint.activate(stackConstraints)
}
}
// MARK: - Appearance
extension MalertView {
/// Dialog view corner radius
@objc public dynamic var cornerRadius: CGFloat {
get { return layer.cornerRadius }
set { layer.cornerRadius = newValue }
}
/// Title text color
@objc public dynamic var textColor: UIColor {
get { return titleLabel.textColor }
set { titleLabel.textColor = newValue }
}
/// Title text Align
@objc public dynamic var textAlign: NSTextAlignment {
get { return titleLabel.textAlignment }
set { titleLabel.textAlignment = newValue }
}
/// Title font
@objc public dynamic var titleFont: UIFont {
get { return titleLabel.font }
set { titleLabel.font = newValue }
}
/// Buttons distribution in stack view
@objc public dynamic var buttonsDistribution: UIStackView.Distribution {
get { return buttonsStackView.distribution }
set { buttonsStackView.distribution = newValue }
}
/// Buttons aligns in stack view
@objc public dynamic var buttonsAligment: UIStackView.Alignment {
get { return buttonsStackView.alignment }
set { buttonsStackView.alignment = newValue }
}
/// Buttons axis in stack view
@objc public dynamic var buttonsAxis: NSLayoutConstraint.Axis {
get { return buttonsStackView.axis }
set { buttonsStackView.axis = newValue }
}
/// Margin inset to titleLabel and CustomView
@objc public dynamic var margin: CGFloat {
get { return inset }
set { inset = newValue }
}
/// Trailing and Leading margin inset to StackView buttons
@objc public dynamic var buttonsSideMargin: CGFloat {
get { return stackSideInset }
set { stackSideInset = newValue }
}
/// Bottom margin inset to StackView buttons
@objc public dynamic var buttonsBottomMargin: CGFloat {
get { return stackBottomInset }
set { stackBottomInset = newValue }
}
/// Margin inset between buttons
@objc public dynamic var buttonsSpace: CGFloat {
get { return buttonsStackView.spacing }
set { buttonsStackView.spacing = newValue }
}
///
@objc public dynamic var buttonsHeight: CGFloat {
get { return _buttonsHeight }
set { _buttonsHeight = newValue }
}
///
@objc public dynamic var separetorColor: UIColor {
get { return _buttonsSeparetorColor }
set { _buttonsSeparetorColor = newValue }
}
///
@objc public dynamic var buttonsFont: UIFont {
get { return _buttonsFont }
set { _buttonsFont = newValue }
}
}
|
7fb652424c95953a0de14b2780c127be
| 32.145455 | 147 | 0.646956 | false | false | false | false |
kiliankoe/DVB
|
refs/heads/master
|
Sources/DVB/Models/RouteChange/RouteChange.swift
|
mit
|
1
|
import Foundation
public struct RouteChange {
public let id: String
public let kind: Kind
public let tripRequestInclude: Bool?
public let title: String
public let htmlDescription: String
public let validityPeriods: [ValidityPeriod]
public let lineIds: [String]
public let publishDate: Date
}
extension RouteChange: Decodable {
private enum CodingKeys: String, CodingKey {
case id = "Id"
case kind = "Type"
case tripRequestInclude = "TripRequestInclude"
case title = "Title"
case htmlDescription = "Description"
case validityPeriods = "ValidityPeriods"
case lineIds = "LineIds"
case publishDate = "PublishDate"
}
}
extension RouteChange: Equatable {}
extension RouteChange: Hashable {}
// MARK: - API
extension RouteChange {
public static func get(shortTerm: Bool = true,
session: URLSession = .shared,
completion: @escaping (Result<RouteChangeResponse>) -> Void) {
let data = [
"shortterm": shortTerm,
]
post(Endpoint.routeChanges, data: data, session: session, completion: completion)
}
}
// MARK: - Utiliy
extension RouteChange: CustomStringConvertible {
public var description: String {
return self.title
}
}
|
546eee6a71419b452bdbd7fc1ee83651
| 25.254902 | 89 | 0.64227 | false | false | false | false |
kevinup7/S4HeaderExtensions
|
refs/heads/master
|
Sources/S4HeaderExtensions/MessageHeaders/TransferEncoding.swift
|
mit
|
1
|
import S4
extension Headers {
/**
The `Transfer-Encoding` header field lists the transfer coding names
corresponding to the sequence of transfer codings that have been (or
will be) applied to the payload body in order to form the message
body.
## Example Headers
`Transfer-Encoding: gzip, chunked`
`Transfer-Encoding: gzip`
## Examples
var response = Response()
response.headers.transferEncoding = [.gzip, .chunked]
var response = Response()
response.headers.transferEncoding = [.gzip]
- seealso: [RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.1)
*/
public var transferEncoding: [Encoding]? {
get {
return Encoding.values(fromHeader: headers["Transfer-Encoding"])
}
set {
headers["Transfer-Encoding"] = newValue?.headerValue
}
}
}
|
d9bb0b167f4773637140e4bba107a8a4
| 26.735294 | 78 | 0.597665 | false | false | false | false |
weirdindiankid/Tinder-Clone
|
refs/heads/master
|
TinderClone/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// TinderClone
//
// Created by Dharmesh Tarapore on 19/01/2015.
// Copyright (c) 2015 Dharmesh Tarapore. All rights reserved.
//
import UIKit
class ViewController: UIViewController, FBLoginViewDelegate,PFLogInViewControllerDelegate, UITextFieldDelegate {
// var profilePictureView:FBProfilePictureView = FBProfilePictureView()
var fbloginView:FBLoginView = FBLoginView()
var facebookLogin:Bool = false
@IBOutlet weak var textfieldUserName: UITextField!
@IBOutlet weak var textfieldPassword: UITextField!
@IBOutlet weak var signInButton: UIButton!
@IBOutlet weak var signUpButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
println("viewDidLoad");
fbloginView.frame = CGRectMake(60.0, 450.0, 200.0, 44.0)
fbloginView.delegate = self
/*fbloginView.readPermissions = ["email",
"basic_info",
"user_location",
"user_birthday",
"user_likes"]*/
self.view.addSubview(fbloginView)
// profilePictureView = FBProfilePictureView(frame: CGRectMake(70.0, fbloginView.frame.size.height + fbloginView.frame.origin.y, 180.0, 200.0))
// self.view.addSubview(profilePictureView)
GlobalVariableSharedInstance.initLocationManager()
}
// Add in an NSRunLoop to make this faster
override func viewWillAppear(animated: Bool)
{
println("viewWillAppear");
//fbloginView.frame = CGRectMake(60.0, 450.0, 200.0, 44.0)
//profilePictureView.frame = CGRectMake(70.0, 450.0, 180.0, 200.0)
let user = PFUser.currentUser() as PFUser!
if (user != nil) //if (self.facebookLogin == true)//if (FBSession.activeSession().isOpen)
{
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("displayTabs"), userInfo: nil, repeats: false)
self.facebookLogin = false
}
else {
FBSession.activeSession().closeAndClearTokenInformation()
}
}
@IBAction func signIn(sender: UIButton)
{
println("signIn");
// self.displayTabs()
self.signInButton.enabled = false
self.signUpButton.enabled = false
var message = ""
if (self.textfieldPassword.text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 0)
{
message = "Password should not be empty"
}
if (self.textfieldUserName.text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 0)
{
message = "User Name should not be empty"
}
if (message.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) != 0)
{
var alert:UIAlertView = UIAlertView(title: "Message", message: message, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
self.signInButton.enabled = true
self.signUpButton.enabled = true
}
else
{
MBProgressHUD.showHUDAddedTo(self.view, animated:true)
PFUser.logInWithUsernameInBackground(self.textfieldUserName.text , password:self.textfieldPassword.text)
{
(user: PFUser!, error: NSError!) -> Void in
if (user != nil)
{
self.displayTabs()
}
else
{
if let errorString = error.userInfo?["error"] as? NSString
{
var alert:UIAlertView = UIAlertView(title: "Error", message: errorString, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
}
self.signInButton.enabled = true
self.signUpButton.enabled = true
MBProgressHUD.hideHUDForView(self.view, animated:false)
}
}
}
override func viewWillLayoutSubviews()
{
super.viewWillAppear(false)
//println("viewWillLayoutSubviews")
}
func loginViewFetchedUserInfo(loginView: FBLoginView!, user: FBGraphUser!)
{
//self.profilePictureView.profileID = user.id
println("loginViewFetchedUserInfo")
var query = PFUser.query()
query.whereKey("fbID", equalTo: user.id)
//
MBProgressHUD.showHUDAddedTo(self.view, animated:true)
query.findObjectsInBackgroundWithBlock({(NSArray objects, NSError error) in
if (error != nil) {
MBProgressHUD.hideHUDForView(self.view, animated:false)
}
else{
if (objects.count == 0)
{
/* fbloginView.readPermissions = ["email"];
var me:FBRequest = FBRequest.requestForMe()
me.startWithCompletionHandler({(NSArray my, NSError error) in*/
println(user)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let imageUploaderView = storyboard.instantiateViewControllerWithIdentifier("ImageSelectorViewController") as ImageSelectorViewController
var email:String? = user.objectForKey("email") as String?
var birthday:String? = user.birthday
if (email==nil) {
email = user.first_name + "@user.com"
}
if (birthday==nil) {
birthday = "10/10/1987"
}
imageUploaderView.setUserName(user.name, password: user.id, Email: email!, andDateOfBirth: birthday!)
imageUploaderView.facebookLogin = true
self.facebookLogin = true
imageUploaderView.user = user
MBProgressHUD.hideHUDForView(self.view, animated:false)
imageUploaderView.loginScreen = self;
self.navigationController!.pushViewController(imageUploaderView, animated: true)
}
else
{
PFUser.logInWithUsernameInBackground(user.name , password:user.id)
{
(user: PFUser!, error: NSError!) -> Void in
if (user != nil)
{
/*
var alert:UIAlertView = UIAlertView(title: "Message", message: "Hi " + user.username + ". You logged in", delegate: nil, cancelButtonTitle: "Ok")
alert.show()
*/
MBProgressHUD.hideHUDForView(self.view, animated:false)
self.displayTabs()
}
else
{
MBProgressHUD.hideHUDForView(self.view, animated:false)
if let errorString = error.userInfo?["error"] as? NSString
{
var alert:UIAlertView = UIAlertView(title: "Error", message: errorString, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
}
self.signInButton.enabled = true
self.signUpButton.enabled = true
}
}
}
})
}
func loginViewShowingLoggedInUser(loginView: FBLoginView!)
{
println("loginViewShowingLoggedInUser")
}
func loginViewShowingLoggedOutUser(loginView: FBLoginView!)
{
println("loginViewShowingLoggedOutUser")
// self.profilePictureView.profileID = nil
}
func displayTabs()
{
println("displayTabs")
MBProgressHUD.showHUDAddedTo(self.view, animated:true)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
var tabbarController = UITabBarController()
let profileSelectorViewController = storyboard.instantiateViewControllerWithIdentifier("ProfileSelectorViewController") as ProfileSelectorViewController
let chatViewController = storyboard.instantiateViewControllerWithIdentifier("ChatViewController") as ChatViewController
let settingsViewController = storyboard.instantiateViewControllerWithIdentifier("SettingsViewController") as SettingsViewController
let profileSelectorNavigationController = UINavigationController(rootViewController: profileSelectorViewController)
let chatNavigationController = UINavigationController(rootViewController: chatViewController)
tabbarController.viewControllers = [ profileSelectorNavigationController, chatNavigationController, settingsViewController]
var tabbarItem = tabbarController.tabBar.items![0] as UITabBarItem;
tabbarItem.image = UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("groups", ofType: "png")!)
tabbarItem.title = nil
tabbarItem = tabbarController.tabBar.items![1] as UITabBarItem;
tabbarItem.image = UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("chat", ofType: "png")!)
tabbarItem.title = nil
tabbarItem = tabbarController.tabBar.items![2] as UITabBarItem;
tabbarItem.image = UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("settings", ofType: "png")!)
tabbarItem.title = nil
//println(tabbarController.viewControllers)
MBProgressHUD.hideHUDForView(self.view, animated:false)
self.presentViewController(tabbarController, animated: true, completion: nil)
}
func textFieldShouldReturn(textField: UITextField!) -> Bool
{
textField.resignFirstResponder()
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
cf674a8a996d1b70f9d4088a09ca4798
| 38.809701 | 177 | 0.55516 | false | false | false | false |
bradhilton/TableViewSource
|
refs/heads/master
|
TableViewSource/TableViewInterfaceSource/TableViewInterfaceSource.swift
|
mit
|
1
|
//
// TableViewInterfaceSource.swift
// TableViewSource
//
// Created by Bradley Hilton on 2/9/16.
// Copyright © 2016 Brad Hilton. All rights reserved.
//
let defaultTableView = UITableView()
protocol TableViewInterfaceSource : TableViewSource, TableViewInterface {}
extension TableViewInterfaceSource {
var rowHeight: CGFloat {
get {
return _interface.rowHeight
}
set {
interface?.rowHeight = newValue
}
}
var sectionHeaderHeight: CGFloat {
get {
return _interface.sectionHeaderHeight
}
set {
interface?.sectionHeaderHeight = newValue
}
}
var sectionFooterHeight: CGFloat {
get {
return _interface.sectionFooterHeight
}
set {
interface?.sectionFooterHeight = newValue
}
}
var estimatedRowHeight: CGFloat {
get {
return _interface.estimatedRowHeight
}
set {
interface?.estimatedRowHeight = newValue
}
}
var estimatedSectionHeaderHeight: CGFloat {
get {
return _interface.estimatedSectionHeaderHeight
}
set {
interface?.estimatedSectionHeaderHeight = newValue
}
}
var estimatedSectionFooterHeight: CGFloat {
get {
return _interface.estimatedSectionFooterHeight
}
set {
interface?.estimatedSectionFooterHeight = newValue
}
}
var separatorInset: UIEdgeInsets {
get {
return _interface.separatorInset
}
set {
interface?.separatorInset = newValue
}
}
var backgroundView: UIView? {
get {
return interface?.backgroundView
}
set {
interface?.backgroundView = newValue
}
}
func reloadData() {
interface?.reloadData()
}
func reloadSectionIndexTitles() {
interface?.reloadSectionIndexTitles()
}
func numberOfSectionsForSource(source: TableViewSource) -> Int {
return _interface.numberOfSectionsForSource(source)
}
func source(source: TableViewSource, numberOfRowsInSection section: Int) -> Int {
return _interface.source(source, numberOfRowsInSection: section)
}
func source(source: TableViewSource, rectForSection section: Int) -> CGRect {
return _interface.source(source, rectForSection: section)
}
func source(source: TableViewSource, rectForHeaderInSection section: Int) -> CGRect {
return _interface.source(source, rectForHeaderInSection: section)
}
func source(source: TableViewSource, rectForFooterInSection section: Int) -> CGRect {
return _interface.source(source, rectForFooterInSection: section)
}
func source(source: TableViewSource, rectForRowAtIndexPath indexPath: NSIndexPath) -> CGRect {
return _interface.source(source, rectForRowAtIndexPath: indexPath)
}
func source(source: TableViewSource, indexPathForRowAtPoint point: CGPoint) -> NSIndexPath? {
return interface?.source(source, indexPathForRowAtPoint: point)
}
func source(source: TableViewSource, indexPathForCell cell: UITableViewCell) -> NSIndexPath? {
return interface?.source(source, indexPathForCell: cell)
}
func source(source: TableViewSource, indexPathsForRowsInRect rect: CGRect) -> [NSIndexPath]? {
return interface?.source(source, indexPathsForRowsInRect: rect)
}
func source(source: TableViewSource, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell? {
return interface?.source(source, cellForRowAtIndexPath: indexPath)
}
var visibleCells: [UITableViewCell] {
return _interface.visibleCells
}
func indexPathsForVisibleRowsForSource(source: TableViewSource) -> [NSIndexPath]? {
return interface?.indexPathsForVisibleRowsForSource(source)
}
func source(source: TableViewSource, headerViewForSection section: Int) -> UITableViewHeaderFooterView? {
return interface?.source(source, headerViewForSection: section)
}
func source(source: TableViewSource, footerViewForSection section: Int) -> UITableViewHeaderFooterView? {
return interface?.source(source, footerViewForSection: section)
}
func source(source: TableViewSource, scrollToRowAtIndexPath indexPath: NSIndexPath, atScrollPosition scrollPosition: UITableViewScrollPosition, animated: Bool) {
interface?.source(source, scrollToRowAtIndexPath: indexPath, atScrollPosition: scrollPosition, animated: animated)
}
func scrollToNearestSelectedRowAtScrollPosition(scrollPosition: UITableViewScrollPosition, animated: Bool) {
interface?.scrollToNearestSelectedRowAtScrollPosition(scrollPosition, animated: animated)
}
func beginUpdates() {
interface?.beginUpdates()
}
func endUpdates() {
interface?.endUpdates()
}
func source(source: TableViewSource, insertSections sections: NSIndexSet, withRowAnimation animation: UITableViewRowAnimation) {
interface?.source(source, insertSections: sections, withRowAnimation: animation)
}
func source(source: TableViewSource, deleteSections sections: NSIndexSet, withRowAnimation animation: UITableViewRowAnimation) {
interface?.source(source, deleteSections: sections, withRowAnimation: animation)
}
func source(source: TableViewSource, reloadSections sections: NSIndexSet, withRowAnimation animation: UITableViewRowAnimation) {
interface?.source(source, reloadSections: sections, withRowAnimation: animation)
}
func source(source: TableViewSource, moveSection section: Int, toSection newSection: Int) {
interface?.source(source, moveSection: section, toSection: newSection)
}
func source(source: TableViewSource, insertRowsAtIndexPaths indexPaths: [NSIndexPath], withRowAnimation animation: UITableViewRowAnimation) {
interface?.source(source, insertRowsAtIndexPaths: indexPaths, withRowAnimation: animation)
}
func source(source: TableViewSource, deleteRowsAtIndexPaths indexPaths: [NSIndexPath], withRowAnimation animation: UITableViewRowAnimation) {
interface?.source(source, deleteRowsAtIndexPaths: indexPaths, withRowAnimation: animation)
}
func source(source: TableViewSource, reloadRowsAtIndexPaths indexPaths: [NSIndexPath], withRowAnimation animation: UITableViewRowAnimation) {
interface?.source(source, reloadRowsAtIndexPaths: indexPaths, withRowAnimation: animation)
}
func source(source: TableViewSource, moveRowAtIndexPath indexPath: NSIndexPath, toIndexPath newIndexPath: NSIndexPath) {
interface?.source(source, moveRowAtIndexPath: indexPath, toIndexPath: newIndexPath)
}
var editing: Bool {
get {
return _interface.editing
}
set {
interface?.editing = newValue
}
}
func setEditing(editing: Bool, animated: Bool) {
interface?.setEditing(editing, animated: animated)
}
var allowsSelection: Bool {
get {
return _interface.allowsSelection
}
set {
interface?.allowsSelection = newValue
}
}
var allowsSelectionDuringEditing: Bool {
get {
return _interface.allowsSelectionDuringEditing
}
set {
interface?.allowsSelectionDuringEditing = newValue
}
}
var allowsMultipleSelection: Bool {
get {
return _interface.allowsMultipleSelection
}
set {
interface?.allowsMultipleSelection = newValue
}
}
var allowsMultipleSelectionDuringEditing: Bool {
get {
return _interface.allowsMultipleSelectionDuringEditing
}
set {
interface?.allowsMultipleSelectionDuringEditing = newValue
}
}
func indexPathForSelectedRowForSource(source: TableViewSource) -> NSIndexPath? {
return interface?.indexPathForSelectedRowForSource(source)
}
func indexPathsForSelectedRowsForSource(source: TableViewSource) -> [NSIndexPath]? {
return interface?.indexPathsForSelectedRowsForSource(source)
}
func source(source: TableViewSource, selectRowAtIndexPath indexPath: NSIndexPath?, animated: Bool, scrollPosition: UITableViewScrollPosition) {
interface?.source(source, selectRowAtIndexPath: indexPath, animated: animated, scrollPosition: scrollPosition)
}
func source(source: TableViewSource, deselectRowAtIndexPath indexPath: NSIndexPath, animated: Bool) {
interface?.source(source, deselectRowAtIndexPath: indexPath, animated: animated)
}
var sectionIndexMinimumDisplayRowCount: Int {
get {
return _interface.sectionIndexMinimumDisplayRowCount
}
set {
interface?.sectionIndexMinimumDisplayRowCount = newValue
}
}
var sectionIndexColor: UIColor? {
get {
return interface?.sectionIndexColor
}
set {
interface?.sectionIndexColor = newValue
}
}
var sectionIndexBackgroundColor: UIColor? {
get {
return interface?.sectionIndexBackgroundColor
}
set {
interface?.sectionIndexBackgroundColor = newValue
}
}
var sectionIndexTrackingBackgroundColor: UIColor? {
get {
return interface?.sectionIndexTrackingBackgroundColor
}
set {
interface?.sectionIndexTrackingBackgroundColor = newValue
}
}
var separatorStyle: UITableViewCellSeparatorStyle {
get {
return _interface.separatorStyle
}
set {
interface?.separatorStyle = newValue
}
}
var separatorColor: UIColor? {
get {
return interface?.separatorColor
}
set {
interface?.separatorColor = newValue
}
}
var separatorEffect: UIVisualEffect? {
get {
return interface?.separatorEffect
}
set {
interface?.separatorEffect = newValue
}
}
var tableHeaderView: UIView? {
get {
return interface?.tableHeaderView
}
set {
interface?.tableHeaderView = newValue
}
}
var tableFooterView: UIView? {
get {
return interface?.tableFooterView
}
set {
interface?.tableFooterView = newValue
}
}
func dequeueReusableCellWithIdentifier(identifier: String) -> UITableViewCell? {
return interface?.dequeueReusableCellWithIdentifier(identifier)
}
func source(source: TableViewSource, dequeueReusableCellWithIdentifier identifier: String, forIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return _interface.source(source, dequeueReusableCellWithIdentifier: identifier, forIndexPath: indexPath)
}
func dequeueReusableHeaderFooterViewWithIdentifier(identifier: String) -> UITableViewHeaderFooterView? {
return interface?.dequeueReusableHeaderFooterViewWithIdentifier(identifier)
}
func registerNib(nib: UINib?, forCellReuseIdentifier identifier: String) {
interface?.registerNib(nib, forCellReuseIdentifier: identifier)
}
func registerClass(cellClass: AnyClass?, forCellReuseIdentifier identifier: String) {
interface?.registerClass(cellClass, forCellReuseIdentifier: identifier)
}
func registerNib(nib: UINib?, forHeaderFooterViewReuseIdentifier identifier: String) {
interface?.registerNib(nib, forHeaderFooterViewReuseIdentifier: identifier)
}
func registerClass(aClass: AnyClass?, forHeaderFooterViewReuseIdentifier identifier: String) {
interface?.registerClass(aClass, forHeaderFooterViewReuseIdentifier: identifier)
}
}
|
59c544d20bf09b94850bedbbee37eace
| 31.831099 | 165 | 0.662339 | false | false | false | false |
joseria/JADynamicTypeExampleInSwift
|
refs/heads/master
|
JADynamicTypeExample/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// JADynamicTypeExample
//
// Created by Alvarez, Jose (MTV) on 10/21/14.
// Copyright (c) 2014 Jose Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class ViewController: UIViewController {
// Labels
@IBOutlet weak var bodyLabel: UILabel!
@IBOutlet weak var caption1Label: UILabel!
@IBOutlet weak var caption2Label: UILabel!
@IBOutlet weak var footnoteLabel: UILabel!
@IBOutlet weak var headlineLabel: UILabel!
@IBOutlet weak var subheadlineLabel: UILabel!
// Buttons
@IBOutlet weak var bodyButton: UIButton!
@IBOutlet weak var caption1Button: UIButton!
@IBOutlet weak var caption2Button: UIButton!
@IBOutlet weak var footnoteButton: UIButton!
@IBOutlet weak var headlineButton: UIButton!
@IBOutlet weak var subheadlineButton: UIButton!
// Container view labels
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var bodyInView: UILabel!
@IBOutlet weak var caption1InView: UILabel!
@IBOutlet weak var caption2InView: UILabel!
@IBOutlet weak var footnoteInView: UILabel!
@IBOutlet weak var headlineInView: UILabel!
@IBOutlet weak var subheadlineInView: UITextView!
// Switchers
@IBOutlet weak var italicsLabel: UILabel!
@IBOutlet weak var boldLabel: UILabel!
@IBOutlet weak var italicsSwitch: UISwitch!
@IBOutlet weak var boldSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
containerView.layer.borderColor = UIColor.grayColor().CGColor
containerView.layer.borderWidth = 1.0
let fontDescriptor = UIFontDescriptor.preferredFontDescriptorWithTextStyle(UIFontTextStyleBody)
let italicsFontDescriptor = fontDescriptor.fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits.TraitItalic)
italicsLabel.font = UIFont(descriptor:italicsFontDescriptor, size:0)
let boldFontDescriptor = fontDescriptor.fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits.TraitBold)
boldLabel.font = UIFont(descriptor:boldFontDescriptor, size:0)
NSNotificationCenter.defaultCenter().addObserverForName(UIContentSizeCategoryDidChangeNotification, object: nil, queue: NSOperationQueue.mainQueue()) { (note:NSNotification) -> Void in
self.handleContentSizeCategoryDidChangeNotification()
}
}
func handleContentSizeCategoryDidChangeNotification () {
evaluateFonts()
}
func evaluateFonts () {
// Update labels
bodyLabel.font = evaluateFont(UIFontTextStyleBody)
caption1Label.font = evaluateFont(UIFontTextStyleCaption1)
caption2Label.font = evaluateFont(UIFontTextStyleCaption2)
footnoteLabel.font = evaluateFont(UIFontTextStyleFootnote)
headlineLabel.font = evaluateFont(UIFontTextStyleHeadline)
subheadlineLabel.font = evaluateFont(UIFontTextStyleSubheadline)
// Update buttons
bodyButton.titleLabel?.font = evaluateFont(UIFontTextStyleBody)
caption1Button.titleLabel?.font = evaluateFont(UIFontTextStyleCaption1)
caption2Button.titleLabel?.font = evaluateFont(UIFontTextStyleCaption2)
footnoteButton.titleLabel?.font = evaluateFont(UIFontTextStyleFootnote)
headlineButton.titleLabel?.font = evaluateFont(UIFontTextStyleHeadline)
subheadlineButton.titleLabel?.font = evaluateFont(UIFontTextStyleSubheadline)
// Update container view labels
bodyInView.font = evaluateFont(UIFontTextStyleBody)
caption1InView.font = evaluateFont(UIFontTextStyleCaption1)
caption2InView.font = evaluateFont(UIFontTextStyleCaption2)
footnoteInView.font = evaluateFont(UIFontTextStyleFootnote)
headlineInView.font = evaluateFont(UIFontTextStyleHeadline)
subheadlineInView.font = evaluateFont(UIFontTextStyleSubheadline)
}
// Helper function that handles displaying a font w/ italics and bold traits.
func evaluateFont(fontStyle:String)->UIFont {
let fontDescriptor = UIFontDescriptor.preferredFontDescriptorWithTextStyle(fontStyle)
var traitsDescriptor:UIFontDescriptor
if (italicsSwitch.on) {
traitsDescriptor = fontDescriptor.fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits.TraitItalic)
} else if (boldSwitch.on) {
traitsDescriptor = fontDescriptor.fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits.TraitBold)
} else {
traitsDescriptor = fontDescriptor
}
return UIFont(descriptor: traitsDescriptor, size: 0)
}
@IBAction func updateItalics(sender: UISwitch) {
// Reset bold since multiple trait support does not always work
boldSwitch.on = false
evaluateFonts()
}
@IBAction func updateBolds(sender: UISwitch) {
// Reset italics since multiple trait support does not always work
italicsSwitch.on = false
evaluateFonts()
}
}
|
1792eb143876968dc1ef8ec901fd48a2
| 43.536232 | 192 | 0.727302 | false | false | false | false |
RevenueCat/purchases-ios
|
refs/heads/main
|
Tests/UnitTests/TestHelpers/OSVersionEquivalent.swift
|
mit
|
1
|
//
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// OSVersion.swift
//
// Created by Nacho Soto on 4/13/22.
import Foundation
import UIKit
/// The equivalent version for the current device running tests.
/// Examples:
/// - `tvOS 15.1` maps to `.iOS15`
/// - `iOS 14.3` maps to `.iOS14`
/// - `macCatalyst 15.2` maps to `.iOS15`
enum OSVersionEquivalent: Int {
case iOS12 = 12
case iOS13 = 13
case iOS14 = 14
case iOS15 = 15
case iOS16 = 16
}
extension OSVersionEquivalent {
static let current: Self = {
#if os(macOS)
// Not currently supported
// Must convert e.g.: macOS 10.15 to iOS 13
fatalError(Error.unknownOS().localizedDescription)
#else
// Note: this is either iOS/tvOS/macCatalyst
// They all share equivalent versions
let majorVersion = ProcessInfo().operatingSystemVersion.majorVersion
guard let equivalent = Self(rawValue: majorVersion) else {
fatalError(Error.unknownOS().localizedDescription)
}
return equivalent
#endif
}()
}
private extension OSVersionEquivalent {
private enum Error: Swift.Error {
case unknownOS(systemName: String, version: String)
static func unknownOS() -> Self {
let device = UIDevice.current
return .unknownOS(systemName: device.systemName, version: device.systemVersion)
}
}
}
|
52833467dd4d651aee9015c81a66bc5c
| 23.101449 | 91 | 0.637402 | false | false | false | false |
OpenGenus/cosmos
|
refs/heads/master
|
code/data_structures/src/tree/binary_tree/binary_tree/tree/tree.swift
|
gpl-3.0
|
5
|
// Part of Cosmos by OpenGenus Foundation
public enum BinarySearchTree<T: Comparable> {
case empty
case leaf(T)
indirect case node(BinarySearchTree, T, BinarySearchTree)
public var count: Int {
switch self {
case .empty: return 0
case .leaf: return 1
case let .node(left, _, right): return left.count + 1 + right.count
}
}
public var height: Int {
switch self {
case .empty: return 0
case .leaf: return 1
case let .node(left, _, right): return 1 + max(left.height, right.height)
}
}
public func insert(newValue: T) -> BinarySearchTree {
switch self {
case .empty:
return .leaf(newValue)
case .leaf(let value):
if newValue < value {
return .node(.leaf(newValue), value, .empty)
} else {
return .node(.empty, value, .leaf(newValue))
}
case .node(let left, let value, let right):
if newValue < value {
return .node(left.insert(newValue), value, right)
} else {
return .node(left, value, right.insert(newValue))
}
}
}
public func search(x: T) -> BinarySearchTree? {
switch self {
case .empty:
return nil
case .leaf(let y):
return (x == y) ? self : nil
case let .node(left, y, right):
if x < y {
return left.search(x)
} else if y < x {
return right.search(x)
} else {
return self
}
}
}
public func contains(x: T) -> Bool {
return search(x) != nil
}
public func minimum() -> BinarySearchTree {
var node = self
var prev = node
while case let .node(next, _, _) = node {
prev = node
node = next
}
if case .leaf = node {
return node
}
return prev
}
public func maximum() -> BinarySearchTree {
var node = self
var prev = node
while case let .node(_, _, next) = node {
prev = node
node = next
}
if case .leaf = node {
return node
}
return prev
}
}
extension BinarySearchTree: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .empty: return "."
case .leaf(let value): return "\(value)"
case .node(let left, let value, let right):
return "(\(left.debugDescription) <- \(value) -> \(right.debugDescription))"
}
}
}
|
75a4668f7b9789c4e8b876c1ee12960b
| 22.019802 | 82 | 0.577204 | false | false | false | false |
prebid/prebid-mobile-ios
|
refs/heads/master
|
InternalTestApp/PrebidMobileDemoRendering/ViewControllers/Adapters/Prebid/GAM/UnifiedNativeAdView.swift
|
apache-2.0
|
1
|
/* Copyright 2018-2021 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import GoogleMobileAds
import PrebidMobile
class UnifiedNativeAdView: GADNativeAdView {
/// The height constraint applied to the ad view, where necessary.
private var heightConstraint: NSLayoutConstraint?
func renderUnifiedNativeAd(_ unifiedNativeAd: GADNativeAd) {
// Deactivate the height constraint that was set when the previous video ad loaded.
heightConstraint?.isActive = false
// Populate the native ad view with the native ad assets.
// The headline and mediaContent are guaranteed to be present in every native ad.
(headlineView as? UILabel)?.text = unifiedNativeAd.headline
mediaView?.mediaContent = unifiedNativeAd.mediaContent
// // Some native ads will include a video asset, while others do not. Apps can use the
// // GADVideoController's hasVideoContent property to determine if one is present, and adjust their
// // UI accordingly.
// let mediaContent = unifiedNativeAd.mediaContent
// if mediaContent.hasVideoContent {
// // By acting as the delegate to the GADVideoController, this ViewController receives messages
// // about events in the video lifecycle.
// mediaContent.videoController.delegate = self
// videoStatusLabel.text = "Ad contains a video asset."
// } else {
// videoStatusLabel.text = "Ad does not contain a video."
// }
// This app uses a fixed width for the GADMediaView and changes its height to match the aspect
// ratio of the media it displays.
if let mediaView = mediaView, unifiedNativeAd.mediaContent.aspectRatio > 0 {
heightConstraint = NSLayoutConstraint(
item: mediaView,
attribute: .height,
relatedBy: .equal,
toItem: mediaView,
attribute: .width,
multiplier: CGFloat(1 / unifiedNativeAd.mediaContent.aspectRatio),
constant: 0)
heightConstraint?.isActive = true
}
// These assets are not guaranteed to be present. Check that they are before
// showing or hiding them.
(bodyView as? UILabel)?.text = unifiedNativeAd.body
bodyView?.isHidden = unifiedNativeAd.body == nil
(callToActionView as? UIButton)?.setTitle(unifiedNativeAd.callToAction, for: .normal)
callToActionView?.isHidden = unifiedNativeAd.callToAction == nil
(iconView as? UIImageView)?.image = unifiedNativeAd.icon?.image
iconView?.isHidden = unifiedNativeAd.icon == nil
(starRatingView as? UIImageView)?.image = imageOfStars(from: unifiedNativeAd.starRating)
starRatingView?.isHidden = unifiedNativeAd.starRating == nil
(storeView as? UILabel)?.text = unifiedNativeAd.store
storeView?.isHidden = unifiedNativeAd.store == nil
(priceView as? UILabel)?.text = unifiedNativeAd.price
priceView?.isHidden = unifiedNativeAd.price == nil
(advertiserView as? UILabel)?.text = unifiedNativeAd.advertiser
advertiserView?.isHidden = unifiedNativeAd.advertiser == nil
// In order for the SDK to process touch events properly, user interaction should be disabled.
callToActionView?.isUserInteractionEnabled = false
// Associate the native ad view with the native ad object. This is
// required to make the ad clickable.
// Note: this should always be done after populating the ad views.
nativeAd = unifiedNativeAd
}
/// Returns a `UIImage` representing the number of stars from the given star rating; returns `nil`
/// if the star rating is less than 3.5 stars.
private func imageOfStars(from starRating: NSDecimalNumber?) -> UIImage? {
guard let rating = starRating?.doubleValue else {
return nil
}
if rating >= 5 {
return UIImage(named: "stars_5")
} else if rating >= 4.5 {
return UIImage(named: "stars_4_5")
} else if rating >= 4 {
return UIImage(named: "stars_4")
} else if rating >= 3.5 {
return UIImage(named: "stars_3_5")
} else {
return nil
}
}
}
|
6f49f04dc56e6cd0b34f30243ffc43ab
| 43.681818 | 107 | 0.650865 | false | false | false | false |
hovansuit/FoodAndFitness
|
refs/heads/master
|
FoodAndFitness/Controllers/History/HistoryViewModel.swift
|
mit
|
1
|
//
// HistoryViewModel.swift
// FoodAndFitness
//
// Created by Mylo Ho on 4/26/17.
// Copyright © 2017 SuHoVan. All rights reserved.
//
import UIKit
import RealmS
import RealmSwift
import SwiftDate
class HistoryViewModel {
let breakfastFoods: [UserFood]
let lunchFoods: [UserFood]
let dinnerFoods: [UserFood]
let userExercises: [UserExercise]
let trackings: [Tracking]
let date: Date
fileprivate let userFoods: [UserFood]
init(date: Date) {
self.date = date
let realm = RealmS()
userFoods = realm.objects(UserFood.self).filter { (userFood) -> Bool in
guard let me = User.me, let user = userFood.userHistory?.user else { return false }
return me.id == user.id && userFood.createdAt.isInSameDayOf(date: date)
}
breakfastFoods = userFoods.filter({ (userFood) -> Bool in
return userFood.meal == HomeViewController.AddActivity.breakfast.title
})
lunchFoods = userFoods.filter({ (userFood) -> Bool in
return userFood.meal == HomeViewController.AddActivity.lunch.title
})
dinnerFoods = userFoods.filter({ (userFood) -> Bool in
return userFood.meal == HomeViewController.AddActivity.dinner.title
})
userExercises = realm.objects(UserExercise.self).filter({ (userExercise) -> Bool in
guard let me = User.me, let user = userExercise.userHistory?.user else { return false }
return me.id == user.id && userExercise.createdAt.isInSameDayOf(date: date)
})
trackings = realm.objects(Tracking.self).filter { (tracking) -> Bool in
guard let me = User.me, let user = tracking.userHistory?.user else { return false }
return me.id == user.id && tracking.createdAt.isInSameDayOf(date: date)
}
}
func dataForProgressCell() -> ProgressCell.Data? {
guard let userHistory = RealmS().objects(UserHistory.self).filter({ (userHistory) -> Bool in
let userHistoryDate = DateInRegion(absoluteDate: userHistory.createdAt).ffDate()
let historyDate = DateInRegion(absoluteDate: self.date).ffDate()
return userHistoryDate <= historyDate
}).last else { return nil }
var eaten = eatenToday()
let burn = burnToday()
let calories = userHistory.caloriesToday + Double(burn)
if Int(calories) - eaten < 0 {
eaten = Int(calories)
}
let carbsString = "\(carbsLeft(calories: calories))" + Strings.gLeft
let proteinString = "\(proteinLeft(calories: calories))" + Strings.gLeft
let fatString = "\(fatLeft(calories: calories))" + Strings.gLeft
return ProgressCell.Data(calories: Int(calories), eaten: eaten, burn: burn, carbs: carbsString, protein: proteinString, fat: fatString)
}
private func eatenToday() -> Int {
let eaten = userFoods.map { (userFood) -> Int in
return userFood.calories
}.reduce(0) { (result, calories) -> Int in
return result + calories
}
return eaten
}
private func carbsLeft(calories: Double) -> Int {
let carbsUserFoods = userFoods.map { (userFood) -> Int in
return userFood.carbs
}.reduce(0) { (result, carbs) -> Int in
return result + carbs
}
let carbsLeft = carbs(calories: calories) - carbsUserFoods
if carbsLeft < 0 {
return 0
} else {
return carbsLeft
}
}
private func proteinLeft(calories: Double) -> Int {
let proteinUserFoods = userFoods.map { (userFood) -> Int in
return userFood.protein
}.reduce(0) { (result, protein) -> Int in
return result + protein
}
let proteinLeft = protein(calories: calories) - proteinUserFoods
if proteinLeft < 0 {
return 0
} else {
return proteinLeft
}
}
private func fatLeft(calories: Double) -> Int {
let fatUserFoods = userFoods.map { (userFood) -> Int in
return userFood.fat
}.reduce(0) { (result, fat) -> Int in
return result + fat
}
let fatLeft = fat(calories: calories) - fatUserFoods
if fatLeft < 0 {
return 0
} else {
return fatLeft
}
}
private func burnToday() -> Int {
let exercisesBurn = userExercises.map { (userExercise) -> Int in
return userExercise.calories
}.reduce(0) { (result, calories) -> Int in
return result + calories
}
let trackingsBurn = trackings.map { (tracking) -> Int in
return tracking.caloriesBurn
}.reduce(0) { (result, calories) -> Int in
return result + calories
}
return exercisesBurn + trackingsBurn
}
}
|
83dab694fef37ece27a4622956caeb77
| 36.356061 | 143 | 0.594808 | false | false | false | false |
akisute/ReactiveCocoaSwift
|
refs/heads/master
|
ReactiveCocoaSwift/Views/ListViewController.swift
|
mit
|
1
|
//
// ListViewController.swift
// ReactiveCocoaSwift
//
// Created by Ono Masashi on 2015/01/14.
// Copyright (c) 2015年 akisute. All rights reserved.
//
import UIKit
import ReactiveCocoa
class ListViewController: UITableViewController {
var presentation: ListViewControllerPresentation!
// MARK: - UIViewController
override func viewDidLoad() {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: nil, action: nil)
self.navigationItem.rightBarButtonItem?.rac_command = RACCommand(signalBlock: { (sender: AnyObject!) -> RACSignal! in
self.presentation.addNote()
return RACSignal.empty()
})
self.presentation.documentUpdatedSignal.subscribeNext { (notesValue: AnyObject!) -> Void in
self.tableView.reloadData()
}
}
// MARK: - UITableViewDelegate
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.presentation.numberOfSections
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.presentation.numberOfRowsInSection(section)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellIdentifier = "Cell"
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as UITableViewCell
let note = self.presentation.noteForRowAtIndexPath(indexPath)
cell.textLabel?.text = note.text
cell.detailTextLabel?.text = note.timestamp
return cell
}
}
|
68fbe88608315f08882dd275afc64098
| 34.875 | 139 | 0.698026 | false | false | false | false |
dulingkang/Capture
|
refs/heads/master
|
Capture/Capture/Util/CustumPhotoAlbum.swift
|
mit
|
1
|
//
// CustumPhotoAlbum.swift
// Capture
//
// Created by dulingkang on 15/11/15.
// Copyright © 2015 ShawnDu. All rights reserved.
//
import UIKit
import Photos
class CustomPhotoAlbum {
var assetCollection: PHAssetCollection!
var albumFound : Bool = false
var photosAsset: PHFetchResult!
var collection: PHAssetCollection!
var assetCollectionPlaceholder: PHObjectPlaceholder!
static let albumName = "爱拍美图"
class var sharedInstance: CustomPhotoAlbum {
struct Singleton {
static let instance = CustomPhotoAlbum()
}
return Singleton.instance
}
init() {
self.createAlbum()
}
private func createAlbum() {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", CustomPhotoAlbum.albumName)
let collection : PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)
if let _: AnyObject = collection.firstObject {
self.albumFound = true
assetCollection = collection.firstObject as! PHAssetCollection
} else {
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let createAlbumRequest : PHAssetCollectionChangeRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(CustomPhotoAlbum.albumName)
self.assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection
}, completionHandler: { success, error in
self.albumFound = (success ? true: false)
if (success) {
let collectionFetchResult = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([self.assetCollectionPlaceholder.localIdentifier], options: nil)
print(collectionFetchResult)
self.assetCollection = collectionFetchResult.firstObject as! PHAssetCollection
}
})
}
}
// performChanges(changeBlock: dispatch_block_t, completionHandler: ((Bool, NSError?) -> Void)?)
func saveImage(image: UIImage) {
if self.assetCollection != nil {
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let assetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
let assetPlaceholder = assetChangeRequest.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection)
albumChangeRequest?.addAssets([assetPlaceholder!])
}, completionHandler: {
success, error in
if error != nil {
print(error)
} else {
}
})
}
}
}
|
50e4975bc20fab80d1bf9f032b30dfa7
| 39.506849 | 176 | 0.628678 | false | false | false | false |
jxxcarlson/exploring_swift
|
refs/heads/master
|
heatFlow.playground/Contents.swift
|
mit
|
1
|
import Cocoa
typealias vector = [Double]
typealias matrix = [vector]
func next_state(x: vector, k: Double) -> vector {
var y = vector(count: x.count, repeatedValue:0.0)
let lastIndex = x.count - 1
// Boundary conditions:
y[0] = x[0]
y[lastIndex] = x[lastIndex]
for (var i = 1; i < lastIndex; i++) {
let u = (k/2)*(x[i-1] + x[i + 1])
let v = (1-k)*x[i]
y[i] = u + v
}
return y
}
func run(initial_state:vector, n: Int) -> matrix {
var sa:matrix = [initial_state]
for(var i = 1; i < n; i++) {
sa = sa + [next_state(sa[i-1], k: 0.8)]
}
return sa
}
var c1: vector = [1.0, 0, 0, 0, 0, 0.3, 0.9, 0.3, 0, 0]
var result = run(c1, n: 10)
for state in result {
print(state)
}
print(result[0])
result.count
result[0].count
class Thermograph {
var state = vector()
init( data: vector ) {
state = data
}
func draw(frame: NSRect) {
let width = frame.width
let height = frame.height
let n = state.count
var x = CGFloat(0.0)
let dx = CGFloat(width/CGFloat(n))
for (var i = 0; i < n; i++) {
let currentRect = NSMakeRect(x, 0, dx, height)
x = x + dx
let temperature = CGFloat(state[i])
let currentColor = NSColor(red: temperature, green: 0.0,
blue: 0.0, alpha: 1.0)
currentColor.set()
NSRectFill(currentRect)
}
}
}
class Thermograph2D {
var state = matrix()
init( data: matrix ) {
state = data
}
func draw(frame: NSRect) {
let width = frame.width
let height = frame.height
let n_rows = state.count
let n_cols = (state[0]).count
var x = CGFloat(0.0)
var y = CGFloat(0.0)
let dx = CGFloat(width/CGFloat(n_cols))
let dy = CGFloat(height/CGFloat(n_rows))
for (var row = 0; row < n_rows; row++) {
x = CGFloat(0.0)
for (var col = 0; col < n_cols; col++ ) {
let currentRect = NSMakeRect(x, y, dx, dy)
x = x + dx
let temperature = CGFloat(state[row][col])
print("t[\(row),\(col)] = \(temperature)")
let currentColor = NSColor(red: temperature, green: 0.0,
blue: 0.0, alpha: 1.0)
currentColor.set()
NSRectFill(currentRect)
}
y = y + dy
}
}
}
let k = 3
let tg = Thermograph(data:result[k])
// let tg = Thermograph(data:[1, 0.8, 0.6, 0.4, 0.2, 0.0, 0.2, 0.4, 0.6, 0.8, 1.0])
print(tg.state)
class GView: NSView {
override func drawRect(dirtyRect: NSRect) {
tg.draw(frame)
}
}
let view = GView(frame: NSRect(x: 0, y: 0, width: 500, height: 20))
let tg2d = Thermograph2D(data: result)
class GView2D: NSView {
override func drawRect(dirtyRect: NSRect) {
tg2d.draw(frame)
}
}
let view2D = GView2D(frame: NSRect(x: 0, y: 0, width: 500, height: 500))
|
5596f6832377fc9fadce2b51395daf51
| 20.085526 | 83 | 0.489236 | false | false | false | false |
TENDIGI/Obsidian-UI-iOS
|
refs/heads/master
|
src/CharacterTextView.swift
|
mit
|
1
|
//
// CharacterTextView.swift
// Alfredo
//
// Created by Eric Kunz on 10/26/15.
// Copyright © 2015 TENDIGI, LLC. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
import CoreText
class CharacterTextView: UITextView, NSLayoutManagerDelegate {
var oldCharacterTextLayers: [CALayer] = []
var characterTextLayers: [CALayer] = []
override var text: String! {
get {
return super.text
}
set {
self.attributedText = NSAttributedString(string: newValue)
}
}
override var attributedText: NSAttributedString! {
get {
return super.attributedText
}
set {
cleanOutOldCharacterTextLayers()
oldCharacterTextLayers = Array<CALayer>(characterTextLayers)
let newAttributedText = NSMutableAttributedString(attributedString: newValue)
newAttributedText.addAttribute(NSAttributedStringKey.foregroundColor, value:UIColor.clear, range: NSRange(location: 0, length: newValue.length))
super.attributedText = newAttributedText
}
}
override init(frame: CGRect, textContainer: NSTextContainer!) {
super.init(frame: frame, textContainer: textContainer)
setupLayoutManager()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLayoutManager()
}
override func awakeFromNib() {
super.awakeFromNib()
setupLayoutManager()
}
func setupLayoutManager() {
layoutManager.delegate = self
}
func layoutManager(_ layoutManager: NSLayoutManager, didCompleteLayoutFor textContainer: NSTextContainer?, atEnd layoutFinishedFlag: Bool) {
calculateTextLayers()
}
func calculateTextLayers() {
let wordRange = NSRange(location: 0, length: attributedText.length)
let attributedString = self.internalAttributedText()
// for var index = wordRange.location; index < wordRange.length+wordRange.location; index += 0 {
// let glyphRange = NSRange(location: index, length: 1)
// let characterRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange:nil)
// let textContainer = layoutManager.textContainer(forGlyphAt: index, effectiveRange: nil)
// var glyphRect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer!)
// let location = layoutManager.location(forGlyphAt: index)
// let kerningRange = layoutManager.range(ofNominallySpacedGlyphsContaining: index)
//
// if kerningRange.length > 1 && kerningRange.location == index {
// let previousLayer = self.characterTextLayers[self.characterTextLayers.endIndex]
// var frame = previousLayer.frame
// frame.size.width += (glyphRect.maxX+location.x)-frame.maxX
// previousLayer.frame = frame
// }
//
//
// glyphRect.origin.y += location.y-(glyphRect.height/2)
// let textLayer = CATextLayer(frame: glyphRect, string: (attributedString?.attributedSubstring(from: characterRange))!)
//
// layer.addSublayer(textLayer)
// characterTextLayers.append(textLayer)
//
// let stepGlyphRange = layoutManager.glyphRange(forCharacterRange: characterRange, actualCharacterRange:nil)
// index += stepGlyphRange.length
// }
}
func internalAttributedText() -> NSMutableAttributedString! {
let wordRange = NSRange(location: 0, length: self.attributedText.length)
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(NSAttributedStringKey.foregroundColor, value: textColor!.cgColor, range: wordRange)
attributedText.addAttribute(NSAttributedStringKey.font, value: font!, range: wordRange)
return attributedText
}
func cleanOutOldCharacterTextLayers() {
//Remove all text layers from the superview
for textLayer in oldCharacterTextLayers {
textLayer.removeFromSuperlayer()
}
//clean out the text layer
characterTextLayers.removeAll(keepingCapacity: false)
}
}
|
f7614c5a4e9d6fd2631dc6590fbf7663
| 35.594828 | 156 | 0.669022 | false | false | false | false |
Coderian/SwiftedGPX
|
refs/heads/master
|
SwiftedGPX/Elements/Satellites.swift
|
mit
|
1
|
//
// Sat.swift
// SwiftedGPX
//
// Created by 佐々木 均 on 2016/02/16.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// GPX Satellites
///
/// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd)
///
/// <xsd:element name="sat" type="xsd:nonNegativeInteger" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// Number of satellites used to calculate the GPX fix.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
public class Satellites : SPXMLElement, HasXMLElementValue, HasXMLElementSimpleValue {
public static var elementName: String = "sat"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch parent {
case let v as WayPoint: v.value.sat = self
case let v as TrackPoint: v.value.sat = self
case let v as RoutePoint: v.value.sat = self
default: break
}
}
}
}
public var value: UInt!
public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement{
self.value = UInt(contents)
self.parent = parent
return parent
}
public required init(attributes:[String:String]){
super.init(attributes: attributes)
}
}
|
08f3c3907e08084d0053687bb00735c3
| 30.404255 | 86 | 0.589153 | false | false | false | false |
izotx/iTenWired-Swift
|
refs/heads/master
|
Conference App/MapViewController.swift
|
bsd-2-clause
|
1
|
// Copyright (c) 2016, Izotx
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Izotx nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// MapViewController.swift
// Conference App
//
// Created by Julian L on 4/8/16.
import UIKit
import MapKit
import CoreLocation
class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
// Outlets for Map, and Segment Result
@IBOutlet weak var segmentResult: UISegmentedControl!
@IBOutlet weak var mainMap: MKMapView!
@IBOutlet weak var segmentStyle: UISegmentedControl!
/// CLLocation Manager
var locationManager: CLLocationManager = CLLocationManager()
/// The Start Location
var startLocation: CLLocation!
/// The destination location
var destination: MKMapItem?
// Pulls Map Data
var mapController: MapData = MapData()
var locArray: [ConferenceLocation] = []
var annotationArray: [AddAnnotation] = []
// Coordinates for Center Location
var latSum:Double = 0.00
var longSum:Double = 0.00
// Fallback in case JSON does not load
var mainLatitude: CLLocationDegrees = 30.331991 // Need to get from JSON
var mainLongitude: CLLocationDegrees = -87.136002 // Need to get from JSON
var locationStatus : NSString = "Not Started"
@IBAction func openDirections(sender: AnyObject) {
// Segmented Control on the Bottom of Screen (iTenWired, My Location, & Directions)
switch sender.selectedSegmentIndex
{
case 0:
// Show All Map Annotations
let newCoords = CLLocationCoordinate2D(latitude: CLLocationDegrees(latSum), longitude: CLLocationDegrees(longSum))
let span = MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5)
let newRegion:MKCoordinateRegion = MKCoordinateRegion(center:newCoords, span:span )
self.mainMap.setRegion(newRegion, animated: true)
case 1:
// Show User's Location on the Map
self.mainMap.showsUserLocation = true;
let latDelta:CLLocationDegrees = 0.04
let lonDelta:CLLocationDegrees = 0.04
// If lat & long are available, center map on location
if let latitude:CLLocationDegrees = locationManager.location?.coordinate.latitude {
if let longitude:CLLocationDegrees = locationManager.location?.coordinate.longitude {
let userLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
let region:MKCoordinateRegion = MKCoordinateRegionMake(userLocation, span)
mainMap.setRegion(region, animated: false)
}
}
default:
break;
}
}
@IBAction func menuButtonAction(sender: AnyObject) {
if let splitController = self.splitViewController{
if !splitController.collapsed {
splitController.toggleMasterView()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
segmentStyle.layer.cornerRadius = 5
// Setup the Map and Location Manager
self.locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
self.mainMap.delegate = self
startLocation = nil
// Retrieves locations from MapData and loaded into locArray
for locs in mapController.conferenceLocations {
locArray.append(locs)
}
if (annotationArray.count == 0) {
addNotations()
}
if let splitController = self.splitViewController{
splitController.toggleMasterView()
}
}
// Adds the Info Button to all of the Annotations
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "LocationAnnotation"
if annotation.isKindOfClass(AddAnnotation.self) {
if let annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) {
annotationView.annotation = annotation
return annotationView
} else {
let annotationView = MKPinAnnotationView(annotation:annotation, reuseIdentifier:identifier)
annotationView.enabled = true
annotationView.canShowCallout = true
let btn = UIButton(type: .DetailDisclosure)
annotationView.rightCalloutAccessoryView = btn
return annotationView
}
}
return nil
}
// Object that Selected Map Annotation will be Stored In
var selectedAnnotation: AddAnnotation!
// Called when Annotation Info Button is Selected
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView {
if let tempName = view.annotation?.title, let tempLat = view.annotation?.coordinate.latitude, let tempLong = view.annotation?.coordinate.longitude, let tempSub = view.annotation?.subtitle {
let tempCoord = CLLocationCoordinate2D(latitude: tempLat, longitude: tempLong)
selectedAnnotation = AddAnnotation(title: tempName!, coordinate: tempCoord, info: tempSub!)
}
//selectedAnnotation = view.annotation as? MKPointAnnotation
// Launches AnnotationDetailViewController
performSegueWithIdentifier("NextScene", sender: self)
}
}
// Preparing to segue to AnnotationDetailViewController and sending the selected annotation data with it
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let destination = segue.destinationViewController as? AnnotationDetailViewController {
destination.receivedAnnotation = selectedAnnotation
}
}
// This is called when viewDidLoad() and sets up all of the annotations on the map
func addNotations() {
// Centers Map on Main Location (Called on Launch)
var count = 0.00
// All locations "loc" are stored in this array and converted into annotations
for locs in locArray {
if let tempLat = CLLocationDegrees(locs.latitude), let tempLong = CLLocationDegrees(locs.longitude), let tempName:String = locs.name, let tempDesc:String = locs.description {
let tempCoord = CLLocationCoordinate2D(latitude: CLLocationDegrees(tempLat), longitude: CLLocationDegrees(tempLong))
latSum += Double(tempLat)
longSum += Double(tempLong)
let tempAnnotation = AddAnnotation(title: tempName, coordinate: tempCoord, info: tempDesc)
annotationArray.append(tempAnnotation)
count += 1
}
}
// Add annotations to the map
if !(annotationArray.isEmpty) {
self.mainMap.addAnnotations(annotationArray)
// Gets the average coordinates to center the map region on
latSum = latSum/count
longSum = longSum/count
// Centers the map based on average of locations
let newCoords = CLLocationCoordinate2D(latitude: CLLocationDegrees(latSum), longitude: CLLocationDegrees(longSum))
let span = MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5)
let newRegion:MKCoordinateRegion = MKCoordinateRegion(center:newCoords, span:span )
self.mainMap.setRegion(newRegion, animated: true)
self.mainMap.showsUserLocation = true;
}
else {
// // Presents an error message saying "No Internet Connection"
// let noInternet = UIAlertController(title: "Internet Connection", message: "Map cannot be loaded because there is no internet connection.", preferredStyle: UIAlertControllerStyle.Alert)
//
// noInternet.addAction(UIAlertAction(title: "Dismiss", style: .Default, handler: { (action: UIAlertAction!) in
// print("Handle Ok logic here")
// }))
//
// presentViewController(noInternet, animated: true, completion: nil)
latSum = mainLatitude
longSum = mainLongitude
let newCoords = CLLocationCoordinate2D(latitude: CLLocationDegrees(latSum), longitude: CLLocationDegrees(longSum))
let span = MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5)
let newRegion:MKCoordinateRegion = MKCoordinateRegion(center:newCoords, span:span )
self.mainMap.setRegion(newRegion, animated: true)
}
}
func locationManager(manager: CLLocationManager,
didChangeAuthorizationStatus status: CLAuthorizationStatus) {
var shouldIAllow = false
switch status {
case CLAuthorizationStatus.Restricted:
locationStatus = "Restricted Access to location"
case CLAuthorizationStatus.Denied:
locationStatus = "User denied access to location"
case CLAuthorizationStatus.NotDetermined:
locationStatus = "Status not determined"
default:
locationStatus = "Allowed to location Access"
shouldIAllow = true
}
NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
if (shouldIAllow == true) {
NSLog("Location to Allowed")
// Start location services
locationManager.startUpdatingLocation()
} else {
NSLog("Denied access: \(locationStatus)")
}
}
@IBAction func showMenu(sender: AnyObject) {
if let splitController = self.splitViewController{
if !splitController.collapsed {
splitController.toggleMasterView()
} else{
let rightNavController = splitViewController!.viewControllers.first as! UINavigationController
rightNavController.popToRootViewControllerAnimated(true)
}
}
}
}
|
7b4900d3f088818231f9297f0330fa07
| 41.248276 | 201 | 0.639732 | false | false | false | false |
lijianwei-jj/OOSegmentViewController
|
refs/heads/master
|
OOSegmentViewController/OOCursorMoveEffect.swift
|
mit
|
1
|
//
// OOCursorMoveEffect.swift
// OOSegmentViewController
//
// Created by lee on 16/7/6.
// Copyright © 2016年 clearlove. All rights reserved.
//
import UIKit
@objc public protocol CursorMoveEffect {
@objc optional func scroll(_ scrollView:UIScrollView,navBar:OOSegmentNavigationBar,cursor:UIView,newItem:UIButton,oldItem:UIButton);
@objc optional func scroll(_ scrollView:UIScrollView,navBar:OOSegmentNavigationBar,cursor:UIView,fullWidth:CGFloat,xScale:CGFloat,correctXScale:CGFloat,computeWidth:CGFloat,leftXOffset:CGFloat,centerXOffset:CGFloat,finished:Bool);
}
open class OOCursorMoveEffect: CursorMoveEffect {
// @objc public func scroll(scrollView: UIScrollView, navBar: OOSegmentNavigationBar, cursor: UIView, newItem: UIButton, oldItem: UIButton) {
// let fullWidth = CGRectGetWidth(scrollView.frame)
// let button = newItem , oldButton = oldItem
//
// let xScale = scrollView.contentOffset.x % fullWidth / fullWidth
//
// let indicatorWidth = button.frame.size.width // titleWidthAtFont(titleFont, index: index)
// let oldWidth = oldButton.frame.size.width // titleWidthAtFont(titleFont, index: oldIndex)
// let f = CGFloat(newItem.tag - oldItem.tag)
// var s = (f > 0 ? 1.0 - (xScale == 0 ? 1.0 : xScale) : xScale) // == 1.0 ? xScale : 0
// s = s < 0.01 || s > 0.99 ? round(s) : s
// let w = (oldWidth - indicatorWidth) * s + indicatorWidth
// let xOffset = (oldButton.center.x - button.center.x) * s
// let x = xOffset + button.center.x
// // print(xOffset)
// // print("nx:\(button.center.x) ox:\(oldButton.center.x) x:\(x) f:\(f) s:\(s) xs:\(xScale)")
//
//
// cursor.frame.size.width = w
// cursor.center.x = x
// if navBar.contentSize.width > fullWidth {
// UIView.animateWithDuration(0.3) {
// if CGRectGetMaxX(navBar.bounds) < CGRectGetMaxX(button.frame) + 2 {
// navBar.contentOffset.x += (CGRectGetMaxX(button.frame) - CGRectGetMaxX(navBar.bounds) + 2) + navBar.itemOffset
// } else if CGRectGetMinX(navBar.bounds) > CGRectGetMinX(button.frame) - 2 {
// navBar.contentOffset.x = CGRectGetMinX(button.frame) - 2 - navBar.itemOffset
// }
// }
// }
// }
@objc open func scroll(_ scrollView: UIScrollView, navBar: OOSegmentNavigationBar, cursor: UIView, fullWidth: CGFloat, xScale: CGFloat, correctXScale: CGFloat, computeWidth: CGFloat, leftXOffset: CGFloat, centerXOffset: CGFloat, finished: Bool) {
// let maxMargin = fullWidth - computeWidth - navBar.itemMargin - navBar.itemOffset
// let effect = OOCursorLeftDockMoveEffect(leftMargin: leftXOffset >= maxMargin ? maxMargin : leftXOffset )
// effect.scroll(scrollView, navBar: navBar, cursor: cursor, fullWidth: fullWidth, xScale: xScale, correctXScale: correctXScale, computeWidth: computeWidth, leftXOffset: leftXOffset, centerXOffset: centerXOffset, finished: finished)
cursor.frame.size.width = computeWidth
cursor.center.x = centerXOffset
let minOffset = leftXOffset - navBar.itemOffset,
maxOffset = leftXOffset + computeWidth + navBar.itemOffset
if navBar.bounds.maxX < maxOffset {
navBar.contentOffset.x += maxOffset - navBar.bounds.maxX
} else if navBar.contentOffset.x > minOffset {
navBar.contentOffset.x = minOffset
}
}
}
open class OOCursorCenterMoveEffect : CursorMoveEffect {
//
// @objc public func scroll(scrollView: UIScrollView, navBar: OOSegmentNavigationBar, cursor: UIView, newItem: UIButton, oldItem: UIButton) {
// let fullWidth = CGRectGetWidth(scrollView.frame)
// let button = newItem , oldButton = oldItem
//
// let xScale = scrollView.contentOffset.x % fullWidth / fullWidth
//
// let indicatorWidth = button.frame.size.width // titleWidthAtFont(titleFont, index: index)
// let oldWidth = oldButton.frame.size.width // titleWidthAtFont(titleFont, index: oldIndex)
// let f = CGFloat(newItem.tag - oldItem.tag)
// var s = (f > 0 ? 1.0 - (xScale == 0 ? 1.0 : xScale) : xScale) // == 1.0 ? xScale : 0
// s = s < 0.01 || s > 0.99 ? round(s) : s
// let w = (oldWidth - indicatorWidth) * s + indicatorWidth
// let xOffset = (oldButton.center.x - button.center.x) * s
// let x = xOffset + button.center.x
// // print(xOffset)
// // print("nx:\(button.center.x) ox:\(oldButton.center.x) x:\(x) f:\(f) s:\(s) xs:\(xScale)")
//
//
// cursor.frame.size.width = w
// cursor.center.x = x
// if navBar.contentSize.width > fullWidth {
// var offset = CGFloat(0)
// if button.center.x < fullWidth / 2.0 || button.center.x > navBar.contentSize.width - fullWidth / 2.0 {
// offset = button.center.x < fullWidth / 2.0 ? fullWidth / 2.0 - button.center.x : navBar.contentSize.width - fullWidth / 2.0 - button.center.x
// }
// UIView.animateWithDuration(0.3) {
// navBar.contentOffset.x = button.center.x - fullWidth / 2.0 + offset
// }
// }
// }
@objc open func scroll(_ scrollView: UIScrollView, navBar: OOSegmentNavigationBar, cursor: UIView, fullWidth: CGFloat, xScale: CGFloat, correctXScale: CGFloat, computeWidth: CGFloat, leftXOffset: CGFloat, centerXOffset: CGFloat, finished: Bool) {
let effect = OOCursorLeftDockMoveEffect(leftMargin: (fullWidth - computeWidth) / 2.0)
effect.scroll(scrollView, navBar: navBar, cursor: cursor, fullWidth: fullWidth, xScale: xScale, correctXScale: correctXScale, computeWidth: computeWidth, leftXOffset: centerXOffset - computeWidth / 2.0, centerXOffset: centerXOffset, finished: finished)
}
}
open class OOCursorLeftDockMoveEffect : CursorMoveEffect {
open var leftMargin : CGFloat
public init(leftMargin:CGFloat = 40) {
self.leftMargin = leftMargin
}
// @objc public func scroll(scrollView: UIScrollView, navBar: OOSegmentNavigationBar, cursor: UIView, newItem: UIButton, oldItem: UIButton) {
// let fullWidth = CGRectGetWidth(scrollView.frame)
// let button = newItem , oldButton = oldItem
//
// let xScale = scrollView.contentOffset.x % fullWidth / fullWidth
//
// let indicatorWidth = button.frame.size.width // titleWidthAtFont(titleFont, index: index)
// let oldWidth = oldButton.frame.size.width // titleWidthAtFont(titleFont, index: oldIndex)
// let f = CGFloat(newItem.tag - oldItem.tag)
// var s = (f > 0 ? 1.0 - (xScale == 0 ? 1.0 : xScale) : xScale) // == 1.0 ? xScale : 0
// s = s < 0.01 || s > 0.99 ? round(s) : s
// let w = round((oldWidth - indicatorWidth) * s + indicatorWidth)
// let xOffset = round((oldButton.frame.origin.x - button.frame.origin.x) * s)
// let x = xOffset + button.frame.origin.x
//
// cursor.frame.size.width = w
// cursor.frame.origin.x = x
// if navBar.contentSize.width > fullWidth {
// let targetX = x - navBar.itemMargin - leftMargin
// if targetX <= navBar.contentSize.width - fullWidth && targetX >= 0 {
// navBar.contentOffset.x = targetX
// }
// }
//
// }
@objc open func scroll(_ scrollView: UIScrollView, navBar: OOSegmentNavigationBar, cursor: UIView, fullWidth: CGFloat, xScale: CGFloat, correctXScale: CGFloat, computeWidth: CGFloat, leftXOffset: CGFloat, centerXOffset: CGFloat, finished: Bool) {
cursor.frame.size.width = computeWidth
cursor.frame.origin.x = leftXOffset
if navBar.contentSize.width > fullWidth {
let targetX = leftXOffset - leftMargin
guard targetX >= 0 else {
return
}
let maxOffset = navBar.contentSize.width - fullWidth
if targetX <= maxOffset {
navBar.contentOffset.x = targetX
} else if navBar.contentOffset.x < maxOffset {
navBar.contentOffset.x = maxOffset
}
}
}
}
|
7e528edd45eff832fbefe9ae2ad6b6e0
| 51.708861 | 260 | 0.62512 | false | false | false | false |
fletcher89/SwiftyRC
|
refs/heads/master
|
Sources/SwiftyRC/Types/Message.swift
|
mit
|
1
|
//
// Message.swift
// SwiftyRC
//
// Created by Christian on 22.07.17.
//
import Foundation
// MARK: Internal
internal extension IRC {
/// Represents a message
///
/// - ping: A `PING` message
/// - serverReply: A numeric code reply
/// - event: A event
/// - unknown: I have no idea
enum Message {
case ping(ping: IRC.Ping)
case serverReply(reply: IRC.Reply)
case event(event: IRC.Event)
case unknown(rawMessage: IRC.RawMessage)
}
}
// MARK: Internal Message API
internal extension IRC.Message {
/// Returns an `IRC.Message` case from a raw message
///
/// - Parameter message: The raw message
/// - Returns: -
static func from(rawMessage message: IRC.RawMessage) -> IRC.Message {
var prefix = ""
var messageSplitBySpaces = message.split(separator: " ")
if messageSplitBySpaces.count >= 3 && message.characters[message.characters.startIndex] == ":" {
// If we have three or more elements and the first one is a colon... we found ourselves an event or server reply code!
// First, extract the prefix
prefix = String(messageSplitBySpaces[0])
prefix = String(prefix[prefix.index(after: prefix.startIndex)...])
// Check if we're having an event or a code reply by trying to convert the second element in the message to Int
if let code = Int(String(messageSplitBySpaces[1])) {
// We have a code reply
return .serverReply(reply:
IRC.Reply(
type: IRC.ReplyType(rawValue: code) ?? IRC.ReplyType.unknownReplyType,
rawMessage: message
)
)
} else {
// Or an event...
// Remove the prefix from the split message array
messageSplitBySpaces.remove(at: 0)
// The next item in the list is the event
// Try to extract an `IRC.EventType` from this, if we don't get anything, just return .notImplemented
// Finally, convert the messages array into an array of strings (from substrings)
let rawEvent = String(messageSplitBySpaces.remove(at: 0))
let eventType = IRC.EventType(rawValue: rawEvent) ?? IRC.EventType.notImplemented
let arguments = messageSplitBySpaces.map { String($0) }
guard let user = IRC.User(with: prefix)
else {
return .unknown(rawMessage: message)
}
// And return the event enum case
return .event(event:
IRC.Event(
user: user,
type: eventType,
arguments: arguments,
rawMessage: message
)
)
}
} else if message.hasPrefix("PING") {
// Was it a PING instead?
return .ping(ping:
IRC.Ping(
payload: String(message[message.index(message.startIndex, offsetBy: 5)...]),
rawMessage: message
)
)
}
// Well... gotta catch this!
return .unknown(rawMessage: message)
}
}
|
f701267d0221fea73945bc21e02ee02f
| 36.182796 | 130 | 0.520243 | false | false | false | false |
SusanDoggie/Doggie
|
refs/heads/main
|
Sources/DoggieGeometry/Bezier/LineSegment.swift
|
mit
|
1
|
//
// LineSegment.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. 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.
//
@frozen
public struct LineSegment<Element: ScalarMultiplicative>: BezierProtocol where Element.Scalar == Double {
public var p0: Element
public var p1: Element
@inlinable
@inline(__always)
public init() {
self.p0 = .zero
self.p1 = .zero
}
@inlinable
@inline(__always)
public init(_ p0: Element, _ p1: Element) {
self.p0 = p0
self.p1 = p1
}
}
extension Bezier {
@inlinable
@inline(__always)
public init(_ bezier: LineSegment<Element>) {
self.init(bezier.p0, bezier.p1)
}
}
extension LineSegment: Hashable where Element: Hashable {
}
extension LineSegment: Decodable where Element: Decodable {
@inlinable
@inline(__always)
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
self.init(try container.decode(Element.self), try container.decode(Element.self))
}
}
extension LineSegment: Encodable where Element: Encodable {
@inlinable
@inline(__always)
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(p0)
try container.encode(p1)
}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension LineSegment: Sendable where Element: Sendable { }
extension LineSegment {
@inlinable
@inline(__always)
public func map(_ transform: (Element) -> Element) -> LineSegment {
return LineSegment(transform(p0), transform(p1))
}
@inlinable
@inline(__always)
public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Element) -> Void) -> Result {
var accumulator = initialResult
updateAccumulatingResult(&accumulator, p0)
updateAccumulatingResult(&accumulator, p1)
return accumulator
}
@inlinable
@inline(__always)
public func combined(_ other: LineSegment, _ transform: (Element, Element) -> Element) -> LineSegment {
return LineSegment(transform(p0, other.p0), transform(p1, other.p1))
}
}
extension LineSegment {
public typealias Indices = Range<Int>
@inlinable
@inline(__always)
public var startIndex: Int {
return 0
}
@inlinable
@inline(__always)
public var endIndex: Int {
return 2
}
@inlinable
@inline(__always)
public subscript(position: Int) -> Element {
get {
return withUnsafeTypePunnedPointer(of: self, to: Element.self) { $0[position] }
}
set {
withUnsafeMutableTypePunnedPointer(of: &self, to: Element.self) { $0[position] = newValue }
}
}
}
extension LineSegment {
@inlinable
@inline(__always)
public var start: Element {
return p0
}
@inlinable
@inline(__always)
public var end: Element {
return p1
}
@inlinable
@inline(__always)
public func eval(_ t: Double) -> Element {
return p0 + t * (p1 - p0)
}
@inlinable
@inline(__always)
public func split(_ t: Double) -> (LineSegment, LineSegment) {
let q0 = p0 + t * (p1 - p0)
return (LineSegment(p0, q0), LineSegment(q0, p1))
}
@inlinable
@inline(__always)
public func elevated() -> QuadBezier<Element> {
return QuadBezier(p0, eval(0.5), p1)
}
@inlinable
@inline(__always)
public func derivative() -> LineSegment {
let q = p1 - p0
return LineSegment(q, q)
}
}
extension LineSegment where Element == Double {
@inlinable
@inline(__always)
public var polynomial: Polynomial {
let a = p0
let b = p1 - p0
return [a, b]
}
}
extension LineSegment where Element == Point {
@inlinable
@inline(__always)
public func _closest(_ point: Point) -> Double {
let a = p0 - point
let b = p1 - p0
let c = b.x * a.x + b.y * a.y
let d = b.x * b.x + b.y * b.y
return -c / d
}
@inlinable
@inline(__always)
public func distance(from point: Point) -> Double {
let d = p1 - p0
let m = p0.y * p1.x - p0.x * p1.y
return abs(d.y * point.x - d.x * point.y + m) / d.magnitude
}
}
extension LineSegment where Element == Point {
@inlinable
@inline(__always)
public func closest(_ point: Point, in range: ClosedRange<Double> = -.infinity ... .infinity) -> [Double] {
let a = p0 - point
let b = p1 - p0
return Polynomial(b.x * a.x + b.y * a.y, b.x * b.x + b.y * b.y).roots(in: range)
}
}
extension LineSegment where Element == Point {
@inlinable
@inline(__always)
public var area: Double {
return 0.5 * (p0.x * p1.y - p0.y * p1.x)
}
}
extension LineSegment where Element: Tensor {
@inlinable
@inline(__always)
public func length(_ t: Double = 1) -> Double {
return p0.distance(to: eval(t))
}
@inlinable
@inline(__always)
public func inverseLength(_ length: Double) -> Double {
return length / p0.distance(to: p1)
}
}
extension LineSegment where Element == Point {
@inlinable
@inline(__always)
public var boundary: Rect {
let minX = Swift.min(p0.x, p1.x)
let minY = Swift.min(p0.y, p1.y)
let maxX = Swift.max(p0.x, p1.x)
let maxY = Swift.max(p0.y, p1.y)
return Rect(x: minX, y: minY, width: maxX - minX, height: maxY - minY)
}
}
extension LineSegment where Element == Point {
@inlinable
@inline(__always)
public func intersect(_ other: LineSegment) -> Point? {
let q0 = p0 - p1
let q1 = other.p0 - other.p1
let d = q0.x * q1.y - q0.y * q1.x
if d.almostZero() {
return nil
}
let a = (p0.x * p1.y - p0.y * p1.x) / d
let b = (other.p0.x * other.p1.y - other.p0.y * other.p1.x) / d
return Point(x: q1.x * a - q0.x * b, y: q1.y * a - q0.y * b)
}
}
|
37c6491c3f43d3ab83427ce5267e5c49
| 25.893382 | 131 | 0.600137 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor
|
refs/heads/master
|
TranslationEditor/UserCell.swift
|
mit
|
1
|
//
// UserCell.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 6.6.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import UIKit
class UserCell: UITableViewCell
{
// OUTLETS ---------------------
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var createdLabel: UILabel!
@IBOutlet weak var isAdminSwitch: UISwitch!
@IBOutlet weak var clearPasswordButton: BasicButton!
@IBOutlet weak var deleteButton: BasicButton!
// ATTRIBUTES -----------------
static let identifier = "UserCell"
private var setAdminAction: ((UITableViewCell, Bool) -> ())?
private var passwordAction: ((UITableViewCell) -> ())?
private var deleteAction: ((UITableViewCell) -> ())?
// ACTIONS ---------------------
@IBAction func adminValueChanged(_ sender: Any)
{
setAdminAction?(self, isAdminSwitch.isOn)
}
@IBAction func clearPasswordPressed(_ sender: Any)
{
passwordAction?(self)
}
@IBAction func deletePressed(_ sender: Any)
{
deleteAction?(self)
}
// OTHER METHODS -------------
func configure(name: String, created: Date, isAdmin: Bool, hasPassword: Bool, deleteEnabled: Bool, setAdminAction: @escaping (UITableViewCell, Bool) -> (), clearPasswordAction: @escaping (UITableViewCell) -> (), deleteAction: @escaping (UITableViewCell) -> ())
{
self.passwordAction = clearPasswordAction
self.deleteAction = deleteAction
self.setAdminAction = setAdminAction
nameLabel.text = name
isAdminSwitch.isOn = isAdmin
clearPasswordButton.isEnabled = hasPassword
deleteButton.isEnabled = deleteEnabled
let formatter = DateFormatter()
formatter.dateStyle = .medium
createdLabel.text = formatter.string(from: created)
}
}
|
04a547506bc62422c3748b0e97ff3bfc
| 24.343284 | 261 | 0.693168 | false | false | false | false |
ahayman/RxStream
|
refs/heads/master
|
RxStream/Streams/Cold.swift
|
mit
|
1
|
//
// Cold.swift
// RxStream
//
// Created by Aaron Hayman on 3/15/17.
// Copyright © 2017 Aaron Hayman. All rights reserved.
//
import Foundation
/**
A Cold stream is a kind of stream that only produces values when it is asked to.
A cold stream can be asked to produce a value by making a `request` anywhere down stream.
It differs from other types of stream in that a cold stream will only produce one value per request.
Moreover, the result of a request will _only_ be passed back down the chain that originally requested it.
This prevents other branches from receiving requests they did not ask for.
*/
public class Cold<Request, Response> : Stream<Response> {
public typealias ColdTask = (_ state: Observable<StreamState>, _ request: Request, _ response: (Result<Response>) -> Void) -> Void
typealias ParentProcessor = (Request, EventPath) -> Void
override var streamType: StreamType { return .cold }
/// The processor responsible for filling a request. It can either be a ColdTask or a ParentProcessor (a Parent stream that can handle fill the request).
private var requestProcessor: Either<ColdTask, ParentProcessor>
/// The promise needed to pass into the promise task.
lazy private var stateObservable: ObservableInput<StreamState> = ObservableInput(self.state)
/// Override and observe didSet to update the observable
override public var state: StreamState {
didSet {
stateObservable.set(state)
}
}
func newSubStream<U>(_ op: String) -> Cold<Request, U> {
return Cold<Request, U>(op: op) { [weak self] (request, key) in
self?.process(request: request, withKey: key)
}
}
func newMappedRequestStream<U>(mapper: @escaping (U) -> Request) -> Cold<U, Response> {
return Cold<U, Response>(op: "mapRequest<\(String(describing: Request.self))>"){ [weak self] (request: U, key: EventPath) in
self?.process(request: mapper(request), withKey: key)
}
}
/**
A cold stream must be initialized with a Task that takes a request and returns a response.
A task should return only 1 response for each request. All other responses will be ignored.
*/
public init(task: @escaping ColdTask) {
self.requestProcessor = Either(task)
super.init(op: "Task")
}
init(op: String, processor: @escaping ParentProcessor) {
self.requestProcessor = Either(processor)
super.init(op: op)
}
private func make(request: Request, withKey key: EventPath, withTask task: @escaping ColdTask) {
let work = {
var key: EventPath? = key
task(self.stateObservable, request) {
guard let requestKey = key else { return }
key = nil
$0
.onFailure { self.process(event: .error($0), withKey: requestKey) }
.onSuccess { self.process(event: .next($0), withKey: requestKey) }
}
}
if let dispatch = self.dispatch {
dispatch.execute(work)
} else {
work()
}
}
private func process(request: Request, withKey key: EventPath) {
guard isActive else { return }
let key: EventPath = .key(id, next: key)
requestProcessor
.onLeft{ self.make(request: request, withKey: key, withTask: $0) }
.onRight{ $0(request, key) }
}
/**
Make a request from this stream. The response will be passed back once the task has completed.
- parameters:
- request: The request object to submit to the stream's task
- share: **default:** false: If false, then the response will end here. If true, then the response will be passed to all attached streams.
*/
public func request(_ request: Request, share: Bool = false) {
process(request: request, withKey: share ? .share : .end)
}
/**
Make a request from this stream. The response will be passed back once the task has completed.
- parameter request: The request object to submit to the stream's task
*/
public func request(_ request: Request) {
process(request: request, withKey: .end)
}
/// Terminate the Cold Stream with a reason.
public func terminate(withReason reason: Termination) {
self.process(event: .terminate(reason: reason), withKey: .share)
}
deinit {
if self.isActive {
self.process(event: .terminate(reason: .completed))
}
}
}
|
cf0dd189f59d340b85d94b87b49723b1
| 34.380165 | 156 | 0.678813 | false | false | false | false |
kfarst/alarm
|
refs/heads/master
|
alarm/TimePresenter.swift
|
mit
|
1
|
//
// TimePresenter.swift
// alarm
//
// Created by Michael Lewis on 3/8/15.
// Copyright (c) 2015 Kevin Farst. All rights reserved.
//
import Foundation
class TimePresenter: Comparable {
// Support time-based, or sunrise/sunset based
let type: AlarmEntity.AlarmType
let time: RawTime?
// Time type is required, and a raw time is optional
init(type: AlarmEntity.AlarmType, time: RawTime? = nil) {
self.type = type
self.time = time
// If we're dealing with an AlarmType of .Time, ensure
// that we have a valid `time`.
if type == .Time {
assert(time != nil)
}
}
// Allow creation by raw hours/minutes
convenience init(hour24: Int, minute: Int) {
self.init(type: .Time, time: RawTime(hour24: hour24, minute: minute))
}
// Create a TimePresenter, using an AlarmEntity as the base
convenience init(alarmEntity: AlarmEntity) {
switch alarmEntity.alarmTypeEnum {
case .Time:
self.init(
hour24: Int(alarmEntity.hour),
minute: Int(alarmEntity.minute)
)
default:
self.init(type: alarmEntity.alarmTypeEnum)
}
}
// This presenter supports static times as well as sun-based times
// This function will return a raw time representing what the
// true time is, no matter how this presenter was constructed.
func calculatedTime() -> RawTime? {
switch self.type {
case .Time:
return time!
case .Sunrise:
return SunriseHelper.singleton.sunrise()
case .Sunset:
return SunriseHelper.singleton.sunset()
}
}
// Don't include the am/pm portion in the main wheel
func stringForWheelDisplay() -> String {
// Precalculate the time
let time = calculatedTime()
switch self.type {
case .Time:
// Special formatting for special times
if time!.hour24 == 0 && time!.minute == 0 {
return "midnight"
} else if time!.hour24 == 12 && time!.minute == 0 {
return "noon"
} else {
return String(format: "%2d : %02d", time!.hour12, time!.minute)
}
case .Sunrise:
// If we can't comput the time, just return "sunrise"
if (time == nil) {
return "sunrise"
} else {
return String(format: "sunrise (%2d:%02d)", time!.hour12, time!.minute)
}
case .Sunset:
// If we can't comput the time, just return "sunrise"
if (time == nil) {
return "sunset"
} else {
return String(format: "sunset (%2d:%02d)", time!.hour12, time!.minute)
}
}
}
// The table display view doesn't need times for sunrise/sunset
func stringForTableDisplay() -> String {
switch self.type {
case .Time:
// Special formatting for special times
if time!.hour24 == 0 && time!.minute == 0 {
return "midnight"
} else if time!.hour24 == 12 && time!.minute == 0 {
return "noon"
} else {
return String(format: "%2d:%02d %@", time!.hour12, time!.minute, TimePresenter.amPmToString(time!.amOrPm))
}
case .Sunrise:
return "Sunrise"
case .Sunset:
return "Sunset"
}
}
func stringForAmPm() -> String {
if let time = calculatedTime() {
return TimePresenter.amPmToString(time.amOrPm)
} else {
return "error"
}
}
func primaryStringForTwoPartDisplay() -> String {
switch self.type {
case .Time:
// Special formatting for special times
if time!.hour24 == 0 && time!.minute == 0 {
return "midnight"
} else if time!.hour24 == 12 && time!.minute == 0 {
return "noon"
} else {
return String(format: "%2d:%02d %@", time!.hour12, time!.minute, TimePresenter.amPmToString(time!.amOrPm))
}
case .Sunrise:
return "Sunrise"
case .Sunset:
return "Sunset"
}
}
func secondaryStringForTwoPartDisplay() -> String {
switch self.type {
case .Time:
return ""
case .Sunrise, .Sunset:
let time = calculatedTime()
// Special formatting for special times
if time!.hour24 == 0 && time!.minute == 0 {
return "midnight"
} else if time!.hour24 == 12 && time!.minute == 0 {
return "noon"
} else {
return String(format: "%2d:%02d %@", time!.hour12, time!.minute, TimePresenter.amPmToString(time!.amOrPm))
}
}
}
// Generate all of the time elements that we will allow.
// This includes sunset and sunrise.
class func generateAllElements() -> Array<TimePresenter> {
// Start by generating the static times
var times = (0...23).map {
hour in
[0, 15, 30, 45].map {
minute in
TimePresenter(hour24: hour, minute: minute)
}
}.reduce([], combine: +)
// Add in sunrise and sunset.
// Skip them if they can't be calculated
let sunrise = TimePresenter(type: AlarmEntity.AlarmType.Sunrise)
if sunrise.calculatedTime() != nil {
times.append(sunrise)
}
let sunset = TimePresenter(type: AlarmEntity.AlarmType.Sunset)
if sunset.calculatedTime() != nil {
times.append(sunset)
}
// Sort the entire array, based upon calculated time
return times.sorted { $0 < $1 }
}
class func amPmToString(amPm: RawTime.AmPm) -> String {
switch amPm {
case .AM:
return "am"
case .PM:
return "pm"
}
}
/* Private */
}
// Comparison operators for TimePresenter
func <(left: TimePresenter, right: TimePresenter) -> Bool {
return left.calculatedTime() < right.calculatedTime()
}
func ==(left: TimePresenter, right: TimePresenter) -> Bool {
// They have to share the same type to be equal
if left.type == right.type {
switch left.type {
case .Time:
// If it's static time, make sure it's the same
return left.time == right.time
default:
// If it's sunrise/sunset, type alone is enough
return true
}
} else {
// If type is different, they're inequal
return false
}
}
|
e567657151e94d339c86600d1d23be6d
| 26.882629 | 114 | 0.61054 | false | false | false | false |
MadArkitekt/Swift_Tutorials_And_Demos
|
refs/heads/master
|
CustomViewTransitions/CustomViewTransitions/ViewController.swift
|
gpl-2.0
|
1
|
//
// ViewController.swift
// CustomViewTransitions
//
// Created by Edward Salter on 9/6/14.
// Copyright (c) 2014 Edward Salter. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let transitionManager = TransAnimateManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
let toViewController = segue.destinationViewController as UIViewController
toViewController.transitioningDelegate = self.transitionManager
}
@IBAction func unwindToViewController(segue: UIStoryboardSegue)
{
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return self.presentingViewController == nil ? UIStatusBarStyle.Default : UIStatusBarStyle.LightContent
}
}
|
921adac0bacbe060c7a4d7e862107b44
| 26.825 | 110 | 0.697215 | false | false | false | false |
tamaracha/libsane
|
refs/heads/master
|
Sources/Device.swift
|
mit
|
1
|
import Clibsane
/// Represents a SANE device.
public class Device {
//MARK: Types
/// Device-specific errors
public enum DeviceError: Error {
/// Currently, the device has no open handle
case noHandle
}
/// Possible states of a device
public enum State {
/// The physical device is inaccessible
case disconnected
/// The physical device is accessible. This is the default state
case connected
/// The device is open and can execute different operations
case open
}
/**
An additional information bitset which is returned after setting a device option. It is implemented as a OptionSet for better swift integration.
- seealso: http://sane.alioth.debian.org/html/doc012.html
*/
struct Info: OptionSet {
let rawValue: Int32
/// The given value couldn't be set exactly, but the nearest aproximate value is used
static let inexact = Info(rawValue: SANE_INFO_INEXACT)
/// The option descriptors may have changed
static let reloadOptions = Info(rawValue: SANE_INFO_RELOAD_OPTIONS)
/// the device parameters may have changed.
static let reloadParams = Info(rawValue: SANE_INFO_RELOAD_PARAMS)
}
/// This constant is used as maximal buffer size when reading image data
static private let bufferSize = 1024*1024
//MARK: Properties
/// Properties which describe a SANE device
public let name, model, vendor, type: String
/// The current device state
public private(set) var state: State = .connected
/// The options of the device
public private(set) var options = [String: BaseOption]()
private var handle: SANE_Handle? {
didSet {
state = handle == nil ? .connected : .open
}
}
//MARK: Lifecycle Hooks
init(_ name: String, model: String, vendor: String, type: String) {
self.name = name
self.vendor = vendor
self.model = model
self.type = type
}
convenience init(_ name: String) {
self.init(name, model: "unknown", vendor: "Noname", type: "virtual device")
}
init(from device: SANE_Device) {
name = String(cString: device.name)
model = String(cString: device.model)
vendor = String(cString: device.vendor)
type = String(cString: device.type)
}
deinit {
close()
}
//MARK: Methods
/// Open the device for configuration and image taking
public func open() throws {
var handle: SANE_Handle?
let status = sane_open(name, &handle)
guard status == SANE_STATUS_GOOD else {
throw Status(rawValue: status)!
}
self.handle = handle
if state == .open {
try getOptions()
}
}
/// Terminate the interaction with the device
public func close() {
if let handle = handle {
sane_close(handle)
}
handle = nil
options.removeAll()
}
/// Load the options of the device
func getOptions() throws {
guard case .open = state else {
return
}
guard let handle = handle else {
throw DeviceError.noHandle
}
var count: SANE_Int = 1
let status = sane_control_option(handle, 0, SANE_ACTION_GET_VALUE, &count, nil)
guard status == SANE_STATUS_GOOD else {
throw Status(rawValue: status)!
}
guard count > 1 else {
return
}
for index in 1 ... count-1 {
let descriptor = sane_get_option_descriptor(handle, index).pointee
var option: BaseOption
switch descriptor.type {
case SANE_TYPE_BOOL:
option = SwitchOption(from: descriptor, at: index, of: self)
case SANE_TYPE_INT:
option = IntOption(from: descriptor, at: index, of: self)
case SANE_TYPE_FIXED:
option = NumericOption(from: descriptor, at: index, of: self)
case SANE_TYPE_STRING:
option = TextOption(from: descriptor, at: index, of: self)
case SANE_TYPE_BUTTON:
option = ButtonOption(from: descriptor, at: index, of: self)
case SANE_TYPE_GROUP:
continue
default:
continue
}
options[option.name] = option
}
}
/// Reload the options of the device
func reloadOptions() throws {
guard case .open = state else {
return
}
guard let handle = handle else {
throw DeviceError.noHandle
}
for (_, option) in options {
let descriptor = sane_get_option_descriptor(handle, option.index).pointee
option.update(descriptor)
}
}
/// Set an option to its default value
func setAuto(at index: SANE_Int) throws {
guard case .open = state else {
return
}
guard let handle = handle else {
throw DeviceError.noHandle
}
let status = sane_control_option(handle, index, SANE_ACTION_SET_AUTO, nil, nil)
guard status == SANE_STATUS_GOOD else {
throw Status(rawValue: status)!
}
}
/// Get the value of an option
func getValue(at index: SANE_Int, to ptr: UnsafeMutableRawPointer) throws {
guard case .open = state else {
return
}
guard let handle = handle else {
throw DeviceError.noHandle
}
let status = sane_control_option(handle, index, SANE_ACTION_GET_VALUE, ptr, nil)
guard status == SANE_STATUS_GOOD else {
throw Status(rawValue: status)!
}
}
/// Change the value of an option
func setValue(at index: SANE_Int, to ptr: UnsafeMutableRawPointer) throws {
guard case .open = state else {
return
}
guard let handle = handle else {
throw DeviceError.noHandle
}
var saneInfo: SANE_Int = 0
let status = sane_control_option(handle, index, SANE_ACTION_SET_VALUE, ptr, &saneInfo)
guard status == SANE_STATUS_GOOD else {
throw Status(rawValue: status)!
}
let info = Info(rawValue: saneInfo)
if info.contains(.reloadOptions) {
try reloadOptions()
}
}
/// Get the scan parameters of the device
public func getParameters() throws -> Parameters {
guard let handle = handle else {
throw DeviceError.noHandle
}
var params = SANE_Parameters()
let status = sane_get_parameters(handle, ¶ms)
guard status == SANE_STATUS_GOOD else {
throw Status(rawValue: status)!
}
return Parameters(params)
}
private func start() throws {
guard case .open = state else {
return
}
guard let handle = handle else {
throw DeviceError.noHandle
}
let status = sane_start(handle)
guard status == SANE_STATUS_GOOD else {
throw Status(rawValue: status)!
}
}
private func setAsync() throws -> Bool {
guard let handle = handle else {
throw DeviceError.noHandle
}
let status = sane_set_io_mode(handle, SANE_TRUE)
if status == SANE_STATUS_GOOD {
return true
}
else if status == SANE_STATUS_UNSUPPORTED {
return false
} else {
throw Status(rawValue: status)!
}
}
private func read(frameSize: Int? = nil, maxLen: Int = Device.bufferSize) throws -> [SANE_Byte] {
guard let handle = handle else {
throw DeviceError.noHandle
}
var data = [SANE_Byte]()
var buf = [SANE_Byte](repeating: 0, count: maxLen)
var status: SANE_Status
var n: SANE_Int = 0
if let frameSize = frameSize {
repeat {
status = sane_read(handle, &buf, SANE_Int(maxLen), &n)
data += buf.prefix(Int(n))
} while status == SANE_STATUS_GOOD && data.count < frameSize
}
else {
repeat {
status = sane_read(handle, &buf, SANE_Int(maxLen), &n)
data += buf.prefix(Int(n))
} while status == SANE_STATUS_GOOD
}
guard status == SANE_STATUS_EOF || status == SANE_STATUS_GOOD else {
throw Status(rawValue: status)!
}
return data
}
/// Cancel a currently pending physical operation
public func cancel() {
guard case .open = state else {
return
}
if let handle = handle {
sane_cancel(handle)
}
}
/// Scan an image
public func scan() throws -> (data: [SANE_Byte], params: Parameters) {
try start()
let params = try getParameters()
let data = try read(frameSize: params.bytesTotal)
cancel()
return (data: data, params: params)
}
}
//MARK: Extensions
extension Device: CustomStringConvertible {
/// use the device name as description
public var description: String {
return name
}
}
extension Device: Hashable {
/// use the device name as hash value
public var hashValue: Int {
return name.hashValue
}
}
extension Device: Comparable {
/// Devices can be equated by their hash value
static public func ==(lhs: Device, rhs: Device) -> Bool {
return lhs.hashValue == rhs.hashValue
}
static public func <(lhs: Device, rhs: Device) -> Bool {
return lhs.hashValue < rhs.hashValue
}
}
|
6738ef9382a7553b3874435f8062748c
| 27.169935 | 147 | 0.644316 | false | false | false | false |
WalletOne/P2P
|
refs/heads/master
|
P2PExample/Controllers/Employer/EmployerViewController.swift
|
mit
|
1
|
//
// EmployerViewController.swift
// P2P_iOS
//
// Created by Vitaliy Kuzmenko on 02/08/2017.
// Copyright © 2017 Wallet One. All rights reserved.
//
import UIKit
import P2PCore
import P2PUI
class EmployerViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let employer = Employer()
employer.id = "vitaliykuzmenko" // NSUUID().uuidString
employer.title = "Vitaliy Kuzmenko"
employer.phoneNumber = "79281234567"
DataStorage.default.employer = employer
P2PCore.setPayer(id: employer.id, title: employer.title, phoneNumber: employer.phoneNumber)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
switch segue.identifier! {
case "DealsViewController":
let vc = segue.destination as! DealsViewController
vc.userTypeId = .employer
default:break
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let paymentToolsIndexPath = IndexPath(row: 0, section: 1)
let refundsIndexPath = IndexPath(row: 1, section: 1)
switch indexPath {
case paymentToolsIndexPath:
presentPaymentTools()
case refundsIndexPath:
presentRefunds()
default:
break
}
}
func presentPaymentTools() {
let vc = PaymentToolsViewController(owner: .payer, delegate: nil)
navigationController?.pushViewController(vc, animated: true)
}
func presentRefunds() {
let vc = RefundsViewController(dealId: nil)
navigationController?.pushViewController(vc, animated: true)
}
}
|
54c6d2e80c21e6c41b60ae64d7d7fafb
| 28.492063 | 99 | 0.64155 | false | false | false | false |
noppoMan/SwiftKnex
|
refs/heads/master
|
Sources/SwiftKnex/Clauses/Join.swift
|
mit
|
1
|
//
// Join.swift
// SwiftKnex
//
// Created by Yuki Takei on 2017/01/12.
//
//
class Join: Buildable {
let table: String
let type: JoinType
var conditions = [ConditionalFilter]()
init(table: String, type: JoinType){
self.table = table
self.type = type
}
public func build() throws -> String {
var conds = [String]()
for cond in conditions {
let prefix: String
if conds.count == 0 {
prefix = "ON"
} else {
prefix = "AND"
}
try conds.append(prefix + " " + cond.toQuery(secure: false))
}
return try "\(type.build()) \(table) \(conds.joined(separator: " "))"
}
}
enum JoinType {
case left
case right
case inner
case `default`
}
extension JoinType {
public func build() throws -> String {
switch self {
case .left:
return "LEFT JOIN"
case .right:
return "RIGHT JOIN"
case .inner:
return "INNER JOIN"
case .default:
//`\(table)` ON \(filter.toQuery(secure: false))"
return "JOIN"
}
}
}
extension Collection where Self.Iterator.Element == Join {
func build() throws -> String {
let clauses: [String] = try self.map { try $0.build() }
return clauses.joined(separator: " ")
}
}
|
7b027a5647cd38baa9d787a176eeae37
| 21.121212 | 77 | 0.49726 | false | false | false | false |
casd82/powerup-iOS
|
refs/heads/develop
|
Powerup/Accessory.swift
|
gpl-2.0
|
2
|
/** Data model for accessories (i.e. Eyes, Hair, etc) */
import UIKit
// The types of the accessories.
enum AccessoryType: String {
case face = "Face"
case eyes = "Eyes"
case hair = "Hair"
case clothes = "Clothes"
case necklace = "Necklace"
case handbag = "Handbag"
case hat = "Hat"
case glasses = "Glasses"
case unknown = ""
}
struct Accessory {
// The type of the accessory.
var type: AccessoryType
// Each accessory has a unique ID.
var id: Int
// The image of the accessory.
var image: UIImage?
// The image shown in Shop Scene boxes.
var displayImage: UIImage?
// The price to buy the accessory.
var points: Int
// Whether the accessory is purchased yet.
var purchased: Bool
init(type: AccessoryType, id: Int, imageName: String, points: Int, purchased: Bool) {
self.type = type
self.id = id
self.image = UIImage(named: imageName)
self.points = points
self.purchased = purchased
// Set display image. Avatar image is prefixed with "avatar_", display image is prefixed with "display_", so we have to substring from '_' and prefix it with "display".
let fromIndex = imageName.count >= 6 ? imageName.index(imageName.startIndex, offsetBy: 6) : imageName.startIndex
let displayName = "display" + String(imageName[fromIndex...])
self.displayImage = UIImage(named: displayName)
}
init(type: AccessoryType) {
do {
self = try DatabaseAccessor.sharedInstance.getAccessory(accessoryType: type, accessoryIndex: 1)
} catch _ {
self.type = .unknown
self.id = 0
self.image = nil
self.displayImage = nil
self.points = 0
self.purchased = false
}
}
}
|
fc44f50e3e21c564608e7bae24f2821c
| 28.483871 | 176 | 0.615974 | false | false | false | false |
Eonil/ClangWrapper.Swift
|
refs/heads/master
|
ClangWrapper/Cursor+Equatable.swift
|
mit
|
2
|
//
// Cursor+Equatable.swift
// ClangWrapper
//
// Created by Hoon H. on 2015/01/21.
// Copyright (c) 2015 Eonil. All rights reserved.
//
extension Cursor: Equatable {
}
public func == (left:Cursor, right:Cursor) -> Bool {
let r = clang_equalCursors(left.raw, right.raw)
return r != 0
}
public func != (left:Cursor, right:Cursor) -> Bool {
return !(left == right)
}
extension Cursor: Hashable {
public var hashValue:Int {
get {
return Int(bitPattern: UInt(clang_hashCursor(raw)))
}
}
}
|
be3d4f22a19e7579e638147a459a0929
| 10.413043 | 54 | 0.634286 | false | false | false | false |
harlanhaskins/trill
|
refs/heads/master
|
Sources/Diagnostics/StreamConsumer.swift
|
mit
|
2
|
///
/// StreamConsumer.swift
///
/// Copyright 2016-2017 the Trill project authors.
/// Licensed under the MIT License.
///
/// Full license text available at https://github.com/trill-lang/trill
///
import Source
import Foundation
public class StreamConsumer<StreamType: ColoredStream>: DiagnosticConsumer {
var stream: StreamType
public init(stream: inout StreamType) {
self.stream = stream
}
func highlightString(forDiag diag: Diagnostic) -> String {
guard let loc = diag.loc, loc.line > 0 && loc.column > 0 else { return "" }
var s = [Character]()
let ranges = diag.highlights
.filter { $0.start.line == loc.line && $0.end.line == loc.line }
.sorted { $0.start.charOffset < $1.start.charOffset }
if !ranges.isEmpty {
s = [Character](repeating: " ", count: ranges.last!.end.column)
for r in ranges {
let range = (r.start.column - 1)..<(r.end.column - 1)
let tildes = [Character](repeating: "~", count: range.count)
s.replaceSubrange(range, with: tildes)
}
}
let index = loc.column - 1
if index >= s.endIndex {
s += [Character](repeating: " ", count: s.endIndex.distance(to: index))
s.append("^")
} else {
s[index] = "^" as Character
}
return String(s)
}
func sourceFile(for diag: Diagnostic) -> SourceFile? {
return diag.loc?.file
}
public func consume(_ diagnostic: Diagnostic) {
let file = sourceFile(for: diagnostic)
stream.write("\(diagnostic.diagnosticType): ",
with: [.bold, diagnostic.diagnosticType.color])
stream.write("\(diagnostic.message)\n", with: [.bold])
if let loc = diagnostic.loc,
let line = file?.lines[loc.line - 1],
loc.line > 0 {
stream.write(" --> ", with: [.bold, .cyan])
let filename = file?.path.basename ?? "<unknown>"
stream.write("\(filename)")
if let sourceLoc = diagnostic.loc {
stream.write(":\(sourceLoc.line):\(sourceLoc.column)",
with: [.bold])
}
stream.write("\n")
let lineStr = "\(loc.line)"
let indentation = "\(indent(lineStr.count))"
stream.write(" \(indentation)|\n", with: [.cyan])
if let prior = file?.lines[safe: loc.line - 2] {
stream.write(" \(indentation)| ", with: [.cyan])
stream.write("\(prior)\n")
}
stream.write(" \(lineStr)| ", with: [.cyan])
stream.write("\(line)\n")
stream.write(" \(indentation)| ", with: [.cyan])
stream.write(highlightString(forDiag: diagnostic),
with: [.bold, .green])
stream.write("\n")
if let next = file?.lines[safe: loc.line] {
stream.write(" \(indentation)| ", with: [.cyan])
stream.write("\(next)\n")
}
stream.write("\n")
}
}
}
func indent(_ n: Int) -> String {
return String(repeating: " ", count: n)
}
|
96c2f5a20d4a51a90fe018bd10fda93e
| 34.876404 | 83 | 0.526464 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/Platform/Sources/PlatformUIKit/Components/AssetPieChartView/LoadingState+AssetPieChart.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Charts
import ComposableArchitectureExtensions
import PlatformKit
extension LoadingState where Content == PieChartData {
/// Initializer that receives the interaction state and
/// maps it to `self`
init(with state: LoadingState<[AssetPieChart.Value.Interaction]>) {
switch state {
case .loading:
self = .loading
case .loaded(let values):
let data: PieChartData
if values.allSatisfy(\.percentage.isZero) {
data = .empty
} else {
data = PieChartData(with: values)
}
self = .loaded(next: data)
}
}
}
|
ae83fbcc3e491053a8fa9ed768e5b8e5
| 27.92 | 71 | 0.598893 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.