repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DigitalCroma/CodPol
|
CodPol/SideMenu/SideMenuViewController.swift
|
1
|
2359
|
//
// SideMenuViewController.swift
// CodPol
//
// Created by Juan Carlos Samboní Ramírez on 18/02/17.
// Copyright © 2017 DigitalCroma. All rights reserved.
//
import UIKit
import SideMenu
let kSideMenuCellIdentifier = "Cell"
class SideMenuViewController: UIViewController {
@IBOutlet weak var headerView: UIView!
@IBOutlet weak var menuTableView: UITableView!
let menuOptions = PlistParser.getSideMenuList()
var selectedIndexPath: IndexPath!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
navigationController?.setNavigationBarHidden(true, animated: false)
menuTableView.register(UITableViewCell.self, forCellReuseIdentifier: kSideMenuCellIdentifier)
selectedIndexPath = IndexPath(row: 0, section: 0)
menuTableView.selectRow(at: selectedIndexPath, animated: false, scrollPosition: .top)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension SideMenuViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menuOptions?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: kSideMenuCellIdentifier)
cell?.textLabel?.text = menuOptions?[indexPath.row].text
return cell!
}
}
extension SideMenuViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedIndexPath = indexPath
guard let location = menuOptions?[indexPath.row].location,
let identifier = menuOptions?[indexPath.row].identifier
else {
return
}
let viewController = UIStoryboard.init(name: location, bundle: nil).instantiateViewController(withIdentifier: identifier)
navigationController?.pushViewController(viewController, animated: true)
}
}
|
mit
|
9a7eae6e11d94d55de2ed257bc92c126
| 33.144928 | 129 | 0.704584 | 5.40367 | false | false | false | false |
rockbruno/ErrorKing
|
Sources/Classes/Model/ErrorProne.swift
|
2
|
4582
|
//
// ErrorProne.swift
// ErrorKing
//
// Created by Bruno Rocha on 8/13/16.
// Copyright © 2016 Bruno Rocha. All rights reserved.
//
import Foundation
import UIKit
open class ErrorKing {
weak var originalVC: UIViewController?
fileprivate var storedData: ErrorKingStoredData = ErrorKingStoredData()
fileprivate var emptyStateView: ErrorKingEmptyStateView?
fileprivate struct ErrorKingStoredData {
fileprivate var title = ""
fileprivate var description = ""
fileprivate var emptyStateText = ""
fileprivate var shouldDisplayError = false
}
fileprivate init () {}
final fileprivate func setup(owner: ErrorProne) {
originalVC = owner as? UIViewController
let emptyState = ErrorKingEmptyStateView()
emptyState.setup()
setEmptyStateView(toView: emptyState)
}
final public func setEmptyStateView(toView view: ErrorKingEmptyStateView) {
guard let originalVC = originalVC else {
return
}
let emptyStateView = view
emptyStateView.coordinator = self
emptyStateView.frame = originalVC.view.frame
emptyStateView.layoutIfNeeded()
emptyStateView.isHidden = true
emptyStateView.removeFromSuperview()
originalVC.view.addSubview(emptyStateView)
self.emptyStateView = emptyStateView
}
final public func setEmptyStateFrame(_ rect: CGRect) {
emptyStateView?.frame = rect
}
final public func setError(title: String, description: String, emptyStateText: String) {
storedData.shouldDisplayError = true
storedData.title = title
storedData.description = description
storedData.emptyStateText = emptyStateText
displayErrorIfNeeded()
}
final public func displayErrorIfNeeded() {
guard storedData.shouldDisplayError else { return }
displayError(storedData.title, description: storedData.description)
}
final fileprivate func displayError(_ title: String, description: String) {
guard originalVC?.isVisible == true else {
return
}
emptyStateView?.errorLabel?.text = storedData.emptyStateText
storedData.shouldDisplayError = false
DispatchQueue.main.async { [weak self] in
let alertController = ErrorKingAlertController(title: title, message: description)
let handler: ErrorKingVoidHandler = { _ in
self?.prepareEmptyState()
}
alertController.addButtonAndHandler(nil)
self?.originalVC?.present(alertController.alert, animated: true, completion: handler)
}
}
final fileprivate func prepareEmptyState() {
(originalVC as? ErrorProne)?.actionBeforeDisplayingErrorKingEmptyState()
}
final public func actionBeforeDisplayingErrorKingEmptyState() {
displayEmptyState()
}
final fileprivate func displayEmptyState() {
guard let originalVC = originalVC else {
return
}
originalVC.view.isUserInteractionEnabled = true
emptyStateView?.alpha = 0
emptyStateView?.isHidden = false
UIView.animate(withDuration: 0.5, animations: {
self.emptyStateView?.alpha = 1.0
})
}
final public func errorKingEmptyStateReloadButtonTouched() {
emptyStateView?.isHidden = true
}
}
extension UIViewController {
var isVisible: Bool {
return self.isViewLoaded && self.view.window != nil
}
}
//MARK: ErrorProne Protocol
public protocol ErrorProne: class {
func actionBeforeDisplayingErrorKingEmptyState()
func errorKingEmptyStateReloadButtonTouched()
}
private extension UIViewController {
struct AssociatedKeys {
static var EKDescriptiveName = "ek_DescriptiveName"
}
}
public extension ErrorProne where Self: UIViewController {
var errorKing: ErrorKing {
guard let object = objc_getAssociatedObject(self, &Self.AssociatedKeys.EKDescriptiveName) as? ErrorKing else {
let ek = ErrorKing()
ek.setup(owner: self)
objc_setAssociatedObject(self, &AssociatedKeys.EKDescriptiveName, ek, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return ek
}
return object
}
func actionBeforeDisplayingErrorKingEmptyState() {
errorKing.actionBeforeDisplayingErrorKingEmptyState()
}
func errorKingEmptyStateReloadButtonTouched() {
errorKing.errorKingEmptyStateReloadButtonTouched()
}
}
|
mit
|
f9767f9b2be0645cdb3cc127a71bace7
| 31.260563 | 118 | 0.673215 | 5.289838 | false | false | false | false |
GeekerHua/GHSwiftTest
|
GHPlayground.playground/Pages/map.xcplaygroundpage/Contents.swift
|
1
|
2726
|
//: [Previous](@previous)
import UIKit
var fa2 = [[1,2],[3],[4,5,6]]
var fa2m = fa2.flatMap({$0})
print(fa2m)
class ListItem {
var icon: UIImage?
var title: String = ""
var url: NSURL!
static func listItemsFromJSONData(jsonData: NSData?) -> [ListItem] {
guard let nonNilJsonData = jsonData,
let json = try? NSJSONSerialization.JSONObjectWithData(nonNilJsonData, options: []),
let jsonItems = json as? Array<NSDictionary>
else {
// 倘若JSON序列化失败,或者转换类型失败
// 返回一个空数组结果
return []
}
return jsonItems.flatMap({ (itemDesc: NSDictionary) -> ListItem? in
let item = ListItem()
if let icon = itemDesc["icon"] as? String {
item.icon = UIImage(named: icon)
}
if let title = itemDesc["title"] as? String {
item.title = title
}
if let urlString = itemDesc["url"] as? String, let url = NSURL(string: urlString) {
item.url = url
}
var icon: UIImage?
let iconName = itemDesc["icon"] as? String
// 三种写法
// item = iconName.flatMap(UIImage.init)
icon = iconName.flatMap{ UIImage(named: $0) }
// item = iconName.flatMap({ imageName in
// UIImage(named: imageName)
// })
return item
})
return jsonItems.map({ (itemDesc: NSDictionary) -> ListItem in
let item = ListItem()
if let icon = itemDesc["icon"] as? String {
item.icon = UIImage(named: icon)
}
if let title = itemDesc["title"] as? String {
item.title = title
}
if let urlString = itemDesc["url"] as? String, let url = NSURL(string: urlString) {
item.url = url
}
return item
})
var items = [ListItem]()
for itemDesc in jsonItems {
let item = ListItem()
if let icon = itemDesc["icon"] as? String {
item.icon = UIImage(named: icon)
}
if let title = itemDesc["title"] as? String {
item.title = title
}
if let urlString = itemDesc["url"] as? String, let url = NSURL(string: urlString) {
item.url = url
}
items.append(item)
}
return items
}
}
|
mit
|
87c27796f083a851b0e3a6ca511e2b1c
| 29.666667 | 96 | 0.462519 | 4.738899 | false | false | false | false |
segmentio/analytics-ios
|
Examples/FullExampleFlowCatalyst/Analytics Example/Controllers/SignInViewController.swift
|
2
|
1742
|
//
// SigninViewController.swift
// Analytics Example
//
// Created by Cody Garvin on 6/9/20.
// Copyright © 2020 Cody Garvin. All rights reserved.
//
import UIKit
import Analytics
class SigninViewController: StepsViewController {
private var continueButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
descriptionString = "Login with details using identify"
codeString = """
// Start with the analytics singleton
let analytics = Analytics.shared()
// Screen
analytics.screen("Dashboard")
// Signed in
analytics.track("Signed In", properties: ["username": "pgibbons"])
"""
// Add the button
let signinButton = UIButton.SegmentButton("Sign In", target: self, action: #selector(signin(_:)))
continueButton = UIButton.SegmentButton("Continue", target: self, action: #selector(continueToNext(_:)))
continueButton.isEnabled = false
propertyViews = [signinButton, UIView.separator(), continueButton, UIView.separator()]
// Fire off the beginning analytics
startAnalytics()
}
private
func startAnalytics() {
let analytics = Analytics.shared()
// identify screen load
analytics.screen("Dashboard")
}
@objc
func signin(_ sender: Any) {
let analytics = Analytics.shared()
// track CTA tap
analytics.track("Signed In", properties: ["username": "pgibbons"])
continueButton.isEnabled = true
}
@objc
func continueToNext(_ sender: Any) {
let trailEndVC = TrialEndViewController(nibName: nil, bundle: nil)
navigationController?.pushViewController(trailEndVC, animated: true)
}
}
|
mit
|
7416268df172221e6cb6a3bb4b22693a
| 26.634921 | 112 | 0.64618 | 4.743869 | false | false | false | false |
loiwu/SCoreData
|
UnCloudNotes/UnCloudNotes/NotesListViewController.swift
|
1
|
4010
|
//
// NotesListViewController.swift
// UnCloudNotes
//
// Created by loi on 1/28/15.
// Copyright (c) 2015 GWrabbit. All rights reserved.
//
import UIKit
import CoreData
//@objc (NotesListViewController)
class NotesListViewController: UITableViewController, NSFetchedResultsControllerDelegate {
lazy var stack : CoreDataStack = CoreDataStack(modelName:"UnCloudNotesDataModel", storeName:"UnCloudNotes", options:[NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: false])
var _notes : NSFetchedResultsController? = nil
var notes : NSFetchedResultsController {
if _notes == nil {
let request = NSFetchRequest(entityName: "Note")
request.sortDescriptors = [NSSortDescriptor(key: "dateCreated", ascending: false)]
let notes = NSFetchedResultsController(fetchRequest: request, managedObjectContext: stack.context, sectionNameKeyPath: nil, cacheName: nil)
notes.delegate = self
_notes = notes
}
return _notes!
}
override func viewWillAppear(animated: Bool){
super.viewWillAppear(animated)
notes.performFetch(nil)
tableView.reloadData()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var objects = notes.fetchedObjects
if let objects = objects
{
return objects.count
}
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let note = notes.fetchedObjects![indexPath.row] as Note
var identifier = "NoteCell"
if note.image != nil {
identifier = "NoteCellImage"
}
var cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as NoteTableViewCell;
cell.note = notes.fetchedObjects![indexPath.row] as? Note
return cell
}
func controllerWillChangeContent(controller: NSFetchedResultsController) {
}
func controller(controller: NSFetchedResultsController!, didChangeObject anObject: AnyObject!, atIndexPath indexPath: NSIndexPath!, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath!) {
switch type
{
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Automatic)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
default:
break
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController!) {
}
@IBAction
func unwindToNotesList(segue:UIStoryboardSegue) {
NSLog("Unwinding to Notes List")
var error : NSErrorPointer = nil
if stack.context.hasChanges
{
if stack.context.save(error) == false
{
print("Error saving \(error)")
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "createNote"
{
let context = NSManagedObjectContext(concurrencyType: .ConfinementConcurrencyType)
context.parentContext = stack.context
let navController = segue.destinationViewController as UINavigationController
let nextViewController = navController.topViewController as CreateNoteViewController
nextViewController.managedObjectContext = context
}
if segue.identifier == "showNoteDetail" {
let detailView = segue.destinationViewController as NoteDetailViewController
if let selectedIndex = tableView.indexPathForSelectedRow() {
if let objects = notes.fetchedObjects {
detailView.note = objects[selectedIndex.row] as? Note
}
}
}
}
}
|
mit
|
ed26f8fc38b2955ba8fb217195532bf0
| 36.12963 | 220 | 0.658105 | 5.958395 | false | false | false | false |
m-alani/contests
|
hackerrank/BirthdayCakeCandles.swift
|
1
|
725
|
//
// BirthdayCakeCandles.swift
//
// Practice solution - Marwan Alani - 2017
//
// Check the problem (and run the code) on HackerRank @ https://www.hackerrank.com/challenges/birthday-cake-candles
// Note: make sure that you select "Swift" from the top-right language menu of the code editor when testing this code
//
import Foundation
// Read (and ignore) N
_ = readLine()
// Read the candles heights
let heights = String(readLine()!)!.components(separatedBy: " ").map({Int($0)!})
// Process the case
var output = 0
var max = heights[0]
for height in heights {
if height > max {
max = height
output = 1
} else if height == max {
output += 1
}
}
// Print the output
print(output)
|
mit
|
06528b3f8f5ef4b254441e812c146333
| 22.387097 | 118 | 0.657931 | 3.571429 | false | false | false | false |
jasnig/ScrollPageView
|
ScrollPageView/SegmentStyle.swift
|
1
|
3081
|
//
// SegmentStyle.swift
// ScrollViewController
//
// Created by jasnig on 16/4/13.
// Copyright © 2016年 ZeroJ. All rights reserved.
// github: https://github.com/jasnig
// 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles
//
// 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
public struct SegmentStyle {
/// 是否显示遮盖
public var showCover = false
/// 是否显示下划线
public var showLine = false
/// 是否缩放文字
public var scaleTitle = false
/// 是否可以滚动标题
public var scrollTitle = true
/// 是否颜色渐变
public var gradualChangeTitleColor = false
/// 是否显示附加的按钮
public var showExtraButton = false
public var extraBtnBackgroundImageName: String?
/// 下面的滚动条的高度 默认2
public var scrollLineHeight: CGFloat = 2
/// 下面的滚动条的颜色
public var scrollLineColor = UIColor.brownColor()
/// 遮盖的背景颜色
public var coverBackgroundColor = UIColor.lightGrayColor()
/// 遮盖圆角
public var coverCornerRadius = 14.0
/// cover的高度 默认28
public var coverHeight: CGFloat = 28.0
/// 文字间的间隔 默认15
public var titleMargin: CGFloat = 15
/// 文字 字体 默认14.0
public var titleFont = UIFont.systemFontOfSize(14.0)
/// 放大倍数 默认1.3
public var titleBigScale: CGFloat = 1.3
/// 默认倍数 不可修改
let titleOriginalScale: CGFloat = 1.0
/// 文字正常状态颜色 请使用RGB空间的颜色值!! 如果提供的不是RGB空间的颜色值就可能crash
public var normalTitleColor = UIColor(red: 51.0/255.0, green: 53.0/255.0, blue: 75/255.0, alpha: 1.0)
/// 文字选中状态颜色 请使用RGB空间的颜色值!! 如果提供的不是RGB空间的颜色值就可能crash
public var selectedTitleColor = UIColor(red: 255.0/255.0, green: 0.0/255.0, blue: 121/255.0, alpha: 1.0)
public init() {
}
}
|
mit
|
f841b988823906f3637ef4e2779ac872
| 33.1375 | 108 | 0.700733 | 3.866856 | false | false | false | false |
1170197998/SinaWeibo
|
SFWeiBo/SFWeiBo/Classes/Oauth/UserAccount.swift
|
1
|
4807
|
//
// UserAccount.swift
// SFWeiBo
//
// Created by mac on 16/4/6.
// Copyright © 2016年 ShaoFeng. All rights reserved.
//
import UIKit
import SVProgressHUD
class UserAccount: NSObject,NSCoding {
/*
access_token string 用户授权的唯一票据,用于调用微博的开放接口,
expires_in string access_token的生命周期,单位是秒数。
remind_in string access_token的生命周期(该参数即将废弃,开发者请使用expires_in)。
uid string 授权用户的UID,
*/
var access_token: String?
var expires_in: NSNumber? {
didSet {
//赋值的时候调用次方法(根据过期的秒数生成真正的过期时间)
expires_Date = NSDate(timeIntervalSince1970: (expires_in?.doubleValue)!)
}
}
//保存用户过期时间
var expires_Date: NSDate?
var uid: String?
//用户头像(大图)
var avatar_large: String?
//用户昵称
var screen_name: String?
override init() {
}
init(dict: [String:AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
//忽略没有的key
}
//重写description
override var description: String {
//定义属性数组
let property = ["access_token","expires_in","uid","expires_Date","avatar_large","screen_name"]
//根据属性数组,将属性转换为字典
let dict = self.dictionaryWithValuesForKeys(property)
//将字典转换为字符串
return "\(dict)"
}
func loadUserInfo(finish: (account: UserAccount?, error:NSError?) -> ()) {
//断言
assert(access_token != nil, "没有授权")
let path = "2/users/show.json"
let params = ["access_token":access_token!, "uid":uid!]
NetworkTools.shareNetworkTools().GET(path, parameters: params, progress: { (_) -> Void in
}, success: { (_, JSON) -> Void in
print(JSON)
//判断字典是否有值
if let dict = JSON as? [String: AnyObject] {
self.screen_name = dict["screen_name"] as? String
self.avatar_large = dict["avatar_large"] as? String
//保存用户信息
//self.saveAccount()
finish(account: self, error: nil)
return
}
finish(account: nil, error: nil)
}) { (_, error) -> Void in
print(error)
finish(account: nil, error: error)
}
}
//返回用户是否登录
class func userLogin() -> Bool {
return UserAccount.loadAccount() != nil
}
//MARK: - 保存和读取 Keyed
static let filePath = "account.plist".cacheDir()
func saveAccount() {
NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.filePath) //对象发放访问需要加类名
}
//加载授权模型
static var account: UserAccount?
class func loadAccount() -> UserAccount? {
//判断是否已经记载过(已经加载过则不加载)
if account != nil {
return account
}
//加载授权模型
account = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? UserAccount //类方法直接访问
//判断授权信息是否过期
if account?.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedAscending {
//已经过期
return nil
}
return account
}
//MARK: - NSCoding
//写入到文件
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(access_token, forKey: "access_token")
aCoder.encodeObject(expires_in, forKey: "expires_in")
aCoder.encodeObject(uid, forKey: "uid")
aCoder.encodeObject(expires_Date, forKey: "expires_Date")
aCoder.encodeObject(screen_name, forKey: "screen_name")
aCoder.encodeObject(avatar_large, forKey: "avatar_large")
}
//从文件中读取
required init?(coder aDecoder: NSCoder) {
access_token = aDecoder.decodeObjectForKey("access_token") as? String
expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber
uid = aDecoder.decodeObjectForKey("uid") as? String
expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
}
}
|
apache-2.0
|
5d5e8f3fe20cbd34efbba1d563eb9cee
| 29.338028 | 102 | 0.568477 | 4.386965 | false | false | false | false |
philipgreat/b2b-swift-app
|
B2BSimpleApp/B2BSimpleApp/CreditAccountRemoteManagerImpl.swift
|
1
|
2376
|
//Domain B2B/CreditAccount/
import SwiftyJSON
import Alamofire
import ObjectMapper
class CreditAccountRemoteManagerImpl:RemoteManagerImpl,CustomStringConvertible{
override init(){
//lazy load for all the properties
//This is good for UI applications as it might saves RAM which is very expensive in mobile devices
}
override var remoteURLPrefix:String{
//Every manager need to config their own URL
return "https://philipgreat.github.io/naf/creditAccountManager/"
}
func loadCreditAccountDetail(creditAccountId:String,
creditAccountSuccessAction: (CreditAccount)->String,
creditAccountErrorAction: (String)->String){
let methodName = "loadCreditAccountDetail"
let parameters = [creditAccountId]
let url = compositeCallURL(methodName, parameters: parameters)
Alamofire.request(.GET, url).validate().responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
if let creditAccount = self.extractCreditAccountFromJSON(json){
creditAccountSuccessAction(creditAccount)
}
}
case .Failure(let error):
print(error)
creditAccountErrorAction("\(error)")
}
}
}
func extractCreditAccountFromJSON(json:JSON) -> CreditAccount?{
let jsonTool = SwiftyJSONTool()
let creditAccount = jsonTool.extractCreditAccount(json)
return creditAccount
}
//Confirming to the protocol CustomStringConvertible of Foundation
var description: String{
//Need to find out a way to improve this method performance as this method might called to
//debug or log, using + is faster than \(var).
let result = "CreditAccountRemoteManagerImpl, V1"
return result
}
static var CLASS_VERSION = 1
//This value is for serializer like message pack to identify the versions match between
//local and remote object.
}
//Reference http://grokswift.com/simple-rest-with-swift/
//Reference https://github.com/SwiftyJSON/SwiftyJSON
//Reference https://github.com/Alamofire/Alamofire
//Reference https://github.com/Hearst-DD/ObjectMapper
//let remote = RemoteManagerImpl()
//let result = remote.compositeCallURL(methodName: "getDetail",parameters:["O0000001"])
//print(result)
|
mit
|
8735e05596540c79bf47aca8101e39da
| 26.97561 | 100 | 0.705387 | 3.953411 | false | false | false | false |
wireapp/wire-ios-sync-engine
|
Source/UserSession/UserProfileUpdateStatus.swift
|
1
|
15911
|
//
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
/// Number of autogenerated names to try as handles
private let alternativeAutogeneratedNames = 3
/// Tracks the status of request to update the user profile
@objcMembers public class UserProfileUpdateStatus: NSObject {
/// phone credentials to update
fileprivate(set) var phoneNumberToSet: ZMPhoneCredentials?
/// should be removing phone
fileprivate(set) var removePhoneNumber: Bool?
/// email to set
fileprivate(set) var emailToSet: String?
/// password to set
fileprivate(set) var passwordToSet: String?
/// phone number to validate
fileprivate(set) var phoneNumberForWhichCodeIsRequested: String?
/// handle to check for availability
fileprivate(set) var handleToCheck: String?
/// handle to check
fileprivate(set) var handleToSet: String?
/// last set password and email
fileprivate(set) var lastEmailAndPassword: ZMEmailCredentials?
/// suggested handles to check for availability
fileprivate(set) var suggestedHandlesToCheck: [String]?
/// best handle suggestion found so far
fileprivate(set) public var bestHandleSuggestion: String?
/// analytics instance used to perform the tracking calls
fileprivate weak var analytics: AnalyticsType?
let managedObjectContext: NSManagedObjectContext
/// Callback invoked when there is a new request to send
let newRequestCallback : () -> Void
public convenience init(managedObjectContext: NSManagedObjectContext) {
self.init(managedObjectContext: managedObjectContext, analytics: managedObjectContext.analytics)
}
// This separate initializer is needed as functions with default arguments are not visible in objective-c
init(managedObjectContext: NSManagedObjectContext, analytics: AnalyticsType?) {
self.managedObjectContext = managedObjectContext
self.newRequestCallback = { RequestAvailableNotification.notifyNewRequestsAvailable(nil) }
self.analytics = analytics ?? managedObjectContext.analytics
}
}
// MARK: - User profile protocol
extension UserProfileUpdateStatus: UserProfile {
public var lastSuggestedHandle: String? {
return self.bestHandleSuggestion
}
public func requestPhoneVerificationCode(phoneNumber: String) {
self.managedObjectContext.performGroupedBlock {
self.phoneNumberForWhichCodeIsRequested = phoneNumber
self.newRequestCallback()
}
}
public func requestPhoneNumberChange(credentials: ZMPhoneCredentials) {
self.managedObjectContext.performGroupedBlock {
self.phoneNumberToSet = credentials
self.newRequestCallback()
}
}
public func requestPhoneNumberRemoval() {
self.managedObjectContext.performGroupedBlock {
let selfUser = ZMUser.selfUser(in: self.managedObjectContext)
guard selfUser.emailAddress != nil else {
self.didFailPhoneNumberRemoval(error: UserProfileUpdateError.removingLastIdentity)
return
}
self.removePhoneNumber = true
self.newRequestCallback()
}
}
public func requestEmailChange(email: String) throws {
guard !email.isEmpty else {
throw UserProfileUpdateError.missingArgument
}
self.managedObjectContext.performGroupedBlock {
let selfUser = ZMUser.selfUser(in: self.managedObjectContext)
guard selfUser.emailAddress != nil else {
self.didFailEmailUpdate(error: UserProfileUpdateError.emailNotSet)
return
}
self.emailToSet = email
self.newRequestCallback()
}
}
public func requestSettingEmailAndPassword(credentials: ZMEmailCredentials) throws {
guard let email = credentials.email, let password = credentials.password else {
throw UserProfileUpdateError.missingArgument
}
self.managedObjectContext.performGroupedBlock {
let selfUser = ZMUser.selfUser(in: self.managedObjectContext)
guard selfUser.emailAddress == nil else {
self.didFailEmailUpdate(error: UserProfileUpdateError.emailAlreadySet)
return
}
self.lastEmailAndPassword = credentials
self.emailToSet = email
self.passwordToSet = password
self.newRequestCallback()
}
}
public func cancelSettingEmailAndPassword() {
self.managedObjectContext.performGroupedBlock {
self.lastEmailAndPassword = nil
self.emailToSet = nil
self.passwordToSet = nil
self.newRequestCallback()
}
}
public func requestCheckHandleAvailability(handle: String) {
self.managedObjectContext.performGroupedBlock {
self.handleToCheck = handle
self.newRequestCallback()
}
}
public func requestSettingHandle(handle: String) {
self.managedObjectContext.performGroupedBlock {
self.handleToSet = handle
self.newRequestCallback()
}
}
public func cancelSettingHandle() {
self.managedObjectContext.performGroupedBlock {
self.handleToSet = nil
}
}
public func suggestHandles() {
self.managedObjectContext.performGroupedBlock {
guard self.suggestedHandlesToCheck == nil else {
// already searching
return
}
if let bestHandle = self.bestHandleSuggestion {
self.suggestedHandlesToCheck = [bestHandle]
} else {
let name = ZMUser.selfUser(in: self.managedObjectContext).name
self.suggestedHandlesToCheck = RandomHandleGenerator.generatePossibleHandles(displayName: name ?? "",
alternativeNames: alternativeAutogeneratedNames)
}
self.newRequestCallback()
}
}
}
// MARK: - Update status
extension UserProfileUpdateStatus {
/// Invoked when requested a phone verification code successfully
func didRequestPhoneVerificationCodeSuccessfully() {
self.phoneNumberForWhichCodeIsRequested = nil
UserProfileUpdateNotification(type: .phoneNumberVerificationCodeRequestDidSucceed).post(in: managedObjectContext.notificationContext)
}
/// Invoked when failed to request a verification code
func didFailPhoneVerificationCodeRequest(error: Error) {
self.phoneNumberForWhichCodeIsRequested = nil
UserProfileUpdateNotification(type: .phoneNumberVerificationCodeRequestDidFail(error: error)).post(in: managedObjectContext.notificationContext)
}
/// Invoked when changing the phone number succeeded
func didChangePhoneSuccesfully() {
self.phoneNumberToSet = nil
}
/// Invoked when changing the phone number failed
func didFailChangingPhone(error: Error) {
self.phoneNumberToSet = nil
UserProfileUpdateNotification(type: .phoneNumberChangeDidFail(error: error)).post(in: managedObjectContext.notificationContext)
}
/// Invoked when the request to set password succedeed
func didUpdatePasswordSuccessfully() {
self.passwordToSet = nil
}
/// Invoked when the request to set password failed
func didFailPasswordUpdate() {
self.lastEmailAndPassword = nil
self.emailToSet = nil
self.passwordToSet = nil
UserProfileUpdateNotification(type: .passwordUpdateDidFail).post(in: managedObjectContext.notificationContext)
}
/// Invoked when the request to change email was sent successfully
func didUpdateEmailSuccessfully() {
self.emailToSet = nil
UserProfileUpdateNotification(type: .emailDidSendVerification).post(in: managedObjectContext.notificationContext)
}
/// Invoked when the request to change phone number was sent successfully
func didRemovePhoneNumberSuccessfully() {
self.removePhoneNumber = nil
UserProfileUpdateNotification(type: .didRemovePhoneNumber).post(in: managedObjectContext.notificationContext)
}
/// Invoked when the request to change phone number failed
func didFailPhoneNumberRemoval(error: Error) {
self.removePhoneNumber = nil
UserProfileUpdateNotification(type: .phoneNumberRemovalDidFail(error: error)).post(in: managedObjectContext.notificationContext)
}
/// Invoked when the request to change email failed
func didFailEmailUpdate(error: Error) {
self.lastEmailAndPassword = nil
self.emailToSet = nil
self.passwordToSet = nil
UserProfileUpdateNotification(type: .emailUpdateDidFail(error: error)).post(in: managedObjectContext.notificationContext)
}
/// Invoked when the request to fetch a handle returned not found
func didNotFindHandle(handle: String) {
if self.handleToCheck == handle {
self.handleToCheck = nil
}
UserProfileUpdateNotification(type: .didCheckAvailabilityOfHandle(handle: handle, available: true)).post(in: managedObjectContext.notificationContext)
}
/// Invoked when the request to fetch a handle returned successfully
func didFetchHandle(handle: String) {
if self.handleToCheck == handle {
self.handleToCheck = nil
}
UserProfileUpdateNotification(type: .didCheckAvailabilityOfHandle(handle: handle, available: false)).post(in: managedObjectContext.notificationContext)
}
/// Invoked when the request to fetch a handle failed with
/// an error that is not "not found"
func didFailRequestToFetchHandle(handle: String) {
if self.handleToCheck == handle {
self.handleToCheck = nil
}
UserProfileUpdateNotification(type: .didFailToCheckAvailabilityOfHandle(handle: handle)).post(in: managedObjectContext.notificationContext)
}
/// Invoked when the handle was succesfully set
func didSetHandle() {
if let handle = self.handleToSet {
ZMUser.selfUser(in: self.managedObjectContext).handle = handle
}
self.handleToSet = nil
UserProfileUpdateNotification(type: .didSetHandle).post(in: managedObjectContext.notificationContext)
}
/// Invoked when the handle was not set because of a generic error
func didFailToSetHandle() {
self.handleToSet = nil
UserProfileUpdateNotification(type: .didFailToSetHandle).post(in: managedObjectContext.notificationContext)
}
/// Invoked when the handle was not set because it was already existing
func didFailToSetAlreadyExistingHandle() {
self.handleToSet = nil
UserProfileUpdateNotification(type: .didFailToSetHandleBecauseExisting).post(in: managedObjectContext.notificationContext)
}
/// Invoked when a good handle suggestion is found
func didFindHandleSuggestion(handle: String) {
self.bestHandleSuggestion = handle
self.suggestedHandlesToCheck = nil
UserProfileUpdateNotification(type: .didFindHandleSuggestion(handle: handle)).post(in: managedObjectContext.notificationContext)
}
/// Invoked when all potential suggested handles were not available
func didNotFindAvailableHandleSuggestion() {
if ZMUser.selfUser(in: self.managedObjectContext).handle != nil {
// it has handle, no need to keep suggesting
self.suggestedHandlesToCheck = nil
} else {
let name = ZMUser.selfUser(in: self.managedObjectContext).name
self.suggestedHandlesToCheck = RandomHandleGenerator.generatePossibleHandles(displayName: name ?? "",
alternativeNames: alternativeAutogeneratedNames)
}
}
/// Invoked when failed to fetch handle suggestion
func didFailToFindHandleSuggestion() {
self.suggestedHandlesToCheck = nil
}
}
// MARK: - Data
extension UserProfileUpdateStatus: ZMCredentialProvider {
/// The email credentials being set
public func emailCredentials() -> ZMEmailCredentials? {
guard !self.currentlySettingEmail && !self.currentlySettingPassword else {
return nil
}
return self.lastEmailAndPassword
}
public func credentialsMayBeCleared() {
self.lastEmailAndPassword = nil
}
}
// MARK: - External status
extension UserProfileUpdateStatus {
/// Whether the current user has an email set in the profile
private var selfUserHasEmail: Bool {
let selfUser = ZMUser.selfUser(in: self.managedObjectContext)
return selfUser.emailAddress != nil && selfUser.emailAddress != ""
}
/// Whether the current user has a phone number set in the profile
private var selfUserHasPhoneNumber: Bool {
let selfUser = ZMUser.selfUser(in: self.managedObjectContext)
return selfUser.phoneNumber != nil && selfUser.phoneNumber != ""
}
/// Whether we are currently changing email
public var currentlyChangingEmail: Bool {
guard self.selfUserHasEmail else {
return false
}
return self.emailToSet != nil
}
/// Whether we are currently setting the email.
public var currentlySettingEmail: Bool {
guard !self.selfUserHasEmail else {
return false
}
return self.emailToSet != nil && self.passwordToSet == nil
}
/// Whether we are currently setting the password.
public var currentlySettingPassword: Bool {
guard !self.selfUserHasEmail else {
return false
}
return self.passwordToSet != nil
}
/// Whether we are currently requesting a PIN to update the phone
public var currentlyRequestingPhoneVerificationCode: Bool {
return self.phoneNumberForWhichCodeIsRequested != nil
}
/// Whether we are currently requesting a change of phone number
public var currentlySettingPhone: Bool {
return self.phoneNumberToSet != nil
}
/// Whether we are currently removing phone number
public var currentlyRemovingPhoneNumber: Bool {
guard self.selfUserHasPhoneNumber && self.selfUserHasEmail else {
return false
}
return self.removePhoneNumber == true
}
/// Whether we are currently waiting to check for availability of a handle
public var currentlyCheckingHandleAvailability: Bool {
return self.handleToCheck != nil
}
/// Whether we are currently requesting a change of handle
public var currentlySettingHandle: Bool {
return self.handleToSet != nil
}
/// Whether we are currently looking for a valid suggestion for a handle
public var currentlyGeneratingHandleSuggestion: Bool {
return ZMUser.selfUser(in: self.managedObjectContext).handle == nil && self.suggestedHandlesToCheck != nil
}
}
// MARK: - Helpers
/// Errors
public enum UserProfileUpdateError: Int, Error {
case missingArgument
case emailAlreadySet
case emailNotSet
case removingLastIdentity
}
|
gpl-3.0
|
61078c4480bdf3957c01ae1b40154932
| 35.493119 | 159 | 0.689146 | 5.386256 | false | false | false | false |
rechsteiner/Parchment
|
Parchment/Structs/PagingItems.swift
|
1
|
3191
|
import Foundation
/// A data structure used to hold an array of `PagingItem`'s, with
/// methods for getting the index path for a given `PagingItem` and
/// vice versa.
public struct PagingItems {
/// A sorted array of the currently visible `PagingItem`'s.
public let items: [PagingItem]
let hasItemsBefore: Bool
let hasItemsAfter: Bool
private var cachedItems: [Int: PagingItem]
init(items: [PagingItem], hasItemsBefore: Bool = false, hasItemsAfter: Bool = false) {
self.items = items
self.hasItemsBefore = hasItemsBefore
self.hasItemsAfter = hasItemsAfter
cachedItems = [:]
for item in items {
cachedItems[item.identifier] = item
}
}
/// The `IndexPath` for a given `PagingItem`. Returns nil if the
/// `PagingItem` is not in the `items` array.
///
/// - Parameter pagingItem: A `PagingItem` instance
/// - Returns: The `IndexPath` for the given `PagingItem`
public func indexPath(for pagingItem: PagingItem) -> IndexPath? {
guard let index = items.firstIndex(where: { $0.isEqual(to: pagingItem) }) else { return nil }
return IndexPath(item: index, section: 0)
}
/// The `PagingItem` for a given `IndexPath`. This method will crash
/// if you pass in an `IndexPath` that is currently not visible in
/// the collection view.
///
/// - Parameter indexPath: An `IndexPath` that is currently visible
/// - Returns: The `PagingItem` for the given `IndexPath`
public func pagingItem(for indexPath: IndexPath) -> PagingItem {
return items[indexPath.item]
}
/// The direction from a given `PagingItem` to another `PagingItem`.
/// If the `PagingItem`'s are equal the direction will be .none.
///
/// - Parameter from: The current `PagingItem`
/// - Parameter to: The `PagingItem` being scrolled towards
/// - Returns: The `PagingDirection` for a given `PagingItem`
public func direction(from: PagingItem, to: PagingItem) -> PagingDirection {
if from.isBefore(item: to) {
return .forward(sibling: isSibling(from: from, to: to))
} else if to.isBefore(item: from) {
return .reverse(sibling: isSibling(from: from, to: to))
}
return .none
}
func isSibling(from: PagingItem, to: PagingItem) -> Bool {
guard
let fromIndex = items.firstIndex(where: { $0.isEqual(to: from) }),
let toIndex = items.firstIndex(where: { $0.isEqual(to: to) })
else { return false }
if fromIndex == toIndex - 1 {
return true
} else if fromIndex - 1 == toIndex {
return true
} else {
return false
}
}
func contains(_ pagingItem: PagingItem) -> Bool {
return cachedItems[pagingItem.identifier] != nil ? true : false
}
func union(_ newItems: [PagingItem]) -> [PagingItem] {
let old = Set(items.map { AnyPagingItem(base: $0) })
let new = Set(newItems.map { AnyPagingItem(base: $0) })
return Array(old.union(new))
.map { $0.base }
.sorted(by: { $0.isBefore(item: $1) })
}
}
|
mit
|
03220780543435044e98aaa7612faa04
| 36.104651 | 101 | 0.613601 | 4.112113 | false | false | false | false |
josefdolezal/fit-cvut
|
BI-PSI/assignment-01/assignment-01/BotServer.swift
|
1
|
2458
|
//
// BotServer.swift
// assignment-01
//
// Created by Josef Dolezal on 30/04/16.
// Copyright © 2016 Josef Dolezal. All rights reserved.
//
import Foundation
// MARK: BotServer
class BotServer {
internal static let connectionTimeout = 1
internal static let rechargingTimeout = 5
private let serverSocket : Int32
private var callback : ((Int32)->())?
private var maxConnections : Int32!
private var address : sockaddr_in
private var socketClosed = false
init(atPort port : Int) {
serverSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)
address = sockaddr_in.shortInit(AF_INET, port: port, socketAddress: BrigdeToC.ADDR_ANY)
}
func run(maxConnections connections: Int32, connectionCallback: (Int32)->()) -> RunResult {
maxConnections = connections
callback = connectionCallback
if bind(serverSocket, address.asSockAddr(), address.sockLen()) < 0 {
return closeSocketOnError(RunResult.CANNOT_BIND)
}
if listen(serverSocket, 10) < 0 {
return closeSocketOnError(RunResult.CANNOT_LISTEN)
}
connectionLoop()
return RunResult.CONNECTION_CLOSED
}
private func connectionLoop() -> RunResult {
var remoteAddress = sockaddr_in();
var remoteAddressLen = socklen_t();
while true {
let requestDescriptor = accept(serverSocket, remoteAddress.asSockAddr(), &remoteAddressLen)
if requestDescriptor < 0 {
return closeSocketOnError(RunResult.CANNOT_ACCEPT)
}
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) {
self.callback?(requestDescriptor)
}
}
}
private func closeSocketOnError(error: RunResult) -> RunResult {
close(serverSocket)
socketClosed = true
return error
}
deinit {
if !socketClosed {
close(serverSocket)
}
}
}
// MARK: - Server states
enum RunResult {
case CANNOT_BIND
case CANNOT_LISTEN
case CANNOT_ACCEPT
case CANNOT_SEND
case CLOSE_IMMEDIATELY
case CLOSE_WHEN_SENT
case TALK_AGAIN
case SELECT_DOES_NOT_WORK
case CONNECTION_TIMEOUT
case CONNECTION_CLOSED_BY_CLIENT
case CONNECTION_CLOSED
case CONNECTED
case RECEIVE
}
|
mit
|
74087923b8c5ae72e730aa98fe620b9a
| 25.430108 | 103 | 0.614164 | 4.3875 | false | false | false | false |
LYM-mg/MGDYZB
|
MGDYZB/MGDYZB/Class/Live/Controller/ScienceViewController.swift
|
1
|
4982
|
//
// ScienceViewController.swift
// MGDYZB
//
// Created by i-Techsys.com on 17/2/25.
// Copyright © 2017年 ming. All rights reserved.
//
import UIKit
import SafariServices
class ScienceViewController: BaseViewController {
fileprivate lazy var scienceVM = ScienceViewModel()
fileprivate lazy var collectionView : UICollectionView = {[weak self] in
// 1.创建layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
// layout.headerReferenceSize = CGSizeMake(kScreenW, kHeaderViewH)
layout.sectionInset = UIEdgeInsets(top: kItemMargin, left: kItemMargin, bottom: 0, right: kItemMargin)
// 2.创建UICollectionView
let collectionView = UICollectionView(frame: self!.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.scrollsToTop = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// 3.注册
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
// MARK: - setUpUI
extension ScienceViewController {
internal override func setUpMainView() {
contentView = collectionView
view.addSubview(collectionView)
super.setUpMainView()
setUpRefresh()
}
}
// MARK: - setUpUI
extension ScienceViewController {
fileprivate func setUpRefresh() {
// MARK: - 下拉
self.collectionView.header = MJRefreshGifHeader(refreshingBlock: { [weak self]() -> Void in
self!.scienceVM.offset = 0
self?.loadData()
self!.collectionView.header.endRefreshing()
self?.collectionView.footer.endRefreshing()
})
// MARK: - 上拉
self.collectionView.footer = MJRefreshAutoGifFooter(refreshingBlock: {[weak self] () -> Void in
self!.scienceVM.offset += 20
self?.loadData()
self!.collectionView.header.endRefreshing()
self?.collectionView.footer.endRefreshing()
})
self.collectionView.header.isAutoChangeAlpha = true
self.collectionView.header.beginRefreshing()
self.collectionView.footer.noticeNoMoreData()
}
// 加载数据
fileprivate func loadData() {
scienceVM.loadScienceData { (err) in
if err == nil {
self.collectionView.reloadData()
}else {
debugPrint(err)
}
self.loadDataFinished()
}
}
}
// MARK: - UICollectionViewDataSource
extension ScienceViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return scienceVM.scienceModels.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 1.取出Cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell
// 2.给cell设置数据
let anchor = scienceVM.scienceModels[(indexPath as NSIndexPath).item]
cell.anchor = anchor
return cell
}
}
// MARK: - UICollectionViewDelegate
extension ScienceViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let anchor = scienceVM.scienceModels[indexPath.item]
anchor.isVertical == 0 ? pushNormalRoomVc(model: anchor) : presentShowRoomVc(model: anchor)
}
fileprivate func pushNormalRoomVc(model: AnchorModel) {
let webViewVc = WKWebViewController(navigationTitle: model.room_name, urlStr: model.jumpUrl)
show(webViewVc, sender: nil)
}
fileprivate func presentShowRoomVc(model: AnchorModel) {
if #available(iOS 9, *) {
if let url = URL(string: model.jumpUrl) {
let webViewVc = SFSafariViewController(url: url, entersReaderIfAvailable: true)
present(webViewVc, animated: true, completion: nil)
}
} else {
let webViewVc = WKWebViewController(navigationTitle: model.room_name, urlStr: model.jumpUrl)
present(webViewVc, animated: true, completion: nil)
}
}
}
|
mit
|
7b60be0040fca7b25e51107e03315336
| 34.014184 | 130 | 0.656877 | 5.443219 | false | false | false | false |
giftbott/ViperModuleTemplate
|
install_template.swift
|
1
|
4957
|
//
// install_template.swift
// Install VIPER Template
//
// Created by giftbott on 17/02/2017.
// Copyright © 2017 giftbott. All rights reserved.
//
import Foundation
let fileManager = FileManager.default
/// Should select template only if more than one
func setup() {
let templateChecker = try? fileManager
.contentsOfDirectory(atPath: ".")
.filter { $0.hasSuffix(".xctemplate") }
guard let templates = templateChecker, !templates.isEmpty else {
printInConsole("xctemplate directory does not exist")
return
}
guard templates.count > 1 else {
installTemplate(templates[0])
return
}
/// Show xctemplates in current directory
print("Select Template")
print(String(repeating: "#", count:30))
print(templates.enumerated().map { String(describing: "\($0 + 1): \($1)") }.joined(separator: "\n"))
print(String(repeating: "#", count:30), terminator: "\n\n")
/// User select xctemplate
var templateName: String = templates[0]
while true {
print("Select template number : ", terminator: "")
let input = readLine() ?? "1"
guard let num = Int(input), num >= 1, num <= templates.count else {
print("Wrong Value\n")
continue
}
templateName = templates[num - 1]
printInConsole("\(templateName) is selected")
print()
break
}
installTemplate(templateName)
}
/// Copy template to selected target path
func installTemplate(_ templateName: String) {
// Print Target Directory Path
print("Select Directory Path to Install Template")
print(String(repeating: "#", count:40))
print("1: Custom File Template")
print("2: Xcode File Template (admin only)")
print(String(repeating: "#", count:40), terminator: "\n\n")
// Select Target Base Path
let userHomeDirectory = "/Users/".appending(bash(command: "whoami", arguments: []))
let xcodeBasePath = bash(command: "xcode-select", arguments: ["--print-path"])
// Default Path (For Custom File Template)
var directoryPath = userHomeDirectory
var pathEndPoint = PathEndPoint.customFileTemplate.rawValue
while true {
print("Select Target Path Number : ", terminator: "")
let input = readLine() ?? "1"
guard let num = Int(input), num >= 1, num <= 2 else {
print("Wrong Value\n")
continue
}
switch num {
case 1:
guard !isRootUserWithSudoCommand() else {
authorityAlert(needSudo: false)
return
}
case 2:
guard isRootUserWithSudoCommand() else {
authorityAlert(needSudo: true)
return
}
directoryPath = xcodeBasePath
pathEndPoint = PathEndPoint.xcodeFileTemplate.rawValue
default:
break
}
directoryPath.append(pathEndPoint)
printInConsole("Template will be installed at \(directoryPath)")
break
}
let filePath = directoryPath.appending("/\(templateName)")
_ = bash(command: "mkdir", arguments: ["-p", directoryPath])
copyTemplate(from: templateName, to: filePath)
}
///
func copyTemplate(from: String, to: String) {
do {
printInConsole(".....")
defer { print() }
if !fileManager.fileExists(atPath: to) {
try fileManager.copyItem(atPath: from, toPath: to)
printInConsole("Template installed succesfully.")
} else {
try _ = fileManager.removeItem(atPath: to)
try fileManager.copyItem(atPath: from, toPath: to)
printInConsole("Template has been replaced succesfully.")
}
} catch let error as NSError {
printInConsole("Ooops! Something went wrong: \(error.localizedFailureReason!)")
}
}
/// Bash Shell Command
func bash(command: String, arguments: [String]) -> String {
let commandPath = shell(launchPath: "/bin/bash", arguments: ["-c", "which \(command)" ])
return shell(launchPath: commandPath, arguments: arguments)
}
func shell(launchPath: String, arguments: [String]) -> String {
let task = Process()
task.launchPath = launchPath
task.arguments = arguments
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: String.Encoding.utf8)!
return output.trimmingCharacters(in: .newlines)
}
func isRootUserWithSudoCommand() -> Bool {
return bash(command: "whoami", arguments: []) == "root"
}
/// Print Helper
func printInConsole(_ message: String) {
print(">>>>", message)
}
func authorityAlert(needSudo: Bool) {
if needSudo {
print("It needs to be executed with sudo command\n")
} else {
print("CustomTemplate must be executed without sudo command\n")
}
}
/// Target Url
enum PathEndPoint: String {
case customFileTemplate = "/Library/Developer/Xcode/Templates/File Templates/Custom"
//iOS Platform
case xcodeFileTemplate = "/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templates/File Templates/Source"
}
// ===============
// MARK: - Execute
// ===============
setup()
|
mit
|
005d7432e0d892990cdff685079919ac
| 26.842697 | 113 | 0.664851 | 4.106048 | false | false | false | false |
EzimetYusup/WormTabStrip
|
WormTabStrip/WormTabStrip/WormLib/WormTabStrip.swift
|
1
|
24705
|
//
// Test.swift
// EYViewPager
//
// Created by Ezimet Yusuf on 7/4/16.
// Copyright © 2016 Ezimet Yusup. All rights reserved.
//
import Foundation
import UIKit
public protocol WormTabStripDelegate: class {
//return the Number SubViews in the ViewPager
func wtsNumberOfTabs() -> Int
//return the View for sepecific position
func wtsViewOfTab(index:Int) -> UIView
//return the title for each view
func wtsTitleForTab(index:Int) -> String
func wtsDidSelectTab(index:Int)
//the delegate that ViewPager has got End with Left Direction
func wtsReachedLeftEdge(panParam: UIPanGestureRecognizer)
//the delegate that ViewPager has got End with Right Direction
func wtsReachedRightEdge(panParam: UIPanGestureRecognizer)
}
public enum WormStyle{
case bubble
case line
}
public struct WormTabStripStylePropertyies {
var wormStyel: WormStyle = .bubble
/**********************
Heights
**************************/
var kHeightOfWorm: CGFloat = 3
var kHeightOfWormForBubble: CGFloat = 45
var kHeightOfDivider: CGFloat = 2
var kHeightOfTopScrollView: CGFloat = 50
var kMinimumWormHeightRatio: CGFloat = 4/5
/**********************
paddings
**************************/
//Padding of tabs text to each side
var kPaddingOfIndicator: CGFloat = 30
//initial value for the tabs margin
var kWidthOfButtonMargin: CGFloat = 0
var isHideTopScrollView = false
var spacingBetweenTabs: CGFloat = 15
var isWormEnable = true
/**********
fonts
************/
// font size of tabs
//let kFontSizeOfTabButton:CGFloat = 15
var tabItemDefaultFont: UIFont = UIFont(name: "arial", size: 14)!
var tabItemSelectedFont: UIFont = UIFont(name: "arial", size: 16)!
/*****
colors
****/
var tabItemDefaultColor: UIColor = .white
var tabItemSelectedColor: UIColor = .red
//color for worm
var WormColor: UIColor = UIColor(netHex: 0x1EAAF1)
var topScrollViewBackgroundColor: UIColor = UIColor(netHex: 0x364756)
var contentScrollViewBackgroundColor: UIColor = UIColor.gray
var dividerBackgroundColor: UIColor = UIColor.red
}
public class WormTabStrip: UIView,UIScrollViewDelegate {
private let topScrollView: UIScrollView = UIScrollView()
private let contentScrollView: UIScrollView = UIScrollView()
public var shouldCenterSelectedWorm = true
public var Width: CGFloat!
public var Height: CGFloat!
private var titles: [String]! = []
private var contentViews: [UIView]! = []
private var tabs: [WormTabStripButton]! = []
private let divider: UIView = UIView()
private let worm: UIView = UIView()
public var eyStyle: WormTabStripStylePropertyies = WormTabStripStylePropertyies()
//delegate
weak var delegate: WormTabStripDelegate?
//Justify flag
private var isJustified = false
//tapping flag
private var isUserTappingTab = false
private var dynamicWidthOfTopScrollView: CGFloat = 0
private let plusOneforMarginOfLastTabToScreenEdge = 1
//MARK: init
override init(frame: CGRect) {
super.init(frame: frame)
Width = self.frame.width
Height = self.frame.height
}
convenience required public init(key:String) {
self.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func buildUI() {
validate()
addTopScrollView()
addWorm()
addDivider()
addContentScrollView()
buildContent()
checkAndJustify()
selectTabAt(index: currentTabIndex)
setTabStyle()
}
private func validate(){
if delegate == nil {
assert(false, "EYDelegate is null, please set the EYDelegate")
return
}
if delegate!.wtsNumberOfTabs() <= currentTabIndex {
assert(false, "currentTabIndex can not be bigger or equal to EYnumberOfTab")
}
// for i in 0..<delegate.EYnumberOfTab() {
// titles.append(delegate.EYTitlesOfTab(i))
// contentViews.append(delegate.EYviewOfTab(i))
// }
//
// if titles.count != contentViews.count {
// assert(false, "title's size and contentView's size not matching")
// }
}
// add top scroll view to the view stack which will contain the all the tabs
private func addTopScrollView(){
topScrollView.frame = CGRect(x: 0,y: 0, width:Width,height:eyStyle.kHeightOfTopScrollView)
topScrollView.backgroundColor = eyStyle.topScrollViewBackgroundColor
topScrollView.showsHorizontalScrollIndicator = false
self.addSubview(topScrollView)
}
// add divider between the top scroll view and content scroll view
private func addDivider(){
divider.frame = CGRect(x:0,y: eyStyle.kHeightOfTopScrollView, width:Width, height:eyStyle.kHeightOfDivider)
divider.backgroundColor = eyStyle.dividerBackgroundColor
self.addSubview(divider)
}
// add content scroll view to the view stack which will hold mian views such like table view ...
private func addContentScrollView(){
if eyStyle.isHideTopScrollView {
//rootScrollView = UIScrollView(frame: CGRectMake(0,0,Width,Height))
contentScrollView.frame = CGRect(x: 0,y: 0,width: Width,height: Height);
}else{
contentScrollView.frame = CGRect(x: 0,y: eyStyle.kHeightOfTopScrollView+eyStyle.kHeightOfDivider,width: Width, height: Height-eyStyle.kHeightOfTopScrollView-eyStyle.kHeightOfDivider)
}
contentScrollView.backgroundColor = eyStyle.contentScrollViewBackgroundColor
contentScrollView.isPagingEnabled = true
contentScrollView.delegate = self
contentScrollView.showsHorizontalScrollIndicator = false
contentScrollView.showsVerticalScrollIndicator = false
contentScrollView.bounces = false
contentScrollView.panGestureRecognizer.addTarget(self, action: #selector(scrollHandleUIPanGestureRecognizer))
self.addSubview(contentScrollView)
}
private func addWorm(){
topScrollView.addSubview(worm)
resetHeightOfWorm()
worm.frame.size.width = 100
worm.backgroundColor = eyStyle.WormColor
}
private func buildContent(){
buildTopScrollViewsContent()
buildContentScrollViewsContent()
}
private func buildTopScrollViewsContent(){
dynamicWidthOfTopScrollView = 0
var XOffset:CGFloat = eyStyle.spacingBetweenTabs;
for i in 0..<delegate!.wtsNumberOfTabs(){
//build the each tab and position it
let tab:WormTabStripButton = WormTabStripButton()
tab.index = i
formatButton(tab: tab, XOffset: XOffset)
XOffset += eyStyle.spacingBetweenTabs + tab.frame.width
dynamicWidthOfTopScrollView += eyStyle.spacingBetweenTabs + tab.frame.width
topScrollView.addSubview(tab)
tabs.append(tab)
topScrollView.contentSize.width = dynamicWidthOfTopScrollView
}
}
/**************************
format tab style, tap event
***************************************/
private func formatButton(tab:WormTabStripButton,XOffset:CGFloat){
tab.frame.size.height = eyStyle.kHeightOfTopScrollView
tab.paddingToEachSide = eyStyle.kPaddingOfIndicator
// tab.backgroundColor = UIColor.yellowColor()
tab.tabText = delegate!.wtsTitleForTab(index: tab.index!) as NSString?
tab.textColor = eyStyle.tabItemDefaultColor
tab.frame.origin.x = XOffset
tab.frame.origin.y = 0
tab.textAlignment = .center
tab.isUserInteractionEnabled = true
let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.tabPress(sender:)))
tap.numberOfTapsRequired = 1
tap.numberOfTouchesRequired = 1
tab.addGestureRecognizer(tap)
}
// add all content views to content scroll view and tabs to top scroll view
private func buildContentScrollViewsContent(){
let count = delegate!.wtsNumberOfTabs()
contentScrollView.contentSize.width = CGFloat(count)*self.frame.width
for i in 0..<count{
//position each content view
let view = delegate!.wtsViewOfTab(index: i)
view.frame.origin.x = CGFloat(i)*Width
view.frame.origin.y = 0
view.frame.size.height = contentScrollView.frame.size.height
var responder: UIResponder? = view
while !(responder is UIViewController) {
responder = responder?.next
if nil == responder {
break
}
}
let vc = (responder as? UIViewController)!
guard let parent = delegate as? UIViewController else {
contentScrollView.addSubview(view)
return
}
parent.addChild(vc)
vc.beginAppearanceTransition(true, animated: false)
contentScrollView.addSubview(view)
vc.didMove(toParent: parent)
vc.endAppearanceTransition()
}
}
/*** if the content width of the topScrollView smaller than screen width
do justification to the tabs by increasing spcases between the tabs
and rebuild all top and content views
***/
private func checkAndJustify(){
if dynamicWidthOfTopScrollView < Width && !isJustified {
isJustified = true
// calculate the available space
let gap:CGFloat = Width - dynamicWidthOfTopScrollView
// increase the space by dividing available space to # of tab plus one
//plus one bc we always want to have margin from last tab to to right edge of screen
eyStyle.spacingBetweenTabs += gap/CGFloat(delegate!.wtsNumberOfTabs()+plusOneforMarginOfLastTabToScreenEdge)
dynamicWidthOfTopScrollView = 0
var XOffset:CGFloat = eyStyle.spacingBetweenTabs;
for tab in tabs {
tab.frame.origin.x = XOffset
XOffset += eyStyle.spacingBetweenTabs + tab.frame.width
dynamicWidthOfTopScrollView += eyStyle.spacingBetweenTabs + tab.frame.width
topScrollView.contentSize.width = dynamicWidthOfTopScrollView
}
}
}
/*******
tabs selector
********/
@objc func tabPress(sender:AnyObject){
isUserTappingTab = true
let tap:UIGestureRecognizer = sender as! UIGestureRecognizer
let tab:WormTabStripButton = tap.view as! WormTabStripButton
selectTab(tab: tab)
}
func selectTabAt(index:Int){
if index >= tabs.count {return}
let tab = tabs[index]
selectTab(tab: tab)
}
private func selectTab(tab:WormTabStripButton){
prevTabIndex = currentTabIndex
currentTabIndex = tab.index!
setTabStyle()
natruallySlideWormToPosition(tab: tab)
natruallySlideContentScrollViewToPosition(index: tab.index!)
adjustTopScrollViewsContentOffsetX(tab: tab)
centerCurrentlySelectedWorm(tab: tab)
}
/*******
move worm to the correct position with slinding animation when the tabs are clicked
********/
private func natruallySlideWormToPosition(tab:WormTabStripButton){
UIView.animate(withDuration: 0.3) {
self.slideWormToTabPosition(tab: tab)
}
}
private func slideWormToTabPosition(tab:WormTabStripButton){
self.worm.frame.origin.x = tab.frame.origin.x
self.worm.frame.size.width = tab.frame.width
}
/*********************
if the tab was at position of only half of it was showing up,
we need to adjust it by setting content OffSet X of Top ScrollView
when the tab was clicked
*********************/
private func adjustTopScrollViewsContentOffsetX(tab:WormTabStripButton){
let widhtOfTab:CGFloat = tab.bounds.size.width
let XofTab:CGFloat = tab.frame.origin.x
let spacingBetweenTabs = eyStyle.spacingBetweenTabs
//if tab at right edge of screen
if XofTab - topScrollView.contentOffset.x > Width - (spacingBetweenTabs+widhtOfTab) {
topScrollView.setContentOffset(CGPoint(x:XofTab - (Width-(spacingBetweenTabs+widhtOfTab)) , y:0), animated: true)
}
//if tab at left edge of screen
if XofTab - topScrollView.contentOffset.x < spacingBetweenTabs {
topScrollView.setContentOffset(CGPoint(x:XofTab - spacingBetweenTabs, y:0), animated: true)
}
}
func centerCurrentlySelectedWorm(tab:WormTabStripButton){
//check the settings
if shouldCenterSelectedWorm == false {return}
//if worm tab was right/left side of screen and if there are enough space to scroll to center
let XofTab:CGFloat = tab.frame.origin.x
let toLeftOfScreen = (Width-tab.frame.width)/2
//return if there is no enough space at right
if XofTab + tab.frame.width + toLeftOfScreen > topScrollView.contentSize.width{
return
}
//return if there is no enough space at left
if XofTab - toLeftOfScreen < 0 {
return
}
//center it
if topScrollView.contentSize.width - XofTab+tab.frame.width > toLeftOfScreen{
// XofTab = x + (screenWidth-tab.frame.width)/2
let offsetX = XofTab - toLeftOfScreen
topScrollView.setContentOffset(CGPoint.init(x: offsetX, y: 0), animated: true)
}
}
/*******
move content scroll view to the correct position with animation when the tabs are clicked
********/
private func natruallySlideContentScrollViewToPosition(index:Int){
let point = CGPoint(x:CGFloat(index)*Width,y: 0)
UIView.animate(withDuration: 0.3, animations: {
self.contentScrollView.setContentOffset(point, animated: false)
}) { (finish) in
self.isUserTappingTab = false
}
}
/*************************************************
//MARK: UIScrollView Delegate start
******************************************/
var prevTabIndex = 0
var currentTabIndex = 0
var currentWormX:CGFloat = 0
var currentWormWidth:CGFloat = 0
var contentScrollContentOffsetX:CGFloat = 0
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
currentTabIndex = Int(scrollView.contentOffset.x/Width)
setTabStyle()
prevTabIndex = currentTabIndex
let tab = tabs[currentTabIndex]
//need to call setTabStyle twice because, when user swipe their finger really fast, scrollViewWillBeginDragging method will be called agian without scrollViewDidEndDecelerating get call
setTabStyle()
currentWormX = tab.frame.origin.x
currentWormWidth = tab.frame.width
contentScrollContentOffsetX = scrollView.contentOffset.x
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
//if user was tapping tab no need to do worm animation
if isUserTappingTab == true {return}
if eyStyle.isWormEnable == false {return}
let currentX = scrollView.contentOffset.x
var gap:CGFloat = 0
//if user dragging to right, which means scrolling finger from right to left
//which means scroll view is scrolling to right, worm also should worm to right
if currentX > contentScrollContentOffsetX {
gap = currentX - contentScrollContentOffsetX
if gap > Width {
contentScrollContentOffsetX = currentX
currentTabIndex = Int(currentX/Width)
let tab = tabs[currentTabIndex]
natruallySlideWormToPosition(tab: tab)
return
}
//if currentTab is not last one do worm to next tab position
if currentTabIndex + 1 <= tabs.count {
let nextDistance:CGFloat = calculateNextMoveDistance(gap: gap, nextTotal: getNextTotalWormingDistance(index: currentTabIndex+1))
// println(nextDistance)
setWidthAndHeightOfWormForDistance(distance: nextDistance)
}
}else{
//else user dragging to left, which means scrolling finger from left to right
//which means scroll view is scrolling to left, worm also should worm to left
gap = contentScrollContentOffsetX - currentX
//if current is not first tab at left do worm to left
if currentTabIndex >= 1 {
let nextDistance:CGFloat = calculateNextMoveDistance(gap: gap, nextTotal: getNextTotalWormingDistance(index: currentTabIndex-1))
print(nextDistance)
wormToNextLeft(distance: nextDistance)
}
}
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let currentX = scrollView.contentOffset.x
currentTabIndex = Int(currentX/Width)
let tab = tabs[currentTabIndex]
setTabStyle()
adjustTopScrollViewsContentOffsetX(tab: tab)
UIView.animate(withDuration: 0.23) {
self.slideWormToTabPosition(tab: tab)
self.resetHeightOfWorm()
self.centerCurrentlySelectedWorm(tab: tab)
}
}
/*************************************************
//MARK: UIScrollView Delegate end
******************************************/
/*************************************************
//MARK: UIScrollView Delegate Calculations start
******************************************/
private func getNextTotalWormingDistance(index:Int)->CGFloat{
let tab = tabs[index]
let nextTotal:CGFloat = eyStyle.spacingBetweenTabs + tab.frame.width
return nextTotal
}
private func calculateNextMoveDistance(gap:CGFloat,nextTotal:CGFloat)->CGFloat{
let nextMove:CGFloat = (gap*nextTotal)/Width
return nextMove
}
private func setWidthAndHeightOfWormForDistance(distance:CGFloat){
if distance < 1 {
resetHeightOfWorm()
}else{
let height:CGFloat = self.calculatePrespectiveHeightOfIndicatorLine(distance: distance)
worm.frame.size.height = height
worm.frame.size.width = currentWormWidth + distance
}
if eyStyle.wormStyel == .line {
worm.frame.origin.y = eyStyle.kHeightOfTopScrollView - eyStyle.kHeightOfWorm
}else{
worm.frame.origin.y = (eyStyle.kHeightOfTopScrollView-worm.frame.size.height)/2
}
worm.layer.cornerRadius = worm.frame.size.height/2
}
private func wormToNextLeft(distance:CGFloat){
setWidthAndHeightOfWormForDistance(distance: distance)
worm.frame.origin.x = currentWormX - distance
}
private func resetHeightOfWorm(){
// if the style is line it should be placed under the tab
if eyStyle.wormStyel == .line {
worm.frame.origin.y = eyStyle.kHeightOfTopScrollView - eyStyle.kHeightOfWorm
worm.frame.size.height = eyStyle.kHeightOfWorm
}else{
worm.frame.origin.y = (eyStyle.kHeightOfTopScrollView - eyStyle.kHeightOfWormForBubble)/2
worm.frame.size.height = eyStyle.kHeightOfWormForBubble
}
worm.layer.cornerRadius = worm.frame.size.height/2
}
private func calculatePrespectiveHeightOfIndicatorLine(distance:CGFloat)->CGFloat{
var height:CGFloat = 0
var originalHeight:CGFloat = 0
if eyStyle.wormStyel == .line {
height = eyStyle.kHeightOfWorm*(self.currentWormWidth/(distance+currentWormWidth))
originalHeight = eyStyle.kHeightOfWorm
}else{
height = eyStyle.kHeightOfWormForBubble*(self.currentWormWidth/(distance+currentWormWidth))
originalHeight = eyStyle.kHeightOfWormForBubble
}
//if the height of worm becoming too small just make it half of it
if height < (originalHeight*eyStyle.kMinimumWormHeightRatio) {
height = originalHeight*eyStyle.kMinimumWormHeightRatio
}
// return worm.frame.height
return height
}
private func setTabStyle(){
makePrevTabDefaultStyle()
makeCurrentTabSelectedStyle()
}
private func makePrevTabDefaultStyle(){
let tab = tabs[prevTabIndex]
tab.textColor = eyStyle.tabItemDefaultColor
tab.font = eyStyle.tabItemDefaultFont
}
private func makeCurrentTabSelectedStyle(){
let tab = tabs[currentTabIndex]
tab.textColor = eyStyle.tabItemSelectedColor
tab.font = eyStyle.tabItemSelectedFont
syncAppearanceOfVC()
delegate!.wtsDidSelectTab(index: currentTabIndex)
}
private func syncAppearanceOfVC(){
let count = delegate!.wtsNumberOfTabs()
contentScrollView.contentSize.width = CGFloat(count)*self.frame.width
for i in 0..<count{
//position each content view
let view = delegate!.wtsViewOfTab(index: i)
view.frame.origin.x = CGFloat(i)*Width
view.frame.origin.y = 0
view.frame.size.height = contentScrollView.frame.size.height
var responder: UIResponder? = view
while !(responder is UIViewController) {
responder = responder?.next
if nil == responder {
break
}
}
if i == currentTabIndex {
//view will move to parent
let vc = (responder as? UIViewController)!
guard let parent = delegate as? UIViewController else {
return
}
parent.addChild(vc)
vc.beginAppearanceTransition(true, animated: false)
vc.didMove(toParent: parent)
vc.endAppearanceTransition()
} else {
//remove view from parent
let vc = (responder as? UIViewController)!
guard let parent = delegate as? UIViewController else {
return
}
vc.beginAppearanceTransition(false, animated: false)
vc.willMove(toParent: nil)
vc.removeFromParent()
vc.endAppearanceTransition()
}
}
}
/*************************************************
//MARK: Worm Calculations Ends
******************************************/
@objc func scrollHandleUIPanGestureRecognizer(panParam:UIPanGestureRecognizer){
if contentScrollView.contentOffset.x <= 0 {
self.delegate?.wtsReachedLeftEdge(panParam: panParam)
}
else
if contentScrollView.contentOffset.x >= contentScrollView.contentSize.width - contentScrollView.bounds.size.width {
self.delegate?.wtsReachedRightEdge(panParam: panParam)
}
}
}
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(netHex:Int) {
self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
}
}
|
mit
|
8209a45912387cd9012ee5ee829f2412
| 35.926756 | 194 | 0.607999 | 4.806226 | false | false | false | false |
SirWellington/sir-wellington-mall
|
Pods/BRYXBanner/Pod/Classes/Banner.swift
|
1
|
17960
|
//
// Banner.swift
//
// Created by Harlan Haskins on 7/27/15.
// Copyright (c) 2015 Bryx. All rights reserved.
//
import UIKit
private enum BannerState {
case Showing, Hidden, Gone
}
/// A level of 'springiness' for Banners.
///
/// - None: The banner will slide in and not bounce.
/// - Slight: The banner will bounce a little.
/// - Heavy: The banner will bounce a lot.
public enum BannerSpringiness {
case None, Slight, Heavy
private var springValues: (damping: CGFloat, velocity: CGFloat) {
switch self {
case .None: return (damping: 1.0, velocity: 1.0)
case .Slight: return (damping: 0.7, velocity: 1.5)
case .Heavy: return (damping: 0.6, velocity: 2.0)
}
}
}
/// Banner is a dropdown notification view that presents above the main view controller, but below the status bar.
public class Banner: UIView {
class func topWindow() -> UIWindow? {
for window in UIApplication.sharedApplication().windows.reverse() {
if window.windowLevel == UIWindowLevelNormal && !window.hidden && window.frame != CGRectZero { return window }
}
return nil
}
private let contentView = UIView()
private let labelView = UIView()
private let backgroundView = UIView()
/// How long the slide down animation should last.
public var animationDuration: NSTimeInterval = 0.4
/// The preferred style of the status bar during display of the banner. Defaults to `.LightContent`.
///
/// If the banner's `adjustsStatusBarStyle` is false, this property does nothing.
public var preferredStatusBarStyle = UIStatusBarStyle.LightContent
/// Whether or not this banner should adjust the status bar style during its presentation. Defaults to `false`.
public var adjustsStatusBarStyle = false
/// How 'springy' the banner should display. Defaults to `.Slight`
public var springiness = BannerSpringiness.Slight
/// The color of the text as well as the image tint color if `shouldTintImage` is `true`.
public var textColor = UIColor.whiteColor() {
didSet {
resetTintColor()
}
}
/// Whether or not the banner should show a shadow when presented.
public var hasShadows = true {
didSet {
resetShadows()
}
}
/// The color of the background view. Defaults to `nil`.
override public var backgroundColor: UIColor? {
get { return backgroundView.backgroundColor }
set { backgroundView.backgroundColor = newValue }
}
/// The opacity of the background view. Defaults to 0.95.
override public var alpha: CGFloat {
get { return backgroundView.alpha }
set { backgroundView.alpha = newValue }
}
/// A block to call when the uer taps on the banner.
public var didTapBlock: (() -> ())?
/// A block to call after the banner has finished dismissing and is off screen.
public var didDismissBlock: (() -> ())?
/// Whether or not the banner should dismiss itself when the user taps. Defaults to `true`.
public var dismissesOnTap = true
/// Whether or not the banner should dismiss itself when the user swipes up. Defaults to `true`.
public var dismissesOnSwipe = true
/// Whether or not the banner should tint the associated image to the provided `textColor`. Defaults to `true`.
public var shouldTintImage = true {
didSet {
resetTintColor()
}
}
/// The label that displays the banner's title.
public let titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
/// The label that displays the banner's subtitle.
public let detailLabel: UILabel = {
let label = UILabel()
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
/// The image on the left of the banner.
let image: UIImage?
/// The image view that displays the `image`.
public let imageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .ScaleAspectFit
return imageView
}()
private var bannerState = BannerState.Hidden {
didSet {
if bannerState != oldValue {
forceUpdates()
}
}
}
/// A Banner with the provided `title`, `subtitle`, and optional `image`, ready to be presented with `show()`.
///
/// - parameter title: The title of the banner. Optional. Defaults to nil.
/// - parameter subtitle: The subtitle of the banner. Optional. Defaults to nil.
/// - parameter image: The image on the left of the banner. Optional. Defaults to nil.
/// - parameter backgroundColor: The color of the banner's background view. Defaults to `UIColor.blackColor()`.
/// - parameter didTapBlock: An action to be called when the user taps on the banner. Optional. Defaults to `nil`.
public required init(title: String? = nil, subtitle: String? = nil, image: UIImage? = nil, backgroundColor: UIColor = UIColor.blackColor(), didTapBlock: (() -> ())? = nil) {
self.didTapBlock = didTapBlock
self.image = image
super.init(frame: CGRectZero)
resetShadows()
addGestureRecognizers()
initializeSubviews()
resetTintColor()
titleLabel.text = title
detailLabel.text = subtitle
backgroundView.backgroundColor = backgroundColor
backgroundView.alpha = 0.95
}
private func forceUpdates() {
guard let superview = superview, showingConstraint = showingConstraint, hiddenConstraint = hiddenConstraint else { return }
switch bannerState {
case .Hidden:
superview.removeConstraint(showingConstraint)
superview.addConstraint(hiddenConstraint)
case .Showing:
superview.removeConstraint(hiddenConstraint)
superview.addConstraint(showingConstraint)
case .Gone:
superview.removeConstraint(hiddenConstraint)
superview.removeConstraint(showingConstraint)
superview.removeConstraints(commonConstraints)
}
setNeedsLayout()
setNeedsUpdateConstraints()
layoutIfNeeded()
updateConstraintsIfNeeded()
}
internal func didTap(recognizer: UITapGestureRecognizer) {
if dismissesOnTap {
dismiss()
}
didTapBlock?()
}
internal func didSwipe(recognizer: UISwipeGestureRecognizer) {
if dismissesOnSwipe {
dismiss()
}
}
private func addGestureRecognizers() {
addGestureRecognizer(UITapGestureRecognizer(target: self, action: "didTap:"))
let swipe = UISwipeGestureRecognizer(target: self, action: "didSwipe:")
swipe.direction = .Up
addGestureRecognizer(swipe)
}
private func resetTintColor() {
titleLabel.textColor = textColor
detailLabel.textColor = textColor
imageView.image = shouldTintImage ? image?.imageWithRenderingMode(.AlwaysTemplate) : image
imageView.tintColor = shouldTintImage ? textColor : nil
}
private func resetShadows() {
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOpacity = self.hasShadows ? 0.5 : 0.0
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowRadius = 4
}
private var contentTopOffsetConstraint: NSLayoutConstraint!
private var minimumHeightConstraint: NSLayoutConstraint!
private func initializeSubviews() {
let views = [
"backgroundView": backgroundView,
"contentView": contentView,
"imageView": imageView,
"labelView": labelView,
"titleLabel": titleLabel,
"detailLabel": detailLabel
]
translatesAutoresizingMaskIntoConstraints = false
addSubview(backgroundView)
minimumHeightConstraint = backgroundView.constraintWithAttribute(.Height, .GreaterThanOrEqual, to: 80)
addConstraint(minimumHeightConstraint) // Arbitrary, but looks nice.
addConstraints(backgroundView.constraintsEqualToSuperview())
backgroundView.backgroundColor = backgroundColor
backgroundView.addSubview(contentView)
labelView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(labelView)
labelView.addSubview(titleLabel)
labelView.addSubview(detailLabel)
backgroundView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("H:|[contentView]|", views: views))
backgroundView.addConstraint(contentView.constraintWithAttribute(.Bottom, .Equal, to: .Bottom, of: backgroundView))
contentTopOffsetConstraint = contentView.constraintWithAttribute(.Top, .Equal, to: .Top, of: backgroundView)
backgroundView.addConstraint(contentTopOffsetConstraint)
let leftConstraintText: String
if image == nil {
leftConstraintText = "|"
} else {
contentView.addSubview(imageView)
contentView.addConstraint(imageView.constraintWithAttribute(.Leading, .Equal, to: contentView, constant: 15.0))
contentView.addConstraint(imageView.constraintWithAttribute(.CenterY, .Equal, to: contentView))
imageView.addConstraint(imageView.constraintWithAttribute(.Width, .Equal, to: 25.0))
imageView.addConstraint(imageView.constraintWithAttribute(.Height, .Equal, to: .Width))
leftConstraintText = "[imageView]"
}
let constraintFormat = "H:\(leftConstraintText)-(15)-[labelView]-(8)-|"
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat(constraintFormat, views: views))
contentView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("V:|-(>=1)-[labelView]-(>=1)-|", views: views))
backgroundView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("H:|[contentView]-(<=1)-[labelView]", options: .AlignAllCenterY, views: views))
for view in [titleLabel, detailLabel] {
let constraintFormat = "H:|[label]-(8)-|"
contentView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat(constraintFormat, options: .DirectionLeadingToTrailing, metrics: nil, views: ["label": view]))
}
labelView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("V:|-(10)-[titleLabel][detailLabel]-(10)-|", views: views))
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var showingConstraint: NSLayoutConstraint?
private var hiddenConstraint: NSLayoutConstraint?
private var commonConstraints = [NSLayoutConstraint]()
override public func didMoveToSuperview() {
super.didMoveToSuperview()
guard let superview = superview where bannerState != .Gone else { return }
commonConstraints = self.constraintsWithAttributes([.Leading, .Trailing], .Equal, to: superview)
superview.addConstraints(commonConstraints)
showingConstraint = self.constraintWithAttribute(.Top, .Equal, to: .Top, of: superview)
let yOffset: CGFloat = -7.0 // Offset the bottom constraint to make room for the shadow to animate off screen.
hiddenConstraint = self.constraintWithAttribute(.Bottom, .Equal, to: .Top, of: superview, constant: yOffset)
}
public override func layoutSubviews() {
super.layoutSubviews()
adjustHeightOffset()
}
private func adjustHeightOffset() {
guard let superview = superview else { return }
if superview === Banner.topWindow() {
let statusBarSize = UIApplication.sharedApplication().statusBarFrame.size
let heightOffset = min(statusBarSize.height, statusBarSize.width) // Arbitrary, but looks nice.
contentTopOffsetConstraint.constant = heightOffset
minimumHeightConstraint.constant = statusBarSize.height > 0 ? 80 : 40
} else {
contentTopOffsetConstraint.constant = 0
minimumHeightConstraint.constant = 0
}
}
/// Shows the banner. If a view is specified, the banner will be displayed at the top of that view, otherwise at top of the top window. If a `duration` is specified, the banner dismisses itself automatically after that duration elapses.
/// - parameter view: A view the banner will be shown in. Optional. Defaults to 'nil', which in turn means it will be shown in the top window. duration A time interval, after which the banner will dismiss itself. Optional. Defaults to `nil`.
public func show(view: UIView? = Banner.topWindow(), duration: NSTimeInterval? = nil) {
guard let view = view else {
print("[Banner]: Could not find view. Aborting.")
return
}
view.addSubview(self)
forceUpdates()
let (damping, velocity) = self.springiness.springValues
let oldStatusBarStyle = UIApplication.sharedApplication().statusBarStyle
if adjustsStatusBarStyle {
UIApplication.sharedApplication().setStatusBarStyle(preferredStatusBarStyle, animated: true)
}
UIView.animateWithDuration(animationDuration, delay: 0.0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .AllowUserInteraction, animations: {
self.bannerState = .Showing
}, completion: { finished in
guard let duration = duration else { return }
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(duration * NSTimeInterval(NSEC_PER_SEC))), dispatch_get_main_queue()) {
self.dismiss(self.adjustsStatusBarStyle ? oldStatusBarStyle : nil)
}
})
}
/// Dismisses the banner.
public func dismiss(oldStatusBarStyle: UIStatusBarStyle? = nil) {
let (damping, velocity) = self.springiness.springValues
UIView.animateWithDuration(animationDuration, delay: 0.0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .AllowUserInteraction, animations: {
self.bannerState = .Hidden
if let oldStatusBarStyle = oldStatusBarStyle {
UIApplication.sharedApplication().setStatusBarStyle(oldStatusBarStyle, animated: true)
}
}, completion: { finished in
self.bannerState = .Gone
self.removeFromSuperview()
self.didDismissBlock?()
})
}
}
extension NSLayoutConstraint {
class func defaultConstraintsWithVisualFormat(format: String, options: NSLayoutFormatOptions = .DirectionLeadingToTrailing, metrics: [String: AnyObject]? = nil, views: [String: AnyObject] = [:]) -> [NSLayoutConstraint] {
return NSLayoutConstraint.constraintsWithVisualFormat(format, options: options, metrics: metrics, views: views)
}
}
extension UIView {
func constraintsEqualToSuperview(edgeInsets: UIEdgeInsets = UIEdgeInsetsZero) -> [NSLayoutConstraint] {
self.translatesAutoresizingMaskIntoConstraints = false
var constraints = [NSLayoutConstraint]()
if let superview = self.superview {
constraints.append(self.constraintWithAttribute(.Leading, .Equal, to: superview, constant: edgeInsets.left))
constraints.append(self.constraintWithAttribute(.Trailing, .Equal, to: superview, constant: edgeInsets.right))
constraints.append(self.constraintWithAttribute(.Top, .Equal, to: superview, constant: edgeInsets.top))
constraints.append(self.constraintWithAttribute(.Bottom, .Equal, to: superview, constant: edgeInsets.bottom))
}
return constraints
}
func constraintWithAttribute(attribute: NSLayoutAttribute, _ relation: NSLayoutRelation, to constant: CGFloat, multiplier: CGFloat = 1.0) -> NSLayoutConstraint {
self.translatesAutoresizingMaskIntoConstraints = false
return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relation, toItem: nil, attribute: .NotAnAttribute, multiplier: multiplier, constant: constant)
}
func constraintWithAttribute(attribute: NSLayoutAttribute, _ relation: NSLayoutRelation, to otherAttribute: NSLayoutAttribute, of item: AnyObject? = nil, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0) -> NSLayoutConstraint {
self.translatesAutoresizingMaskIntoConstraints = false
return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relation, toItem: item ?? self, attribute: otherAttribute, multiplier: multiplier, constant: constant)
}
func constraintWithAttribute(attribute: NSLayoutAttribute, _ relation: NSLayoutRelation, to item: AnyObject, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0) -> NSLayoutConstraint {
self.translatesAutoresizingMaskIntoConstraints = false
return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relation, toItem: item, attribute: attribute, multiplier: multiplier, constant: constant)
}
func constraintsWithAttributes(attributes: [NSLayoutAttribute], _ relation: NSLayoutRelation, to item: AnyObject, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0) -> [NSLayoutConstraint] {
return attributes.map { self.constraintWithAttribute($0, relation, to: item, multiplier: multiplier, constant: constant) }
}
}
|
mit
|
bd0b00eaecbfd067648be93bdfed37bd
| 46.515873 | 245 | 0.681737 | 5.434191 | false | false | false | false |
nguyenantinhbk77/practice-swift
|
Networking/Downloading asynchronously with NSURLConnection/Downloading asynchronously with NSURLConnection/ViewController.swift
|
2
|
1901
|
//
// ViewController.swift
// Downloading asynchronously with NSURLConnection
//
// Created by Domenico Solazzo on 16/05/15.
// License MIT
//
import UIKit
extension NSURL{
/* An extension on the NSURL class that allows us to retrieve the current
documents folder path */
class func documentsFolder() -> NSURL{
let fileManager = NSFileManager()
return fileManager.URLForDirectory(.DocumentDirectory,
inDomain: .UserDomainMask,
appropriateForURL: nil,
create: false,
error: nil)!
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://www.domenicosolazzo/swiftcode")
let request = NSURLRequest(URL: url!)
let operationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: operationQueue) {[weak self]
(response:NSURLResponse!, data:NSData!, error:NSError!) in
/* Now we may have access to the data, but check if an error came back
first or not */
if data.length > 0 && error == nil{
/* Append the filename to the documents directory */
let filePath =
NSURL.documentsFolder().URLByAppendingPathComponent("apple.html")
if data.writeToURL(filePath, atomically: true){
println("Successfully saved the file to \(filePath)")
} else {
println("Failed to save the file to \(filePath)")
}
} else if data.length == 0 && error == nil{
println("Nothing was downloaded")
} else if error != nil{
println("Error happened = \(error)")
}
}
}
}
|
mit
|
aa8f8ba4f3f96f411489d3562a41c11d
| 32.350877 | 92 | 0.56444 | 5.462644 | false | false | false | false |
mercadopago/px-ios
|
MercadoPagoSDK/MercadoPagoSDK/UI/PaymentMethod/PXPaymentMethodComponentRenderer.swift
|
1
|
6905
|
import UIKit
class PXPaymentMethodComponentRenderer: NSObject {
// Image
let IMAGE_WIDTH: CGFloat = 48.0
let IMAGE_HEIGHT: CGFloat = 48.0
// Action Button
let BUTTON_HEIGHT: CGFloat = 34.0
let TITLE_FONT_SIZE: CGFloat = PXLayout.M_FONT
let SUBTITLE_FONT_SIZE: CGFloat = PXLayout.XS_FONT
let DESCRIPTION_DETAIL_FONT_SIZE: CGFloat = PXLayout.XXS_FONT
let DISCLAIMER_FONT_SIZE: CGFloat = PXLayout.XXXS_FONT
func render(component: PXPaymentMethodComponent) -> PXPaymentMethodView {
let pmBodyView = PXPaymentMethodView()
pmBodyView.backgroundColor = component.props.backgroundColor
pmBodyView.translatesAutoresizingMaskIntoConstraints = false
let paymentMethodIcon = component.getPaymentMethodIconComponent()
pmBodyView.paymentMethodIcon = paymentMethodIcon.render()
pmBodyView.paymentMethodIcon!.layer.cornerRadius = IMAGE_WIDTH / 2
pmBodyView.paymentMethodIcon!.layer.borderWidth = 2
pmBodyView.paymentMethodIcon!.layer.borderColor = ThemeManager.shared.lightTintColor().cgColor
pmBodyView.addSubview(pmBodyView.paymentMethodIcon!)
PXLayout.centerHorizontally(view: pmBodyView.paymentMethodIcon!).isActive = true
PXLayout.setHeight(owner: pmBodyView.paymentMethodIcon!, height: IMAGE_HEIGHT).isActive = true
PXLayout.setWidth(owner: pmBodyView.paymentMethodIcon!, width: IMAGE_WIDTH).isActive = true
PXLayout.pinTop(view: pmBodyView.paymentMethodIcon!, withMargin: PXLayout.L_MARGIN).isActive = true
// Title
let title = UILabel()
title.translatesAutoresizingMaskIntoConstraints = false
pmBodyView.titleLabel = title
pmBodyView.addSubview(title)
title.font = Utils.getFont(size: TITLE_FONT_SIZE)
title.attributedText = component.props.title
title.textColor = component.props.boldLabelColor
title.textAlignment = .center
title.numberOfLines = 0
pmBodyView.putOnBottomOfLastView(view: title, withMargin: PXLayout.S_MARGIN)?.isActive = true
PXLayout.pinLeft(view: title, withMargin: PXLayout.S_MARGIN).isActive = true
PXLayout.pinRight(view: title, withMargin: PXLayout.S_MARGIN).isActive = true
if let detailText = component.props.subtitle {
let detailLabel = UILabel()
detailLabel.numberOfLines = 2
detailLabel.translatesAutoresizingMaskIntoConstraints = false
pmBodyView.addSubview(detailLabel)
pmBodyView.subtitleLabel = detailLabel
detailLabel.font = Utils.getFont(size: SUBTITLE_FONT_SIZE)
detailLabel.attributedText = detailText
detailLabel.textColor = component.props.lightLabelColor
detailLabel.textAlignment = .center
pmBodyView.putOnBottomOfLastView(view: detailLabel, withMargin: PXLayout.XXS_MARGIN)?.isActive = true
PXLayout.pinLeft(view: detailLabel, withMargin: PXLayout.XXS_MARGIN).isActive = true
PXLayout.pinRight(view: detailLabel, withMargin: PXLayout.XXS_MARGIN).isActive = true
}
if let paymentMethodDescription = component.props.descriptionTitle {
let descriptionLabel = UILabel()
descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
pmBodyView.addSubview(descriptionLabel)
pmBodyView.descriptionTitleLabel = descriptionLabel
descriptionLabel.font = Utils.getFont(size: DESCRIPTION_DETAIL_FONT_SIZE)
descriptionLabel.attributedText = paymentMethodDescription
descriptionLabel.numberOfLines = 2
descriptionLabel.textColor = component.props.lightLabelColor
descriptionLabel.textAlignment = .center
pmBodyView.putOnBottomOfLastView(view: descriptionLabel, withMargin: PXLayout.XS_MARGIN)?.isActive = true
PXLayout.pinLeft(view: descriptionLabel, withMargin: PXLayout.XS_MARGIN).isActive = true
PXLayout.pinRight(view: descriptionLabel, withMargin: PXLayout.XS_MARGIN).isActive = true
}
if let pmDetailText = component.props.descriptionDetail {
let pmDetailLabel = UILabel()
pmDetailLabel.translatesAutoresizingMaskIntoConstraints = false
pmBodyView.descriptionDetailLabel = pmDetailLabel
pmBodyView.addSubview(pmDetailLabel)
pmDetailLabel.font = Utils.getFont(size: DESCRIPTION_DETAIL_FONT_SIZE)
pmDetailLabel.attributedText = pmDetailText
pmDetailLabel.textColor = component.props.lightLabelColor
pmDetailLabel.textAlignment = .center
pmBodyView.putOnBottomOfLastView(view: pmDetailLabel, withMargin: PXLayout.XXS_MARGIN)?.isActive = true
PXLayout.pinLeft(view: pmDetailLabel, withMargin: PXLayout.XXS_MARGIN).isActive = true
PXLayout.pinRight(view: pmDetailLabel, withMargin: PXLayout.XXS_MARGIN).isActive = true
}
if let disclaimer = component.props.disclaimer {
let disclaimerLabel = UILabel()
disclaimerLabel.translatesAutoresizingMaskIntoConstraints = false
pmBodyView.disclaimerLabel = disclaimerLabel
pmBodyView.addSubview(disclaimerLabel)
disclaimerLabel.numberOfLines = 2
disclaimerLabel.font = Utils.getFont(size: DISCLAIMER_FONT_SIZE)
disclaimerLabel.attributedText = disclaimer
disclaimerLabel.textColor = component.props.lightLabelColor
disclaimerLabel.textAlignment = .center
pmBodyView.putOnBottomOfLastView(view: disclaimerLabel, withMargin: PXLayout.M_MARGIN)?.isActive = true
PXLayout.pinLeft(view: disclaimerLabel, withMargin: PXLayout.XS_MARGIN).isActive = true
PXLayout.pinRight(view: disclaimerLabel, withMargin: PXLayout.XS_MARGIN).isActive = true
}
if let action = component.props.action {
let actionButton = PXSecondaryButton()
actionButton.translatesAutoresizingMaskIntoConstraints = false
actionButton.buttonTitle = action.label
actionButton.accessibilityIdentifier = "change_payment_method_button"
actionButton.add(for: .touchUpInside, action.action)
pmBodyView.actionButton = actionButton
pmBodyView.addSubview(actionButton)
pmBodyView.putOnBottomOfLastView(view: actionButton, withMargin: PXLayout.S_MARGIN)?.isActive = true
PXLayout.pinLeft(view: actionButton, withMargin: PXLayout.XXS_MARGIN).isActive = true
PXLayout.pinRight(view: actionButton, withMargin: PXLayout.XXS_MARGIN).isActive = true
// PXLayout.setHeight(owner: actionButton, height: BUTTON_HEIGHT).isActive = true
}
pmBodyView.pinLastSubviewToBottom(withMargin: PXLayout.L_MARGIN)?.isActive = true
return pmBodyView
}
}
|
mit
|
bbde9b4a126300ec9dd4c79322ccdf3d
| 54.685484 | 117 | 0.707748 | 5.152985 | false | false | false | false |
AnderGoig/SwiftInstagram
|
Sources/Endpoints/Users.swift
|
1
|
3629
|
//
// Users.swift
// SwiftInstagram
//
// Created by Ander Goig on 29/10/17.
// Copyright © 2017 Ander Goig. All rights reserved.
//
extension Instagram {
// MARK: User Endpoints
/// Get information about a user.
///
/// - parameter userId: The ID of the user whose information to retrieve, or "self" to reference the currently authenticated user.
/// - parameter success: The callback called after a correct retrieval.
/// - parameter failure: The callback called after an incorrect retrieval.
///
/// - important: It requires *public_content* scope when getting information about a user other than yours.
public func user(_ userId: String, success: SuccessHandler<InstagramUser>?, failure: FailureHandler?) {
request("/users/\(userId)", success: success, failure: failure)
}
/// Get the most recent media published by a user.
///
/// - parameter userId: The ID of the user whose recent media to retrieve, or "self" to reference the currently authenticated user.
/// - parameter maxId: Return media earlier than this `maxId`.
/// - parameter minId: Return media later than this `minId`.
/// - parameter count: Count of media to return.
/// - parameter success: The callback called after a correct retrieval.
/// - parameter failure: The callback called after an incorrect retrieval.
///
/// - important: It requires *public_content* scope when getting recent media published by a user other than yours.
public func recentMedia(fromUser userId: String,
maxId: String? = nil,
minId: String? = nil,
count: Int? = nil,
success: SuccessHandler<[InstagramMedia]>?,
failure: FailureHandler?) {
var parameters = Parameters()
parameters["max_id"] ??= maxId
parameters["min_id"] ??= minId
parameters["count"] ??= count
request("/users/\(userId)/media/recent", parameters: parameters, success: success, failure: failure)
}
/// Get the list of recent media liked by the currently authenticated user.
///
/// - parameter maxLikeId: Return media liked before this id.
/// - parameter count: Count of media to return.
/// - parameter success: The callback called after a correct retrieval.
/// - parameter failure: The callback called after an incorrect retrieval.
///
/// - important: It requires *public_content* scope.
public func userLikedMedia(maxLikeId: String? = nil, count: Int? = nil, success: SuccessHandler<[InstagramMedia]>?, failure: FailureHandler?) {
var parameters = Parameters()
parameters["max_like_id"] ??= maxLikeId
parameters["count"] ??= count
request("/users/self/media/liked", parameters: parameters, success: success, failure: failure)
}
/// Get a list of users matching the query.
///
/// - parameter query: A query string.
/// - parameter count: Number of users to return.
/// - parameter success: The callback called after a correct retrieval.
/// - parameter failure: The callback called after an incorrect retrieval.
///
/// - important: It requires *public_content* scope.
public func search(user query: String, count: Int? = nil, success: SuccessHandler<[InstagramUser]>?, failure: FailureHandler?) {
var parameters = Parameters()
parameters["q"] = query
parameters["count"] ??= count
request("/users/search", parameters: parameters, success: success, failure: failure)
}
}
|
mit
|
10641b1f94414e1551c192669dc36270
| 43.243902 | 147 | 0.644157 | 4.78628 | false | false | false | false |
Conaaando/swift-hacker-rank
|
00.Warmup/04-plus-minus.swift
|
1
|
2029
|
#!/usr/bin/swift
/*
https://github.com/singledev/swift-hacker-rank
04-plus-minus.swift
https://www.hackerrank.com/challenges/plus-minus
Created by Fernando Fernandes on 2/25/16.
Copyright © 2016 SINGLEDEV. All rights reserved.
http://stackoverflow.com/users/584548/singledev
Instructions:
$ chmod a+x 04-plus-minus.swift
$ ./04-plus-minus.swift
*/
import Foundation
var inputIntegers: [Int] = [0]
var positives: Double = 0
var negatives: Double = 0
var zeros: Double = 0
extension Double {
func decimalPlaces(decimalPlaces: Int) -> String {
// Unfortunately, Swift removes trailling zeros when using the good ol' "%.6f"...
//let formattedNumberString = String.localizedStringWithFormat("%.\(decimalPlaces)f", self)
//return Double(formattedNumberString)!
// ... so let's use NSNumberFormatter instead.
let formatter = NSNumberFormatter()
formatter.maximumFractionDigits = decimalPlaces
formatter.minimumSignificantDigits = decimalPlaces
formatter.maximumSignificantDigits = decimalPlaces
return formatter.stringFromNumber(self) ?? "\(self)"
}
}
func calculateFractionOfElements() {
for number in inputIntegers {
if number == 0 {
zeros++
} else if number > 0 {
positives++
} else {
negatives++
}
}
}
print("Type a number, then press ENTER")
var n = Int(readLine()!)!
print("Type \(n) space-separated integers, then press ENTER")
var inputString: [String] = readLine()!.characters.split(" ").map(String.init)
inputIntegers = inputString.map{ Int($0) ?? 0 }
calculateFractionOfElements()
// Conversions between integer and floating-point numeric types must be made explicit.
print("Positives: \(Double(positives / Double(inputIntegers.count)).decimalPlaces(6))")
print("Negatives: \(Double(negatives / Double(inputIntegers.count)).decimalPlaces(6))")
print("Zeros: \(Double(zeros / Double(inputIntegers.count)).decimalPlaces(6))")
|
mit
|
7913529383d1f834fbb84036c011c515
| 29.268657 | 99 | 0.683432 | 4.155738 | false | false | false | false |
CosmicMind/Samples
|
Projects/Programmatic/Photos/Photos/PhotoViewController.swift
|
1
|
5136
|
/*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* 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 CosmicMind 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 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 UIKit
import Material
import Motion
class PhotoViewController: UIViewController {
fileprivate var closeButton: IconButton!
fileprivate var collectionView: UICollectionView!
fileprivate var index: Int
var dataSourceItems = [DataSourceItem]()
public required init?(coder aDecoder: NSCoder) {
index = 0
super.init(coder: aDecoder)
}
public init(index: Int) {
self.index = index
super.init(nibName: nil, bundle: nil)
}
open override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
prepareCloseButton()
preparePhotos()
prepareCollectionView()
prepareToolbar()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
}
extension PhotoViewController {
func prepareCloseButton() {
closeButton = IconButton(image: Icon.cm.close)
closeButton.addTarget(self, action: #selector(handleCloseButton(button:)) , for: .touchUpInside)
}
fileprivate func preparePhotos() {
PhotosDataSource.forEach { [weak self, w = view.bounds.width] in
guard let image = UIImage(named: $0) else {
return
}
self?.dataSourceItems.append(DataSourceItem(data: image, width: w))
}
}
fileprivate func prepareCollectionView() {
let w = view.bounds.width
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
layout.itemSize = CGSize(width: w, height: w)
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.backgroundColor = .clear
collectionView.dataSource = self
collectionView.delegate = self
collectionView.isPagingEnabled = true
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.register(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: "PhotoCollectionViewCell")
view.layout(collectionView).center(offsetY: -44).width(w).height(w)
collectionView.scrollRectToVisible(CGRect(x: w * CGFloat(index), y: 0, width: w, height: w), animated: false)
}
func prepareToolbar() {
guard let toolbar = toolbarController?.toolbar else {
return
}
toolbar.titleLabel.text = "Photo Name"
toolbar.detailLabel.text = "July 19 2017"
toolbar.leftViews = [closeButton]
}
}
extension PhotoViewController: CollectionViewDataSource {
@objc
open func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
@objc
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSourceItems.count
}
@objc
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCollectionViewCell", for: indexPath) as! PhotoCollectionViewCell
guard let image = dataSourceItems[indexPath.item].data as? UIImage else {
return cell
}
cell.imageView.image = image
cell.imageView.motionIdentifier = "photo_\(indexPath.item)"
return cell
}
}
extension PhotoViewController: CollectionViewDelegate {}
fileprivate extension PhotoViewController {
@objc
func handleCloseButton(button: UIButton) {
toolbarController?.transition(to: PhotoCollectionViewController())
}
}
|
bsd-3-clause
|
f53af4c587e5aeb24ec4591f64685e6a
| 33.24 | 141 | 0.73715 | 4.914833 | false | false | false | false |
epv44/EVTopTabBar
|
Pod/Classes/EVPageViewTopTabBar.swift
|
1
|
15204
|
//
// EVPageViewTopTabBar.swift
// Pods
//
// Created by Eric Vennaro on 2/29/16.
//
//
import UIKit
public enum IndicatorLayoutStyle {
case setWidth(CGFloat), textWidth, buttonWidth
}
///UIView that represents the tab EVPageViewTopTabBar
open class EVPageViewTopTabBar: UIView {
private var tabs: NumberOfTabs
private let indicatorStyle: IndicatorLayoutStyle
fileprivate var indicatorXPosition = NSLayoutConstraint()
fileprivate var indicatorWidth = NSLayoutConstraint()
fileprivate var buttonFontColors: (selectedColor: UIColor, unselectedColor: UIColor)?
///Delegate for the tab bar
open weak var delegate: EVTabBarDelegate?
internal var currentState: Int
fileprivate var indicatorView: UIView? {
didSet {
indicatorView?.translatesAutoresizingMaskIntoConstraints = false
indicatorView?.layer.cornerRadius = 4
addSubview(indicatorView!)
}
}
private var rightButton: UIButton? {
didSet {
rightButton?.translatesAutoresizingMaskIntoConstraints = false
rightButton?.addTarget(self, action: .buttonTapped, for: .touchUpInside)
addSubview(rightButton!)
}
}
private var leftButton: UIButton? {
didSet {
leftButton?.translatesAutoresizingMaskIntoConstraints = false
leftButton?.addTarget(self, action: .buttonTapped, for: .touchUpInside)
addSubview(leftButton!)
}
}
private var middleButton: UIButton? {
didSet {
middleButton?.translatesAutoresizingMaskIntoConstraints = false
middleButton?.addTarget(self, action: .buttonTapped, for: .touchUpInside)
addSubview(middleButton!)
}
}
private var middleRightButton: UIButton? {
didSet {
middleRightButton?.translatesAutoresizingMaskIntoConstraints = false
middleRightButton?.addTarget(self, action: .buttonTapped, for: .touchUpInside)
addSubview(middleRightButton!)
}
}
///Stored property to set the selected and unselected font color
open var fontColors: (selectedColor: UIColor, unselectedColor: UIColor)? {
didSet {
buttonFontColors = fontColors
rightButton?.setTitleColor(fontColors!.unselectedColor, for: UIControl.State())
middleButton?.setTitleColor(fontColors!.unselectedColor, for: UIControl.State())
leftButton?.setTitleColor(fontColors!.selectedColor, for: UIControl.State())
middleRightButton?.setTitleColor(fontColors!.unselectedColor, for: UIControl.State())
}
}
///Stored property sets the text for the right UIButton
open var rightButtonText: String? {
didSet {
rightButton?.setTitle(rightButtonText, for: UIControl.State())
setNeedsLayout()
}
}
///Stored property sets the text for the left UIButton
open var leftButtonText: String? {
didSet {
leftButton?.setTitle(leftButtonText, for: UIControl.State())
setNeedsLayout()
}
}
///Stored property sets the text for the middle UIButton
open var middleButtonText: String? {
didSet {
middleButton?.setTitle(middleButtonText, for: UIControl.State())
setNeedsLayout()
}
}
open var middleRightButtonText: String? {
didSet {
middleRightButton?.setTitle(middleRightButtonText, for: UIControl.State())
setNeedsLayout()
}
}
///Stored property sets the font for both UIButton labels
open var labelFont: UIFont? {
didSet {
rightButton?.titleLabel?.font = labelFont
leftButton?.titleLabel?.font = labelFont
middleButton?.titleLabel?.font = labelFont
middleRightButton?.titleLabel?.font = labelFont
setNeedsLayout()
}
}
///Stored property sets the background color of the indicator view
open var indicatorViewColor: UIColor? {
didSet {
indicatorView?.backgroundColor = indicatorViewColor
setNeedsLayout()
}
}
//MARK: - Initialization
///init with frame
public init(for tabs: NumberOfTabs, withIndicatorStyle indicatorStyle: IndicatorLayoutStyle) {
self.tabs = tabs
self.indicatorStyle = indicatorStyle
currentState = 111
super.init(frame: CGRect.zero)
setupUI()
}
///init with coder
required public init?(coder aDecoder: NSCoder) {
tabs = .two
indicatorStyle = .textWidth
currentState = 111
super.init(coder: aDecoder)
setupUI()
}
//MARK: - Methods
//Sets UI attributes for the tab bar
private func setupUI() {
indicatorView = UIView()
switch tabs {
case .two:
rightButton = UIButton()
leftButton = UIButton()
leftButton?.tag = 111
rightButton?.tag = 222
case .three:
rightButton = UIButton()
leftButton = UIButton()
middleButton = UIButton()
leftButton?.tag = 111
middleButton?.tag = 222
rightButton?.tag = 333
case .four:
rightButton = UIButton()
leftButton = UIButton()
middleButton = UIButton()
middleRightButton = UIButton()
leftButton?.tag = 111
middleButton?.tag = 222
middleRightButton?.tag = 333
rightButton?.tag = 444
}
setupGestureRecognizers()
setConstraints()
}
@objc func buttonWasTouched(_ sender: UIButton!) {
animate(to: sender.tag)
}
@objc func respondToRightSwipe(_ gesture: UIGestureRecognizer) {
if currentState.modTen < rightButton!.tag.modTen {
animate(to: (currentState.modTen + 1).toTag)
}
}
@objc func respondToLeftSwipe(_ gesture: UIGestureRecognizer) {
if currentState.modTen > leftButton!.tag.modTen {
animate(to: (currentState.modTen - 1).toTag)
}
}
public func getIndicatorViewConstraint(for button: UIButton) -> NSLayoutConstraint {
guard let indicatorView = indicatorView else {
fatalError("Must set indicator view");
}
switch indicatorStyle {
case .setWidth(let width):
return NSLayoutConstraint(
item: indicatorView,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: width
)
case .buttonWidth:
return NSLayoutConstraint(
item: indicatorView,
attribute: .width,
relatedBy: .equal,
toItem: button,
attribute: .width,
multiplier: 1,
constant: 0
)
case .textWidth:
return NSLayoutConstraint(
item: indicatorView,
attribute: .width,
relatedBy: .equal,
toItem: button.titleLabel,
attribute: .width,
multiplier: 1,
constant: 0
)
}
}
private func setupGestureRecognizers() {
let rightSwipe = UISwipeGestureRecognizer(target: self, action: .respondToRightSwipe)
let leftSwipe = UISwipeGestureRecognizer(target: self, action: .respondToLeftSwipe)
rightSwipe.direction = .right
leftSwipe.direction = .left
addGestureRecognizer(rightSwipe)
addGestureRecognizer(leftSwipe)
}
//MARK: - Constraints
private func setConstraints() {
guard let leftButton = leftButton,
let rightButton = rightButton,
let indicatorView = indicatorView else {
NSLog("Error: must set views in order to establish constraints")
return
}
var views: [String: AnyObject] = [:]
switch tabs {
case .two:
views = [
"leftButton" : leftButton,
"indicatorView" : indicatorView,
"rightButton" : rightButton
]
addConstraint(
NSLayoutConstraint(
item: leftButton,
attribute: .centerX,
relatedBy: .equal,
toItem: self,
attribute: .centerX,
multiplier: 1,
constant: -70
)
)
addConstraint(
NSLayoutConstraint(
item: rightButton,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .width,
multiplier: 1,
constant: 100
)
)
addConstraint(
NSLayoutConstraint(
item: rightButton,
attribute: .leading,
relatedBy: .equal,
toItem: leftButton,
attribute: .trailing,
multiplier: 1,
constant: 30
)
)
addConstraint(
NSLayoutConstraint(
item: leftButton,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .width,
multiplier: 1,
constant: 100
)
)
case .three:
views = [
"leftButton" : leftButton,
"indicatorView" : indicatorView,
"rightButton" : rightButton,
"middleButton" : middleButton!
]
addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "|-40-[leftButton]-[middleButton(==leftButton)]-[rightButton(==leftButton)]-40-|",
options: [],
metrics: nil,
views: views
)
)
addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-9-[middleButton]-12-|",
options: [],
metrics: nil,
views: views
)
)
case .four:
views = [
"leftButton" : leftButton,
"indicatorView" : indicatorView,
"rightButton" : rightButton,
"middleButton" : middleButton!,
"middleRightButton" : middleRightButton!
]
addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "|-[leftButton]-[middleButton(==leftButton)]-[middleRightButton(==leftButton)]-[rightButton(==leftButton)]-|",
options: [],
metrics: nil,
views: views
)
)
addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-9-[middleButton]-12-|",
options: [],
metrics: nil,
views: views
)
)
addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-9-[middleRightButton]-12-|",
options: [],
metrics: nil,
views: views
)
)
}
addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-9-[leftButton][indicatorView(==3)]-9-|",
options: [],
metrics: nil,
views: views
)
)
indicatorXPosition = NSLayoutConstraint(
item: indicatorView,
attribute: .centerX,
relatedBy: .equal,
toItem: leftButton,
attribute: .centerX,
multiplier: 1,
constant: 0
)
addConstraint(indicatorXPosition)
indicatorWidth = getIndicatorViewConstraint(for: leftButton)
addConstraint(indicatorWidth)
addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-9-[rightButton]-12-|",
options: [],
metrics: nil,
views: views
)
)
}
}
extension EVPageViewTopTabBar: AnimateTransition {
internal func animate(to newState: Int) {
let direction: UIPageViewController.NavigationDirection = newState.modTen - currentState.modTen > 0 ? .forward : .reverse
guard let fromButton = viewWithTag(currentState) as? UIButton,
let toButton = viewWithTag(newState) as? UIButton,
let indicatorView = indicatorView else {
NSLog("Error, do not use tags 111, 222, 333, 444 these are used to identify buttons in EVTopTabBar")
return
}
let constraint = NSLayoutConstraint(
item: indicatorView,
attribute: .centerX,
relatedBy: .equal,
toItem: toButton,
attribute: .centerX,
multiplier: 1,
constant: 0
)
let widthConstraint = getIndicatorViewConstraint(for: toButton)
if let topBarDelegate = delegate {
topBarDelegate.willSelectViewControllerAtIndex(newState.modTen - 1, direction: direction)
UIView.animate(withDuration: 0.5, delay: 0, options: UIView.AnimationOptions(), animations: {
self.removeConstraint(self.indicatorXPosition)
self.removeConstraint(self.indicatorWidth)
self.indicatorXPosition = constraint
self.indicatorWidth = widthConstraint
self.addConstraints(
[self.indicatorXPosition, self.indicatorWidth]
)
self.layoutIfNeeded()
}, completion: { finished in
fromButton.setTitleColor(self.buttonFontColors?.unselectedColor, for: UIControl.State())
toButton.setTitleColor(self.buttonFontColors?.selectedColor, for: UIControl.State())
}
)
}
currentState = newState
}
}
//MARK: - Selector
private extension Selector {
static let buttonTapped = #selector(EVPageViewTopTabBar.buttonWasTouched(_:))
static let respondToRightSwipe = #selector(EVPageViewTopTabBar.respondToRightSwipe(_:))
static let respondToLeftSwipe = #selector(EVPageViewTopTabBar.respondToLeftSwipe(_:))
}
private extension Int {
var modTen: Int {
return self % 10
}
var toTag: Int {
return (self + (self * 10) + (self * 100))
}
}
|
mit
|
6b6bba76de54cd7bb25886afcf3d97b9
| 33.712329 | 148 | 0.544594 | 5.95768 | false | false | false | false |
gribozavr/swift
|
test/NameBinding/Dependencies/private-function-return-type-fine.swift
|
1
|
1143
|
// REQUIRES: shell
// Also uses awk:
// XFAIL OS=windows
// RUN: %target-swift-frontend -enable-fine-grained-dependencies -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DOLD -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-OLD
// RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh <%t.swiftdeps >%t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t-processed.swiftdeps
// RUN: %target-swift-frontend -enable-fine-grained-dependencies -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DNEW -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-NEW
// RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh <%t.swiftdeps >%t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t-processed.swiftdeps
private func testReturnType() -> InterestingType { fatalError() }
// CHECK-OLD: sil_global @$s4main1x{{[^ ]+}} : $Int
// CHECK-NEW: sil_global @$s4main1x{{[^ ]+}} : $Double
public var x = testReturnType() + 0
// CHECK-DEPS: topLevel interface '' InterestingType false
|
apache-2.0
|
8e57e8b904b85feece1b0c71f80cb7a9
| 59.157895 | 237 | 0.726159 | 3.361765 | false | true | false | false |
juliaguo/shakeWake
|
shakeWake/AlarmClock/Simple Alarm Clock/ViewController.swift
|
1
|
3763
|
//
// ViewController.swift
// Simple Alarm Clock
//
// Created by Daniel Lerner on 5/3/17.
// Copyright © 2017 Daniel Lerner. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var cancelAlarmButton: UIButton!
@IBOutlet weak var setAlarmButton: UIButton!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var turnOffAlarmButton: UIButton!
var theTimer: NSTimer!
var dateString: NSString!
var strDate: String?
var selectedAlarmTime: String?
var player: AVAudioPlayer?
var userAsleep: Bool = true
override func viewDidLoad() {
super.viewDidLoad()
// Initialize strDate value in case user sets alarm on current date selected
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
strDate = dateFormatter.stringFromDate(datePicker.date)
turnOffAlarmButton.enabled = false
setTime()
}
@IBAction func datePickerAction(sender: AnyObject) {
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
strDate = dateFormatter.stringFromDate(datePicker.date)
}
@IBAction func setAlarmAction(sender: AnyObject) {
selectedAlarmTime = strDate
userAsleep = true
}
func playSound() {
let url = NSBundle.mainBundle().URLForResource("alarm_sound", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOfURL: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}
}
func checkTime(alarmTime: String, currentTime: NSDate) -> Bool {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
var alarmAsDate: NSDate!
if (alarmTime != ""){
alarmAsDate = dateFormatter.dateFromString(alarmTime)
if (alarmAsDate.timeIntervalSinceDate(currentTime) < 1){
return true
}
}
return false
}
func soundAlarm(){
playSound()
// figure out how to check if button pressed or allow that to happen, maybe just simulator?
}
@IBAction func turnOffAlarm(sender: AnyObject) {
userAsleep = false
selectedAlarmTime = ""
setAlarmButton.enabled = true
cancelAlarmButton.enabled = true
turnOffAlarmButton.enabled = false
}
@IBAction func cancelAlarmAction(sender: AnyObject) {
selectedAlarmTime = ""
userAsleep = false
}
func setTime() {
theTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "setTime", userInfo: nil, repeats: false)
let date: NSDate = NSDate()
let dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "hh:mm:ss: a"
dateString = dateFormatter.stringFromDate(date)
timeLabel.text = dateString as String
if (selectedAlarmTime != nil){
var timeToWake: Bool = checkTime(selectedAlarmTime!, currentTime: date)
if(timeToWake){
soundAlarm()
turnOffAlarmButton.enabled = true
cancelAlarmButton.enabled = false
setAlarmButton.enabled = false
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
4a4f948e9bd1c17c3a113c4433cc9711
| 29.33871 | 126 | 0.619086 | 5.042895 | false | false | false | false |
romankisil/eqMac2
|
native/app/Source/UI/UIState.swift
|
1
|
2875
|
//
// ViewsState.swift
// eqMac
//
// Created by Roman Kisil on 07/07/2018.
// Copyright © 2018 Roman Kisil. All rights reserved.
//
import Foundation
import SwiftyUserDefaults
import ReSwift
import SwiftyJSON
import BetterCodable
fileprivate struct ScaleDefault: DefaultCodableStrategy {
static var defaultValue: Double = 1
}
fileprivate struct MinWidthDefault: DefaultCodableStrategy {
static var defaultValue: Double = 400
}
fileprivate struct MinHeightDefault: DefaultCodableStrategy {
static var defaultValue: Double = 400
}
fileprivate struct StatusItemIconTypeDefault: DefaultCodableStrategy {
static var defaultValue: StatusItemIconType = .classic
}
struct UIState: State {
var height: Double = 400
var width: Double = 400
var windowPosition: NSPoint? = nil
@DefaultFalse var alwaysOnTop = false
var settings: JSON = JSON()
var mode: UIMode = .window
@DefaultCodable<StatusItemIconTypeDefault> var statusItemIconType = StatusItemIconTypeDefault.value
@DefaultCodable<ScaleDefault> var scale = ScaleDefault.value
@DefaultCodable<MinHeightDefault> var minHeight = MinHeightDefault.value
@DefaultCodable<MinWidthDefault> var minWidth = MinWidthDefault.value
var maxHeight: Double?
var maxWidth: Double?
@DefaultFalse var fromUI = false
@DefaultFalse var resizable = false
}
enum UIAction: Action {
case setHeight(Double, Bool? = nil)
case setWidth(Double, Bool? = nil)
case setWindowPosition(NSPoint)
case setAlwaysOnTop(Bool)
case setSettings(JSON)
case setMode(UIMode)
case setStatusItemIconType(StatusItemIconType)
case setScale(Double)
case setMinHeight(Double)
case setMinWidth(Double)
case setMaxHeight(Double?)
case setMaxWidth(Double?)
case setResizable(Bool)
}
func UIStateReducer(action: Action, state: UIState?) -> UIState {
var state = state ?? UIState()
switch action as? UIAction {
case .setHeight(let height, let fromUI)?:
state.height = height
state.fromUI = fromUI == true
case .setWidth(let width, let fromUI)?:
state.width = width
state.fromUI = fromUI == true
case .setWindowPosition(let point)?:
state.windowPosition = point
case .setAlwaysOnTop(let alwaysOnTop)?:
state.alwaysOnTop = alwaysOnTop
case .setSettings(let settings)?:
state.settings = settings
case .setMode(let mode)?:
state.mode = mode
case .setStatusItemIconType(let type)?:
state.statusItemIconType = type
case .setScale(let scale)?:
state.scale = scale
case .setMinHeight(let minHeight)?:
state.minHeight = minHeight
case .setMinWidth(let minWidth)?:
state.minWidth = minWidth
case .setMaxHeight(let maxHeight)?:
state.maxHeight = maxHeight
case .setMaxWidth(let maxWidth)?:
state.maxWidth = maxWidth
case .setResizable(let resizable)?:
state.resizable = resizable
case .none:
break
}
return state
}
|
mit
|
16c78193de4dbe375962b7e45148a2a5
| 27.455446 | 101 | 0.744607 | 4.15919 | false | false | false | false |
Zig1375/SwiftClickHouse
|
Sources/SwiftClickHouse/Core/enums/ServerCodes.swift
|
1
|
953
|
import Foundation
enum ServerCodes : UInt64 {
case Hello = 0; /// Имя, версия, ревизия.
case Data = 1; /// Блок данных со сжатием или без.
case Exception = 2; /// Исключение во время обработки запроса.
case Progress = 3; /// Прогресс выполнения запроса: строк считано, байт считано.
case Pong = 4; /// Ответ на Ping.
case EndOfStream = 5; /// Все пакеты были переданы.
case ProfileInfo = 6; /// Пакет с профайлинговой информацией.
case Totals = 7; /// Блок данных с тотальными значениями, со сжатием или без.
case Extremes = 8; /// Блок данных с минимумами и максимумами, аналогично.
}
|
mit
|
65170d6930230f53376ed95dacc5e34f
| 51.538462 | 90 | 0.617862 | 2.616858 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
Rocket.Chat.ShareExtension/State/ActionCreators/SubmitContent.swift
|
1
|
4660
|
//
// SubmitContent.swift
// Rocket.Chat.ShareExtension
//
// Created by Matheus Cardoso on 3/13/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import Foundation
fileprivate extension SEStore {
enum Request {
case file(UploadMessageRequest)
case text(SendMessageRequest)
}
var contentRequests: [(Int, Request)] {
return store.state.content.map { content -> Request in
switch content.type {
case .file(let file):
return .file(UploadMessageRequest(
roomId: store.state.currentRoom.rid,
data: file.data,
filename: file.name,
mimetype: file.mimetype,
description: file.description
))
case .text(let text):
return .text(SendMessageRequest(
id: "ios_se_\(String.random(10))",
roomId: store.state.currentRoom.rid,
text: text
))
}
}.enumerated().map { ($0, $1) }
}
}
var urlTasks: [URLSessionTask?] = []
func submitFiles(store: SEStore, completion: @escaping (() -> Void)) {
var fileRequests = store.contentRequests.compactMap { index, request -> (index: Int, request: UploadMessageRequest)? in
switch request {
case .file(let request):
return (index, request)
default:
return nil
}
}
func requestNext() {
DispatchQueue.main.async {
guard let (index, request) = fileRequests.popLast() else {
completion()
return
}
let content = store.state.content[index]
store.dispatch(.setContentValue(content.withStatus(.sending), index: index))
let task = store.state.api?.fetch(request) { response in
switch response {
case .resource(let resource):
let content = store.state.content[index]
DispatchQueue.main.async {
if let error = resource.error {
store.dispatch(.setContentValue(content.withStatus(.errored(error)), index: index))
} else {
store.dispatch(.setContentValue(content.withStatus(.succeeded), index: index))
}
}
case .error(let error):
let content = store.state.content[index]
DispatchQueue.main.async {
store.dispatch(.setContentValue(content.withStatus(.errored("\(error)")), index: index))
}
}
requestNext()
}
urlTasks.append(task)
}
}
requestNext()
}
func submitMessages(store: SEStore, completion: @escaping (() -> Void)) {
var messageRequests = store.contentRequests.compactMap { index, request -> (index: Int, request: SendMessageRequest)? in
switch request {
case .text(let request):
return (index, request)
default:
return nil
}
}
func requestNext() {
guard let (index, request) = messageRequests.popLast() else {
completion()
return
}
let content = store.state.content[index]
store.dispatch(.setContentValue(content.withStatus(.sending), index: index))
let task = store.state.api?.fetch(request) { response in
switch response {
case .resource:
DispatchQueue.main.async {
let content = store.state.content[index]
store.dispatch(.setContentValue(content.withStatus(.succeeded), index: index))
}
case .error(let error):
DispatchQueue.main.async {
let content = store.state.content[index]
store.dispatch(.setContentValue(content.withStatus(.errored("\(error)")), index: index))
}
}
requestNext()
}
urlTasks.append(task)
}
requestNext()
}
func submitContent(_ store: SEStore) -> SEAction? {
submitMessages(store: store) {
submitFiles(store: store) {
DispatchQueue.main.async {
store.dispatch(.makeSceneTransition(.push(.report)))
}
}
}
return nil
}
func cancelSubmittingContent(_ store: SEStore) -> SEAction? {
urlTasks.forEach {
$0?.cancel()
}
urlTasks.removeAll()
return nil
}
|
mit
|
75e679c814ebb5e6db3ee3630ddfa321
| 29.651316 | 124 | 0.52844 | 4.904211 | false | false | false | false |
gssdromen/CedFilterView
|
FilterTest/Extension/StringExtension.swift
|
1
|
3410
|
//
// StringExtension.swift
// SecondHandHouseBroker
//
// Created by Cedric Wu on 1/27/16.
// Copyright © 2016 FangDuoDuo. All rights reserved.
//
import Foundation
extension String {
// func sha1() -> String {
// let data = self.dataUsingEncoding(NSUTF8StringEncoding)!
// var digest = [UInt8](count: Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0)
// CC_SHA1(data.bytes, CC_LONG(data.length), &digest)
// let hexBytes = digest.map { String(format: "%02hhx", $0) }
// return hexBytes.joinWithSeparator("")
// }
func heightWithConstrainedWidth(_ width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return boundingBox.height
}
func sizeWithConstrainedWidth(_ width: CGFloat, font: UIFont) -> CGSize {
let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return boundingBox.size
}
func isNumberWithMostTwoDecimal() -> Bool {
return self.checkRegex("\\d*(\\.\\d{0,2})?")
}
func isPhoneNumber() -> Bool {
return self.checkRegex("^\\d{11}$")
}
func checkRegex(_ reg: String) -> Bool {
let test = NSPredicate(format: "SELF MATCHES %@", reg)
let result = test.evaluate(with: self)
return result
}
func messUpPhoneNumber() -> String {
if self.isPhoneNumber() {
let index1 = self.characters.index(self.startIndex, offsetBy: 3)
let index2 = self.characters.index(self.endIndex, offsetBy: -4)
return self.substring(to: index1) + "****" + self.substring(from: index2)
} else {
return self
}
}
func pickWordsWithRegex(_ reg: String) -> [String] {
var result = [String]()
do {
let regex = try NSRegularExpression(pattern: reg, options: NSRegularExpression.Options.caseInsensitive)
let array = regex.matches(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSMakeRange(0, self.characters.count))
for range in array {
let startIndex = self.characters.index(self.startIndex, offsetBy: range.range.location)
let endIndex = self.characters.index(self.startIndex, offsetBy: range.range.location + range.range.length)
result.append(self.substring(with: startIndex ..< endIndex))
}
} catch {
}
return result
}
func urlEncode() -> String {
return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
// 返回第一个名字
func getIconName() -> String {
if self.characters.count == 1 {
return self
}
let str = self as NSString
let sss = str.substring(to: 1).cString(using: String.Encoding.utf8)
if strlen(sss) == 1 {
return str.substring(to: 2)
} else {
return str.substring(to: 1)
}
return ""
}
}
|
gpl-3.0
|
ac822b9181001f2a3a0e3f474c8711cf
| 34.364583 | 176 | 0.628866 | 4.386305 | false | false | false | false |
cplaverty/KeitaiWaniKani
|
WaniKaniKit/Model/UserInformation.swift
|
1
|
1279
|
//
// UserInformation.swift
// WaniKaniKit
//
// Copyright © 2017 Chris Laverty. All rights reserved.
//
public struct UserInformation: StandaloneResourceData, Equatable {
public let id: String
public let username: String
public let level: Int
public let profileURL: URL
public let startedAt: Date
public let subscription: Subscription
public let currentVacationStartedAt: Date?
public var effectiveLevel: Int {
return min(level, subscription.maxLevelGranted)
}
private enum CodingKeys: String, CodingKey {
case id
case username
case level
case profileURL = "profile_url"
case startedAt = "started_at"
case subscription
case currentVacationStartedAt = "current_vacation_started_at"
}
}
extension UserInformation {
public struct Subscription: Codable, Equatable {
public let isActive: Bool
public let type: String
public let maxLevelGranted: Int
public let periodEndsAt: Date?
private enum CodingKeys: String, CodingKey {
case isActive = "active"
case type
case maxLevelGranted = "max_level_granted"
case periodEndsAt = "period_ends_at"
}
}
}
|
mit
|
b6b49abdec9a64eb324e810c2818650c
| 26.782609 | 69 | 0.646322 | 4.859316 | false | false | false | false |
iPantry/iPantry-iOS
|
Pantry/Models/PantryUser.swift
|
1
|
5531
|
//
// PantryUser.swift
// Pantry
//
// Created by Justin Oroz on 6/17/17.
// Copyright © 2017 Justin Oroz. All rights reserved.
//
import Foundation
import FirebaseAuth
import FirebaseDatabase
final class PantryUser {
/// The current logged in User
static var current: PantryUser?
/// Sets up the current user
static func configure() {
guard current == nil else {
return
}
PantryUser.current = PantryUser()
}
private var user: User?
private var authHandle: AuthStateDidChangeListenerHandle?
private var userRef: DatabaseReference?
private var userHandle: UInt?
private var userDict: [String: AnyObject]?
private(set) var pantry: Pantry?
private init() {
self.authHandle = Auth.auth().addStateDidChangeListener(authStateChanged)
}
deinit {
Auth.auth().removeStateDidChangeListener(self.authHandle!)
if self.userHandle != nil {
Database.database().reference().removeObserver(withHandle: self.userHandle!)
}
}
/// Handles Firebase Authentication changes
/// Signs in Anonymously if no user logged in
/// Begins observing User directory when logged in
///
/// - Parameters:
/// - auth: Firebase User object
/// - user: Firebase Auth object
private func authStateChanged(auth: Auth, user: User?) {
self.user = user
if self.userHandle != nil { // remove old observer
Database.database().reference().removeObserver(withHandle: self.userHandle!)
self.userHandle = nil
}
guard let user = user else {
fb_log(.info, message: "No User logged in")
NotificationCenter.default.post(name: .pantryUserDoesNotExist, object: self)
Auth.auth().signInAnonymously { (_, error) in
if error != nil {
fb_log(.error, message: "Could not log in anonymously", args: ["error": error!.localizedDescription])
// TODO: Alert User, retry
}
}
return
}
NotificationCenter.default.post(name: .pantryUserExists, object: self)
if user.isAnonymous {
fb_log(.info, message: "User is logged in anonymously")
NotificationCenter.default.post(name: .pantryUserIsAnonymous, object: self)
}
guard !user.isAnonymous else {
// User is Anonymous
self.userRef = nil
self.userHandle = nil
fb_log(.info, message: "User is logged in anonymously, user directory ignored")
NotificationCenter.default.post(name: .pantryUserIsAnonymous, object: self)
return
}
self.userRef = Database.database().reference().child("users").child(user.uid)
self.userHandle = self.userRef!.observe(.value, with: userDirChanged)
fb_log(.info, message: "A User is logged in", args: ["email": user.email ?? "nil"])
NotificationCenter.default.post(name: .pantryUserIsLoggedIn, object: self)
}
/// Called when data in the user directory is changed
///
/// - Parameter snapshot: Firebase snapshot
private func userDirChanged(snapshot: DataSnapshot) {
guard self.user != nil else {
// no user logged in, do nothing
self.userHandle = nil
self.userRef = nil
return
}
guard snapshot.exists() else {
// create user dictionary
var userDict = [String: AnyObject]()
var childUpdates = [String: AnyObject]()
if self.user!.isAnonymous {
userDict["pantry"] = false as AnyObject
childUpdates["/users/\(self.user!.uid)"] = userDict as AnyObject
} else {
let pantryRef = Database.database().reference().child("pantries")
let newPantryId = pantryRef.childByAutoId().key
// add pantry ID to user
userDict["pantry"] = newPantryId as AnyObject
childUpdates["/users/\(self.user!.uid)"] = userDict as AnyObject
// create pantry
childUpdates["/pantries/\(newPantryId)/members"] = [self.user!.uid: true] as AnyObject
}
Database.database().reference().updateChildValues(childUpdates)
return
}
guard let userDict = snapshot.value as? [String: AnyObject] else {
fb_log(.error, message: "User directory snapshot malformed", args: ["snapshot": snapshot.description])
return
}
if let _ = userDict["pantry"] as? Bool {
self.pantry = Pantry(withId: PantryIdentifier(self.user!.uid, indexedBy: .creator))
} else if let pantryId = userDict["pantry"] as? String {
self.pantry = Pantry(withId: PantryIdentifier(pantryId, indexedBy: .pantryId))
} else {
self.pantry = nil
}
self.userDict = userDict
NotificationCenter.default.post(name: .pantryUserWasUpdated, object: self)
}
var state: PantryUserState? {
guard let user = self.user else {
return nil
}
if user.isAnonymous {
return .anonymous
} else {
return .loggedIn
}
}
var pantryIdentifier: PantryIdentifier? {
guard let user = self.user else {
return nil
}
if user.isAnonymous {
return PantryIdentifier(user.uid, indexedBy: .creator)
} else if let pantryId = self.userDict?["pantry"] as? String {
return PantryIdentifier(pantryId, indexedBy: .pantryId)
} else {
return nil
}
}
var uid: String? {
return self.user?.uid
}
var email: String? {
return self.user?.email
}
}
// MARK: - Enums
enum PantryUserState {
case anonymous
case loggedIn
}
// MARK: - Notifications
extension Notification.Name {
static let pantryUserWasUpdated = Notification.Name("pantryUserWasUpdatedNotification")
static let pantryUserIsAnonymous = Notification.Name("PantryUserIsAnonymousNotification")
static let pantryUserIsLoggedIn = Notification.Name("PantryUserIsLoggedInNotification")
static let pantryUserDoesNotExist = Notification.Name("PantryUserDoesNotExistNotification")
static let pantryUserExists = Notification.Name("PantryUserExistsNotification")
}
|
agpl-3.0
|
68d09a0468d62fbd5c269baeaa49eca3
| 26.788945 | 106 | 0.71085 | 3.586252 | false | false | false | false |
CombineCommunity/CombineExt
|
Sources/Operators/Amb.swift
|
1
|
6931
|
//
// Amb.swift
// CombineExt
//
// Created by Shai Mishali on 29/03/2020.
// Copyright © 2020 Combine Community. All rights reserved.
//
#if canImport(Combine)
import Combine
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public extension Publisher {
/// Returns a publisher which mirrors the first publisher to emit an event.
///
/// - parameter other: The second publisher to "compete" against.
///
/// - returns: A publisher which mirrors either `self` or `other`.
func amb<Other: Publisher>(_ other: Other)
-> Publishers.Amb<Self, Other> where Other.Output == Output, Other.Failure == Failure {
Publishers.Amb(first: self, second: other)
}
/// Returns a publisher which mirrors the first publisher to emit an event.
///
/// - parameter others: Other publishers to "compete" against.
///
/// - returns: A publisher which mirrors the first publisher to emit an event.
func amb<Other: Publisher>(with others: Other...)
-> AnyPublisher<Self.Output, Self.Failure> where Other.Output == Output, Other.Failure == Failure {
amb(with: others)
}
/// Returns a publisher which mirrors the first publisher to emit an event.
///
/// - parameter others: Other publishers to "compete" against.
///
/// - returns: A publisher which mirrors the first publisher to emit an event.
func amb<Others: Collection>(with others: Others)
-> AnyPublisher<Self.Output, Self.Failure>
where Others.Element: Publisher, Others.Element.Output == Output, Others.Element.Failure == Failure {
others.reduce(self.eraseToAnyPublisher()) { result, current in
result.amb(current).eraseToAnyPublisher()
}
}
}
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public extension Collection where Element: Publisher {
/// Projects a collection of publishers onto one that has each “compete”. The publisher that wins out by emitting first will be mirrored.
///
/// - Returns: A publisher which mirrors the first publisher to emit an event.
func amb() -> AnyPublisher<Element.Output, Element.Failure> {
switch count {
case 0:
return Empty().eraseToAnyPublisher()
case 1:
return self[startIndex]
.amb(with: [Element]())
default:
let first = self[startIndex]
let others = self[index(after: startIndex)...]
return first
.amb(with: others)
}
}
}
// MARK: - Publisher
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public extension Publishers {
struct Amb<First: Publisher, Second: Publisher>: Publisher where First.Output == Second.Output, First.Failure == Second.Failure {
public func receive<S: Subscriber>(subscriber: S) where Failure == S.Failure, Output == S.Input {
subscriber.receive(subscription: Subscription(first: first,
second: second,
downstream: subscriber))
}
public typealias Output = First.Output
public typealias Failure = First.Failure
private let first: First
private let second: Second
public init(first: First,
second: Second) {
self.first = first
self.second = second
}
}
}
// MARK: - Subscription
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
private extension Publishers.Amb {
class Subscription<Downstream: Subscriber>: Combine.Subscription where Output == Downstream.Input, Failure == Downstream.Failure {
private var firstSink: Sink<First, Downstream>?
private var secondSink: Sink<Second, Downstream>?
private var preDecisionDemand = Subscribers.Demand.none
private var decision: Decision? {
didSet {
guard let decision = decision else { return }
switch decision {
case .first:
secondSink = nil
case .second:
firstSink = nil
}
request(preDecisionDemand)
preDecisionDemand = .none
}
}
init(first: First,
second: Second,
downstream: Downstream) {
self.firstSink = Sink(upstream: first,
downstream: downstream) { [weak self] in
guard let self = self,
self.decision == nil else { return }
self.decision = .first
}
self.secondSink = Sink(upstream: second,
downstream: downstream) { [weak self] in
guard let self = self,
self.decision == nil else { return }
self.decision = .second
}
}
func request(_ demand: Subscribers.Demand) {
guard decision != nil else {
preDecisionDemand += demand
return
}
firstSink?.demand(demand)
secondSink?.demand(demand)
}
func cancel() {
firstSink = nil
secondSink = nil
}
}
}
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
private enum Decision {
case first
case second
}
// MARK: - Sink
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
private extension Publishers.Amb {
class Sink<Upstream: Publisher, Downstream: Subscriber>: CombineExt.Sink<Upstream, Downstream> where Upstream.Output == Downstream.Input, Upstream.Failure == Downstream.Failure {
private let emitted: () -> Void
init(upstream: Upstream,
downstream: Downstream,
emitted: @escaping () -> Void) {
self.emitted = emitted
super.init(upstream: upstream,
downstream: downstream,
transformOutput: { $0 },
transformFailure: { $0 })
}
override func receive(subscription: Combine.Subscription) {
super.receive(subscription: subscription)
// We demand a single event from each upstreram publisher
// so we can determine who wins the race
subscription.request(.max(1))
}
override func receive(_ input: Upstream.Output) -> Subscribers.Demand {
emitted()
return buffer.buffer(value: input)
}
override func receive(completion: Subscribers.Completion<Downstream.Failure>) {
emitted()
buffer.complete(completion: completion)
}
}
}
#endif
|
mit
|
90d5a1d7e7f615ef3b018d21c8039230
| 34.701031 | 182 | 0.564684 | 4.843357 | false | false | false | false |
mike-ferenduros/SwiftySockets
|
Sources/BufferedSocket.swift
|
1
|
4727
|
//
// BufferedSocket.swift
// SwiftySockets
//
// Created by Michael Ferenduros on 11/09/2016.
// Copyright © 2016 Mike Ferenduros. All rights reserved.
//
import Foundation
open class BufferedSocket : DispatchSocket, DispatchSocketReadableDelegate, DispatchSocketWritableDelegate {
override public var debugDescription: String {
return "BufferedSocket(\(socket.debugDescription))"
}
override open func close() throws {
readQueue.removeAll()
writeQueue.removeAll()
try super.close()
}
/**
Read exactly `count` bytes.
- Parameter count: Number of bytes to read
- Parameter completion: Completion-handler, invoked on DispatchQueue.main on success
*/
public func read(_ count: Int, completion: @escaping (Data)->()) {
read(min: count, max: count, completion: completion)
}
/**
Read up to `max` bytes
- Parameter max: Maximum number of bytes to read
- Parameter completion: Completion-handler, invoked on DispatchQueue.main on success
*/
public func read(max: Int, completion: @escaping (Data)->()) {
read(min: 1, max: max, completion: completion)
}
/**
Read at least `min` bytes, up to `max` bytes
- Parameter min: Minimum number of bytes to read
- Parameter min: Maximum number of bytes to read
- Parameter completion: Completion-handler, invoked on DispatchQueue.main on success
*/
public func read(min: Int, max: Int, completion: @escaping (Data)->()) {
precondition(min <= max)
precondition(min > 0)
guard isOpen else { return }
let newItem = ReadItem(buffer: Data(capacity: max), min: min, max: max, completion: completion)
readQueue.append(newItem)
readableDelegate = self
}
private struct ReadItem {
var buffer: Data
let min, max: Int
let completion: (Data)->()
}
private var readQueue: [ReadItem] = []
open func dispatchSocketReadable(_ socket: DispatchSocket, count: Int) {
guard count > 0 else { try? close(); return }
do {
while var item = readQueue.first {
let wanted = item.max - item.buffer.count
let buffer = try self.socket.recv(length: min(wanted, count), options: .dontWait)
item.buffer.append(buffer)
readQueue[0] = item
if item.buffer.count >= item.min {
readQueue.removeFirst()
item.completion(item.buffer)
} else {
break
}
}
}
catch POSIXError(EAGAIN) {}
catch POSIXError(EWOULDBLOCK) {}
catch {
try? close()
}
if readQueue.count == 0 {
readableDelegate = nil
}
}
private var writeQueue: [Data] = []
/**
Asynchronously write data to the connected socket.
For stream-type sockets, the entire contents of `data` is always written
For datagram-type sockets, only a single datagram is sent, hence the data may be truncated.
- Parameter data: Data to be written.
*/
public func write(_ data: Data) {
guard isOpen else { return }
var data = data
//Try and shortcut the whole dispatch-source stuff if possible.
if writeQueue.count == 0, let written = try? self.socket.send(buffer: data, options: .dontWait), written > 0 {
if written == data.count || self.type == .datagram {
return
} else {
data = data.subdata(in: written ..< data.count)
}
}
writeQueue.append(data)
writableDelegate = self
}
open func dispatchSocketWritable(_ socket: DispatchSocket) {
do {
while let packet = writeQueue.first {
let written = try self.socket.send(buffer: packet, options: .dontWait)
if written == packet.count || self.type == .datagram {
//Datagrams are truncated to whatever gets accepted by a single send()
_ = writeQueue.removeFirst()
} else {
if written > 0 {
//For streams, we try and send the entire packet, even if it takes multiple calls
writeQueue[0] = packet.subdata(in: written ..< packet.count)
}
break
}
}
} catch POSIXError(EAGAIN) {
} catch POSIXError(EWOULDBLOCK) {
} catch {
try? close()
return
}
if writeQueue.count == 0 {
writableDelegate = nil
}
}
}
|
mit
|
1e2b58741005bfd86550b59747864941
| 31.14966 | 118 | 0.570673 | 4.66996 | false | false | false | false |
efremidze/Haptica
|
Sources/Extensions.swift
|
1
|
547
|
//
// Extensions.swift
// Haptica
//
// Created by Lasha Efremidze on 8/16/18.
// Copyright © 2018 efremidze. All rights reserved.
//
import UIKit
extension UIControl.Event: Hashable {
public var hashValue: Int {
return Int(rawValue)
}
}
func == (lhs: UIControl.Event, rhs: UIControl.Event) -> Bool {
return lhs.rawValue == rhs.rawValue
}
extension OperationQueue {
static var serial: OperationQueue {
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
return queue
}
}
|
mit
|
eead269f69c19704c7d4797083bb66cf
| 19.222222 | 62 | 0.657509 | 3.928058 | false | false | false | false |
PocketSwift/PocketNet
|
StaticPods/Reqres/Source/Reqres.swift
|
1
|
9945
|
//
// Reqres.swift
// Reqres
//
// Created by Jan Mísař on 05/27/2016.
// Copyright (c) 2016 Jan Mísař. All rights reserved.
//
import Foundation
let ReqresRequestHandledKey = "ReqresRequestHandledKey"
let ReqresRequestTimeKey = "ReqresRequestTimeKey"
open class Reqres: URLProtocol, URLSessionDelegate {
var dataTask: URLSessionDataTask?
var newRequest: NSMutableURLRequest?
public static var sessionDelegate: URLSessionDelegate?
public static var policyManager: ServerTrustPolicyManager?
public static var allowUTF8Emoji: Bool = true
public static var logger: ReqresLogging = ReqresDefaultLogger()
open class func register() {
URLProtocol.registerClass(self)
}
open class func unregister() {
URLProtocol.unregisterClass(self)
}
open class func defaultSessionConfiguration() -> URLSessionConfiguration {
let config = URLSessionConfiguration.default
config.protocolClasses?.insert(Reqres.self, at: 0)
return config
}
// MARK: - NSURLProtocol
open override class func canInit(with request: URLRequest) -> Bool {
guard self.property(forKey: ReqresRequestHandledKey, in: request) == nil && self.logger.logLevel != .none else {
return false
}
return true
}
open override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
open override class func requestIsCacheEquivalent(_ a: URLRequest, to b: URLRequest) -> Bool {
return super.requestIsCacheEquivalent(a, to: b)
}
open override func startLoading() {
guard let req = (request as NSURLRequest).mutableCopy() as? NSMutableURLRequest, newRequest == nil else { return }
self.newRequest = req
URLProtocol.setProperty(true, forKey: ReqresRequestHandledKey, in: newRequest!)
URLProtocol.setProperty(Date(), forKey: ReqresRequestTimeKey, in: newRequest!)
let session = URLSession(configuration: .default, delegate: Reqres.sessionDelegate ?? self, delegateQueue: nil)
session.serverTrustPolicyManager = Reqres.policyManager
dataTask = session.dataTask(with: request) { [weak self] data, response, error in
guard let `self` = self else { return }
if let error = error {
self.client?.urlProtocol(self, didFailWithError: error)
self.logError(self.request, error: error as NSError)
return
}
guard let response = response, let data = data else { return }
self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .allowed)
self.client?.urlProtocol(self, didLoad: data)
self.client?.urlProtocolDidFinishLoading(self)
self.logResponse(response, method: nil, data: data)
}
dataTask?.resume()
logRequest(newRequest! as URLRequest)
}
open override func stopLoading() {
dataTask?.cancel()
}
// MARK: - Logging
open func logError(_ request: URLRequest, error: NSError) {
var s = ""
if type(of: self).allowUTF8Emoji {
s += "⚠️ "
}
if let method = request.httpMethod {
s += "\(method) "
}
if let url = request.url?.absoluteString {
s += "\(url) "
}
s += "ERROR: \(error.localizedDescription)"
if let reason = error.localizedFailureReason {
s += "\nReason: \(reason)"
}
if let suggestion = error.localizedRecoverySuggestion {
s += "\nSuggestion: \(suggestion)"
}
type(of: self).logger.logError(s)
}
open func logRequest(_ request: URLRequest) {
var s = ""
if type(of: self).allowUTF8Emoji {
s += "⬆️ "
}
if let method = request.httpMethod {
s += "\(method) "
}
if let url = request.url?.absoluteString {
s += "'\(url)' "
}
if type(of: self).logger.logLevel == .verbose {
if let headers = request.allHTTPHeaderFields, headers.count > 0 {
s += "\n" + logHeaders(headers as [String : AnyObject])
}
s += "\nBody: \(bodyString(request.httpBodyData))"
type(of: self).logger.logVerbose(s)
} else {
type(of: self).logger.logLight(s)
}
}
open func logResponse(_ response: URLResponse, method: String?, data: Data? = nil) {
var s = ""
if type(of: self).allowUTF8Emoji {
s += "⬇️ "
}
if let method = method {
s += "\(method)"
} else if let method = newRequest?.httpMethod {
s += "\(method) "
}
if let url = response.url?.absoluteString {
s += "'\(url)' "
}
if let httpResponse = response as? HTTPURLResponse {
s += "("
if type(of: self).allowUTF8Emoji {
let iconNumber = Int(floor(Double(httpResponse.statusCode) / 100.0))
if let iconString = statusIcons[iconNumber] {
s += "\(iconString) "
}
}
s += "\(httpResponse.statusCode)"
if let statusString = statusStrings[httpResponse.statusCode] {
s += " \(statusString)"
}
s += ")"
if let startDate = URLProtocol.property(forKey: ReqresRequestTimeKey, in: newRequest! as URLRequest) as? Date {
let difference = fabs(startDate.timeIntervalSinceNow)
s += String(format: " [time: %.5f s]", difference)
}
}
if type(of: self).logger.logLevel == .verbose {
if let headers = (response as? HTTPURLResponse)?.allHeaderFields as? [String: AnyObject], headers.count > 0 {
s += "\n" + logHeaders(headers)
}
s += "\nBody: \(bodyString(data))"
type(of: self).logger.logVerbose(s)
} else {
type(of: self).logger.logLight(s)
}
}
open func logHeaders(_ headers: [String: AnyObject]) -> String {
var s = "Headers: [\n"
for (key, value) in headers {
s += "\t\(key) : \(value)\n"
}
s += "]"
return s
}
func bodyString(_ body: Data?) -> String {
if let body = body {
if let json = try? JSONSerialization.jsonObject(with: body, options: .mutableContainers),
let pretty = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted),
let string = String(data: pretty, encoding: String.Encoding.utf8) {
return string
} else if let string = String(data: body, encoding: String.Encoding.utf8) {
return string
} else {
return body.description
}
} else {
return "nil"
}
}
}
extension URLRequest {
var httpBodyData: Data? {
guard let stream = httpBodyStream else {
return httpBody
}
let data = NSMutableData()
stream.open()
let bufferSize = 4_096
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
while stream.hasBytesAvailable {
let bytesRead = stream.read(buffer, maxLength: bufferSize)
if bytesRead > 0 {
let readData = Data(bytes: UnsafePointer<UInt8>(buffer), count: bytesRead)
data.append(readData)
} else if bytesRead < 0 {
print("error occured while reading HTTPBodyStream: \(bytesRead)")
} else {
break
}
}
stream.close()
return data as Data
}
}
let statusIcons = [
1: "ℹ️",
2: "✅",
3: "⤴️",
4: "⛔️",
5: "❌"
]
let statusStrings = [
// 1xx (Informational)
100: "Continue",
101: "Switching Protocols",
102: "Processing",
// 2xx (Success)
200: "OK",
201: "Created",
202: "Accepted",
203: "Non-Authoritative Information",
204: "No Content",
205: "Reset Content",
206: "Partial Content",
207: "Multi-Status",
208: "Already Reported",
226: "IM Used",
// 3xx (Redirection)
300: "Multiple Choices",
301: "Moved Permanently",
302: "Found",
303: "See Other",
304: "Not Modified",
305: "Use Proxy",
306: "Switch Proxy",
307: "Temporary Redirect",
308: "Permanent Redirect",
// 4xx (Client Error)
400: "Bad Request",
401: "Unauthorized",
402: "Payment Required",
403: "Forbidden",
404: "Not Found",
405: "Method Not Allowed",
406: "Not Acceptable",
407: "Proxy Authentication Required",
408: "Request Timeout",
409: "Conflict",
410: "Gone",
411: "Length Required",
412: "Precondition Failed",
413: "Request Entity Too Large",
414: "Request-URI Too Long",
415: "Unsupported Media Type",
416: "Requested Range Not Satisfiable",
417: "Expectation Failed",
418: "I'm a teapot",
420: "Enhance Your Calm",
422: "Unprocessable Entity",
423: "Locked",
424: "Method Failure",
425: "Unordered Collection",
426: "Upgrade Required",
428: "Precondition Required",
429: "Too Many Requests",
431: "Request Header Fields Too Large",
451: "Unavailable For Legal Reasons",
// 5xx (Server Error)
500: "Internal Server Error",
501: "Not Implemented",
502: "Bad Gateway",
503: "Service Unavailable",
504: "Gateway Timeout",
505: "HTTP Version Not Supported",
506: "Variant Also Negotiates",
507: "Insufficient Storage",
508: "Loop Detected",
509: "Bandwidth Limit Exceeded",
510: "Not Extended",
511: "Network Authentication Required"
]
|
mit
|
cedf15b0f6af0531f77f5684d1125a48
| 27.81686 | 123 | 0.570564 | 4.419527 | false | false | false | false |
rhwood/roster-decoder
|
Sources/Profile.swift
|
1
|
8287
|
//
// Profile.swift
// Roster Decoder
//
// Created by Randall Wood on 9/15/18.
// Copyright © 2018 Alexandria Software. All rights reserved.
//
import UIKit
import os.log
enum ProfileError: Error {
case invalidProfile
case noRosterFile
case noRosterDir
case externalRoster
case emptyRoster
case invalidRoster
var description: String {
switch self {
case .invalidProfile:
return "This does not appear to be a JMRI Configuration Profile."
case .noRosterFile:
return "This JMRI Configuration Profile is missing a roster.xml file."
case .noRosterDir:
return "This JMRI Configuration Profile is missing a roster directory."
case .externalRoster:
return "The roster for this JMRI Configuration Profile is configured to be elsewhere."
+ "You will need to open the owning profile or roster.xml file directly."
case .emptyRoster:
return "The roster is empty."
case .invalidRoster:
return "This file is not a JMRI roster."
}
}
}
class Profile: UIDocument {
public enum PropertyKey: String {
case profileName = "profile.name"
case rosterDirectory = "jmri-jmrit-roster.directory"
case userFiles = "jmri-implementation.user-files"
}
static let rosterFileName = "roster.xml"
static let rosterDirName = "roster"
static let profileDirName = "profile"
static let profilePropertiesName = "profile.properties"
static let portablePathPreferences = "preference\\:"
static let portablePathProfile = "profile\\:"
var name: String {
return self.properties[PropertyKey.profileName.rawValue] ?? "Unknown"
}
var rosterFile: FileWrapper?
var rosterDir: FileWrapper?
var rootDir: FileWrapper?
var userFilesDir: FileWrapper?
var profilePropertiesFile: FileWrapper?
var properties = [String: String]()
var roster: Roster?
var loadError: ProfileError?
override func contents(forType typeName: String) throws -> Any {
// Encode your document with an instance of NSData or NSFileWrapper
return Data()
}
override func load(fromContents contents: Any, ofType typeName: String?) throws {
os_log("Loading file of type %@", typeName ?? "nil")
if let dir = contents as? FileWrapper, dir.isDirectory {
try load(fromFileWrapperAsDir: dir, ofType: typeName)
} else if let data = contents as? Data {
try load(fromData: data, ofType: typeName)
} else {
if contents is FileWrapper {
os_log("%@ is a FileWrapper but not a directory", self.fileURL as CVarArg)
}
os_log("%@ is not a JMRI Configuration Profile", type: .error, self.fileURL as CVarArg)
loadError = ProfileError.invalidProfile
throw loadError!
}
}
// MARK: Load from Profile
func load(fromFileWrapperAsDir fileWrapper: FileWrapper, ofType typeName: String?) throws {
rootDir = fileWrapper
setProfileFiles(fileWrapper: fileWrapper)
// read profile/profile.properties
if profilePropertiesFile != nil,
let data = String(bytes: (profilePropertiesFile?.regularFileContents)!, encoding: .utf8) {
try readProfileProperties(data: data)
try setRosterFromProperties()
} else {
os_log("This is not a JMRI configuration profile.")
loadError = ProfileError.invalidProfile
throw loadError!
}
// get name and roster path
// if roster path starts with "preferences:", accept roster
if rosterFile == nil || !(rosterFile?.isRegularFile)! {
// if roster is empty, show message about roster being empty
os_log("No roster in profile (missing roster.xml file)")
loadError = ProfileError.noRosterFile
throw loadError!
} else {
do {
roster = try Roster(profile: self)
} catch {
loadError = ProfileError.invalidRoster
throw loadError!
}
}
if rosterDir == nil || !(rosterDir?.isDirectory)! {
// even if the roster file exists, there is no roster
os_log("No roster in profile (missing roster directory)")
loadError = ProfileError.noRosterDir
throw loadError!
}
if roster?.entries.count == 0
&& !UserDefaults.standard.bool(forKey: SettingsViewController.showEmptyRosterKey) {
loadError = ProfileError.emptyRoster
throw loadError!
}
}
func setProfileFiles(fileWrapper: FileWrapper) {
for file in fileWrapper.fileWrappers! {
switch file.key {
case Profile.profileDirName:
for dir in file.value.fileWrappers! {
switch dir.key {
case Profile.profilePropertiesName:
profilePropertiesFile = dir.value
default:
break
}
}
case Profile.rosterDirName:
rosterDir = file.value
case Profile.rosterFileName:
rosterFile = file.value
default:
break
}
}
}
func readProfileProperties(data: String) throws {
for line in data.components(separatedBy: CharacterSet.newlines) {
if let equals = line.firstIndex(of: "=") {
let keyEnd = line.index(before: equals)
let valueStart = line.index(after: equals)
properties[String(line[...keyEnd])] = String(line[valueStart...])
}
}
// uncomment to log all profile properties
// for property in properties {
// os_log("Property %@ is %@", property.key, property.value)
// }
}
func setRosterFromProperties() throws {
if let dir = properties[Profile.PropertyKey.userFiles.rawValue] {
if dir.starts(with: Profile.portablePathProfile) {
let index = dir.index(dir.startIndex, offsetBy: Profile.portablePathProfile.count)
if dir[index...] == "" {
userFilesDir = rootDir
} else {
userFilesDir = rootDir
for part in dir[index...].split(separator: "\\") {
userFilesDir = userFilesDir?.fileWrappers![String(part)]
}
}
} else {
properties[PropertyKey.userFiles.rawValue] = nil
}
}
if let dir = properties[Profile.PropertyKey.rosterDirectory.rawValue] {
var index: String.Index
if dir.starts(with: Profile.portablePathPreferences) {
index = dir.index(dir.startIndex, offsetBy: Profile.portablePathPreferences.count)
rosterDir = userFilesDir
} else if dir.starts(with: Profile.portablePathProfile) {
index = dir.index(dir.startIndex, offsetBy: Profile.portablePathProfile.count)
rosterDir = rootDir
} else {
os_log("This profile does not contain a roster")
loadError = ProfileError.externalRoster
throw loadError!
}
if dir[index...] != "" {
for part in dir[index...].split(separator: "\\") {
rosterDir = rosterDir?.fileWrappers![String(part)]
}
}
rosterFile = rosterDir?.fileWrappers![Profile.rosterFileName]
rosterDir = rosterDir?.fileWrappers![Profile.rosterDirName]
}
os_log("Roster file: %@", rosterFile!.filename!)
os_log("Roster directory: %@", rosterDir?.filename! ?? "NONE")
os_log("User files: %@", userFilesDir!.filename!)
}
// MARK: Load from XML
func load(fromData data: Data, ofType typeName: String?) throws {
do {
roster = try Roster(data: data)
} catch {
loadError = ProfileError.invalidRoster
throw loadError!
}
}
}
|
mit
|
847e3d7635d45d1460ea4e5876d6fde4
| 37.184332 | 102 | 0.583997 | 4.811847 | false | false | false | false |
SerjKultenko/Calculator3
|
Calculator/CoordinatesSet.swift
|
1
|
1452
|
//
// CoordinatesSet.swift
// Calculator
//
// Created by Sergei Kultenko on 06/09/2017.
// Copyright © 2017 Sergey Kultenko. All rights reserved.
//
import Foundation
import UIKit
struct CoordinatesSet: Sequence, IteratorProtocol
{
let center: CGPoint
let halfWidth: CGFloat
let halfHeight: CGFloat
let pointsPerUnit: CGFloat
var startingPointX: CGFloat
init(center: CGPoint, halfWidth: CGFloat, halfHeight: CGFloat, pointsPerUnit: CGFloat) {
self.center = center
self.halfWidth = halfWidth
self.halfHeight = halfHeight
self.pointsPerUnit = pointsPerUnit
startingPointX = center.x - halfWidth
}
mutating func next() -> CGFloat? {
if startingPointX >= (center.x + halfWidth) {
return nil
} else {
defer { startingPointX += 1 }
return xUnitFromPoint(startingPointX)
}
}
func convertToCGPointFromUnits(xUnit x:CGFloat, yUnit y:CGFloat) -> CGPoint? {
guard pointsPerUnit > 0 else {
return nil
}
let xPoints = x * pointsPerUnit + center.x
let yPoints = center.y - y * pointsPerUnit
return CGPoint(x: xPoints, y: yPoints)
}
func xUnitFromPoint(_ point: CGFloat) -> CGFloat? {
guard pointsPerUnit > 0 else {
return nil
}
return CGFloat(point - center.x)/pointsPerUnit
}
}
|
mit
|
6fcf70302753b3c8b867e08e490e5030
| 25.381818 | 92 | 0.609924 | 4.591772 | false | false | false | false |
vnu/vTweetz
|
Pods/SwiftDate/SwiftDate_src/Region.swift
|
2
|
5751
|
//
// SwiftDate, an handy tool to manage date and timezones in swift
// Created by: Daniele Margutti
// Main contributors: Jeroen Houtzager
//
//
// 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
// Backward compatibility resolves issue https://github.com/malcommac/SwiftDate/issues/121
//
@available(*, renamed="DateRegion")
public typealias DateRegion = Region
/// Region encapsulates all objects you need when representing a date from an absolute time like NSDate.
///
@available(*, introduced=2.0)
public struct Region: Equatable {
/// Calendar to interpret date values. You can alter the calendar to adjust the representation of date to your needs.
///
public let calendar: NSCalendar!
/// Time zone to interpret date values
/// Because the time zone is part of calendar, this is a shortcut to that variable.
/// You can alter the time zone to adjust the representation of date to your needs.
///
public let timeZone: NSTimeZone!
/// Locale to interpret date values
/// Because the locale is part of calendar, this is a shortcut to that variable.
/// You can alter the locale to adjust the representation of date to your needs.
///
public let locale: NSLocale!
/// Initialise with a calendar and/or a time zone
///
/// - Parameters:
/// - calendar: the calendar to work with
/// - timeZone: the time zone to work with
/// - locale: the locale to work with
///
internal init(
calendar: NSCalendar,
timeZone: NSTimeZone,
locale: NSLocale) {
self.calendar = calendar
self.timeZone = timeZone
self.locale = locale
// Assign calendar fields
self.calendar.timeZone = self.timeZone
self.calendar.locale = locale
}
/// Initialise with a date components
///
/// - Parameters:
/// - components: the date components to initialise with
///
internal init(_ components: NSDateComponents) {
let calendar = components.calendar ?? NSCalendar.currentCalendar()
let timeZone = components.timeZone ?? NSTimeZone.defaultTimeZone()
let locale = calendar.locale ?? NSLocale.currentLocale()
self.init(calendar: calendar, timeZone: timeZone, locale: locale)
}
/// Initialise with a calendar and/or a time zone
///
/// - Parameters:
/// - calendarName: the calendar to work with to assign in `CalendarName` format, default = the current calendar
/// - timeZoneName: the time zone to work with in `TimeZoneConvertible` format, default is the default time zone
/// - localeName: the locale to work with, default is the current locale
///
public init(
calendarName: CalendarName? = nil,
timeZoneName: TimeZoneName? = nil,
localeName: LocaleName? = nil) {
let calendar = calendarName?.calendar ?? NSCalendar.currentCalendar()
let timeZone = timeZoneName?.timeZone ?? NSTimeZone.defaultTimeZone()
let locale = localeName?.locale ?? NSLocale.currentLocale()
self.init(calendar: calendar, timeZone: timeZone, locale: locale)
}
/// Today's date
///
/// - Returns: the date of today at midnight (00:00) in the current calendar and default time zone.
///
public func today() -> DateInRegion {
return DateInRegion(region: self).startOf(.Day)
}
/// Yesterday's date
///
/// - Returns: the date of yesterday at midnight (00:00)
///
public func yesterday() -> DateInRegion {
return today() - 1.days
}
/// Tomorrow's date
///
/// - Returns: the date of tomorrow at midnight (00:00)
///
public func tomorrow() -> DateInRegion {
return today() + 1.days
}
}
public func ==(left: Region, right: Region) -> Bool {
if left.calendar.calendarIdentifier != right.calendar.calendarIdentifier {
return false
}
if left.timeZone.secondsFromGMT != right.timeZone.secondsFromGMT {
return false
}
if left.locale.localeIdentifier != right.locale.localeIdentifier {
return false
}
return true
}
extension Region: Hashable {
public var hashValue: Int {
return calendar.hashValue ^ timeZone.hashValue ^ locale.hashValue
}
}
extension Region: CustomStringConvertible {
public var description: String {
let timeZoneAbbreviation = timeZone.abbreviation ?? ""
return "\(calendar.calendarIdentifier); \(timeZone.name):\(timeZoneAbbreviation); \(locale.localeIdentifier)"
}
}
|
apache-2.0
|
5ac58c15940c2d248600d84ebb39b2d0
| 34.95 | 121 | 0.659885 | 4.780549 | false | false | false | false |
scinfu/SwiftSoup
|
Tests/SwiftSoupTests/TokenQueueTest.swift
|
1
|
2863
|
//
// TokenQueueTest.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 13/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import XCTest
import SwiftSoup
class TokenQueueTest: XCTestCase {
func testLinuxTestSuiteIncludesAllTests() {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
let thisClass = type(of: self)
let linuxCount = thisClass.allTests.count
let darwinCount = Int(thisClass.defaultTestSuite.testCaseCount)
XCTAssertEqual(linuxCount, darwinCount, "\(darwinCount - linuxCount) tests are missing from allTests")
#endif
}
func testChompBalanced() {
let tq = TokenQueue(":contains(one (two) three) four")
let pre = tq.consumeTo("(")
let guts = tq.chompBalanced("(", ")")
let remainder = tq.remainder()
XCTAssertEqual(":contains", pre)
XCTAssertEqual("one (two) three", guts)
XCTAssertEqual(" four", remainder)
}
func testChompEscapedBalanced() {
let tq = TokenQueue(":contains(one (two) \\( \\) \\) three) four")
let pre = tq.consumeTo("(")
let guts = tq.chompBalanced("(", ")")
let remainder = tq.remainder()
XCTAssertEqual(":contains", pre)
XCTAssertEqual("one (two) \\( \\) \\) three", guts)
XCTAssertEqual("one (two) ( ) ) three", TokenQueue.unescape(guts))
XCTAssertEqual(" four", remainder)
}
func testChompBalancedMatchesAsMuchAsPossible() {
let tq = TokenQueue("unbalanced(something(or another")
tq.consumeTo("(")
let match = tq.chompBalanced("(", ")")
XCTAssertEqual("something(or another", match)
}
func testUnescape() {
XCTAssertEqual("one ( ) \\", TokenQueue.unescape("one \\( \\) \\\\"))
}
func testChompToIgnoreCase() {
let t = "<textarea>one < two </TEXTarea>"
var tq = TokenQueue(t)
var data = tq.chompToIgnoreCase("</textarea")
XCTAssertEqual("<textarea>one < two ", data)
tq = TokenQueue("<textarea> one two < three </oops>")
data = tq.chompToIgnoreCase("</textarea")
XCTAssertEqual("<textarea> one two < three </oops>", data)
}
func testAddFirst() {
let tq = TokenQueue("One Two")
tq.consumeWord()
tq.addFirst("Three")
XCTAssertEqual("Three Two", tq.remainder())
}
static var allTests = {
return [
("testLinuxTestSuiteIncludesAllTests", testLinuxTestSuiteIncludesAllTests),
("testChompBalanced", testChompBalanced),
("testChompEscapedBalanced", testChompEscapedBalanced),
("testChompBalancedMatchesAsMuchAsPossible", testChompBalancedMatchesAsMuchAsPossible),
("testUnescape", testUnescape),
("testChompToIgnoreCase", testChompToIgnoreCase),
("testAddFirst", testAddFirst)
]
}()
}
|
mit
|
c62c915fb09487fc2b19542c38cb8028
| 31.896552 | 114 | 0.618798 | 4.382848 | false | true | false | false |
zameericle/ProductHuntExtn
|
ProductHuntExtn/TodayViewController.swift
|
1
|
4076
|
//
// TodayViewController.swift
// ProductHuntExtn
//
// Created by Zameer Andani on 6/13/14.
//
//
import Cocoa
import NotificationCenter
class TodayViewController: NSViewController, NCWidgetProviding, NCWidgetListViewDelegate, ListRowViewDelegate {
@IBOutlet var listViewController: NCWidgetListViewController?
// #pragma mark - NSViewController
override func viewDidLoad() {
super.viewDidLoad()
// Call hook-api and get the hunts for today
let data : NSData = NSData(contentsOfURL: NSURL(string: "http://hook-api.herokuapp.com/today"))
let JSON = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as? Dictionary<String, AnyObject>
let hunts: AnyObject? = JSON!["hunts"]
self.listViewController!.contents = hunts as Array
}
override func dismissViewController(viewController: NSViewController) {
super.dismissViewController(viewController)
}
// #pragma mark ListRowViewDelegate
func openURL(URL: NSURL)
{
self.extensionContext.openURL(URL, completionHandler: nil)
}
// #pragma mark - NCWidgetProviding
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) {
// Refresh the widget's contents in preparation for a snapshot.
// Call the completion handler block after the widget's contents have been
// refreshed. Pass NCUpdateResultNoData to indicate that nothing has changed
// or NCUpdateResultNewData to indicate that there is new data since the
// last invocation of this method.
completionHandler(.NewData)
}
func widgetMarginInsetsForProposedMarginInsets(var defaultMarginInset: NSEdgeInsets) -> NSEdgeInsets {
// Override the left margin so that the list view is flush with the edge.
defaultMarginInset.left = 0
return defaultMarginInset
}
func widgetAllowsEditing() -> Bool {
// Return true to indicate that the widget supports editing of content and
// that the list view should be allowed to enter an edit mode.
return true
}
func widgetDidBeginEditing() {
// The user has clicked the edit button.
// Put the list view into editing mode.
self.listViewController!.editing = true
}
func widgetDidEndEditing() {
// The user has clicked the Done button, begun editing another widget,
// or the Notification Center has been closed.
// Take the list view out of editing mode.
self.listViewController!.editing = false
}
// #pragma mark - NCWidgetListViewDelegate
func widgetList(list: NCWidgetListViewController, viewControllerForRow row: Int) -> NSViewController! {
// Return a new view controller subclass for displaying an item of widget
// content. The NCWidgetListViewController will set the representedObject
// of this view controller to one of the objects in its contents array.
let lrv = ListRowViewController()
lrv.delegate = self;
return lrv
}
func widgetListPerformAddAction(list: NCWidgetListViewController) {
// The user has clicked the add button in the list view.
// Display a search controller for adding new content to the widget.
}
func widgetList(list: NCWidgetListViewController, shouldReorderRow row: Int) -> Bool {
// Return true to allow the item to be reordered in the list by the user.
return true
}
func widgetList(list: NCWidgetListViewController, didReorderRow row: Int, toRow newIndex: Int) {
// The user has reordered an item in the list.
}
func widgetList(list: NCWidgetListViewController, shouldRemoveRow row: Int) -> Bool {
// Return true to allow the item to be removed from the list by the user.
return true
}
func widgetList(list: NCWidgetListViewController, didRemoveRow row: Int) {
// The user has removed an item from the list.
}
}
|
mit
|
a157b8ffea87808503588adc579497b3
| 36.740741 | 158 | 0.693327 | 5.146465 | false | false | false | false |
TakuSemba/DribbbleSwiftApp
|
Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/APIWrappers/APIWrappersViewController.swift
|
1
|
5042
|
//
// APIWrappersViewController.swift
// RxExample
//
// Created by Carlos García on 8/7/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import UIKit
import CoreLocation
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
extension UILabel {
public override var accessibilityValue: String! {
get {
return self.text
}
set {
self.text = newValue
self.accessibilityValue = newValue
}
}
}
class APIWrappersViewController: ViewController {
@IBOutlet weak var debugLabel: UILabel!
@IBOutlet weak var openActionSheet: UIButton!
@IBOutlet weak var openAlertView: UIButton!
@IBOutlet weak var bbitem: UIBarButtonItem!
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var switcher: UISwitch!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var button: UIButton!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var mypan: UIPanGestureRecognizer!
@IBOutlet weak var textView: UITextView!
let manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
datePicker.date = NSDate(timeIntervalSince1970: 0)
// MARK: UIBarButtonItem
bbitem.rx_tap
.subscribeNext { [weak self] x in
self?.debug("UIBarButtonItem Tapped")
}
.addDisposableTo(disposeBag)
// MARK: UISegmentedControl
// also test two way binding
let segmentedValue = Variable(0)
segmentedControl.rx_value <-> segmentedValue
segmentedValue.asObservable()
.subscribeNext { [weak self] x in
self?.debug("UISegmentedControl value \(x)")
}
.addDisposableTo(disposeBag)
// MARK: UISwitch
// also test two way binding
let switchValue = Variable(true)
switcher.rx_value <-> switchValue
switchValue.asObservable()
.subscribeNext { [weak self] x in
self?.debug("UISwitch value \(x)")
}
.addDisposableTo(disposeBag)
// MARK: UIActivityIndicatorView
switcher.rx_value
.bindTo(activityIndicator.rx_animating)
.addDisposableTo(disposeBag)
// MARK: UIButton
button.rx_tap
.subscribeNext { [weak self] x in
self?.debug("UIButton Tapped")
}
.addDisposableTo(disposeBag)
// MARK: UISlider
// also test two way binding
let sliderValue = Variable<Float>(1.0)
slider.rx_value <-> sliderValue
sliderValue.asObservable()
.subscribeNext { [weak self] x in
self?.debug("UISlider value \(x)")
}
.addDisposableTo(disposeBag)
// MARK: UIDatePicker
// also test two way binding
let dateValue = Variable(NSDate(timeIntervalSince1970: 0))
datePicker.rx_date <-> dateValue
dateValue.asObservable()
.subscribeNext { [weak self] x in
self?.debug("UIDatePicker date \(x)")
}
.addDisposableTo(disposeBag)
// MARK: UITextField
// also test two way binding
let textValue = Variable("")
textField <-> textValue
textValue.asObservable()
.subscribeNext { [weak self] x in
self?.debug("UITextField text \(x)")
}
.addDisposableTo(disposeBag)
// MARK: UIGestureRecognizer
mypan.rx_event
.subscribeNext { [weak self] x in
self?.debug("UIGestureRecognizer event \(x.state)")
}
.addDisposableTo(disposeBag)
// MARK: UITextView
// also test two way binding
let textViewValue = Variable("")
textView <-> textViewValue
textViewValue.asObservable()
.subscribeNext { [weak self] x in
self?.debug("UITextView text \(x)")
}
.addDisposableTo(disposeBag)
// MARK: CLLocationManager
#if !RX_NO_MODULE
manager.requestWhenInUseAuthorization()
#endif
manager.rx_didUpdateLocations
.subscribeNext { x in
print("rx_didUpdateLocations \(x)")
}
.addDisposableTo(disposeBag)
_ = manager.rx_didFailWithError
.subscribeNext { x in
print("rx_didFailWithError \(x)")
}
manager.rx_didChangeAuthorizationStatus
.subscribeNext { status in
print("Authorization status \(status)")
}
.addDisposableTo(disposeBag)
manager.startUpdatingLocation()
}
func debug(string: String) {
print(string)
debugLabel.text = string
}
}
|
apache-2.0
|
084162896bb74c458a6061982aa84014
| 23.466019 | 67 | 0.579563 | 5.460455 | false | false | false | false |
Bouke/HAP
|
Sources/HAP/Base/Predefined/Characteristics/Characteristic.Ping.swift
|
1
|
1969
|
import Foundation
public extension AnyCharacteristic {
static func ping(
_ value: Data = Data(),
permissions: [CharacteristicPermission] = [.read],
description: String? = "Ping",
format: CharacteristicFormat? = .data,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.ping(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func ping(
_ value: Data = Data(),
permissions: [CharacteristicPermission] = [.read],
description: String? = "Ping",
format: CharacteristicFormat? = .data,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<Data> {
GenericCharacteristic<Data>(
type: .ping,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
|
mit
|
c557fcff9afbcf6b3c7dd233e9af0ae0
| 31.278689 | 66 | 0.563738 | 5.439227 | false | false | false | false |
LoveAlwaysYoung/EnjoyUniversity
|
EnjoyUniversity/EnjoyUniversity/Classes/ViewModel/CommunityListViewModel.swift
|
1
|
4042
|
//
// CommunityListViewModel.swift
// EnjoyUniversity
//
// Created by lip on 17/3/30.
// Copyright © 2017年 lip. All rights reserved.
//
import Foundation
import YYModel
class CommunityListViewModel{
/// 我参加的社团视图模型列表
lazy var modelList = [CommunityViewModel]()
/// 我收藏的社团视图模型列表
lazy var collectedlist = [CommunityViewModel]()
/// 我搜索的社团视图模型列表
lazy var searchList = [CommunityViewModel]()
/// 加载社团列表
///
/// - Parameters:
/// - isPullUp: 是否为上拉加载更多
/// - completion: 完成回调
func loadCommunityList(isPullUp:Bool,completion:@escaping (Bool,Bool)->()){
var page = 1
let rows = EUREQUESTCOUNT
if isPullUp {
if modelList.count > 0 {
// swift 整数相处直接舍弃余数
page = modelList.count / rows + 1
}
}
EUNetworkManager.shared.getCommunityList(page: page,rows: rows) { (list, isSuccess) in
// 1.字典数组转模型数组
guard let modelArray = NSArray.yy_modelArray(with: Community.self, json: list ?? []) as? [Community] else{
completion(false,false)
return
}
if modelArray.count == 0{
completion(true,false)
return
}
var temp = [CommunityViewModel]()
for model in modelArray {
temp.append(CommunityViewModel(model: model))
}
if isPullUp {
self.modelList = self.modelList + temp
}else{
self.modelList = temp
}
completion(true,true)
}
}
/// 加载我收藏的社团列表
///
/// - Parameter completion: 完成回调
func loadMyCommunityCollection(completion:@escaping (Bool,Bool)->()){
EUNetworkManager.shared.getMyCommunityCollection { (isSuccess, array) in
if !isSuccess{
completion(false,false)
return
}
guard let array = array,let modelarray = NSArray.yy_modelArray(with: Community.self, json: array) as? [Community] else{
completion(true,false)
return
}
self.collectedlist.removeAll()
for model in modelarray{
self.collectedlist.append(CommunityViewModel(model: model))
}
completion(true,true)
}
}
/// 加载我搜索的社团列表
///
/// - Parameters:
/// - keyword: 关键字
/// - completion: 完成回调
func loadSearchedCommunity(keyword:String,isPullUp:Bool,completion:@escaping (Bool,Bool)->()){
var page = 1
let rows = EUREQUESTCOUNT
if isPullUp {
if searchList.count >= rows {
// swift 整数相处直接舍弃余数
page = searchList.count / rows + 1
}
}
EUNetworkManager.shared.searchCommunity(keyword: keyword, page: page, rows: rows) { (isSuccess, array) in
if !isSuccess{
completion(false,false)
return
}
guard let array = array,let modelarray = NSArray.yy_modelArray(with: Community.self, json: array) as? [Community] else{
completion(true,false)
return
}
var temp = [CommunityViewModel]()
for model in modelarray{
temp.append(CommunityViewModel(model: model))
}
if isPullUp{
self.searchList = self.searchList + temp
}else{
self.searchList = temp
}
completion(true,true)
}
}
}
|
mit
|
62b2e2a5da0ab1176e4a473a37503ce9
| 27.214815 | 131 | 0.503807 | 4.803279 | false | false | false | false |
RocAndTrees/DYLiveTelevision
|
LXLive/LXLive/Classes/Tools/Common.swift
|
1
|
319
|
//
// Common.swift
// LXLive
//
// Created by pxl on 2017/1/31.
// Copyright © 2017年 pxl. All rights reserved.
//
import UIKit
let kStatusBarH : CGFloat = 20
let kNavigationBarH : CGFloat = 44
let kTabbarH : CGFloat = 48
let kScreenW = UIScreen.main.bounds.width
let kScreenH = UIScreen.main.bounds.height
|
mit
|
ad567904c8957aa42472fcd38f250a4e
| 15.631579 | 47 | 0.702532 | 3.361702 | false | false | false | false |
EZ-NET/CodePiece
|
CodePiece/Controls/HashtagTextField.swift
|
1
|
1192
|
//
// HashtagTextField.swift
// CodePiece
//
// Created by Tomohiro Kumagai on H27/07/28.
// Copyright © 平成27年 EasyStyle G.K. All rights reserved.
//
import Cocoa
import ESTwitter
@objcMembers
final class HashtagTextField : NSTextField {
private var hashtagsBeforeEditing: HashtagSet = []
var hashtags: HashtagSet {
get {
return HashtagSet(hashtagsDisplayText: super.stringValue)
}
set (newHashtags) {
stringValue = newHashtags.sorted().twitterDisplayText
hashtagsBeforeEditing = newHashtags
HashtagsDidChangeNotification(hashtags: newHashtags).post()
}
}
override var stringValue: String {
set {
super.stringValue = newValue
}
get {
return hashtags.twitterDisplayText
}
}
override func textDidEndEditing(_ notification: Notification) {
// 表示のために代入し直して正規化します。
stringValue = hashtags.sorted().twitterDisplayText
super.textDidEndEditing(notification)
// 変更があった場合に限り通知します。
if hashtags != hashtagsBeforeEditing {
hashtagsBeforeEditing = hashtags
HashtagsDidChangeNotification(hashtags: hashtags).post()
}
}
}
|
gpl-3.0
|
3f7b11cc0a158703988d039c52808b59
| 17.245902 | 64 | 0.720575 | 3.811644 | false | false | false | false |
RocAndTrees/DYLiveTelevision
|
LXLive/LXLive/Classes/Tools/NetWorkTools.swift
|
1
|
890
|
//
// NetWorkTools.swift
// LXLive
//
// Created by pxl on 2017/2/6.
// Copyright © 2017年 pxl. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType {
case get
case post
}
class NetWorkTools {
class func requestData(_ type : MethodType, URLString : String, parameters: [String:String]? = nil, finishedCallback: @escaping (_ result: AnyObject)->()){
//1.获取类型
let method = type == .get ? HTTPMethod.get : HTTPMethod.post
//2.网络请求
Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
guard let result = response.result.value else{
print(response.result.error!)
return
}
finishedCallback(result as AnyObject)
}
}
}
|
mit
|
7aad07cb457bb31caf696b98ca1370a9
| 20.775 | 159 | 0.567164 | 4.632979 | false | false | false | false |
adib/Cheesy-Movies
|
BadFlix/Controllers/MovieDetailViewController.swift
|
1
|
8224
|
// Cheesy Movies
// Copyright (C) 2016 Sasmito Adibowo – http://cutecoder.org
// 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 UIKit
import SafariServices
import AlamofireImage
class MovieDetailViewController: UIViewController {
@IBOutlet weak var backdropImageView: UIImageView?
@IBOutlet weak var titleLabel: UILabel?
@IBOutlet weak var subtitleLabel: UILabel?
@IBOutlet weak var posterImageView: UIImageView?
@IBOutlet weak var summaryLabel: UILabel?
@IBOutlet weak var votesLabel: UILabel?
@IBOutlet weak var productionHouseLabel: UILabel!
@IBOutlet weak var trailerPlayButton: UIButton!
weak var castCollectionViewController : CastPhotoCollectionViewController?
var trailerViewController : SFSafariViewController?
lazy var runtimeFormatter = {
() -> DateComponentsFormatter in
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .abbreviated
formatter.allowedUnits = [.day,.hour,.minute]
return formatter
}()
lazy var yearFormatter = {
() -> DateFormatter in
let formatter = DateFormatter()
formatter.dateFormat = "yyyy"
return formatter
}()
var item : MovieEntity?
func reloadData() {
// TODO: add title year
if let title = item?.title,
let releaseDate = item?.releaseDate {
// have both date and year
let releaseDateStr = String(format: " (%@)", yearFormatter.string(from: releaseDate as Date))
let font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.title1)
let titleAttributes = [
NSFontAttributeName : font,
NSForegroundColorAttributeName : UIColor.black
]
let yearAttributes = [
NSFontAttributeName : font,
NSForegroundColorAttributeName : UIColor.darkGray
]
let attributedTitle = NSMutableAttributedString(string: title, attributes: titleAttributes)
attributedTitle.append(NSAttributedString(string:releaseDateStr,attributes:yearAttributes))
titleLabel?.attributedText = attributedTitle
} else {
titleLabel?.text = item?.title ?? ""
}
var subtitleText = String()
if let runtimeMinutes = item?.runtime {
if runtimeMinutes > 0 {
if let intervalText = runtimeFormatter.string(from: Double(runtimeMinutes) * 60) {
subtitleText += intervalText
}
}
}
if let genresArray = item?.genres {
if !subtitleText.isEmpty {
subtitleText += " | "
}
var genresStrings = Array<String>()
genresStrings.reserveCapacity(genresArray.count)
for genre in genresArray {
if let title = genre.title {
genresStrings.append(title)
}
}
subtitleText += genresStrings.joined(separator: ", ")
}
subtitleLabel?.text = subtitleText
summaryLabel?.text = item?.overview ?? ""
if let voteAverage = item?.voteAverage {
let crapLevel = Int(round((10 - voteAverage) * 10))
votesLabel?.text = NSString.localizedStringWithFormat(NSLocalizedString("🧀 %d%%", comment: "Crap Level Percentage") as NSString, crapLevel) as String
} else {
votesLabel?.text = "-"
}
productionHouseLabel?.text = item?.productionCompany ?? ""
trailerPlayButton?.isHidden = item?.trailerURLString == nil
if let castCtrl = castCollectionViewController {
castCtrl.item = item?.casts
castCtrl.reloadData()
}
}
func reloadImages() {
guard let item = self.item,
let window = self.view?.window else {
return
}
let nativeScale = window.screen.nativeScale
let rescaleSize = {
(size: CGSize)-> CGSize in
if nativeScale > 1 {
return CGSize(width: size.width * nativeScale, height: size.height * nativeScale)
}
return size
}
if let imageView = self.posterImageView,
let imageURL = item.posterURL(rescaleSize(imageView.bounds.size)) {
imageView.af_setImage(withURL: imageURL)
}
if let imageView = self.backdropImageView {
let posterImageViewSize = rescaleSize(imageView.bounds.size)
if let imageURL = item.backdropURL(posterImageViewSize) {
imageView.af_setImage(withURL: imageURL)
} else if let imageURL = item.posterURL(posterImageViewSize) {
imageView.af_setImage(withURL: imageURL)
}
}
if let castCtrl = castCollectionViewController {
castCtrl.setNeedsReloadImages()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let item = self.item {
reloadData()
item.refresh({
(error) in
guard error == nil else {
// TODO: report error
return
}
self.reloadData()
self.reloadImages()
})
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// image view sizes may have changed, thus an opportunity to get appropriately-sized images
reloadImages()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let segueIdentifier = segue.identifier
if segueIdentifier == "embedCastCollectionView" {
if let castCollectionCtrl = segue.destination as? CastPhotoCollectionViewController {
castCollectionViewController = castCollectionCtrl
castCollectionCtrl.item = item?.casts
}
}
}
// MARK: - Actions
@IBAction func showMovieTrailer(_ sender: AnyObject) {
// TODO: get the trailer URL from the movie
guard let urlString = item?.trailerURLString,
let targetURL = URL(string:urlString) else {
return
}
let safariCtrl = SFSafariViewController(url: targetURL, entersReaderIfAvailable: true)
self.present(safariCtrl, animated: true, completion: {
self.trailerViewController = safariCtrl
})
}
@IBAction func showActivities(_ sender: AnyObject) {
// TODO: get the URL from the movie (either IMDB or the movie's home page
guard let shareURLstring = item?.homepageURLString,
let shareURL = URL(string:shareURLstring) else {
return
}
let activityCtrl = UIActivityViewController(activityItems: [shareURL], applicationActivities: nil)
if let barButtonItem = sender as? UIBarButtonItem {
activityCtrl.modalPresentationStyle = .popover
activityCtrl.popoverPresentationController?.barButtonItem = barButtonItem
}
self.present(activityCtrl, animated: true, completion: nil)
}
}
|
gpl-3.0
|
15a305b8193bc210c36a94c743d97c4d
| 34.123932 | 161 | 0.603601 | 5.497659 | false | false | false | false |
pmlbrito/QuickShotUtils
|
QuickShotUtils/Classes/Extensions/UIImage+QSUAdditions.swift
|
1
|
1766
|
//
// UIImage+QSUAdditions.swift
// Pods
//
// Created by Pedro Brito on 22/06/16.
//
//
import UIKit
public extension UIImage {
public func imageRotatedByDegrees(degrees: CGFloat, flip: Bool) -> UIImage {
// let radiansToDegrees: (CGFloat) -> CGFloat = {
// return $0 * (180.0 / CGFloat(M_PI))
// }
let degreesToRadians: (CGFloat) -> CGFloat = {
return $0 / 180.0 * CGFloat(M_PI)
}
// calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox = UIView(frame: CGRect(origin: CGPoint(x:0, y:0), size: size))
let t = CGAffineTransform(rotationAngle: degreesToRadians(degrees));
rotatedViewBox.transform = t
let rotatedSize = rotatedViewBox.frame.size
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize)
let bitmap = UIGraphicsGetCurrentContext()
// Move the origin to the middle of the image so we will rotate and scale around the center.
bitmap!.translateBy(x: rotatedSize.width / 2.0, y: rotatedSize.height / 2.0);
// // Rotate the image context
bitmap!.rotate(by: degreesToRadians(degrees));
// Now, draw the rotated/scaled image into the context
var yFlip: CGFloat
if(flip){
yFlip = CGFloat(-1.0)
} else {
yFlip = CGFloat(1.0)
}
bitmap!.scaleBy(x: yFlip, y: -1.0)
// CGContextDrawImage(bitmap, CGRectMake(-size.width / 2, -size.height / 2, size.width, size.height), CGImage)
bitmap!.draw(self.cgImage!, in: CGRect(x: -size.width / 2,y: -size.height / 2,width: size.width,height: size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
|
mit
|
989df0ea7946ab528caff9d9fcd48938
| 29.448276 | 121 | 0.650623 | 3.986456 | false | false | false | false |
SeaHub/ImgTagging
|
ImgTagger/ImgTagger/SettingAvatarTableViewCell.swift
|
1
|
2115
|
//
// SettingAvatarTableViewCell.swift
// ImgTagger
//
// Created by SeaHub on 2017/6/30.
// Copyright © 2017年 SeaCluster. All rights reserved.
//
import UIKit
import Kingfisher
class SettingAvatarTableViewCell: UITableViewCell {
@IBOutlet weak var scoreDescrptionLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var avatarImageView: UIImageView!
func configureCell(userInfo: UserInfo) {
if let imageURL = userInfo.avatarURL {
let url = URL(string: "http://\(imageURL)")!
debugPrint(url)
_ = avatarImageView.kf.setImage(with: url,
placeholder: UIImage(named: "defaultAvatar"),
options: [.transition(ImageTransition.fade(1))],
progressBlock: nil,
completionHandler: nil)
} else {
avatarImageView.image = UIImage(named: "defaultAvatar")
}
let token = ImgTaggerUtil.userToken!
let subStringIndex = token.index(token.startIndex, offsetBy: 5)
self.usernameLabel.text = userInfo.name ?? token.substring(to: subStringIndex)
self.scoreLabel.text = "\(judgeLevel(score: userInfo.score!))\(userInfo.score!) Points"
self.scoreDescrptionLabel.text = "You have been tagged \(userInfo.finishNum!) photo(s)!"
}
func judgeLevel(score: Int) -> String {
if score > 10 {
return "Level 1 - "
} else if score > 20 {
return "Level 2 - "
} else if score > 40 {
return "Level 3 - "
} else if score > 80 {
return "Level 4 - "
} else if score > 160 {
return "Level 5 - "
}
return "Level 0 - "
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
|
gpl-3.0
|
d128975e48ad1bc10d154463bb246dd6
| 32.52381 | 105 | 0.5625 | 4.693333 | false | false | false | false |
milseman/swift
|
test/IDE/print_synthesized_extensions.swift
|
9
|
12752
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module-path %t/print_synthesized_extensions.swiftmodule -emit-module-doc -emit-module-doc-path %t/print_synthesized_extensions.swiftdoc %s
// RUN: %target-swift-ide-test -print-module -annotate-print -synthesize-extension -print-interface -no-empty-line-between-members -module-to-print=print_synthesized_extensions -I %t -source-filename=%s > %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK1 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK2 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK3 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK4 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK5 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK6 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK7 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK8 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK9 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK10 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK11 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK12 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK13 < %t.syn.txt
// RUN: %FileCheck %s -check-prefix=CHECK14 < %t.syn.txt
public protocol P1 {
associatedtype T1
associatedtype T2
func f1(t : T1) -> T1
func f2(t : T2) -> T2
}
public extension P1 where T1 == Int {
func p1IntFunc(i : Int) -> Int {return 0}
}
public extension P1 where T1 : P3 {
func p3Func(i : Int) -> Int {return 0}
}
public protocol P2 {
associatedtype P2T1
}
public extension P2 where P2T1 : P2{
public func p2member() {}
}
public protocol P3 {}
public extension P1 where T1 : P2 {
public func ef1(t : T1) {}
public func ef2(t : T2) {}
}
public extension P1 where T1 == P2, T2 : P3 {
public func ef3(t : T1) {}
public func ef4(t : T1) {}
}
public extension P1 where T2 : P3 {
public func ef5(t : T2) {}
}
public struct S2 {}
public struct S1<T> : P1, P2 {
public typealias T1 = T
public typealias T2 = S2
public typealias P2T1 = T
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
public struct S3<T> : P1 {
public typealias T1 = (T, T)
public typealias T2 = (T, T)
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
public struct S4<T> : P1 {
public typealias T1 = Int
public typealias T2 = Int
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
public struct S5 : P3 {}
public struct S6<T> : P1 {
public typealias T1 = S5
public typealias T2 = S5
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
public extension S6 {
public func f3() {}
}
public struct S7 {
public struct S8 : P1 {
public typealias T1 = S5
public typealias T2 = S5
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
}
public extension P1 where T1 == S9<Int> {
public func S9IntFunc() {}
}
public struct S9<T> : P3 {}
public struct S10 : P1 {
public typealias T1 = S9<Int>
public typealias T2 = S9<Int>
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
public protocol P4 {}
/// Extension on P4Func1
public extension P4 {
func P4Func1() {}
}
/// Extension on P4Func2
public extension P4 {
func P4Func2() {}
}
public struct S11 : P4 {}
public extension S6 {
public func fromActualExtension() {}
}
public protocol P5 {
associatedtype T1
/// This is picked
func foo1()
}
public extension P5 {
/// This is not picked
public func foo1() {}
}
public extension P5 where T1 == Int {
/// This is picked
public func foo2() {}
}
public extension P5 {
/// This is not picked
public func foo2() {}
}
public extension P5 {
/// This is not picked
public func foo3() {}
}
public extension P5 where T1 : Comparable{
/// This is picked
public func foo3() {}
}
public extension P5 where T1 : Comparable {
/// This is picked
public func foo4() {}
}
public extension P5 where T1 : AnyObject {
/// This should not crash
public func foo5() {}
}
public extension P5 {
/// This is not picked
public func foo4() {}
}
public struct S12 : P5{
public typealias T1 = Int
public func foo1() {}
}
public protocol P6 {
func foo1()
func foo2()
}
public extension P6 {
public func foo1() {}
}
public protocol P7 {
associatedtype T1
func f1(t: T1)
}
public extension P7 {
public func nomergeFunc(t: T1) -> T1 { return t }
public func f1(t: T1) -> T1 { return t }
}
public struct S13 {}
extension S13 : P5 {
public typealias T1 = Int
public func foo1() {}
}
// CHECK1: <synthesized>extension <ref:Struct>S1</ref> where T : <ref:Protocol>P2</ref> {
// CHECK1-NEXT: <decl:Func>public func <loc>p2member()</loc></decl>
// CHECK1-NEXT: <decl:Func>public func <loc>ef1(<decl:Param>t: T</decl>)</loc></decl>
// CHECK1-NEXT: <decl:Func>public func <loc>ef2(<decl:Param>t: <ref:Struct>S2</ref></decl>)</loc></decl>
// CHECK1-NEXT: }</synthesized>
// CHECK2: <synthesized>extension <ref:Struct>S1</ref> where T : <ref:Protocol>P3</ref> {
// CHECK2-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
// CHECK2-NEXT: }</synthesized>
// CHECK3: <synthesized>extension <ref:Struct>S1</ref> where T == <ref:Struct>Int</ref> {
// CHECK3-NEXT: <decl:Func>public func <loc>p1IntFunc(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
// CHECK3-NEXT: }</synthesized>
// CHECK4: <synthesized>extension <ref:Struct>S1</ref> where T == <ref:Struct>S9</ref><<ref:Struct>Int</ref>> {
// CHECK4-NEXT: <decl:Func>public func <loc>S9IntFunc()</loc></decl>
// CHECK4-NEXT: }</synthesized>
// CHECK5: <decl:Struct>public struct <loc>S10</loc> : <ref:Protocol>P1</ref> {
// CHECK5-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S9</ref><<ref:Struct>Int</ref>></decl>
// CHECK5-NEXT: <decl:TypeAlias>public typealias <loc>T2</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S9</ref><<ref:Struct>Int</ref>></decl>
// CHECK5-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T1</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T1</ref></decl>
// CHECK5-NEXT: <decl:Func>public func <loc>f2(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T2</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T2</ref></decl></decl>
// CHECK5-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
// CHECK5-NEXT: <decl:Func>public func <loc>ef5(<decl:Param>t: <ref:Struct>S9</ref><<ref:Struct>Int</ref>></decl>)</loc></decl>
// CHECK5-NEXT: <decl:Func>public func <loc>S9IntFunc()</loc></decl>
// CHECK5-NEXT: }</synthesized>
// CHECK6: <synthesized>/// Extension on P4Func1
// CHECK6-NEXT: extension <ref:Struct>S11</ref> {
// CHECK6-NEXT: <decl:Func>public func <loc>P4Func1()</loc></decl>
// CHECK6-NEXT: }</synthesized>
// CHECK7: <synthesized>/// Extension on P4Func2
// CHECK7-NEXT: extension <ref:Struct>S11</ref> {
// CHECK7-NEXT: <decl:Func>public func <loc>P4Func2()</loc></decl>
// CHECK7-NEXT: }</synthesized>
// CHECK8: <decl:Struct>public struct <loc>S4<<decl:GenericTypeParam>T</decl>></loc> : <ref:Protocol>P1</ref> {
// CHECK8-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:Struct>Int</ref></decl>
// CHECK8-NEXT: <decl:TypeAlias>public typealias <loc>T2</loc> = <ref:Struct>Int</ref></decl>
// CHECK8-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref>.<ref:TypeAlias>T1</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref>.<ref:TypeAlias>T1</ref></decl>
// CHECK8-NEXT: <decl:Func>public func <loc>f2(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref>.<ref:TypeAlias>T2</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref>.<ref:TypeAlias>T2</ref></decl></decl>
// CHECK8-NEXT: <decl:Func>public func <loc>p1IntFunc(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
// CHECK8-NEXT: }</synthesized>
// CHECK9: <decl:Struct>public struct <loc>S6<<decl:GenericTypeParam>T</decl>></loc> : <ref:Protocol>P1</ref> {
// CHECK9-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S5</ref></decl>
// CHECK9-NEXT: <decl:TypeAlias>public typealias <loc>T2</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S5</ref></decl>
// CHECK9-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref>.<ref:TypeAlias>T1</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref>.<ref:TypeAlias>T1</ref></decl>
// CHECK9-NEXT: <decl:Func>public func <loc>f2(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref>.<ref:TypeAlias>T2</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref>.<ref:TypeAlias>T2</ref></decl></decl>
// CHECK9-NEXT: <decl:Extension><decl:Func>public func <loc>f3()</loc></decl></decl>
// CHECK9-NEXT: <decl:Extension><decl:Func>public func <loc>fromActualExtension()</loc></decl></decl>
// CHECK9-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
// CHECK9-NEXT: <decl:Func>public func <loc>ef5(<decl:Param>t: <ref:Struct>S5</ref></decl>)</loc></decl>
// CHECK9-NEXT: }</synthesized>
// CHECK10: <synthesized>extension <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S7</ref>.<ref:Struct>S8</ref> {
// CHECK10-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl>
// CHECK10-NEXT: <decl:Func>public func <loc>ef5(<decl:Param>t: <ref:Struct>S5</ref></decl>)</loc></decl>
// CHECK10-NEXT: }</synthesized>
// CHECK11: <decl:Struct>public struct <loc>S12</loc> : <ref:Protocol>P5</ref> {
// CHECK11-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:Struct>Int</ref></decl>
// CHECK11-NEXT: <decl:Func>/// This is picked
// CHECK11-NEXT: public func <loc>foo1()</loc></decl></decl>
// CHECK11-NEXT: <decl:Func>/// This is picked
// CHECK11-NEXT: public func <loc>foo2()</loc></decl>
// CHECK11-NEXT: <decl:Func>/// This is picked
// CHECK11-NEXT: public func <loc>foo3()</loc></decl>
// CHECK11-NEXT: <decl:Func>/// This is picked
// CHECK11-NEXT: public func <loc>foo4()</loc></decl>
// CHECK11-NEXT: <decl:Func>/// This should not crash
// CHECK11-NEXT: public func <loc>foo5()</loc></decl>
// CHECK11-NEXT: }</synthesized>
// CHECK12: <decl:Protocol>public protocol <loc>P6</loc> {
// CHECK12-NEXT: <decl:Func(HasDefault)>public func <loc>foo1()</loc></decl>
// CHECK12-NEXT: <decl:Func>public func <loc>foo2()</loc></decl>
// CHECK12-NEXT: }</decl>
// CHECK13: <decl:Protocol>public protocol <loc>P7</loc> {
// CHECK13-NEXT: <decl:AssociatedType>associatedtype <loc>T1</loc></decl>
// CHECK13-NEXT: <decl:Func(HasDefault)>public func <loc>f1(<decl:Param>t: <ref:GenericTypeParam>Self</ref>.T1</decl>)</loc></decl>
// CHECK13-NEXT: }</decl>
// CHECK13: <decl:Extension>extension <loc><ref:Protocol>P7</ref></loc> {
// CHECK13-NEXT: <decl:Func>public func <loc>nomergeFunc(<decl:Param>t: <ref:GenericTypeParam>Self</ref>.T1</decl>)</loc> -> <ref:GenericTypeParam>Self</ref>.T1</decl>
// CHECK13-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:GenericTypeParam>Self</ref>.T1</decl>)</loc> -> <ref:GenericTypeParam>Self</ref>.T1</decl>
// CHECK13-NEXT: }</decl>
// CHECK14: <decl:Struct>public struct <loc>S13</loc> {</decl>
// CHECK14-NEXT: <decl:Func>/// This is picked
// CHECK14-NEXT: public func <loc>foo2()</loc></decl>
// CHECK14-NEXT: <decl:Func>/// This is picked
// CHECK14-NEXT: public func <loc>foo3()</loc></decl>
// CHECK14-NEXT: <decl:Func>/// This is picked
// CHECK14-NEXT: public func <loc>foo4()</loc></decl>
// CHECK14-NEXT: <decl:Func>/// This should not crash
// CHECK14-NEXT: public func <loc>foo5()</loc></decl>
// CHECK14-NEXT: }</synthesized>
|
apache-2.0
|
eeee167b1e4adfa39558a13442945b5f
| 36.505882 | 279 | 0.655427 | 2.812528 | false | false | false | false |
tristanchu/FlavorFinder
|
FlavorFinder/FlavorFinder/RegisterView.swift
|
1
|
7039
|
//
// RegisterView.swift
// FlavorFinder
//
// Handles the register view for within the container
//
// Created by Courtney Ligh on 2/1/16.
// Copyright © 2016 TeamFive. All rights reserved.
//
import Foundation
import UIKit
import Parse
class RegisterView : UIViewController, UITextFieldDelegate {
// Navigation in containers (set during segue)
var buttonSegue : String!
// MARK: messages ------------------------------------
// validation error messages
let EMAIL_INVALID = "That doesn't look like an email!"
let USERNAME_INVALID = "Usernames must be between \(USERNAME_CHAR_MIN) and \(USERNAME_CHAR_MAX) characters."
let PASSWORD_INVALID = "Passwords must be between \(PASSWORD_CHAR_MIN) and \(PASSWORD_CHAR_MAX) characters."
let PW_MISMATCH = "Passwords don't match!"
let MULTIPLE_INVALID = "Please fix errors and resubmit."
// request error messages
let REQUEST_ERROR_TITLE = "Uhoh!"
let GENERIC_ERROR = "Oops! An error occurred on the server. Please try again."
let USERNAME_IN_USE = "That username is already in use. Please pick a new one!"
let EMAIL_IN_USE = "Email already associated with an account!"
// Toast Text:
let REGISTERED_MSG = "Registed new user " // + username dynamically
// MARK: Properties -----------------------------------
// Text Labels:
@IBOutlet weak var signUpPromptLabel: UILabel!
@IBOutlet weak var warningTextLabel: UILabel!
// Text Fields:
@IBOutlet weak var usernameSignUpField: UITextField!
@IBOutlet weak var pwSignUpField: UITextField!
@IBOutlet weak var retypePwSignUpField: UITextField!
@IBOutlet weak var emailSignUpField: UITextField!
// Buttons (for UI)
@IBOutlet weak var backToLoginButton: UIButton!
@IBOutlet weak var createAccountButton: UIButton!
let backBtnString =
String.fontAwesomeIconWithName(.ChevronLeft) + " Back to login"
// MARK: Actions -----------------------------------
@IBAction func createAccountAction(sender: AnyObject) {
if (emailSignUpField.text != nil && usernameSignUpField.text != nil &&
pwSignUpField.text != nil && retypePwSignUpField.text != nil) {
// Make request:
requestNewUser(emailSignUpField.text!,
username: usernameSignUpField.text!,
password: pwSignUpField.text!,
pwRetyped: retypePwSignUpField.text!)
// request new user calls on success
}
}
@IBAction func backToLoginAction(sender: AnyObject) {
if let parent = parentViewController as? ContainerViewController {
parent.segueIdentifierReceivedFromParent(buttonSegue)
}
}
// MARK: Override Functions --------------------------
/* viewDidLoad
called when app first loads view
*/
override func viewDidLoad() {
super.viewDidLoad()
// Set font awesome chevron:
backToLoginButton.setTitle(backBtnString, forState: .Normal)
// set up text fields:
setUpTextField(usernameSignUpField)
setUpTextField(pwSignUpField)
setUpTextField(retypePwSignUpField)
setUpTextField(emailSignUpField)
// set border button:
setDefaultButtonUI(createAccountButton)
}
// MARK: Functions ------------------------------------
/* setUpTextField
assigns delegate, sets left padding to 5
*/
func setUpTextField(field: UITextField) {
field.delegate = self
field.setTextLeftPadding(5)
}
/* requestNewUser
requests that Parse creates a new user
*/
func requestNewUser(email: String, username: String, password: String, pwRetyped: String) -> PFUser? {
if fieldsAreValid(email, username: username, password: password, pwRetyped: pwRetyped) {
let newUser = PFUser()
newUser.username = username
newUser.email = email
newUser.password = password
newUser.signUpInBackgroundWithBlock { (succeeded, error) -> Void in
if error == nil {
if succeeded {
self.registerSuccess(newUser)
} else {
self.handleError(error)
}
} else {
self.handleError(error)
}
}
return newUser
}
return nil
}
/* fieldsAreValid
checks if entered fields are valid input
*/
func fieldsAreValid(email: String, username: String, password: String, pwRetyped: String) -> Bool {
if isInvalidUsername(username) {
alertUserBadInput(USERNAME_INVALID)
return false
}
if isInvalidPassword(password) {
alertUserBadInput(PASSWORD_INVALID)
return false
}
if pwRetyped.isEmpty {
alertUserBadInput(PW_MISMATCH)
return false
}
if password != pwRetyped {
alertUserBadInput(PW_MISMATCH)
return false
}
if isInvalidEmail(email) {
alertUserBadInput( EMAIL_INVALID)
return false
}
return true
}
/* registerSuccess
actually registers user
*/
func registerSuccess(user: PFUser) {
setUserSession(user)
if let parentVC = self.parentViewController?.parentViewController as! LoginModuleParentViewController? {
if isUserLoggedIn() {
let registeredMsg = self.REGISTERED_MSG + "\(currentUser!.username!)"
parentVC.view.makeToast(registeredMsg, duration: TOAST_DURATION, position: .Bottom)
}
parentVC.loginSucceeded()
}
}
/* handleError
let us know if there is a parse error
*/
func handleError(error: NSError?) {
if let error = error {
print("\(error)")
// error - username already in use:
if error.code == 202 {
alertUserRegisterError(USERNAME_IN_USE)
// error - email already in use
} else if error.code == 203 {
alertUserRegisterError(EMAIL_IN_USE)
// error - generic error
} else {
alertUserRegisterError(GENERIC_ERROR)
}
} else {
print("nil error")
}
}
/* alertUserBadInput
creates popup alert for when user submits bad input
- helper function to make above code cleaner:
*/
func alertUserBadInput(title: String) {
alertPopup(title, msg: self.MULTIPLE_INVALID,
actionTitle: OK_TEXT, currController: self)
}
/* alertUserRegisterError
- helper function to create alert when parse rejects registration
*/
func alertUserRegisterError(msg: String){
alertPopup(self.REQUEST_ERROR_TITLE , msg: msg,
actionTitle: OK_TEXT, currController: self)
}
}
|
mit
|
e763b96f698118ce1db154cfd0d48eac
| 32.674641 | 112 | 0.595482 | 4.932025 | false | false | false | false |
crxiaoluo/DouYuZhiBo
|
DYZB/DYZB/Class/Tools/Swift+Extension/UI/UIImage+CRAdd.swift
|
1
|
7022
|
//
// UIImage+Extension.swift
// Swift图形圆角处理
//
// Created by Apple on 16/5/6.
// Copyright © 2016年 Apple. All rights reserved.
//
import UIKit
extension UIImage{
func cr_setCornerRadius(_ radius: CGFloat,
imageSize: CGSize,
fillColor: UIColor = UIColor.white,
lineWidth: CGFloat = 0.0,
lineColor:UIColor = UIColor.gray,
opaque: Bool = true
) ->UIImage
{
//开启上下文
UIGraphicsBeginImageContextWithOptions(imageSize, opaque, 0.0)
guard let content = UIGraphicsGetCurrentContext() else { return self }
//将当前图形状态推入堆栈
content.saveGState()
let rect = CGRect(origin: CGPoint(x: 0, y: 0) , size: imageSize)
content.scaleBy(x: 1, y: -1)
content.translateBy(x: 0, y: -imageSize.height)
let roundedRect = rect.insetBy(dx: lineWidth * 0.5, dy: lineWidth * 0.5)
//设置贝塞尔曲线
let path = UIBezierPath(roundedRect: roundedRect, byRoundingCorners: .allCorners , cornerRadii: CGSize(width: radius, height: lineWidth))
path.close()
if opaque == true {
fillColor.setFill()
UIRectFill(rect)
}
if lineWidth != 0 {
path.lineWidth = lineWidth
lineColor.set()
path.stroke()
}
path.addClip()
if let cgImage = self.cgImage {
content.draw(cgImage, in: rect)
}
//离开堆栈
content.restoreGState()
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
return self
}
//结束上下文
UIGraphicsEndImageContext()
return image
}
}
extension UIImage{
func cr_setCornerRadiusByAsync(_ radius: CGFloat,
imageSize: CGSize,
fillColor: UIColor = UIColor.white,
lineWidth: CGFloat = 0.0,
lineColor:UIColor = UIColor.gray,
opaque: Bool = true,
finished:@escaping (_ image: UIImage)->() )
{
DispatchQueue.global().async {
//开启上下文
UIGraphicsBeginImageContextWithOptions(imageSize, true, 0.0)
guard let content = UIGraphicsGetCurrentContext() else { return }
//将当前图形状态推入堆栈
content.saveGState()
let rect = CGRect(origin: CGPoint(x: 0, y: 0) , size: imageSize)
content.scaleBy(x: 1, y: -1)
content.translateBy(x: 0, y: -imageSize.height)
let roundedRect = rect.insetBy(dx: lineWidth * 0.5, dy: lineWidth * 0.5)
//设置贝塞尔曲线
let path = UIBezierPath(roundedRect: roundedRect, byRoundingCorners: .allCorners , cornerRadii: CGSize(width: radius, height: lineWidth))
path.close()
if opaque == true {
fillColor.setFill()
UIRectFill(rect)
}
if lineWidth != 0 {
path.lineWidth = lineWidth
lineColor.set()
path.stroke()
}
path.addClip()
if let cgImage = self.cgImage {
content.draw(cgImage, in: rect)
}
//离开堆栈
content.restoreGState()
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
return
}
//结束上下文
UIGraphicsEndImageContext()
DispatchQueue.main.async {
finished(image)
}
}
}
}
/*
绘图第一篇 CGContextSaveGState与CGContextRestoreGState
Push a copy of the current graphics state onto the graphics state stack. Note that the path is not considered part of the graphics state, and is not saved.
说的是什么呢?意思就是说把当前的图形上下文拷贝到图形状态栈中。一个??就是路径是不会被copy进去的,当然更不会被保存下来了。
CGContextSaveGState函数的作用是将当前图形状态推入堆栈。之后,您对图形状态所做的修改会影响随后的描画操作,但不影响存储在堆栈中的拷贝。在修改完成后。
Quartz removes the graphics state that is at the top of the stack so that the most recently saved state becomes the current graphics state.
您可以通过CGContextRestoreGState函数把堆栈顶部的状态弹出,返回最新保存的图形状态。这种推入和弹出的方式是回到之前图形状态的快速方法,避免逐个撤消所有的状态修改;这也是将某些状态(比如裁剪路径)恢复到原有设置的唯一方式。简单理解就是save就是每调用一下就保存下档前的上下文,restore就是取出来当前的图形上下文。
什么时候用呢?
肯定不是你就画一个矩形,画条线的时候用,是在我们想要画比较复杂的图形,对于我们的创建的图形上下文来说,显然改图形上下文(context)的状态将会被多次改变,后面的绘制将对前面的绘制造成影响
(因为图形上下文的对象只有一个,每次通过CGContext命令的时候, 都是不断在修改图形上下文的属性,这个属性对于图形上下文来讲,就是唯一的,比如说设置线段的粗细为1,那么此刻图形上下文里 所有的线段 都是1粗细)*
对此,苹果设置一个保存图形上下文的栈,来随时存储当前你的图形上下文
通过CGContextSaveGState(context);
来保存(推入)图形上下文到栈顶
在绘制(渲染之后),通过CGContextRestoreGState(context);
来更新(将之前入栈的图形上下文状态出栈,将当前的图形上下文状态入栈)图形上下到栈顶
注意:这两个代码一般成对出现, 这样既保护了图形上下文状态的唯一性,也方便了在需要的地方修改图形上下状态
大概,就是这么个意思吧,欢迎补充指正
总结:
绘图的一般流程:
1. 获取当前的图形上下文
CGContextRef context = UIGraphicsGetCurrentContext();
2. 保存当前图形上下文(入栈)
CGContextSaveGState(context);
3.设置上下文状态;
4.绘制(渲染);
5.更新图形上下文,也就是说拿到最新的
CGContextRestoreGState(context);
*/
|
mit
|
a070be40acf5122109986fa9322627e8
| 26.984925 | 170 | 0.546777 | 4.257645 | false | false | false | false |
superk589/CGSSGuide
|
DereGuide/View/WideLoadingButton.swift
|
2
|
1980
|
//
// WideLoadingButton.swift
// DereGuide
//
// Created by zzk on 2017/8/19.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
class WideLoadingButton: WideButton {
private(set) var isLoading = false
let indicator = UIActivityIndicatorView(style: .white)
var normalTitle = "" {
didSet {
if !isLoading {
setTitle(normalTitle, for: .normal)
}
}
}
var loadingTitle = "" {
didSet {
if isLoading {
setTitle(loadingTitle, for: .normal)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
indicator.hidesWhenStopped = true
addSubview(indicator)
if titleLabel != nil {
indicator.snp.makeConstraints { (make) in
make.right.equalTo(titleLabel!.snp.left)
make.centerY.equalToSuperview()
}
} else {
indicator.snp.makeConstraints { (make) in
make.center.equalToSuperview()
}
}
indicator.isHidden = true
}
func setup(normalTitle: String, loadingTitle: String) {
self.normalTitle = normalTitle
self.loadingTitle = loadingTitle
}
func setLoading(_ isLoading: Bool) {
self.isLoading = isLoading
if isLoading {
isUserInteractionEnabled = false
setTitle(loadingTitle, for: .normal)
indicator.startAnimating()
indicator.isHidden = false
titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
} else {
isUserInteractionEnabled = true
setTitle(normalTitle, for: .normal)
indicator.stopAnimating()
titleEdgeInsets = .zero
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
d1f4d49c7ea705174b989d50b23ca280
| 25.039474 | 81 | 0.548762 | 4.935162 | false | false | false | false |
PopcornTimeTV/PopcornTimeTV
|
PopcornKit/Models/Actor.swift
|
1
|
2378
|
import Foundation
import ObjectMapper
/**
Struct for managing actor objects.
*/
public struct Actor: Person, Equatable {
/// Name of the actor.
public let name: String
/// Name of the character the actor played in a movie/show.
public let characterName: String
/// Imdb id of the actor.
public let imdbId: String
/// TMDB id of the actor.
public let tmdbId: Int
/// If headshot image is available, it is returned with size 1000*1500.
public var largeImage: String?
/// If headshot image is available, it is returned with size 600*900.
public var mediumImage: String? {
return largeImage?.replacingOccurrences(of: "original", with: "w500")
}
/// If headshot image is available, it is returned with size 300*450.
public var smallImage: String? {
return largeImage?.replacingOccurrences(of: "original", with: "w300")
}
public init?(map: Map) {
do { self = try Actor(map) }
catch { return nil }
}
private init(_ map: Map) throws {
self.name = try map.value("person.name")
self.characterName = try map.value("character")
self.largeImage = try? map.value("person.images.headshot.full")
self.imdbId = try map.value("person.ids.imdb")
self.tmdbId = try map.value("person.ids.tmdb")
}
public init(name: String = "Unknown", imdbId: String = "nm0000000", tmdbId: Int = 0000000, largeImage: String? = nil) {
self.name = name
self.characterName = ""
self.largeImage = largeImage
self.imdbId = imdbId
self.tmdbId = tmdbId
}
public mutating func mapping(map: Map) {
switch map.mappingType {
case .fromJSON:
if let actor = Actor(map: map) {
self = actor
}
case .toJSON:
name >>> map["person.name"]
characterName >>> map["character"]
largeImage >>> map["person.images.headshot.full"]
imdbId >>> map["person.ids.imdb"]
tmdbId >>> map["person.ids.tmdb"]
}
}
}
// MARK: - Hashable
extension Actor: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(imdbId.hashValue)
}
}
// MARK: Equatable
public func ==(rhs: Actor, lhs: Actor) -> Bool {
return rhs.imdbId == lhs.imdbId
}
|
gpl-3.0
|
ae7bd5755c5a075619e8f2005f53def0
| 28.358025 | 123 | 0.598823 | 4.107081 | false | false | false | false |
skedgo/tripkit-ios
|
Examples/MiniMap/MiniMap/ViewController.swift
|
1
|
3339
|
//
// ViewController.swift
// MiniMap
//
// Created by Adrian Schoenig on 7/7/17.
// Copyright © 2017 SkedGo Pty Ltd. All rights reserved.
//
import Cocoa
import MapKit
import TripKit
class ViewController: NSViewController {
@IBOutlet weak var mapView: MKMapView!
var from: MKAnnotation? = nil
var to: MKAnnotation? = nil
let router = TKRouter()
override func viewDidLoad() {
super.viewDidLoad()
let presser = NSPressGestureRecognizer(target: self, action: #selector(pressTriggered))
presser.minimumPressDuration = 1
mapView.addGestureRecognizer(presser)
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
@objc
func pressTriggered(_ recognizer: NSPressGestureRecognizer) {
guard recognizer.state == .began else { return }
let isFrom = from == nil
let point: NSPoint = recognizer.location(in: mapView)
let coordinate = mapView.convert(point, toCoordinateFrom: mapView)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = isFrom ? "Start" : "End"
if isFrom {
if let oldFrom = from {
mapView.removeAnnotation(oldFrom)
}
from = annotation
} else {
if let oldTo = to {
mapView.removeAnnotation(oldTo)
}
to = annotation
}
mapView.addAnnotation(annotation)
route()
}
func route() {
guard let from = from, let to = to else { return }
router.modeIdentifiers = [
TKTransportMode.publicTransport.modeIdentifier
]
let query = TKRouter.RoutingQuery(
from: from, to: to, at: .leaveASAP, modes: [
"pt_pub"], context: TripKit.shared.tripKitContext
)
router.fetchBestTrip(for: query) { result in
switch result {
case .success(let trip):
for segment in trip.segments {
guard segment.hasVisibility(.onMap) else { continue }
self.mapView.addAnnotation(segment)
for shape in segment.shapes {
guard let polyline = TKRoutePolyline(route: shape) else { continue }
self.mapView.addOverlay(polyline)
}
}
case .failure(let error):
print("Error \(error)")
}
}
}
}
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let pinView: MKPinAnnotationView
if let reused = mapView.dequeueReusableAnnotationView(withIdentifier: "pinView") as? MKPinAnnotationView {
reused.annotation = annotation
pinView = reused
} else {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pinView")
}
pinView.animatesDrop = true
pinView.isDraggable = true
pinView.pinTintColor = annotation.title! == "Start" ? .green : .red
pinView.canShowCallout = true
return pinView
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if let polyline = overlay as? TKRoutePolyline {
let renderer = MKPolylineRenderer(polyline: polyline)
renderer.lineWidth = 10
renderer.strokeColor = polyline.route.routeColor
return renderer
} else {
return MKOverlayRenderer(overlay: overlay)
}
}
}
|
apache-2.0
|
c08027818f31e7ce70ce1f3381dc0f2e
| 25.283465 | 110 | 0.656381 | 4.629681 | false | false | false | false |
steve-holmes/music-app-2
|
MusicApp/Modules/Online/Views/DetailInitialActivityIndicatorView.swift
|
1
|
2447
|
//
// DetailInitialActivityIndicatorView.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/19/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
class DetailInitialActivityIndicatorView: UIView {
fileprivate var indicatorView: NVActivityIndicatorView!
fileprivate(set) weak var sourceView: UIView?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
private func configure() {
indicatorView = NVActivityIndicatorView(
frame: CGRect(x: 0, y: 0, width: 30, height: 30),
type: .lineScale,
color: .toolbarImage,
padding: nil
)
indicatorView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(indicatorView)
let size: CGFloat = 30
NSLayoutConstraint.activate([
indicatorView.centerXAnchor.constraint(equalTo: centerXAnchor),
indicatorView.centerYAnchor.constraint(equalTo: centerYAnchor),
indicatorView.widthAnchor.constraint(equalToConstant: size),
indicatorView.heightAnchor.constraint(equalToConstant: size)
])
self.layoutIfNeeded()
}
}
extension DetailInitialActivityIndicatorView {
func startAnimating(in view: UIView?) {
let sourceView = view ?? getWindow()
self.sourceView = sourceView
self.translatesAutoresizingMaskIntoConstraints = false
sourceView.addSubview(self)
NSLayoutConstraint.activate([
leadingAnchor.constraint(equalTo: sourceView.leadingAnchor),
trailingAnchor.constraint(equalTo: sourceView.trailingAnchor),
bottomAnchor.constraint(equalTo: sourceView.bottomAnchor),
heightAnchor.constraint(equalTo: sourceView.heightAnchor, multiplier: 2.0/3.0)
])
sourceView.layoutIfNeeded()
indicatorView.startAnimating()
}
func stopAnimating() {
indicatorView.stopAnimating()
self.removeFromSuperview()
}
private func getWindow() -> UIView {
let applicationDelegate = UIApplication.shared.delegate as! AppDelegate
return applicationDelegate.window!
}
}
|
mit
|
244bc32df859d517f9639c79e9d1275b
| 28.071429 | 90 | 0.640868 | 5.71897 | false | false | false | false |
finder39/Swignals
|
Source/Swignal4Args.swift
|
1
|
1660
|
//
// Swignal4Args.swift
// Plug
//
// Created by Joseph Neuman on 7/6/16.
// Copyright © 2016 Plug. All rights reserved.
//
import Foundation
open class Swignal4Args<A,B,C,D>: SwignalBase {
public override init() {
}
open func addObserver<L: AnyObject>(_ observer: L, callback: @escaping (_ observer: L, _ arg1: A, _ arg2: B, _ arg3: C, _ arg4: D) -> ()) {
let observer = Observer4Args(swignal: self, observer: observer, callback: callback)
addSwignalObserver(observer)
}
open func fire(_ arg1: A, arg2: B, arg3: C, arg4: D) {
synced(self) {
for watcher in self.swignalObservers {
watcher.fire(arg1, arg2, arg3, arg4)
}
}
}
}
private class Observer4Args<L: AnyObject,A,B,C,D>: ObserverGenericBase<L> {
let callback: (_ observer: L, _ arg1: A, _ arg2: B, _ arg3: C, _ arg4: D) -> ()
init(swignal: SwignalBase, observer: L, callback: @escaping (_ observer: L, _ arg1: A, _ arg2: B, _ arg3: C, _ arg4: D) -> ()) {
self.callback = callback
super.init(swignal: swignal, observer: observer)
}
override func fire(_ args: Any...) {
if let arg1 = args[0] as? A,
let arg2 = args[1] as? B,
let arg3 = args[2] as? C,
let arg4 = args[3] as? D {
fire(arg1: arg1, arg2: arg2, arg3: arg3, arg4: arg4)
} else {
assert(false, "Types incorrect")
}
}
fileprivate func fire(arg1: A, arg2: B, arg3: C, arg4: D) {
if let observer = observer {
callback(observer, arg1, arg2, arg3, arg4)
}
}
}
|
mit
|
ace54959ee6b7b95507fadb95cb8204b
| 29.722222 | 143 | 0.545509 | 3.166031 | false | false | false | false |
cooliean/CLLKit
|
XLForm/Examples/Swift/SwiftExample/Dates/DatesFormViewController.swift
|
13
|
6320
|
//
// DatesFormViewController.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
class DatesFormViewController: XLFormViewController {
private struct Tags {
static let DateInline = "dateInline"
static let TimeInline = "timeInline"
static let DateTimeInline = "dateTimeInline"
static let CountDownTimerInline = "countDownTimerInline"
static let DatePicker = "datePicker"
static let Date = "date"
static let Time = "time"
static let DateTime = "dateTime"
static let CountDownTimer = "countDownTimer"
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
initializeForm()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeForm()
}
override func viewDidLoad() {
super.viewDidLoad()
let barButton = UIBarButtonItem(title: "Disable", style: .Plain, target: self, action: "disableEnable:")
barButton.possibleTitles = Set(["Disable", "Enable"])
navigationItem.rightBarButtonItem = barButton
}
func disableEnable(button : UIBarButtonItem){
form.disabled = !form.disabled
button.title = form.disabled ? "Enable" : "Disable"
tableView.endEditing(true)
tableView.reloadData()
}
func initializeForm() {
let form : XLFormDescriptor
var section : XLFormSectionDescriptor
var row : XLFormRowDescriptor
form = XLFormDescriptor(title: "Date & Time")
section = XLFormSectionDescriptor.formSectionWithTitle("Inline Dates")
form.addFormSection(section)
// Date
row = XLFormRowDescriptor(tag: Tags.DateInline, rowType: XLFormRowDescriptorTypeDateInline, title:"Date")
row.value = NSDate()
section.addFormRow(row)
// Time
row = XLFormRowDescriptor(tag: Tags.TimeInline, rowType: XLFormRowDescriptorTypeTimeInline, title: "Time")
row.value = NSDate()
section.addFormRow(row)
// DateTime
row = XLFormRowDescriptor(tag: Tags.DateTimeInline, rowType: XLFormRowDescriptorTypeDateTimeInline, title: "Date Time")
row.value = NSDate()
section.addFormRow(row)
// CountDownTimer
row = XLFormRowDescriptor(tag: Tags.CountDownTimerInline, rowType:XLFormRowDescriptorTypeCountDownTimerInline, title:"Countdown Timer")
row.value = NSDate()
section.addFormRow(row)
section = XLFormSectionDescriptor.formSectionWithTitle("Dates") //
form.addFormSection(section)
// Date
row = XLFormRowDescriptor(tag: Tags.Date, rowType:XLFormRowDescriptorTypeDate, title:"Date")
row.value = NSDate()
row.cellConfigAtConfigure["minimumDate"] = NSDate()
row.cellConfigAtConfigure["maximumDate"] = NSDate(timeIntervalSinceNow: 60*60*24*3)
section.addFormRow(row)
// Time
row = XLFormRowDescriptor(tag: Tags.Time, rowType: XLFormRowDescriptorTypeTime, title: "Time")
row.cellConfigAtConfigure["minuteInterval"] = 10
row.value = NSDate()
section.addFormRow(row)
// DateTime
row = XLFormRowDescriptor(tag: Tags.DateTime, rowType: XLFormRowDescriptorTypeDateTime, title: "Date Time")
row.value = NSDate()
section.addFormRow(row)
// CountDownTimer
row = XLFormRowDescriptor(tag: Tags.CountDownTimer, rowType: XLFormRowDescriptorTypeCountDownTimer, title: "Countdown Timer")
row.value = NSDate()
section.addFormRow(row)
section = XLFormSectionDescriptor.formSectionWithTitle("Disabled Dates")
section.footerTitle = "DatesFormViewController.swift"
form.addFormSection(section)
// Date
row = XLFormRowDescriptor(tag: nil, rowType: XLFormRowDescriptorTypeDate, title: "Date")
row.disabled = NSNumber(bool: true)
row.required = true
row.value = NSDate()
section.addFormRow(row)
section = XLFormSectionDescriptor.formSectionWithTitle("DatePicker")
form.addFormSection(section)
// DatePicker
row = XLFormRowDescriptor(tag: Tags.DatePicker, rowType:XLFormRowDescriptorTypeDatePicker)
row.cellConfigAtConfigure["datePicker.datePickerMode"] = UIDatePickerMode.Date.rawValue
row.value = NSDate()
section.addFormRow(row)
self.form = form
}
// MARK: - XLFormDescriptorDelegate
override func formRowDescriptorValueHasChanged(formRow: XLFormRowDescriptor!, oldValue: AnyObject!, newValue: AnyObject!) {
super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
if formRow.tag == Tags.DatePicker {
let alertView = UIAlertView(title: "DatePicker", message: "Value Has changed!", delegate: self, cancelButtonTitle: "OK")
alertView.show()
}
}
}
|
mit
|
bc218f958d799d6ee7a067886da8a65a
| 38.012346 | 143 | 0.670253 | 5.184578 | false | false | false | false |
lotpb/iosSQLswift
|
mySQLswift/ContactController.swift
|
1
|
7511
|
//
// ContactController.swift
// mySQLswift
//
// Created by Peter Balsamo on 1/20/16.
// Copyright © 2016 Peter Balsamo. All rights reserved.
//
import UIKit
import Contacts
class ContactController: UIViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak private var tableView: UITableView!
@IBOutlet weak private var searchBar: UISearchBar!
private var contacts = [CNContact]()
private var authStatus: CNAuthorizationStatus = .Denied {
didSet { // switch enabled search bar, depending contacts permission
searchBar.userInteractionEnabled = authStatus == .Authorized
if authStatus == .Authorized { // all search
contacts = fetchContacts("")
tableView.reloadData()
}
}
}
private let kCellID = "Cell"
// =========================================================================
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
checkAuthorization()
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: kCellID)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// =========================================================================
// MARK: - UISearchBarDelegate
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
contacts = fetchContacts(searchText)
tableView.reloadData()
}
// =========================================================================
//MARK: - UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contacts.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(kCellID, forIndexPath: indexPath)
let contact = contacts[indexPath.row]
// get the full name
let fullName = CNContactFormatter.stringFromContact(contact, style: .FullName) ?? "NO NAME"
cell.textLabel?.text = fullName
return cell
}
// =========================================================================
//MARK: - UITableViewDelegate
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let deleteActionHandler = { (action: UITableViewRowAction, index: NSIndexPath) in
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { [unowned self] (action: UIAlertAction) in
// set the data to be deleted
let request = CNSaveRequest()
let contact = self.contacts[index.row].mutableCopy() as! CNMutableContact
request.deleteContact(contact)
do {
// save
let fullName = CNContactFormatter.stringFromContact(contact, style: .FullName) ?? "NO NAME"
let store = CNContactStore()
try store.executeSaveRequest(request)
NSLog("\(fullName) Deleted")
// update table
self.contacts.removeAtIndex(index.row)
dispatch_async(dispatch_get_main_queue(), {
self.tableView.deleteRowsAtIndexPaths([index], withRowAnimation: .Fade)
})
} catch let error as NSError {
NSLog("Delete error \(error.localizedDescription)")
}
})
let cancelAction = UIAlertAction(title: "CANCEL", style: UIAlertActionStyle.Default, handler: { [unowned self] (action: UIAlertAction) in
self.tableView.editing = false
})
// show alert
self.showAlert(title: "Delete Contact", message: "OK?", actions: [okAction, cancelAction])
}
return [UITableViewRowAction(style: .Destructive, title: "Delete", handler: deleteActionHandler)]
}
// =========================================================================
// MARK: - IBAction
@IBAction func tapped(sender: AnyObject) {
view.endEditing(true)
}
// =========================================================================
// MARK: - Helpers
private func checkAuthorization() {
// get current status
let status = CNContactStore.authorizationStatusForEntityType(.Contacts)
authStatus = status
switch status {
case .NotDetermined: // case of first access
CNContactStore().requestAccessForEntityType(.Contacts) { [unowned self] (granted, error) in
if granted {
NSLog("Permission allowed")
self.authStatus = .Authorized
} else {
NSLog("Permission denied")
self.authStatus = .Denied
}
}
case .Restricted, .Denied:
NSLog("Unauthorized")
let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
let settingsAction = UIAlertAction(title: "Settings", style: .Default, handler: { (action: UIAlertAction) in
let url = NSURL(string: UIApplicationOpenSettingsURLString)
UIApplication.sharedApplication().openURL(url!)
})
showAlert(
title: "Permission Denied",
message: "You have not permission to access contacts. Please allow the access the Settings screen.",
actions: [okAction, settingsAction])
case .Authorized:
NSLog("Authorized")
}
}
// fetch the contact of matching names
private func fetchContacts(name: String) -> [CNContact] {
let store = CNContactStore()
do {
let request = CNContactFetchRequest(keysToFetch: [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)])
if name.isEmpty { // all search
request.predicate = nil
} else {
request.predicate = CNContact.predicateForContactsMatchingName(name)
}
var contacts = [CNContact]()
try store.enumerateContactsWithFetchRequest(request, usingBlock: { (contact, error) in
contacts.append(contact)
})
return contacts
} catch let error as NSError {
NSLog("Fetch error \(error.localizedDescription)")
return []
}
}
private func showAlert(title title: String, message: String, actions: [UIAlertAction]) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
for action in actions {
alert.addAction(action)
}
dispatch_async(dispatch_get_main_queue(), { [unowned self] () in
self.presentViewController(alert, animated: true, completion: nil)
})
}
}
|
gpl-2.0
|
c5735393d0fc9432ddb509ab896da488
| 36.733668 | 149 | 0.545551 | 6.133987 | false | false | false | false |
exercism/xswift
|
exercises/binary/Sources/Binary/BinaryExample.swift
|
2
|
856
|
extension Int {
init(_ value: Binary?) {
if let value = value {
self = value.toDecimal
} else {
self = 0 }
}
}
struct Binary {
private var UIntValue: UInt = 0
fileprivate var toDecimal: Int {
return Int(UIntValue)
}
private func bi2Uint(_ input: String) -> UInt? {
let orderedInput = Array(input.reversed())
var tempUInt: UInt = 0
for (inx, each) in orderedInput.enumerated() {
if each == "1" {
tempUInt += UInt(0x1 << inx)
}
if each != "0" && each != "1" {
return nil
}
}
return tempUInt
}
init?(_ input: String) {
if bi2Uint(input) != nil {
self.UIntValue = bi2Uint(input)!
} else {
return nil
}
}
}
|
mit
|
e97dad648087b6502d873f50b23c4feb
| 22.777778 | 54 | 0.461449 | 4.037736 | false | false | false | false |
nathawes/swift
|
test/IRGen/sil_witness_tables.swift
|
9
|
3621
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t %S/sil_witness_tables_external_conformance.swift
// RUN: %target-swift-frontend -I %t -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
import sil_witness_tables_external_conformance
// FIXME: This should be a SIL test, but we can't parse sil_witness_tables
// yet.
protocol A {}
protocol P {
associatedtype Assoc: A
static func staticMethod()
func instanceMethod()
}
protocol Q : P {
func qMethod()
}
protocol QQ {
func qMethod()
}
struct AssocConformer: A {}
struct Conformer: Q, QQ {
typealias Assoc = AssocConformer
static func staticMethod() {}
func instanceMethod() {}
func qMethod() {}
}
// CHECK: [[EXTERNAL_CONFORMER_EXTERNAL_P_WITNESS_TABLE:@"\$s39sil_witness_tables_external_conformance17ExternalConformerVAA0F1PAAWP"]] = external{{( dllimport)?}} global i8*, align 8
// CHECK: [[CONFORMER_Q_WITNESS_TABLE:@"\$s18sil_witness_tables9ConformerVAA1QAAWP"]] = hidden constant [3 x i8*] [
// CHECK: i8* bitcast ([5 x i8*]* [[CONFORMER_P_WITNESS_TABLE:@"\$s18sil_witness_tables9ConformerVAA1PAAWP"]] to i8*),
// CHECK: i8* bitcast (void (%T18sil_witness_tables9ConformerV*, %swift.type*, i8**)* @"$s18sil_witness_tables9ConformerVAA1QA2aDP7qMethod{{[_0-9a-zA-Z]*}}FTW" to i8*)
// CHECK: ]
// CHECK: [[CONFORMER_P_WITNESS_TABLE]] = hidden global [5 x i8*] [
// CHECK: @"associated conformance 18sil_witness_tables9ConformerVAA1PAA5AssocAaDP_AA1A"
// CHECK: "symbolic{{.*}}18sil_witness_tables14AssocConformerV"
// CHECK: i8* bitcast (void (%swift.type*, %swift.type*, i8**)* @"$s18sil_witness_tables9ConformerVAA1PA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW" to i8*),
// CHECK: i8* bitcast (void (%T18sil_witness_tables9ConformerV*, %swift.type*, i8**)* @"$s18sil_witness_tables9ConformerVAA1PA2aDP14instanceMethod{{[_0-9a-zA-Z]*}}FTW" to i8*)
// CHECK: ]
// CHECK: [[CONFORMER2_P_WITNESS_TABLE:@"\$s18sil_witness_tables10Conformer2VAA1PAAWP"]] = hidden global [5 x i8*]
struct Conformer2: Q {
typealias Assoc = AssocConformer
static func staticMethod() {}
func instanceMethod() {}
func qMethod() {}
}
// CHECK-LABEL: define hidden swiftcc void @"$s18sil_witness_tables7erasure1cAA2QQ_pAA9ConformerV_tF"(%T18sil_witness_tables2QQP* noalias nocapture sret %0)
// CHECK: [[WITNESS_TABLE_ADDR:%.*]] = getelementptr inbounds %T18sil_witness_tables2QQP, %T18sil_witness_tables2QQP* %0, i32 0, i32 2
// CHECK-NEXT: store i8** getelementptr inbounds ([2 x i8*], [2 x i8*]* [[CONFORMER_QQ_WITNESS_TABLE:@"\$s.*WP"]], i32 0, i32 0), i8*** [[WITNESS_TABLE_ADDR]], align 8
func erasure(c: Conformer) -> QQ {
return c
}
// CHECK-LABEL: define hidden swiftcc void @"$s18sil_witness_tables15externalErasure1c0a1_b1_c1_D12_conformance9ExternalP_pAD0G9ConformerV_tF"(%T39sil_witness_tables_external_conformance9ExternalPP* noalias nocapture sret %0)
// CHECK: [[WITNESS_TABLE_ADDR:%.*]] = getelementptr inbounds %T39sil_witness_tables_external_conformance9ExternalPP, %T39sil_witness_tables_external_conformance9ExternalPP* %0, i32 0, i32 2
// CHECK-NEXT: store i8** [[EXTERNAL_CONFORMER_EXTERNAL_P_WITNESS_TABLE]], i8*** %2, align 8
func externalErasure(c: ExternalConformer) -> ExternalP {
return c
}
// FIXME: why do these have different linkages?
// CHECK-LABEL: define hidden swiftcc %swift.metadata_response @"$s18sil_witness_tables14AssocConformerVMa"(i64 %0)
// CHECK: ret %swift.metadata_response { %swift.type* bitcast (i64* getelementptr inbounds {{.*}} @"$s18sil_witness_tables14AssocConformerVMf", i32 0, i32 1) to %swift.type*), i64 0 }
|
apache-2.0
|
e7870d88f8346d4deebba8dcf670ff6e
| 46.025974 | 225 | 0.713063 | 3.224399 | false | false | false | false |
priyanka16/RPChatUI
|
RPChatUI/Classes/ContactsCardCollectionViewCell.swift
|
1
|
3304
|
//
// ContactsCardCollectionViewCell.swift
// RPChatterBox
//
// Created by Priyanka
// Copyright © 2017 __MyCompanyName__. All rights reserved.
//
import UIKit
import QuartzCore
protocol ContactsCardCollectionViewCellDelegate : class {
func didSelectContact(with contactId: Int)
}
class ContactsCardCollectionViewCell: UICollectionViewCell {
weak var delegate: ContactsCardCollectionViewCellDelegate?
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var gradientImageView: UIImageView!
@IBOutlet weak var contactImage: UIImageView!
@IBOutlet weak var contactNameLabel: UILabel!
@IBOutlet weak var contactDesignationLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var selectButton: UIButton!
func setupCollectionViewCell(for index: Int) {
self.backgroundColor = UIColor.clear
self.containerView.layer.cornerRadius = 8.0
self.containerView.layer.borderWidth = 1.0
self.containerView.layer.borderColor = UIColor(red: 242 / 255.0, green: 242 / 255.0, blue: 242 / 255.0, alpha: 1.0).cgColor
self.containerView.layer.masksToBounds = true
self.containerView.layer.shadowColor = UIColor(red: 230 / 255.0, green: 230 / 255.0, blue: 230 / 255.0, alpha: 1.0).cgColor
self.containerView.layer.shadowOffset = CGSize(width: -2.0, height: 2.0)
self.containerView.layer.shadowRadius = 2.0
self.containerView.layer.shadowOpacity = 1.0
self.containerView.layer.masksToBounds = false
self.gradientImageView.layer.cornerRadius = 8.0
self.gradientImageView.layer.borderWidth = 1.0
self.gradientImageView.layer.borderColor = UIColor(red: 242 / 255.0, green: 242 / 255.0, blue: 242 / 255.0, alpha: 1.0).cgColor
self.gradientImageView.layer.masksToBounds = true
self.selectButton.layer.cornerRadius = 10.0
self.selectButton.layer.borderWidth = 0.5
self.selectButton.layer.borderColor = UIColor(red: 68 / 255.0, green: 65 / 255.0, blue: 235 / 255.0, alpha: 1.0).cgColor
if let customBundle = Bundle.init(identifier: "org.cocoapods.RPChatUI")?.path(forResource: "RPBundle", ofType: "bundle") {
if let imagePath: String = (customBundle.appending("/icConactBackground.tiff")) {
if let image = UIImage(contentsOfFile:imagePath) {
gradientImageView.image = image
}
}
}
if let customBundle = Bundle.init(identifier: "org.cocoapods.RPChatUI")?.path(forResource: "RPBundle", ofType: "bundle") {
if let imagePath: String = (customBundle.appending("/icContactImage.tiff")) {
if let image = UIImage(contentsOfFile:imagePath) {
contactImage.image = image
}
}
}
}
@IBAction func selectContact(_ sender: AnyObject) {
selectButton.backgroundColor = UIColor(red: 69 / 255.0, green: 65 / 255.0, blue: 234 / 255.0, alpha: 1.0)
self.selectButton.setTitleColor(UIColor.white, for: .normal)
self.delegate?.didSelectContact(with: sender.tag)
}
}
|
mit
|
9268f4880ffb183391919cb567ac4407
| 41.896104 | 135 | 0.662731 | 4.340342 | false | false | false | false |
AlesTsurko/DNMKit
|
DNMModel/DurationNode.swift
|
1
|
36447
|
//
// DurationNode.swift
// denm_model
//
// Created by James Bean on 8/11/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import Foundation
/**
DurationNode is a hierarchical structure with an accompanying datum of Duration. NYI: Partition
*/
public class DurationNode: Node, DurationSpanning {
// deprecate
public var id: String?
// MARK: Attributes
/// Duration of DurationNode
public var duration: Duration
public var offsetDuration: Duration = DurationZero
// make better interface
public var durationInterval: DurationInterval {
return DurationInterval(duration: duration, startDuration: offsetDuration)
}
public var components: [Component] = []
public var isRest: Bool { return getIsRest() }
/// All Instrument ID values organized by Performer ID keys
public var instrumentIDsByPerformerID: [String : [String]] { get { return getIIDsByPID() } }
/// If this DurationNode is a continuation from another ("tied")
public var hasExtensionStart: Bool { return getHasExtensionStart() }
/// If this DurationNode continues into another ("tied")
public var hasExtensionStop: Bool { return getHasExtensionStop() }
/// If this DurationNode shall be represented with metrical beaming
public var isMetrical: Bool = true
/**
If this DurationNode is either [1] subdividable (non-tuplet), or [2] should not be
represented with tuplet bracket(s).
*/
public var isNumerical: Bool = true
/// If this DurationNode has only Extension Components (ties) (not a rest, but no info).
public var hasOnlyExtensionComponents: Bool { return getHasOnlyExtensionComponents() }
/*
public func distanceFromDurationNode(durationNode: DurationNode) -> Duration? {
// TODO
return nil
}
public func distanceFromDuration(duration: Duration) -> Duration? {
// TODO
return nil
}
*/
// MARK: Analyze DurationNode
/// Array of integers with reduced relative durations of children
public var relativeDurationsOfChildren: [Int]? {
get { return getRelativeDurationsOfChildren() }
}
/// The reduced, leveled Subdivision of children
public var subdivisionOfChildren: Subdivision? {
get { return getSubdivisionOfChildren() }
}
/// Scale of children DurationNodes
public var scaleOfChildren: Float? { get { return getScaleOfChildren() } }
/// If DurationNode is subdividable (non-tuplet)
public var isSubdividable: Bool { get { return getIsSubdividable() } }
/*
// implement
public class func rangeFromDurationNodes(durationNodes: [DurationNode],
inDurationSpan durationSpan: DurationSpan
) -> [DurationNode]
{
return []
}
*/
/// From an array of DurationNodes, choose those that fit within the given DurationSpan
public class func rangeFromDurationNodes(
durationNodes: [DurationNode],
afterDuration start: Duration,
untilDuration stop: Duration
) -> [DurationNode]
{
var durationNodeRange: [DurationNode] = []
for durationNode in durationNodes {
if (
durationNode.offsetDuration >= start &&
durationNode.offsetDuration + durationNode.duration <= stop
)
{
durationNodeRange.append(durationNode)
}
}
// make nil returnable if count == 0
return durationNodeRange
}
public class func random() -> DurationNode {
let amountBeats = randomInt(3, max: 9)
let duration = Duration(amountBeats,16)
let amountEvents = randomInt(4, max: 9)
var sequence: [Int] = []
for _ in 0..<amountEvents {
let duration: Int = [1,1,1,2,2,3].random()
sequence.append(duration)
}
let durationNode = DurationNode(duration: duration, sequence: sequence)
return durationNode
}
public class func getMaximumSubdivisionOfSequence(sequence: [DurationNode])
-> Subdivision?
{
var maxSubdivision: Subdivision?
for child in sequence {
if maxSubdivision == nil || child.duration.subdivision! > maxSubdivision! {
maxSubdivision = child.duration.subdivision!
}
}
return maxSubdivision
}
public class func getMinimumSubdivisionOfSequence(sequence: [DurationNode])
-> Subdivision?
{
var minSubdivision: Subdivision?
for child in sequence {
if minSubdivision == nil || child.duration.subdivision! < minSubdivision! {
minSubdivision = child.duration.subdivision!
}
}
return minSubdivision
}
public class func matchDurationsOfSequence(sequence: [DurationNode]) {
DurationNode.levelDurationsOfSequence(sequence)
DurationNode.reduceDurationsOfSequence(sequence)
}
public class func levelDurationsOfSequence(sequence: [DurationNode]) {
let maxSubdivision: Subdivision = getMaximumSubdivisionOfSequence(sequence)!
for child in sequence {
child.duration.respellAccordingToSubdivision(maxSubdivision)
}
}
public class func reduceDurationsOfSequence(sequence: [DurationNode]) {
if !DurationNode.allSubdivisionsOfSequenceAreEquivalent(sequence) {
DurationNode.levelDurationsOfSequence(sequence)
}
let relativeDurationsOfSequence = getRelativeDurationsOfSequence(sequence)
let durationGCD: Int = gcd(relativeDurationsOfSequence)
for node in sequence {
let newBeats = node.duration.beats! / durationGCD
node.duration.respellAccordingToBeats(newBeats)
}
/*
levelDurationsOfChildren()
let durationGCD: Int = gcd(relativeDurationsOfChildren!)
for child in children as! [DurationNode] {
let newBeats = child.duration.beats! / durationGCD
child.duration.respellAccordingToBeats(newBeats)
//child.duration.beats! /= durationGCD
}
*/
}
public class func allSubdivisionsOfSequenceAreEquivalent(sequence: [DurationNode]) -> Bool {
if sequence.count == 0 { return false }
let refSubdivision = sequence.first!.duration.subdivision!
for i in 1..<sequence.count {
if sequence[i].duration.subdivision! != refSubdivision { return false }
}
return true
}
public class func getRelativeDurationsOfSequence(sequence: [DurationNode]) -> [Int] {
// make copy of sequence, to not change current values of DurationNode sequence
var sequence_copy: [DurationNode] = []
for node in sequence { sequence_copy.append(node.copy()) }
if !DurationNode.allSubdivisionsOfSequenceAreEquivalent(sequence_copy) {
DurationNode.levelDurationsOfSequence(sequence_copy)
}
//DurationNode.reduceDurationsOfSequence(sequence_copy) // make this an option?
var relativeDurations: [Int] = []
for node in sequence_copy { relativeDurations.append(node.duration.beats!.amount) }
return relativeDurations
}
/**
Create a DurationNode with Duration
- parameter duration: Duration
- returns: Initialized DurationNode
*/
public init(duration: Duration) {
self.duration = duration
}
/*
public init(duration: Duration, sequence: NSArray) {
self.duration = duration
super.init()
addChildrenWithSequence(sequence)
}
*/
/**
Create a DurationNode with a Duration and a sequence of relative durations.
- parameter duration: Duration
- parameter sequence: Sequence of relative durations of child nodes
- returns: Initialized DurationNode object
*/
public init(duration: Duration, offsetDuration: Duration = DurationZero, sequence: NSArray) {
self.duration = duration
self.offsetDuration = offsetDuration
super.init()
addChildrenWithSequence(sequence)
}
/**
Create a DurationNode with a Duration as an array of two integers: [beats, subdivision] and
a sequence of relative durations.
- parameter duration: Duration as an array of two integers: [beats, subdivision]
- parameter sequence: Sequence of relative durations of child nodes
- returns: Initialized DurationNode object
*/
public init(duration: (Int, Int), offsetDuration: (Int, Int) = (0,8), sequence: NSArray) {
self.duration = Duration(duration.0, duration.1)
self.offsetDuration = Duration(offsetDuration.0, offsetDuration.1)
super.init()
addChildrenWithSequence(sequence)
}
/*
public override func addChild(node: Node) -> Self {
super.addChild(node)
matchDurationsOfTree()
return self
}
*/
/*
public func addRandomComponentsToLeavesWithPID(pID: String, andIID iID: String) {
for leaf in leaves as! [DurationNode] {
leaf.addComponent(
ComponentPitch(
pID: pID, iID: iID, pitches: [
randomFloat(min: 60, max: 84, resolution: 0.25)
]
)
)
leaf.addComponent(ComponentArticulation(pID: pID, iID: iID, markings: ["."]))
//leaf.addComponent(ComponentDynamic(pID: pID, iID: iID, marking: "fff"))
}
}
*/
public func addChildWithBeats(beats: Int) -> DurationNode {
let child = DurationNode(duration: Duration(beats, duration.subdivision!.value))
// perhaps do some calculation here...to figure out proper
addChild(child)
return child
//println("children: \(children)")
//(root as! DurationNode).matchDurationsOfTree()
//println("children after match durations of tree (destructive): \(children))")
//(root as! DurationNode).scaleDurationsOfChildren()
//println("children after scale durations of children: \(children)")
}
/**
Set Duration of DurationNode
- parameter duration: Duration of DurationNode
- returns: DurationNode object
*/
public func setDuration(duration: Duration) -> DurationNode {
self.duration = duration
return self
}
/**
Add child nodes with relative durations in sequence.
- parameter sequence: Sequence of relative durations of child nodes
- returns: DurationNode object
*/
public func addChildrenWithSequence(sequence: NSArray) -> DurationNode {
traverseToAddChildrenWithSequence(sequence, parent: self)
(root as! DurationNode).matchDurationsOfTree()
(root as! DurationNode).scaleDurationsOfChildren()
// weird, encapsulate
if sequence.count == 1 {
(children.first! as! DurationNode).duration.setSubdivision(duration.subdivision!)
}
setOffsetDurationOfChildren()
return self
}
public func addComponent(component: Component) {
components.append(component)
}
public func clearComponents() {
components = []
}
public func setOffsetDurationOfChildren() {
var offsetDuration = self.offsetDuration
traverseToSetOffsetDurationOfChildrenOfDurationNode(self,
andOffsetDuration: &offsetDuration
)
}
private func traverseToSetOffsetDurationOfChildrenOfDurationNode(durationNode: DurationNode,
inout andOffsetDuration offsetDuration: Duration
)
{
durationNode.offsetDuration = offsetDuration
// must incorporate SCALE into here...
for child in durationNode.children as! [DurationNode] {
var newOffsetDuration = offsetDuration
if child.isContainer {
traverseToSetOffsetDurationOfChildrenOfDurationNode(child,
andOffsetDuration: &newOffsetDuration
)
}
// LEAF
else { child.offsetDuration = offsetDuration }
offsetDuration += child.duration
// have to do that thing where it resets the duration back to what it was
}
}
// could this be done with [AnyObject]? ...then do the type cast check?
// for testing only, i'd assume; rather not dip into NSArray…
private func traverseToAddChildrenWithSequence(sequence: NSArray, parent: DurationNode) {
for el in sequence {
if let leafBeats = el as? Int {
let leafNode = DurationNode(
duration: Duration(abs(leafBeats), duration.subdivision!.value)
)
parent.addChild(leafNode)
}
else if let container = el as? NSArray {
var node: DurationNode?
if let beats = container[0] as? Int {
node = DurationNode(duration: Duration(beats, duration.subdivision!.value))
parent.addChild(node!)
}
if let seq = container[1] as? NSArray {
traverseToAddChildrenWithSequence(seq, parent: node!)
}
}
}
}
/*
/**
Set if DurationNode is extended at the beginning
- parameter hasExtensionBegin: If DurationNode is extended at the beginning
- returns: DurationNode object
*/
public func setHasExtensionStart(hasExtensionStart: Bool) -> DurationNode {
self.hasExtensionStart = hasExtensionStart
return self
}
/**
Set if DurationNode extends into the next
- parameter hasExtensionEnd: If DurationNode extends into the next
- returns: DurationNode object
*/
public func setHasExtensionStop(hasExtensionStop: Bool) -> DurationNode {
self.hasExtensionStop = hasExtensionStop
return self
}
*/
// MARK: Operations
/**
Deep copy of DurationNode. A new DurationNode is created with all attributes equivalant
to original.
When comparing a Node that has been copied from another,"===" will return false,
while "==" will return true (NYI).
- returns: DurationNode object
*/
public override func copy() -> DurationNode {
var node: Node = self
descendToCopy(&node)
return node as! DurationNode
}
/**
This is the recursive counterpart to copy(). This method copies the Duration of each
child and descends to each child, if applicable.
- parameter node: Node
*/
public override func descendToCopy(inout node: Node) {
let newParent: DurationNode = DurationNode(duration: (node as! DurationNode).duration)
if node.isContainer {
for child in node.children {
var newChild: Node = child
descendToCopy(&newChild)
newParent.addChild(newChild)
}
}
node = newParent
}
// should be private
public func matchDurationsOfTree() {
var node = self
traverseToMatchDurationsOfTree(&node)
}
// should be private
private func traverseToMatchDurationsOfTree(inout node: DurationNode) {
if node.isContainer {
node.matchDurationToChildren_destructive()
for child in node.children as! [DurationNode] {
var child = child
traverseToMatchDurationsOfTree(&child)
}
}
}
// should be private?
public func scaleDurationsOfTree(scale scale: Float) -> DurationNode {
duration.setScale(scale)
scaleDurationsOfChildren()
return self
}
/**
Recursively scales the Durations of all Nodes in a DurationNode tree. This scale is used
when calculating the graphical widths and temporal lengths of (embedded-)tuplet rhythms.
*/
public func scaleDurationsOfChildren() {
var node: DurationNode = self
var scale: Float = duration.scale
descendToScaleDurationsOfChildren(&node, scale: &scale)
}
/**
This is the recursive counterpart to scaleDurationsOfChildren(). This method sets the
inheritedScale of the Duration of each Node in a DurationNode tree.
- parameter node: DurationNode to be scaled
- parameter scale: Amount by which to scale Duration of DurationNode
*/
public func descendToScaleDurationsOfChildren(
inout node: DurationNode, inout scale: Float
)
{
node.duration.setScale(scale)
if node.isContainer {
let beats: Float = Float(node.duration.beats!.amount)
let sumAsInt: Int = node.relativeDurationsOfChildren!.sum()
let sum: Float = Float(sumAsInt)
var newScale = scale * (beats / sum)
for child in node.children as! [DurationNode] {
var child = child
descendToScaleDurationsOfChildren(&child, scale: &newScale)
}
}
}
// make this private, can only happen on INIT_WITH_SEQ()
private func matchDurationToChildren_destructive() {
for child in children as! [DurationNode] {
child.duration.respellAccordingToSubdivision(duration.subdivision!)
}
let beats: Int = duration.beats!.amount
var reduced: [Int] = []
let relDurs = relativeDurationsOfChildren!
let relDursGCD = gcd(relDurs)
for d in relDurs { reduced.append(d / relDursGCD) }
let sum: Int = reduced.sum()
if sum < beats {
for c in 0..<children.count {
let child = children[c] as! DurationNode
child.duration.respellAccordingToBeats(reduced[c])
}
}
else if sum > beats {
let closestPowerOfTwo = getClosestPowerOfTwo(multiplier: beats, value: sum)
let scale: Int = closestPowerOfTwo / beats
let newBeats = duration.beats!.amount * scale
duration.respellAccordingToBeats(newBeats)
for child in children as! [DurationNode] {
child.duration.setSubdivision(duration.subdivision!)
}
}
for c in 0..<children.count {
let child = children[c] as! DurationNode
child.duration.setBeats(reduced[c])
}
// encapsulate
// reduce if there's all evens
var beatsWithChildBeats: [Int] = [duration.beats!.amount]
for child in children as! [DurationNode] {
beatsWithChildBeats.append(child.duration.beats!.amount)
}
let allDursGCD = gcd(beatsWithChildBeats)
//print("all durs GCD: \(allDursGCD)")
if allDursGCD > 1 {
// deal with cur node
//let newBeats: Int = duration.beats!.amount / allDursGCD
//duration.respellAccordingToBeats(newBeats)
// deal with children
/*
for child in children as! [DurationNode] {
//let newBeats: Int = child.duration.beats!.amount / allDursGCD
//child.duration.respellAccordingToBeats(newBeats)
}
*/
}
//reduceDurationsOfChildren()
}
public func matchDurationToChildren_nonDestructive() {
// respelling only
}
/**
Ensures that the Duration of this DurationNode is appropriate considering the context of
the Durations of its children.
In many cases, this means that the Duration of this DurationNode is respelled according to
the amount of beats that most closely matches the sum of the leveled and reduced children
Durations (e.g. original DurationNode.duration = (2,16), and original
DurationNode.relativeDurationsOfChildren.sum() = 13; new DurationNode.duration = (16,128)).
In other cases, this means that the Durations of the children DurationNodes are respelled
such that their sum matches the most-reduced form the Duration of this DurationNode (e.g.
original DurationNode.duration = (7,32), and the amounts of beats for the children are
[1,2,1]; the new amounts of beats for the children are [2,4,2], with a sum of 8).
*/
public func matchDurationToChildren() {
// currently does nothing
/*
for child in children as! [DurationNode] {
child.duration.respellAccordingToSubdivision(duration.subdivision!)
}
levelDurationsOfChildren()
reduceDurationsOfChildren()
let beats: Int = duration.beats!.amount
let sum: Int = relativeDurationsOfChildren!.sum()
println("matchDurationToChildren BEFORE: beats: \(beats) / sum: \(sum)")
/*
// first, set the subdivisions to match!
for child in children as! [DurationNode] {
child.duration.setSubdivision(duration.subdivision!)
}
*/
// e.g.: 7:13
if sum < beats {
println("sum: \(sum) < beats: \(beats)")
/*
for b in 0..<relativeDurationsOfChildren!.count {
var beats = relativeDurationsOfChildren![b]
var child = (children as! [DurationNode])[b]
child.duration.respellAccordingToBeats(b)
}
*/
for child in children as! [DurationNode] {
child.duration.respellAccordingToSubdivision(duration.subdivision!)
}
// is parent changed?
/*
let closestPowerOfTwo = getClosestPowerOfTwo(multiplier: sum, value: beats)
let scale: Float = Float(closestPowerOfTwo) / Float(sum)
for child in children as! [DurationNode] {
// why can't i just respell according to parent.subdivision?
// -- see above
// are there cases where this won't work
let newBeats = child.duration.beats! * Int(scale)
child.duration.respellAccordingToBeats(newBeats)
}
*/
}
else if sum > beats {
println("sum: \(sum) > beats: \(beats)")
let closestPowerOfTwo = getClosestPowerOfTwo(multiplier: beats, value: sum)
duration.respellAccordingToBeats(closestPowerOfTwo)
for child in children as! [DurationNode] {
child.duration.setSubdivision(duration.subdivision!)
}
}
*/
/*
if beats > sum {
let closestPowerOfTwo = getClosestPowerOfTwo(multiplier: sum, value: beats)
let scale: Float = Float(closestPowerOfTwo) / Float(sum)
for child in children as! [DurationNode] {
child.duration.beats! *= Int(scale)
}
}
else if beats < sum {
let closestPowerOfTwo = getClosestPowerOfTwo(multiplier: beats, value: sum)
duration.respellAccordingToBeats(Beats(amount: closestPowerOfTwo))
for child in children as! [DurationNode] {
//child.duration.setSubdivision(duration.subdivision!)
child.duration.respellAccordingToSubdivision(duration.subdivision!)
}
}
*/
}
/**
Levels and Reduces the Durations of all of the children of this DurationNode, if present.
*/
public func matchDurationsOfChildren() {
reduceDurationsOfChildren()
}
/**
Ensures that the Durations of each child of this DurationNode have the same Subdivision.
*/
public func levelDurationsOfChildren() {
if !isContainer { return }
DurationNode.levelDurationsOfSequence(children as! [DurationNode])
}
/**
Ensures that the Durations of each child, once leveled, are reduced to the greatest degree.
*/
public func reduceDurationsOfChildren() {
if !isContainer { return }
DurationNode.levelDurationsOfSequence(children as! [DurationNode])
DurationNode.reduceDurationsOfSequence(children as! [DurationNode])
}
/**
Partitions this DurationNode at the desired Subdivision.
NYI: Less friendly partition-points. Arbitrary arrays of partition widths ([3,5,3]).
- parameter newSubdivision: The Subdivision at which to partition DurationNode
- returns: An array of DurationNodes, partitioned at the desired Subdivision
*/
public func partitionAtSubdivision(newSubdivision: Subdivision) -> [DurationNode] {
matchDurationToChildren()
assert(newSubdivision >= subdivisionOfChildren!, "can't divide by bigger subdivision")
let ratio: Int = newSubdivision.value / subdivisionOfChildren!.value
var multiplied: [DurationNode] = makeChildrenWithDurationsScaledByRatio(ratio)
var compound: [[DurationNode]] = [[]]
let sum: Int = getSumOfDurationNodes(children as! [DurationNode])
recurseToPartitionAtSubdivision(&multiplied, compound: &compound, sum: sum)
// encapsulate ----------------------------------------------------------------------->
var partitioned: [DurationNode] = []
for beat in compound {
let newParent = DurationNode(duration: Duration(subdivision: newSubdivision))
for child in beat { newParent.addChild(child) }
newParent.matchDurationToChildren()
partitioned.append(newParent)
}
// <----------------------------------------------------------------------- encapsulate
return partitioned
}
/**
This is the recursive counterpart to partitionAtSubdivision().
- parameter array: Array of DurationNodes
- parameter compound: Array of Arrays of Durations, with a width prescribed by the Subdivision
- parameter sum: Width of each Partition
*/
public func recurseToPartitionAtSubdivision(
inout array: [DurationNode],
inout compound: [[DurationNode]],
sum: Int
) {
let curBeats: Int = array[0].duration.beats!.amount
var accumulated: Int = 0
if compound.last!.last == nil { accumulated = curBeats }
else {
for dur in compound.last! { accumulated += dur.duration.beats!.amount }
accumulated += curBeats
}
if accumulated < sum {
var newLast: [DurationNode] = compound.last!
newLast.append(array[0])
compound.removeLast()
compound.append(newLast)
array.removeAtIndex(0)
if array.count > 0 {
recurseToPartitionAtSubdivision(&array, compound: &compound, sum: sum)
}
}
else if accumulated == sum {
var newLast: [DurationNode] = compound.last!
newLast.append(array[0])
compound.removeLast()
compound.append(newLast)
array.removeAtIndex(0)
if array.count > 0 {
compound.append([])
recurseToPartitionAtSubdivision(&array, compound: &compound, sum: sum)
}
}
else {
var newLast: [DurationNode] = compound.last!
let endNode: DurationNode = array[0].copy()
endNode.duration.beats!.setAmount(sum - (accumulated - curBeats))
endNode.addComponent(ComponentExtensionStart())
//endNode.setHasExtensionStart(true)
newLast.append(endNode)
compound.removeLast()
compound.append(newLast)
var beginBeats = array[0].duration.beats!.amount - endNode.duration.beats!.amount
if curBeats > sum {
while beginBeats > sum {
let newNode: DurationNode = array[0].copy()
newNode.duration.beats!.setAmount(sum)
newNode.addComponent(ComponentExtensionStop())
newNode.addComponent(ComponentExtensionStart())
compound.append([newNode])
beginBeats -= sum
}
}
if beginBeats > 0 {
let newNode: DurationNode = array[0].copy()
newNode.duration.beats!.setAmount(beginBeats)
newNode.addComponent(ComponentExtensionStop())
compound.append([newNode])
}
array.removeAtIndex(0)
if array.count > 0 {
recurseToPartitionAtSubdivision(&array, compound: &compound, sum: sum)
}
}
}
/**
- parameter ratio: Amount by which to scale the Durations of the children of this DurationNode
- returns: An array of DurationNodes with Durations scaled by ratio
*/
public func makeChildrenWithDurationsScaledByRatio(ratio: Int) -> [DurationNode] {
var multiplied: [DurationNode] = []
for child in children as! [DurationNode] {
let newChild: DurationNode = child.copy()
let newBeats = newChild.duration.beats! * ratio * duration.beats!.amount
newChild.duration.setBeats(newBeats)
newChild.duration.subdivision! *= getClosestPowerOfTwo(
multiplier: 2, value: newChild.duration.beats!.amount
) * ratio
multiplied.append(newChild)
}
return multiplied
}
/**
- returns: Maximum Subdivision of children of this DurationNode, if present.
*/
public func getMaximumSubdivisionOfChildren() -> Subdivision? {
if isContainer {
var maxSubdivision: Subdivision?
for child in children {
let durNodeChild = child as! DurationNode
if (
maxSubdivision == nil ||
durNodeChild.duration.subdivision! > maxSubdivision!
)
{
maxSubdivision = durNodeChild.duration.subdivision!
}
}
return maxSubdivision
}
else { return nil }
}
/**
- returns: An array of integers of relative amounts of Beats in the Durations of children.
*/
public func getRelativeDurationsOfChildren() -> [Int]? {
if !isContainer { return nil }
var relativeDurations: [Int] = []
for child in children as! [DurationNode] {
let child_copy = child.copy()
child_copy.duration.respellAccordingToSubdivision(duration.subdivision!)
relativeDurations.append(child_copy.duration.beats!.amount)
}
return relativeDurations
}
/**
Checks if the sum of the Durations of all children DurationNodes are equivelant to the
amount of Beats in this DurationNode. Otherwise, this DurationNode is a tuplet.
- returns: If this DurationNode is subdividable
*/
public func getIsSubdividable() -> Bool {
matchDurationToChildren()
let sum: Int = relativeDurationsOfChildren!.sum()
let beats: Int = duration.beats!.amount
return sum == beats
}
private func getIsRest() -> Bool {
if !isLeaf { return false }
for component in components { if !(component is ComponentRest) { return false } }
return true
}
/**
- returns: Subdivision of children, if present.
*/
public func getSubdivisionOfChildren() -> Subdivision? {
if !isContainer { return nil }
// match (level, reduce) children to parent
return (children[0] as! DurationNode).duration.subdivision!
}
private func getScaleOfChildren() -> Float {
return (children as! [DurationNode]).first!.duration.scale
}
/**
- parameter durationNodes: Array of DurationNodes
- returns: Sum of the Beats in the Durations of each DurationNode in array.
*/
public func getSumOfDurationNodes(durationNodes: [DurationNode]) -> Int {
var sum: Int = 0
for child in durationNodes { sum += child.duration.beats!.amount }
return sum
}
private func getIIDsByPID() -> [String : [String]] {
var iIDsByPID: [String : [String]] = [:]
let durationNode = self
descendToGetIIDsByPID(durationNode: durationNode, iIDsByPID: &iIDsByPID)
return iIDsByPID
}
// FIXME
private func descendToGetIIDsByPID(
durationNode durationNode: DurationNode,
inout iIDsByPID: [String : [String]]
)
{
func addInstrumentID(
iID: String,
andPerformerID pID: String,
inout toIIDsByPID iIDsByPID: [String : [String]]
)
{
if iIDsByPID[pID] == nil { iIDsByPID[pID] = [iID] }
else if !iIDsByPID[pID]!.contains(iID) { iIDsByPID[pID]!.append(iID) }
}
for component in durationNode.components {
addInstrumentID(component.instrumentID,
andPerformerID: component.performerID,
toIIDsByPID: &iIDsByPID
)
}
if durationNode.isContainer {
for child in durationNode.children as! [DurationNode] {
descendToGetIIDsByPID(durationNode: child, iIDsByPID: &iIDsByPID)
}
}
}
private func getDurationSpan() -> DurationSpan {
return DurationSpan(duration: duration, startDuration: offsetDuration)
}
private func getHasExtensionStart() -> Bool {
for component in components {
if component is ComponentExtensionStart { return true }
}
return false
}
private func getHasExtensionStop() -> Bool {
for component in components {
if component is ComponentExtensionStop { return true }
}
return false
}
private func getHasOnlyExtensionComponents() -> Bool {
for component in components {
if !(component is ComponentExtensionStart) && !(component is ComponentExtensionStop) {
return false
}
}
return true
}
public override func getDescription() -> String {
var description: String = "DurationNode"
if isRoot { description += " (root)" }
else if isLeaf { description = "leaf" }
else { description = "internal" }
// add duration info : make this DurationSpan
description += ": \(duration), offset: \(offsetDuration)"
if isRest { description += " (rest)" }
// add component info
if components.count > 0 {
description += ": "
for (c, component) in components.enumerate() {
if c > 0 { description += ", " }
description += "\(component)"
}
description += ";"
}
// traverse children
if isContainer {
for child in children {
description += "\n"
for _ in 0..<child.depth { description += "\t" }
description += "\(child)"
}
}
return description
}
}
public typealias DurationNodeStratum = [DurationNode]
/*
// MAKE EXTENSION -- add to DurationNode as class func
public func makeDurationSpanWithDurationNodes(durationNodes: [DurationNode]) -> DurationSpan {
if durationNodes.count == 0 { return DurationSpan() }
else {
let nds = durationNodes
let startDuration = nds.sort({
$0.durationSpan.startDuration < $1.durationSpan.startDuration
}).first!.durationSpan.startDuration
let stopDuration = nds.sort({
$0.durationSpan.stopDuration > $1.durationSpan.stopDuration
}).first!.durationSpan.stopDuration
return DurationSpan(startDuration: startDuration, stopDuration: stopDuration)
}
}
*/
|
gpl-2.0
|
2071524a30bbf766b65e29ccbe6a582c
| 34.314922 | 98 | 0.602541 | 4.811089 | false | false | false | false |
admkopec/BetaOS
|
Kernel/Modules/ACPI/MADT.swift
|
1
|
9488
|
//
// MADT.swift
// Kernel
//
// Created by Adam Kopeć on 10/31/17.
// Copyright © 2017-2018 Adam Kopeć. All rights reserved.
//
import Addressing
import Loggable
struct MADT: Loggable, ACPITable {
let Name = "MADT"
var Header: SDTHeader
fileprivate let tablePointer: UnsafeMutablePointer<ACPIMADT>
fileprivate let dataLength: Int
fileprivate(set) var madtEntries: [MADTEntry] = []
let LocalInterruptControllerAddress: Address
var HasCompatDual8259: Bool {
return tablePointer.pointee.MultipleAPICFlags.bit(0)
}
var description: String {
return "MADT: \(Header)"
}
init(ptr: Address) {
Header = SDTHeader(ptr: (UnsafeMutablePointer<ACPISDTHeader_t>(bitPattern: ptr.virtual))!)
tablePointer = UnsafeMutablePointer<ACPIMADT>(bitPattern: ptr.virtual)!
dataLength = Int(Header.Length) - MemoryLayout<ACPIMADT>.size
LocalInterruptControllerAddress = Address(tablePointer.pointee.LocalInterruptControllerAddress)
Log("Local Interrupt Controller Address = \(LocalInterruptControllerAddress)", level: .Info)
Log("HasCompatDual8259 = \(HasCompatDual8259)", level: .Info)
guard dataLength >= 2 else {
Log("dataLength is less than 2!", level: .Error)
return
}
madtEntries = decodeEntries()
for entry in madtEntries {
Log("Entry: \(entry.debugDescription)", level: .Debug)
}
}
fileprivate func decodeEntries() -> [MADTEntry] {
return (tablePointer + 1).withMemoryRebound(to: UInt8.self,
capacity: dataLength) {
var entries: [MADTEntry] = []
let controllers = UnsafeBufferPointer(start: $0,
count: dataLength)
var position = 0
while position < controllers.count {
let bytesRemaining = controllers.count - position
guard bytesRemaining > 2 else {
Log("BytesRemaining: \(bytesRemaining), count: \(controllers.count), position: \(position)", level: .Error)
fatalError()
}
let tableLen = Int(controllers[position + 1])
guard tableLen > 0 && tableLen <= controllers.count - position
else {
Log("Table Length: \(tableLen), position: \(position), controllers.count: \(controllers.count)", level: .Error)
fatalError()
}
let start: UnsafeMutablePointer<UInt8> = $0.advanced(by: position)
let tableData = UnsafeBufferPointer(start: start,
count: tableLen)
let table = decodeTable(table: tableData)
entries.append(table)
position += tableLen
}
return entries
}
}
fileprivate func decodeTable(table: UnsafeBufferPointer<UInt8>) -> MADTEntry {
guard let type = IntControllerTableType(rawValue: table[0]) else {
Log("Unknown MADT entry: \(String(table[0], radix: 16))", level: .Error)
fatalError()
}
switch type {
case .processorLocalApic:
return ProcessorLocalApicTable(table: table)
case .ioApic:
return IOApicTable(table: table)
case .interruptSourceOverride:
return InterruptSourceOverrideTable(table: table)
case .localApicNmi:
return LocalApicNmiTable(table: table)
default:
Log("\(type): unsupported", level: .Error)
fatalError()
}
}
//
// Tables:
//
struct ProcessorLocalApicTable: MADTEntry {
let tableType = IntControllerTableType.processorLocalApic
let tableLength = 8
let processorUID: UInt8
let apicID: UInt8
let localApicFlags: UInt32
var enabled: Bool { return localApicFlags.bit(0) }
var debugDescription: String {
return "\(tableType): uid: \(String(processorUID, radix: 16)) apicID: \(String(apicID, radix: 16)) flags: \(String(localApicFlags, radix: 16)) enabled: \(enabled ? "Yes" : "No")"
}
fileprivate init(table: UnsafeBufferPointer<UInt8>) {
guard table.count == tableLength else {
fatalError("Invalid ProcessorLocalApic size")
}
processorUID = table[2]
apicID = table[3]
// ACPI tables are all little endian
localApicFlags = UInt32(withBytes: table[4], table[5],
table[6], table[7]);
}
}
struct IOApicTable: MADTEntry {
let tableType = IntControllerTableType.ioApic
let tableLength = 12
let ioApicID: UInt8
let ioApicAddress: UInt32
let globalSystemInterruptBase: UInt32
var debugDescription: String {
let desc: String = String(describing: tableType)
+ ": APIC ID: \(String(ioApicID, radix: 16)) "
+ "Addr: \(String(ioApicAddress, radix: 16)) "
+ "Interrupt Base: \(String(globalSystemInterruptBase, radix: 16))"
return desc
}
fileprivate init(table: UnsafeBufferPointer<UInt8>) {
guard table.count == tableLength else {
fatalError("Invalid IOApicTable size")
}
ioApicID = table[2]
ioApicAddress = UInt32(withBytes: table[4], table[5],
table[6], table[7]);
globalSystemInterruptBase = UInt32(withBytes: table[8], table[9],
table[10], table[11])
}
}
struct InterruptSourceOverrideTable: MADTEntry {
let tableType = IntControllerTableType.interruptSourceOverride
let tableLength = 10
let bus: UInt8
let sourceIRQ: UInt8
let globalInterrupt: UInt32
let flags: UInt16
var debugDescription: String {
return "\(tableType): bus: \(String(bus, radix: 16)) irq: \(String(sourceIRQ, radix: 16)) globalInterrupt: \(String(globalInterrupt, radix: 16)) flags: \(String(flags, radix: 16))"
}
fileprivate init(table: UnsafeBufferPointer<UInt8>) {
guard table.count == tableLength else {
fatalError("Invalid InterruptSourceOverrideTable size")
}
bus = table[2]
sourceIRQ = table[3]
globalInterrupt = UInt32(withBytes: table[4], table[5],
table[6], table[7]);
flags = UInt16(withBytes: table[8], table[9])
}
}
struct LocalApicNmiTable: MADTEntry {
let tableType = IntControllerTableType.localApicNmi
let tableLength = 6
let acpiProcessorUID: UInt8
let flags: UInt16
let localApicLint: UInt8
var debugDescription: String {
return "\(tableType): processor UID: \(String(acpiProcessorUID, radix: 16)) flags: \(String(flags, radix: 16)) LINT# \(String(localApicLint, radix: 16))"
}
fileprivate init(table: UnsafeBufferPointer<UInt8>) {
guard table.count == tableLength else {
fatalError("Invalid LocalApicNmiTable size")
}
acpiProcessorUID = table[2]
flags = UInt16(withBytes: table[3], table[4])
localApicLint = table[5]
}
}
}
enum IntControllerTableType: UInt8 {
case processorLocalApic = 0x00
case ioApic = 0x01
case interruptSourceOverride = 0x02
case nmiSource = 0x03
case localApicNmi = 0x04
case localApicAddressOverride = 0x05
case ioSapic = 0x06
case localSapic = 0x07
case platformInterruptSources = 0x08
case processorLocalx2Apic = 0x09
case localx2ApicNmi = 0x0A
case gicCPUInterface = 0x0B
case gicDistributor = 0x0C
case gicMsiFrame = 0x0D
case gicRedistributor = 0x0E
case gicInterruptTranslationService = 0x0F
// 0x10 - 0x7F are reserved, 0x80-0xFF are for OEM use so treat as
// invalid for now
}
protocol MADTEntry: CustomDebugStringConvertible {
var tableType: IntControllerTableType { get }
}
|
apache-2.0
|
80f714c4541d341b854efd7e156e502c
| 40.060606 | 192 | 0.516183 | 5.021175 | false | false | false | false |
huonw/swift
|
test/Compatibility/exhaustive_switch.swift
|
1
|
30728
|
// RUN: %target-typecheck-verify-swift -swift-version 3 -enable-resilience
// RUN: %target-typecheck-verify-swift -swift-version 4 -enable-resilience
func foo(a: Int?, b: Int?) -> Int {
switch (a, b) {
case (.none, _): return 1
case (_, .none): return 2
case (.some(_), .some(_)): return 3
}
switch (a, b) {
case (.none, _): return 1
case (_, .none): return 2
case (_?, _?): return 3
}
switch Optional<(Int?, Int?)>.some((a, b)) {
case .none: return 1
case let (_, x?)?: return x
case let (x?, _)?: return x
case (.none, .none)?: return 0
}
}
func bar(a: Bool, b: Bool) -> Int {
switch (a, b) {
case (false, false):
return 1
case (true, _):
return 2
case (false, true):
return 3
}
}
enum Result<T> {
case Ok(T)
case Error(Error)
func shouldWork<U>(other: Result<U>) -> Int {
switch (self, other) { // No warning
case (.Ok, .Ok): return 1
case (.Error, .Error): return 2
case (.Error, _): return 3
case (_, .Error): return 4
}
}
}
enum Foo {
case A(Int)
case B(Int)
}
func foo() {
switch (Foo.A(1), Foo.B(1)) {
case (.A(_), .A(_)):
()
case (.B(_), _):
()
case (_, .B(_)):
()
}
switch (Foo.A(1), Optional<(Int, Int)>.some((0, 0))) {
case (.A(_), _):
break
case (.B(_), (let q, _)?):
print(q)
case (.B(_), nil):
break
}
}
class C {}
enum Bar {
case TheCase(C?)
}
func test(f: Bar) -> Bool {
switch f {
case .TheCase(_?):
return true
case .TheCase(nil):
return false
}
}
func op(this : Optional<Bool>, other : Optional<Bool>) -> Optional<Bool> {
switch (this, other) { // No warning
case let (.none, w):
return w
case let (w, .none):
return w
case let (.some(e1), .some(e2)):
return .some(e1 && e2)
}
}
enum Threepeat {
case a, b, c
}
func test3(x: Threepeat, y: Threepeat) {
switch (x, y) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{add missing case: '(.a, .c)'}}
case (.a, .a):
()
case (.b, _):
()
case (.c, _):
()
case (_, .b):
()
}
}
enum A {
case A(Int)
case B(Bool)
case C
case D
}
enum B {
case A
case B
}
func s(a: A, b: B) {
switch (a, b) {
case (.A(_), .A):
break
case (.A(_), .B):
break
case (.B(_), let b):
// expected-warning@-1 {{immutable value 'b' was never used; consider replacing with '_' or removing it}}
break
case (.C, _), (.D, _):
break
}
}
enum Grimble {
case A
case B
case C
}
enum Gromble {
case D
case E
}
func doSomething(foo:Grimble, bar:Gromble) {
switch(foo, bar) { // No warning
case (.A, .D):
break
case (.A, .E):
break
case (.B, _):
break
case (.C, _):
break
}
}
enum E {
case A
case B
}
func f(l: E, r: E) {
switch (l, r) {
case (.A, .A):
return
case (.A, _):
return
case (_, .A):
return
case (.B, .B):
return
}
}
enum TestEnum {
case A, B
}
func switchOverEnum(testEnumTuple: (TestEnum, TestEnum)) {
switch testEnumTuple {
case (_,.B):
// Matches (.A, .B) and (.B, .B)
break
case (.A,_):
// Matches (.A, .A)
// Would also match (.A, .B) but first case takes precedent
break
case (.B,.A):
// Matches (.B, .A)
break
}
}
func tests(a: Int?, b: String?) {
switch (a, b) {
case let (.some(n), _): print("a: ", n, "?")
case (.none, _): print("Nothing", "?")
}
switch (a, b) {
case let (.some(n), .some(s)): print("a: ", n, "b: ", s)
case let (.some(n), .none): print("a: ", n, "Nothing")
case (.none, _): print("Nothing")
}
switch (a, b) {
case let (.some(n), .some(s)): print("a: ", n, "b: ", s)
case let (.some(n), .none): print("a: ", n, "Nothing")
case let (.none, .some(s)): print("Nothing", "b: ", s)
case (.none, _): print("Nothing", "?")
}
switch (a, b) {
case let (.some(n), .some(s)): print("a: ", n, "b: ", s)
case let (.some(n), .none): print("a: ", n, "Nothing")
case let (.none, .some(s)): print("Nothing", "b: ", s)
case (.none, .none): print("Nothing", "Nothing")
}
}
enum X {
case Empty
case A(Int)
case B(Int)
}
func f(a: X, b: X) {
switch (a, b) {
case (_, .Empty): ()
case (.Empty, _): ()
case (.A, .A): ()
case (.B, .B): ()
case (.A, .B): ()
case (.B, .A): ()
}
}
func f2(a: X, b: X) {
switch (a, b) {
case (.A, .A): ()
case (.B, .B): ()
case (.A, .B): ()
case (.B, .A): ()
case (_, .Empty): ()
case (.Empty, _): ()
case (.A, .A): () // expected-warning {{case is already handled by previous patterns; consider removing it}}
case (.B, .B): () // expected-warning {{case is already handled by previous patterns; consider removing it}}
case (.A, .B): () // expected-warning {{case is already handled by previous patterns; consider removing it}}
case (.B, .A): () // expected-warning {{case is already handled by previous patterns; consider removing it}}
default: ()
}
}
enum XX : Int {
case A
case B
case C
case D
case E
}
func switcheroo(a: XX, b: XX) -> Int {
switch(a, b) { // No warning
case (.A, _) : return 1
case (_, .A) : return 2
case (.C, _) : return 3
case (_, .C) : return 4
case (.B, .B) : return 5
case (.B, .D) : return 6
case (.D, .B) : return 7
case (.B, .E) : return 8
case (.E, .B) : return 9
case (.E, _) : return 10
case (_, .E) : return 11
case (.D, .D) : return 12
default:
print("never hits this:", a, b)
return 13
}
}
enum PatternCasts {
case one(Any)
case two
}
func checkPatternCasts() {
// Pattern casts with this structure shouldn't warn about duplicate cases.
let x: PatternCasts = .one("One")
switch x {
case .one(let s as String): print(s)
case .one: break
case .two: break
}
// But should warn here.
switch x {
case .one(_): print(s)
case .one: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
case .two: break
}
}
enum MyNever {}
func ~= (_ : MyNever, _ : MyNever) -> Bool { return true }
func myFatalError() -> MyNever { fatalError() }
func checkUninhabited() {
// Scrutinees of uninhabited type may match any number and kind of patterns
// that Sema is willing to accept at will. After all, it's quite a feat to
// productively inhabit the type of crashing programs.
func test1(x : Never) {
switch x {} // No diagnostic.
}
func test2(x : Never) {
switch (x, x) {} // No diagnostic.
}
func test3(x : MyNever) {
switch x { // No diagnostic.
case myFatalError(): break
case myFatalError(): break
case myFatalError(): break
}
}
}
enum Runcible {
case spoon
case hat
case fork
}
func checkDiagnosticMinimality(x: Runcible?) {
switch (x!, x!) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{add missing case: '(.fork, _)'}}
// expected-note@-2 {{add missing case: '(.hat, .hat)'}}
// expected-note@-3 {{add missing case: '(_, .fork)'}}
case (.spoon, .spoon):
break
case (.spoon, .hat):
break
case (.hat, .spoon):
break
}
switch (x!, x!) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{add missing case: '(.fork, _)'}}
// expected-note@-2 {{add missing case: '(.hat, .spoon)'}}
// expected-note@-3 {{add missing case: '(.spoon, .hat)'}}
// expected-note@-4 {{add missing case: '(_, .fork)'}}
case (.spoon, .spoon):
break
case (.hat, .hat):
break
}
}
enum LargeSpaceEnum {
case case0
case case1
case case2
case case3
case case4
case case5
case case6
case case7
case case8
case case9
case case10
}
func notQuiteBigEnough() -> Bool {
switch (LargeSpaceEnum.case1, LargeSpaceEnum.case2) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 110 {{add missing case:}}
case (.case0, .case0): return true
case (.case1, .case1): return true
case (.case2, .case2): return true
case (.case3, .case3): return true
case (.case4, .case4): return true
case (.case5, .case5): return true
case (.case6, .case6): return true
case (.case7, .case7): return true
case (.case8, .case8): return true
case (.case9, .case9): return true
case (.case10, .case10): return true
}
}
enum OverlyLargeSpaceEnum {
case case0
case case1
case case2
case case3
case case4
case case5
case case6
case case7
case case8
case case9
case case10
case case11
}
enum ContainsOverlyLargeEnum {
case one(OverlyLargeSpaceEnum)
case two(OverlyLargeSpaceEnum)
case three(OverlyLargeSpaceEnum, OverlyLargeSpaceEnum)
}
func quiteBigEnough() -> Bool {
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{the compiler is unable to check that this switch is exhaustive in reasonable time}}
// expected-note@-1 {{do you want to add a default clause?}}
case (.case0, .case0): return true
case (.case1, .case1): return true
case (.case2, .case2): return true
case (.case3, .case3): return true
case (.case4, .case4): return true
case (.case5, .case5): return true
case (.case6, .case6): return true
case (.case7, .case7): return true
case (.case8, .case8): return true
case (.case9, .case9): return true
case (.case10, .case10): return true
case (.case11, .case11): return true
}
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{the compiler is unable to check that this switch is exhaustive in reasonable time}}
// expected-note@-1 {{do you want to add a default clause?}}
case (.case0, _): return true
case (.case1, _): return true
case (.case2, _): return true
case (.case3, _): return true
case (.case4, _): return true
case (.case5, _): return true
case (.case6, _): return true
case (.case7, _): return true
case (.case8, _): return true
case (.case9, _): return true
case (.case10, _): return true
}
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) { // expected-error {{the compiler is unable to check that this switch is exhaustive in reasonable time}}
case (.case0, _): return true
case (.case1, _): return true
case (.case2, _): return true
case (.case3, _): return true
case (.case4, _): return true
case (.case5, _): return true
case (.case6, _): return true
case (.case7, _): return true
case (.case8, _): return true
case (.case9, _): return true
case (.case10, _): return true
@unknown default: return false // expected-note {{remove '@unknown' to handle remaining values}} {{3-12=}}
}
// No diagnostic
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
case (.case0, _): return true
case (.case1, _): return true
case (.case2, _): return true
case (.case3, _): return true
case (.case4, _): return true
case (.case5, _): return true
case (.case6, _): return true
case (.case7, _): return true
case (.case8, _): return true
case (.case9, _): return true
case (.case10, _): return true
case (.case11, _): return true
}
// No diagnostic
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
case (_, .case0): return true
case (_, .case1): return true
case (_, .case2): return true
case (_, .case3): return true
case (_, .case4): return true
case (_, .case5): return true
case (_, .case6): return true
case (_, .case7): return true
case (_, .case8): return true
case (_, .case9): return true
case (_, .case10): return true
case (_, .case11): return true
}
// No diagnostic
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
case (_, _): return true
}
// No diagnostic
switch (OverlyLargeSpaceEnum.case1, OverlyLargeSpaceEnum.case2) {
case (.case0, .case0): return true
case (.case1, .case1): return true
case (.case2, .case2): return true
case (.case3, .case3): return true
case _: return true
}
// No diagnostic
switch ContainsOverlyLargeEnum.one(.case0) {
case .one: return true
case .two: return true
case .three: return true
}
// Make sure we haven't just stopped emitting diagnostics.
switch OverlyLargeSpaceEnum.case1 { // expected-error {{switch must be exhaustive}} expected-note 12 {{add missing case}}
}
}
indirect enum InfinitelySized {
case one
case two
case recur(InfinitelySized)
case mutualRecur(MutuallyRecursive, InfinitelySized)
}
indirect enum MutuallyRecursive {
case one
case two
case recur(MutuallyRecursive)
case mutualRecur(InfinitelySized, MutuallyRecursive)
}
func infinitelySized() -> Bool {
switch (InfinitelySized.one, InfinitelySized.one) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 8 {{add missing case:}}
case (.one, .one): return true
case (.two, .two): return true
}
switch (MutuallyRecursive.one, MutuallyRecursive.one) { // expected-error {{switch must be exhaustive}}
// expected-note@-1 8 {{add missing case:}}
case (.one, .one): return true
case (.two, .two): return true
}
}
func diagnoseDuplicateLiterals() {
let str = "def"
let int = 2
let dbl = 2.5
// No Diagnostics
switch str {
case "abc": break
case "def": break
case "ghi": break
default: break
}
switch str {
case "abc": break
case "def": break // expected-note {{first occurrence of identical literal pattern is here}}
case "def": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case "ghi": break
default: break
}
switch str {
case "abc", "def": break // expected-note 2 {{first occurrence of identical literal pattern is here}}
case "ghi", "jkl": break
case "abc", "def": break // expected-warning 2 {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
switch str {
case "xyz": break // expected-note {{first occurrence of identical literal pattern is here}}
case "ghi": break
case "def": break
case "abc": break
case "xyz": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
func someStr() -> String { return "sdlkj" }
let otherStr = "ifnvbnwe"
switch str {
case "sdlkj": break
case "ghi": break // expected-note {{first occurrence of identical literal pattern is here}}
case someStr(): break
case "def": break
case otherStr: break
case "xyz": break // expected-note {{first occurrence of identical literal pattern is here}}
case "ifnvbnwe": break
case "ghi": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case "xyz": break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
// No Diagnostics
switch int {
case -2: break
case -1: break
case 0: break
case 1: break
case 2: break
case 3: break
default: break
}
switch int {
case -2: break // expected-note {{first occurrence of identical literal pattern is here}}
case -2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 1: break
case 2: break // expected-note {{first occurrence of identical literal pattern is here}}
case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 3: break
default: break
}
switch int {
case -2, -2: break // expected-note {{first occurrence of identical literal pattern is here}} expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 1, 2: break // expected-note 3 {{first occurrence of identical literal pattern is here}}
case 2, 3: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 1, 2: break // expected-warning 2 {{literal value is already handled by previous pattern; consider removing it}}
case 4, 5: break
case 7, 7: break // expected-note {{first occurrence of identical literal pattern is here}}
// expected-warning@-1 {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
switch int {
case 1: break // expected-note {{first occurrence of identical literal pattern is here}}
case 2: break // expected-note 2 {{first occurrence of identical literal pattern is here}}
case 3: break
case 17: break // expected-note {{first occurrence of identical literal pattern is here}}
case 4: break
case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 001: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 5: break
case 0x11: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 0b10: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
switch int {
case 10: break
case 0b10: break // expected-note {{first occurrence of identical literal pattern is here}}
case -0b10: break // expected-note {{first occurrence of identical literal pattern is here}}
case 3000: break
case 0x12: break // expected-note {{first occurrence of identical literal pattern is here}}
case 400: break
case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case -2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 18: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
func someInt() -> Int { return 0x1234 }
let otherInt = 13254
switch int {
case 13254: break
case 3000: break
case 00000002: break // expected-note {{first occurrence of identical literal pattern is here}}
case 0x1234: break
case someInt(): break
case 400: break
case 2: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 18: break
case otherInt: break
case 230: break
default: break
}
// No Diagnostics
switch dbl {
case -3.5: break
case -2.5: break
case -1.5: break
case 1.5: break
case 2.5: break
case 3.5: break
default: break
}
switch dbl {
case -3.5: break
case -2.5: break // expected-note {{first occurrence of identical literal pattern is here}}
case -2.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case -1.5: break
case 1.5: break
case 2.5: break // expected-note {{first occurrence of identical literal pattern is here}}
case 2.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 3.5: break
default: break
}
switch dbl {
case 1.5, 4.5, 7.5, 6.9: break // expected-note 2 {{first occurrence of identical literal pattern is here}}
case 3.4, 1.5: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 7.5, 2.3: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
switch dbl {
case 1: break
case 1.5: break // expected-note 2 {{first occurrence of identical literal pattern is here}}
case 2.5: break
case 3.5: break // expected-note {{first occurrence of identical literal pattern is here}}
case 5.3132: break
case 1.500: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 46.2395: break
case 1.5000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 0003.50000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 23452.43: break
default: break
}
func someDouble() -> Double { return 324.4523 }
let otherDouble = 458.2345
switch dbl {
case 1: break // expected-note {{first occurrence of identical literal pattern is here}}
case 1.5: break
case 2.5: break
case 3.5: break // expected-note {{first occurrence of identical literal pattern is here}}
case 5.3132: break
case 46.2395: break
case someDouble(): break
case 0003.50000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case otherDouble: break
case 2.50505: break // expected-note {{first occurrence of identical literal pattern is here}}
case 23452.43: break
case 00001: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
case 123453: break
case 2.50505000000: break // expected-warning {{literal value is already handled by previous pattern; consider removing it}}
default: break
}
}
func checkLiteralTuples() {
let str1 = "abc"
let str2 = "def"
let int1 = 23
let int2 = 7
let dbl1 = 4.23
let dbl2 = 23.45
// No Diagnostics
switch (str1, str2) {
case ("abc", "def"): break
case ("def", "ghi"): break
case ("ghi", "def"): break
case ("abc", "def"): break // We currently don't catch this
default: break
}
// No Diagnostics
switch (int1, int2) {
case (94, 23): break
case (7, 23): break
case (94, 23): break // We currently don't catch this
case (23, 7): break
default: break
}
// No Diagnostics
switch (dbl1, dbl2) {
case (543.21, 123.45): break
case (543.21, 123.45): break // We currently don't catch this
case (23.45, 4.23): break
case (4.23, 23.45): break
default: break
}
}
func sr6975() {
enum E {
case a, b
}
let e = E.b
switch e {
case .a as E: // expected-warning {{'as' test is always true}}
print("a")
case .b: // Valid!
print("b")
case .a: // expected-warning {{case is already handled by previous patterns; consider removing it}}
print("second a")
}
}
public enum NonExhaustive {
case a, b
}
public enum NonExhaustivePayload {
case a(Int), b(Bool)
}
@_frozen public enum TemporalProxy {
case seconds(Int)
case milliseconds(Int)
case microseconds(Int)
case nanoseconds(Int)
@_downgrade_exhaustivity_check
case never
}
// Inlinable code is considered "outside" the module and must include a default
// case.
@inlinable
public func testNonExhaustive(_ value: NonExhaustive, _ payload: NonExhaustivePayload, for interval: TemporalProxy, flag: Bool) {
switch value { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}}
case .a: break
}
switch value { // no-warning
case .a: break
case .b: break
}
switch value {
case .a: break
case .b: break
default: break // no-warning
}
switch value {
case .a: break
case .b: break
@unknown case _: break // no-warning
}
switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}}
case .a: break
@unknown case _: break
}
switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.a'}} {{none}} expected-note {{add missing case: '.b'}} {{none}}
@unknown case _: break
}
switch value {
case _: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
// Test being part of other spaces.
switch value as Optional { // no-warning
case .a?: break
case .b?: break
case nil: break
}
switch value as Optional {
case _?: break
case nil: break
} // no-warning
switch value as Optional {
case .a?: break
case .b?: break
case nil: break
@unknown case _: break
} // no-warning
switch (value, flag) { // no-warning
case (.a, _): break
case (.b, false): break
case (_, true): break
}
switch (value, flag) {
case (.a, _): break
case (.b, false): break
case (_, true): break
@unknown case _: break
} // no-warning
switch (flag, value) { // no-warning
case (_, .a): break
case (false, .b): break
case (true, _): break
}
switch (flag, value) {
case (_, .a): break
case (false, .b): break
case (true, _): break
@unknown case _: break
} // no-warning
switch (value, value) { // no-warning
case (.a, _), (_, .a): break
case (.b, _), (_, .b): break
}
switch (value, value) {
case (.a, _), (_, .a): break
case (.b, _), (_, .b): break
@unknown case _: break
} // no-warning
// Test interaction with @_downgrade_exhaustivity_check.
switch (value, interval) { // no-warning
case (_, .seconds): break
case (.a, _): break
case (.b, _): break
}
switch (value, interval) { // no-warning
case (_, .never): break
case (.a, _): break
case (.b, _): break
}
// Test payloaded enums.
switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}}
case .a: break
}
switch payload { // no-warning
case .a: break
case .b: break
}
switch payload {
case .a: break
case .b: break
default: break // no-warning
}
switch payload {
case .a: break
case .b: break
@unknown case _: break // no-warning
}
switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}}
case .a: break
@unknown case _: break
}
switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}}
case .a: break
case .b(false): break
}
switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}}
case .a: break
case .b(false): break
@unknown case _: break
}
// Test fully-covered switches.
switch interval {
case .seconds, .milliseconds, .microseconds, .nanoseconds: break
case .never: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
switch flag {
case true: break
case false: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
switch flag as Optional {
case _?: break
case nil: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
switch (flag, value) {
case (true, _): break
case (false, _): break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
}
public func testNonExhaustiveWithinModule(_ value: NonExhaustive, _ payload: NonExhaustivePayload, for interval: TemporalProxy, flag: Bool) {
switch value { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}}
case .a: break
}
switch value { // no-warning
case .a: break
case .b: break
}
switch value {
case .a: break
case .b: break
default: break // no-warning
}
switch value {
case .a: break
case .b: break
@unknown case _: break // no-warning
}
switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b'}} {{none}}
case .a: break
@unknown case _: break
}
switch value { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.a'}} {{none}} expected-note {{add missing case: '.b'}} {{none}}
@unknown case _: break
}
switch value {
case _: break
@unknown case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
// Test being part of other spaces.
switch value as Optional { // no-warning
case .a?: break
case .b?: break
case nil: break
}
switch value as Optional {
case _?: break
case nil: break
} // no-warning
switch (value, flag) { // no-warning
case (.a, _): break
case (.b, false): break
case (_, true): break
}
switch (flag, value) { // no-warning
case (_, .a): break
case (false, .b): break
case (true, _): break
}
switch (value, value) { // no-warning
case (.a, _): break
case (.b, _): break
case (_, .a): break
case (_, .b): break
}
switch (value, value) { // no-warning
case (.a, _): break
case (.b, _): break
case (_, .a): break
case (_, .b): break
@unknown case _: break
}
// Test interaction with @_downgrade_exhaustivity_check.
switch (value, interval) { // no-warning
case (_, .seconds): break
case (.a, _): break
case (.b, _): break
}
switch (value, interval) { // no-warning
case (_, .never): break
case (.a, _): break
case (.b, _): break
}
// Test payloaded enums.
switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}}
case .a: break
}
switch payload { // no-warning
case .a: break
case .b: break
}
switch payload {
case .a: break
case .b: break
default: break // no-warning
}
switch payload {
case .a: break
case .b: break
@unknown case _: break // no-warning
}
switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(_)'}} {{none}}
case .a: break
@unknown case _: break
}
switch payload { // expected-error {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}}
case .a: break
case .b(false): break
}
switch payload { // expected-warning {{switch must be exhaustive}} {{none}} expected-note {{add missing case: '.b(true)'}} {{none}}
case .a: break
case .b(false): break
@unknown case _: break
}
}
enum UnavailableCase {
case a
case b
@available(*, unavailable)
case oopsThisWasABadIdea
}
enum UnavailableCaseOSSpecific {
case a
case b
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
@available(macOS, unavailable)
@available(iOS, unavailable)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
case unavailableOnAllTheseApplePlatforms
#else
@available(*, unavailable)
case dummyCaseForOtherPlatforms
#endif
}
enum UnavailableCaseOSIntroduced {
case a
case b
@available(macOS 50, iOS 50, tvOS 50, watchOS 50, *)
case notYetIntroduced
}
func testUnavailableCases(_ x: UnavailableCase, _ y: UnavailableCaseOSSpecific, _ z: UnavailableCaseOSIntroduced) {
switch x {
case .a: break
case .b: break
} // no-error
switch y {
case .a: break
case .b: break
} // no-error
switch z {
case .a: break
case .b: break
case .notYetIntroduced: break
} // no-error
}
|
apache-2.0
|
b06d71399e2f5dcc7c97cf5cf819a915
| 24.908938 | 191 | 0.636195 | 3.596442 | false | false | false | false |
urbn/URBNValidator
|
Pod/Classes/ObjC/URBNValidatorCompat.swift
|
1
|
2667
|
//
// URBNValidatorCompat.swift
// URBNValidator
//
// Created by Nick DiStefano on 12/21/15.
//
//
import Foundation
@objc public protocol CompatValidator {
var localizationBundle: Bundle { get }
func validateKey(_ key: String, withValue value: AnyObject?, rule: URBNCompatBaseRule) throws
func validate(_ item: CompatValidateable , stopOnFirstError: Bool) throws
}
@objc public protocol CompatValidateable {
func validationMap() -> [String: CompatValidatingValue]
}
extension CompatValidateable {
func backingValidationMap() -> [String: ValidatingValue<AnyObject>] {
return validationMap().reduce([String: ValidatingValue<AnyObject>]()) { (dict, items: (key: String, value: CompatValidatingValue)) -> [String: ValidatingValue<AnyObject>] in
var dictionary = dict
dictionary[items.key] = items.value.backingRules()
return dictionary
}
}
}
@objc open class URBNCompatValidator: NSObject, CompatValidator {
fileprivate var backingValidator: URBNValidator = URBNValidator(bundle: Bundle(for: URBNCompatValidator.self))
open var localizationBundle: Bundle {
get {
return backingValidator.localizationBundle
}
set {
backingValidator.localizationBundle = newValue
}
}
open func validateKey(_ key: String, withValue value: AnyObject?, rule: URBNCompatBaseRule) throws {
try backingValidator.validate(key, value: value, rule: rule.backingRule)
}
open func validate(_ item: CompatValidateable , stopOnFirstError: Bool) throws {
try backingValidator.validate(ConvertCompat(cv: item), stopOnFirstError: stopOnFirstError)
}
}
class ConvertCompat: Validateable {
typealias V = AnyObject
var rules = [String: ValidatingValue<V>]()
init(cv: CompatValidateable) {
rules = cv.backingValidationMap()
}
func validationMap() -> [String : ValidatingValue<V>] {
return rules
}
}
@objc open class CompatValidatingValue: NSObject {
open var value: AnyObject?
open var rules: [URBNCompatBaseRule]
public init(_ value: AnyObject?, rules: [URBNCompatBaseRule]) {
self.value = value
self.rules = rules
super.init()
}
public convenience init(value: AnyObject?, rules: URBNCompatBaseRule...) {
self.init(value, rules: rules)
}
}
extension CompatValidatingValue {
func backingRules() -> ValidatingValue<AnyObject> {
let mrules = rules.map { $0.backingRule as ValidationRule }
let v = ValidatingValue(value, rules: mrules)
return v
}
}
|
mit
|
7aeb9a972119b53b821e8ab019e79de3
| 28.633333 | 181 | 0.670791 | 4.452421 | false | false | false | false |
ProVir/WebServiceSwift
|
WebServiceExample/ViewController.swift
|
1
|
6979
|
//
// ViewController.swift
// WebServiceExample
//
// Created by Короткий Виталий on 24.08.17.
// Copyright © 2017 ProVir. All rights reserved.
//
import UIKit
import WebServiceSwift
class ViewController: UIViewController {
@IBOutlet weak var rawTextView: UITextView!
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var rawSwitch: UISwitch!
let siteWebProvider: SiteWebProvider = WebService.createDefault().createProvider()
let siteYouTubeProvider: WebServiceRequestProvider<SiteWebServiceRequests.SiteYouTube> = WebService.default.createProvider()
override func viewDidLoad() {
super.viewDidLoad()
let rawLabel = UILabel(frame: .zero)
rawLabel.text = "Raw mode: "
rawLabel.sizeToFit()
let rawItem = UIBarButtonItem(customView: rawLabel)
navigationItem.rightBarButtonItems?.append(rawItem)
siteWebProvider.delegate = self
siteYouTubeProvider.excludeDuplicateDefault = true
}
@IBAction func actionChangeRaw() {
if rawSwitch.isOn {
rawTextView.isHidden = false
webView.isHidden = true
} else {
rawTextView.isHidden = true
webView.isHidden = false
}
}
@IBAction func actionSelect(_ sender: Any) {
let alert = UIAlertController(title: "Site select", message: "Select site to go, please:", preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Google.com",
style: .default,
handler: { _ in
self.requestSiteSearch(.init(site: .google, domain: "com"))
}))
alert.addAction(UIAlertAction(title: "Google.ru",
style: .default,
handler: { _ in
self.requestSiteSearch(.init(site: .google, domain: "ru"))
}))
alert.addAction(UIAlertAction(title: "Yandex.ru",
style: .default,
handler: { _ in
self.requestSiteSearch(.init(site: .yandex, domain: "ru"))
}))
alert.addAction(UIAlertAction(title: "GMail",
style: .default,
handler: { _ in
self.requestSiteMail(.init(site: .google))
}))
alert.addAction(UIAlertAction(title: "Mail.ru",
style: .default,
handler: { _ in
self.requestSiteMail(.init(site: .mail))
}))
alert.addAction(UIAlertAction(title: "YouTube",
style: .default,
handler: { _ in
self.requestSiteYouTube()
}))
present(alert, animated: true, completion: nil)
}
@IBAction func actionDeleteAll(_ sender: UIBarButtonItem) {
WebService.default.deleteAllInStorages()
}
//MARK: Requests
func requestSiteSearch(_ request: SiteWebServiceRequests.SiteSearch) {
siteWebProvider.cancelAllRequests()
siteYouTubeProvider.cancelRequests()
siteWebProvider.requestHtmlDataFromSiteSearch(request, dataFromStorage: { [weak self] html in
self?.rawTextView.text = html
self?.webView.loadHTMLString(html, baseURL: request.urlSite)
}) { [weak self] response in
switch response {
case .data(let html):
self?.webServiceResponse(request: request, isStorageRequest: false, html: html)
case .error(let error):
self?.webServiceResponse(isStorageRequest: false, error: error)
case .canceledRequest:
break
}
}
}
func requestSiteMail(_ request: SiteWebServiceRequests.SiteMail) {
siteYouTubeProvider.cancelRequests()
siteWebProvider.requestHtmlDataFromSiteMail(request, includeResponseStorage: true)
}
func requestSiteYouTube() {
siteWebProvider.cancelAllRequests()
siteYouTubeProvider.readStorage(dependencyNextRequest: .dependFull) { [weak self] (timeStamp, response) in
if case .data(let html) = response {
if let timeStamp = timeStamp { print("Data from storage timeStamp = \(timeStamp)") }
self?.webServiceResponse(request: SiteWebServiceRequests.SiteYouTube(), isStorageRequest: true, html: html)
}
}
siteYouTubeProvider.performRequest { [weak self] response in
switch response {
case .data(let html):
self?.webServiceResponse(request: SiteWebServiceRequests.SiteYouTube(), isStorageRequest: false, html: html)
case .error(let error):
self?.webServiceResponse(isStorageRequest: false, error: error)
case .canceledRequest:
break
}
}
}
}
//MARK: Responses
extension ViewController: SiteWebProviderDelegate {
func webServiceResponse(request: WebServiceBaseRequesting, isStorageRequest: Bool, html: String) {
let baseUrl: URL
if let request = request as? SiteWebServiceRequests.SiteSearch {
baseUrl = request.urlSite
} else if let request = request as? SiteWebServiceRequests.SiteMail {
baseUrl = request.urlSite
} else if let request = request as? SiteWebServiceRequests.SiteYouTube {
baseUrl = request.urlSite
} else {
return
}
rawTextView.text = html
webView.loadHTMLString(html, baseURL: baseUrl)
}
func webServiceResponse(request: WebServiceBaseRequesting, isStorageRequest: Bool, error: Error) {
webServiceResponse(isStorageRequest: isStorageRequest, error: error)
}
func webServiceResponse(isStorageRequest: Bool, error: Error) {
if isStorageRequest {
print("Error read from storage: \(error)")
return
}
let text = (error as NSError).localizedDescription
let alert = UIAlertController(title: "Error", message: text, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK",
style: .default,
handler: nil))
present(alert, animated: true, completion: nil)
}
}
|
mit
|
c69c9a78f4ca42323bdda93ef4680c33
| 36.637838 | 128 | 0.556082 | 5.315267 | false | false | false | false |
jad6/CV
|
Swift/Jad's CV/Sections/Education/EducationView_Phone.swift
|
1
|
5852
|
//
// EducationView_Phone.swift
// Jad's CV
//
// Created by Jad Osseiran on 28/07/2014.
// Copyright (c) 2014 Jad. All rights reserved.
//
import UIKit
class EducationView_Phone: EducationView {
//MARK:- Constants
private struct LayoutConstants_Phone {
struct Padding {
static let betweenTopInfoAndTextView: CGFloat = 10.0
}
struct TextView {
static let fadeImageViewOffsetBeforeBackgroundImageView: CGFloat = 88.0
static let backgroundImageViewOffsetBeforeEndOftext: CGFloat = 44.0
static let backgroundImageViewHeight: CGFloat = 320.0
static var fadeImageViewHeight: CGFloat {
return backgroundImageViewHeight + fadeImageViewOffsetBeforeBackgroundImageView
}
static var bottomInset: CGFloat {
return backgroundImageViewHeight - backgroundImageViewOffsetBeforeEndOftext
}
}
}
//MARK:- Properties
private var textViewTextHeight: CGFloat = 0.0
private let fadeImageView = UIImageView()
//MARK:- Init
required init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
let fadeImage = UIImage(named: "fade_down").resizableImageWithCapInsets(UIEdgeInsets(top: 0.0, left: 1.0, bottom: 260.0, right: 1.0))
self.fadeImageView.image = fadeImage
self.backgroundImageView.contentMode = .ScaleAspectFill
self.textView.showsVerticalScrollIndicator = false
self.textView.textContainerInset = UIEdgeInsets(top: 0.0, left: 40.0, bottom: LayoutConstants_Phone.TextView.bottomInset, right: 40.0)
self.textView.addObserver(self, forKeyPath: "contentSize", options: .New, context: nil)
self.textView.addSubview(self.backgroundImageView)
self.textView.sendSubviewToBack(self.backgroundImageView)
self.textView.insertSubview(self.fadeImageView, aboveSubview: self.backgroundImageView)
}
deinit {
self.textView.removeObserver(self, forKeyPath: "contentSize")
}
//MARK:- Layout
override func layoutSubviews() {
super.layoutSubviews()
universityLogoImageView.frame.size = LayoutConstants.imageViewSize
universityLogoImageView.frame.origin.x = LayoutConstants.Padding.side
let labelXOrigin = universityLogoImageView.frame.maxX + LayoutConstants.Padding.betweenHorizontal
let boundingLabelWidth = bounds.size.width - labelXOrigin
let boundingLabelSize = CGSize(width: boundingLabelWidth, height: bounds.size.height)
statusLabel.frame.size = statusLabel.sizeThatFits(boundingLabelSize)
statusLabel.frame.origin.x = labelXOrigin
statusLabel.frame.origin.y = LayoutConstants.Padding.top
establishmentLabel.frame.size = establishmentLabel.sizeThatFits(boundingLabelSize)
establishmentLabel.frame.origin.x = labelXOrigin
establishmentLabel.frame.origin.y = statusLabel.frame.maxY + LayoutConstants.Padding.betweenVertical
completionDateLabel.frame.size = completionDateLabel.sizeThatFits(boundingLabelSize)
completionDateLabel.frame.origin.x = labelXOrigin
completionDateLabel.frame.origin.y = establishmentLabel.frame.maxY + LayoutConstants.Padding.betweenVertical
let totalLabelHeights = totalHeight(views: [statusLabel, establishmentLabel, completionDateLabel], separatorLength: LayoutConstants.Padding.betweenVertical)
universityLogoImageView.frame.origin.y = statusLabel.frame.origin.y + floor((totalLabelHeights - universityLogoImageView.frame.size.height) / 2.0)
textView.frame.size.width = bounds.width
textView.frame.origin.y = max(universityLogoImageView.frame.maxY, completionDateLabel.frame.maxY) + LayoutConstants_Phone.Padding.betweenTopInfoAndTextView
textView.frame.size.height = bounds.size.height - textView.frame.origin.y
backgroundImageView.frame.size.width = textView.frame.width
backgroundImageView.frame.size.height = LayoutConstants_Phone.TextView.backgroundImageViewHeight
backgroundImageView.frame.origin.y = textViewTextHeight - LayoutConstants_Phone.TextView.backgroundImageViewOffsetBeforeEndOftext
fadeImageView.frame.size.width = textView.frame.width
fadeImageView.frame.size.height = LayoutConstants_Phone.TextView.fadeImageViewHeight
fadeImageView.frame.origin.y = backgroundImageView.frame.origin.y - LayoutConstants_Phone.TextView.fadeImageViewOffsetBeforeBackgroundImageView
}
//MARK:- Logic
func recalculateTextViewTextHeight() {
let boundingSize = CGSize(width: textView.frame.size.width - textView.textContainerInset.left - textView.textContainerInset.right, height: CGFloat.max)
//FIXME: When Apple fixes the NSStringDrawingOptions on iOS do that.
// let options: NSStringDrawingOptions = .UsesLineFragmentOrigin | .UsesFontLeading
let textSize = textView.text.boundingRectWithSize(boundingSize, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: textView.font], context: nil)
textViewTextHeight = textSize.height
}
//MARK:- KVO
override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafeMutablePointer<()>) {
if keyPath == "contentSize" {
recalculateTextViewTextHeight()
}
}
//MARK:- Dynamic type
override func reloadDynamicTypeContent() {
super.reloadDynamicTypeContent()
recalculateTextViewTextHeight()
}
}
|
bsd-3-clause
|
cfb0420f56e84d7fa049c896be407dfd
| 42.348148 | 169 | 0.704204 | 5.169611 | false | false | false | false |
daniochouno/CollectionViewCells
|
CollectionViewCells/CollectionViewController.swift
|
1
|
3766
|
//
// ViewController.swift
// CollectionViewCells
//
// Created by daniel.martinez on 26/8/15.
// Copyright (c) 2015 info.danielmartinez. All rights reserved.
//
import UIKit
class CollectionViewController: UICollectionViewController, UISearchResultsUpdating, UISearchBarDelegate {
@IBOutlet weak var searchbarView: UIView!
var resultSearchController = UISearchController()
var searchButton: UIBarButtonItem!
private let reuseIdentifier = "cellIdentifier"
var items: [String]!
var filteredItems: [String]!
override func viewDidLoad() {
super.viewDidLoad()
initializeItems()
setupSearchBar()
}
func initializeItems() {
items = []
for (var i = 0; i < 40; i++) {
items.append("Hello\(i)")
}
filteredItems = items
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
self.navigationItem.titleView = nil
self.navigationItem.rightBarButtonItem = searchButton
}
func showSearch() {
self.navigationItem.rightBarButtonItem = nil
self.navigationItem.titleView = resultSearchController.searchBar
resultSearchController.searchBar.becomeFirstResponder()
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchText = searchController.searchBar.text
if ((searchText == nil) || (searchText == "")) {
filteredItems = items
} else {
filteredItems = items.filter { $0.rangeOfString(searchText) != nil }
}
self.collectionView!.reloadData()
}
func setupSearchBar() {
searchButton = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "showSearch")
navigationItem.rightBarButtonItem = searchButton
self.resultSearchController = {
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = false
controller.hidesNavigationBarDuringPresentation = false // default true
controller.searchBar.sizeToFit()
return controller
}()
self.resultSearchController.searchBar.delegate = self
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return filteredItems.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CircleWithNotificationCollectionViewCell
let item: String = self.filteredItems[indexPath.row]
cell.imageView.layer.cornerRadius = cell.imageView.frame.size.width/2
cell.imageView.clipsToBounds = true
cell.imageView.layer.borderColor = UIColor.whiteColor().CGColor
cell.imageView.layer.borderWidth = 5.0
cell.imageView.image = UIImage(named: "ExampleImage")
cell.notificationIcon.textContainerInset = UIEdgeInsetsMake(2, 2, 2, 2)
cell.notificationIcon.text = "99999999"
cell.notificationIcon.layer.cornerRadius = 5
cell.locationName.text = item
var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
var blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = cell.imageView.bounds
cell.imageView.addSubview(blurEffectView)
return cell
}
}
|
mit
|
47f84fb19a5bd1f9276a4abe88048244
| 33.236364 | 159 | 0.664896 | 5.893584 | false | false | false | false |
RoverPlatform/rover-ios
|
Sources/Experiences/Services/ExperienceStore/ExperienceStoreService.swift
|
1
|
3950
|
//
// ExperienceStoreService.swift
// Rover
//
// Created by Sean Rucker on 2019-05-10.
// Copyright © 2019 Rover Labs Inc. All rights reserved.
//
import Foundation
import os.log
import RoverFoundation
import RoverData
class ExperienceStoreService: ExperienceStore {
let client: FetchExperienceClient
init(client: FetchExperienceClient) {
self.client = client
}
private class CacheKey: NSObject {
let identifier: ExperienceIdentifier
init(identifier: ExperienceIdentifier) {
self.identifier = identifier
}
override func isEqual(_ object: Any?) -> Bool {
guard let rhs = object as? CacheKey else {
return false
}
let lhs = self
return lhs.identifier == rhs.identifier
}
override var hash: Int {
return identifier.hashValue
}
}
private class CacheValue: NSObject {
let experience: Experience
init(experience: Experience) {
self.experience = experience
}
}
private var cache = NSCache<CacheKey, CacheValue>()
/// Return the experience for the given identifier from cache, provided that it has already been retrieved once
/// in this session. Returns nil if the experience is not present in the cache.
func experience(for identifier: ExperienceIdentifier) -> Experience? {
let key = CacheKey(identifier: identifier)
return cache.object(forKey: key)?.experience
}
private var tasks = [ExperienceIdentifier: URLSessionTask]()
private var completionHandlers = [ExperienceIdentifier: [(Result<Experience, Failure>) -> Void]]()
/// Fetch an experience for the given identifier from Rover's servers.
///
/// Before making a network request the experience store will first attempt to retreive the experience from
/// its cache and will return the cache result if found.
func fetchExperience(for identifier: ExperienceIdentifier, completionHandler newHandler: @escaping (Result<Experience, Failure>) -> Void) {
if !Thread.isMainThread {
os_log("ExperienceStore is not thread-safe – fetchExperience should only be called from main thread.", log: .rover, type: .default)
}
let existingHandlers = completionHandlers[identifier, default: []]
completionHandlers[identifier] = existingHandlers + [newHandler]
if tasks[identifier] != nil {
return
}
if let experience = experience(for: identifier) {
invokeCompletionHandlers(
for: identifier,
with: .success(experience)
)
return
}
let task = client.task(with: identifier) { result in
self.tasks[identifier] = nil
defer {
self.invokeCompletionHandlers(for: identifier, with: result)
}
switch result {
case let .failure(error):
os_log("Failed to fetch experience: %@", log: .rover, type: .error, error.debugDescription)
case let .success(experience):
let key = CacheKey(identifier: identifier)
let value = CacheValue(experience: experience)
self.cache.setObject(value, forKey: key)
}
}
tasks[identifier] = task
task.resume()
}
private func invokeCompletionHandlers(for identifier: ExperienceIdentifier, with result: Result<Experience, Failure>) {
let completionHandlers = self.completionHandlers[identifier, default: []]
self.completionHandlers[identifier] = nil
for completionHandler in completionHandlers {
completionHandler(result)
}
}
}
|
apache-2.0
|
21b4f9398bcd2587740d4d7dd2754166
| 33.017241 | 143 | 0.60593 | 5.435262 | false | false | false | false |
naokits/bluemix-swift-demo-ios
|
BMSDemo/AppDelegate.swift
|
1
|
4454
|
//
// AppDelegate.swift
// BMSDemo
//
// Created by Naoki Tsutsui on 5/18/16.
// Copyright © 2016 Naoki Tsutsui. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
DemoClient.setup()
self.printPlistDir()
self.printUserDefaults()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.todo == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
// MARK: - Utility Methods
/// プロパティリストの保存場所をコンソールに表示する
func printPlistDir() {
let dirs = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)
let libraryDir = dirs[0]
let preferencesDir = libraryDir + "/Preferences"
print("plistのディレクトリ: \(preferencesDir)")
}
/// 保存されているUserDefaultsの内容を表示する(アプリで追加した内容のみ)
func printUserDefaults() {
let appDomain = NSBundle.mainBundle().bundleIdentifier
let dic = NSUserDefaults.standardUserDefaults().persistentDomainForName(appDomain!)
print("-----------------------------------------------------")
print("All Keys: \(dic?.keys)")
for (key, value) in dic! {
print("*** key: \(key)\n value: \(value)")
}
print("-----------------------------------------------------")
}
}
|
mit
|
02ed06b9994a28ac16b16af71c668b52
| 47.144444 | 285 | 0.70667 | 5.895238 | false | false | false | false |
square/wire
|
wire-library/wire-runtime-swift/src/main/swift/Int+Additions.swift
|
1
|
3111
|
/*
* Copyright 2020 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
extension Int32 {
/**
* Encode as a ZigZag-encoded 32-bit value. ZigZag encodes signed integers into values that
* can be efficiently encoded with varint. (Otherwise, negative values must be sign-extended to
* 64 bits to be varint encoded, thus always taking 10 bytes on the wire.)
*
* - returns: An unsigned 32-bit integer
*/
func zigZagEncoded() -> UInt32 {
// Note: the right-shift must be arithmetic
return UInt32(bitPattern: (self << 1) ^ (self >> 31))
}
}
extension UInt32 {
/**
* Compute the number of bytes that would be needed to encode a varint.
*/
var varintSize: UInt32 {
if self & (~0 << 7) == 0 { return 1 }
if self & (~0 << 14) == 0 { return 2 }
if self & (~0 << 21) == 0 { return 3 }
if self & (~0 << 28) == 0 { return 4 }
return 5
}
/**
* Decodes a ZigZag-encoded 32-bit value. ZigZag encodes signed integers into values that can be
* efficiently encoded with varint. (Otherwise, negative values must be sign-extended to 64 bits
* to be varint encoded, thus always taking 10 bytes on the wire.)
*
* - returns: A signed 32-bit integer.
*/
func zigZagDecoded() -> Int32 {
return Int32(bitPattern: (self >> 1)) ^ -(Int32(bitPattern: self) & 1)
}
}
// MARK: -
extension Int64 {
/**
* Encode as a ZigZag-encoded 64-bit value. ZigZag encodes signed integers into values that
* can be efficiently encoded with varint. (Otherwise, negative values must be sign-extended to
* 64 bits to be varint encoded, thus always taking 10 bytes on the wire.)
*
* - returns: An unsigned 64-bit integer
*/
func zigZagEncoded() -> UInt64 {
// Note: the right-shift must be arithmetic
return UInt64(bitPattern: (self << 1) ^ (self >> 63))
}
}
// MARK: -
extension UInt64 {
/**
* Encode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers into values that can be
* efficiently encoded with varint. (Otherwise, negative values must be sign-extended to 64 bits
* to be varint encoded, thus always taking 10 bytes on the wire.)
*
* - returns: An unsigned 64-bit integer, stored in a signed int because Java has no explicit
* unsigned support.
*/
func zigZagDecoded() -> Int64 {
// Note: the right-shift must be arithmetic
return Int64(bitPattern: (self >> 1)) ^ -(Int64(bitPattern: self) & 1)
}
}
|
apache-2.0
|
f0ddc71df209c8f4f74891d82f788d1b
| 31.40625 | 100 | 0.642237 | 4.061358 | false | false | false | false |
kotdark/Swift
|
GesturePinch/PinchGesture/ViewController.swift
|
1
|
2194
|
//
// ViewController.swift
// PinchGesture
//
// Created by Carlos Butron on 01/12/14.
// Copyright (c) 2015 Carlos Butron. All rights reserved.
//
// 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 UIKit
class ViewController: UIViewController {
var lastScaleFactor:CGFloat = 1
@IBOutlet weak var image: UIImageView!
override func viewDidLoad() {
let pinchGesture:UIPinchGestureRecognizer =
UIPinchGestureRecognizer(target: self, action: "pinchGesture:")
image.addGestureRecognizer(pinchGesture)
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.
}
@IBAction func pinchGesture(sender : UIPinchGestureRecognizer) {
let factor = sender.scale
if (factor > 1) {
//aumentamos el zoom
sender.view?.transform = CGAffineTransformMakeScale(
lastScaleFactor + (factor-1),
lastScaleFactor + (factor-1));
} else {
//reducimos el zoom
sender.view?.transform = CGAffineTransformMakeScale(
lastScaleFactor * factor,
lastScaleFactor * factor);
}
if (sender.state == UIGestureRecognizerState.Ended){
if (factor > 1) {
lastScaleFactor += (factor-1);
} else {
lastScaleFactor *= factor;
} }
}
}
|
gpl-3.0
|
9fd167b4c34fd14b71d3f901b8bd16bd
| 33.28125 | 121 | 0.642206 | 4.975057 | false | false | false | false |
soffes/SyntaxKit
|
SyntaxKit/Theme.swift
|
2
|
1497
|
//
// Theme.swift
// SyntaxKit
//
// Created by Sam Soffes on 10/11/14.
// Copyright © 2014-2015 Sam Soffes. All rights reserved.
//
import Foundation
import X
#if !os(OSX)
import UIKit
#endif
public typealias Attributes = [String: AnyObject]
public struct Theme {
// MARK: - Properties
public let UUID: String
public let name: String
public let attributes: [String: Attributes]
// MARK: - Initializers
public init?(dictionary: [NSObject: AnyObject]) {
guard let UUID = dictionary["uuid"] as? String,
name = dictionary["name"] as? String,
rawSettings = dictionary["settings"] as? [[String: AnyObject]]
else { return nil }
self.UUID = UUID
self.name = name
var attributes = [String: Attributes]()
for raw in rawSettings {
guard let scopes = raw["scope"] as? String else { continue }
guard var setting = raw["settings"] as? [String: AnyObject] else { continue }
if let value = setting.removeValueForKey("foreground") as? String {
setting[NSForegroundColorAttributeName] = Color(hex: value)
}
if let value = setting.removeValueForKey("background") as? String {
setting[NSBackgroundColorAttributeName] = Color(hex: value)
}
// TODO: caret, invisibles, lightHighlight, selection, font style
for scope in scopes.componentsSeparatedByString(",") {
let key = scope.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
attributes[key] = setting
}
}
self.attributes = attributes
}
}
|
mit
|
17e4b8103329ff1b9c89d2c3ec3edcb7
| 23.933333 | 102 | 0.701203 | 3.865633 | false | false | false | false |
stripe/stripe-ios
|
StripePaymentSheet/StripePaymentSheet/Internal/Link/ACH/LinkFinancialConnectionsAuthManager.swift
|
1
|
5689
|
//
// LinkFinancialConnectionsAuthManager.swift
// StripePaymentSheet
//
// Created by Ramon Torres on 5/8/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import UIKit
import AuthenticationServices
@_spi(STP) import StripeCore
/// For internal SDK use only
@objc(STP_Internal_LinkFinancialConnectionsAuthManager)
final class LinkFinancialConnectionsAuthManager: NSObject {
struct Constants {
static let linkedAccountIDQueryParameterName = "linked_account"
}
enum Error: Swift.Error, LocalizedError {
case canceled
case failedToStart
case noLinkedAccountID
case noURL
case unexpectedURL
var errorDescription: String? {
return NSError.stp_unexpectedErrorMessage()
}
}
struct Manifest: Decodable {
let hostedAuthURL: URL
let successURL: URL
let cancelURL: URL
enum CodingKeys: String, CodingKey {
case hostedAuthURL = "hosted_auth_url"
case successURL = "success_url"
case cancelURL = "cancel_url"
}
}
let linkAccount: PaymentSheetLinkAccount
let window: UIWindow?
init(linkAccount: PaymentSheetLinkAccount, window: UIWindow?) {
self.linkAccount = linkAccount
self.window = window
}
/// Initiate a Financial Connections session for Link Instant Debits.
/// - Parameter clientSecret: The client secret of the consumer's Link account session.
/// - Returns: The ID for the newly linked account.
/// - Throws: Either `Error.canceled`, meaning the user canceled the flow, or an error describing what went wrong.
func start(clientSecret: String) async throws -> String {
let manifest = try await generateHostedURL(withClientSecret: clientSecret)
return try await authenticate(withManifest: manifest)
}
}
extension LinkFinancialConnectionsAuthManager {
private func generateHostedURL(withClientSecret clientSecret: String) async throws -> Manifest {
return try await withCheckedThrowingContinuation { continuation in
linkAccount.apiClient.post(
resource: "link_account_sessions/generate_hosted_url",
parameters: [
"client_secret": clientSecret,
"fullscreen": true,
"hide_close_button": true
],
ephemeralKeySecret: linkAccount.publishableKey
).observe { result in
continuation.resume(with: result)
}
}
}
private func authenticate(withManifest manifest: Manifest) async throws -> String {
try await withCheckedThrowingContinuation { continuation in
let authSession = ASWebAuthenticationSession(
url: manifest.hostedAuthURL,
callbackURLScheme: manifest.successURL.scheme,
completionHandler: { url, error in
if let error = error {
if let authenticationSessionError = error as? ASWebAuthenticationSessionError,
authenticationSessionError.code == .canceledLogin
{
return continuation.resume(throwing: Error.canceled)
}
return continuation.resume(throwing: error)
}
guard let url = url else {
return continuation.resume(throwing: Error.noURL)
}
if url.matchesSchemeHostAndPath(of: manifest.successURL) {
if let linkedAccountID = Self.extractLinkedAccountID(from: url) {
return continuation.resume(returning: linkedAccountID)
} else {
return continuation.resume(throwing: Error.noLinkedAccountID)
}
} else if url.matchesSchemeHostAndPath(of: manifest.cancelURL) {
return continuation.resume(throwing: Error.canceled)
} else {
return continuation.resume(throwing: Error.unexpectedURL)
}
}
)
authSession.presentationContextProvider = self
authSession.prefersEphemeralWebBrowserSession = true
if #available(iOS 13.4, *) {
guard authSession.canStart else {
return continuation.resume(throwing: Error.failedToStart)
}
}
authSession.start()
}
}
}
// MARK: - Presentation context
@available(iOS 13, *)
extension LinkFinancialConnectionsAuthManager: ASWebAuthenticationPresentationContextProviding {
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
return self.window ?? ASPresentationAnchor()
}
}
// MARK: - Utils
extension LinkFinancialConnectionsAuthManager {
private static func extractLinkedAccountID(from url: URL) -> String? {
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
assertionFailure("Invalid URL")
return nil
}
return components
.queryItems?
.first(where: { $0.name == Constants.linkedAccountIDQueryParameterName })?
.value
}
}
private extension URL {
func matchesSchemeHostAndPath(of otherURL: URL) -> Bool {
return (
self.scheme == otherURL.scheme &&
self.host == otherURL.host &&
self.path == otherURL.path
)
}
}
|
mit
|
43672807d9ed12e68151dd148044b7c2
| 32.656805 | 118 | 0.604606 | 5.511628 | false | false | false | false |
NoryCao/zhuishushenqi
|
zhuishushenqi/NewVersion/Search/ZSSearchInfoTableViewCell.swift
|
1
|
1612
|
//
// ZSSearchInfoTableViewCell.swift
// zhuishushenqi
//
// Created by yung on 2020/1/5.
// Copyright © 2020 QS. All rights reserved.
//
import UIKit
protocol ZSSearchInfoTableViewCellDelegate:class {
func infoCell(cell:ZSSearchInfoTableViewCell,click download:UIButton)
}
class ZSSearchInfoTableViewCell: UITableViewCell {
weak var delegate:ZSSearchInfoTableViewCellDelegate?
private lazy var downloadBtn:UIButton = {
let bt = UIButton(type: .custom)
bt.setTitle("缓存", for: .normal)
bt.setTitle("已缓存", for: .selected)
bt.setTitleColor(UIColor.red, for: .normal)
bt.setTitleColor(UIColor.gray, for: .selected)
bt.frame = CGRect(x: 0, y: 0, width: 60, height: 30)
bt.addTarget(self, action: #selector(downloadAction(bt:)), for: .touchUpInside)
return bt
}()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func layoutSubviews() {
super.layoutSubviews()
accessoryView = self.downloadBtn
}
func downloadFinish() {
self.downloadBtn.isSelected = true
}
override func prepareForReuse() {
self.downloadBtn.isSelected = false
}
@objc
private func downloadAction(bt:UIButton) {
if bt.isSelected == false {
delegate?.infoCell(cell: self, click: bt)
}
}
}
|
mit
|
548d91ecb30906462d91ea9ebfde02ca
| 25.683333 | 87 | 0.642099 | 4.362398 | false | false | false | false |
ello/ello-ios
|
Sources/Networking/CategoryService.swift
|
1
|
1416
|
////
/// CategoryService.swift
//
import PromiseKit
class CategoryService {
func loadCategories() -> Promise<[Category]> {
if let categories = Globals.cachedCategories {
return .value(categories)
}
return ElloProvider.shared.request(.categories)
.map { data, _ -> [Category] in
guard let categories = data as? [Category] else {
throw NSError.uncastableModel()
}
Globals.cachedCategories = categories
Preloader().preloadImages(categories)
return categories
}
}
func loadCreatorCategories() -> Promise<[Category]> {
return loadCategories()
.map { categories -> [Category] in
return categories.filter { $0.isCreatorType }
}
}
func loadCategory(_ categorySlug: String) -> Promise<Category> {
if let category = Globals.cachedCategories?.find({ $0.slug == categorySlug }) {
return .value(category)
}
return ElloProvider.shared.request(.category(slug: categorySlug))
.map { data, _ -> Category in
guard let category = data as? Category else {
throw NSError.uncastableModel()
}
Preloader().preloadImages([category])
return category
}
}
}
|
mit
|
a79aad6471434b529796de6de9d3b071
| 28.5 | 87 | 0.544492 | 5.149091 | false | false | false | false |
audiokit/AudioKit
|
Sources/AudioKit/Operations/OperationGenerator.swift
|
1
|
7750
|
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
import CAudioKit
/// Operation-based generator
public class OperationGenerator: Node, AudioUnitContainer, Toggleable {
/// Internal audio unit type
public typealias AudioUnitType = InternalAU
/// Four letter unique description "cstg"
public static let ComponentDescription = AudioComponentDescription(generator: "cstg")
// MARK: - Properties
/// Internal audio unit
public private(set) var internalAU: AudioUnitType?
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU?.isStarted ?? false
}
// MARK: - Parameters
internal static func makeParam(_ number: Int) -> NodeParameterDef {
return NodeParameterDef(
identifier: "parameter\(number)",
name: "Parameter \(number)",
address: akGetParameterAddress("OperationGeneratorParameter\(number)"),
range: floatRange,
unit: .generic,
flags: .default)
}
/// Specification for Parameter 1
public static let parameter1Def = OperationGenerator.makeParam(1)
/// Specification for Parameter 2
public static let parameter2Def = OperationGenerator.makeParam(2)
/// Specification for Parameter 3
public static let parameter3Def = OperationGenerator.makeParam(3)
/// Specification for Parameter 4
public static let parameter4Def = OperationGenerator.makeParam(4)
/// Specification for Parameter 5
public static let parameter5Def = OperationGenerator.makeParam(5)
/// Specification for Parameter 6
public static let parameter6Def = OperationGenerator.makeParam(6)
/// Specification for Parameter 7
public static let parameter7Def = OperationGenerator.makeParam(7)
/// Specification for Parameter 8
public static let parameter8Def = OperationGenerator.makeParam(8)
/// Specification for Parameter 9
public static let parameter9Def = OperationGenerator.makeParam(9)
/// Specification for Parameter 10
public static let parameter10Def = OperationGenerator.makeParam(10)
/// Specification for Parameter 11
public static let parameter11Def = OperationGenerator.makeParam(11)
/// Specification for Parameter 12
public static let parameter12Def = OperationGenerator.makeParam(12)
/// Specification for Parameter 13
public static let parameter13Def = OperationGenerator.makeParam(13)
/// Specification for Parameter 14
public static let parameter14Def = OperationGenerator.makeParam(14)
/// Operation parameter 1
@Parameter public var parameter1: AUValue
/// Operation parameter 2
@Parameter public var parameter2: AUValue
/// Operation parameter 3
@Parameter public var parameter3: AUValue
/// Operation parameter 4
@Parameter public var parameter4: AUValue
/// Operation parameter 5
@Parameter public var parameter5: AUValue
/// Operation parameter 6
@Parameter public var parameter6: AUValue
/// Operation parameter 7
@Parameter public var parameter7: AUValue
/// Operation parameter 8
@Parameter public var parameter8: AUValue
/// Operation parameter 9
@Parameter public var parameter9: AUValue
/// Operation parameter 10
@Parameter public var parameter10: AUValue
/// Operation parameter 11
@Parameter public var parameter11: AUValue
/// Operation parameter 12
@Parameter public var parameter12: AUValue
/// Operation parameter 13
@Parameter public var parameter13: AUValue
/// Operation parameter 14
@Parameter public var parameter14: AUValue
// MARK: - Audio Unit
/// Internal audio unit for Operation Generator
public class InternalAU: AudioUnitBase {
/// Get an array of the parameter definitions
/// - Returns: Array of parameter definitions
public override func getParameterDefs() -> [NodeParameterDef] {
[OperationGenerator.parameter1Def,
OperationGenerator.parameter2Def,
OperationGenerator.parameter3Def,
OperationGenerator.parameter4Def,
OperationGenerator.parameter5Def,
OperationGenerator.parameter6Def,
OperationGenerator.parameter7Def,
OperationGenerator.parameter8Def,
OperationGenerator.parameter9Def,
OperationGenerator.parameter10Def,
OperationGenerator.parameter11Def,
OperationGenerator.parameter12Def,
OperationGenerator.parameter13Def,
OperationGenerator.parameter14Def]
}
/// Create the DSP Refence for this node
/// - Returns: DSP Reference
public override func createDSP() -> DSPRef {
akCreateDSP("OperationGeneratorDSP")
}
/// Trigger the operation generator
public override func trigger() {
akOperationGeneratorTrigger(dsp)
}
/// Set sporth string
/// - Parameter sporth: Sporth string
public func setSporth(_ sporth: String) {
sporth.withCString { str -> Void in
akOperationGeneratorSetSporth(dsp, str, Int32(sporth.utf8CString.count))
}
}
}
// MARK: - Initializers
/// Initialize with a mono or stereo operation
///
/// - parameter operation: Operation to generate, can be mono or stereo
///
public convenience init(operation: ([Operation]) -> ComputedParameter) {
let computedParameter = operation(Operation.parameters)
if type(of: computedParameter) == Operation.self {
if let monoOperation = computedParameter as? Operation {
self.init(sporth: monoOperation.sporth + " dup ")
return
}
} else {
if let stereoOperation = computedParameter as? StereoOperation {
self.init(sporth: stereoOperation.sporth + " swap ")
return
}
}
Log("Operation initialization failed.")
self.init(sporth: "")
}
/// Initialize with a operation that takes no arguments
///
/// - parameter operation: Operation to generate
///
public convenience init(operation: () -> ComputedParameter) {
self.init(operation: { _ in operation() })
}
/// Initialize the generator for stereo (2 channels)
///
/// - Parameters:
/// - channelCount: Only 2 channels are supported, but need to differentiate the initializer
/// - operations: Array of operations [left, right]
///
public convenience init(channelCount: Int, operations: ([Operation]) -> [Operation]) {
let computedParameters = operations(Operation.parameters)
let left = computedParameters[0]
if channelCount == 2 {
let right = computedParameters[1]
self.init(sporth: "\(right.sporth) \(left.sporth)")
} else {
self.init(sporth: "\(left.sporth)")
}
}
/// Initialize this generator node with a generic sporth stack and a triggering flag
///
/// - parameter sporth: String of valid Sporth code
///
public init(sporth: String = "") {
super.init(avAudioNode: AVAudioNode())
instantiateAudioUnit { avAudioUnit in
self.avAudioUnit = avAudioUnit
self.avAudioNode = avAudioUnit
self.internalAU = avAudioUnit.auAudioUnit as? AudioUnitType
self.internalAU?.setSporth(sporth)
}
}
/// Trigger the sound with current parameters
open func trigger() {
internalAU?.trigger()
}
}
|
mit
|
2496d766b114f9f70c21e9ecf4876845
| 36.08134 | 100 | 0.662968 | 5.434783 | false | false | false | false |
iMetalk/TCZDemo
|
SwiftStudyDemo/SwiftDemo/TypeCasting.playground/Contents.swift
|
1
|
2123
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
class MediaItem {
var name: String
init(name: String) {
self.name = name
}
}
class Movie: MediaItem {
var director: String
init(name: String, director: String) {
self.director = director
super.init(name: name)
}
}
class Song: MediaItem {
var artist: String
init(name: String, artist: String) {
self.artist = artist
super.init(name: name)
}
}
let library = [
Movie(name: "Casablanca", director: "Michael Curtiz"),
Song(name: "Blue Suede Shoes", artist: "Elvis Presley"),
Movie(name: "Citizen Kane", director: "Orson Welles"),
Song(name: "The One And Only", artist: "Chesney Hawkes"),
Song(name: "Never Gonna Give You Up", artist: "Rick Astley")
]
// Use the type check operator (is) to check whether an instance is of a certain subclass type. The type check operator returns true if the instance is of that subclass type and false if it is not.
library[0] is Movie
library[0] is Song
var hello = "Hello world"
var aFolat: Float = 1.2
library.first
/*
Use the conditional form of the type cast operator (as?) when you are not sure if the downcast will succeed. This form of the operator will always return an optional value, and the value will be nil if the downcast was not possible. This enables you to check for a successful downcast.
Use the forced form of the type cast operator (as!) only when you are sure that the downcast will always succeed. This form of the operator will trigger a runtime error if you try to downcast to an incorrect class type.
*/
for item in library {
if let movie = item as? Movie {
print(movie.name)
}else if let song = item as? Song{
print(song.name)
}
}
/*
Any can represent an instance of any type at all, including function types.
AnyObject can represent an instance of any class type.
*/
var anyArray = [Any]()
anyArray.append(1)
anyArray.append("String")
anyArray.append(Song(name: "菊花台", artist: "周杰伦"))
for thing in anyArray {
}
|
mit
|
167b6646676e2aa38af2e46b0c1bd36b
| 27.917808 | 286 | 0.687826 | 3.690559 | false | false | false | false |
darina/omim
|
iphone/Maps/Core/Ads/BannerType.swift
|
5
|
1552
|
enum BannerType {
case none
case facebook(String)
case rb(String)
case mopub(String)
var banner: Banner? {
switch self {
case .none: return nil
case let .facebook(id): return FacebookBanner(bannerID: id)
case let .rb(id): return RBBanner(bannerID: id)
case let .mopub(id): return MopubBanner(bannerID: id)
}
}
var mwmType: MWMBannerType {
switch self {
case .none: return .none
case .facebook: return .facebook
case .rb: return .rb
case .mopub: return .mopub
}
}
init(type: MWMBannerType, id: String, query: String = "") {
switch type {
case .facebook: self = .facebook(id)
case .rb: self = .rb(id)
case .mopub: self = .mopub(id)
default: self = .none
}
}
}
extension BannerType: Equatable {
static func ==(lhs: BannerType, rhs: BannerType) -> Bool {
switch (lhs, rhs) {
case (.none, .none): return true
case let (.facebook(l), .facebook(r)): return l == r
case let (.rb(l), .rb(r)): return l == r
case let (.mopub(l), .mopub(r)): return l == r
case (.none, _),
(.facebook, _),
(.rb, _),
(.mopub, _): return false
}
}
}
extension BannerType: Hashable {
func hash(into hasher: inout Hasher) {
switch self {
case .none: hasher.combine(mwmType.hashValue)
case let .facebook(id): hasher.combine(mwmType.hashValue ^ id.hashValue)
case let .rb(id): hasher.combine(mwmType.hashValue ^ id.hashValue)
case let .mopub(id): hasher.combine(mwmType.hashValue ^ id.hashValue)
}
}
}
|
apache-2.0
|
de039d33c3694467a6226228df253ade
| 25.305085 | 76 | 0.612113 | 3.396061 | false | false | false | false |
apple/swift
|
test/Interpreter/objc_extensions.swift
|
12
|
1933
|
// RUN: %target-run-simple-swift %s | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
// Category on a nested class
class OuterClass {
class InnerClass: NSObject {}
}
extension OuterClass.InnerClass {
@objc static let propertyInExtension = "foo"
@objc func dynamicMethod() -> String {
return "bar"
}
}
let x = OuterClass.InnerClass()
// CHECK: foo
print(type(of: x).propertyInExtension)
// CHECK: bar
print(x.dynamicMethod())
// Category on a concrete subclass of a generic base class
class Base<T> {
let t: T
init(t: T) { self.t = t }
}
class Derived : Base<Int> {}
extension Derived {
@objc func otherMethod() -> Int {
return t
}
}
let y: AnyObject = Derived(t: 100)
// CHECK: 100
// This call fails due to rdar://problem/47053588, where categories
// don't attach to a dynamically initialized Swift class, on macOS 10.9
// and iOS 7. Disable it for now when testing on those versions.
if #available(macOS 10.10, iOS 8, *) {
print(y.otherMethod())
} else {
print("100") // Hack to satisfy FileCheck.
}
extension NSObject {
@objc func sillyMethod() -> Int {
return 123
}
}
let z: AnyObject = NSObject()
// CHECK: 123
print(z.sillyMethod())
// Category on an ObjC generic class using a type-pinning parameter, including
// a cast to an existential metatype
@objc protocol CacheNameDefaulting {
static var defaultCacheName: String { get }
}
extension OuterClass.InnerClass: CacheNameDefaulting {
static var defaultCacheName: String { "InnerClasses" }
}
extension NSCache {
@objc convenience init(ofObjects objectTy: ObjectType.Type, forKeys keyTy: KeyType.Type) {
self.init()
if let defaultNameTy = objectTy as? CacheNameDefaulting.Type {
self.name = defaultNameTy.defaultCacheName
}
}
}
let cache = NSCache(ofObjects: OuterClass.InnerClass.self, forKeys: NSString.self)
// CHECK: InnerClasses
print(cache.name)
|
apache-2.0
|
729c06adf77f19489a1ac3676373e6f0
| 20.965909 | 92 | 0.705639 | 3.573013 | false | false | false | false |
liuchuo/LeetCode-practice
|
Swift/100. Same Tree.swift
|
1
|
182
|
// 100. Same Tree
// 8 ms
if let p = p, let q = q {
return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
} else {
return p == nil && q == nil
}
|
gpl-3.0
|
fc46a202af4b5354343d43d0d6b99753
| 25.142857 | 87 | 0.549451 | 2.637681 | false | false | false | false |
rnystrom/GitHawk
|
Classes/Issues/Comments/Reactions/IssueReactionCell.swift
|
1
|
5354
|
//
// IssueReactionCell.swift
// Freetime
//
// Created by Ryan Nystrom on 6/1/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import SnapKit
final class IssueReactionCell: UICollectionViewCell {
private static var cache = [String: CGFloat]()
private static let spacing: CGFloat = 4
private static var emojiFont: UIFont { return UIFont.systemFont(ofSize: Styles.Text.body.size + 2) }
private static var countFont: UIFont { return Styles.Text.body.preferredFont }
static func width(emoji: String, count: Int) -> CGFloat {
let key = "\(emoji)\(count)"
if let cached = cache[key] {
return cached
}
let emojiWidth = (emoji as NSString).size(withAttributes: [.font: emojiFont]).width
let countWidth = ("\(count)" as NSString).size(withAttributes: [.font: countFont]).width
let width = emojiWidth + countWidth + 3 * spacing
cache[key] = width
return width
}
private let emojiLabel = UILabel()
private let countLabel = ShowMoreDetailsLabel()
private var detailText = ""
override init(frame: CGRect) {
super.init(frame: frame)
accessibilityTraits |= UIAccessibilityTraitButton
isAccessibilityElement = true
emojiLabel.textAlignment = .center
emojiLabel.backgroundColor = .clear
// hint bigger emoji than labels
emojiLabel.font = UIFont.systemFont(ofSize: Styles.Text.body.size + 2)
contentView.addSubview(emojiLabel)
emojiLabel.snp.makeConstraints { make in
make.centerY.equalToSuperview()
make.left.equalToSuperview().offset(IssueReactionCell.spacing)
}
countLabel.textAlignment = .center
countLabel.backgroundColor = .clear
countLabel.font = Styles.Text.body.preferredFont
countLabel.textColor = Styles.Colors.Blue.medium.color
contentView.addSubview(countLabel)
countLabel.snp.makeConstraints { make in
make.centerY.equalTo(emojiLabel)
make.left.equalTo(emojiLabel.snp.right).offset(IssueReactionCell.spacing)
}
let longPress = UILongPressGestureRecognizer(
target: self,
action: #selector(IssueReactionCell.showMenu(recognizer:))
)
isUserInteractionEnabled = true
addGestureRecognizer(longPress)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// required for UIMenuController
override var canBecomeFirstResponder: Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return action == #selector(IssueReactionCell.empty)
}
// MARK: Public API
func configure(emoji: String, count: Int, detail: String, isViewer: Bool) {
emojiLabel.text = emoji
countLabel.text = "\(count)"
detailText = detail
contentView.backgroundColor = isViewer ? Styles.Colors.Blue.light.color : .clear
accessibilityHint = isViewer
? NSLocalizedString("Tap to remove your reaction", comment: "")
: NSLocalizedString("Tap to react with this emoji", comment: "")
}
func popIn() {
emojiLabel.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
emojiLabel.alpha = 0
UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.2, options: [.curveEaseInOut], animations: {
self.emojiLabel.transform = .identity
self.emojiLabel.alpha = 1
})
countLabel.alpha = 0
UIView.animate(withDuration: 0.3, delay: 0, animations: {
self.countLabel.alpha = 1
})
}
func pullOut() {
// hack to prevent changing to "0"
countLabel.text = "1"
countLabel.alpha = 1
emojiLabel.transform = .identity
emojiLabel.alpha = 1
UIView.animate(withDuration: 0.2, delay: 0, animations: {
self.countLabel.alpha = 0
self.emojiLabel.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
self.emojiLabel.alpha = 0
})
}
func iterate(add: Bool) {
let animation = CATransition()
animation.duration = 0.25
animation.type = kCATransitionPush
animation.subtype = add ? kCATransitionFromTop : kCATransitionFromBottom
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
countLabel.layer.add(animation, forKey: "text-change")
}
// MARK: Private API
@objc func showMenu(recognizer: UITapGestureRecognizer) {
guard recognizer.state == .began,
!detailText.isEmpty else { return }
becomeFirstResponder()
let menu = UIMenuController.shared
menu.menuItems = [
UIMenuItem(title: detailText, action: #selector(IssueReactionCell.empty))
]
menu.setTargetRect(contentView.bounds, in: self)
menu.setMenuVisible(true, animated: trueUnlessReduceMotionEnabled)
}
@objc func empty() {}
// MARK: Accessibility
override var accessibilityLabel: String? {
get {
return AccessibilityHelper.generatedLabel(forCell: self)
}
set { }
}
}
|
mit
|
9c7043b8727ef5c7f151c44ea3c4971c
| 32.879747 | 150 | 0.644125 | 4.826871 | false | false | false | false |
jhurray/Ladybug
|
Source/JSONCodable.swift
|
1
|
5435
|
//
// JSONCodable.swift
// Ladybug
//
// Created by Jeff Hurray on 7/29/17.
// Copyright © 2017 jhurray. All rights reserved.
//
import Foundation
/// A typealias of string. In future versions may be `AnyKeyPath`.
public typealias PropertyKey = String
/// A protocol that provides Codable conformance and supports initialization from JSON and JSON Data
public protocol JSONCodable: Codable {
/**
Initialize an object with a JSON object
- Parameter json: JSON object that will be mapped to the conforming object
*/
init(json: Any) throws
/**
Initialize an object with JSON Data
- Parameter data: JSON Data that will be serialized and mapped to the conforming object
*/
init(data: Data) throws
/// Encode the object into a JSON object
func toJSON() throws -> Any
/// Encode the object into Data
func toData() throws -> Data
/// Supplies an array of transformers used to map JSON values to properties of the conforming object
static var transformersByPropertyKey: [PropertyKey: JSONTransformer] { get }
}
/// Error type thrown by objects conforming to JSONCodable
public enum JSONCodableError: Swift.Error {
/// Thrown when an object conforming to JSONCodable expects a certain type, but receives another
case badType(expectedType: Any.Type, receivedType: Any.Type)
}
public extension Array where Element: JSONCodable {
/**
Initialize an array of objects conforming to JSONCodable with JSON Data
- Parameter data: JSON Data that will be serialized and mapped to the list of objects conforming to JSONCodable
*/
public init(data: Data) throws {
let json = try JSONSerialization.jsonObject(with: data)
try self.init(json: json)
}
/**
Initialize an array of objects conforming to JSONCodable with a JSON object
- Parameter json: JSON object that will mapped to the list of objects conforming to JSONCodable
*/
public init(json: Any) throws {
guard let objectList = json as? [Any] else {
throw JSONCodableError.badType(expectedType: [Any].self, receivedType: type(of: json))
}
guard let jsonList = objectList as? [[String: Any]] else {
throw JSONCodableError.badType(expectedType: [[String: Any]].self, receivedType: type(of: objectList))
}
var list: [Element] = []
for json in jsonList {
let object = try Element(json: json)
list.append(object)
}
self = list
}
public func toJSON() throws -> Any {
let data = try toData()
let object = try JSONSerialization.jsonObject(with: data)
return object
}
public func toData() throws -> Data {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .millisecondsSince1970
let data = try encoder.encode(self)
return data
}
/// A transformer that explicitly declares a nested list type
public static var transformer: JSONTransformer {
return NestedListTransformer<Element>()
}
}
/// For use if you are using `JSONCodable` as a generic constraint
/// because Array does not explicitly conform to `JSONCodable`
public struct List<T: JSONCodable>: JSONCodable {
public let object: Array<T>
public init(json: Any) throws {
object = try Array<T>(json: json)
}
public init(data: Data) throws {
object = try Array<T>(data: data)
}
}
public extension JSONCodable {
public init(data: Data) throws {
let json = try JSONSerialization.jsonObject(with: data)
try self.init(json: json)
}
public init(json: Any) throws {
guard var jsonDictionary = json as? [String: Any] else {
throw JSONCodableError.badType(expectedType: [String: Any].self, receivedType: type(of: json))
}
Self.alterForDecoding(&jsonDictionary)
let jsonData = try JSONSerialization.data(withJSONObject: jsonDictionary, options: [])
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .millisecondsSince1970
let instance = try decoder.decode(Self.self, from: jsonData)
self = instance
}
public func toJSON() throws -> Any {
let data = try toData()
let object = try JSONSerialization.jsonObject(with: data)
return object
}
public func toData() throws -> Data {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .millisecondsSince1970
let data = try encoder.encode(self)
return data
}
/// A transformer that explicitly declares a nested type
public static var transformer: JSONTransformer {
return NestedObjectTransformer<Self>()
}
internal static func alterForDecoding(_ json: inout [String: Any]) {
for (propertyKey, transformer) in Self.transformersByPropertyKey {
transformer.transform(&json, mappingTo: propertyKey)
}
}
internal static func alterForEncoding(_ json: inout [String: Any]) {
for (propertyKey, transformer) in Self.transformersByPropertyKey {
transformer.reverseTransform(&json, mappingFrom: propertyKey)
}
}
public static var transformersByPropertyKey: [PropertyKey: JSONTransformer] {
return [:]
}
}
|
mit
|
5616409ad8d8da4aa810c7512915fd92
| 32.134146 | 116 | 0.65403 | 4.83452 | false | false | false | false |
quickthyme/PUTcat
|
PUTcat/Presentation/Parser/ParserViewController+ViewData.swift
|
1
|
2896
|
import UIKit
// MARK: - View Data
extension ParserViewController {
func getViewDataSectionTitle(section:Int) -> String {
return self.viewData.section[section].title
}
func getViewDataItem(forIndexPath indexPath:IndexPath) -> ParserViewDataItem {
return self.viewData.section[indexPath.section].item[indexPath.row]
}
func replaceViewDataItem(atIndexPath indexPath:IndexPath, withItem newItem: ParserViewDataItem) {
self.viewData.section[indexPath.section].item[indexPath.row] = newItem
}
func findIndexPath(forRefID refID:String) -> IndexPath? {
let data = self.viewData
for s in 0..<data.section.count {
for i in 0..<data.section[s].item.count {
guard (data.section[s].item[i].refID == refID) else { continue }
return IndexPath(row: i, section: s)
}
}
return nil
}
func updateViewDataItem(title: String, forRefID refID:String) {
guard let indexPath = self.findIndexPath(forRefID: refID) else { return }
self.viewData.section[indexPath.section].item[indexPath.row].title = title
let item = self.viewData.section[indexPath.section].item[indexPath.row]
self.delegate?.update(item: item, parentRefID: viewDataParent.refID, viewController: self)
}
func updateViewDataItem(detail: String, forRefID refID:String) {
guard let indexPath = self.findIndexPath(forRefID: refID) else { return }
self.viewData.section[indexPath.section].item[indexPath.row].detail = detail
let item = self.viewData.section[indexPath.section].item[indexPath.row]
self.delegate?.update(item: item, parentRefID: viewDataParent.refID, viewController: self)
}
func deleteViewDataItem(indexPath: IndexPath) {
let item = self.getViewDataItem(forIndexPath: indexPath)
self.viewData.section[indexPath.section].item.remove(at: indexPath.row)
self.delegate?.delete(item: item, parentRefID: viewDataParent.refID, viewController: self)
}
func moveViewDataItem(fromIndexPath: IndexPath, toIndexPath:IndexPath) {
var data = self.viewData
let fromItem = data.section[fromIndexPath.section].item.remove(at: fromIndexPath.row)
data.section[toIndexPath.section].item.insert(fromItem, at: toIndexPath.row)
self.viewData = data
self.delegate?.updateOrdinality(viewData: data, parentRefID: viewDataParent.refID, viewController: self)
}
func copyViewDataItem(indexPath: IndexPath) {
let item = self.getViewDataItem(forIndexPath: indexPath)
var newItem = item; newItem.refID = "COPY"
self.viewData.section[indexPath.section].item.insert(newItem, at: indexPath.row+1)
self.delegate?.copy(item: item, parentRefID: viewDataParent.refID, viewController: self)
}
}
|
apache-2.0
|
d321ddd5c73bd3f948baeaca185198dc
| 44.25 | 112 | 0.688191 | 4.191027 | false | false | false | false |
CharlesVu/Smart-iPad
|
MKHome/UK/UK - National Rail/TrainServicesExtension.swift
|
1
|
1983
|
//
// TrainClasses.swift
// MKHome
//
// Created by charles on 16/11/2016.
// Copyright © 2016 charles. All rights reserved.
//
import Foundation
import HuxleySwift
extension HuxleySwift.TrainServices {
var delay: TimeInterval {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "HH:mm"
if let normalLeavingTime = std,
let estimatedLeavingTime = etd {
let normalLeavingDate = formatter.date(from: normalLeavingTime)
let estimatedLeavingDate = formatter.date(from: estimatedLeavingTime)
return estimatedLeavingDate!.timeIntervalSince(normalLeavingDate!)
}
return -1
}
func getJourneyDuration(toStationCRS crs: String) -> TimeInterval {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "HH:mm"
let arrivalCallingPoint = getCallingPoint(crs: crs)
if let leavingTimeString = std,
let arrivalTimeString = arrivalCallingPoint?.st {
let leavingTime = formatter.date(from: leavingTimeString)
let arrivalTime = formatter.date(from: arrivalTimeString)
if let leavingTime = leavingTime {
var duration = arrivalTime!.timeIntervalSince(leavingTime)
if duration < 0 {
duration += 1.day
}
return duration
}
}
return -1
}
func getCallingPoint(crs: String) -> HuxleySwift.CallingPoint? {
for subsequentCallingPoint in subsequentCallingPoints {
if let callingPoints = subsequentCallingPoint.callingPoint {
for callpoint in callingPoints {
if callpoint.crs == crs {
return callpoint
}
}
}
}
return nil
}
}
|
mit
|
98173dddd12304bf4384e3a1e8e97602
| 29.96875 | 81 | 0.596367 | 4.775904 | false | false | false | false |
drewag/Swiftlier
|
Sources/Swiftlier/Model/Structured/Structured.swift
|
1
|
2137
|
//
// Structured.swift
// file-sync-services
//
// Created by Andrew J Wagner on 4/15/17.
//
//
import Foundation
public protocol Structured {
var string: String? {get}
var int: Int? {get}
var double: Double? {get}
var bool: Bool? {get}
var array: [Self]? {get}
var dictionary: [String:Self]? {get}
subscript(string: String) -> Self? {get}
subscript(int: Int) -> Self? {get}
}
extension Structured {
public var url: URL? {
guard let string = self.string else {
return nil
}
return URL(string: string)
}
// Key Path Format
// - Each element is separated by a period (.)
// - Access an element in an array with arrayName[index]
//
// Example: "key1.array[2].value1" gets "example" from:
// [
// "key1": [
// "array": [
// [
// "value1": "example"
// ]
// ]
// ]
// ]
public func object(atKeyPath keyPath: String) throws -> Self? {
guard !keyPath.isEmpty else {
return self
}
var components = keyPath.components(separatedBy: ".")
let next = components.removeFirst()
guard let startIndex = next.firstIndex(of: "[") else {
return try self[next]?.object(atKeyPath: components.joined(separator: "."))
}
guard next.last == "]" else {
throw GenericSwiftlierError("parsing keypath", because: "no matching bracket ']' was found at the end")
}
let name = String(next[next.startIndex...next.index(before: startIndex)])
let lastIndex = next.index(next.endIndex, offsetBy: -2)
let indexString = String(next[next.index(after: startIndex)...lastIndex])
guard let index = Int(indexString) else {
throw GenericSwiftlierError("parsing keypath", because: "invalid index '\(indexString)'")
}
guard let array = self[name]?.array, index < array.count else {
return nil
}
return try array[index].object(atKeyPath: components.joined(separator: "."))
}
}
|
mit
|
9c151cf94da9389eef57ff134c99ddcd
| 28.680556 | 115 | 0.562471 | 4.078244 | false | false | false | false |
APUtils/APExtensions
|
APExtensions/Classes/Core/_Extensions/_Foundation/StringProtocol+Utils.swift
|
1
|
10392
|
//
// StringProtocol+Utils.swift
// APExtensions
//
// Created by Anton Plebanovich on 1/4/20.
// Copyright © 2020 Anton Plebanovich. All rights reserved.
//
import Foundation
import RoutableLogger
// ******************************* MARK: - Representation
public extension StringProtocol {
/// Returns string as URL. Properly escapes URL components if needed.
var asURL: URL? {
// Check for existing percent escapes first to prevent double-escaping of % character
if range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) != nil {
// Already encoded
return URL(string: asString)
}
// Gettin host component
var reducedString = asString
var components = reducedString.components(separatedBy: "://")
let hostComponent: String
if components.count == 2 {
hostComponent = components[0]
reducedString = components[1]
} else {
hostComponent = ""
}
// Getting fragment component
components = reducedString.components(separatedBy: "#")
let fragmentComponent: String
if components.count == 2 {
reducedString = components[0]
fragmentComponent = components[1]
} else {
reducedString = components[0]
fragmentComponent = ""
}
// Getting query component
components = reducedString.components(separatedBy: "?")
let queryComponent: String
if components.count == 2 {
reducedString = components[0]
queryComponent = components[1]
} else {
reducedString = components[0]
queryComponent = ""
}
// What have left is a path
let pathComponent: String = reducedString
guard let escapedHostComponent = hostComponent.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else { return nil }
guard let escapedPathComponent = pathComponent.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { return nil }
guard let escapedQueryComponent = queryComponent.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return nil }
guard let escapedFragmentComponent = fragmentComponent.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) else { return nil }
var urlString = ""
if !escapedHostComponent.isEmpty {
urlString = "\(escapedHostComponent)://"
}
if !escapedPathComponent.isEmpty {
urlString = "\(urlString)\(escapedPathComponent)"
}
if !escapedQueryComponent.isEmpty {
urlString = "\(urlString)?\(escapedQueryComponent)"
}
if !escapedFragmentComponent.isEmpty {
urlString = "\(urlString)#\(escapedFragmentComponent)"
}
return URL(string: urlString)
}
/// Returns `self` as file URL
var asFileURL: URL {
return URL(fileURLWithPath: asString)
}
/// Returns `self` as `Bool` if conversion is possible.
var asBool: Bool? {
if let bool = Bool(asString) {
return bool
}
switch lowercased() {
case "true", "yes", "1", "enable": return true
case "false", "no", "0", "disable": return false
default: return nil
}
}
/// Returns `self` as `Double`
var asDouble: Double? {
return Double(self)
}
/// Returns `self` as `Int`
var asInt: Int? {
return Int(self)
}
/// Returns `self` as `String`
var asString: String {
if let string = self as? String {
return string
} else {
return String(self)
}
}
/// Returns string as NSAttributedString
var asAttributedString: NSAttributedString {
return NSAttributedString(string: asString)
}
/// Returns string as NSMutableAttributedString
var asMutableAttributedString: NSMutableAttributedString {
return NSMutableAttributedString(string: asString)
}
}
// ******************************* MARK: - To
public extension StringProtocol {
func safeJSONArray(file: String = #file, function: String = #function, line: UInt = #line) -> [Any]? {
safeUTF8Data(file: file, function: function, line: line)?
.safeJSONArray(file: file, function: function, line: line)
}
/// Converts string to UTF8 data if possible and report error if unable
func safeUTF8Data(file: String = #file, function: String = #function, line: UInt = #line) -> Data? {
guard let data = data(using: .utf8) else {
RoutableLogger.logError("Unable to convert string to UTF8 data", data: ["self": self], file: file, function: function, line: line)
return nil
}
return data
}
}
// ******************************* MARK: - Base64
public extension StringProtocol {
/// Returns base64 encoded string
var encodedBase64: String? {
return data(using: .utf8)?.base64EncodedString()
}
/// Returns string decoded from base64 string
var decodedBase64: String? {
// String MUST be dividable by 4. https://stackoverflow.com/questions/36364324/swift-base64-decoding-returns-nil/36366421#36366421
let remainder = count % 4
let encodedString: String
if remainder > 0 {
encodedString = padding(toLength: count + 4 - remainder, withPad: "=", startingAt: 0)
} else {
encodedString = self.asString
}
guard let data = Data(base64Encoded: encodedString) else { return nil }
return String(data: data, encoding: .utf8)
}
}
// ******************************* MARK: - Trimming
public extension StringProtocol {
/// Strips whitespace and new line characters
var trimmed: String {
let trimmedString = trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
return trimmedString
}
}
// ******************************* MARK: - Splitting
public extension StringProtocol {
/// Splits string by capital letters without stripping them
var splittedByCapitals: [String] {
return splitBefore(separator: { $0.isUppercase }).map({ String($0) })
}
/// Split string into slices of specified length
func splitByLength(_ length: Int) -> [String] {
var result = [String]()
var collectedCharacters = [Character]()
collectedCharacters.reserveCapacity(length)
var count = 0
for character in self {
collectedCharacters.append(character)
count += 1
if (count == length) {
// Reached the desired length
count = 0
result.append(String(collectedCharacters))
collectedCharacters.removeAll(keepingCapacity: true)
}
}
// Append the remainder
if !collectedCharacters.isEmpty {
result.append(String(collectedCharacters))
}
return result
}
}
// ******************************* MARK: - Bounding Rect
public extension StringProtocol {
/// Width of a string written in one line.
func oneLineWidth(font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
let boundingBox = asString.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil)
return boundingBox.width
}
/// Height of a string for specified font and width.
func height(font: UIFont, width: CGFloat) -> CGFloat {
return height(attributes: [.font: font], width: width)
}
/// Height of a string for specified attributes and width.
func height(attributes: [NSAttributedString.Key: Any], width: CGFloat) -> CGFloat {
let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let height = asString.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil).height + c.pixelSize
return height
}
}
// ******************************* MARK: - Capitalization
public extension StringProtocol {
func capitalizingFirstLetter() -> String {
return prefix(1).capitalized + dropFirst()
}
}
// ******************************* MARK: - Subscript
public extension StringProtocol {
subscript(value: Int) -> Character {
self[index(at: value)]
}
}
public extension StringProtocol {
subscript(value: NSRange) -> SubSequence {
self[value.lowerBound..<value.upperBound]
}
}
public extension StringProtocol {
subscript(value: CountableClosedRange<Int>) -> SubSequence {
self[index(at: value.lowerBound)...index(at: value.upperBound)]
}
subscript(value: CountableRange<Int>) -> SubSequence {
self[index(at: value.lowerBound)..<index(at: value.upperBound)]
}
subscript(value: PartialRangeUpTo<Int>) -> SubSequence {
self[..<index(at: value.upperBound)]
}
subscript(value: PartialRangeThrough<Int>) -> SubSequence {
self[...index(at: value.upperBound)]
}
subscript(value: PartialRangeFrom<Int>) -> SubSequence {
self[index(at: value.lowerBound)...]
}
}
private extension StringProtocol {
func index(at offset: Int) -> String.Index {
index(startIndex, offsetBy: offset)
}
}
// ******************************* MARK: - Appending
public extension StringProtocol {
func appending<T: StringProtocol, U: StringProtocol>(_ string: T?, separator: U) -> String {
guard let string = string, !string.isEmpty else { return asString }
if isEmpty {
return appending(string)
} else {
return appending("\(separator)\(string)")
}
}
}
// ******************************* MARK: - Range
public extension StringProtocol {
/// Range from the start to the end.
var fullRange: Range<String.Index> {
Range<String.Index>(uncheckedBounds: (startIndex, endIndex))
}
}
|
mit
|
9380f9f031fdd0f77402b80f99a6164e
| 31.270186 | 148 | 0.596574 | 5.012542 | false | false | false | false |
53ningen/todo
|
TODO/DB/Realm/Repository/IssueRepositoryOnRealm.swift
|
1
|
3765
|
import Foundation
import RealmSwift
/// IssueRepositoryのRealm実装
class IssueRepositoryOnRealm: IssueRepository {
private let realm: Realm = try! Realm()
private var nextId: String {
if let id = (realm.objects(IssueObject.self).last.flatMap { Int($0.id) }) {
return String(id + 1)
} else {
return "1"
}
}
func findById(_ id: Id<Issue>) -> Issue? {
return realm.object(ofType: IssueObject.self, forPrimaryKey: id.value as AnyObject)?.toIssue
}
func findAll() -> [Issue] {
return realm.objects(IssueObject.self).flatMap { $0.toIssue }
}
func findAll(_ state: IssueState) -> [Issue] {
let pred = NSPredicate(format: "state == %@", state.rawValue)
return realm.objects(IssueObject.self).filter(pred).flatMap { $0.toIssue }
}
func findByKeyword(_ keyword: String) -> [Issue] {
let pred = NSPredicate(format: "title CONTAINS '%@' OR desc CONTAINS '%@'", keyword, keyword)
return realm.objects(IssueObject.self).filter(pred).flatMap { $0.toIssue }
}
func findByLabel(_ label: Label, state: IssueState) -> [Issue] {
let pred = NSPredicate(format: "id == %@", label.id.value)
return realm.objects(LabelObject.self)
.filter(pred)
.flatMap { $0.issues }
.flatMap { $0.toIssue }
.filter {
switch ($0.info.state, state) {
case (.open, .open): return true
case (.closed(_), .closed(_)): return true
default: return false
}
}
}
func findByMilestone(_ milestone: Milestone, state: IssueState) -> [Issue] {
let pred = NSPredicate(format: "id == %@", milestone.id.value)
return realm.objects(MilestoneObject.self)
.filter(pred)
.flatMap { $0.issues }
.flatMap { $0.toIssue }
.filter {
switch ($0.info.state, state) {
case (.open, .open): return true
case (.closed(_), .closed(_)): return true
default: return false
}
}
}
func add(_ info: IssueInfo) {
try! realm.write {
realm.add(IssueObject.of(nextId, info: info))
}
}
func update(_ issue: Issue) {
try! realm.write {
if let obj = realm.object(ofType: IssueObject.self, forPrimaryKey: issue.id.value as AnyObject) {
obj.update(issue.info)
}
}
}
func open(_ id: Id<Issue>) {
try! realm.write {
if let obj = realm.object(ofType: IssueObject.self, forPrimaryKey: id.value as AnyObject) , obj.state == IssueState.closed(closedAt: 0).rawValue {
obj.open()
}
}
}
func close(_ id: Id<Issue>) {
try! realm.write {
if let obj = realm.object(ofType: IssueObject.self, forPrimaryKey: id.value as AnyObject) , obj.state == IssueState.open.rawValue {
obj.close(Int64(NSDate().timeIntervalSince1970))
}
}
}
internal func deleteAll() {
try! realm.write {
realm.delete(realm.objects(IssueObject.self))
}
}
}
extension IssueObject {
var toIssue: Issue? {
guard let state = IssueState.of(state, closedAt: closedAt.value) else { return nil }
let info = IssueInfo(title: title, desc: desc ,state: state, labels: labels.flatMap { $0.toLabel }, milestone: milestone.flatMap { $0.toMilestone }, locked: locked, createdAt: createdAt, updatedAt: updatedAt)
return Issue(id: Id<Issue>(value: id), info: info)
}
}
|
mit
|
d1c77da6e5979b3ea351d29711cdb28f
| 32.864865 | 216 | 0.551476 | 4.162791 | false | false | false | false |
cdmx/MiniMancera
|
miniMancera/View/Home/VHome.swift
|
1
|
2526
|
import UIKit
class VHome:View
{
private(set) weak var viewOptions:VHomeOptions!
private weak var viewHeader:VHomeHeader!
private weak var viewFooter:VHomeFooter!
private weak var spinner:VSpinner?
private let kHeaderHeight:CGFloat = 170
private let kFooterHeight:CGFloat = 140
required init(controller:UIViewController)
{
super.init(controller:controller)
guard
let controller:CHome = self.controller as? CHome
else
{
return
}
let viewHeader:VHomeHeader = VHomeHeader(controller:controller)
self.viewHeader = viewHeader
let viewOptions:VHomeOptions = VHomeOptions(controller:controller)
self.viewOptions = viewOptions
let viewFooter:VHomeFooter = VHomeFooter(controller:controller)
self.viewFooter = viewFooter
let spinner:VSpinner = VSpinner()
self.spinner = spinner
addSubview(spinner)
addSubview(viewHeader)
addSubview(viewOptions)
addSubview(viewFooter)
NSLayoutConstraint.equals(
view:spinner,
toView:self)
NSLayoutConstraint.topToTop(
view:viewHeader,
toView:self)
NSLayoutConstraint.height(
view:viewHeader,
constant:kHeaderHeight)
NSLayoutConstraint.equalsHorizontal(
view:viewHeader,
toView:self)
NSLayoutConstraint.topToBottom(
view:viewOptions,
toView:viewHeader)
NSLayoutConstraint.bottomToTop(
view:viewOptions,
toView:viewFooter)
NSLayoutConstraint.equalsHorizontal(
view:viewOptions,
toView:self)
NSLayoutConstraint.bottomToBottom(
view:viewFooter,
toView:self)
NSLayoutConstraint.height(
view:viewFooter,
constant:kFooterHeight)
NSLayoutConstraint.equalsHorizontal(
view:viewFooter,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
deinit
{
spinner?.stopAnimating()
}
//MARK: public
func sessionLoaded()
{
spinner?.stopAnimating()
spinner?.removeFromSuperview()
viewOptions.refresh()
viewHeader.isHidden = false
viewFooter.isHidden = false
}
}
|
mit
|
bc5642d2710196ea05e394ca924e2e5e
| 24.77551 | 74 | 0.583927 | 5.563877 | false | false | false | false |
fernandomarins/food-drivr-pt
|
hackathon-for-hunger/Donation.swift
|
1
|
1679
|
//
// Donation.swift
// hackathon-for-hunger
//
// Created by Ian Gristock on 3/30/16.
// Copyright © 2016 Hacksmiths. All rights reserved.
//
import Foundation
import RealmSwift
import ObjectMapper
enum DonationStatus: Int {
case Pending = 0
case Accepted
case Suspended
case Cancelled
case PickedUp
case DroppedOff
case Any
}
class Donation: Object, Mappable {
typealias JsonDict = [String: AnyObject]
dynamic var id: Int = 0
dynamic var donor: Participant?
dynamic var driver: Participant?
dynamic var recipient: Recipient?
dynamic var pickup: Location?
dynamic var dropoff: Location?
dynamic var meta: MetaData?
var donationItems = List<DonationType>()
private dynamic var rawStatus = 0
var status: DonationStatus {
get{
if let status = DonationStatus(rawValue: rawStatus) {
return status
}
return .Pending
}
set{
rawStatus = newValue.rawValue
}
}
override static func primaryKey() -> String? {
return "id"
}
required convenience init?(_ map: Map) {
self.init()
}
func mapping(map: Map) {
id <- map["id"]
rawStatus <- map["status_id"]
donor <- map["participants.donor"]
driver <- map["participants.driver"]
donationItems <- (map["items"], ListTransform<DonationType>())
pickup <- map["pickup"]
dropoff <- map["dropoff"]
recipient <- map["recipient"]
meta <- map["meta"]
}
}
|
mit
|
0ada674c50d4c6c09c96e5682ce2cf66
| 23.333333 | 72 | 0.562574 | 4.547425 | false | false | false | false |
ianyh/Amethyst
|
Amethyst/Layout/Layouts/TallRightLayout.swift
|
1
|
4045
|
//
// TallRightLayout.swift
// Amethyst
//
// Created by Ian Ynda-Hummel on 12/14/15.
// Copyright © 2015 Ian Ynda-Hummel. All rights reserved.
//
import Silica
class TallRightLayout<Window: WindowType>: Layout<Window>, PanedLayout {
override static var layoutName: String { return "Tall Right" }
override static var layoutKey: String { return "tall-right" }
enum CodingKeys: String, CodingKey {
case mainPaneCount
case mainPaneRatio
}
private(set) var mainPaneCount: Int = 1
private(set) var mainPaneRatio: CGFloat = 0.5
required init() {
super.init()
}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.mainPaneCount = try values.decode(Int.self, forKey: .mainPaneCount)
self.mainPaneRatio = try values.decode(CGFloat.self, forKey: .mainPaneRatio)
super.init()
}
override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(mainPaneCount, forKey: .mainPaneCount)
try container.encode(mainPaneRatio, forKey: .mainPaneRatio)
}
func recommendMainPaneRawRatio(rawRatio: CGFloat) {
mainPaneRatio = rawRatio
}
func increaseMainPaneCount() {
mainPaneCount += 1
}
func decreaseMainPaneCount() {
mainPaneCount = max(1, mainPaneCount - 1)
}
override func frameAssignments(_ windowSet: WindowSet<Window>, on screen: Screen) -> [FrameAssignmentOperation<Window>]? {
let windows = windowSet.windows
guard !windows.isEmpty else {
return []
}
let mainPaneCount = min(windows.count, self.mainPaneCount)
let secondaryPaneCount = windows.count - mainPaneCount
let hasSecondaryPane = secondaryPaneCount > 0
let screenFrame = screen.adjustedFrame()
let mainPaneWindowHeight = round(screenFrame.size.height / CGFloat(mainPaneCount))
let secondaryPaneWindowHeight = hasSecondaryPane ? round(screenFrame.size.height / CGFloat(secondaryPaneCount)) : 0.0
let secondaryPaneWindowWidth = round(screenFrame.size.width * (hasSecondaryPane ? CGFloat(1.0 - mainPaneRatio) : 0))
let mainPaneWindowWidth = screenFrame.size.width - secondaryPaneWindowWidth
return windows.reduce([]) { frameAssignments, window -> [FrameAssignmentOperation<Window>] in
var assignments = frameAssignments
var windowFrame = CGRect.zero
let isMain = frameAssignments.count < mainPaneCount
var scaleFactor: CGFloat
if isMain {
scaleFactor = screenFrame.size.width / mainPaneWindowWidth
windowFrame.origin.x = screenFrame.origin.x + secondaryPaneWindowWidth
windowFrame.origin.y = screenFrame.origin.y + (mainPaneWindowHeight * CGFloat(frameAssignments.count))
windowFrame.size.width = mainPaneWindowWidth
windowFrame.size.height = mainPaneWindowHeight
} else {
scaleFactor = screenFrame.size.width / secondaryPaneWindowWidth
windowFrame.origin.x = screenFrame.origin.x
windowFrame.origin.y = screenFrame.origin.y + secondaryPaneWindowHeight * CGFloat(windows.count - (frameAssignments.count + 1))
windowFrame.size.width = secondaryPaneWindowWidth
windowFrame.size.height = secondaryPaneWindowHeight
}
let resizeRules = ResizeRules(isMain: isMain, unconstrainedDimension: .horizontal, scaleFactor: scaleFactor)
let frameAssignment = FrameAssignment<Window>(
frame: windowFrame,
window: window,
screenFrame: screenFrame,
resizeRules: resizeRules
)
assignments.append(FrameAssignmentOperation(frameAssignment: frameAssignment, windowSet: windowSet))
return assignments
}
}
}
|
mit
|
a36def3c325080d7ebd6cff9a2509e42
| 37.884615 | 143 | 0.664194 | 4.627002 | false | false | false | false |
finder39/Swimgur
|
SWNetworking/Forms/RefreshTokenForm.swift
|
1
|
1194
|
//
// RefreshTokenForm.swift
// Swimgur
//
// Created by Joseph Neuman on 8/9/14.
// Copyright (c) 2014 Joseph Neuman. All rights reserved.
//
import Foundation
private let refreshTokenFornRefreshTokenKey = "refresh_token"
private let refreshTokenFornClientIDKey = "client_id"
private let refreshTokenFornClientSecretKey = "client_secret"
private let refreshTokenFornGrantTypeKey = "grant_type"
public class RefreshTokenForm {
public var refreshToken: String?
public var clientID: String?
public var clientSecret: String?
public var grantType: String?
public init() {
}
public func httpParametersDictionary() -> Dictionary<String, String> {
var dictionary:Dictionary<String, String> = Dictionary()
if let refreshToken = refreshToken { dictionary[refreshTokenFornRefreshTokenKey] = refreshToken }
if let clientID = clientID { dictionary[refreshTokenFornClientIDKey] = clientID }
if let clientSecret = clientSecret { dictionary[refreshTokenFornClientSecretKey] = clientSecret }
if let grantType = grantType { dictionary[refreshTokenFornGrantTypeKey] = grantType }
return dictionary
}
func JSONString() -> String {
return ""
}
}
|
mit
|
e61e41eefa269ab9442bf0858cf96834
| 30.447368 | 101 | 0.747906 | 4.455224 | false | false | false | false |
kumabook/MusicFav
|
MusicFav/CloudAPIClientExtension.swift
|
1
|
7230
|
//
// FeedlyAPI.swift
// MusicFav
//
// Created by Hiroki Kumamoto on 8/2/15.
// Copyright (c) 2015 Hiroki Kumamoto. All rights reserved.
//
import Foundation
import SwiftyJSON
import FeedlyKit
import OAuthSwift
import Prephirences
open class FeedlyOAuthRequestRetrier: OAuthRequestRetrier {
public override func refreshed(_ succeeded: Bool) {
if succeeded {
CloudAPIClient.credential = oauth.client.credential
CloudAPIClient.shared.updateAccessToken(oauth.client.credential.oauthToken)
} else {
CloudAPIClient.credential = nil
CloudAPIClient.logout()
}
}
}
public extension CloudAPIClient {
fileprivate static let userDefaults = UserDefaults.standard
fileprivate static var _profile: Profile?
fileprivate static var _notificationDateComponents: DateComponents?
fileprivate static var _lastChecked: Date?
public static var profile: Profile? {
get {
if let p = _profile {
return p
}
if let data: NSData = userDefaults.object(forKey: "profile") as? NSData {
_profile = NSKeyedUnarchiver.unarchiveObject(with: data as Data) as? Profile
return _profile
}
return nil
}
set(profile) {
if let p = profile {
userDefaults.set(NSKeyedArchiver.archivedData(withRootObject: p), forKey: "profile")
} else {
userDefaults.removeObject(forKey: "profile")
}
_profile = profile
}
}
static var oauth: OAuth2Swift!
static var credential: OAuthSwiftCredential? {
get {
return KeychainPreferences.sharedInstance[CloudAPIClient.keyChainGroup] as? OAuthSwiftCredential
}
set {
KeychainPreferences.sharedInstance[CloudAPIClient.keyChainGroup] = newValue
}
}
public static var isExpired: Bool {
return credential?.isTokenExpired() ?? true
}
static func authorize(callback: (() -> ())? = nil) {
let vc = OAuthViewController(oauth: oauth)
oauth.authorizeURLHandler = vc
let _ = oauth.authorize(
withCallbackURL: URL(string: CloudAPIClient.redirectUrl)!,
scope: CloudAPIClient.scope.joined(separator: ","),
state: "Feedly",
success: { credential, response, parameters in
CloudAPIClient.credential = credential
CloudAPIClient.shared.updateAccessToken(credential.oauthToken)
let _ = CloudAPIClient.shared.fetchProfile().on(
failed: { error in
callback?()
}, value: { profile in
CloudAPIClient.login(profile: profile, token: credential.oauthToken)
AppDelegate.shared.reload()
callback?()
}).start()
},
failure: { error in
callback?()
})
}
public static var notificationDateComponents: DateComponents? {
get {
if let components = _notificationDateComponents {
return components
}
if let data: Data = userDefaults.object(forKey: "notification_date_components") as? Data {
return NSKeyedUnarchiver.unarchiveObject(with: data as Data) as? DateComponents
}
return nil
}
set(notificationDateComponents) {
if let components = notificationDateComponents {
userDefaults.set(NSKeyedArchiver.archivedData(withRootObject: components), forKey: "notification_date_components")
} else {
userDefaults.removeObject(forKey: "notification_date_components")
}
_notificationDateComponents = notificationDateComponents
}
}
public static var lastChecked: Date? {
get {
if let time = _lastChecked {
return time as Date
}
if let data: Data = userDefaults.object(forKey: "last_checked") as? Data {
return NSKeyedUnarchiver.unarchiveObject(with: data) as? Date
}
return nil
}
set(lastChecked) {
if let date = lastChecked {
userDefaults.set(NSKeyedArchiver.archivedData(withRootObject: date), forKey: "last_checked")
} else {
userDefaults.removeObject(forKey: "last_checked")
}
_lastChecked = lastChecked
}
}
fileprivate static func clearAllAccount() {
credential = nil
oauth.client.credential.oauthToken = ""
oauth.client.credential.oauthTokenSecret = ""
oauth.client.credential.oauthTokenExpiresAt = nil
oauth.client.credential.oauthRefreshToken = ""
logout()
}
fileprivate static func loadConfig() {
let bundle = Bundle.main
if let path = bundle.path(forResource: "feedly", ofType: "json") {
let data = NSData(contentsOfFile: path)
let jsonObject: AnyObject? = try! JSONSerialization.jsonObject(with: data! as Data,
options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject?
if let obj: AnyObject = jsonObject {
let json = JSON(obj)
if json["target"].stringValue == "production" {
CloudAPIClient.shared = CloudAPIClient(target: .production)
} else {
CloudAPIClient.shared = CloudAPIClient(target: .sandbox)
}
if let clientId = json["client_id"].string {
CloudAPIClient.clientId = clientId
}
if let clientSecret = json["client_secret"].string {
CloudAPIClient.clientSecret = clientSecret
}
}
}
}
public static func setup() {
loadConfig()
oauth = OAuth2Swift(
consumerKey: clientId,
consumerSecret: clientSecret,
authorizeUrl: shared.authUrl,
accessTokenUrl: shared.tokenUrl,
responseType: "code"
)
if let c = credential {
oauth.client.credential.oauthToken = c.oauthToken
oauth.client.credential.oauthTokenSecret = c.oauthTokenSecret
oauth.client.credential.oauthTokenExpiresAt = c.oauthTokenExpiresAt
oauth.client.credential.oauthRefreshToken = c.oauthRefreshToken
}
if let p = profile, let c = credential {
CloudAPIClient.login(profile: p, token: c.oauthToken)
}
shared.manager.retrier = FeedlyOAuthRequestRetrier(oauth)
CloudAPIClient.sharedPipe.0.observeResult({ result in
guard let event = result.value else { return }
switch event {
case .Login(let profile):
self.profile = profile
case .Logout:
self.profile = nil
self.credential = nil
}
})
}
}
|
mit
|
d19b8669d2edba4e09e69b0c74302ab0
| 35.700508 | 130 | 0.57538 | 5.440181 | false | false | false | false |
mennovf/Swift-MathEagle
|
MathEagle/Source/Linear Algebra/Dimensions.swift
|
1
|
3715
|
//
// Dimensions.swift
// MathEagle
//
// Created by Rugen Heidbuchel on 26/05/15.
// Copyright (c) 2015 Jorestha Solutions. All rights reserved.
//
/**
A struct representing the dimensions of a 2-dimensional matrix.
*/
public struct Dimensions: Equatable, Addable {
/**
The number of rows in the dimensions.
*/
public let rows: Int
/**
The number of columns in the dimensions.
*/
public let columns: Int
// MARK: Initialisers
/**
Creates a new dimensions object with the given number of rows and columns.
- parameter rows: The number of rows in the dimensions.
- parameter columns: The number of columns in the dimensions.
*/
public init(_ rows: Int = 0, _ columns: Int = 0) {
self.rows = rows
self.columns = columns
}
/**
Creates a new dimensions object where the number of rows and columns are equal.
- parameter size: The size of the dimensions. This value will be used for both the
number of rows and columns.
*/
public init(size: Int) {
self.init(size, size)
}
// MARK: Properties
/**
Returns the minimal value of both dimension values (rows, columns).
*/
public var minimum: Int {
return self.rows < self.columns ? self.rows : self.columns
}
/**
Returns the size of these dimensions. Returns nil if the rows and columns
dimensions values are not equal.
*/
public var size: Int? {
return self.rows == self.columns ? self.rows : nil
}
/**
Returns the product of the two dimension values: rows * columns.
*/
public var product: Int {
return self.rows * self.columns
}
/**
Returns a new Dimensions object with the two dimensions swapped.
*/
public var transpose: Dimensions {
return Dimensions(self.columns, self.rows)
}
/**
Returns whether the dimensions are sqaure or not. Dimensions are sqaure when the number of
rows equals the number of columns.
- returns: true if the dimensions are square.
*/
public var isSquare: Bool {
return self.rows == self.columns
}
/**
Returns the rows dimension value when index == 0, otherwise the columns dimension
value is returned.
*/
public subscript(index: Int) -> Int {
return index == 0 ? self.rows : self.columns
}
/**
Returns whether the dimensions are empty or not.
- returns: true if the dimensions are empty.
*/
public var isEmpty: Bool {
return self.rows == 0 && self.columns == 0
}
}
// MARK: Dimensions Equality
public func == (left: Dimensions, right: Dimensions) -> Bool {
return left[0] == right[0] && left[1] == right[1]
}
// MARK: Dimensions Tuple Equality
public func == (left: Dimensions, right: (Int, Int)) -> Bool {
let (n, m) = right
return left[0] == n && left[1] == m
}
public func == (left: (Int, Int), right: Dimensions) -> Bool {
return right == left
}
// MARK: Dimensions Summation
public func + (left: Dimensions, right: Dimensions) -> Dimensions {
return Dimensions(left[0] + right[0], left[1] + right[1])
}
// MARK: Dimensions Negation
public prefix func - (dimensions: Dimensions) -> Dimensions {
return Dimensions(-dimensions[0], -dimensions[1])
}
// MARK: Dimensions Subtraction
public func - (left: Dimensions, right: Dimensions) -> Dimensions {
return left + -right
}
|
mit
|
921609e8d1f2e940ba4b23874179700e
| 23.287582 | 98 | 0.585734 | 4.42789 | false | false | false | false |
xiaohaieryi/DYZB-YW
|
DYZB-YW/DYZB-YW/Classes/DYYTools/Extenstion/UIBarButtonItem-Extension.swift
|
1
|
1295
|
//
// UIBarButtonItem-Extension.swift
// DYZB-YW
//
// Created by 于武 on 2017/7/28.
// Copyright © 2017年 于武. All rights reserved.
//
import UIKit
extension UIBarButtonItem{
//方法一:扩展一种类方法
// class func creatItem(imageName :String,highImageName:String,size : CGSize) -> UIBarButtonItem{
//
// let btn = UIButton()
//
// btn.setImage(UIImage(named :imageName), for: .normal)
// btn.setImage(UIImage(named :highImageName), for: .highlighted)
// btn.frame = CGRect(origin:CGPoint.zero, size: size)
//
// return UIBarButtonItem(customView: btn)
//
//
// }
//方法二:1)利用便利构造函数。推荐使用 2)默认参数
convenience init (imageName : String,highImageName : String = "", size : CGSize = CGSize.zero){
let btn = UIButton()
btn.setImage(UIImage(named :imageName), for: .normal)
if highImageName != "" {
btn.setImage(UIImage(named :highImageName), for: .highlighted)
}
if size == CGSize.zero {
btn.sizeToFit()
}else{
btn.frame = CGRect(origin:CGPoint.zero, size: size)
}
self.init(customView :btn)
}
}
|
mit
|
4a091240bd904a8a759d1c2b53848d7a
| 23.816327 | 100 | 0.567434 | 3.848101 | false | false | false | false |
caicai0/ios_demo
|
sameHeader/sameHeader/contentController.swift
|
1
|
2055
|
//
// contentController.swift
// sameHeader
//
// Created by 李玉峰 on 2017/5/3.
// Copyright © 2017年 李玉峰. All rights reserved.
//
import UIKit
class contentController: UIViewController {
@IBOutlet open weak var tableView: UITableView!
var localSize:CGSize = CGSize.zero
weak var localHeader:UIView? = nil
open var header:UIView?{
set{
localHeader = header
//初始化操作
}
get{
return localHeader
}
}
open var headerSize:CGSize {
set{
localSize = newValue
tableView.contentInset = UIEdgeInsetsMake(localSize.height+64, 0, 0, 0)
}
get{
return localSize
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension contentController : UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
cell.textLabel?.text = "slldk\(indexPath.row)";
return cell
}
//UIScrollViewDelegate
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
print("\(#function) in \(#file)\n")
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
print("\(#function) in \(#file)\n")
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
print("\(#function) in \(#file)\n")
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
print("\(#function) in \(#file)\n")
}
}
|
mit
|
5b12b9bf707f384a253cdac54f913400
| 25.363636 | 100 | 0.62069 | 5.139241 | false | false | false | false |
akkakks/firefox-ios
|
Utils/ExtensionUtils.swift
|
2
|
3777
|
/* 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 UIKit
import MobileCoreServices
import Storage
struct ExtensionUtils {
/// Small structure to encapsulate all the possible data that we can get from an application sharing a web page or a url.
/// Look through the extensionContext for a url and title. Walks over all inputItems and then over all the attachments.
/// Has a completionHandler because ultimately an XPC call to the sharing application is done.
/// We can always extract a URL and sometimes a title. The favicon is currently just a placeholder, but future code can possibly interact with a web page to find a proper icon.
static func extractSharedItemFromExtensionContext(extensionContext: NSExtensionContext?, completionHandler: (ShareItem?, NSError!) -> Void) {
if extensionContext != nil {
if let inputItems : [NSExtensionItem] = extensionContext!.inputItems as? [NSExtensionItem] {
for inputItem in inputItems {
if let attachments = inputItem.attachments as? [NSItemProvider] {
for attachment in attachments {
if attachment.hasItemConformingToTypeIdentifier(kUTTypeURL as String) {
attachment.loadItemForTypeIdentifier(kUTTypeURL as String, options: nil, completionHandler: { (obj, err) -> Void in
if err != nil {
completionHandler(nil, err)
} else {
let title = inputItem.attributedContentText?.string as String?
if let url = obj as? NSURL {
completionHandler(ShareItem(url: url.absoluteString!, title: title), nil)
} else {
completionHandler(nil, NSError(domain: "org.mozilla.fennec", code: 999, userInfo: ["Problem": "Non-URL result."]))
}
}
})
return
}
}
}
}
}
}
completionHandler(nil, nil)
}
/// Return the shared container identifier (also known as the app group) to be used with for example background http requests.
///
/// This function is smart enough to find out if it is being called from an extension or the main application. In case of the
/// former, it will chop off the extension identifier from the bundle since that is a suffix not used in the app group.
///
/// :returns: the shared container identifier (app group) or the string "group.unknown" if it cannot find the group
static func sharedContainerIdentifier() -> String {
let bundle = NSBundle.mainBundle()
if let packageType = bundle.objectForInfoDictionaryKey("CFBundlePackageType") as? NSString {
switch packageType {
case "XPC!":
let identifier = bundle.bundleIdentifier!
let components = identifier.componentsSeparatedByString(".")
let baseIdentifier = ".".join(components[0..<components.count-1])
return "group.\(baseIdentifier)"
case "APPL":
return "group.\(bundle.bundleIdentifier!)"
default:
return "group.unknown"
}
}
return "group.unknown"
}
}
|
mpl-2.0
|
018e05c3055415de307df33b49b37ac0
| 54.544118 | 180 | 0.570294 | 5.864907 | false | false | false | false |
starrpatty28/MJMusicApp
|
MJMusicApp/MJMusicApp/ThrillerAlbumVC.swift
|
1
|
1302
|
//
// ThrillerAlbumVC.swift
// MJMusicApp
//
// Created by Noi-Ariella Baht Israel on 3/22/17.
// Copyright © 2017 Plant A Seed of Code. All rights reserved.
//
import UIKit
import AVFoundation
class ThrillerAlbumVC: UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "40 Thriller", ofType: "mp3")!))
audioPlayer.prepareToPlay()
}
catch{
print(error)
}
}
@IBAction func youtubeClkd(_ sender: Any) {
openURL(url: "https://www.youtube.com/watch?v=CZqM_PgQ7BM&list=PLDs_1K5H3Lco3c8l0IMj0ZpOARsaDuwj1")
}
func openURL(url:String!) {
if let url = NSURL(string:url) {
UIApplication.shared.openURL(url as URL)
}
}
@IBAction func backBtnPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func playMusic(_ sender: Any) {
audioPlayer.play()
}
}
|
mit
|
a944e3bcfe9a193396cd90f2bfd818e1
| 23.54717 | 144 | 0.607225 | 3.966463 | false | false | false | false |
ahoppen/swift
|
test/Constraints/metatypes.swift
|
17
|
1406
|
// RUN: %target-typecheck-verify-swift
class A {}
class B : A {}
let test0 : A.Type = A.self
let test1 : A.Type = B.self
let test2 : B.Type = A.self // expected-error {{cannot convert value of type 'A.Type' to specified type 'B.Type'}}
let test3 : AnyClass = A.self
let test4 : AnyClass = B.self
struct S {}
let test5 : S.Type = S.self
let test6 : AnyClass = S.self // expected-error {{cannot convert value of type 'S.Type' to specified type 'AnyClass' (aka 'AnyObject.Type')}}
func acceptMeta<T>(_ meta: T.Type) { }
acceptMeta(A) // expected-error {{expected member name or constructor call after type name}}
// expected-note@-1 {{add arguments after the type to construct a value of the type}}
// expected-note@-2 {{use '.self' to reference the type object}}
acceptMeta((A) -> Void) // expected-error {{expected member name or constructor call after type name}}
// expected-note@-1 {{use '.self' to reference the type object}}
func id<T>(_ x: T.Type) -> T.Type { x }
// rdar://62890683: Don't allow arbitrary subtyping for a metatype's instance type.
let _: A?.Type = B.self // expected-error {{cannot convert value of type 'B.Type' to specified type 'A?.Type'}}
let _: A?.Type = id(B.self) // expected-error {{cannot convert value of type 'B.Type' to specified type 'A?.Type'}}
let _: S?.Type = id(S.self) // expected-error {{cannot convert value of type 'S.Type' to specified type 'S?.Type'}}
|
apache-2.0
|
582a6909a8248e05f98b64d751e87bb9
| 44.354839 | 141 | 0.684211 | 3.300469 | false | true | false | false |
dev-aleksey/ScaleTransition
|
scaletransitiondemo/UI/LoginAppearance.swift
|
1
|
2252
|
//
//
// LoginAppearance.swift
//
// Copyright (c) 21/02/16. Alex K ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
// MARK: textField
protocol PlaceholderColor {
func placeholderColor(color: UIColor)
}
extension PlaceholderColor where Self: UITextField {
func placeholderColor(color: UIColor) {
if let placeholder = placeholder {
attributedPlaceholder = NSAttributedString(string: placeholder,
attributes:[NSForegroundColorAttributeName : UIColor.white])
}
}
}
class WhiteTextField: UITextField, PlaceholderColor {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
placeholderColor(color: .white)
}
}
protocol Bordered {
func borderWidth(width: Float, color: UIColor)
}
extension Bordered where Self: UIView {
func borderWidth(width: Float, color: UIColor) {
layer.borderColor = color.cgColor
layer.borderWidth = CGFloat(width)
}
}
class CountinueButton: UIButton, Bordered {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
borderWidth(width: 2, color: UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 0.3))
backgroundColor = .clear
}
}
|
mit
|
ce2e4869cbb561b42b41f30edb9fcf4d
| 31.171429 | 92 | 0.741563 | 4.339114 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.